text
stringlengths
478
483k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ppp_unregister_channel(struct ppp_channel *chan) { struct channel *pch = chan->ppp; struct ppp_net *pn; if (!pch) return; /* should never happen */ chan->ppp = NULL; /* * This ensures that we have returned from any calls into the * the channel's start_xmit or ioctl routine before we proceed. */ down_write(&pch->chan_sem); spin_lock_bh(&pch->downl); pch->chan = NULL; spin_unlock_bh(&pch->downl); up_write(&pch->chan_sem); ppp_disconnect_channel(pch); pn = ppp_pernet(pch->chan_net); spin_lock_bh(&pn->all_channels_lock); list_del(&pch->list); spin_unlock_bh(&pn->all_channels_lock); pch->file.dead = 1; wake_up_interruptible(&pch->file.rwait); if (atomic_dec_and_test(&pch->file.refcnt)) ppp_destroy_channel(pch); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'ppp: take reference on channels netns Let channels hold a reference on their network namespace. Some channel types, like ppp_async and ppp_synctty, can have their userspace controller running in a different namespace. Therefore they can't rely on them to preclude their netns from being removed from under them. ================================================================== BUG: KASAN: use-after-free in ppp_unregister_channel+0x372/0x3a0 at addr ffff880064e217e0 Read of size 8 by task syz-executor/11581 ============================================================================= BUG net_namespace (Not tainted): kasan: bad access detected ----------------------------------------------------------------------------- Disabling lock debugging due to kernel taint INFO: Allocated in copy_net_ns+0x6b/0x1a0 age=92569 cpu=3 pid=6906 [< none >] ___slab_alloc+0x4c7/0x500 kernel/mm/slub.c:2440 [< none >] __slab_alloc+0x4c/0x90 kernel/mm/slub.c:2469 [< inline >] slab_alloc_node kernel/mm/slub.c:2532 [< inline >] slab_alloc kernel/mm/slub.c:2574 [< none >] kmem_cache_alloc+0x23a/0x2b0 kernel/mm/slub.c:2579 [< inline >] kmem_cache_zalloc kernel/include/linux/slab.h:597 [< inline >] net_alloc kernel/net/core/net_namespace.c:325 [< none >] copy_net_ns+0x6b/0x1a0 kernel/net/core/net_namespace.c:360 [< none >] create_new_namespaces+0x2f6/0x610 kernel/kernel/nsproxy.c:95 [< none >] copy_namespaces+0x297/0x320 kernel/kernel/nsproxy.c:150 [< none >] copy_process.part.35+0x1bf4/0x5760 kernel/kernel/fork.c:1451 [< inline >] copy_process kernel/kernel/fork.c:1274 [< none >] _do_fork+0x1bc/0xcb0 kernel/kernel/fork.c:1723 [< inline >] SYSC_clone kernel/kernel/fork.c:1832 [< none >] SyS_clone+0x37/0x50 kernel/kernel/fork.c:1826 [< none >] entry_SYSCALL_64_fastpath+0x16/0x7a kernel/arch/x86/entry/entry_64.S:185 INFO: Freed in net_drop_ns+0x67/0x80 age=575 cpu=2 pid=2631 [< none >] __slab_free+0x1fc/0x320 kernel/mm/slub.c:2650 [< inline >] slab_free kernel/mm/slub.c:2805 [< none >] kmem_cache_free+0x2a0/0x330 kernel/mm/slub.c:2814 [< inline >] net_free kernel/net/core/net_namespace.c:341 [< none >] net_drop_ns+0x67/0x80 kernel/net/core/net_namespace.c:348 [< none >] cleanup_net+0x4e5/0x600 kernel/net/core/net_namespace.c:448 [< none >] process_one_work+0x794/0x1440 kernel/kernel/workqueue.c:2036 [< none >] worker_thread+0xdb/0xfc0 kernel/kernel/workqueue.c:2170 [< none >] kthread+0x23f/0x2d0 kernel/drivers/block/aoe/aoecmd.c:1303 [< none >] ret_from_fork+0x3f/0x70 kernel/arch/x86/entry/entry_64.S:468 INFO: Slab 0xffffea0001938800 objects=3 used=0 fp=0xffff880064e20000 flags=0x5fffc0000004080 INFO: Object 0xffff880064e20000 @offset=0 fp=0xffff880064e24200 CPU: 1 PID: 11581 Comm: syz-executor Tainted: G B 4.4.0+ Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.8.2-0-g33fbe13 by qemu-project.org 04/01/2014 00000000ffffffff ffff8800662c7790 ffffffff8292049d ffff88003e36a300 ffff880064e20000 ffff880064e20000 ffff8800662c77c0 ffffffff816f2054 ffff88003e36a300 ffffea0001938800 ffff880064e20000 0000000000000000 Call Trace: [< inline >] __dump_stack kernel/lib/dump_stack.c:15 [<ffffffff8292049d>] dump_stack+0x6f/0xa2 kernel/lib/dump_stack.c:50 [<ffffffff816f2054>] print_trailer+0xf4/0x150 kernel/mm/slub.c:654 [<ffffffff816f875f>] object_err+0x2f/0x40 kernel/mm/slub.c:661 [< inline >] print_address_description kernel/mm/kasan/report.c:138 [<ffffffff816fb0c5>] kasan_report_error+0x215/0x530 kernel/mm/kasan/report.c:236 [< inline >] kasan_report kernel/mm/kasan/report.c:259 [<ffffffff816fb4de>] __asan_report_load8_noabort+0x3e/0x40 kernel/mm/kasan/report.c:280 [< inline >] ? ppp_pernet kernel/include/linux/compiler.h:218 [<ffffffff83ad71b2>] ? ppp_unregister_channel+0x372/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392 [< inline >] ppp_pernet kernel/include/linux/compiler.h:218 [<ffffffff83ad71b2>] ppp_unregister_channel+0x372/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392 [< inline >] ? ppp_pernet kernel/drivers/net/ppp/ppp_generic.c:293 [<ffffffff83ad6f26>] ? ppp_unregister_channel+0xe6/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392 [<ffffffff83ae18f3>] ppp_asynctty_close+0xa3/0x130 kernel/drivers/net/ppp/ppp_async.c:241 [<ffffffff83ae1850>] ? async_lcp_peek+0x5b0/0x5b0 kernel/drivers/net/ppp/ppp_async.c:1000 [<ffffffff82c33239>] tty_ldisc_close.isra.1+0x99/0xe0 kernel/drivers/tty/tty_ldisc.c:478 [<ffffffff82c332c0>] tty_ldisc_kill+0x40/0x170 kernel/drivers/tty/tty_ldisc.c:744 [<ffffffff82c34943>] tty_ldisc_release+0x1b3/0x260 kernel/drivers/tty/tty_ldisc.c:772 [<ffffffff82c1ef21>] tty_release+0xac1/0x13e0 kernel/drivers/tty/tty_io.c:1901 [<ffffffff82c1e460>] ? release_tty+0x320/0x320 kernel/drivers/tty/tty_io.c:1688 [<ffffffff8174de36>] __fput+0x236/0x780 kernel/fs/file_table.c:208 [<ffffffff8174e405>] ____fput+0x15/0x20 kernel/fs/file_table.c:244 [<ffffffff813595ab>] task_work_run+0x16b/0x200 kernel/kernel/task_work.c:115 [< inline >] exit_task_work kernel/include/linux/task_work.h:21 [<ffffffff81307105>] do_exit+0x8b5/0x2c60 kernel/kernel/exit.c:750 [<ffffffff813fdd20>] ? debug_check_no_locks_freed+0x290/0x290 kernel/kernel/locking/lockdep.c:4123 [<ffffffff81306850>] ? mm_update_next_owner+0x6f0/0x6f0 kernel/kernel/exit.c:357 [<ffffffff813215e6>] ? __dequeue_signal+0x136/0x470 kernel/kernel/signal.c:550 [<ffffffff8132067b>] ? recalc_sigpending_tsk+0x13b/0x180 kernel/kernel/signal.c:145 [<ffffffff81309628>] do_group_exit+0x108/0x330 kernel/kernel/exit.c:880 [<ffffffff8132b9d4>] get_signal+0x5e4/0x14f0 kernel/kernel/signal.c:2307 [< inline >] ? kretprobe_table_lock kernel/kernel/kprobes.c:1113 [<ffffffff8151d355>] ? kprobe_flush_task+0xb5/0x450 kernel/kernel/kprobes.c:1158 [<ffffffff8115f7d3>] do_signal+0x83/0x1c90 kernel/arch/x86/kernel/signal.c:712 [<ffffffff8151d2a0>] ? recycle_rp_inst+0x310/0x310 kernel/include/linux/list.h:655 [<ffffffff8115f750>] ? setup_sigcontext+0x780/0x780 kernel/arch/x86/kernel/signal.c:165 [<ffffffff81380864>] ? finish_task_switch+0x424/0x5f0 kernel/kernel/sched/core.c:2692 [< inline >] ? finish_lock_switch kernel/kernel/sched/sched.h:1099 [<ffffffff81380560>] ? finish_task_switch+0x120/0x5f0 kernel/kernel/sched/core.c:2678 [< inline >] ? context_switch kernel/kernel/sched/core.c:2807 [<ffffffff85d794e9>] ? __schedule+0x919/0x1bd0 kernel/kernel/sched/core.c:3283 [<ffffffff81003901>] exit_to_usermode_loop+0xf1/0x1a0 kernel/arch/x86/entry/common.c:247 [< inline >] prepare_exit_to_usermode kernel/arch/x86/entry/common.c:282 [<ffffffff810062ef>] syscall_return_slowpath+0x19f/0x210 kernel/arch/x86/entry/common.c:344 [<ffffffff85d88022>] int_ret_from_sys_call+0x25/0x9f kernel/arch/x86/entry/entry_64.S:281 Memory state around the buggy address: ffff880064e21680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff880064e21700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb >ffff880064e21780: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ^ ffff880064e21800: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff880064e21880: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ================================================================== Fixes: 273ec51dd7ce ("net: ppp_generic - introduce net-namespace functionality v2") Reported-by: Baozeng Ding <[email protected]> Signed-off-by: Guillaume Nault <[email protected]> Reviewed-by: Cyrill Gorcunov <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void set_fat(DOS_FS * fs, uint32_t cluster, int32_t new) { unsigned char *data = NULL; int size; loff_t offs; if (new == -1) new = FAT_EOF(fs); else if ((long)new == -2) new = FAT_BAD(fs); switch (fs->fat_bits) { case 12: data = fs->fat + cluster * 3 / 2; offs = fs->fat_start + cluster * 3 / 2; if (cluster & 1) { FAT_ENTRY prevEntry; get_fat(&prevEntry, fs->fat, cluster - 1, fs); data[0] = ((new & 0xf) << 4) | (prevEntry.value >> 8); data[1] = new >> 4; } else { FAT_ENTRY subseqEntry; if (cluster != fs->clusters - 1) get_fat(&subseqEntry, fs->fat, cluster + 1, fs); else subseqEntry.value = 0; data[0] = new & 0xff; data[1] = (new >> 8) | ((0xff & subseqEntry.value) << 4); } size = 2; break; case 16: data = fs->fat + cluster * 2; offs = fs->fat_start + cluster * 2; *(unsigned short *)data = htole16(new); size = 2; break; case 32: { FAT_ENTRY curEntry; get_fat(&curEntry, fs->fat, cluster, fs); data = fs->fat + cluster * 4; offs = fs->fat_start + cluster * 4; /* According to M$, the high 4 bits of a FAT32 entry are reserved and * are not part of the cluster number. So we never touch them. */ *(uint32_t *)data = htole32((new & 0xfffffff) | (curEntry.reserved << 28)); size = 4; } break; default: die("Bad FAT entry size: %d bits.", fs->fat_bits); } fs_write(offs, size, data); if (fs->nfats > 1) { fs_write(offs + fs->fat_size, size, data); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'set_fat(): Fix off-by-2 error leading to corruption in FAT12 In FAT12 two 12 bit entries are combined to a 24 bit value (three bytes). Therefore, when an even numbered FAT entry is set in FAT12, it must be be combined with the following entry. To prevent accessing beyond the end of the FAT array, it must be checked that the cluster is not the last one. Previously, the check tested that the requested cluster was equal to fs->clusters - 1. However, fs->clusters is the number of data clusters not including the two reserved FAT entries at the start so the test triggered two clusters early. If the third to last entry was written on a FAT12 filesystem with an odd number of clusters, the second to last entry would be corrupted. This corruption may also lead to invalid memory accesses when the corrupted entry becomes out of bounds and is used later. Change the test to fs->clusters + 1 to fix. Reported-by: Hanno Böck Signed-off-by: Andreas Bombe <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void read_boot(DOS_FS * fs) { struct boot_sector b; unsigned total_sectors; unsigned short logical_sector_size, sectors; unsigned fat_length; unsigned total_fat_entries; off_t data_size; fs_read(0, sizeof(b), &b); logical_sector_size = GET_UNALIGNED_W(b.sector_size); if (!logical_sector_size) die("Logical sector size is zero."); /* This was moved up because it's the first thing that will fail */ /* if the platform needs special handling of unaligned multibyte accesses */ /* but such handling isn't being provided. See GET_UNALIGNED_W() above. */ if (logical_sector_size & (SECTOR_SIZE - 1)) die("Logical sector size (%d bytes) is not a multiple of the physical " "sector size.", logical_sector_size); fs->cluster_size = b.cluster_size * logical_sector_size; if (!fs->cluster_size) die("Cluster size is zero."); if (b.fats != 2 && b.fats != 1) die("Currently, only 1 or 2 FATs are supported, not %d.\n", b.fats); fs->nfats = b.fats; sectors = GET_UNALIGNED_W(b.sectors); total_sectors = sectors ? sectors : le32toh(b.total_sect); if (verbose) printf("Checking we can access the last sector of the filesystem\n"); /* Can't access last odd sector anyway, so round down */ fs_test((off_t)((total_sectors & ~1) - 1) * logical_sector_size, logical_sector_size); fat_length = le16toh(b.fat_length) ? le16toh(b.fat_length) : le32toh(b.fat32_length); fs->fat_start = (off_t)le16toh(b.reserved) * logical_sector_size; fs->root_start = ((off_t)le16toh(b.reserved) + b.fats * fat_length) * logical_sector_size; fs->root_entries = GET_UNALIGNED_W(b.dir_entries); fs->data_start = fs->root_start + ROUND_TO_MULTIPLE(fs->root_entries << MSDOS_DIR_BITS, logical_sector_size); data_size = (off_t)total_sectors * logical_sector_size - fs->data_start; fs->data_clusters = data_size / fs->cluster_size; fs->root_cluster = 0; /* indicates standard, pre-FAT32 root dir */ fs->fsinfo_start = 0; /* no FSINFO structure */ fs->free_clusters = -1; /* unknown */ if (!b.fat_length && b.fat32_length) { fs->fat_bits = 32; fs->root_cluster = le32toh(b.root_cluster); if (!fs->root_cluster && fs->root_entries) /* M$ hasn't specified this, but it looks reasonable: If * root_cluster is 0 but there is a separate root dir * (root_entries != 0), we handle the root dir the old way. Give a * warning, but convertig to a root dir in a cluster chain seems * to complex for now... */ printf("Warning: FAT32 root dir not in cluster chain! " "Compatibility mode...\n"); else if (!fs->root_cluster && !fs->root_entries) die("No root directory!"); else if (fs->root_cluster && fs->root_entries) printf("Warning: FAT32 root dir is in a cluster chain, but " "a separate root dir\n" " area is defined. Cannot fix this easily.\n"); if (fs->data_clusters < FAT16_THRESHOLD) printf("Warning: Filesystem is FAT32 according to fat_length " "and fat32_length fields,\n" " but has only %lu clusters, less than the required " "minimum of %d.\n" " This may lead to problems on some systems.\n", (unsigned long)fs->data_clusters, FAT16_THRESHOLD); check_fat_state_bit(fs, &b); fs->backupboot_start = le16toh(b.backup_boot) * logical_sector_size; check_backup_boot(fs, &b, logical_sector_size); read_fsinfo(fs, &b, logical_sector_size); } else if (!atari_format) { /* On real MS-DOS, a 16 bit FAT is used whenever there would be too * much clusers otherwise. */ fs->fat_bits = (fs->data_clusters >= FAT12_THRESHOLD) ? 16 : 12; if (fs->data_clusters >= FAT16_THRESHOLD) die("Too many clusters (%lu) for FAT16 filesystem.", fs->data_clusters); check_fat_state_bit(fs, &b); } else { /* On Atari, things are more difficult: GEMDOS always uses 12bit FATs * on floppies, and always 16 bit on harddisks. */ fs->fat_bits = 16; /* assume 16 bit FAT for now */ /* If more clusters than fat entries in 16-bit fat, we assume * it's a real MSDOS FS with 12-bit fat. */ if (fs->data_clusters + 2 > fat_length * logical_sector_size * 8 / 16 || /* if it has one of the usual floppy sizes -> 12bit FAT */ (total_sectors == 720 || total_sectors == 1440 || total_sectors == 2880)) fs->fat_bits = 12; } /* On FAT32, the high 4 bits of a FAT entry are reserved */ fs->eff_fat_bits = (fs->fat_bits == 32) ? 28 : fs->fat_bits; fs->fat_size = fat_length * logical_sector_size; fs->label = calloc(12, sizeof(uint8_t)); if (fs->fat_bits == 12 || fs->fat_bits == 16) { struct boot_sector_16 *b16 = (struct boot_sector_16 *)&b; if (b16->extended_sig == 0x29) memmove(fs->label, b16->label, 11); else fs->label = NULL; } else if (fs->fat_bits == 32) { if (b.extended_sig == 0x29) memmove(fs->label, &b.label, 11); else fs->label = NULL; } total_fat_entries = (uint64_t)fs->fat_size * 8 / fs->fat_bits; if (fs->data_clusters > total_fat_entries - 2) die("Filesystem has %u clusters but only space for %u FAT entries.", fs->data_clusters, total_fat_entries - 2); if (!fs->root_entries && !fs->root_cluster) die("Root directory has zero size."); if (fs->root_entries & (MSDOS_DPS - 1)) die("Root directory (%d entries) doesn't span an integral number of " "sectors.", fs->root_entries); if (logical_sector_size & (SECTOR_SIZE - 1)) die("Logical sector size (%d bytes) is not a multiple of the physical " "sector size.", logical_sector_size); #if 0 /* linux kernel doesn't check that either */ /* ++roman: On Atari, these two fields are often left uninitialized */ if (!atari_format && (!b.secs_track || !b.heads)) die("Invalid disk format in boot sector."); #endif if (verbose) dump_boot(fs, &b, logical_sector_size); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-703'], 'message': 'read_boot(): Handle excessive FAT size specifications The variable used for storing the FAT size (in bytes) was an unsigned int. Since the size in sectors read from the BPB was not sufficiently checked, this could end up being zero after multiplying it with the sector size while some offsets still stayed excessive. Ultimately it would cause segfaults when accessing FAT entries for which no memory was allocated. Make it more robust by changing the types used to store FAT size to off_t and abort if there is no room for data clusters. Additionally check that FAT size is not specified as zero. Fixes #25 and fixes #26. Reported-by: Hanno Böck Signed-off-by: Andreas Bombe <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color) { int lastBorder; /* Seek left */ int leftLimit, rightLimit; int i; leftLimit = (-1); if (border < 0) { /* Refuse to fill to a non-solid border */ return; } for (i = x; (i >= 0); i--) { if (gdImageGetPixel (im, i, y) == border) { break; } gdImageSetPixel (im, i, y, color); leftLimit = i; } if (leftLimit == (-1)) { return; } /* Seek right */ rightLimit = x; for (i = (x + 1); (i < im->sx); i++) { if (gdImageGetPixel (im, i, y) == border) { break; } gdImageSetPixel (im, i, y, color); rightLimit = i; } /* Look at lines above and below and start paints */ /* Above */ if (y > 0) { lastBorder = 1; for (i = leftLimit; (i <= rightLimit); i++) { int c; c = gdImageGetPixel (im, i, y - 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder (im, i, y - 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } /* Below */ if (y < ((im->sy) - 1)) { lastBorder = 1; for (i = leftLimit; (i <= rightLimit); i++) { int c; c = gdImageGetPixel (im, i, y + 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder (im, i, y + 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed bug #22965 (Crash in gd lib's ImageFillToBorder()).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int tipc_nl_publ_dump(struct sk_buff *skb, struct netlink_callback *cb) { int err; u32 tsk_portid = cb->args[0]; u32 last_publ = cb->args[1]; u32 done = cb->args[2]; struct net *net = sock_net(skb->sk); struct tipc_sock *tsk; if (!tsk_portid) { struct nlattr **attrs; struct nlattr *sock[TIPC_NLA_SOCK_MAX + 1]; err = tipc_nlmsg_parse(cb->nlh, &attrs); if (err) return err; err = nla_parse_nested(sock, TIPC_NLA_SOCK_MAX, attrs[TIPC_NLA_SOCK], tipc_nl_sock_policy); if (err) return err; if (!sock[TIPC_NLA_SOCK_REF]) return -EINVAL; tsk_portid = nla_get_u32(sock[TIPC_NLA_SOCK_REF]); } if (done) return 0; tsk = tipc_sk_lookup(net, tsk_portid); if (!tsk) return -EINVAL; lock_sock(&tsk->sk); err = __tipc_nl_list_sk_publ(skb, cb, tsk, &last_publ); if (!err) done = 1; release_sock(&tsk->sk); sock_put(&tsk->sk); cb->args[0] = tsk_portid; cb->args[1] = last_publ; cb->args[2] = done; return skb->len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'tipc: check nl sock before parsing nested attributes Make sure the socket for which the user is listing publication exists before parsing the socket netlink attributes. Prior to this patch a call without any socket caused a NULL pointer dereference in tipc_nl_publ_dump(). Tested-and-reported-by: Baozeng Ding <[email protected]> Signed-off-by: Richard Alpe <[email protected]> Acked-by: Jon Maloy <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlParseElementDecl(xmlParserCtxtPtr ctxt) { const xmlChar *name; int ret = -1; xmlElementContentPtr content = NULL; /* GROW; done in the caller */ if (CMP9(CUR_PTR, '<', '!', 'E', 'L', 'E', 'M', 'E', 'N', 'T')) { xmlParserInputPtr input = ctxt->input; SKIP(9); if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after 'ELEMENT'\n"); } SKIP_BLANKS; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseElementDecl: no name for Element\n"); return(-1); } while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after the element name\n"); } SKIP_BLANKS; if (CMP5(CUR_PTR, 'E', 'M', 'P', 'T', 'Y')) { SKIP(5); /* * Element must always be empty. */ ret = XML_ELEMENT_TYPE_EMPTY; } else if ((RAW == 'A') && (NXT(1) == 'N') && (NXT(2) == 'Y')) { SKIP(3); /* * Element is a generic container. */ ret = XML_ELEMENT_TYPE_ANY; } else if (RAW == '(') { ret = xmlParseElementContentDecl(ctxt, name, &content); } else { /* * [ WFC: PEs in Internal Subset ] error handling. */ if ((RAW == '%') && (ctxt->external == 0) && (ctxt->inputNr == 1)) { xmlFatalErrMsg(ctxt, XML_ERR_PEREF_IN_INT_SUBSET, "PEReference: forbidden within markup decl in internal subset\n"); } else { xmlFatalErrMsg(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, "xmlParseElementDecl: 'EMPTY', 'ANY' or '(' expected\n"); } return(-1); } SKIP_BLANKS; /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); SKIP_BLANKS; if (RAW != '>') { xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL); if (content != NULL) { xmlFreeDocElementContent(ctxt->myDoc, content); } } else { if (input != ctxt->input) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, "Element declaration doesn't start and stop in the same entity\n"); } NEXT; if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->elementDecl != NULL)) { if (content != NULL) content->parent = NULL; ctxt->sax->elementDecl(ctxt->userData, name, ret, content); if ((content != NULL) && (content->parent == NULL)) { /* * this is a trick: if xmlAddElementDecl is called, * instead of copying the full tree it is plugged directly * if called from the parser. Avoid duplicating the * interfaces or change the API/ABI */ xmlFreeDocElementContent(ctxt->myDoc, content); } } else if (content != NULL) { xmlFreeDocElementContent(ctxt->myDoc, content); } } } return(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Heap-based buffer-underreads due to xmlParseName For https://bugzilla.gnome.org/show_bug.cgi?id=759573 * parser.c: (xmlParseElementDecl): Return early on invalid input to fix non-minimized test case (759573-2.xml). Otherwise the parser gets into a bad state in SKIP(3) at the end of the function. (xmlParseConditionalSections): Halt parsing when hitting invalid input that would otherwise caused xmlParserHandlePEReference() to recurse unexpectedly. This fixes the minimized test case (759573.xml). * result/errors/759573-2.xml: Add. * result/errors/759573-2.xml.err: Add. * result/errors/759573-2.xml.str: Add. * result/errors/759573.xml: Add. * result/errors/759573.xml.err: Add. * result/errors/759573.xml.str: Add. * test/errors/759573-2.xml: Add. * test/errors/759573.xml: Add.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref, const xmlChar **URI, int *tlen) { const xmlChar *localname; const xmlChar *prefix; const xmlChar *attname; const xmlChar *aprefix; const xmlChar *nsname; xmlChar *attvalue; const xmlChar **atts = ctxt->atts; int maxatts = ctxt->maxatts; int nratts, nbatts, nbdef; int i, j, nbNs, attval, oldline, oldcol, inputNr; const xmlChar *base; unsigned long cur; int nsNr = ctxt->nsNr; if (RAW != '<') return(NULL); NEXT1; /* * NOTE: it is crucial with the SAX2 API to never call SHRINK beyond that * point since the attribute values may be stored as pointers to * the buffer and calling SHRINK would destroy them ! * The Shrinking is only possible once the full set of attribute * callbacks have been done. */ reparse: SHRINK; base = ctxt->input->base; cur = ctxt->input->cur - ctxt->input->base; inputNr = ctxt->inputNr; oldline = ctxt->input->line; oldcol = ctxt->input->col; nbatts = 0; nratts = 0; nbdef = 0; nbNs = 0; attval = 0; /* Forget any namespaces added during an earlier parse of this element. */ ctxt->nsNr = nsNr; localname = xmlParseQName(ctxt, &prefix); if (localname == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "StartTag: invalid element name\n"); return(NULL); } *tlen = ctxt->input->cur - ctxt->input->base - cur; /* * Now parse the attributes, it ends up with the ending * * (S Attribute)* S? */ SKIP_BLANKS; GROW; if ((ctxt->input->base != base) || (inputNr != ctxt->inputNr)) goto base_changed; while (((RAW != '>') && ((RAW != '/') || (NXT(1) != '>')) && (IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) { const xmlChar *q = CUR_PTR; unsigned int cons = ctxt->input->consumed; int len = -1, alloc = 0; attname = xmlParseAttribute2(ctxt, prefix, localname, &aprefix, &attvalue, &len, &alloc); if ((ctxt->input->base != base) || (inputNr != ctxt->inputNr)) { if ((attvalue != NULL) && (alloc != 0)) xmlFree(attvalue); attvalue = NULL; goto base_changed; } if ((attname != NULL) && (attvalue != NULL)) { if (len < 0) len = xmlStrlen(attvalue); if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) { const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len); xmlURIPtr uri; if (URL == NULL) { xmlErrMemory(ctxt, "dictionary allocation failure"); if ((attvalue != NULL) && (alloc != 0)) xmlFree(attvalue); return(NULL); } if (*URL != 0) { uri = xmlParseURI((const char *) URL); if (uri == NULL) { xmlNsErr(ctxt, XML_WAR_NS_URI, "xmlns: '%s' is not a valid URI\n", URL, NULL, NULL); } else { if (uri->scheme == NULL) { xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE, "xmlns: URI %s is not absolute\n", URL, NULL, NULL); } xmlFreeURI(uri); } if (URL == ctxt->str_xml_ns) { if (attname != ctxt->str_xml) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "xml namespace URI cannot be the default namespace\n", NULL, NULL, NULL); } goto skip_default_ns; } if ((len == 29) && (xmlStrEqual(URL, BAD_CAST "http://www.w3.org/2000/xmlns/"))) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "reuse of the xmlns namespace name is forbidden\n", NULL, NULL, NULL); goto skip_default_ns; } } /* * check that it's not a defined namespace */ for (j = 1;j <= nbNs;j++) if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL) break; if (j <= nbNs) xmlErrAttributeDup(ctxt, NULL, attname); else if (nsPush(ctxt, NULL, URL) > 0) nbNs++; skip_default_ns: if (alloc != 0) xmlFree(attvalue); if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>')))) break; if (!IS_BLANK_CH(RAW)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "attributes construct error\n"); break; } SKIP_BLANKS; continue; } if (aprefix == ctxt->str_xmlns) { const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len); xmlURIPtr uri; if (attname == ctxt->str_xml) { if (URL != ctxt->str_xml_ns) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "xml namespace prefix mapped to wrong URI\n", NULL, NULL, NULL); } /* * Do not keep a namespace definition node */ goto skip_ns; } if (URL == ctxt->str_xml_ns) { if (attname != ctxt->str_xml) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "xml namespace URI mapped to wrong prefix\n", NULL, NULL, NULL); } goto skip_ns; } if (attname == ctxt->str_xmlns) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "redefinition of the xmlns prefix is forbidden\n", NULL, NULL, NULL); goto skip_ns; } if ((len == 29) && (xmlStrEqual(URL, BAD_CAST "http://www.w3.org/2000/xmlns/"))) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "reuse of the xmlns namespace name is forbidden\n", NULL, NULL, NULL); goto skip_ns; } if ((URL == NULL) || (URL[0] == 0)) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "xmlns:%s: Empty XML namespace is not allowed\n", attname, NULL, NULL); goto skip_ns; } else { uri = xmlParseURI((const char *) URL); if (uri == NULL) { xmlNsErr(ctxt, XML_WAR_NS_URI, "xmlns:%s: '%s' is not a valid URI\n", attname, URL, NULL); } else { if ((ctxt->pedantic) && (uri->scheme == NULL)) { xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE, "xmlns:%s: URI %s is not absolute\n", attname, URL, NULL); } xmlFreeURI(uri); } } /* * check that it's not a defined namespace */ for (j = 1;j <= nbNs;j++) if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname) break; if (j <= nbNs) xmlErrAttributeDup(ctxt, aprefix, attname); else if (nsPush(ctxt, attname, URL) > 0) nbNs++; skip_ns: if (alloc != 0) xmlFree(attvalue); if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>')))) break; if (!IS_BLANK_CH(RAW)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "attributes construct error\n"); break; } SKIP_BLANKS; if ((ctxt->input->base != base) || (inputNr != ctxt->inputNr)) goto base_changed; continue; } /* * Add the pair to atts */ if ((atts == NULL) || (nbatts + 5 > maxatts)) { if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) { if (attvalue[len] == 0) xmlFree(attvalue); goto failed; } maxatts = ctxt->maxatts; atts = ctxt->atts; } ctxt->attallocs[nratts++] = alloc; atts[nbatts++] = attname; atts[nbatts++] = aprefix; atts[nbatts++] = NULL; /* the URI will be fetched later */ atts[nbatts++] = attvalue; attvalue += len; atts[nbatts++] = attvalue; /* * tag if some deallocation is needed */ if (alloc != 0) attval = 1; } else { if ((attvalue != NULL) && (attvalue[len] == 0)) xmlFree(attvalue); } failed: GROW if (ctxt->instate == XML_PARSER_EOF) break; if ((ctxt->input->base != base) || (inputNr != ctxt->inputNr)) goto base_changed; if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>')))) break; if (!IS_BLANK_CH(RAW)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "attributes construct error\n"); break; } SKIP_BLANKS; if ((cons == ctxt->input->consumed) && (q == CUR_PTR) && (attname == NULL) && (attvalue == NULL)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlParseStartTag: problem parsing attributes\n"); break; } GROW; if ((ctxt->input->base != base) || (inputNr != ctxt->inputNr)) goto base_changed; } /* * The attributes defaulting */ if (ctxt->attsDefault != NULL) { xmlDefAttrsPtr defaults; defaults = xmlHashLookup2(ctxt->attsDefault, localname, prefix); if (defaults != NULL) { for (i = 0;i < defaults->nbAttrs;i++) { attname = defaults->values[5 * i]; aprefix = defaults->values[5 * i + 1]; /* * special work for namespaces defaulted defs */ if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) { /* * check that it's not a defined namespace */ for (j = 1;j <= nbNs;j++) if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL) break; if (j <= nbNs) continue; nsname = xmlGetNamespace(ctxt, NULL); if (nsname != defaults->values[5 * i + 2]) { if (nsPush(ctxt, NULL, defaults->values[5 * i + 2]) > 0) nbNs++; } } else if (aprefix == ctxt->str_xmlns) { /* * check that it's not a defined namespace */ for (j = 1;j <= nbNs;j++) if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname) break; if (j <= nbNs) continue; nsname = xmlGetNamespace(ctxt, attname); if (nsname != defaults->values[2]) { if (nsPush(ctxt, attname, defaults->values[5 * i + 2]) > 0) nbNs++; } } else { /* * check that it's not a defined attribute */ for (j = 0;j < nbatts;j+=5) { if ((attname == atts[j]) && (aprefix == atts[j+1])) break; } if (j < nbatts) continue; if ((atts == NULL) || (nbatts + 5 > maxatts)) { if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) { return(NULL); } maxatts = ctxt->maxatts; atts = ctxt->atts; } atts[nbatts++] = attname; atts[nbatts++] = aprefix; if (aprefix == NULL) atts[nbatts++] = NULL; else atts[nbatts++] = xmlGetNamespace(ctxt, aprefix); atts[nbatts++] = defaults->values[5 * i + 2]; atts[nbatts++] = defaults->values[5 * i + 3]; if ((ctxt->standalone == 1) && (defaults->values[5 * i + 4] != NULL)) { xmlValidityError(ctxt, XML_DTD_STANDALONE_DEFAULTED, "standalone: attribute %s on %s defaulted from external subset\n", attname, localname); } nbdef++; } } } } /* * The attributes checkings */ for (i = 0; i < nbatts;i += 5) { /* * The default namespace does not apply to attribute names. */ if (atts[i + 1] != NULL) { nsname = xmlGetNamespace(ctxt, atts[i + 1]); if (nsname == NULL) { xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE, "Namespace prefix %s for %s on %s is not defined\n", atts[i + 1], atts[i], localname); } atts[i + 2] = nsname; } else nsname = NULL; /* * [ WFC: Unique Att Spec ] * No attribute name may appear more than once in the same * start-tag or empty-element tag. * As extended by the Namespace in XML REC. */ for (j = 0; j < i;j += 5) { if (atts[i] == atts[j]) { if (atts[i+1] == atts[j+1]) { xmlErrAttributeDup(ctxt, atts[i+1], atts[i]); break; } if ((nsname != NULL) && (atts[j + 2] == nsname)) { xmlNsErr(ctxt, XML_NS_ERR_ATTRIBUTE_REDEFINED, "Namespaced Attribute %s in '%s' redefined\n", atts[i], nsname, NULL); break; } } } } nsname = xmlGetNamespace(ctxt, prefix); if ((prefix != NULL) && (nsname == NULL)) { xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE, "Namespace prefix %s on %s is not defined\n", prefix, localname, NULL); } *pref = prefix; *URI = nsname; /* * SAX: Start of Element ! */ if ((ctxt->sax != NULL) && (ctxt->sax->startElementNs != NULL) && (!ctxt->disableSAX)) { if (nbNs > 0) ctxt->sax->startElementNs(ctxt->userData, localname, prefix, nsname, nbNs, &ctxt->nsTab[ctxt->nsNr - 2 * nbNs], nbatts / 5, nbdef, atts); else ctxt->sax->startElementNs(ctxt->userData, localname, prefix, nsname, 0, NULL, nbatts / 5, nbdef, atts); } /* * Free up attribute allocated strings if needed */ if (attval != 0) { for (i = 3,j = 0; j < nratts;i += 5,j++) if ((ctxt->attallocs[j] != 0) && (atts[i] != NULL)) xmlFree((xmlChar *) atts[i]); } return(localname); base_changed: /* * the attribute strings are valid iif the base didn't changed */ if (attval != 0) { for (i = 3,j = 0; j < nratts;i += 5,j++) if ((ctxt->attallocs[j] != 0) && (atts[i] != NULL)) xmlFree((xmlChar *) atts[i]); } /* * We can't switch from one entity to another in the middle * of a start tag */ if (inputNr != ctxt->inputNr) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, "Start tag doesn't start and stop in the same entity\n"); return(NULL); } ctxt->input->cur = ctxt->input->base + cur; ctxt->input->line = oldline; ctxt->input->col = oldcol; if (ctxt->wellFormed == 1) { goto reparse; } return(NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Heap use-after-free in xmlSAX2AttributeNs For https://bugzilla.gnome.org/show_bug.cgi?id=759020 * parser.c: (xmlParseStartTag2): Attribute strings are only valid if the base does not change, so add another check where the base may change. Make sure to set 'attvalue' to NULL after freeing it. * result/errors/759020.xml: Added. * result/errors/759020.xml.err: Added. * result/errors/759020.xml.str: Added. * test/errors/759020.xml: Added test case.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: htmlParseSystemLiteral(htmlParserCtxtPtr ctxt) { const xmlChar *q; xmlChar *ret = NULL; if (CUR == '"') { NEXT; q = CUR_PTR; while ((IS_CHAR_CH(CUR)) && (CUR != '"')) NEXT; if (!IS_CHAR_CH(CUR)) { htmlParseErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, "Unfinished SystemLiteral\n", NULL, NULL); } else { ret = xmlStrndup(q, CUR_PTR - q); NEXT; } } else if (CUR == '\'') { NEXT; q = CUR_PTR; while ((IS_CHAR_CH(CUR)) && (CUR != '\'')) NEXT; if (!IS_CHAR_CH(CUR)) { htmlParseErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, "Unfinished SystemLiteral\n", NULL, NULL); } else { ret = xmlStrndup(q, CUR_PTR - q); NEXT; } } else { htmlParseErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, " or ' expected\n", NULL, NULL); } return(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Heap use-after-free in htmlParsePubidLiteral and htmlParseSystemiteral For https://bugzilla.gnome.org/show_bug.cgi?id=760263 * HTMLparser.c: Add BASE_PTR convenience macro. (htmlParseSystemLiteral): Store length and start position instead of a pointer while iterating through the public identifier since the underlying buffer may change, resulting in a stale pointer being used. (htmlParsePubidLiteral): Ditto.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlFatalErr(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *info) { const char *errmsg; char errstr[129] = ""; if ((ctxt != NULL) && (ctxt->disableSAX != 0) && (ctxt->instate == XML_PARSER_EOF)) return; switch (error) { case XML_ERR_INVALID_HEX_CHARREF: errmsg = "CharRef: invalid hexadecimal value"; break; case XML_ERR_INVALID_DEC_CHARREF: errmsg = "CharRef: invalid decimal value"; break; case XML_ERR_INVALID_CHARREF: errmsg = "CharRef: invalid value"; break; case XML_ERR_INTERNAL_ERROR: errmsg = "internal error"; break; case XML_ERR_PEREF_AT_EOF: errmsg = "PEReference at end of document"; break; case XML_ERR_PEREF_IN_PROLOG: errmsg = "PEReference in prolog"; break; case XML_ERR_PEREF_IN_EPILOG: errmsg = "PEReference in epilog"; break; case XML_ERR_PEREF_NO_NAME: errmsg = "PEReference: no name"; break; case XML_ERR_PEREF_SEMICOL_MISSING: errmsg = "PEReference: expecting ';'"; break; case XML_ERR_ENTITY_LOOP: errmsg = "Detected an entity reference loop"; break; case XML_ERR_ENTITY_NOT_STARTED: errmsg = "EntityValue: \" or ' expected"; break; case XML_ERR_ENTITY_PE_INTERNAL: errmsg = "PEReferences forbidden in internal subset"; break; case XML_ERR_ENTITY_NOT_FINISHED: errmsg = "EntityValue: \" or ' expected"; break; case XML_ERR_ATTRIBUTE_NOT_STARTED: errmsg = "AttValue: \" or ' expected"; break; case XML_ERR_LT_IN_ATTRIBUTE: errmsg = "Unescaped '<' not allowed in attributes values"; break; case XML_ERR_LITERAL_NOT_STARTED: errmsg = "SystemLiteral \" or ' expected"; break; case XML_ERR_LITERAL_NOT_FINISHED: errmsg = "Unfinished System or Public ID \" or ' expected"; break; case XML_ERR_MISPLACED_CDATA_END: errmsg = "Sequence ']]>' not allowed in content"; break; case XML_ERR_URI_REQUIRED: errmsg = "SYSTEM or PUBLIC, the URI is missing"; break; case XML_ERR_PUBID_REQUIRED: errmsg = "PUBLIC, the Public Identifier is missing"; break; case XML_ERR_HYPHEN_IN_COMMENT: errmsg = "Comment must not contain '--' (double-hyphen)"; break; case XML_ERR_PI_NOT_STARTED: errmsg = "xmlParsePI : no target name"; break; case XML_ERR_RESERVED_XML_NAME: errmsg = "Invalid PI name"; break; case XML_ERR_NOTATION_NOT_STARTED: errmsg = "NOTATION: Name expected here"; break; case XML_ERR_NOTATION_NOT_FINISHED: errmsg = "'>' required to close NOTATION declaration"; break; case XML_ERR_VALUE_REQUIRED: errmsg = "Entity value required"; break; case XML_ERR_URI_FRAGMENT: errmsg = "Fragment not allowed"; break; case XML_ERR_ATTLIST_NOT_STARTED: errmsg = "'(' required to start ATTLIST enumeration"; break; case XML_ERR_NMTOKEN_REQUIRED: errmsg = "NmToken expected in ATTLIST enumeration"; break; case XML_ERR_ATTLIST_NOT_FINISHED: errmsg = "')' required to finish ATTLIST enumeration"; break; case XML_ERR_MIXED_NOT_STARTED: errmsg = "MixedContentDecl : '|' or ')*' expected"; break; case XML_ERR_PCDATA_REQUIRED: errmsg = "MixedContentDecl : '#PCDATA' expected"; break; case XML_ERR_ELEMCONTENT_NOT_STARTED: errmsg = "ContentDecl : Name or '(' expected"; break; case XML_ERR_ELEMCONTENT_NOT_FINISHED: errmsg = "ContentDecl : ',' '|' or ')' expected"; break; case XML_ERR_PEREF_IN_INT_SUBSET: errmsg = "PEReference: forbidden within markup decl in internal subset"; break; case XML_ERR_GT_REQUIRED: errmsg = "expected '>'"; break; case XML_ERR_CONDSEC_INVALID: errmsg = "XML conditional section '[' expected"; break; case XML_ERR_EXT_SUBSET_NOT_FINISHED: errmsg = "Content error in the external subset"; break; case XML_ERR_CONDSEC_INVALID_KEYWORD: errmsg = "conditional section INCLUDE or IGNORE keyword expected"; break; case XML_ERR_CONDSEC_NOT_FINISHED: errmsg = "XML conditional section not closed"; break; case XML_ERR_XMLDECL_NOT_STARTED: errmsg = "Text declaration '<?xml' required"; break; case XML_ERR_XMLDECL_NOT_FINISHED: errmsg = "parsing XML declaration: '?>' expected"; break; case XML_ERR_EXT_ENTITY_STANDALONE: errmsg = "external parsed entities cannot be standalone"; break; case XML_ERR_ENTITYREF_SEMICOL_MISSING: errmsg = "EntityRef: expecting ';'"; break; case XML_ERR_DOCTYPE_NOT_FINISHED: errmsg = "DOCTYPE improperly terminated"; break; case XML_ERR_LTSLASH_REQUIRED: errmsg = "EndTag: '</' not found"; break; case XML_ERR_EQUAL_REQUIRED: errmsg = "expected '='"; break; case XML_ERR_STRING_NOT_CLOSED: errmsg = "String not closed expecting \" or '"; break; case XML_ERR_STRING_NOT_STARTED: errmsg = "String not started expecting ' or \""; break; case XML_ERR_ENCODING_NAME: errmsg = "Invalid XML encoding name"; break; case XML_ERR_STANDALONE_VALUE: errmsg = "standalone accepts only 'yes' or 'no'"; break; case XML_ERR_DOCUMENT_EMPTY: errmsg = "Document is empty"; break; case XML_ERR_DOCUMENT_END: errmsg = "Extra content at the end of the document"; break; case XML_ERR_NOT_WELL_BALANCED: errmsg = "chunk is not well balanced"; break; case XML_ERR_EXTRA_CONTENT: errmsg = "extra content at the end of well balanced chunk"; break; case XML_ERR_VERSION_MISSING: errmsg = "Malformed declaration expecting version"; break; case XML_ERR_NAME_TOO_LONG: errmsg = "Name too long use XML_PARSE_HUGE option"; break; #if 0 case: errmsg = ""; break; #endif default: errmsg = "Unregistered error message"; } if (info == NULL) snprintf(errstr, 128, "%s\n", errmsg); else snprintf(errstr, 128, "%s: %%s\n", errmsg); if (ctxt != NULL) ctxt->errNo = error; __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL, NULL, 0, info, NULL, NULL, 0, 0, &errstr[0], info); if (ctxt != NULL) { ctxt->wellFormed = 0; if (ctxt->recovery == 0) ctxt->disableSAX = 1; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'Fix some format string warnings with possible format string vulnerability For https://bugzilla.gnome.org/show_bug.cgi?id=761029 Decorate every method in libxml2 with the appropriate LIBXML_ATTR_FORMAT(fmt,args) macro and add some cleanups following the reports.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlParseEntityDecl(xmlParserCtxtPtr ctxt) { const xmlChar *name = NULL; xmlChar *value = NULL; xmlChar *URI = NULL, *literal = NULL; const xmlChar *ndata = NULL; int isParameter = 0; xmlChar *orig = NULL; int skipped; /* GROW; done in the caller */ if (CMP8(CUR_PTR, '<', '!', 'E', 'N', 'T', 'I', 'T', 'Y')) { xmlParserInputPtr input = ctxt->input; SHRINK; SKIP(8); skipped = SKIP_BLANKS; if (skipped == 0) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after '<!ENTITY'\n"); } if (RAW == '%') { NEXT; skipped = SKIP_BLANKS; if (skipped == 0) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after '%'\n"); } isParameter = 1; } name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseEntityDecl: no name\n"); return; } if (xmlStrchr(name, ':') != NULL) { xmlNsErr(ctxt, XML_NS_ERR_COLON, "colons are forbidden from entities names '%s'\n", name, NULL, NULL); } skipped = SKIP_BLANKS; if (skipped == 0) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after the entity name\n"); } ctxt->instate = XML_PARSER_ENTITY_DECL; /* * handle the various case of definitions... */ if (isParameter) { if ((RAW == '"') || (RAW == '\'')) { value = xmlParseEntityValue(ctxt, &orig); if (value) { if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL)) ctxt->sax->entityDecl(ctxt->userData, name, XML_INTERNAL_PARAMETER_ENTITY, NULL, NULL, value); } } else { URI = xmlParseExternalID(ctxt, &literal, 1); if ((URI == NULL) && (literal == NULL)) { xmlFatalErr(ctxt, XML_ERR_VALUE_REQUIRED, NULL); } if (URI) { xmlURIPtr uri; uri = xmlParseURI((const char *) URI); if (uri == NULL) { xmlErrMsgStr(ctxt, XML_ERR_INVALID_URI, "Invalid URI: %s\n", URI); /* * This really ought to be a well formedness error * but the XML Core WG decided otherwise c.f. issue * E26 of the XML erratas. */ } else { if (uri->fragment != NULL) { /* * Okay this is foolish to block those but not * invalid URIs. */ xmlFatalErr(ctxt, XML_ERR_URI_FRAGMENT, NULL); } else { if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL)) ctxt->sax->entityDecl(ctxt->userData, name, XML_EXTERNAL_PARAMETER_ENTITY, literal, URI, NULL); } xmlFreeURI(uri); } } } } else { if ((RAW == '"') || (RAW == '\'')) { value = xmlParseEntityValue(ctxt, &orig); if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL)) ctxt->sax->entityDecl(ctxt->userData, name, XML_INTERNAL_GENERAL_ENTITY, NULL, NULL, value); /* * For expat compatibility in SAX mode. */ if ((ctxt->myDoc == NULL) || (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) { if (ctxt->myDoc == NULL) { ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE); if (ctxt->myDoc == NULL) { xmlErrMemory(ctxt, "New Doc failed"); return; } ctxt->myDoc->properties = XML_DOC_INTERNAL; } if (ctxt->myDoc->intSubset == NULL) ctxt->myDoc->intSubset = xmlNewDtd(ctxt->myDoc, BAD_CAST "fake", NULL, NULL); xmlSAX2EntityDecl(ctxt, name, XML_INTERNAL_GENERAL_ENTITY, NULL, NULL, value); } } else { URI = xmlParseExternalID(ctxt, &literal, 1); if ((URI == NULL) && (literal == NULL)) { xmlFatalErr(ctxt, XML_ERR_VALUE_REQUIRED, NULL); } if (URI) { xmlURIPtr uri; uri = xmlParseURI((const char *)URI); if (uri == NULL) { xmlErrMsgStr(ctxt, XML_ERR_INVALID_URI, "Invalid URI: %s\n", URI); /* * This really ought to be a well formedness error * but the XML Core WG decided otherwise c.f. issue * E26 of the XML erratas. */ } else { if (uri->fragment != NULL) { /* * Okay this is foolish to block those but not * invalid URIs. */ xmlFatalErr(ctxt, XML_ERR_URI_FRAGMENT, NULL); } xmlFreeURI(uri); } } if ((RAW != '>') && (!IS_BLANK_CH(CUR))) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required before 'NDATA'\n"); } SKIP_BLANKS; if (CMP5(CUR_PTR, 'N', 'D', 'A', 'T', 'A')) { SKIP(5); if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after 'NDATA'\n"); } SKIP_BLANKS; ndata = xmlParseName(ctxt); if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->unparsedEntityDecl != NULL)) ctxt->sax->unparsedEntityDecl(ctxt->userData, name, literal, URI, ndata); } else { if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL)) ctxt->sax->entityDecl(ctxt->userData, name, XML_EXTERNAL_GENERAL_PARSED_ENTITY, literal, URI, NULL); /* * For expat compatibility in SAX mode. * assuming the entity repalcement was asked for */ if ((ctxt->replaceEntities != 0) && ((ctxt->myDoc == NULL) || (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE)))) { if (ctxt->myDoc == NULL) { ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE); if (ctxt->myDoc == NULL) { xmlErrMemory(ctxt, "New Doc failed"); return; } ctxt->myDoc->properties = XML_DOC_INTERNAL; } if (ctxt->myDoc->intSubset == NULL) ctxt->myDoc->intSubset = xmlNewDtd(ctxt->myDoc, BAD_CAST "fake", NULL, NULL); xmlSAX2EntityDecl(ctxt, name, XML_EXTERNAL_GENERAL_PARSED_ENTITY, literal, URI, NULL); } } } } if (ctxt->instate == XML_PARSER_EOF) return; SKIP_BLANKS; if (RAW != '>') { xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, "xmlParseEntityDecl: entity %s not terminated\n", name); xmlHaltParser(ctxt); } else { if (input != ctxt->input) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, "Entity declaration doesn't start and stop in the same entity\n"); } NEXT; } if (orig != NULL) { /* * Ugly mechanism to save the raw entity value. */ xmlEntityPtr cur = NULL; if (isParameter) { if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) cur = ctxt->sax->getParameterEntity(ctxt->userData, name); } else { if ((ctxt->sax != NULL) && (ctxt->sax->getEntity != NULL)) cur = ctxt->sax->getEntity(ctxt->userData, name); if ((cur == NULL) && (ctxt->userData==ctxt)) { cur = xmlSAX2GetEntity(ctxt, name); } } if (cur != NULL) { if (cur->orig != NULL) xmlFree(orig); else cur->orig = orig; } else xmlFree(orig); } if (value != NULL) xmlFree(value); if (URI != NULL) xmlFree(URI); if (literal != NULL) xmlFree(literal); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'Fix some format string warnings with possible format string vulnerability For https://bugzilla.gnome.org/show_bug.cgi?id=761029 Decorate every method in libxml2 with the appropriate LIBXML_ATTR_FORMAT(fmt,args) macro and add some cleanups following the reports.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlStrPrintf(xmlChar *buf, int len, const xmlChar *msg, ...) { va_list args; int ret; if((buf == NULL) || (msg == NULL)) { return(-1); } va_start(args, msg); ret = vsnprintf((char *) buf, len, (const char *) msg, args); va_end(args); buf[len - 1] = 0; /* be safe ! */ return(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'Fix some format string warnings with possible format string vulnerability For https://bugzilla.gnome.org/show_bug.cgi?id=761029 Decorate every method in libxml2 with the appropriate LIBXML_ATTR_FORMAT(fmt,args) macro and add some cleanups following the reports.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlSchemaInternalErr2(xmlSchemaAbstractCtxtPtr actxt, const char *funcName, const char *message, const xmlChar *str1, const xmlChar *str2) { xmlChar *msg = NULL; if (actxt == NULL) return; msg = xmlStrdup(BAD_CAST "Internal error: "); msg = xmlStrcat(msg, BAD_CAST funcName); msg = xmlStrcat(msg, BAD_CAST ", "); msg = xmlStrcat(msg, BAD_CAST message); msg = xmlStrcat(msg, BAD_CAST ".\n"); if (actxt->type == XML_SCHEMA_CTXT_VALIDATOR) xmlSchemaErr(actxt, XML_SCHEMAV_INTERNAL, NULL, (const char *) msg, str1, str2); else if (actxt->type == XML_SCHEMA_CTXT_PARSER) xmlSchemaErr(actxt, XML_SCHEMAP_INTERNAL, NULL, (const char *) msg, str1, str2); FREE_AND_NULL(msg) } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'Fix some format string warnings with possible format string vulnerability For https://bugzilla.gnome.org/show_bug.cgi?id=761029 Decorate every method in libxml2 with the appropriate LIBXML_ATTR_FORMAT(fmt,args) macro and add some cleanups following the reports.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlCreateZMemBuff( int compression ) { int z_err; int hdr_lgth; xmlZMemBuffPtr buff = NULL; if ( ( compression < 1 ) || ( compression > 9 ) ) return ( NULL ); /* Create the control and data areas */ buff = xmlMalloc( sizeof( xmlZMemBuff ) ); if ( buff == NULL ) { xmlIOErrMemory("creating buffer context"); return ( NULL ); } (void)memset( buff, 0, sizeof( xmlZMemBuff ) ); buff->size = INIT_HTTP_BUFF_SIZE; buff->zbuff = xmlMalloc( buff->size ); if ( buff->zbuff == NULL ) { xmlFreeZMemBuff( buff ); xmlIOErrMemory("creating buffer"); return ( NULL ); } z_err = deflateInit2( &buff->zctrl, compression, Z_DEFLATED, DFLT_WBITS, DFLT_MEM_LVL, Z_DEFAULT_STRATEGY ); if ( z_err != Z_OK ) { xmlChar msg[500]; xmlFreeZMemBuff( buff ); buff = NULL; xmlStrPrintf(msg, 500, (const xmlChar *) "xmlCreateZMemBuff: %s %d\n", "Error initializing compression context. ZLIB error:", z_err ); xmlIOErr(XML_IO_WRITE, (const char *) msg); return ( NULL ); } /* Set the header data. The CRC will be needed for the trailer */ buff->crc = crc32( 0L, NULL, 0 ); hdr_lgth = snprintf( (char *)buff->zbuff, buff->size, "%c%c%c%c%c%c%c%c%c%c", GZ_MAGIC1, GZ_MAGIC2, Z_DEFLATED, 0, 0, 0, 0, 0, 0, LXML_ZLIB_OS_CODE ); buff->zctrl.next_out = buff->zbuff + hdr_lgth; buff->zctrl.avail_out = buff->size - hdr_lgth; return ( buff ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'Fix some format string warnings with possible format string vulnerability For https://bugzilla.gnome.org/show_bug.cgi?id=761029 Decorate every method in libxml2 with the appropriate LIBXML_ATTR_FORMAT(fmt,args) macro and add some cleanups following the reports.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlSchemaFormatNodeForError(xmlChar ** msg, xmlSchemaAbstractCtxtPtr actxt, xmlNodePtr node) { xmlChar *str = NULL; *msg = NULL; if ((node != NULL) && (node->type != XML_ELEMENT_NODE) && (node->type != XML_ATTRIBUTE_NODE)) { /* * Don't try to format other nodes than element and * attribute nodes. * Play save and return an empty string. */ *msg = xmlStrdup(BAD_CAST ""); return(*msg); } if (node != NULL) { /* * Work on tree nodes. */ if (node->type == XML_ATTRIBUTE_NODE) { xmlNodePtr elem = node->parent; *msg = xmlStrdup(BAD_CAST "Element '"); if (elem->ns != NULL) *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, elem->ns->href, elem->name)); else *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, NULL, elem->name)); FREE_AND_NULL(str); *msg = xmlStrcat(*msg, BAD_CAST "', "); *msg = xmlStrcat(*msg, BAD_CAST "attribute '"); } else { *msg = xmlStrdup(BAD_CAST "Element '"); } if (node->ns != NULL) *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, node->ns->href, node->name)); else *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, NULL, node->name)); FREE_AND_NULL(str); *msg = xmlStrcat(*msg, BAD_CAST "': "); } else if (actxt->type == XML_SCHEMA_CTXT_VALIDATOR) { xmlSchemaValidCtxtPtr vctxt = (xmlSchemaValidCtxtPtr) actxt; /* * Work on node infos. */ if (vctxt->inode->nodeType == XML_ATTRIBUTE_NODE) { xmlSchemaNodeInfoPtr ielem = vctxt->elemInfos[vctxt->depth]; *msg = xmlStrdup(BAD_CAST "Element '"); *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, ielem->nsName, ielem->localName)); FREE_AND_NULL(str); *msg = xmlStrcat(*msg, BAD_CAST "', "); *msg = xmlStrcat(*msg, BAD_CAST "attribute '"); } else { *msg = xmlStrdup(BAD_CAST "Element '"); } *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, vctxt->inode->nsName, vctxt->inode->localName)); FREE_AND_NULL(str); *msg = xmlStrcat(*msg, BAD_CAST "': "); } else if (actxt->type == XML_SCHEMA_CTXT_PARSER) { /* * Hmm, no node while parsing? * Return an empty string, in case NULL will break something. */ *msg = xmlStrdup(BAD_CAST ""); } else { TODO return (NULL); } /* * VAL TODO: The output of the given schema component is currently * disabled. */ #if 0 if ((type != NULL) && (xmlSchemaIsGlobalItem(type))) { *msg = xmlStrcat(*msg, BAD_CAST " ["); *msg = xmlStrcat(*msg, xmlSchemaFormatItemForReport(&str, NULL, type, NULL, 0)); FREE_AND_NULL(str) *msg = xmlStrcat(*msg, BAD_CAST "]"); } #endif return (*msg); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'Fix some format string warnings with possible format string vulnerability For https://bugzilla.gnome.org/show_bug.cgi?id=761029 Decorate every method in libxml2 with the appropriate LIBXML_ATTR_FORMAT(fmt,args) macro and add some cleanups following the reports.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlIOHTTPWrite( void * context, const char * buffer, int len ) { xmlIOHTTPWriteCtxtPtr ctxt = context; if ( ( ctxt == NULL ) || ( ctxt->doc_buff == NULL ) || ( buffer == NULL ) ) return ( -1 ); if ( len > 0 ) { /* Use gzwrite or fwrite as previously setup in the open call */ #ifdef HAVE_ZLIB_H if ( ctxt->compression > 0 ) len = xmlZMemBuffAppend( ctxt->doc_buff, buffer, len ); else #endif len = xmlOutputBufferWrite( ctxt->doc_buff, len, buffer ); if ( len < 0 ) { xmlChar msg[500]; xmlStrPrintf(msg, 500, (const xmlChar *) "xmlIOHTTPWrite: %s\n%s '%s'.\n", "Error appending to internal buffer.", "Error sending document to URI", ctxt->uri ); xmlIOErr(XML_IO_WRITE, (const char *) msg); } } return ( len ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'Fix some format string warnings with possible format string vulnerability For https://bugzilla.gnome.org/show_bug.cgi?id=761029 Decorate every method in libxml2 with the appropriate LIBXML_ATTR_FORMAT(fmt,args) macro and add some cleanups following the reports.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlRelaxNGGetErrorString(xmlRelaxNGValidErr err, const xmlChar * arg1, const xmlChar * arg2) { char msg[1000]; if (arg1 == NULL) arg1 = BAD_CAST ""; if (arg2 == NULL) arg2 = BAD_CAST ""; msg[0] = 0; switch (err) { case XML_RELAXNG_OK: return (NULL); case XML_RELAXNG_ERR_MEMORY: return (xmlCharStrdup("out of memory\n")); case XML_RELAXNG_ERR_TYPE: snprintf(msg, 1000, "failed to validate type %s\n", arg1); break; case XML_RELAXNG_ERR_TYPEVAL: snprintf(msg, 1000, "Type %s doesn't allow value '%s'\n", arg1, arg2); break; case XML_RELAXNG_ERR_DUPID: snprintf(msg, 1000, "ID %s redefined\n", arg1); break; case XML_RELAXNG_ERR_TYPECMP: snprintf(msg, 1000, "failed to compare type %s\n", arg1); break; case XML_RELAXNG_ERR_NOSTATE: return (xmlCharStrdup("Internal error: no state\n")); case XML_RELAXNG_ERR_NODEFINE: return (xmlCharStrdup("Internal error: no define\n")); case XML_RELAXNG_ERR_INTERNAL: snprintf(msg, 1000, "Internal error: %s\n", arg1); break; case XML_RELAXNG_ERR_LISTEXTRA: snprintf(msg, 1000, "Extra data in list: %s\n", arg1); break; case XML_RELAXNG_ERR_INTERNODATA: return (xmlCharStrdup ("Internal: interleave block has no data\n")); case XML_RELAXNG_ERR_INTERSEQ: return (xmlCharStrdup("Invalid sequence in interleave\n")); case XML_RELAXNG_ERR_INTEREXTRA: snprintf(msg, 1000, "Extra element %s in interleave\n", arg1); break; case XML_RELAXNG_ERR_ELEMNAME: snprintf(msg, 1000, "Expecting element %s, got %s\n", arg1, arg2); break; case XML_RELAXNG_ERR_ELEMNONS: snprintf(msg, 1000, "Expecting a namespace for element %s\n", arg1); break; case XML_RELAXNG_ERR_ELEMWRONGNS: snprintf(msg, 1000, "Element %s has wrong namespace: expecting %s\n", arg1, arg2); break; case XML_RELAXNG_ERR_ELEMWRONG: snprintf(msg, 1000, "Did not expect element %s there\n", arg1); break; case XML_RELAXNG_ERR_TEXTWRONG: snprintf(msg, 1000, "Did not expect text in element %s content\n", arg1); break; case XML_RELAXNG_ERR_ELEMEXTRANS: snprintf(msg, 1000, "Expecting no namespace for element %s\n", arg1); break; case XML_RELAXNG_ERR_ELEMNOTEMPTY: snprintf(msg, 1000, "Expecting element %s to be empty\n", arg1); break; case XML_RELAXNG_ERR_NOELEM: snprintf(msg, 1000, "Expecting an element %s, got nothing\n", arg1); break; case XML_RELAXNG_ERR_NOTELEM: return (xmlCharStrdup("Expecting an element got text\n")); case XML_RELAXNG_ERR_ATTRVALID: snprintf(msg, 1000, "Element %s failed to validate attributes\n", arg1); break; case XML_RELAXNG_ERR_CONTENTVALID: snprintf(msg, 1000, "Element %s failed to validate content\n", arg1); break; case XML_RELAXNG_ERR_EXTRACONTENT: snprintf(msg, 1000, "Element %s has extra content: %s\n", arg1, arg2); break; case XML_RELAXNG_ERR_INVALIDATTR: snprintf(msg, 1000, "Invalid attribute %s for element %s\n", arg1, arg2); break; case XML_RELAXNG_ERR_LACKDATA: snprintf(msg, 1000, "Datatype element %s contains no data\n", arg1); break; case XML_RELAXNG_ERR_DATAELEM: snprintf(msg, 1000, "Datatype element %s has child elements\n", arg1); break; case XML_RELAXNG_ERR_VALELEM: snprintf(msg, 1000, "Value element %s has child elements\n", arg1); break; case XML_RELAXNG_ERR_LISTELEM: snprintf(msg, 1000, "List element %s has child elements\n", arg1); break; case XML_RELAXNG_ERR_DATATYPE: snprintf(msg, 1000, "Error validating datatype %s\n", arg1); break; case XML_RELAXNG_ERR_VALUE: snprintf(msg, 1000, "Error validating value %s\n", arg1); break; case XML_RELAXNG_ERR_LIST: return (xmlCharStrdup("Error validating list\n")); case XML_RELAXNG_ERR_NOGRAMMAR: return (xmlCharStrdup("No top grammar defined\n")); case XML_RELAXNG_ERR_EXTRADATA: return (xmlCharStrdup("Extra data in the document\n")); default: return (xmlCharStrdup("Unknown error !\n")); } if (msg[0] == 0) { snprintf(msg, 1000, "Unknown error code %d\n", err); } msg[1000 - 1] = 0; return (xmlStrdup((xmlChar *) msg)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'More format string warnings with possible format string vulnerability For https://bugzilla.gnome.org/show_bug.cgi?id=761029 adds a new xmlEscapeFormatString() function to escape composed format strings'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlSchemaComplexTypeErr(xmlSchemaAbstractCtxtPtr actxt, xmlParserErrors error, xmlNodePtr node, xmlSchemaTypePtr type ATTRIBUTE_UNUSED, const char *message, int nbval, int nbneg, xmlChar **values) { xmlChar *str = NULL, *msg = NULL; xmlChar *localName, *nsName; const xmlChar *cur, *end; int i; xmlSchemaFormatNodeForError(&msg, actxt, node); msg = xmlStrcat(msg, (const xmlChar *) message); msg = xmlStrcat(msg, BAD_CAST "."); /* * Note that is does not make sense to report that we have a * wildcard here, since the wildcard might be unfolded into * multiple transitions. */ if (nbval + nbneg > 0) { if (nbval + nbneg > 1) { str = xmlStrdup(BAD_CAST " Expected is one of ( "); } else str = xmlStrdup(BAD_CAST " Expected is ( "); nsName = NULL; for (i = 0; i < nbval + nbneg; i++) { cur = values[i]; if (cur == NULL) continue; if ((cur[0] == 'n') && (cur[1] == 'o') && (cur[2] == 't') && (cur[3] == ' ')) { cur += 4; str = xmlStrcat(str, BAD_CAST "##other"); } /* * Get the local name. */ localName = NULL; end = cur; if (*end == '*') { localName = xmlStrdup(BAD_CAST "*"); end++; } else { while ((*end != 0) && (*end != '|')) end++; localName = xmlStrncat(localName, BAD_CAST cur, end - cur); } if (*end != 0) { end++; /* * Skip "*|*" if they come with negated expressions, since * they represent the same negated wildcard. */ if ((nbneg == 0) || (*end != '*') || (*localName != '*')) { /* * Get the namespace name. */ cur = end; if (*end == '*') { nsName = xmlStrdup(BAD_CAST "{*}"); } else { while (*end != 0) end++; if (i >= nbval) nsName = xmlStrdup(BAD_CAST "{##other:"); else nsName = xmlStrdup(BAD_CAST "{"); nsName = xmlStrncat(nsName, BAD_CAST cur, end - cur); nsName = xmlStrcat(nsName, BAD_CAST "}"); } str = xmlStrcat(str, BAD_CAST nsName); FREE_AND_NULL(nsName) } else { FREE_AND_NULL(localName); continue; } } str = xmlStrcat(str, BAD_CAST localName); FREE_AND_NULL(localName); if (i < nbval + nbneg -1) str = xmlStrcat(str, BAD_CAST ", "); } str = xmlStrcat(str, BAD_CAST " ).\n"); msg = xmlStrcat(msg, BAD_CAST str); FREE_AND_NULL(str) } else msg = xmlStrcat(msg, BAD_CAST "\n"); xmlSchemaErr(actxt, error, node, (const char *) msg, NULL, NULL); xmlFree(msg); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'More format string warnings with possible format string vulnerability For https://bugzilla.gnome.org/show_bug.cgi?id=761029 adds a new xmlEscapeFormatString() function to escape composed format strings'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlSchemaPSimpleTypeErr(xmlSchemaParserCtxtPtr ctxt, xmlParserErrors error, xmlSchemaBasicItemPtr ownerItem ATTRIBUTE_UNUSED, xmlNodePtr node, xmlSchemaTypePtr type, const char *expected, const xmlChar *value, const char *message, const xmlChar *str1, const xmlChar *str2) { xmlChar *msg = NULL; xmlSchemaFormatNodeForError(&msg, ACTXT_CAST ctxt, node); if (message == NULL) { /* * Use default messages. */ if (type != NULL) { if (node->type == XML_ATTRIBUTE_NODE) msg = xmlStrcat(msg, BAD_CAST "'%s' is not a valid value of "); else msg = xmlStrcat(msg, BAD_CAST "The character content is not a " "valid value of "); if (! xmlSchemaIsGlobalItem(type)) msg = xmlStrcat(msg, BAD_CAST "the local "); else msg = xmlStrcat(msg, BAD_CAST "the "); if (WXS_IS_ATOMIC(type)) msg = xmlStrcat(msg, BAD_CAST "atomic type"); else if (WXS_IS_LIST(type)) msg = xmlStrcat(msg, BAD_CAST "list type"); else if (WXS_IS_UNION(type)) msg = xmlStrcat(msg, BAD_CAST "union type"); if (xmlSchemaIsGlobalItem(type)) { xmlChar *str = NULL; msg = xmlStrcat(msg, BAD_CAST " '"); if (type->builtInType != 0) { msg = xmlStrcat(msg, BAD_CAST "xs:"); msg = xmlStrcat(msg, type->name); } else msg = xmlStrcat(msg, xmlSchemaFormatQName(&str, type->targetNamespace, type->name)); msg = xmlStrcat(msg, BAD_CAST "'."); FREE_AND_NULL(str); } } else { if (node->type == XML_ATTRIBUTE_NODE) msg = xmlStrcat(msg, BAD_CAST "The value '%s' is not valid."); else msg = xmlStrcat(msg, BAD_CAST "The character content is not " "valid."); } if (expected) { msg = xmlStrcat(msg, BAD_CAST " Expected is '"); msg = xmlStrcat(msg, BAD_CAST expected); msg = xmlStrcat(msg, BAD_CAST "'.\n"); } else msg = xmlStrcat(msg, BAD_CAST "\n"); if (node->type == XML_ATTRIBUTE_NODE) xmlSchemaPErr(ctxt, node, error, (const char *) msg, value, NULL); else xmlSchemaPErr(ctxt, node, error, (const char *) msg, NULL, NULL); } else { msg = xmlStrcat(msg, BAD_CAST message); msg = xmlStrcat(msg, BAD_CAST ".\n"); xmlSchemaPErrExt(ctxt, node, error, NULL, NULL, NULL, (const char*) msg, str1, str2, NULL, NULL, NULL); } /* Cleanup. */ FREE_AND_NULL(msg) } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'More format string warnings with possible format string vulnerability For https://bugzilla.gnome.org/show_bug.cgi?id=761029 adds a new xmlEscapeFormatString() function to escape composed format strings'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len, int what, xmlChar end, xmlChar end2, xmlChar end3) { xmlChar *buffer = NULL; size_t buffer_size = 0; size_t nbchars = 0; xmlChar *current = NULL; xmlChar *rep = NULL; const xmlChar *last; xmlEntityPtr ent; int c,l; if ((ctxt == NULL) || (str == NULL) || (len < 0)) return(NULL); last = str + len; if (((ctxt->depth > 40) && ((ctxt->options & XML_PARSE_HUGE) == 0)) || (ctxt->depth > 1024)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); return(NULL); } /* * allocate a translation buffer. */ buffer_size = XML_PARSER_BIG_BUFFER_SIZE; buffer = (xmlChar *) xmlMallocAtomic(buffer_size); if (buffer == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. * we are operating on already parsed values. */ if (str < last) c = CUR_SCHAR(str, l); else c = 0; while ((c != 0) && (c != end) && /* non input consuming loop */ (c != end2) && (c != end3)) { if (c == 0) break; if ((c == '&') && (str[1] == '#')) { int val = xmlParseStringCharRef(ctxt, &str); if (val != 0) { COPY_BUF(0,buffer,nbchars,val); } if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding Entity Reference: %.30s\n", str); ent = xmlParseStringEntityRef(ctxt, &str); if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) goto int_error; xmlParserEntityCheck(ctxt, 0, ent, 0); if (ent != NULL) ctxt->nbentities += ent->checked / 2; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (ent->content != NULL) { COPY_BUF(0,buffer,nbchars,ent->content[0]); if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else { xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, "predefined entity has no content\n"); } } else if ((ent != NULL) && (ent->content != NULL)) { ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) goto int_error; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { if (xmlParserEntityCheck(ctxt, nbchars, ent, 0)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; buffer[nbchars++] = '&'; if (nbchars + i + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, i + XML_PARSER_BUFFER_SIZE); } for (;i > 0;i--) buffer[nbchars++] = *cur++; buffer[nbchars++] = ';'; } } else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding PE Reference: %.30s\n", str); ent = xmlParseStringPEReference(ctxt, &str); if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP) goto int_error; xmlParserEntityCheck(ctxt, 0, ent, 0); if (ent != NULL) ctxt->nbentities += ent->checked / 2; if (ent != NULL) { if (ent->content == NULL) { xmlLoadEntityContent(ctxt, ent); } ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { if (xmlParserEntityCheck(ctxt, nbchars, ent, 0)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } } else { COPY_BUF(l,buffer,nbchars,c); str += l; if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } if (str < last) c = CUR_SCHAR(str, l); else c = 0; } buffer[nbchars] = 0; return(buffer); mem_error: xmlErrMemory(ctxt, NULL); int_error: if (rep != NULL) xmlFree(rep); if (buffer != NULL) xmlFree(buffer); return(NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix inappropriate fetch of entities content For https://bugzilla.gnome.org/show_bug.cgi?id=761430 libfuzzer regression testing exposed another case where the parser would fetch content of an external entity while not in validating mode. Plug that hole'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: htmlParseName(htmlParserCtxtPtr ctxt) { const xmlChar *in; const xmlChar *ret; int count = 0; GROW; /* * Accelerator for simple ASCII names */ in = ctxt->input->cur; if (((*in >= 0x61) && (*in <= 0x7A)) || ((*in >= 0x41) && (*in <= 0x5A)) || (*in == '_') || (*in == ':')) { in++; while (((*in >= 0x61) && (*in <= 0x7A)) || ((*in >= 0x41) && (*in <= 0x5A)) || ((*in >= 0x30) && (*in <= 0x39)) || (*in == '_') || (*in == '-') || (*in == ':') || (*in == '.')) in++; if ((*in > 0) && (*in < 0x80)) { count = in - ctxt->input->cur; ret = xmlDictLookup(ctxt->dict, ctxt->input->cur, count); ctxt->input->cur = in; ctxt->nbChars += count; ctxt->input->col += count; return(ret); } } return(htmlParseNameComplex(ctxt)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Bug 758605: Heap-based buffer overread in xmlDictAddString <https://bugzilla.gnome.org/show_bug.cgi?id=758605> Reviewed by David Kilzer. * HTMLparser.c: (htmlParseName): Add bounds check. (htmlParseNameComplex): Ditto. * result/HTML/758605.html: Added. * result/HTML/758605.html.err: Added. * result/HTML/758605.html.sax: Added. * runtest.c: (pushParseTest): The input for the new test case was so small (4 bytes) that htmlParseChunk() was never called after htmlCreatePushParserCtxt(), thereby creating a false positive test failure. Fixed by using a do-while loop so we always call htmlParseChunk() at least once. * test/HTML/758605.html: Added.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pushParseTest(const char *filename, const char *result, const char *err ATTRIBUTE_UNUSED, int options) { xmlParserCtxtPtr ctxt; xmlDocPtr doc; const char *base; int size, res; int cur = 0; nb_tests++; /* * load the document in memory and work from there. */ if (loadMem(filename, &base, &size) != 0) { fprintf(stderr, "Failed to load %s\n", filename); return(-1); } #ifdef LIBXML_HTML_ENABLED if (options & XML_PARSE_HTML) ctxt = htmlCreatePushParserCtxt(NULL, NULL, base + cur, 4, filename, XML_CHAR_ENCODING_NONE); else #endif ctxt = xmlCreatePushParserCtxt(NULL, NULL, base + cur, 4, filename); xmlCtxtUseOptions(ctxt, options); cur += 4; while (cur < size) { if (cur + 1024 >= size) { #ifdef LIBXML_HTML_ENABLED if (options & XML_PARSE_HTML) htmlParseChunk(ctxt, base + cur, size - cur, 1); else #endif xmlParseChunk(ctxt, base + cur, size - cur, 1); break; } else { #ifdef LIBXML_HTML_ENABLED if (options & XML_PARSE_HTML) htmlParseChunk(ctxt, base + cur, 1024, 0); else #endif xmlParseChunk(ctxt, base + cur, 1024, 0); cur += 1024; } } doc = ctxt->myDoc; #ifdef LIBXML_HTML_ENABLED if (options & XML_PARSE_HTML) res = 1; else #endif res = ctxt->wellFormed; xmlFreeParserCtxt(ctxt); free((char *)base); if (!res) { xmlFreeDoc(doc); fprintf(stderr, "Failed to parse %s\n", filename); return(-1); } #ifdef LIBXML_HTML_ENABLED if (options & XML_PARSE_HTML) htmlDocDumpMemory(doc, (xmlChar **) &base, &size); else #endif xmlDocDumpMemory(doc, (xmlChar **) &base, &size); xmlFreeDoc(doc); res = compareFileMem(result, base, size); if ((base == NULL) || (res != 0)) { if (base != NULL) xmlFree((char *)base); fprintf(stderr, "Result for %s failed in %s\n", filename, result); return(-1); } xmlFree((char *)base); if (err != NULL) { res = compareFileMem(err, testErrors, testErrorsSize); if (res != 0) { fprintf(stderr, "Error for %s failed\n", filename); return(-1); } } return(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Bug 758605: Heap-based buffer overread in xmlDictAddString <https://bugzilla.gnome.org/show_bug.cgi?id=758605> Reviewed by David Kilzer. * HTMLparser.c: (htmlParseName): Add bounds check. (htmlParseNameComplex): Ditto. * result/HTML/758605.html: Added. * result/HTML/758605.html.err: Added. * result/HTML/758605.html.sax: Added. * runtest.c: (pushParseTest): The input for the new test case was so small (4 bytes) that htmlParseChunk() was never called after htmlCreatePushParserCtxt(), thereby creating a false positive test failure. Fixed by using a do-while loop so we always call htmlParseChunk() at least once. * test/HTML/758605.html: Added.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlFAParseCharRange(xmlRegParserCtxtPtr ctxt) { int cur, len; int start = -1; int end = -1; if (CUR == '\0') { ERROR("Expecting ']'"); return; } cur = CUR; if (cur == '\\') { NEXT; cur = CUR; switch (cur) { case 'n': start = 0xA; break; case 'r': start = 0xD; break; case 't': start = 0x9; break; case '\\': case '|': case '.': case '-': case '^': case '?': case '*': case '+': case '{': case '}': case '(': case ')': case '[': case ']': start = cur; break; default: ERROR("Invalid escape value"); return; } end = start; len = 1; } else if ((cur != 0x5B) && (cur != 0x5D)) { end = start = CUR_SCHAR(ctxt->cur, len); } else { ERROR("Expecting a char range"); return; } /* * Since we are "inside" a range, we can assume ctxt->cur is past * the start of ctxt->string, and PREV should be safe */ if ((start == '-') && (NXT(1) != ']') && (PREV != '[') && (PREV != '^')) { NEXTL(len); return; } NEXTL(len); cur = CUR; if ((cur != '-') || (NXT(1) == ']')) { xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg, XML_REGEXP_CHARVAL, start, end, NULL); return; } NEXT; cur = CUR; if (cur == '\\') { NEXT; cur = CUR; switch (cur) { case 'n': end = 0xA; break; case 'r': end = 0xD; break; case 't': end = 0x9; break; case '\\': case '|': case '.': case '-': case '^': case '?': case '*': case '+': case '{': case '}': case '(': case ')': case '[': case ']': end = cur; break; default: ERROR("Invalid escape value"); return; } len = 1; } else if ((cur != 0x5B) && (cur != 0x5D)) { end = CUR_SCHAR(ctxt->cur, len); } else { ERROR("Expecting the end of a char range"); return; } NEXTL(len); /* TODO check that the values are acceptable character ranges for XML */ if (end < start) { ERROR("End of range is before start of range"); } else { xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg, XML_REGEXP_CHARVAL, start, end, NULL); } return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Bug 757711: heap-buffer-overflow in xmlFAParsePosCharGroup <https://bugzilla.gnome.org/show_bug.cgi?id=757711> * xmlregexp.c: (xmlFAParseCharRange): Only advance to the next character if there is no error. Advancing to the next character in case of an error while parsing regexp leads to an out of bounds access.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlStrncat(xmlChar *cur, const xmlChar *add, int len) { int size; xmlChar *ret; if ((add == NULL) || (len == 0)) return(cur); if (len < 0) return(NULL); if (cur == NULL) return(xmlStrndup(add, len)); size = xmlStrlen(cur); ret = (xmlChar *) xmlRealloc(cur, (size + len + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlErrMemory(NULL, NULL); return(cur); } memcpy(&ret[size], add, len * sizeof(xmlChar)); ret[size + len] = 0; return(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Bug 763071: heap-buffer-overflow in xmlStrncat <https://bugzilla.gnome.org/show_bug.cgi?id=763071> * xmlstring.c: (xmlStrncat): Return NULL if xmlStrlen returns a negative length. (xmlStrncatNew): Ditto.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int x25_negotiate_facilities(struct sk_buff *skb, struct sock *sk, struct x25_facilities *new, struct x25_dte_facilities *dte) { struct x25_sock *x25 = x25_sk(sk); struct x25_facilities *ours = &x25->facilities; struct x25_facilities theirs; int len; memset(&theirs, 0, sizeof(theirs)); memcpy(new, ours, sizeof(*new)); len = x25_parse_facilities(skb, &theirs, dte, &x25->vc_facil_mask); if (len < 0) return len; /* * They want reverse charging, we won't accept it. */ if ((theirs.reverse & 0x01 ) && (ours->reverse & 0x01)) { SOCK_DEBUG(sk, "X.25: rejecting reverse charging request\n"); return -1; } new->reverse = theirs.reverse; if (theirs.throughput) { int theirs_in = theirs.throughput & 0x0f; int theirs_out = theirs.throughput & 0xf0; int ours_in = ours->throughput & 0x0f; int ours_out = ours->throughput & 0xf0; if (!ours_in || theirs_in < ours_in) { SOCK_DEBUG(sk, "X.25: inbound throughput negotiated\n"); new->throughput = (new->throughput & 0xf0) | theirs_in; } if (!ours_out || theirs_out < ours_out) { SOCK_DEBUG(sk, "X.25: outbound throughput negotiated\n"); new->throughput = (new->throughput & 0x0f) | theirs_out; } } if (theirs.pacsize_in && theirs.pacsize_out) { if (theirs.pacsize_in < ours->pacsize_in) { SOCK_DEBUG(sk, "X.25: packet size inwards negotiated down\n"); new->pacsize_in = theirs.pacsize_in; } if (theirs.pacsize_out < ours->pacsize_out) { SOCK_DEBUG(sk, "X.25: packet size outwards negotiated down\n"); new->pacsize_out = theirs.pacsize_out; } } if (theirs.winsize_in && theirs.winsize_out) { if (theirs.winsize_in < ours->winsize_in) { SOCK_DEBUG(sk, "X.25: window size inwards negotiated down\n"); new->winsize_in = theirs.winsize_in; } if (theirs.winsize_out < ours->winsize_out) { SOCK_DEBUG(sk, "X.25: window size outwards negotiated down\n"); new->winsize_out = theirs.winsize_out; } } return len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'net: fix a kernel infoleak in x25 module Stack object "dte_facilities" is allocated in x25_rx_call_request(), which is supposed to be initialized in x25_negotiate_facilities. However, 5 fields (8 bytes in total) are not initialized. This object is then copied to userland via copy_to_user, thus infoleak occurs. Signed-off-by: Kangjie Lu <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gdImageScaleTwoPass(const gdImagePtr src, const unsigned int new_width, const unsigned int new_height) { const unsigned int src_width = src->sx; const unsigned int src_height = src->sy; gdImagePtr tmp_im = NULL; gdImagePtr dst = NULL; /* First, handle the trivial case. */ if (src_width == new_width && src_height == new_height) { return gdImageClone(src); }/* if */ /* Convert to truecolor if it isn't; this code requires it. */ if (!src->trueColor) { gdImagePaletteToTrueColor(src); }/* if */ /* Scale horizontally unless sizes are the same. */ if (src_width == new_width) { tmp_im = src; } else { tmp_im = gdImageCreateTrueColor(new_width, src_height); if (tmp_im == NULL) { return NULL; } gdImageSetInterpolationMethod(tmp_im, src->interpolation_id); _gdScalePass(src, src_width, tmp_im, new_width, src_height, HORIZONTAL); }/* if .. else*/ /* If vertical sizes match, we're done. */ if (src_height == new_height) { assert(tmp_im != src); return tmp_im; }/* if */ /* Otherwise, we need to scale vertically. */ dst = gdImageCreateTrueColor(new_width, new_height); if (dst != NULL) { gdImageSetInterpolationMethod(dst, src->interpolation_id); _gdScalePass(tmp_im, src_height, dst, new_height, new_width, VERTICAL); }/* if */ if (src != tmp_im) { gdFree(tmp_im); }/* if */ return dst; }/* gdImageScaleTwoPass*/ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'gdImageScaleTwoPass memory leak fix Fixing memory leak in gdImageScaleTwoPass, as reported by @cmb69 and confirmed by @vapier. This bug actually bit me in production and I'm very thankful that it was reported with an easy fix. Fixes #173.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int odbc_bindcols(odbc_result *result TSRMLS_DC) { RETCODE rc; int i; SQLSMALLINT colnamelen; /* Not used */ SQLLEN displaysize; SQLUSMALLINT colfieldid; int charextraalloc; result->values = (odbc_result_value *) safe_emalloc(sizeof(odbc_result_value), result->numcols, 0); result->longreadlen = ODBCG(defaultlrl); result->binmode = ODBCG(defaultbinmode); for(i = 0; i < result->numcols; i++) { charextraalloc = 0; colfieldid = SQL_COLUMN_DISPLAY_SIZE; rc = PHP_ODBC_SQLCOLATTRIBUTE(result->stmt, (SQLUSMALLINT)(i+1), PHP_ODBC_SQL_DESC_NAME, result->values[i].name, sizeof(result->values[i].name), &colnamelen, 0); rc = PHP_ODBC_SQLCOLATTRIBUTE(result->stmt, (SQLUSMALLINT)(i+1), SQL_COLUMN_TYPE, NULL, 0, NULL, &result->values[i].coltype); /* Don't bind LONG / BINARY columns, so that fetch behaviour can * be controlled by odbc_binmode() / odbc_longreadlen() */ switch(result->values[i].coltype) { case SQL_BINARY: case SQL_VARBINARY: case SQL_LONGVARBINARY: case SQL_LONGVARCHAR: #if defined(ODBCVER) && (ODBCVER >= 0x0300) case SQL_WLONGVARCHAR: #endif result->values[i].value = NULL; break; #ifdef HAVE_ADABAS case SQL_TIMESTAMP: result->values[i].value = (char *)emalloc(27); SQLBindCol(result->stmt, (SQLUSMALLINT)(i+1), SQL_C_CHAR, result->values[i].value, 27, &result->values[i].vallen); break; #endif /* HAVE_ADABAS */ case SQL_CHAR: case SQL_VARCHAR: #if defined(ODBCVER) && (ODBCVER >= 0x0300) case SQL_WCHAR: case SQL_WVARCHAR: colfieldid = SQL_DESC_OCTET_LENGTH; #else charextraalloc = 1; #endif default: rc = PHP_ODBC_SQLCOLATTRIBUTE(result->stmt, (SQLUSMALLINT)(i+1), colfieldid, NULL, 0, NULL, &displaysize); #if defined(ODBCVER) && (ODBCVER >= 0x0300) if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO && colfieldid == SQL_DESC_OCTET_LENGTH) { /* This is a quirk for ODBC 2.0 compatibility for broken driver implementations. */ charextraalloc = 1; rc = SQLColAttributes(result->stmt, (SQLUSMALLINT)(i+1), SQL_COLUMN_DISPLAY_SIZE, NULL, 0, NULL, &displaysize); } #endif /* Workaround for drivers that report NVARCHAR(MAX) columns as SQL_WVARCHAR with size 0 (bug #69975) */ if (result->values[i].coltype == SQL_WVARCHAR && displaysize == 0) { result->values[i].coltype = SQL_WLONGVARCHAR; result->values[i].value = NULL; break; } /* Workaround for Oracle ODBC Driver bug (#50162) when fetching TIMESTAMP column */ if (result->values[i].coltype == SQL_TIMESTAMP) { displaysize += 3; } if (charextraalloc) { /* Since we don't know the exact # of bytes, allocate extra */ displaysize *= 4; } result->values[i].value = (char *)emalloc(displaysize + 1); rc = SQLBindCol(result->stmt, (SQLUSMALLINT)(i+1), SQL_C_CHAR, result->values[i].value, displaysize + 1, &result->values[i].vallen); break; } } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'fixed fix #69975 wrt. ODBCVER < 0x0300'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int append_multiple_key_values(smart_str* loc_name, HashTable* hash_arr, char* key_name TSRMLS_DC) { zval** ele_value = NULL; int i = 0; int isFirstSubtag = 0; int max_value = 0; /* Variant/ Extlang/Private etc. */ if( zend_hash_find( hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) { if( Z_TYPE_PP(ele_value) == IS_STRING ){ add_prefix( loc_name , key_name); smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1); smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value)); return SUCCESS; } else if(Z_TYPE_PP(ele_value) == IS_ARRAY ) { HashPosition pos; HashTable *arr = HASH_OF(*ele_value); zval **data = NULL; zend_hash_internal_pointer_reset_ex(arr, &pos); while(zend_hash_get_current_data_ex(arr, (void **)&data, &pos) != FAILURE) { if(Z_TYPE_PP(data) != IS_STRING) { return FAILURE; } if (isFirstSubtag++ == 0){ add_prefix(loc_name , key_name); } smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1); smart_str_appendl(loc_name, Z_STRVAL_PP(data) , Z_STRLEN_PP(data)); zend_hash_move_forward_ex(arr, &pos); } return SUCCESS; } else { return FAILURE; } } else { char cur_key_name[31]; /* Decide the max_value: the max. no. of elements allowed */ if( strcmp(key_name , LOC_VARIANT_TAG) ==0 ){ max_value = MAX_NO_VARIANT; } if( strcmp(key_name , LOC_EXTLANG_TAG) ==0 ){ max_value = MAX_NO_EXTLANG; } if( strcmp(key_name , LOC_PRIVATE_TAG) ==0 ){ max_value = MAX_NO_PRIVATE; } /* Multiple variant values as variant0, variant1 ,variant2 */ isFirstSubtag = 0; for( i=0 ; i< max_value; i++ ){ snprintf( cur_key_name , 30, "%s%d", key_name , i); if( zend_hash_find( hash_arr , cur_key_name , strlen(cur_key_name) + 1,(void **)&ele_value ) == SUCCESS ){ if( Z_TYPE_PP(ele_value)!= IS_STRING ){ /* variant is not a string */ return FAILURE; } /* Add the contents */ if (isFirstSubtag++ == 0){ add_prefix(loc_name , cur_key_name); } smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1); smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value)); } } /* end of for */ } /* end of else */ return SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int getStrrtokenPos(char* str, int savedPos) { int result =-1; int i; for(i=savedPos-1; i>=0; i--) { if(isIDSeparator(*(str+i)) ){ /* delimiter found; check for singleton */ if(i>=2 && isIDSeparator(*(str+i-2)) ){ /* a singleton; so send the position of token before the singleton */ result = i-2; } else { result = i; } break; } } if(result < 1){ /* Just in case inavlid locale e.g. '-x-xyz' or '-sl_Latn' */ result =-1; } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int add_array_entry(const char* loc_name, zval* hash_arr, char* key_name TSRMLS_DC) { char* key_value = NULL; char* cur_key_name = NULL; char* token = NULL; char* last_ptr = NULL; int result = 0; int cur_result = 0; int cnt = 0; if( strcmp(key_name , LOC_PRIVATE_TAG)==0 ){ key_value = get_private_subtags( loc_name ); result = 1; } else { key_value = get_icu_value_internal( loc_name , key_name , &result,1 ); } if( (strcmp(key_name , LOC_PRIVATE_TAG)==0) || ( strcmp(key_name , LOC_VARIANT_TAG)==0) ){ if( result > 0 && key_value){ /* Tokenize on the "_" or "-" */ token = php_strtok_r( key_value , DELIMITER ,&last_ptr); if( cur_key_name ){ efree( cur_key_name); } cur_key_name = (char*)ecalloc( 25, 25); sprintf( cur_key_name , "%s%d", key_name , cnt++); add_assoc_string( hash_arr, cur_key_name , token ,TRUE ); /* tokenize on the "_" or "-" and stop at singleton if any */ while( (token = php_strtok_r(NULL , DELIMITER , &last_ptr)) && (strlen(token)>1) ){ sprintf( cur_key_name , "%s%d", key_name , cnt++); add_assoc_string( hash_arr, cur_key_name , token , TRUE ); } /* if( strcmp(key_name, LOC_PRIVATE_TAG) == 0 ){ } */ } } else { if( result == 1 ){ add_assoc_string( hash_arr, key_name , key_value , TRUE ); cur_result = 1; } } if( cur_key_name ){ efree( cur_key_name); } /*if( key_name != LOC_PRIVATE_TAG && key_value){*/ if( key_value){ efree(key_value); } return cur_result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION( locale_get_region ) { get_icu_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(locale_lookup) { char* fallback_loc = NULL; int fallback_loc_len = 0; const char* loc_range = NULL; int loc_range_len = 0; zval* arr = NULL; HashTable* hash_arr = NULL; zend_bool boolCanonical = 0; char* result =NULL; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "as|bs", &arr, &loc_range, &loc_range_len, &boolCanonical, &fallback_loc, &fallback_loc_len) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_lookup: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_range_len == 0) { loc_range = intl_locale_get_default(TSRMLS_C); } hash_arr = HASH_OF(arr); if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 ) { RETURN_EMPTY_STRING(); } result = lookup_loc_range(loc_range, hash_arr, boolCanonical TSRMLS_CC); if(result == NULL || result[0] == '\0') { if( fallback_loc ) { result = estrndup(fallback_loc, fallback_loc_len); } else { RETURN_EMPTY_STRING(); } } RETVAL_STRINGL(result, strlen(result), 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(locale_get_all_variants) { const char* loc_name = NULL; int loc_name_len = 0; int result = 0; char* token = NULL; char* variant = NULL; char* saved_ptr = NULL; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &loc_name, &loc_name_len ) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_parse: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } array_init( return_value ); /* If the locale is grandfathered, stop, no variants */ if( findOffset( LOC_GRANDFATHERED , loc_name ) >= 0 ){ /* ("Grandfathered Tag. No variants."); */ } else { /* Call ICU variant */ variant = get_icu_value_internal( loc_name , LOC_VARIANT_TAG , &result ,0); if( result > 0 && variant){ /* Tokenize on the "_" or "-" */ token = php_strtok_r( variant , DELIMITER , &saved_ptr); add_next_index_stringl( return_value, token , strlen(token) ,TRUE ); /* tokenize on the "_" or "-" and stop at singleton if any */ while( (token = php_strtok_r(NULL , DELIMITER, &saved_ptr)) && (strlen(token)>1) ){ add_next_index_stringl( return_value, token , strlen(token) ,TRUE ); } } if( variant ){ efree( variant ); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static char* get_private_subtags(const char* loc_name) { char* result =NULL; int singletonPos = 0; int len =0; const char* mod_loc_name =NULL; if( loc_name && (len = strlen(loc_name)>0 ) ){ mod_loc_name = loc_name ; len = strlen(mod_loc_name); while( (singletonPos = getSingletonPos(mod_loc_name))!= -1){ if( singletonPos!=-1){ if( (*(mod_loc_name+singletonPos)=='x') || (*(mod_loc_name+singletonPos)=='X') ){ /* private subtag start found */ if( singletonPos + 2 == len){ /* loc_name ends with '-x-' ; return NULL */ } else{ /* result = mod_loc_name + singletonPos +2; */ result = estrndup(mod_loc_name + singletonPos+2 , (len -( singletonPos +2) ) ); } break; } else{ if( singletonPos + 1 >= len){ /* String end */ break; } else { /* singleton found but not a private subtag , hence check further in the string for the private subtag */ mod_loc_name = mod_loc_name + singletonPos +1; len = strlen(mod_loc_name); } } } } /* end of while */ } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int append_key_value(smart_str* loc_name, HashTable* hash_arr, char* key_name) { zval** ele_value = NULL; if(zend_hash_find(hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) { if(Z_TYPE_PP(ele_value)!= IS_STRING ){ /* element value is not a string */ return FAILURE; } if(strcmp(key_name, LOC_LANG_TAG) != 0 && strcmp(key_name, LOC_GRANDFATHERED_LANG_TAG)!=0 ) { /* not lang or grandfathered tag */ smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1); } smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value)); return SUCCESS; } return LOC_NOT_FOUND; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION( locale_get_keywords ) { UEnumeration* e = NULL; UErrorCode status = U_ZERO_ERROR; const char* kw_key = NULL; int32_t kw_key_len = 0; const char* loc_name = NULL; int loc_name_len = 0; /* ICU expects the buffer to be allocated before calling the function and so the buffer size has been explicitly specified ICU uloc.h #define ULOC_KEYWORD_AND_VALUES_CAPACITY 100 hence the kw_value buffer size is 100 */ char* kw_value = NULL; int32_t kw_value_len = 100; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &loc_name, &loc_name_len ) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_get_keywords: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } /* Get the keywords */ e = uloc_openKeywords( loc_name, &status ); if( e != NULL ) { /* Traverse it, filling the return array. */ array_init( return_value ); while( ( kw_key = uenum_next( e, &kw_key_len, &status ) ) != NULL ){ kw_value = ecalloc( 1 , kw_value_len ); /* Get the keyword value for each keyword */ kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len , &status ); if (status == U_BUFFER_OVERFLOW_ERROR) { status = U_ZERO_ERROR; kw_value = erealloc( kw_value , kw_value_len+1); kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len+1 , &status ); } else if(!U_FAILURE(status)) { kw_value = erealloc( kw_value , kw_value_len+1); } if (U_FAILURE(status)) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_get_keywords: Error encountered while getting the keyword value for the keyword", 0 TSRMLS_CC ); if( kw_value){ efree( kw_value ); } zval_dtor(return_value); RETURN_FALSE; } add_assoc_stringl( return_value, (char *)kw_key, kw_value , kw_value_len, 0); } /* end of while */ } /* end of if e!=NULL */ uenum_close( e ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(locale_get_primary_language ) { get_icu_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int getSingletonPos(const char* str) { int result =-1; int i=0; int len = 0; if( str && ((len=strlen(str))>0) ){ for( i=0; i<len ; i++){ if( isIDSeparator(*(str+i)) ){ if( i==1){ /* string is of the form x-avy or a-prv1 */ result =0; break; } else { /* delimiter found; check for singleton */ if( isIDSeparator(*(str+i+2)) ){ /* a singleton; so send the position of separator before singleton */ result = i+1; break; } } } }/* end of for */ } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(locale_compose) { smart_str loc_name_s = {0}; smart_str *loc_name = &loc_name_s; zval* arr = NULL; HashTable* hash_arr = NULL; int result = 0; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "a", &arr) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_compose: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } hash_arr = HASH_OF( arr ); if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 ) RETURN_FALSE; /* Check for grandfathered first */ result = append_key_value(loc_name, hash_arr, LOC_GRANDFATHERED_LANG_TAG); if( result == SUCCESS){ RETURN_SMART_STR(loc_name); } if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Not grandfathered */ result = append_key_value(loc_name, hash_arr , LOC_LANG_TAG); if( result == LOC_NOT_FOUND ){ intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_compose: parameter array does not contain 'language' tag.", 0 TSRMLS_CC ); smart_str_free(loc_name); RETURN_FALSE; } if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Extlang */ result = append_multiple_key_values(loc_name, hash_arr , LOC_EXTLANG_TAG TSRMLS_CC); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Script */ result = append_key_value(loc_name, hash_arr , LOC_SCRIPT_TAG); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Region */ result = append_key_value( loc_name, hash_arr , LOC_REGION_TAG); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Variant */ result = append_multiple_key_values( loc_name, hash_arr , LOC_VARIANT_TAG TSRMLS_CC); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Private */ result = append_multiple_key_values( loc_name, hash_arr , LOC_PRIVATE_TAG TSRMLS_CC); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } RETURN_SMART_STR(loc_name); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(locale_get_display_language) { get_icu_disp_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHPAPI PHP_FUNCTION(fread) { zval *arg1; long len; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &arg1, &len) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); if (len <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(len + 1); Z_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72114 - int/size_t confusion in fread'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int socket_create(uint16_t port) { int sfd = -1; int yes = 1; #ifdef WIN32 WSADATA wsa_data; if (!wsa_init) { if (WSAStartup(MAKEWORD(2,2), &wsa_data) != ERROR_SUCCESS) { fprintf(stderr, "WSAStartup failed!\n"); ExitProcess(-1); } wsa_init = 1; } #endif struct sockaddr_in saddr; if (0 > (sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))) { perror("socket()"); return -1; } if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) { perror("setsockopt()"); socket_close(sfd); return -1; } #ifdef SO_NOSIGPIPE if (setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) { perror("setsockopt()"); socket_close(sfd); return -1; } #endif memset((void *) &saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = htonl(INADDR_ANY); saddr.sin_port = htons(port); if (0 > bind(sfd, (struct sockaddr *) &saddr, sizeof(saddr))) { perror("bind()"); socket_close(sfd); return -1; } if (listen(sfd, 1) == -1) { perror("listen()"); socket_close(sfd); return -1; } return sfd; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-703'], 'message': 'common: [security fix] Make sure sockets only listen locally'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xsltNumberFormatGetAnyLevel(xsltTransformContextPtr context, xmlNodePtr node, xsltCompMatchPtr countPat, xsltCompMatchPtr fromPat, double *array) { int amount = 0; int cnt = 0; xmlNodePtr cur; /* select the starting node */ switch (node->type) { case XML_ELEMENT_NODE: cur = node; break; case XML_ATTRIBUTE_NODE: cur = ((xmlAttrPtr) node)->parent; break; case XML_TEXT_NODE: case XML_PI_NODE: case XML_COMMENT_NODE: cur = node->parent; break; default: cur = NULL; break; } while (cur != NULL) { /* process current node */ if (countPat == NULL) { if ((node->type == cur->type) && /* FIXME: must use expanded-name instead of local name */ xmlStrEqual(node->name, cur->name)) { if ((node->ns == cur->ns) || ((node->ns != NULL) && (cur->ns != NULL) && (xmlStrEqual(node->ns->href, cur->ns->href) ))) cnt++; } } else { if (xsltTestCompMatchList(context, cur, countPat)) cnt++; } if ((fromPat != NULL) && xsltTestCompMatchList(context, cur, fromPat)) { break; /* while */ } /* Skip to next preceding or ancestor */ if ((cur->type == XML_DOCUMENT_NODE) || #ifdef LIBXML_DOCB_ENABLED (cur->type == XML_DOCB_DOCUMENT_NODE) || #endif (cur->type == XML_HTML_DOCUMENT_NODE)) break; /* while */ while ((cur->prev != NULL) && ((cur->prev->type == XML_DTD_NODE) || (cur->prev->type == XML_XINCLUDE_START) || (cur->prev->type == XML_XINCLUDE_END))) cur = cur->prev; if (cur->prev != NULL) { for (cur = cur->prev; cur->last != NULL; cur = cur->last); } else { cur = cur->parent; } } array[amount++] = (double) cnt; return(amount); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix xsltNumberFormatGetMultipleLevel Namespace nodes are actually an xmlNs, not an xmlNode. They must be special-cased in xsltNumberFormatGetMultipleLevel to avoid an out-of-bounds heap access. Move the test whether a node matches the "count" pattern to a separate function to make the code more readable. As a side effect, we also compare expanded names when walking up the ancestor axis, fixing an insignificant bug.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter) { double width_d; double scale_f_d = 1.0; const double filter_width_d = DEFAULT_BOX_RADIUS; int windows_size; unsigned int u; LineContribType *res; if (scale_d < 1.0) { width_d = filter_width_d / scale_d; scale_f_d = scale_d; } else { width_d= filter_width_d; } windows_size = 2 * (int)ceil(width_d) + 1; res = _gdContributionsAlloc(line_size, windows_size); for (u = 0; u < line_size; u++) { const double dCenter = (double)u / scale_d; /* get the significant edge points affecting the pixel */ register int iLeft = MAX(0, (int)floor (dCenter - width_d)); int iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1); double dTotalWeight = 0.0; int iSrc; res->ContribRow[u].Left = iLeft; res->ContribRow[u].Right = iRight; /* Cut edge points to fit in filter window in case of spill-off */ if (iRight - iLeft + 1 > windows_size) { if (iLeft < ((int)src_size - 1 / 2)) { iLeft++; } else { iRight--; } } for (iSrc = iLeft; iSrc <= iRight; iSrc++) { dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc))); } if (dTotalWeight < 0.0) { _gdContributionsFree(res); return NULL; } if (dTotalWeight > 0.0) { for (iSrc = iLeft; iSrc <= iRight; iSrc++) { res->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight; } } } return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed memory overrun bug in gdImageScaleTwoPass _gdContributionsCalc would compute a window size and then adjust the left and right positions of the window to make a window within that size. However, it was storing the values in the struct *before* it made the adjustment. This change fixes that.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline int _setEdgePixel(const gdImagePtr src, unsigned int x, unsigned int y, gdFixed coverage, const int bgColor) { const gdFixed f_127 = gd_itofx(127); register int c = src->tpixels[y][x]; c = c | (( (int) (gd_fxtof(gd_mulfx(coverage, f_127)) + 50.5f)) << 24); return _color_blend(bgColor, c); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed bug #72227: imagescale out-of-bounds read Ported from https://github.com/libgd/libgd/commit/4f65a3e4eedaffa1efcf9ee1eb08f0b504fbc31a'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter) { double width_d; double scale_f_d = 1.0; const double filter_width_d = DEFAULT_BOX_RADIUS; int windows_size; unsigned int u; LineContribType *res; if (scale_d < 1.0) { width_d = filter_width_d / scale_d; scale_f_d = scale_d; } else { width_d= filter_width_d; } windows_size = 2 * (int)ceil(width_d) + 1; res = _gdContributionsAlloc(line_size, windows_size); for (u = 0; u < line_size; u++) { const double dCenter = (double)u / scale_d; /* get the significant edge points affecting the pixel */ register int iLeft = MAX(0, (int)floor (dCenter - width_d)); int iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1); double dTotalWeight = 0.0; int iSrc; res->ContribRow[u].Left = iLeft; res->ContribRow[u].Right = iRight; /* Cut edge points to fit in filter window in case of spill-off */ if (iRight - iLeft + 1 > windows_size) { if (iLeft < ((int)src_size - 1 / 2)) { iLeft++; } else { iRight--; } } for (iSrc = iLeft; iSrc <= iRight; iSrc++) { dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc))); } if (dTotalWeight < 0.0) { _gdContributionsFree(res); return NULL; } if (dTotalWeight > 0.0) { for (iSrc = iLeft; iSrc <= iRight; iSrc++) { res->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight; } } } return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed bug #72227: imagescale out-of-bounds read Ported from https://github.com/libgd/libgd/commit/4f65a3e4eedaffa1efcf9ee1eb08f0b504fbc31a'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline void find_entity_for_char( unsigned int k, enum entity_charset charset, const entity_stage1_row *table, const unsigned char **entity, size_t *entity_len, unsigned char *old, size_t oldlen, size_t *cursor) { unsigned stage1_idx = ENT_STAGE1_INDEX(k); const entity_stage3_row *c; if (stage1_idx > 0x1D) { *entity = NULL; *entity_len = 0; return; } c = &table[stage1_idx][ENT_STAGE2_INDEX(k)][ENT_STAGE3_INDEX(k)]; if (!c->ambiguous) { *entity = (const unsigned char *)c->data.ent.entity; *entity_len = c->data.ent.entity_len; } else { /* peek at next char */ size_t cursor_before = *cursor; int status = SUCCESS; unsigned next_char; if (!(*cursor < oldlen)) goto no_suitable_2nd; next_char = get_next_char(charset, old, oldlen, cursor, &status); if (status == FAILURE) goto no_suitable_2nd; { const entity_multicodepoint_row *s, *e; s = &c->data.multicodepoint_table[1]; e = s - 1 + c->data.multicodepoint_table[0].leading_entry.size; /* we could do a binary search but it's not worth it since we have * at most two entries... */ for ( ; s <= e; s++) { if (s->normal_entry.second_cp == next_char) { *entity = s->normal_entry.entity; *entity_len = s->normal_entry.entity_len; return; } } } no_suitable_2nd: *cursor = cursor_before; *entity = (const unsigned char *) c->data.multicodepoint_table[0].leading_entry.default_entity; *entity_len = c->data.multicodepoint_table[0].leading_entry.default_entity_len; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72135 - don't create strings with lengths outside int range'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static enum entity_charset determine_charset(char *charset_hint TSRMLS_DC) { int i; enum entity_charset charset = cs_utf_8; int len = 0; const zend_encoding *zenc; /* Default is now UTF-8 */ if (charset_hint == NULL) return cs_utf_8; if ((len = strlen(charset_hint)) != 0) { goto det_charset; } zenc = zend_multibyte_get_internal_encoding(TSRMLS_C); if (zenc != NULL) { charset_hint = (char *)zend_multibyte_get_encoding_name(zenc); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { if ((len == 4) /* sizeof (none|auto|pass) */ && (!memcmp("pass", charset_hint, 4) || !memcmp("auto", charset_hint, 4) || !memcmp("auto", charset_hint, 4))) { charset_hint = NULL; len = 0; } else { goto det_charset; } } } charset_hint = SG(default_charset); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { goto det_charset; } /* try to detect the charset for the locale */ #if HAVE_NL_LANGINFO && HAVE_LOCALE_H && defined(CODESET) charset_hint = nl_langinfo(CODESET); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { goto det_charset; } #endif #if HAVE_LOCALE_H /* try to figure out the charset from the locale */ { char *localename; char *dot, *at; /* lang[_territory][.codeset][@modifier] */ localename = setlocale(LC_CTYPE, NULL); dot = strchr(localename, '.'); if (dot) { dot++; /* locale specifies a codeset */ at = strchr(dot, '@'); if (at) len = at - dot; else len = strlen(dot); charset_hint = dot; } else { /* no explicit name; see if the name itself * is the charset */ charset_hint = localename; len = strlen(charset_hint); } } #endif det_charset: if (charset_hint) { int found = 0; /* now walk the charset map and look for the codeset */ for (i = 0; charset_map[i].codeset; i++) { if (len == strlen(charset_map[i].codeset) && strncasecmp(charset_hint, charset_map[i].codeset, len) == 0) { charset = charset_map[i].charset; found = 1; break; } } if (!found) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "charset `%s' not supported, assuming utf-8", charset_hint); } } return charset; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72135 - don't create strings with lengths outside int range'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned code_key_a, size_t num) { const uni_to_enc *l = table, *h = &table[num-1], *m; unsigned short code_key; /* we have no mappings outside the BMP */ if (code_key_a > 0xFFFFU) return 0; code_key = (unsigned short) code_key_a; while (l <= h) { m = l + (h - l) / 2; if (code_key < m->un_code_point) h = m - 1; else if (code_key > m->un_code_point) l = m + 1; else return m->cs_code; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72135 - don't create strings with lengths outside int range'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline int process_numeric_entity(const char **buf, unsigned *code_point) { long code_l; int hexadecimal = (**buf == 'x' || **buf == 'X'); /* TODO: XML apparently disallows "X" */ char *endptr; if (hexadecimal && (**buf != '\0')) (*buf)++; /* strtol allows whitespace and other stuff in the beginning * we're not interested */ if ((hexadecimal && !isxdigit(**buf)) || (!hexadecimal && !isdigit(**buf))) { return FAILURE; } code_l = strtol(*buf, &endptr, hexadecimal ? 16 : 10); /* we're guaranteed there were valid digits, so *endptr > buf */ *buf = endptr; if (**buf != ';') return FAILURE; /* many more are invalid, but that depends on whether it's HTML * (and which version) or XML. */ if (code_l > 0x10FFFFL) return FAILURE; if (code_point != NULL) *code_point = (unsigned)code_l; return SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72135 - don't create strings with lengths outside int range'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void php_html_entities(INTERNAL_FUNCTION_PARAMETERS, int all) { char *str, *hint_charset = NULL; int str_len, hint_charset_len = 0; size_t new_len; long flags = ENT_COMPAT; char *replaced; zend_bool double_encode = 1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!b", &str, &str_len, &flags, &hint_charset, &hint_charset_len, &double_encode) == FAILURE) { return; } replaced = php_escape_html_entities_ex(str, str_len, &new_len, all, (int) flags, hint_charset, double_encode TSRMLS_CC); RETVAL_STRINGL(replaced, (int)new_len, 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72135 - don't create strings with lengths outside int range'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline void write_s3row_data( const entity_stage3_row *r, unsigned orig_cp, enum entity_charset charset, zval *arr) { char key[9] = ""; /* two unicode code points in UTF-8 */ char entity[LONGEST_ENTITY_LENGTH + 2] = {'&'}; size_t written_k1; written_k1 = write_octet_sequence(key, charset, orig_cp); if (!r->ambiguous) { size_t l = r->data.ent.entity_len; memcpy(&entity[1], r->data.ent.entity, l); entity[l + 1] = ';'; add_assoc_stringl_ex(arr, key, written_k1 + 1, entity, l + 2, 1); } else { unsigned i, num_entries; const entity_multicodepoint_row *mcpr = r->data.multicodepoint_table; if (mcpr[0].leading_entry.default_entity != NULL) { size_t l = mcpr[0].leading_entry.default_entity_len; memcpy(&entity[1], mcpr[0].leading_entry.default_entity, l); entity[l + 1] = ';'; add_assoc_stringl_ex(arr, key, written_k1 + 1, entity, l + 2, 1); } num_entries = mcpr[0].leading_entry.size; for (i = 1; i <= num_entries; i++) { size_t l, written_k2; unsigned uni_cp, spe_cp; uni_cp = mcpr[i].normal_entry.second_cp; l = mcpr[i].normal_entry.entity_len; if (!CHARSET_UNICODE_COMPAT(charset)) { if (map_from_unicode(uni_cp, charset, &spe_cp) == FAILURE) continue; /* non representable in this charset */ } else { spe_cp = uni_cp; } written_k2 = write_octet_sequence(&key[written_k1], charset, spe_cp); memcpy(&entity[1], mcpr[i].normal_entry.entity, l); entity[l + 1] = ';'; entity[l + 1] = '\0'; add_assoc_stringl_ex(arr, key, written_k1 + written_k2 + 1, entity, l + 1, 1); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72135 - don't create strings with lengths outside int range'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline int map_from_unicode(unsigned code, enum entity_charset charset, unsigned *res) { unsigned char found; const uni_to_enc *table; size_t table_size; switch (charset) { case cs_8859_1: /* identity mapping of code points to unicode */ if (code > 0xFF) { return FAILURE; } *res = code; break; case cs_8859_5: if (code <= 0xA0 || code == 0xAD /* soft hyphen */) { *res = code; } else if (code == 0x2116) { *res = 0xF0; /* numero sign */ } else if (code == 0xA7) { *res = 0xFD; /* section sign */ } else if (code >= 0x0401 && code <= 0x044F) { if (code == 0x040D || code == 0x0450 || code == 0x045D) return FAILURE; *res = code - 0x360; } else { return FAILURE; } break; case cs_8859_15: if (code < 0xA4 || (code > 0xBE && code <= 0xFF)) { *res = code; } else { /* between A4 and 0xBE */ found = unimap_bsearch(unimap_iso885915, code, sizeof(unimap_iso885915) / sizeof(*unimap_iso885915)); if (found) *res = found; else return FAILURE; } break; case cs_cp1252: if (code <= 0x7F || (code >= 0xA0 && code <= 0xFF)) { *res = code; } else { found = unimap_bsearch(unimap_win1252, code, sizeof(unimap_win1252) / sizeof(*unimap_win1252)); if (found) *res = found; else return FAILURE; } break; case cs_macroman: if (code == 0x7F) return FAILURE; table = unimap_macroman; table_size = sizeof(unimap_macroman) / sizeof(*unimap_macroman); goto table_over_7F; case cs_cp1251: table = unimap_win1251; table_size = sizeof(unimap_win1251) / sizeof(*unimap_win1251); goto table_over_7F; case cs_koi8r: table = unimap_koi8r; table_size = sizeof(unimap_koi8r) / sizeof(*unimap_koi8r); goto table_over_7F; case cs_cp866: table = unimap_cp866; table_size = sizeof(unimap_cp866) / sizeof(*unimap_cp866); table_over_7F: if (code <= 0x7F) { *res = code; } else { found = unimap_bsearch(table, code, table_size); if (found) *res = found; else return FAILURE; } break; /* from here on, only map the possible characters in the ASCII range. * to improve support here, it's a matter of building the unicode mappings. * See <http://www.unicode.org/Public/6.0.0/ucd/Unihan.zip> */ case cs_sjis: case cs_eucjp: /* we interpret 0x5C as the Yen symbol. This is not universal. * See <http://www.w3.org/Submission/japanese-xml/#ambiguity_of_yen> */ if (code >= 0x20 && code <= 0x7D) { if (code == 0x5C) return FAILURE; *res = code; } else { return FAILURE; } break; case cs_big5: case cs_big5hkscs: case cs_gb2312: if (code >= 0x20 && code <= 0x7D) { *res = code; } else { return FAILURE; } break; default: return FAILURE; } return SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72135 - don't create strings with lengths outside int range'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_MINIT_FUNCTION(filter) { ZEND_INIT_MODULE_GLOBALS(filter, php_filter_init_globals, NULL); REGISTER_INI_ENTRIES(); REGISTER_LONG_CONSTANT("INPUT_POST", PARSE_POST, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_GET", PARSE_GET, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_COOKIE", PARSE_COOKIE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_ENV", PARSE_ENV, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_SERVER", PARSE_SERVER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_SESSION", PARSE_SESSION, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_REQUEST", PARSE_REQUEST, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_NONE", FILTER_FLAG_NONE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_REQUIRE_SCALAR", FILTER_REQUIRE_SCALAR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_REQUIRE_ARRAY", FILTER_REQUIRE_ARRAY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FORCE_ARRAY", FILTER_FORCE_ARRAY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_NULL_ON_FAILURE", FILTER_NULL_ON_FAILURE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_INT", FILTER_VALIDATE_INT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_BOOLEAN", FILTER_VALIDATE_BOOLEAN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_FLOAT", FILTER_VALIDATE_FLOAT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_REGEXP", FILTER_VALIDATE_REGEXP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_URL", FILTER_VALIDATE_URL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_EMAIL", FILTER_VALIDATE_EMAIL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_IP", FILTER_VALIDATE_IP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_DEFAULT", FILTER_DEFAULT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_UNSAFE_RAW", FILTER_UNSAFE_RAW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_STRING", FILTER_SANITIZE_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_STRIPPED", FILTER_SANITIZE_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_ENCODED", FILTER_SANITIZE_ENCODED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_SPECIAL_CHARS", FILTER_SANITIZE_SPECIAL_CHARS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_FULL_SPECIAL_CHARS", FILTER_SANITIZE_SPECIAL_CHARS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_EMAIL", FILTER_SANITIZE_EMAIL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_URL", FILTER_SANITIZE_URL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_NUMBER_INT", FILTER_SANITIZE_NUMBER_INT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_NUMBER_FLOAT", FILTER_SANITIZE_NUMBER_FLOAT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_MAGIC_QUOTES", FILTER_SANITIZE_MAGIC_QUOTES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_CALLBACK", FILTER_CALLBACK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_OCTAL", FILTER_FLAG_ALLOW_OCTAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_HEX", FILTER_FLAG_ALLOW_HEX, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_STRIP_LOW", FILTER_FLAG_STRIP_LOW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_STRIP_HIGH", FILTER_FLAG_STRIP_HIGH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_STRIP_BACKTICK", FILTER_FLAG_STRIP_BACKTICK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ENCODE_LOW", FILTER_FLAG_ENCODE_LOW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ENCODE_HIGH", FILTER_FLAG_ENCODE_HIGH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ENCODE_AMP", FILTER_FLAG_ENCODE_AMP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_NO_ENCODE_QUOTES", FILTER_FLAG_NO_ENCODE_QUOTES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_EMPTY_STRING_NULL", FILTER_FLAG_EMPTY_STRING_NULL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_FRACTION", FILTER_FLAG_ALLOW_FRACTION, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_THOUSAND", FILTER_FLAG_ALLOW_THOUSAND, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_SCIENTIFIC", FILTER_FLAG_ALLOW_SCIENTIFIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_SCHEME_REQUIRED", FILTER_FLAG_SCHEME_REQUIRED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_HOST_REQUIRED", FILTER_FLAG_HOST_REQUIRED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_PATH_REQUIRED", FILTER_FLAG_PATH_REQUIRED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_QUERY_REQUIRED", FILTER_FLAG_QUERY_REQUIRED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_IPV4", FILTER_FLAG_IPV4, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_IPV6", FILTER_FLAG_IPV6, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_NO_RES_RANGE", FILTER_FLAG_NO_RES_RANGE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_NO_PRIV_RANGE", FILTER_FLAG_NO_PRIV_RANGE, CONST_CS | CONST_PERSISTENT); sapi_register_input_filter(php_sapi_filter, php_sapi_filter_init TSRMLS_CC); return SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Wrong value for FILTER_SANITIZE_FULL_SPECIAL_CHARS in REGISTER_LONG_CONSTANT'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void gdCtxPrintf(gdIOCtx * out, const char *format, ...) { char buf[4096]; int len; va_list args; va_start(args, format); len = vsnprintf(buf, sizeof(buf)-1, format, args); va_end(args); out->putBuf(out, buf, len); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'xbm: avoid stack overflow (read) with large names #211 We use the name passed in to printf into a local stack buffer which is limited to 4000 bytes. So given a large enough value, lots of stack data is leaked. Rewrite the code to do simple memory copies with most of the strings to avoid that issue, and only use stack buffer for small numbers of constant size. This closes #211.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int tipc_nl_compat_link_dump(struct tipc_nl_compat_msg *msg, struct nlattr **attrs) { struct nlattr *link[TIPC_NLA_LINK_MAX + 1]; struct tipc_link_info link_info; int err; if (!attrs[TIPC_NLA_LINK]) return -EINVAL; err = nla_parse_nested(link, TIPC_NLA_LINK_MAX, attrs[TIPC_NLA_LINK], NULL); if (err) return err; link_info.dest = nla_get_flag(link[TIPC_NLA_LINK_DEST]); link_info.up = htonl(nla_get_flag(link[TIPC_NLA_LINK_UP])); strcpy(link_info.str, nla_data(link[TIPC_NLA_LINK_NAME])); return tipc_add_tlv(msg->rep, TIPC_TLV_LINK_INFO, &link_info, sizeof(link_info)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'tipc: fix an infoleak in tipc_nl_compat_link_dump link_info.str is a char array of size 60. Memory after the NULL byte is not initialized. Sending the whole object out can cause a leak. Signed-off-by: Kangjie Lu <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, ExceptionInfo *exception) { #define RenderImageTag "Render/Image" AffineMatrix affine, current; char keyword[MagickPathExtent], geometry[MagickPathExtent], pattern[MagickPathExtent], *primitive, *token; const char *q; DrawInfo **graphic_context; MagickBooleanType proceed; MagickStatusType status; double angle, factor, primitive_extent; PointInfo point; PrimitiveInfo *primitive_info; PrimitiveType primitive_type; register const char *p; register ssize_t i, x; SegmentInfo bounds; size_t extent, length, number_points, number_stops; ssize_t j, k, n; StopInfo *stops; /* Ensure the annotation info is valid. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if ((draw_info->primitive == (char *) NULL) || (*draw_info->primitive == '\0')) return(MagickFalse); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"begin draw-image"); if (*draw_info->primitive != '@') primitive=AcquireString(draw_info->primitive); else primitive=FileToString(draw_info->primitive+1,~0UL,exception); if (primitive == (char *) NULL) return(MagickFalse); primitive_extent=(double) strlen(primitive); (void) SetImageArtifact(image,"MVG",primitive); n=0; number_stops=0; stops=(StopInfo *) NULL; /* Allocate primitive info memory. */ graphic_context=(DrawInfo **) AcquireMagickMemory( sizeof(*graphic_context)); if (graphic_context == (DrawInfo **) NULL) { primitive=DestroyString(primitive); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } number_points=6553; primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*primitive_info)); if (primitive_info == (PrimitiveInfo *) NULL) { primitive=DestroyString(primitive); for ( ; n >= 0; n--) graphic_context[n]=DestroyDrawInfo(graphic_context[n]); graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,draw_info); graphic_context[n]->viewbox=image->page; if ((image->page.width == 0) || (image->page.height == 0)) { graphic_context[n]->viewbox.width=image->columns; graphic_context[n]->viewbox.height=image->rows; } token=AcquireString(primitive); extent=strlen(token)+MagickPathExtent; if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; for (q=primitive; *q != '\0'; ) { /* Interpret graphic primitive. */ GetNextToken(q,&q,extent,keyword); if (*keyword == '\0') break; if (*keyword == '#') { /* Comment. */ while ((*q != '\n') && (*q != '\0')) q++; continue; } p=q-strlen(keyword)-1; primitive_type=UndefinedPrimitive; current=graphic_context[n]->affine; GetAffineMatrix(&affine); switch (*keyword) { case ';': break; case 'a': case 'A': { if (LocaleCompare("affine",keyword) == 0) { GetNextToken(q,&q,extent,token); affine.sx=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.rx=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ry=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.sy=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.tx=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ty=StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("alpha",keyword) == 0) { primitive_type=AlphaPrimitive; break; } if (LocaleCompare("arc",keyword) == 0) { primitive_type=ArcPrimitive; break; } status=MagickFalse; break; } case 'b': case 'B': { if (LocaleCompare("bezier",keyword) == 0) { primitive_type=BezierPrimitive; break; } if (LocaleCompare("border-color",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) QueryColorCompliance(token,AllCompliance, &graphic_context[n]->border_color,exception); break; } status=MagickFalse; break; } case 'c': case 'C': { if (LocaleCompare("clip-path",keyword) == 0) { /* Create clip mask. */ GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->clip_mask,token); (void) DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask,exception); break; } if (LocaleCompare("clip-rule",keyword) == 0) { ssize_t fill_rule; GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) status=MagickFalse; else graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("clip-units",keyword) == 0) { ssize_t clip_units; GetNextToken(q,&q,extent,token); clip_units=ParseCommandOption(MagickClipPathOptions,MagickFalse, token); if (clip_units == -1) { status=MagickFalse; break; } graphic_context[n]->clip_units=(ClipPathUnits) clip_units; if (clip_units == ObjectBoundingBox) { GetAffineMatrix(&current); affine.sx=draw_info->bounds.x2; affine.sy=draw_info->bounds.y2; affine.tx=draw_info->bounds.x1; affine.ty=draw_info->bounds.y1; break; } break; } if (LocaleCompare("circle",keyword) == 0) { primitive_type=CirclePrimitive; break; } if (LocaleCompare("color",keyword) == 0) { primitive_type=ColorPrimitive; break; } status=MagickFalse; break; } case 'd': case 'D': { if (LocaleCompare("decorate",keyword) == 0) { ssize_t decorate; GetNextToken(q,&q,extent,token); decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse, token); if (decorate == -1) status=MagickFalse; else graphic_context[n]->decorate=(DecorationType) decorate; break; } if (LocaleCompare("density",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->density,token); break; } if (LocaleCompare("direction",keyword) == 0) { ssize_t direction; GetNextToken(q,&q,extent,token); direction=ParseCommandOption(MagickDirectionOptions,MagickFalse, token); if (direction == -1) status=MagickFalse; else graphic_context[n]->direction=(DirectionType) direction; break; } status=MagickFalse; break; } case 'e': case 'E': { if (LocaleCompare("ellipse",keyword) == 0) { primitive_type=EllipsePrimitive; break; } if (LocaleCompare("encoding",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->encoding,token); break; } status=MagickFalse; break; } case 'f': case 'F': { if (LocaleCompare("fill",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) FormatLocaleString(pattern,MagickPathExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->fill_pattern,exception); else { status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->fill,exception); if (status == MagickFalse) { ImageInfo *pattern_info; pattern_info=AcquireImageInfo(); (void) CopyMagickString(pattern_info->filename,token, MagickPathExtent); graphic_context[n]->fill_pattern=ReadImage(pattern_info, exception); CatchException(exception); pattern_info=DestroyImageInfo(pattern_info); } } break; } if (LocaleCompare("fill-opacity",keyword) == 0) { GetNextToken(q,&q,extent,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->fill.alpha=(double) QuantumRange* factor*StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("fill-rule",keyword) == 0) { ssize_t fill_rule; GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) status=MagickFalse; else graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("font",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->font,token); if (LocaleCompare("none",token) == 0) graphic_context[n]->font=(char *) RelinquishMagickMemory(graphic_context[n]->font); break; } if (LocaleCompare("font-family",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->family,token); break; } if (LocaleCompare("font-size",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->pointsize=StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("font-stretch",keyword) == 0) { ssize_t stretch; GetNextToken(q,&q,extent,token); stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,token); if (stretch == -1) status=MagickFalse; else graphic_context[n]->stretch=(StretchType) stretch; break; } if (LocaleCompare("font-style",keyword) == 0) { ssize_t style; GetNextToken(q,&q,extent,token); style=ParseCommandOption(MagickStyleOptions,MagickFalse,token); if (style == -1) status=MagickFalse; else graphic_context[n]->style=(StyleType) style; break; } if (LocaleCompare("font-weight",keyword) == 0) { ssize_t weight; GetNextToken(q,&q,extent,token); weight=ParseCommandOption(MagickWeightOptions,MagickFalse,token); if (weight == -1) weight=StringToUnsignedLong(token); graphic_context[n]->weight=(size_t) weight; break; } status=MagickFalse; break; } case 'g': case 'G': { if (LocaleCompare("gradient-units",keyword) == 0) { GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("gravity",keyword) == 0) { ssize_t gravity; GetNextToken(q,&q,extent,token); gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,token); if (gravity == -1) status=MagickFalse; else graphic_context[n]->gravity=(GravityType) gravity; break; } status=MagickFalse; break; } case 'i': case 'I': { if (LocaleCompare("image",keyword) == 0) { ssize_t compose; primitive_type=ImagePrimitive; GetNextToken(q,&q,extent,token); compose=ParseCommandOption(MagickComposeOptions,MagickFalse,token); if (compose == -1) status=MagickFalse; else graphic_context[n]->compose=(CompositeOperator) compose; break; } if (LocaleCompare("interline-spacing",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->interline_spacing=StringToDouble(token, (char **) NULL); break; } if (LocaleCompare("interword-spacing",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->interword_spacing=StringToDouble(token, (char **) NULL); break; } status=MagickFalse; break; } case 'k': case 'K': { if (LocaleCompare("kerning",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->kerning=StringToDouble(token,(char **) NULL); break; } status=MagickFalse; break; } case 'l': case 'L': { if (LocaleCompare("line",keyword) == 0) primitive_type=LinePrimitive; else status=MagickFalse; break; } case 'o': case 'O': { if (LocaleCompare("offset",keyword) == 0) { GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("opacity",keyword) == 0) { GetNextToken(q,&q,extent,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->alpha=ClampToQuantum(QuantumRange*(1.0-((1.0- QuantumScale*graphic_context[n]->alpha)*factor* StringToDouble(token,(char **) NULL)))); graphic_context[n]->fill.alpha=(double) graphic_context[n]->alpha; graphic_context[n]->stroke.alpha=(double) graphic_context[n]->alpha; break; } status=MagickFalse; break; } case 'p': case 'P': { if (LocaleCompare("path",keyword) == 0) { primitive_type=PathPrimitive; break; } if (LocaleCompare("point",keyword) == 0) { primitive_type=PointPrimitive; break; } if (LocaleCompare("polyline",keyword) == 0) { primitive_type=PolylinePrimitive; break; } if (LocaleCompare("polygon",keyword) == 0) { primitive_type=PolygonPrimitive; break; } if (LocaleCompare("pop",keyword) == 0) { GetNextToken(q,&q,extent,token); if (LocaleCompare("clip-path",token) == 0) break; if (LocaleCompare("defs",token) == 0) break; if (LocaleCompare("gradient",token) == 0) break; if (LocaleCompare("graphic-context",token) == 0) { if (n <= 0) { (void) ThrowMagickException(exception,GetMagickModule(), DrawError,"UnbalancedGraphicContextPushPop","`%s'",token); n=0; break; } if (graphic_context[n]->clip_mask != (char *) NULL) if (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0) (void) SetImageMask(image,ReadPixelMask,(Image *) NULL, exception); graphic_context[n]=DestroyDrawInfo(graphic_context[n]); n--; break; } if (LocaleCompare("pattern",token) == 0) break; status=MagickFalse; break; } if (LocaleCompare("push",keyword) == 0) { GetNextToken(q,&q,extent,token); if (LocaleCompare("clip-path",token) == 0) { char name[MagickPathExtent]; GetNextToken(q,&q,extent,token); (void) FormatLocaleString(name,MagickPathExtent,"%s",token); for (p=q; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (LocaleCompare(token,"pop") != 0) continue; GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"clip-path") != 0) continue; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); (void) SetImageArtifact(image,name,token); GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("gradient",token) == 0) { char key[2*MagickPathExtent], name[MagickPathExtent], type[MagickPathExtent]; SegmentInfo segment; GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); GetNextToken(q,&q,extent,token); (void) CopyMagickString(type,token,MagickPathExtent); GetNextToken(q,&q,extent,token); segment.x1=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.y1=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.x2=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.y2=StringToDouble(token,(char **) NULL); if (LocaleCompare(type,"radial") == 0) { GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); } for (p=q; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (LocaleCompare(token,"pop") != 0) continue; GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"gradient") != 0) continue; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); bounds.x1=graphic_context[n]->affine.sx*segment.x1+ graphic_context[n]->affine.ry*segment.y1+ graphic_context[n]->affine.tx; bounds.y1=graphic_context[n]->affine.rx*segment.x1+ graphic_context[n]->affine.sy*segment.y1+ graphic_context[n]->affine.ty; bounds.x2=graphic_context[n]->affine.sx*segment.x2+ graphic_context[n]->affine.ry*segment.y2+ graphic_context[n]->affine.tx; bounds.y2=graphic_context[n]->affine.rx*segment.x2+ graphic_context[n]->affine.sy*segment.y2+ graphic_context[n]->affine.ty; (void) FormatLocaleString(key,MagickPathExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MagickPathExtent,"%s-type",name); (void) SetImageArtifact(image,key,type); (void) FormatLocaleString(key,MagickPathExtent,"%s-geometry",name); (void) FormatLocaleString(geometry,MagickPathExtent, "%gx%g%+.15g%+.15g", MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0), MagickMax(fabs(bounds.y2-bounds.y1+1.0),1.0), bounds.x1,bounds.y1); (void) SetImageArtifact(image,key,geometry); GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("pattern",token) == 0) { char key[2*MagickPathExtent], name[MagickPathExtent]; RectangleInfo pattern_bounds; GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); GetNextToken(q,&q,extent,token); pattern_bounds.x=(ssize_t) ceil(StringToDouble(token, (char **) NULL)-0.5); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); pattern_bounds.y=(ssize_t) ceil(StringToDouble(token, (char **) NULL)-0.5); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); pattern_bounds.width=(size_t) floor(StringToDouble(token, (char **) NULL)+0.5); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); pattern_bounds.height=(size_t) floor(StringToDouble(token, (char **) NULL)+0.5); for (p=q; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (LocaleCompare(token,"pop") != 0) continue; GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"pattern") != 0) continue; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); (void) FormatLocaleString(key,MagickPathExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MagickPathExtent,"%s-geometry", name); (void) FormatLocaleString(geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double)pattern_bounds.width, (double)pattern_bounds.height,(double)pattern_bounds.x, (double)pattern_bounds.y); (void) SetImageArtifact(image,key,geometry); GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("graphic-context",token) == 0) { n++; graphic_context=(DrawInfo **) ResizeQuantumMemory( graphic_context,(size_t) (n+1),sizeof(*graphic_context)); if (graphic_context == (DrawInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL, graphic_context[n-1]); break; } if (LocaleCompare("defs",token) == 0) break; status=MagickFalse; break; } status=MagickFalse; break; } case 'r': case 'R': { if (LocaleCompare("rectangle",keyword) == 0) { primitive_type=RectanglePrimitive; break; } if (LocaleCompare("rotate",keyword) == 0) { GetNextToken(q,&q,extent,token); angle=StringToDouble(token,(char **) NULL); affine.sx=cos(DegreesToRadians(fmod((double) angle,360.0))); affine.rx=sin(DegreesToRadians(fmod((double) angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod((double) angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod((double) angle,360.0))); break; } if (LocaleCompare("roundRectangle",keyword) == 0) { primitive_type=RoundRectanglePrimitive; break; } status=MagickFalse; break; } case 's': case 'S': { if (LocaleCompare("scale",keyword) == 0) { GetNextToken(q,&q,extent,token); affine.sx=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.sy=StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("skewX",keyword) == 0) { GetNextToken(q,&q,extent,token); angle=StringToDouble(token,(char **) NULL); affine.ry=sin(DegreesToRadians(angle)); break; } if (LocaleCompare("skewY",keyword) == 0) { GetNextToken(q,&q,extent,token); angle=StringToDouble(token,(char **) NULL); affine.rx=(-tan(DegreesToRadians(angle)/2.0)); break; } if (LocaleCompare("stop-color",keyword) == 0) { PixelInfo stop_color; number_stops++; if (number_stops == 1) stops=(StopInfo *) AcquireQuantumMemory(2,sizeof(*stops)); else if (number_stops > 2) stops=(StopInfo *) ResizeQuantumMemory(stops,number_stops, sizeof(*stops)); if (stops == (StopInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } GetNextToken(q,&q,extent,token); (void) QueryColorCompliance(token,AllCompliance,&stop_color, exception); stops[number_stops-1].color=stop_color; GetNextToken(q,&q,extent,token); stops[number_stops-1].offset=StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("stroke",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) FormatLocaleString(pattern,MagickPathExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->stroke_pattern,exception); else { status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->stroke,exception); if (status == MagickFalse) { ImageInfo *pattern_info; pattern_info=AcquireImageInfo(); (void) CopyMagickString(pattern_info->filename,token, MagickPathExtent); graphic_context[n]->stroke_pattern=ReadImage(pattern_info, exception); CatchException(exception); pattern_info=DestroyImageInfo(pattern_info); } } break; } if (LocaleCompare("stroke-antialias",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->stroke_antialias= StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("stroke-dasharray",keyword) == 0) { if (graphic_context[n]->dash_pattern != (double *) NULL) graphic_context[n]->dash_pattern=(double *) RelinquishMagickMemory(graphic_context[n]->dash_pattern); if (IsPoint(q) != MagickFalse) { const char *r; r=q; GetNextToken(r,&r,extent,token); if (*token == ',') GetNextToken(r,&r,extent,token); for (x=0; IsPoint(token) != MagickFalse; x++) { GetNextToken(r,&r,extent,token); if (*token == ',') GetNextToken(r,&r,extent,token); } graphic_context[n]->dash_pattern=(double *) AcquireQuantumMemory((size_t) (2UL*x+1UL), sizeof(*graphic_context[n]->dash_pattern)); if (graphic_context[n]->dash_pattern == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } for (j=0; j < x; j++) { GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->dash_pattern[j]=StringToDouble(token, (char **) NULL); if (graphic_context[n]->dash_pattern[j] < 0.0) status=MagickFalse; } if ((x & 0x01) != 0) for ( ; j < (2*x); j++) graphic_context[n]->dash_pattern[j]= graphic_context[n]->dash_pattern[j-x]; graphic_context[n]->dash_pattern[j]=0.0; break; } GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("stroke-dashoffset",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->dash_offset=StringToDouble(token, (char **) NULL); break; } if (LocaleCompare("stroke-linecap",keyword) == 0) { ssize_t linecap; GetNextToken(q,&q,extent,token); linecap=ParseCommandOption(MagickLineCapOptions,MagickFalse,token); if (linecap == -1) status=MagickFalse; else graphic_context[n]->linecap=(LineCap) linecap; break; } if (LocaleCompare("stroke-linejoin",keyword) == 0) { ssize_t linejoin; GetNextToken(q,&q,extent,token); linejoin=ParseCommandOption(MagickLineJoinOptions,MagickFalse, token); if (linejoin == -1) status=MagickFalse; else graphic_context[n]->linejoin=(LineJoin) linejoin; break; } if (LocaleCompare("stroke-miterlimit",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->miterlimit=StringToUnsignedLong(token); break; } if (LocaleCompare("stroke-opacity",keyword) == 0) { GetNextToken(q,&q,extent,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->stroke.alpha=(double) QuantumRange* factor*StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("stroke-width",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->stroke_width=StringToDouble(token, (char **) NULL); break; } status=MagickFalse; break; } case 't': case 'T': { if (LocaleCompare("text",keyword) == 0) { primitive_type=TextPrimitive; break; } if (LocaleCompare("text-align",keyword) == 0) { ssize_t align; GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) status=MagickFalse; else graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-anchor",keyword) == 0) { ssize_t align; GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) status=MagickFalse; else graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-antialias",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->text_antialias= StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("text-undercolor",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) QueryColorCompliance(token,AllCompliance, &graphic_context[n]->undercolor,exception); break; } if (LocaleCompare("translate",keyword) == 0) { GetNextToken(q,&q,extent,token); affine.tx=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ty=StringToDouble(token,(char **) NULL); break; } status=MagickFalse; break; } case 'v': case 'V': { if (LocaleCompare("viewbox",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token, (char **) NULL)-0.5); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token, (char **) NULL)-0.5); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.width=(size_t) floor(StringToDouble( token,(char **) NULL)+0.5); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.height=(size_t) floor(StringToDouble( token,(char **) NULL)+0.5); break; } status=MagickFalse; break; } default: { status=MagickFalse; break; } } if (status == MagickFalse) break; if ((affine.sx != 1.0) || (affine.rx != 0.0) || (affine.ry != 0.0) || (affine.sy != 1.0) || (affine.tx != 0.0) || (affine.ty != 0.0)) { graphic_context[n]->affine.sx=current.sx*affine.sx+current.ry*affine.rx; graphic_context[n]->affine.rx=current.rx*affine.sx+current.sy*affine.rx; graphic_context[n]->affine.ry=current.sx*affine.ry+current.ry*affine.sy; graphic_context[n]->affine.sy=current.rx*affine.ry+current.sy*affine.sy; graphic_context[n]->affine.tx=current.sx*affine.tx+current.ry*affine.ty+ current.tx; graphic_context[n]->affine.ty=current.rx*affine.tx+current.sy*affine.ty+ current.ty; } if (primitive_type == UndefinedPrimitive) { if (*q == '\0') { if (number_stops > 1) { GradientType type; type=LinearGradient; if (draw_info->gradient.type == RadialGradient) type=RadialGradient; (void) GradientImage(image,type,PadSpread,stops,number_stops, exception); } if (number_stops > 0) stops=(StopInfo *) RelinquishMagickMemory(stops); } if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s", (int) (q-p),p); continue; } /* Parse the primitive attributes. */ i=0; j=0; primitive_info[0].point.x=0.0; primitive_info[0].point.y=0.0; for (x=0; *q != '\0'; x++) { /* Define points. */ if (IsPoint(q) == MagickFalse) break; GetNextToken(q,&q,extent,token); point.x=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); point.y=StringToDouble(token,(char **) NULL); GetNextToken(q,(const char **) NULL,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); primitive_info[i].primitive=primitive_type; primitive_info[i].point=point; primitive_info[i].coordinates=0; primitive_info[i].method=FloodfillMethod; i++; if (i < (ssize_t) number_points) continue; number_points<<=1; primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info, (size_t) number_points,sizeof(*primitive_info)); if (primitive_info == (PrimitiveInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); break; } } primitive_info[j].primitive=primitive_type; primitive_info[j].coordinates=(size_t) x; primitive_info[j].method=FloodfillMethod; primitive_info[j].text=(char *) NULL; /* Circumscribe primitive within a circle. */ bounds.x1=primitive_info[j].point.x; bounds.y1=primitive_info[j].point.y; bounds.x2=primitive_info[j].point.x; bounds.y2=primitive_info[j].point.y; for (k=1; k < (ssize_t) primitive_info[j].coordinates; k++) { point=primitive_info[j+k].point; if (point.x < bounds.x1) bounds.x1=point.x; if (point.y < bounds.y1) bounds.y1=point.y; if (point.x > bounds.x2) bounds.x2=point.x; if (point.y > bounds.y2) bounds.y2=point.y; } /* Speculate how many points our primitive might consume. */ length=primitive_info[j].coordinates; switch (primitive_type) { case RectanglePrimitive: { length*=5; break; } case RoundRectanglePrimitive: { double alpha, beta, radius; alpha=bounds.x2-bounds.x1; beta=bounds.y2-bounds.y1; radius=hypot((double) alpha,(double) beta); length*=5; length+=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360; break; } case BezierPrimitive: { if (primitive_info[j].coordinates > 107) (void) ThrowMagickException(exception,GetMagickModule(),DrawError, "TooManyBezierCoordinates","`%s'",token); length=BezierQuantum*primitive_info[j].coordinates; break; } case PathPrimitive: { char *s, *t; GetNextToken(q,&q,extent,token); length=1; t=token; for (s=token; *s != '\0'; s=t) { double value; value=StringToDouble(s,&t); (void) value; if (s == t) { t++; continue; } length++; } length=length*BezierQuantum/2; break; } case CirclePrimitive: case ArcPrimitive: case EllipsePrimitive: { double alpha, beta, radius; alpha=bounds.x2-bounds.x1; beta=bounds.y2-bounds.y1; radius=hypot((double) alpha,(double) beta); length=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360; break; } default: break; } if ((size_t) (i+length) >= number_points) { /* Resize based on speculative points required by primitive. */ number_points+=length+1; primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info, (size_t) number_points,sizeof(*primitive_info)); if (primitive_info == (PrimitiveInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } } switch (primitive_type) { case PointPrimitive: default: { if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } TracePoint(primitive_info+j,primitive_info[j].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case LinePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } TraceLine(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case RectanglePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } TraceRectangle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case RoundRectanglePrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } TraceRoundRectangle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case ArcPrimitive: { if (primitive_info[j].coordinates != 3) { primitive_type=UndefinedPrimitive; break; } TraceArc(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case EllipsePrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } TraceEllipse(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case CirclePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } TraceCircle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PolylinePrimitive: break; case PolygonPrimitive: { primitive_info[i]=primitive_info[j]; primitive_info[i].coordinates=0; primitive_info[j].coordinates++; i++; break; } case BezierPrimitive: { if (primitive_info[j].coordinates < 3) { status=MagickFalse; break; } TraceBezier(primitive_info+j,primitive_info[j].coordinates); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PathPrimitive: { i=(ssize_t) (j+TracePath(primitive_info+j,token)); break; } case AlphaPrimitive: case ColorPrimitive: { ssize_t method; if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } GetNextToken(q,&q,extent,token); method=ParseCommandOption(MagickMethodOptions,MagickFalse,token); if (method == -1) status=MagickFalse; else primitive_info[j].method=(PaintMethod) method; break; } case TextPrimitive: { if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } if (*token != ',') GetNextToken(q,&q,extent,token); primitive_info[j].text=AcquireString(token); break; } case ImagePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } GetNextToken(q,&q,extent,token); primitive_info[j].text=AcquireString(token); break; } } if (primitive_info == (PrimitiveInfo *) NULL) break; if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p),p); if (status == MagickFalse) break; primitive_info[i].primitive=UndefinedPrimitive; if (i == 0) continue; /* Transform points. */ for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { point=primitive_info[i].point; primitive_info[i].point.x=graphic_context[n]->affine.sx*point.x+ graphic_context[n]->affine.ry*point.y+graphic_context[n]->affine.tx; primitive_info[i].point.y=graphic_context[n]->affine.rx*point.x+ graphic_context[n]->affine.sy*point.y+graphic_context[n]->affine.ty; point=primitive_info[i].point; if (point.x < graphic_context[n]->bounds.x1) graphic_context[n]->bounds.x1=point.x; if (point.y < graphic_context[n]->bounds.y1) graphic_context[n]->bounds.y1=point.y; if (point.x > graphic_context[n]->bounds.x2) graphic_context[n]->bounds.x2=point.x; if (point.y > graphic_context[n]->bounds.y2) graphic_context[n]->bounds.y2=point.y; if (primitive_info[i].primitive == ImagePrimitive) break; if (i >= (ssize_t) number_points) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); } if (graphic_context[n]->render != MagickFalse) { if ((n != 0) && (graphic_context[n]->clip_mask != (char *) NULL) && (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0)) status&=DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask,exception); status&=DrawPrimitive(image,graphic_context[n],primitive_info, exception); } if (primitive_info->text != (char *) NULL) primitive_info->text=(char *) RelinquishMagickMemory( primitive_info->text); proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType) primitive_extent); if (proceed == MagickFalse) break; if (status == 0) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end draw-image"); /* Relinquish resources. */ token=DestroyString(token); if (primitive_info != (PrimitiveInfo *) NULL) primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info); primitive=DestroyString(primitive); for ( ; n >= 0; n--) graphic_context[n]=DestroyDrawInfo(graphic_context[n]); graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context); if (status == MagickFalse) ThrowBinaryException(DrawError,"NonconformingDrawingPrimitiveDefinition", keyword); return(status != 0 ? MagickTrue : MagickFalse); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-119'], 'message': 'Prevent buffer overflow in magick/draw.c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) { const char *option; ExceptionInfo *exception; ImageInfo *clone_info; /* Initialize draw attributes. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info != (DrawInfo *) NULL); (void) ResetMagickMemory(draw_info,0,sizeof(*draw_info)); clone_info=CloneImageInfo(image_info); GetAffineMatrix(&draw_info->affine); exception=AcquireExceptionInfo(); (void) QueryColorCompliance("#000F",AllCompliance,&draw_info->fill, exception); (void) QueryColorCompliance("#0000",AllCompliance,&draw_info->stroke, exception); draw_info->stroke_width=1.0; draw_info->alpha=OpaqueAlpha; draw_info->fill_rule=EvenOddRule; draw_info->linecap=ButtCap; draw_info->linejoin=MiterJoin; draw_info->miterlimit=10; draw_info->decorate=NoDecoration; draw_info->pointsize=12.0; draw_info->undercolor.alpha=(Quantum) TransparentAlpha; draw_info->compose=OverCompositeOp; draw_info->render=MagickTrue; draw_info->debug=IsEventLogging(); draw_info->stroke_antialias=clone_info->antialias; if (clone_info->font != (char *) NULL) draw_info->font=AcquireString(clone_info->font); if (clone_info->density != (char *) NULL) draw_info->density=AcquireString(clone_info->density); draw_info->text_antialias=clone_info->antialias; if (clone_info->pointsize != 0.0) draw_info->pointsize=clone_info->pointsize; draw_info->border_color=clone_info->border_color; if (clone_info->server_name != (char *) NULL) draw_info->server_name=AcquireString(clone_info->server_name); option=GetImageOption(clone_info,"direction"); if (option != (const char *) NULL) draw_info->direction=(DirectionType) ParseCommandOption( MagickDirectionOptions,MagickFalse,option); else draw_info->direction=UndefinedDirection; option=GetImageOption(clone_info,"encoding"); if (option != (const char *) NULL) (void) CloneString(&draw_info->encoding,option); option=GetImageOption(clone_info,"family"); if (option != (const char *) NULL) (void) CloneString(&draw_info->family,option); option=GetImageOption(clone_info,"fill"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->fill, exception); option=GetImageOption(clone_info,"gravity"); if (option != (const char *) NULL) draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,option); option=GetImageOption(clone_info,"interline-spacing"); if (option != (const char *) NULL) draw_info->interline_spacing=StringToDouble(option,(char **) NULL); option=GetImageOption(clone_info,"interword-spacing"); if (option != (const char *) NULL) draw_info->interword_spacing=StringToDouble(option,(char **) NULL); option=GetImageOption(clone_info,"kerning"); if (option != (const char *) NULL) draw_info->kerning=StringToDouble(option,(char **) NULL); option=GetImageOption(clone_info,"stroke"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke, exception); option=GetImageOption(clone_info,"strokewidth"); if (option != (const char *) NULL) draw_info->stroke_width=StringToDouble(option,(char **) NULL); option=GetImageOption(clone_info,"style"); if (option != (const char *) NULL) draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions, MagickFalse,option); option=GetImageOption(clone_info,"undercolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor, exception); option=GetImageOption(clone_info,"weight"); if (option != (const char *) NULL) { ssize_t weight; weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option); if (weight == -1) weight=StringToUnsignedLong(option); draw_info->weight=(size_t) weight; } exception=DestroyExceptionInfo(exception); draw_info->signature=MagickCoreSignature; clone_info=DestroyImageInfo(clone_info); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-119'], 'message': 'Prevent buffer overflow in magick/draw.c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info) { typedef struct _LineSegment { double p, q; } LineSegment; LineSegment dx, dy, inverse_slope, slope, theta; MagickBooleanType closed_path; double delta_theta, dot_product, mid, miterlimit; PointInfo box_p[5], box_q[5], center, offset, *path_p, *path_q; PrimitiveInfo *polygon_primitive, *stroke_polygon; register ssize_t i; size_t arc_segments, max_strokes, number_vertices; ssize_t j, n, p, q; /* Allocate paths. */ number_vertices=primitive_info->coordinates; max_strokes=2*number_vertices+6*BezierQuantum+360; path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes, sizeof(*path_p)); path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes, sizeof(*path_q)); polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_vertices+2UL,sizeof(*polygon_primitive)); if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL) || (polygon_primitive == (PrimitiveInfo *) NULL)) return((PrimitiveInfo *) NULL); (void) CopyMagickMemory(polygon_primitive,primitive_info,(size_t) number_vertices*sizeof(*polygon_primitive)); closed_path= (primitive_info[number_vertices-1].point.x == primitive_info[0].point.x) && (primitive_info[number_vertices-1].point.y == primitive_info[0].point.y) ? MagickTrue : MagickFalse; if ((draw_info->linejoin == RoundJoin) || ((draw_info->linejoin == MiterJoin) && (closed_path != MagickFalse))) { polygon_primitive[number_vertices]=primitive_info[1]; number_vertices++; } polygon_primitive[number_vertices].primitive=UndefinedPrimitive; /* Compute the slope for the first line segment, p. */ dx.p=0.0; dy.p=0.0; for (n=1; n < (ssize_t) number_vertices; n++) { dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x; dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y; if ((fabs(dx.p) >= MagickEpsilon) || (fabs(dy.p) >= MagickEpsilon)) break; } if (n == (ssize_t) number_vertices) n=(ssize_t) number_vertices-1L; slope.p=DrawEpsilonReciprocal(dx.p)*dy.p; inverse_slope.p=(-1.0*DrawEpsilonReciprocal(slope.p)); mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit* mid*mid); if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse)) TraceSquareLinecap(polygon_primitive,number_vertices,mid); offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0))); offset.y=(double) (offset.x*inverse_slope.p); if ((dy.p*offset.x-dx.p*offset.y) > 0.0) { box_p[0].x=polygon_primitive[0].point.x-offset.x; box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p; box_p[1].x=polygon_primitive[n].point.x-offset.x; box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p; box_q[0].x=polygon_primitive[0].point.x+offset.x; box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p; box_q[1].x=polygon_primitive[n].point.x+offset.x; box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p; } else { box_p[0].x=polygon_primitive[0].point.x+offset.x; box_p[0].y=polygon_primitive[0].point.y+offset.y; box_p[1].x=polygon_primitive[n].point.x+offset.x; box_p[1].y=polygon_primitive[n].point.y+offset.y; box_q[0].x=polygon_primitive[0].point.x-offset.x; box_q[0].y=polygon_primitive[0].point.y-offset.y; box_q[1].x=polygon_primitive[n].point.x-offset.x; box_q[1].y=polygon_primitive[n].point.y-offset.y; } /* Create strokes for the line join attribute: bevel, miter, round. */ p=0; q=0; path_q[p++]=box_q[0]; path_p[q++]=box_p[0]; for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++) { /* Compute the slope for this line segment, q. */ dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x; dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y; dot_product=dx.q*dx.q+dy.q*dy.q; if (dot_product < 0.25) continue; slope.q=DrawEpsilonReciprocal(dx.q)*dy.q; inverse_slope.q=(-1.0*DrawEpsilonReciprocal(slope.q)); offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0))); offset.y=(double) (offset.x*inverse_slope.q); dot_product=dy.q*offset.x-dx.q*offset.y; if (dot_product > 0.0) { box_p[2].x=polygon_primitive[n].point.x-offset.x; box_p[2].y=polygon_primitive[n].point.y-offset.y; box_p[3].x=polygon_primitive[i].point.x-offset.x; box_p[3].y=polygon_primitive[i].point.y-offset.y; box_q[2].x=polygon_primitive[n].point.x+offset.x; box_q[2].y=polygon_primitive[n].point.y+offset.y; box_q[3].x=polygon_primitive[i].point.x+offset.x; box_q[3].y=polygon_primitive[i].point.y+offset.y; } else { box_p[2].x=polygon_primitive[n].point.x+offset.x; box_p[2].y=polygon_primitive[n].point.y+offset.y; box_p[3].x=polygon_primitive[i].point.x+offset.x; box_p[3].y=polygon_primitive[i].point.y+offset.y; box_q[2].x=polygon_primitive[n].point.x-offset.x; box_q[2].y=polygon_primitive[n].point.y-offset.y; box_q[3].x=polygon_primitive[i].point.x-offset.x; box_q[3].y=polygon_primitive[i].point.y-offset.y; } if (fabs((double) (slope.p-slope.q)) < MagickEpsilon) { box_p[4]=box_p[1]; box_q[4]=box_q[1]; } else { box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+ box_p[3].y)/(slope.p-slope.q)); box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y); box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+ box_q[3].y)/(slope.p-slope.q)); box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y); } if (q >= (ssize_t) (max_strokes-6*BezierQuantum-360)) { max_strokes+=6*BezierQuantum+360; path_p=(PointInfo *) ResizeQuantumMemory(path_p,(size_t) max_strokes, sizeof(*path_p)); path_q=(PointInfo *) ResizeQuantumMemory(path_q,(size_t) max_strokes, sizeof(*path_q)); if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL)) { polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); return((PrimitiveInfo *) NULL); } } dot_product=dx.q*dy.p-dx.p*dy.q; if (dot_product <= 0.0) switch (draw_info->linejoin) { case BevelJoin: { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_p[p++]=box_p[4]; else { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case MiterJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) { path_q[q++]=box_q[4]; path_p[p++]=box_p[4]; } else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case RoundJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_p[p++]=box_p[4]; else { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } center=polygon_primitive[n].point; theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x); theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x); if (theta.q < theta.p) theta.q+=(double) (2.0*MagickPI); arc_segments=(size_t) ceil((double) ((theta.q-theta.p)/ (2.0*sqrt((double) (1.0/mid))))); path_q[q].x=box_q[1].x; path_q[q].y=box_q[1].y; q++; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); path_q[q].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); path_q[q].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); q++; } path_q[q++]=box_q[2]; break; } default: break; } else switch (draw_info->linejoin) { case BevelJoin: { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_q[q++]=box_q[4]; else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; } break; } case MiterJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) { path_q[q++]=box_q[4]; path_p[p++]=box_p[4]; } else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case RoundJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_q[q++]=box_q[4]; else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; } center=polygon_primitive[n].point; theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x); theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x); if (theta.p < theta.q) theta.p+=(double) (2.0*MagickPI); arc_segments=(size_t) ceil((double) ((theta.p-theta.q)/ (2.0*sqrt((double) (1.0/mid))))); path_p[p++]=box_p[1]; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); path_p[p].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); path_p[p].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); p++; } path_p[p++]=box_p[2]; break; } default: break; } slope.p=slope.q; inverse_slope.p=inverse_slope.q; box_p[0]=box_p[2]; box_p[1]=box_p[3]; box_q[0]=box_q[2]; box_q[1]=box_q[3]; dx.p=dx.q; dy.p=dy.q; n=i; } path_p[p++]=box_p[1]; path_q[q++]=box_q[1]; /* Trace stroked polygon. */ stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon)); if (stroke_polygon != (PrimitiveInfo *) NULL) { for (i=0; i < (ssize_t) p; i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=path_p[i]; } if (closed_path != MagickFalse) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[0].point; i++; } for ( ; i < (ssize_t) (p+q+closed_path); i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=path_q[p+q+closed_path-(i+1)]; } if (closed_path != MagickFalse) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[p+closed_path].point; i++; } stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[0].point; i++; stroke_polygon[i].primitive=UndefinedPrimitive; stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1); } path_p=(PointInfo *) RelinquishMagickMemory(path_p); path_q=(PointInfo *) RelinquishMagickMemory(path_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); return(stroke_polygon); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-119'], 'message': 'Prevent buffer overflow in magick/draw.c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception) { DrawInfo *clone_info; double length, maximum_length, offset, scale, total_length; MagickStatusType status; PrimitiveInfo *dash_polygon; register ssize_t i; register double dx, dy; size_t number_vertices; ssize_t j, n; assert(draw_info != (const DrawInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash"); for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; number_vertices=(size_t) i; dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (2UL*number_vertices+1UL),sizeof(*dash_polygon)); if (dash_polygon == (PrimitiveInfo *) NULL) return(MagickFalse); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->miterlimit=0; dash_polygon[0]=primitive_info[0]; scale=ExpandAffine(&draw_info->affine); length=scale*(draw_info->dash_pattern[0]-0.5); offset=draw_info->dash_offset != 0.0 ? scale*draw_info->dash_offset : 0.0; j=1; for (n=0; offset > 0.0; j=0) { if (draw_info->dash_pattern[n] <= 0.0) break; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); if (offset > length) { offset-=length; n++; length=scale*(draw_info->dash_pattern[n]+0.5); continue; } if (offset < length) { length-=offset; offset=0.0; break; } offset=0.0; n++; } status=MagickTrue; maximum_length=0.0; total_length=0.0; for (i=1; (i < number_vertices) && (length >= 0.0); i++) { dx=primitive_info[i].point.x-primitive_info[i-1].point.x; dy=primitive_info[i].point.y-primitive_info[i-1].point.y; maximum_length=hypot((double) dx,dy); if (length == 0.0) { n++; if (draw_info->dash_pattern[n] == 0.0) n=0; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); } for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); ) { total_length+=length; if ((n & 0x01) != 0) { dash_polygon[0]=primitive_info[0]; dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx* total_length/maximum_length); dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy* total_length/maximum_length); j=1; } else { if ((j+1) > (ssize_t) (2*number_vertices)) break; dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx* total_length/maximum_length); dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy* total_length/maximum_length); dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception); } n++; if (draw_info->dash_pattern[n] == 0.0) n=0; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); } length-=(maximum_length-total_length); if ((n & 0x01) != 0) continue; dash_polygon[j]=primitive_info[i]; dash_polygon[j].coordinates=1; j++; } if ((total_length <= maximum_length) && ((n & 0x01) == 0) && (j > 1)) { dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x+=MagickEpsilon; dash_polygon[j].point.y+=MagickEpsilon; dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception); } dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash"); return(status != 0 ? MagickTrue : MagickFalse); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-119'], 'message': 'Prevent buffer overflow in magick/draw.c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void _CONSTRUCTOR lib_init(void) { int ret; const char *e; if (_gnutls_global_init_skip() != 0) return; e = getenv("GNUTLS_NO_EXPLICIT_INIT"); if (e != NULL) { ret = atoi(e); if (ret == 1) return; } ret = gnutls_global_init(); if (ret < 0) { fprintf(stderr, "Error in GnuTLS initialization: %s\n", gnutls_strerror(ret)); _gnutls_switch_lib_state(LIB_STATE_ERROR); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'env: use secure_getenv when reading environment variables'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: unsigned _gnutls_fips_mode_enabled(void) { unsigned f1p = 0, f2p; FILE* fd; const char *p; if (_fips_mode != -1) return _fips_mode; p = getenv("GNUTLS_FORCE_FIPS_MODE"); if (p) { if (p[0] == '1') _fips_mode = 1; else if (p[0] == '2') _fips_mode = 2; else _fips_mode = 0; return _fips_mode; } fd = fopen(FIPS_KERNEL_FILE, "r"); if (fd != NULL) { f1p = fgetc(fd); fclose(fd); if (f1p == '1') f1p = 1; else f1p = 0; } f2p = !access(FIPS_SYSTEM_FILE, F_OK); if (f1p != 0 && f2p != 0) { _gnutls_debug_log("FIPS140-2 mode enabled\n"); _fips_mode = 1; return _fips_mode; } if (f2p != 0) { /* a funny state where self tests are performed * and ignored */ _gnutls_debug_log("FIPS140-2 ZOMBIE mode enabled\n"); _fips_mode = 2; return _fips_mode; } _fips_mode = 0; return _fips_mode; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'env: use secure_getenv when reading environment variables'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: dissect_spoolss_keybuffer(tvbuff_t *tvb, int offset, packet_info *pinfo, proto_tree *tree, dcerpc_info *di, guint8 *drep) { guint32 size; int end_offset; if (di->conformant_run) return offset; /* Dissect size and data */ offset = dissect_ndr_uint32(tvb, offset, pinfo, tree, di, drep, hf_keybuffer_size, &size); end_offset = offset + (size*2); if (end_offset < offset) { /* * Overflow - make the end offset one past the end of * the packet data, so we throw an exception (as the * size is almost certainly too big). */ end_offset = tvb_reported_length_remaining(tvb, offset) + 1; } while (offset < end_offset) offset = dissect_spoolss_uint16uni( tvb, offset, pinfo, tree, drep, NULL, hf_keybuffer); return offset; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'SPOOLSS: Try to avoid an infinite loop. Use tvb_reported_length_remaining in dissect_spoolss_uint16uni. Make sure our offset always increments in dissect_spoolss_keybuffer. Change-Id: I7017c9685bb2fa27161d80a03b8fca4ef630e793 Reviewed-on: https://code.wireshark.org/review/14687 Reviewed-by: Gerald Combs <[email protected]> Petri-Dish: Gerald Combs <[email protected]> Tested-by: Petri Dish Buildbot <[email protected]> Reviewed-by: Michael Mann <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: AirPDcapDecryptWPABroadcastKey(const EAPOL_RSN_KEY *pEAPKey, guint8 *decryption_key, PAIRPDCAP_SEC_ASSOCIATION sa, guint eapol_len) { guint8 key_version; guint8 *key_data; guint8 *szEncryptedKey; guint16 key_bytes_len = 0; /* Length of the total key data field */ guint16 key_len; /* Actual group key length */ static AIRPDCAP_KEY_ITEM dummy_key; /* needed in case AirPDcapRsnaMng() wants the key structure */ AIRPDCAP_SEC_ASSOCIATION *tmp_sa; /* We skip verifying the MIC of the key. If we were implementing a WPA supplicant we'd want to verify, but for a sniffer it's not needed. */ /* Preparation for decrypting the group key - determine group key data length */ /* depending on whether the pairwise key is TKIP or AES encryption key */ key_version = AIRPDCAP_EAP_KEY_DESCR_VER(pEAPKey->key_information[1]); if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){ /* TKIP */ key_bytes_len = pntoh16(pEAPKey->key_length); }else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){ /* AES */ key_bytes_len = pntoh16(pEAPKey->key_data_len); /* AES keys must be at least 128 bits = 16 bytes. */ if (key_bytes_len < 16) { return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } } if (key_bytes_len < GROUP_KEY_MIN_LEN || key_bytes_len > eapol_len - sizeof(EAPOL_RSN_KEY)) { return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } /* Encrypted key is in the information element field of the EAPOL key packet */ key_data = (guint8 *)pEAPKey + sizeof(EAPOL_RSN_KEY); szEncryptedKey = (guint8 *)g_memdup(key_data, key_bytes_len); DEBUG_DUMP("Encrypted Broadcast key:", szEncryptedKey, key_bytes_len); DEBUG_DUMP("KeyIV:", pEAPKey->key_iv, 16); DEBUG_DUMP("decryption_key:", decryption_key, 16); /* We are rekeying, save old sa */ tmp_sa=(AIRPDCAP_SEC_ASSOCIATION *)g_malloc(sizeof(AIRPDCAP_SEC_ASSOCIATION)); memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION)); sa->next=tmp_sa; /* As we have no concept of the prior association request at this point, we need to deduce the */ /* group key cipher from the length of the key bytes. In WPA this is straightforward as the */ /* keybytes just contain the GTK, and the GTK is only in the group handshake, NOT the M3. */ /* In WPA2 its a little more tricky as the M3 keybytes contain an RSN_IE, but the group handshake */ /* does not. Also there are other (variable length) items in the keybytes which we need to account */ /* for to determine the true key length, and thus the group cipher. */ if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){ guint8 new_key[32]; guint8 dummy[256]; /* TKIP key */ /* Per 802.11i, Draft 3.0 spec, section 8.5.2, p. 97, line 4-8, */ /* group key is decrypted using RC4. Concatenate the IV with the 16 byte EK (PTK+16) to get the decryption key */ rc4_state_struct rc4_state; /* The WPA group key just contains the GTK bytes so deducing the type is straightforward */ /* Note - WPA M3 doesn't contain a group key so we'll only be here for the group handshake */ sa->wpa.key_ver = (key_bytes_len >=TKIP_GROUP_KEY_LEN)?AIRPDCAP_WPA_KEY_VER_NOT_CCMP:AIRPDCAP_WPA_KEY_VER_AES_CCMP; /* Build the full decryption key based on the IV and part of the pairwise key */ memcpy(new_key, pEAPKey->key_iv, 16); memcpy(new_key+16, decryption_key, 16); DEBUG_DUMP("FullDecrKey:", new_key, 32); crypt_rc4_init(&rc4_state, new_key, sizeof(new_key)); /* Do dummy 256 iterations of the RC4 algorithm (per 802.11i, Draft 3.0, p. 97 line 6) */ crypt_rc4(&rc4_state, dummy, 256); crypt_rc4(&rc4_state, szEncryptedKey, key_bytes_len); } else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){ /* AES CCMP key */ guint8 key_found; guint8 key_length; guint16 key_index; guint8 *decrypted_data; /* Unwrap the key; the result is key_bytes_len in length */ decrypted_data = AES_unwrap(decryption_key, 16, szEncryptedKey, key_bytes_len); /* With WPA2 what we get after Broadcast Key decryption is an actual RSN structure. The key itself is stored as a GTK KDE WPA2 IE (1 byte) id = 0xdd, length (1 byte), GTK OUI (4 bytes), key index (1 byte) and 1 reserved byte. Thus we have to pass pointer to the actual key with 8 bytes offset */ key_found = FALSE; key_index = 0; /* Parse Key data until we found GTK KDE */ /* GTK KDE = 00-0F-AC 01 */ while(key_index < (key_bytes_len - 6) && !key_found){ guint8 rsn_id; guint32 type; /* Get RSN ID */ rsn_id = decrypted_data[key_index]; type = ((decrypted_data[key_index + 2] << 24) + (decrypted_data[key_index + 3] << 16) + (decrypted_data[key_index + 4] << 8) + (decrypted_data[key_index + 5])); if (rsn_id == 0xdd && type == 0x000fac01) { key_found = TRUE; } else { key_index += decrypted_data[key_index+1]+2; } } if (key_found){ key_length = decrypted_data[key_index+1] - 6; if (key_index+8 >= key_bytes_len || key_length > key_bytes_len - key_index - 8) { g_free(decrypted_data); g_free(szEncryptedKey); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } /* Skip over the GTK header info, and don't copy past the end of the encrypted data */ memcpy(szEncryptedKey, decrypted_data+key_index+8, key_length); } else { g_free(decrypted_data); g_free(szEncryptedKey); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } if (key_length == TKIP_GROUP_KEY_LEN) sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_NOT_CCMP; else sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_AES_CCMP; g_free(decrypted_data); } key_len = (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP)?TKIP_GROUP_KEY_LEN:CCMP_GROUP_KEY_LEN; if (key_len > key_bytes_len) { /* the key required for this protocol is longer than the key that we just calculated */ g_free(szEncryptedKey); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } /* Decrypted key is now in szEncryptedKey with len of key_len */ DEBUG_DUMP("Broadcast key:", szEncryptedKey, key_len); /* Load the proper key material info into the SA */ sa->key = &dummy_key; /* we just need key to be not null because it is checked in AirPDcapRsnaMng(). The WPA key materials are actually in the .wpa structure */ sa->validKey = TRUE; /* Since this is a GTK and its size is only 32 bytes (vs. the 64 byte size of a PTK), we fake it and put it in at a 32-byte offset so the */ /* AirPDcapRsnaMng() function will extract the right piece of the GTK for decryption. (The first 16 bytes of the GTK are used for decryption.) */ memset(sa->wpa.ptk, 0, sizeof(sa->wpa.ptk)); memcpy(sa->wpa.ptk+32, szEncryptedKey, key_len); g_free(szEncryptedKey); return AIRPDCAP_RET_SUCCESS_HANDSHAKE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Sanity check eapol_len in AirPDcapDecryptWPABroadcastKey Bug: 12175 Change-Id: Iaf977ba48f8668bf8095800a115ff9a3472dd893 Reviewed-on: https://code.wireshark.org/review/15326 Petri-Dish: Michael Mann <[email protected]> Tested-by: Petri Dish Buildbot <[email protected]> Reviewed-by: Alexis La Goutte <[email protected]> Reviewed-by: Peter Wu <[email protected]> Tested-by: Peter Wu <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: dissect_usb_video_control_interface_descriptor(proto_tree *parent_tree, tvbuff_t *tvb, guint8 descriptor_len, packet_info *pinfo, usb_conv_info_t *usb_conv_info) { video_conv_info_t *video_conv_info = NULL; video_entity_t *entity = NULL; proto_item *item = NULL; proto_item *subtype_item = NULL; proto_tree *tree = NULL; guint8 entity_id = 0; guint16 terminal_type = 0; int offset = 0; guint8 subtype; subtype = tvb_get_guint8(tvb, offset+2); if (parent_tree) { const gchar *subtype_str; subtype_str = val_to_str_ext(subtype, &vc_if_descriptor_subtypes_ext, "Unknown (0x%x)"); tree = proto_tree_add_subtree_format(parent_tree, tvb, offset, descriptor_len, ett_descriptor_video_control, &item, "VIDEO CONTROL INTERFACE DESCRIPTOR [%s]", subtype_str); } /* Common fields */ dissect_usb_descriptor_header(tree, tvb, offset, &vid_descriptor_type_vals_ext); subtype_item = proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_subtype, tvb, offset+2, 1, ENC_LITTLE_ENDIAN); offset += 3; if (subtype == VC_HEADER) { guint8 num_vs_interfaces; proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_bcdUVC, tvb, offset, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_ifdesc_wTotalLength, tvb, offset+2, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_dwClockFrequency, tvb, offset+4, 4, ENC_LITTLE_ENDIAN); num_vs_interfaces = tvb_get_guint8(tvb, offset+8); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_bInCollection, tvb, offset+8, 1, ENC_LITTLE_ENDIAN); if (num_vs_interfaces > 0) { proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_baInterfaceNr, tvb, offset+9, num_vs_interfaces, ENC_NA); } offset += 9 + num_vs_interfaces; } else if ((subtype == VC_INPUT_TERMINAL) || (subtype == VC_OUTPUT_TERMINAL)) { /* Fields common to input and output terminals */ entity_id = tvb_get_guint8(tvb, offset); terminal_type = tvb_get_letohs(tvb, offset+1); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_terminal_id, tvb, offset, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_terminal_type, tvb, offset+1, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_assoc_terminal, tvb, offset+3, 1, ENC_LITTLE_ENDIAN); offset += 4; if (subtype == VC_OUTPUT_TERMINAL) { proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_src_id, tvb, offset, 1, ENC_LITTLE_ENDIAN); ++offset; } proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_iTerminal, tvb, offset, 1, ENC_LITTLE_ENDIAN); ++offset; if (subtype == VC_INPUT_TERMINAL) { if (terminal_type == ITT_CAMERA) { offset = dissect_usb_video_camera_terminal(tree, tvb, offset); } else if (terminal_type == ITT_MEDIA_TRANSPORT_INPUT) { /* @todo */ } } if (subtype == VC_OUTPUT_TERMINAL) { if (terminal_type == OTT_MEDIA_TRANSPORT_OUTPUT) { /* @todo */ } } } else { /* Field common to extension / processing / selector / encoding units */ entity_id = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_unit_id, tvb, offset, 1, ENC_LITTLE_ENDIAN); ++offset; if (subtype == VC_PROCESSING_UNIT) { offset = dissect_usb_video_processing_unit(tree, tvb, offset); } else if (subtype == VC_SELECTOR_UNIT) { offset = dissect_usb_video_selector_unit(tree, tvb, offset); } else if (subtype == VC_EXTENSION_UNIT) { offset = dissect_usb_video_extension_unit(tree, tvb, offset); } else if (subtype == VC_ENCODING_UNIT) { /* @todo UVC 1.5 */ } else { expert_add_info_format(pinfo, subtype_item, &ei_usb_vid_subtype_unknown, "Unknown VC subtype %u", subtype); } } /* Soak up descriptor bytes beyond those we know how to dissect */ if (offset < descriptor_len) { proto_tree_add_item(tree, hf_usb_vid_descriptor_data, tvb, offset, descriptor_len-offset, ENC_NA); /* offset = descriptor_len; */ } if (entity_id != 0) proto_item_append_text(item, " (Entity %d)", entity_id); if (subtype != VC_HEADER && usb_conv_info) { /* Switch to the usb_conv_info of the Video Control interface */ usb_conv_info = get_usb_iface_conv_info(pinfo, usb_conv_info->interfaceNum); video_conv_info = (video_conv_info_t *)usb_conv_info->class_data; if (!video_conv_info) { video_conv_info = wmem_new(wmem_file_scope(), video_conv_info_t); video_conv_info->entities = wmem_tree_new(wmem_file_scope()); usb_conv_info->class_data = video_conv_info; } entity = (video_entity_t*) wmem_tree_lookup32(video_conv_info->entities, entity_id); if (!entity) { entity = wmem_new(wmem_file_scope(), video_entity_t); entity->entityID = entity_id; entity->subtype = subtype; entity->terminalType = terminal_type; wmem_tree_insert32(video_conv_info->entities, entity_id, entity); } } return descriptor_len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Make class "type" for USB conversations. USB dissectors can't assume that only their class type has been passed around in the conversation. Make explicit check that class type expected matches the dissector and stop/prevent dissection if there isn't a match. Bug: 12356 Change-Id: Ib23973a4ebd0fbb51952ffc118daf95e3389a209 Reviewed-on: https://code.wireshark.org/review/15212 Petri-Dish: Michael Mann <[email protected]> Reviewed-by: Martin Kaiser <[email protected]> Petri-Dish: Martin Kaiser <[email protected]> Tested-by: Petri Dish Buildbot <[email protected]> Reviewed-by: Michael Mann <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: dissect_ac_if_hdr_body(tvbuff_t *tvb, gint offset, packet_info *pinfo _U_, proto_tree *tree, usb_conv_info_t *usb_conv_info) { gint offset_start; guint16 bcdADC; guint8 ver_major; double ver; guint8 if_in_collection, i; audio_conv_info_t *audio_conv_info; offset_start = offset; bcdADC = tvb_get_letohs(tvb, offset); ver_major = USB_AUDIO_BCD44_TO_DEC(bcdADC>>8); ver = ver_major + USB_AUDIO_BCD44_TO_DEC(bcdADC&0xFF) / 100.0; proto_tree_add_double_format_value(tree, hf_ac_if_hdr_ver, tvb, offset, 2, ver, "%2.2f", ver); audio_conv_info = (audio_conv_info_t *)usb_conv_info->class_data; if(!audio_conv_info) { audio_conv_info = wmem_new(wmem_file_scope(), audio_conv_info_t); usb_conv_info->class_data = audio_conv_info; /* XXX - set reasonable default values for all components that are not filled in by this function */ } audio_conv_info->ver_major = ver_major; offset += 2; /* version 1 refers to the Basic Audio Device specification, version 2 is the Audio Device class specification, see above */ if (ver_major==1) { proto_tree_add_item(tree, hf_ac_if_hdr_total_len, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; if_in_collection = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_ac_if_hdr_bInCollection, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; for (i=0; i<if_in_collection; i++) { proto_tree_add_item(tree, hf_ac_if_hdr_if_num, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; } } return offset-offset_start; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Make class "type" for USB conversations. USB dissectors can't assume that only their class type has been passed around in the conversation. Make explicit check that class type expected matches the dissector and stop/prevent dissection if there isn't a match. Bug: 12356 Change-Id: Ib23973a4ebd0fbb51952ffc118daf95e3389a209 Reviewed-on: https://code.wireshark.org/review/15212 Petri-Dish: Michael Mann <[email protected]> Reviewed-by: Martin Kaiser <[email protected]> Petri-Dish: Martin Kaiser <[email protected]> Tested-by: Petri Dish Buildbot <[email protected]> Reviewed-by: Michael Mann <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info) { union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header; char line[TOSHIBA_LINE_LENGTH]; int num_items_scanned; guint pkt_len; int pktnum, hr, min, sec, csec; char channel[10], direction[10]; int i, hex_lines; guint8 *pd; /* Our file pointer should be on the line containing the * summary information for a packet. Read in that line and * extract the useful information */ if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } /* Find text in line after "[No.". Limit the length of the * two strings since we have fixed buffers for channel[] and * direction[] */ num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s", &pktnum, &hr, &min, &sec, &csec, channel, direction); if (num_items_scanned != 7) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("toshiba: record header isn't valid"); return FALSE; } /* Scan lines until we find the OFFSET line. In a "telnet" trace, * this will be the next line. But if you save your telnet session * to a file from within a Windows-based telnet client, it may * put in line breaks at 80 columns (or however big your "telnet" box * is). CRT (a Windows telnet app from VanDyke) does this. * Here we assume that 80 columns will be the minimum size, and that * the OFFSET line is not broken in the middle. It's the previous * line that is normally long and can thus be broken at column 80. */ do { if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } /* Check for "OFFSET 0001-0203" at beginning of line */ line[16] = '\0'; } while (strcmp(line, "OFFSET 0001-0203") != 0); num_items_scanned = sscanf(line+64, "LEN=%9u", &pkt_len); if (num_items_scanned != 1) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item"); return FALSE; } if (pkt_len > WTAP_MAX_PACKET_SIZE) { /* * Probably a corrupt capture file; don't blow up trying * to allocate space for an immensely-large packet. */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("toshiba: File has %u-byte packet, bigger than maximum of %u", pkt_len, WTAP_MAX_PACKET_SIZE); return FALSE; } phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; phdr->ts.secs = hr * 3600 + min * 60 + sec; phdr->ts.nsecs = csec * 10000000; phdr->caplen = pkt_len; phdr->len = pkt_len; switch (channel[0]) { case 'B': phdr->pkt_encap = WTAP_ENCAP_ISDN; pseudo_header->isdn.uton = (direction[0] == 'T'); pseudo_header->isdn.channel = (guint8) strtol(&channel[1], NULL, 10); break; case 'D': phdr->pkt_encap = WTAP_ENCAP_ISDN; pseudo_header->isdn.uton = (direction[0] == 'T'); pseudo_header->isdn.channel = 0; break; default: phdr->pkt_encap = WTAP_ENCAP_ETHERNET; /* XXX - is there an FCS in the frame? */ pseudo_header->eth.fcs_len = -1; break; } /* Make sure we have enough room for the packet */ ws_buffer_assure_space(buf, pkt_len); pd = ws_buffer_start_ptr(buf); /* Calculate the number of hex dump lines, each * containing 16 bytes of data */ hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0); for (i = 0; i < hex_lines; i++) { if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } if (!parse_single_hex_dump_line(line, pd, i * 16)) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("toshiba: hex dump not valid"); return FALSE; } } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Don't treat the packet length as unsigned. The scanf family of functions are as annoyingly bad at handling unsigned numbers as strtoul() is - both of them are perfectly willing to accept a value beginning with a negative sign as an unsigned value. When using strtoul(), you can compensate for this by explicitly checking for a '-' as the first character of the string, but you can't do that with sscanf(). So revert to having pkt_len be signed, and scanning it with %d, but check for a negative value and fail if we see a negative value. Bug: 12394 Change-Id: I4b19b95f2e1ffc96dac5c91bff6698c246f52007 Reviewed-on: https://code.wireshark.org/review/15230 Reviewed-by: Guy Harris <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf, char *line, int *err, gchar **err_info) { union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header; int num_items_scanned; int yy, mm, dd, hr, min, sec, csec; guint pkt_len; int pro, off, pri, rm, error; guint code1, code2; char if_name[COSINE_MAX_IF_NAME_LEN] = "", direction[6] = ""; struct tm tm; guint8 *pd; int i, hex_lines, n, caplen = 0; if (sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d:", &yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) { /* appears to be output to a control blade */ num_items_scanned = sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", &yy, &mm, &dd, &hr, &min, &sec, &csec, direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 17) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: purported control blade line doesn't have code values"); return FALSE; } } else { /* appears to be output to PE */ num_items_scanned = sscanf(line, "%5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 10) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: header line is neither control blade nor PE output"); return FALSE; } yy = mm = dd = hr = min = sec = csec = 0; } if (pkt_len > WTAP_MAX_PACKET_SIZE) { /* * Probably a corrupt capture file; don't blow up trying * to allocate space for an immensely-large packet. */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("cosine: File has %u-byte packet, bigger than maximum of %u", pkt_len, WTAP_MAX_PACKET_SIZE); return FALSE; } phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; tm.tm_year = yy - 1900; tm.tm_mon = mm - 1; tm.tm_mday = dd; tm.tm_hour = hr; tm.tm_min = min; tm.tm_sec = sec; tm.tm_isdst = -1; phdr->ts.secs = mktime(&tm); phdr->ts.nsecs = csec * 10000000; phdr->len = pkt_len; /* XXX need to handle other encapsulations like Cisco HDLC, Frame Relay and ATM */ if (strncmp(if_name, "TEST:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_TEST; } else if (strncmp(if_name, "PPoATM:", 7) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoATM; } else if (strncmp(if_name, "PPoFR:", 6) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoFR; } else if (strncmp(if_name, "ATM:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ATM; } else if (strncmp(if_name, "FR:", 3) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_FR; } else if (strncmp(if_name, "HDLC:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_HDLC; } else if (strncmp(if_name, "PPP:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPP; } else if (strncmp(if_name, "ETH:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ETH; } else { pseudo_header->cosine.encap = COSINE_ENCAP_UNKNOWN; } if (strncmp(direction, "l2-tx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_TX; } else if (strncmp(direction, "l2-rx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_RX; } g_strlcpy(pseudo_header->cosine.if_name, if_name, COSINE_MAX_IF_NAME_LEN); pseudo_header->cosine.pro = pro; pseudo_header->cosine.off = off; pseudo_header->cosine.pri = pri; pseudo_header->cosine.rm = rm; pseudo_header->cosine.err = error; /* Make sure we have enough room for the packet */ ws_buffer_assure_space(buf, pkt_len); pd = ws_buffer_start_ptr(buf); /* Calculate the number of hex dump lines, each * containing 16 bytes of data */ hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0); for (i = 0; i < hex_lines; i++) { if (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } if (empty_line(line)) { break; } if ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: hex dump line doesn't have 16 numbers"); return FALSE; } caplen += n; } phdr->caplen = caplen; return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Don't treat the packet length as unsigned. The scanf family of functions are as annoyingly bad at handling unsigned numbers as strtoul() is - both of them are perfectly willing to accept a value beginning with a negative sign as an unsigned value. When using strtoul(), you can compensate for this by explicitly checking for a '-' as the first character of the string, but you can't do that with sscanf(). So revert to having pkt_len be signed, and scanning it with %d, but check for a negative value and fail if we see a negative value. Bug: 12395 Change-Id: I43b458a73b0934e9a5c2c89d34eac5a8f21a7455 Reviewed-on: https://code.wireshark.org/review/15223 Reviewed-by: Guy Harris <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parse_cosine_rec_hdr(struct wtap_pkthdr *phdr, const char *line, int *err, gchar **err_info) { union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header; int num_items_scanned; int yy, mm, dd, hr, min, sec, csec, pkt_len; int pro, off, pri, rm, error; guint code1, code2; char if_name[COSINE_MAX_IF_NAME_LEN] = "", direction[6] = ""; struct tm tm; if (sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d:", &yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) { /* appears to be output to a control blade */ num_items_scanned = sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", &yy, &mm, &dd, &hr, &min, &sec, &csec, direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 17) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: purported control blade line doesn't have code values"); return -1; } } else { /* appears to be output to PE */ num_items_scanned = sscanf(line, "%5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 10) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: header line is neither control blade nor PE output"); return -1; } yy = mm = dd = hr = min = sec = csec = 0; } phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; tm.tm_year = yy - 1900; tm.tm_mon = mm - 1; tm.tm_mday = dd; tm.tm_hour = hr; tm.tm_min = min; tm.tm_sec = sec; tm.tm_isdst = -1; phdr->ts.secs = mktime(&tm); phdr->ts.nsecs = csec * 10000000; phdr->len = pkt_len; /* XXX need to handle other encapsulations like Cisco HDLC, Frame Relay and ATM */ if (strncmp(if_name, "TEST:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_TEST; } else if (strncmp(if_name, "PPoATM:", 7) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoATM; } else if (strncmp(if_name, "PPoFR:", 6) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoFR; } else if (strncmp(if_name, "ATM:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ATM; } else if (strncmp(if_name, "FR:", 3) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_FR; } else if (strncmp(if_name, "HDLC:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_HDLC; } else if (strncmp(if_name, "PPP:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPP; } else if (strncmp(if_name, "ETH:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ETH; } else { pseudo_header->cosine.encap = COSINE_ENCAP_UNKNOWN; } if (strncmp(direction, "l2-tx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_TX; } else if (strncmp(direction, "l2-rx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_RX; } g_strlcpy(pseudo_header->cosine.if_name, if_name, COSINE_MAX_IF_NAME_LEN); pseudo_header->cosine.pro = pro; pseudo_header->cosine.off = off; pseudo_header->cosine.pri = pri; pseudo_header->cosine.rm = rm; pseudo_header->cosine.err = error; return pkt_len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix packet length handling. Treat the packet length as unsigned - it shouldn't be negative in the file. If it is, that'll probably cause the sscanf to fail, so we'll report the file as bad. Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to allocate a huge amount of memory, just as we do in other file readers. Use the now-validated packet size as the length in ws_buffer_assure_space(), so we are certain to have enough space, and don't allocate too much space. Merge the header and packet data parsing routines while we're at it. Bug: 12395 Change-Id: Ia70f33b71ff28451190fcf144c333fd1362646b2 Reviewed-on: https://code.wireshark.org/review/15172 Reviewed-by: Guy Harris <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parse_cosine_hex_dump(FILE_T fh, struct wtap_pkthdr *phdr, int pkt_len, Buffer* buf, int *err, gchar **err_info) { guint8 *pd; gchar line[COSINE_LINE_LENGTH]; int i, hex_lines, n, caplen = 0; /* Make sure we have enough room for the packet */ ws_buffer_assure_space(buf, COSINE_MAX_PACKET_LEN); pd = ws_buffer_start_ptr(buf); /* Calculate the number of hex dump lines, each * containing 16 bytes of data */ hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0); for (i = 0; i < hex_lines; i++) { if (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } if (empty_line(line)) { break; } if ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: hex dump line doesn't have 16 numbers"); return FALSE; } caplen += n; } phdr->caplen = caplen; return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix packet length handling. Treat the packet length as unsigned - it shouldn't be negative in the file. If it is, that'll probably cause the sscanf to fail, so we'll report the file as bad. Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to allocate a huge amount of memory, just as we do in other file readers. Use the now-validated packet size as the length in ws_buffer_assure_space(), so we are certain to have enough space, and don't allocate too much space. Merge the header and packet data parsing routines while we're at it. Bug: 12395 Change-Id: Ia70f33b71ff28451190fcf144c333fd1362646b2 Reviewed-on: https://code.wireshark.org/review/15172 Reviewed-by: Guy Harris <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parse_netscreen_rec_hdr(struct wtap_pkthdr *phdr, const char *line, char *cap_int, gboolean *cap_dir, char *cap_dst, int *err, gchar **err_info) { int sec; int dsec, pkt_len; char direction[2]; char cap_src[13]; phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; if (sscanf(line, "%9d.%9d: %15[a-z0-9/:.-](%1[io]) len=%9d:%12s->%12s/", &sec, &dsec, cap_int, direction, &pkt_len, cap_src, cap_dst) < 5) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: Can't parse packet-header"); return -1; } *cap_dir = (direction[0] == 'o' ? NETSCREEN_EGRESS : NETSCREEN_INGRESS); phdr->ts.secs = sec; phdr->ts.nsecs = dsec * 100000000; phdr->len = pkt_len; return pkt_len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix packet length handling. Treat the packet length as unsigned - it shouldn't be negative in the file. If it is, that'll probably cause the sscanf to fail, so we'll report the file as bad. Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to allocate a huge amount of memory, just as we do in other file readers. Use the now-validated packet size as the length in ws_buffer_assure_space(), so we are certain to have enough space, and don't allocate too much space. Merge the header and packet data parsing routines while we're at it. Bug: 12396 Change-Id: I7f981f9cdcbea7ecdeb88bfff2f12d875de2244f Reviewed-on: https://code.wireshark.org/review/15176 Reviewed-by: Guy Harris <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: netscreen_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info) { int pkt_len; char line[NETSCREEN_LINE_LENGTH]; char cap_int[NETSCREEN_MAX_INT_NAME_LENGTH]; gboolean cap_dir; char cap_dst[13]; if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1) { return FALSE; } if (file_gets(line, NETSCREEN_LINE_LENGTH, wth->random_fh) == NULL) { *err = file_error(wth->random_fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } pkt_len = parse_netscreen_rec_hdr(phdr, line, cap_int, &cap_dir, cap_dst, err, err_info); if (pkt_len == -1) return FALSE; if (!parse_netscreen_hex_dump(wth->random_fh, pkt_len, cap_int, cap_dst, phdr, buf, err, err_info)) return FALSE; return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix packet length handling. Treat the packet length as unsigned - it shouldn't be negative in the file. If it is, that'll probably cause the sscanf to fail, so we'll report the file as bad. Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to allocate a huge amount of memory, just as we do in other file readers. Use the now-validated packet size as the length in ws_buffer_assure_space(), so we are certain to have enough space, and don't allocate too much space. Merge the header and packet data parsing routines while we're at it. Bug: 12396 Change-Id: I7f981f9cdcbea7ecdeb88bfff2f12d875de2244f Reviewed-on: https://code.wireshark.org/review/15176 Reviewed-by: Guy Harris <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: dissect_ppi(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { proto_tree *ppi_tree = NULL, *ppi_flags_tree = NULL, *seg_tree = NULL, *ampdu_tree = NULL; proto_tree *agg_tree = NULL; proto_item *ti = NULL; tvbuff_t *next_tvb; int offset = 0; guint version, flags; gint tot_len, data_len; guint data_type; guint32 dlt; guint32 n_ext_flags = 0; guint32 ampdu_id = 0; fragment_head *fd_head = NULL; fragment_item *ft_fdh = NULL; gint mpdu_count = 0; gchar *mpdu_str; gboolean first_mpdu = TRUE; guint last_frame = 0; gint len_remain, /*pad_len = 0,*/ ampdu_len = 0; struct ieee_802_11_phdr phdr; col_set_str(pinfo->cinfo, COL_PROTOCOL, "PPI"); col_clear(pinfo->cinfo, COL_INFO); version = tvb_get_guint8(tvb, offset); flags = tvb_get_guint8(tvb, offset + 1); tot_len = tvb_get_letohs(tvb, offset+2); dlt = tvb_get_letohl(tvb, offset+4); col_add_fstr(pinfo->cinfo, COL_INFO, "PPI version %u, %u bytes", version, tot_len); /* Dissect the packet */ if (tree) { ti = proto_tree_add_protocol_format(tree, proto_ppi, tvb, 0, tot_len, "PPI version %u, %u bytes", version, tot_len); ppi_tree = proto_item_add_subtree(ti, ett_ppi_pph); proto_tree_add_item(ppi_tree, hf_ppi_head_version, tvb, offset, 1, ENC_LITTLE_ENDIAN); ti = proto_tree_add_item(ppi_tree, hf_ppi_head_flags, tvb, offset + 1, 1, ENC_LITTLE_ENDIAN); ppi_flags_tree = proto_item_add_subtree(ti, ett_ppi_flags); proto_tree_add_item(ppi_flags_tree, hf_ppi_head_flag_alignment, tvb, offset + 1, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(ppi_flags_tree, hf_ppi_head_flag_reserved, tvb, offset + 1, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(ppi_tree, hf_ppi_head_len, tvb, offset + 2, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(ppi_tree, hf_ppi_head_dlt, tvb, offset + 4, 4, ENC_LITTLE_ENDIAN); } tot_len -= PPI_V0_HEADER_LEN; offset += 8; /* We don't have any 802.11 metadata yet. */ memset(&phdr, 0, sizeof(phdr)); phdr.fcs_len = -1; phdr.decrypted = FALSE; phdr.datapad = FALSE; phdr.phy = PHDR_802_11_PHY_UNKNOWN; phdr.presence_flags = 0; while (tot_len > 0) { data_type = tvb_get_letohs(tvb, offset); data_len = tvb_get_letohs(tvb, offset + 2) + 4; tot_len -= data_len; switch (data_type) { case PPI_80211_COMMON: dissect_80211_common(tvb, pinfo, ppi_tree, offset, data_len, &phdr); break; case PPI_80211N_MAC: dissect_80211n_mac(tvb, pinfo, ppi_tree, offset, data_len, TRUE, &n_ext_flags, &ampdu_id, &phdr); break; case PPI_80211N_MAC_PHY: dissect_80211n_mac_phy(tvb, pinfo, ppi_tree, offset, data_len, &n_ext_flags, &ampdu_id, &phdr); break; case PPI_SPECTRUM_MAP: ADD_BASIC_TAG(hf_spectrum_map); break; case PPI_PROCESS_INFO: ADD_BASIC_TAG(hf_process_info); break; case PPI_CAPTURE_INFO: ADD_BASIC_TAG(hf_capture_info); break; case PPI_AGGREGATION_EXTENSION: dissect_aggregation_extension(tvb, pinfo, ppi_tree, offset, data_len); break; case PPI_8023_EXTENSION: dissect_8023_extension(tvb, pinfo, ppi_tree, offset, data_len); break; case PPI_GPS_INFO: if (ppi_gps_handle == NULL) { proto_tree_add_item(ppi_tree, hf_ppi_gps, tvb, offset, data_len, ENC_NA); } else /* we found a suitable dissector */ { /* skip over the ppi_fieldheader, and pass it off to the dedicated GPS dissetor */ next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1); call_dissector(ppi_gps_handle, next_tvb, pinfo, ppi_tree); } break; case PPI_VECTOR_INFO: if (ppi_vector_handle == NULL) { proto_tree_add_item(ppi_tree, hf_ppi_vector, tvb, offset, data_len, ENC_NA); } else /* we found a suitable dissector */ { /* skip over the ppi_fieldheader, and pass it off to the dedicated VECTOR dissetor */ next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1); call_dissector(ppi_vector_handle, next_tvb, pinfo, ppi_tree); } break; case PPI_SENSOR_INFO: if (ppi_sensor_handle == NULL) { proto_tree_add_item(ppi_tree, hf_ppi_harris, tvb, offset, data_len, ENC_NA); } else /* we found a suitable dissector */ { /* skip over the ppi_fieldheader, and pass it off to the dedicated SENSOR dissetor */ next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1); call_dissector(ppi_sensor_handle, next_tvb, pinfo, ppi_tree); } break; case PPI_ANTENNA_INFO: if (ppi_antenna_handle == NULL) { proto_tree_add_item(ppi_tree, hf_ppi_antenna, tvb, offset, data_len, ENC_NA); } else /* we found a suitable dissector */ { /* skip over the ppi_fieldheader, and pass it off to the dedicated ANTENNA dissetor */ next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1); call_dissector(ppi_antenna_handle, next_tvb, pinfo, ppi_tree); } break; case FNET_PRIVATE: if (ppi_fnet_handle == NULL) { proto_tree_add_item(ppi_tree, hf_ppi_fnet, tvb, offset, data_len, ENC_NA); } else /* we found a suitable dissector */ { /* skip over the ppi_fieldheader, and pass it off to the dedicated FNET dissetor */ next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1); call_dissector(ppi_fnet_handle, next_tvb, pinfo, ppi_tree); } break; default: proto_tree_add_item(ppi_tree, hf_ppi_reserved, tvb, offset, data_len, ENC_NA); } offset += data_len; if (IS_PPI_FLAG_ALIGN(flags)){ offset += PADDING4(offset); } } if (ppi_ampdu_reassemble && DOT11N_IS_AGGREGATE(n_ext_flags)) { len_remain = tvb_captured_length_remaining(tvb, offset); #if 0 /* XXX: pad_len never actually used ?? */ if (DOT11N_MORE_AGGREGATES(n_ext_flags)) { pad_len = PADDING4(len_remain); } #endif pinfo->fragmented = TRUE; /* Make sure we aren't going to go past AGGREGATE_MAX * and caclulate our full A-MPDU length */ fd_head = fragment_get(&ampdu_reassembly_table, pinfo, ampdu_id, NULL); while (fd_head) { ampdu_len += fd_head->len + PADDING4(fd_head->len) + 4; fd_head = fd_head->next; } if (ampdu_len > AGGREGATE_MAX) { if (tree) { proto_tree_add_expert_format(ppi_tree, pinfo, &ei_ppi_invalid_length, tvb, offset, -1, "Aggregate length greater than maximum (%u)", AGGREGATE_MAX); THROW(ReportedBoundsError); } else { return; } } /* * Note that we never actually reassemble our A-MPDUs. Doing * so would require prepending each MPDU with an A-MPDU delimiter * and appending it with padding, only to hand it off to some * routine which would un-do the work we just did. We're using * the reassembly code to track MPDU sizes and frame numbers. */ /*??fd_head = */fragment_add_seq_next(&ampdu_reassembly_table, tvb, offset, pinfo, ampdu_id, NULL, len_remain, TRUE); pinfo->fragmented = TRUE; /* Do reassembly? */ fd_head = fragment_get(&ampdu_reassembly_table, pinfo, ampdu_id, NULL); /* Show our fragments */ if (fd_head && tree) { ft_fdh = fd_head; /* List our fragments */ seg_tree = proto_tree_add_subtree_format(ppi_tree, tvb, offset, -1, ett_ampdu_segments, &ti, "A-MPDU (%u bytes w/hdrs):", ampdu_len); PROTO_ITEM_SET_GENERATED(ti); while (ft_fdh) { if (ft_fdh->tvb_data && ft_fdh->len) { last_frame = ft_fdh->frame; if (!first_mpdu) proto_item_append_text(ti, ","); first_mpdu = FALSE; proto_item_append_text(ti, " #%u(%u)", ft_fdh->frame, ft_fdh->len); proto_tree_add_uint_format(seg_tree, hf_ampdu_segment, tvb, 0, 0, last_frame, "Frame: %u (%u byte%s)", last_frame, ft_fdh->len, plurality(ft_fdh->len, "", "s")); } ft_fdh = ft_fdh->next; } if (last_frame && last_frame != pinfo->fd->num) proto_tree_add_uint(seg_tree, hf_ampdu_reassembled_in, tvb, 0, 0, last_frame); } if (fd_head && !DOT11N_MORE_AGGREGATES(n_ext_flags)) { if (tree) { ti = proto_tree_add_protocol_format(tree, proto_get_id_by_filter_name("wlan_aggregate"), tvb, 0, tot_len, "IEEE 802.11 Aggregate MPDU"); agg_tree = proto_item_add_subtree(ti, ett_ampdu); } while (fd_head) { if (fd_head->tvb_data && fd_head->len) { mpdu_count++; mpdu_str = wmem_strdup_printf(wmem_packet_scope(), "MPDU #%d", mpdu_count); next_tvb = tvb_new_chain(tvb, fd_head->tvb_data); add_new_data_source(pinfo, next_tvb, mpdu_str); ampdu_tree = proto_tree_add_subtree(agg_tree, next_tvb, 0, -1, ett_ampdu_segment, NULL, mpdu_str); call_dissector_with_data(ieee80211_radio_handle, next_tvb, pinfo, ampdu_tree, &phdr); } fd_head = fd_head->next; } proto_tree_add_uint(seg_tree, hf_ampdu_count, tvb, 0, 0, mpdu_count); pinfo->fragmented=FALSE; } else { next_tvb = tvb_new_subset_remaining(tvb, offset); col_set_str(pinfo->cinfo, COL_PROTOCOL, "IEEE 802.11n"); col_set_str(pinfo->cinfo, COL_INFO, "Unreassembled A-MPDU data"); call_dissector(data_handle, next_tvb, pinfo, tree); } return; } next_tvb = tvb_new_subset_remaining(tvb, offset); /* * You can't just call an arbitrary subdissector based on a * LINKTYPE_ value, because they may expect a particular * pseudo-header to be passed to them. * * So we look for LINKTYPE_IEEE802_11, which is 105, and, if * that's what the LINKTYPE_ value is, pass it a pointer * to a struct ieee_802_11_phdr; otherwise, we pass it * a null pointer - if it actually matters, we need to * construct the appropriate pseudo-header and pass that. */ if (dlt == 105) { /* LINKTYPE_IEEE802_11 */ call_dissector_with_data(ieee80211_radio_handle, next_tvb, pinfo, tree, &phdr); } else { /* Everything else. This will pass a NULL data argument. */ dissector_try_uint(wtap_encap_dissector_table, wtap_pcap_encap_to_wtap_encap(dlt), next_tvb, pinfo, tree); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'The WTAP_ENCAP_ETHERNET dissector needs to be passed a struct eth_phdr. We now require that. Make it so. Bug: 12440 Change-Id: Iffee520976b013800699bde3c6092a3e86be0d76 Reviewed-on: https://code.wireshark.org/review/15424 Reviewed-by: Guy Harris <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: dissect_pktap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { proto_tree *pktap_tree = NULL; proto_item *ti = NULL; tvbuff_t *next_tvb; int offset = 0; guint32 pkt_len, rectype, dlt; col_set_str(pinfo->cinfo, COL_PROTOCOL, "PKTAP"); col_clear(pinfo->cinfo, COL_INFO); pkt_len = tvb_get_letohl(tvb, offset); col_add_fstr(pinfo->cinfo, COL_INFO, "PKTAP, %u byte header", pkt_len); /* Dissect the packet */ ti = proto_tree_add_item(tree, proto_pktap, tvb, offset, pkt_len, ENC_NA); pktap_tree = proto_item_add_subtree(ti, ett_pktap); proto_tree_add_item(pktap_tree, hf_pktap_hdrlen, tvb, offset, 4, ENC_LITTLE_ENDIAN); if (pkt_len < MIN_PKTAP_HDR_LEN) { proto_tree_add_expert(tree, pinfo, &ei_pktap_hdrlen_too_short, tvb, offset, 4); return; } offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_rectype, tvb, offset, 4, ENC_LITTLE_ENDIAN); rectype = tvb_get_letohl(tvb, offset); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_dlt, tvb, offset, 4, ENC_LITTLE_ENDIAN); dlt = tvb_get_letohl(tvb, offset); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_ifname, tvb, offset, 24, ENC_ASCII|ENC_NA); offset += 24; proto_tree_add_item(pktap_tree, hf_pktap_flags, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_pfamily, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_llhdrlen, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_lltrlrlen, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_pid, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_cmdname, tvb, offset, 20, ENC_UTF_8|ENC_NA); offset += 20; proto_tree_add_item(pktap_tree, hf_pktap_svc_class, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_iftype, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; proto_tree_add_item(pktap_tree, hf_pktap_ifunit, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; proto_tree_add_item(pktap_tree, hf_pktap_epid, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_ecmdname, tvb, offset, 20, ENC_UTF_8|ENC_NA); /*offset += 20;*/ if (rectype == PKT_REC_PACKET) { next_tvb = tvb_new_subset_remaining(tvb, pkt_len); dissector_try_uint(wtap_encap_dissector_table, wtap_pcap_encap_to_wtap_encap(dlt), next_tvb, pinfo, tree); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'The WTAP_ENCAP_ETHERNET dissector needs to be passed a struct eth_phdr. We now require that. Make it so. Bug: 12440 Change-Id: Iffee520976b013800699bde3c6092a3e86be0d76 Reviewed-on: https://code.wireshark.org/review/15424 Reviewed-by: Guy Harris <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parse_wbxml_attribute_list_defined (proto_tree *tree, tvbuff_t *tvb, guint32 offset, guint32 str_tbl, guint8 level, guint8 *codepage_attr, const wbxml_decoding *map) { guint32 tvb_len = tvb_reported_length (tvb); guint32 off = offset; guint32 len; guint str_len; guint32 ent; guint32 idx; guint8 peek; guint8 attr_save_known = 0; /* Will contain peek & 0x3F (attr identity) */ const char *attr_save_literal = NULL; /* Will contain the LITERAL attr identity */ DebugLog(("parse_wbxml_attr_defined (level = %u, offset = %u)\n", level, offset)); /* Parse attributes */ while (off < tvb_len) { peek = tvb_get_guint8 (tvb, off); DebugLog(("ATTR: (top of while) level = %3u, peek = 0x%02X, " "off = %u, tvb_len = %u\n", level, peek, off, tvb_len)); if ((peek & 0x3F) < 5) switch (peek) { /* Global tokens in state = ATTR */ case 0x00: /* SWITCH_PAGE */ *codepage_attr = tvb_get_guint8 (tvb, off+1); proto_tree_add_text (tree, tvb, off, 2, " | Attr | A -->%3d " "| SWITCH_PAGE (Attr code page) |", *codepage_attr); off += 2; break; case 0x01: /* END */ /* BEWARE * The Attribute END token means either ">" or "/>" * and as a consequence both must be treated separately. * This is done in the TAG state parser. */ off++; DebugLog(("ATTR: level = %u, Return: len = %u\n", level, off - offset)); return (off - offset); case 0x02: /* ENTITY */ ent = tvb_get_guintvar (tvb, off+1, &len); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| ENTITY " "| %s'&#%u;'", level, *codepage_attr, Indent (level), ent); off += 1+len; break; case 0x03: /* STR_I */ len = tvb_strsize (tvb, off+1); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| STR_I (Inline string) " "| %s\'%s\'", level, *codepage_attr, Indent (level), tvb_format_text (tvb, off+1, len-1)); off += 1+len; break; case 0x04: /* LITERAL */ /* ALWAYS means the start of a new attribute, * and may only contain the NAME of the attribute. */ idx = tvb_get_guintvar (tvb, off+1, &len); str_len = tvb_strsize (tvb, str_tbl+idx); attr_save_known = 0; attr_save_literal = tvb_format_text (tvb, str_tbl+idx, str_len-1); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| LITERAL (Literal Attribute) " "| %s<%s />", level, *codepage_attr, Indent (level), attr_save_literal); off += 1+len; break; case 0x40: /* EXT_I_0 */ case 0x41: /* EXT_I_1 */ case 0x42: /* EXT_I_2 */ /* Extension tokens */ len = tvb_strsize (tvb, off+1); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| EXT_I_%1x (Extension Token) " "| %s(%s: \'%s\')", level, *codepage_attr, peek & 0x0f, Indent (level), map_token (map->global, 0, peek), tvb_format_text (tvb, off+1, len-1)); off += 1+len; break; /* 0x43 impossible in ATTR state */ /* 0x44 impossible in ATTR state */ case 0x80: /* EXT_T_0 */ case 0x81: /* EXT_T_1 */ case 0x82: /* EXT_T_2 */ /* Extension tokens */ idx = tvb_get_guintvar (tvb, off+1, &len); { char *s; if (map->ext_t[peek & 0x03]) s = (map->ext_t[peek & 0x03])(tvb, idx, str_tbl); else s = wmem_strdup_printf(wmem_packet_scope(), "EXT_T_%1x (%s)", peek & 0x03, map_token (map->global, 0, peek)); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| EXT_T_%1x (Extension Token) " "| %s%s)", level, *codepage_attr, peek & 0x0f, Indent (level), s); } off += 1+len; break; case 0x83: /* STR_T */ idx = tvb_get_guintvar (tvb, off+1, &len); str_len = tvb_strsize (tvb, str_tbl+idx); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| STR_T (Tableref string) " "| %s\'%s\'", level, *codepage_attr, Indent (level), tvb_format_text (tvb, str_tbl+idx, str_len-1)); off += 1+len; break; /* 0x84 impossible in ATTR state */ case 0xC0: /* EXT_0 */ case 0xC1: /* EXT_1 */ case 0xC2: /* EXT_2 */ /* Extension tokens */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| EXT_%1x (Extension Token) " "| %s(%s)", level, *codepage_attr, peek & 0x0f, Indent (level), map_token (map->global, 0, peek)); off++; break; case 0xC3: /* OPAQUE - WBXML 1.1 and newer */ if (tvb_get_guint8 (tvb, 0)) { /* WBXML 1.x (x > 0) */ char *str; if (attr_save_known) { /* Knwon attribute */ if (map->opaque_binary_attr) { str = map->opaque_binary_attr(tvb, off + 1, attr_save_known, *codepage_attr, &len); } else { str = default_opaque_binary_attr(tvb, off + 1, attr_save_known, *codepage_attr, &len); } } else { /* lITERAL attribute */ if (map->opaque_literal_tag) { str = map->opaque_literal_attr(tvb, off + 1, attr_save_literal, *codepage_attr, &len); } else { str = default_opaque_literal_attr(tvb, off + 1, attr_save_literal, *codepage_attr, &len); } } proto_tree_add_text (tree, tvb, off, 1 + len, " %3d | Attr | A %3d " "| OPAQUE (Opaque data) " "| %s%s", level, *codepage_attr, Indent (level), str); off += 1 + len; } else { /* WBXML 1.0 - RESERVED_2 token (invalid) */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| RESERVED_2 (Invalid Token!) " "| WBXML 1.0 parsing stops here.", level, *codepage_attr); /* Stop processing as it is impossible to parse now */ off = tvb_len; DebugLog(("ATTR: level = %u, Return: len = %u\n", level, off - offset)); return (off - offset); } break; /* 0xC4 impossible in ATTR state */ default: proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| %-10s (Invalid Token!) " "| WBXML parsing stops here.", level, *codepage_attr, val_to_str_ext (peek, &vals_wbxml1x_global_tokens_ext, "(unknown 0x%x)")); /* Move to end of buffer */ off = tvb_len; break; } else { /* Known atribute token */ if (peek & 0x80) { /* attrValue */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| Known attrValue 0x%02X " "| %s%s", level, *codepage_attr, peek & 0x7f, Indent (level), map_token (map->attrValue, *codepage_attr, peek)); off++; } else { /* attrStart */ attr_save_known = peek & 0x7f; proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| Known attrStart 0x%02X " "| %s%s", level, *codepage_attr, attr_save_known, Indent (level), map_token (map->attrStart, *codepage_attr, peek)); off++; } } } /* End WHILE */ DebugLog(("ATTR: level = %u, Return: len = %u (end of function body)\n", level, off - offset)); return (off - offset); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-119', 'CWE-787'], 'message': 'WBXML: add a basic sanity check for offset overflow This is a naive approach allowing to detact that something went wrong, without the need to replace all proto_tree_add_text() calls as what was done in master-2.0 branch. Bug: 12408 Change-Id: Ia14905005e17ae322c2fc639ad5e491fa08b0108 Reviewed-on: https://code.wireshark.org/review/15310 Reviewed-by: Michael Mann <[email protected]> Reviewed-by: Pascal Quantin <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parse_wbxml_tag (proto_tree *tree, tvbuff_t *tvb, guint32 offset, guint32 str_tbl, guint8 *level, guint8 *codepage_stag, guint8 *codepage_attr) { guint32 tvb_len = tvb_reported_length (tvb); guint32 off = offset; guint32 len; guint str_len; guint32 ent; guint32 idx; guint8 peek; guint32 tag_len; /* Length of the idx (uintvar) from a LITERAL tag */ guint8 tag_save_known = 0; /* Will contain peek & 0x3F (tag identity) */ guint8 tag_new_known = 0; /* Will contain peek & 0x3F (tag identity) */ const char *tag_save_literal; /* Will contain the LITERAL tag identity */ const char *tag_new_literal; /* Will contain the LITERAL tag identity */ char *tag_save_buf = NULL; /* Will contain "tag_0x%02X" */ char *tag_new_buf = NULL; /* Will contain "tag_0x%02X" */ guint8 parsing_tag_content = FALSE; /* Are we parsing content from a tag with content: <x>Content</x> The initial state is FALSE. This state will trigger recursion. */ tag_save_literal = NULL; /* Prevents compiler warning */ DebugLog(("parse_wbxml_tag (level = %u, offset = %u)\n", *level, offset)); while (off < tvb_len) { peek = tvb_get_guint8 (tvb, off); DebugLog(("STAG: (top of while) level = %3u, peek = 0x%02X, off = %u, tvb_len = %u\n", *level, peek, off, tvb_len)); if ((peek & 0x3F) < 4) switch (peek) { /* Global tokens in state = STAG but not the LITERAL tokens */ case 0x00: /* SWITCH_PAGE */ *codepage_stag = tvb_get_guint8 (tvb, off+1); proto_tree_add_text (tree, tvb, off, 2, " | Tag | T -->%3d " "| SWITCH_PAGE (Tag code page) " "|", *codepage_stag); off += 2; break; case 0x01: /* END: only possible for Tag with Content */ if (tag_save_known) { /* Known TAG */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| END (Known Tag 0x%02X) " "| %s</%s>", *level, *codepage_stag, tag_save_known, Indent (*level), tag_save_literal); /* We already looked it up! */ } else { /* Literal TAG */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| END (Literal Tag) " "| %s</%s>", *level, *codepage_stag, Indent (*level), tag_save_literal ? tag_save_literal : ""); } (*level)--; off++; /* Reset code page: not needed as return from recursion */ DebugLog(("STAG: level = %u, Return: len = %u\n", *level, off - offset)); return (off - offset); case 0x02: /* ENTITY */ ent = tvb_get_guintvar (tvb, off+1, &len); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| ENTITY " "| %s'&#%u;'", *level, *codepage_stag, Indent (*level), ent); off += 1+len; break; case 0x03: /* STR_I */ len = tvb_strsize (tvb, off+1); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| STR_I (Inline string) " "| %s\'%s\'", *level, *codepage_stag, Indent(*level), tvb_format_text (tvb, off+1, len-1)); off += 1+len; break; case 0x40: /* EXT_I_0 */ case 0x41: /* EXT_I_1 */ case 0x42: /* EXT_I_2 */ /* Extension tokens */ len = tvb_strsize (tvb, off+1); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| EXT_I_%1x (Extension Token) " "| %s(Inline string extension: \'%s\')", *level, *codepage_stag, peek & 0x0f, Indent (*level), tvb_format_text (tvb, off+1, len-1)); off += 1+len; break; case 0x43: /* PI */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| PI (XML Processing Instruction) " "| %s<?xml", *level, *codepage_stag, Indent (*level)); len = parse_wbxml_attribute_list (tree, tvb, off, str_tbl, *level, codepage_attr); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (PI) " "| %s?>", *level, *codepage_stag, Indent (*level)); break; case 0x80: /* EXT_T_0 */ case 0x81: /* EXT_T_1 */ case 0x82: /* EXT_T_2 */ /* Extension tokens */ idx = tvb_get_guintvar (tvb, off+1, &len); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| EXT_T_%1x (Extension Token) " "| %s(Extension Token, integer value: %u)", *level, *codepage_stag, peek & 0x0f, Indent (*level), idx); off += 1+len; break; case 0x83: /* STR_T */ idx = tvb_get_guintvar (tvb, off+1, &len); str_len = tvb_strsize (tvb, str_tbl+idx); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| STR_T (Tableref string) " "| %s\'%s\'", *level, *codepage_stag, Indent (*level), tvb_format_text (tvb, str_tbl+idx, str_len-1)); off += 1+len; break; case 0xC0: /* EXT_0 */ case 0xC1: /* EXT_1 */ case 0xC2: /* EXT_2 */ /* Extension tokens */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| EXT_%1x (Extension Token) " "| %s(Single-byte extension)", *level, *codepage_stag, peek & 0x0f, Indent (*level)); off++; break; case 0xC3: /* OPAQUE - WBXML 1.1 and newer */ if (tvb_get_guint8 (tvb, 0)) { /* WBXML 1.x (x > 0) */ idx = tvb_get_guintvar (tvb, off+1, &len); proto_tree_add_text (tree, tvb, off, 1 + len + idx, " %3d | Tag | T %3d " "| OPAQUE (Opaque data) " "| %s(%d bytes of opaque data)", *level, *codepage_stag, Indent (*level), idx); off += 1+len+idx; } else { /* WBXML 1.0 - RESERVED_2 token (invalid) */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| RESERVED_2 (Invalid Token!) " "| WBXML 1.0 parsing stops here.", *level, *codepage_stag); /* Stop processing as it is impossible to parse now */ off = tvb_len; DebugLog(("STAG: level = %u, Return: len = %u\n", *level, off - offset)); return (off - offset); } break; /* No default clause, as all cases have been treated */ } else { /* LITERAL or Known TAG */ /* We must store the initial tag, and also retrieve the new tag. * For efficiency reasons, we store the literal tag representation * for known tags too, so we can easily close the tag without the * need of a new lookup and avoiding storage of token codepage. * * There are 4 possibilities: * * 1. Known tag followed by a known tag * 2. Known tag followed by a LITERAL tag * 3. LITERAL tag followed by Known tag * 4. LITERAL tag followed by LITERAL tag */ /* Store the new tag */ tag_len = 0; if ((peek & 0x3F) == 4) { /* LITERAL */ DebugLog(("STAG: LITERAL tag (peek = 0x%02X, off = %u)" " - TableRef follows!\n", peek, off)); idx = tvb_get_guintvar (tvb, off+1, &tag_len); str_len = tvb_strsize (tvb, str_tbl+idx); tag_new_literal = (const gchar*)tvb_get_ptr (tvb, str_tbl+idx, str_len); tag_new_known = 0; /* invalidate known tag_new */ } else { /* Known tag */ tag_new_known = peek & 0x3F; tag_new_buf=wmem_strdup_printf(wmem_packet_scope(), "Tag_0x%02X", tag_new_known); tag_new_literal = tag_new_buf; /* Stored looked up tag name string */ } /* Parsing of TAG starts HERE */ if (peek & 0x40) { /* Content present */ /* Content follows * [!] An explicit END token is expected in these cases! * ==> Recursion possible if we encounter a tag with content; * recursion will return at the explicit END token. */ if (parsing_tag_content) { /* Recurse */ DebugLog(("STAG: Tag in Tag - RECURSE! (off = %u)\n", off)); /* Do not process the attribute list: * recursion will take care of it */ (*level)++; len = parse_wbxml_tag (tree, tvb, off, str_tbl, level, codepage_stag, codepage_attr); off += len; } else { /* Now we will have content to parse */ /* Save the start tag so we can properly close it later. */ if ((peek & 0x3F) == 4) { /* Literal tag */ tag_save_literal = tag_new_literal; tag_save_known = 0; } else { /* Known tag */ tag_save_known = tag_new_known; tag_save_buf=wmem_strdup_printf(wmem_packet_scope(), "Tag_0x%02X", tag_new_known); tag_save_literal = tag_save_buf; /* The last statement avoids needless lookups */ } /* Process the attribute list if present */ if (peek & 0x80) { /* Content and Attribute list present */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02X (AC) " "| %s<%s", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL_AC (Literal tag) (AC) " "| %s<%s", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; } len = parse_wbxml_attribute_list (tree, tvb, off, str_tbl, *level, codepage_attr); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: " "len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (attribute list) " "| %s>", *level, *codepage_stag, Indent (*level)); } else { /* Content, no Attribute list */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02X (.C) " "| %s<%s>", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL_C (Literal Tag) (.C) " "| %s<%s>", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; } } /* The data that follows in the parsing process * represents content for the opening tag * we've just processed in the lines above. * Next time we encounter a tag with content: recurse */ parsing_tag_content = TRUE; DebugLog(("Tag in Tag - No recursion this time! " "(off = %u)\n", off)); } } else { /* No Content */ DebugLog(("<Tag/> in Tag - No recursion! (off = %u)\n", off)); (*level)++; if (peek & 0x80) { /* No Content, Attribute list present */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02X (A.) " "| %s<%s", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; len = parse_wbxml_attribute_list (tree, tvb, off, str_tbl, *level, codepage_attr); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: " "len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (Known Tag) " "| %s/>", *level, *codepage_stag, Indent (*level)); } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL_A (Literal Tag) (A.) " "| %s<%s", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; len = parse_wbxml_attribute_list (tree, tvb, off, str_tbl, *level, codepage_attr); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: " "len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (Literal Tag) " "| %s/>", *level, *codepage_stag, Indent (*level)); } } else { /* No Content, No Attribute list */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02x (..) " "| %s<%s />", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL (Literal Tag) (..) " "| %s<%s />", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; } } (*level)--; /* TODO: Do I have to reset code page here? */ } } /* if (tag & 0x3F) >= 5 */ } /* while */ DebugLog(("STAG: level = %u, Return: len = %u (end of function body)\n", *level, off - offset)); return (off - offset); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-119', 'CWE-787'], 'message': 'WBXML: add a basic sanity check for offset overflow This is a naive approach allowing to detact that something went wrong, without the need to replace all proto_tree_add_text() calls as what was done in master-2.0 branch. Bug: 12408 Change-Id: Ia14905005e17ae322c2fc639ad5e491fa08b0108 Reviewed-on: https://code.wireshark.org/review/15310 Reviewed-by: Michael Mann <[email protected]> Reviewed-by: Pascal Quantin <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ecryptfs_privileged_open(struct file **lower_file, struct dentry *lower_dentry, struct vfsmount *lower_mnt, const struct cred *cred) { struct ecryptfs_open_req req; int flags = O_LARGEFILE; int rc = 0; init_completion(&req.done); req.lower_file = lower_file; req.path.dentry = lower_dentry; req.path.mnt = lower_mnt; /* Corresponding dput() and mntput() are done when the * lower file is fput() when all eCryptfs files for the inode are * released. */ flags |= IS_RDONLY(d_inode(lower_dentry)) ? O_RDONLY : O_RDWR; (*lower_file) = dentry_open(&req.path, flags, cred); if (!IS_ERR(*lower_file)) goto out; if ((flags & O_ACCMODE) == O_RDONLY) { rc = PTR_ERR((*lower_file)); goto out; } mutex_lock(&ecryptfs_kthread_ctl.mux); if (ecryptfs_kthread_ctl.flags & ECRYPTFS_KTHREAD_ZOMBIE) { rc = -EIO; mutex_unlock(&ecryptfs_kthread_ctl.mux); printk(KERN_ERR "%s: We are in the middle of shutting down; " "aborting privileged request to open lower file\n", __func__); goto out; } list_add_tail(&req.kthread_ctl_list, &ecryptfs_kthread_ctl.req_list); mutex_unlock(&ecryptfs_kthread_ctl.mux); wake_up(&ecryptfs_kthread_ctl.wait); wait_for_completion(&req.done); if (IS_ERR(*lower_file)) rc = PTR_ERR(*lower_file); out: return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'ecryptfs: forbid opening files without mmap handler This prevents users from triggering a stack overflow through a recursive invocation of pagefault handling that involves mapping procfs files into virtual memory. Signed-off-by: Jann Horn <[email protected]> Acked-by: Tyler Hicks <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadTGAImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType status; PixelInfo pixel; Quantum index; register Quantum *q; register ssize_t i, x; size_t base, flag, offset, real, skip; ssize_t count, y; TGAInfo tga_info; unsigned char j, k, pixels[4], runlength; unsigned int alpha_bits; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read TGA header information. */ count=ReadBlob(image,1,&tga_info.id_length); tga_info.colormap_type=(unsigned char) ReadBlobByte(image); tga_info.image_type=(TGAImageType) ReadBlobByte(image); if ((count != 1) || ((tga_info.image_type != TGAColormap) && (tga_info.image_type != TGARGB) && (tga_info.image_type != TGAMonochrome) && (tga_info.image_type != TGARLEColormap) && (tga_info.image_type != TGARLERGB) && (tga_info.image_type != TGARLEMonochrome)) || (((tga_info.image_type == TGAColormap) || (tga_info.image_type == TGARLEColormap)) && (tga_info.colormap_type == 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); tga_info.colormap_index=ReadBlobLSBShort(image); tga_info.colormap_length=ReadBlobLSBShort(image); tga_info.colormap_size=(unsigned char) ReadBlobByte(image); tga_info.x_origin=ReadBlobLSBShort(image); tga_info.y_origin=ReadBlobLSBShort(image); tga_info.width=(unsigned short) ReadBlobLSBShort(image); tga_info.height=(unsigned short) ReadBlobLSBShort(image); tga_info.bits_per_pixel=(unsigned char) ReadBlobByte(image); tga_info.attributes=(unsigned char) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); if ((((tga_info.bits_per_pixel <= 1) || (tga_info.bits_per_pixel >= 17)) && (tga_info.bits_per_pixel != 24) && (tga_info.bits_per_pixel != 32))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image structure. */ image->columns=tga_info.width; image->rows=tga_info.height; alpha_bits=(tga_info.attributes & 0x0FU); image->alpha_trait=(alpha_bits > 0) || (tga_info.bits_per_pixel == 32) || (tga_info.colormap_size == 32) ? BlendPixelTrait : UndefinedPixelTrait; if ((tga_info.image_type != TGAColormap) && (tga_info.image_type != TGARLEColormap)) image->depth=(size_t) ((tga_info.bits_per_pixel <= 8) ? 8 : (tga_info.bits_per_pixel <= 16) ? 5 : (tga_info.bits_per_pixel == 24) ? 8 : (tga_info.bits_per_pixel == 32) ? 8 : 8); else image->depth=(size_t) ((tga_info.colormap_size <= 8) ? 8 : (tga_info.colormap_size <= 16) ? 5 : (tga_info.colormap_size == 24) ? 8 : (tga_info.colormap_size == 32) ? 8 : 8); if ((tga_info.image_type == TGAColormap) || (tga_info.image_type == TGAMonochrome) || (tga_info.image_type == TGARLEColormap) || (tga_info.image_type == TGARLEMonochrome)) image->storage_class=PseudoClass; image->compression=NoCompression; if ((tga_info.image_type == TGARLEColormap) || (tga_info.image_type == TGARLEMonochrome) || (tga_info.image_type == TGARLERGB)) image->compression=RLECompression; if (image->storage_class == PseudoClass) { if (tga_info.colormap_type != 0) image->colors=tga_info.colormap_index+tga_info.colormap_length; else { size_t one; one=1; image->colors=one << tga_info.bits_per_pixel; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (tga_info.id_length != 0) { char *comment; size_t length; /* TGA image comment. */ length=(size_t) tga_info.id_length; comment=(char *) NULL; if (~length >= (MagickPathExtent-1)) comment=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,tga_info.id_length,(unsigned char *) comment); comment[tga_info.id_length]='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); } if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(image); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); (void) ResetMagickMemory(&pixel,0,sizeof(pixel)); pixel.alpha=(MagickRealType) OpaqueAlpha; if (tga_info.colormap_type != 0) { /* Read TGA raster colormap. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) tga_info.colormap_index; i++) image->colormap[i]=pixel; for ( ; i < (ssize_t) image->colors; i++) { switch (tga_info.colormap_size) { case 8: default: { /* Gray scale. */ pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.green=pixel.red; pixel.blue=pixel.red; break; } case 15: case 16: { QuantumAny range; /* 5 bits each of red green and blue. */ j=(unsigned char) ReadBlobByte(image); k=(unsigned char) ReadBlobByte(image); range=GetQuantumRange(5UL); pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2, range); pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL*(k & 0x03) << 3)+(1UL*(j & 0xe0) >> 5),range); pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range); break; } case 24: { /* 8 bits each of blue, green and red. */ pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); break; } case 32: { /* 8 bits each of blue, green, red, and alpha. */ pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.alpha=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); break; } } image->colormap[i]=pixel; } } /* Convert TGA pixels to pixel packets. */ base=0; flag=0; skip=MagickFalse; real=0; index=0; runlength=0; offset=0; for (y=0; y < (ssize_t) image->rows; y++) { real=offset; if (((unsigned char) (tga_info.attributes & 0x20) >> 5) == 0) real=image->rows-real-1; q=QueueAuthenticPixels(image,0,(ssize_t) real,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if ((tga_info.image_type == TGARLEColormap) || (tga_info.image_type == TGARLERGB) || (tga_info.image_type == TGARLEMonochrome)) { if (runlength != 0) { runlength--; skip=flag != 0; } else { count=ReadBlob(image,1,&runlength); if (count != 1) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); flag=runlength & 0x80; if (flag != 0) runlength-=128; skip=MagickFalse; } } if (skip == MagickFalse) switch (tga_info.bits_per_pixel) { case 8: default: { /* Gray scale. */ index=(Quantum) ReadBlobByte(image); if (tga_info.colormap_type != 0) pixel=image->colormap[(ssize_t) ConstrainColormapIndex(image, (ssize_t) index,exception)]; else { pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char) index); pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char) index); pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char) index); } break; } case 15: case 16: { QuantumAny range; /* 5 bits each of RGB. */ if (ReadBlob(image,2,pixels) != 2) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); j=pixels[0]; k=pixels[1]; range=GetQuantumRange(5UL); pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2, range); pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL* (k & 0x03) << 3)+(1UL*(j & 0xe0) >> 5),range); pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range); if (image->alpha_trait != UndefinedPixelTrait) pixel.alpha=(MagickRealType) ((k & 0x80) == 0 ? (Quantum) TransparentAlpha : (Quantum) OpaqueAlpha); if (image->storage_class == PseudoClass) index=(Quantum) ConstrainColormapIndex(image,((ssize_t) (k << 8))+ j,exception); break; } case 24: { /* BGR pixels. */ if (ReadBlob(image,3,pixels) != 3) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]); pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]); pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]); break; } case 32: { /* BGRA pixels. */ if (ReadBlob(image,4,pixels) != 4) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]); pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]); pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]); pixel.alpha=(MagickRealType) ScaleCharToQuantum(pixels[3]); break; } } if (status == MagickFalse) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); if (image->storage_class == PseudoClass) SetPixelIndex(image,index,q); SetPixelRed(image,ClampToQuantum(pixel.red),q); SetPixelGreen(image,ClampToQuantum(pixel.green),q); SetPixelBlue(image,ClampToQuantum(pixel.blue),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } /* if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 4) offset+=4; else */ if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 2) offset+=2; else offset++; if (offset >= image->rows) { base++; offset=base; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'https://bugs.launchpad.net/ubuntu/+source/imagemagick/+bug/1490362'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int phar_extract_file(zend_bool overwrite, phar_entry_info *entry, char *dest, int dest_len, char **error TSRMLS_DC) /* {{{ */ { php_stream_statbuf ssb; int len; php_stream *fp; char *fullpath; const char *slash; mode_t mode; cwd_state new_state; char *filename; size_t filename_len; if (entry->is_mounted) { /* silently ignore mounted entries */ return SUCCESS; } if (entry->filename_len >= sizeof(".phar")-1 && !memcmp(entry->filename, ".phar", sizeof(".phar")-1)) { return SUCCESS; } /* strip .. from path and restrict it to be under dest directory */ new_state.cwd = (char*)emalloc(2); new_state.cwd[0] = DEFAULT_SLASH; new_state.cwd[1] = '\0'; new_state.cwd_length = 1; if (virtual_file_ex(&new_state, entry->filename, NULL, CWD_EXPAND TSRMLS_CC) != 0 || new_state.cwd_length <= 1) { if (EINVAL == errno && entry->filename_len > 50) { char *tmp = estrndup(entry->filename, 50); spprintf(error, 4096, "Cannot extract \"%s...\" to \"%s...\", extracted filename is too long for filesystem", tmp, dest); efree(tmp); } else { spprintf(error, 4096, "Cannot extract \"%s\", internal error", entry->filename); } efree(new_state.cwd); return FAILURE; } filename = new_state.cwd + 1; filename_len = new_state.cwd_length - 1; #ifdef PHP_WIN32 /* unixify the path back, otherwise non zip formats might be broken */ { int cnt = filename_len; do { if ('\\' == filename[cnt]) { filename[cnt] = '/'; } } while (cnt-- >= 0); } #endif len = spprintf(&fullpath, 0, "%s/%s", dest, filename); if (len >= MAXPATHLEN) { char *tmp; /* truncate for error message */ fullpath[50] = '\0'; if (entry->filename_len > 50) { tmp = estrndup(entry->filename, 50); spprintf(error, 4096, "Cannot extract \"%s...\" to \"%s...\", extracted filename is too long for filesystem", tmp, fullpath); efree(tmp); } else { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s...\", extracted filename is too long for filesystem", entry->filename, fullpath); } efree(fullpath); efree(new_state.cwd); return FAILURE; } if (!len) { spprintf(error, 4096, "Cannot extract \"%s\", internal error", entry->filename); efree(fullpath); efree(new_state.cwd); return FAILURE; } if (PHAR_OPENBASEDIR_CHECKPATH(fullpath)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", openbasedir/safe mode restrictions in effect", entry->filename, fullpath); efree(fullpath); efree(new_state.cwd); return FAILURE; } /* let see if the path already exists */ if (!overwrite && SUCCESS == php_stream_stat_path(fullpath, &ssb)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", path already exists", entry->filename, fullpath); efree(fullpath); efree(new_state.cwd); return FAILURE; } /* perform dirname */ slash = zend_memrchr(filename, '/', filename_len); if (slash) { fullpath[dest_len + (slash - filename) + 1] = '\0'; } else { fullpath[dest_len] = '\0'; } if (FAILURE == php_stream_stat_path(fullpath, &ssb)) { if (entry->is_dir) { if (!php_stream_mkdir(fullpath, entry->flags & PHAR_ENT_PERM_MASK, PHP_STREAM_MKDIR_RECURSIVE, NULL)) { spprintf(error, 4096, "Cannot extract \"%s\", could not create directory \"%s\"", entry->filename, fullpath); efree(fullpath); free(new_state.cwd); return FAILURE; } } else { if (!php_stream_mkdir(fullpath, 0777, PHP_STREAM_MKDIR_RECURSIVE, NULL)) { spprintf(error, 4096, "Cannot extract \"%s\", could not create directory \"%s\"", entry->filename, fullpath); efree(fullpath); free(new_state.cwd); return FAILURE; } } } if (slash) { fullpath[dest_len + (slash - filename) + 1] = '/'; } else { fullpath[dest_len] = '/'; } filename = NULL; efree(new_state.cwd); /* it is a standalone directory, job done */ if (entry->is_dir) { efree(fullpath); return SUCCESS; } #if PHP_API_VERSION < 20100412 fp = php_stream_open_wrapper(fullpath, "w+b", REPORT_ERRORS|ENFORCE_SAFE_MODE, NULL); #else fp = php_stream_open_wrapper(fullpath, "w+b", REPORT_ERRORS, NULL); #endif if (!fp) { spprintf(error, 4096, "Cannot extract \"%s\", could not open for writing \"%s\"", entry->filename, fullpath); efree(fullpath); return FAILURE; } if (!phar_get_efp(entry, 0 TSRMLS_CC)) { if (FAILURE == phar_open_entry_fp(entry, error, 1 TSRMLS_CC)) { if (error) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to open internal file pointer: %s", entry->filename, fullpath, *error); } else { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to open internal file pointer", entry->filename, fullpath); } efree(fullpath); php_stream_close(fp); return FAILURE; } } if (FAILURE == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to seek internal file pointer", entry->filename, fullpath); efree(fullpath); php_stream_close(fp); return FAILURE; } if (SUCCESS != php_stream_copy_to_stream_ex(phar_get_efp(entry, 0 TSRMLS_CC), fp, entry->uncompressed_filesize, NULL)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", copying contents failed", entry->filename, fullpath); efree(fullpath); php_stream_close(fp); return FAILURE; } php_stream_close(fp); mode = (mode_t) entry->flags & PHAR_ENT_PERM_MASK; if (FAILURE == VCWD_CHMOD(fullpath, mode)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", setting file permissions failed", entry->filename, fullpath); efree(fullpath); return FAILURE; } efree(fullpath); return SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #72321 - use efree() for emalloc allocation'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: MagickExport Image *CloneImage(const Image *image,const size_t columns, const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception) { Image *clone_image; double scale; size_t length; /* Clone the image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((image->columns == 0) || (image->rows == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "NegativeOrZeroImageSize","`%s'",image->filename); return((Image *) NULL); } clone_image=(Image *) AcquireMagickMemory(sizeof(*clone_image)); if (clone_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(clone_image,0,sizeof(*clone_image)); clone_image->signature=MagickCoreSignature; clone_image->storage_class=image->storage_class; clone_image->number_channels=image->number_channels; clone_image->number_meta_channels=image->number_meta_channels; clone_image->metacontent_extent=image->metacontent_extent; clone_image->colorspace=image->colorspace; clone_image->read_mask=image->read_mask; clone_image->write_mask=image->write_mask; clone_image->alpha_trait=image->alpha_trait; clone_image->columns=image->columns; clone_image->rows=image->rows; clone_image->dither=image->dither; if (image->colormap != (PixelInfo *) NULL) { /* Allocate and copy the image colormap. */ clone_image->colors=image->colors; length=(size_t) image->colors; clone_image->colormap=(PixelInfo *) AcquireQuantumMemory(length, sizeof(*clone_image->colormap)); if (clone_image->colormap == (PixelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickMemory(clone_image->colormap,image->colormap,length* sizeof(*clone_image->colormap)); } clone_image->image_info=CloneImageInfo(image->image_info); (void) CloneImageProfiles(clone_image,image); (void) CloneImageProperties(clone_image,image); (void) CloneImageArtifacts(clone_image,image); GetTimerInfo(&clone_image->timer); if (image->ascii85 != (void *) NULL) Ascii85Initialize(clone_image); clone_image->magick_columns=image->magick_columns; clone_image->magick_rows=image->magick_rows; clone_image->type=image->type; clone_image->channel_mask=image->channel_mask; clone_image->channel_map=ClonePixelChannelMap(image->channel_map); (void) CopyMagickString(clone_image->magick_filename,image->magick_filename, MagickPathExtent); (void) CopyMagickString(clone_image->magick,image->magick,MagickPathExtent); (void) CopyMagickString(clone_image->filename,image->filename, MagickPathExtent); clone_image->progress_monitor=image->progress_monitor; clone_image->client_data=image->client_data; clone_image->reference_count=1; clone_image->next=image->next; clone_image->previous=image->previous; clone_image->list=NewImageList(); if (detach == MagickFalse) clone_image->blob=ReferenceBlob(image->blob); else { clone_image->next=NewImageList(); clone_image->previous=NewImageList(); clone_image->blob=CloneBlobInfo((BlobInfo *) NULL); } clone_image->ping=image->ping; clone_image->debug=IsEventLogging(); clone_image->semaphore=AcquireSemaphoreInfo(); if ((columns == 0) || (rows == 0)) { if (image->montage != (char *) NULL) (void) CloneString(&clone_image->montage,image->montage); if (image->directory != (char *) NULL) (void) CloneString(&clone_image->directory,image->directory); clone_image->cache=ReferencePixelCache(image->cache); return(clone_image); } scale=1.0; if (image->columns != 0) scale=(double) columns/(double) image->columns; clone_image->page.width=(size_t) floor(scale*image->page.width+0.5); clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5); clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5); scale=1.0; if (image->rows != 0) scale=(double) rows/(double) image->rows; clone_image->page.height=(size_t) floor(scale*image->page.height+0.5); clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5); clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5); clone_image->columns=columns; clone_image->rows=rows; clone_image->cache=ClonePixelCache(image->cache); return(clone_image); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Set pixel cache to undefined if any resource limit is exceeded'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, source_info; char format[MagickPathExtent], message[MagickPathExtent]; const char *type; MagickBooleanType status; MagickSizeType length, number_pixels; size_t columns, packet_size; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->columns == 0) || (image->rows == 0)) ThrowBinaryException(CacheError,"NoPixelsDefinedInCache",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowBinaryException(ImageError,"WidthOrHeightExceedsLimit", image->filename); source_info=(*cache_info); source_info.file=(-1); (void) FormatLocaleString(cache_info->filename,MagickPathExtent,"%s[%.20g]", image->filename,(double) GetImageIndexInList(image)); cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->alpha_trait=image->alpha_trait; cache_info->read_mask=image->read_mask; cache_info->write_mask=image->write_mask; cache_info->rows=image->rows; cache_info->columns=image->columns; InitializePixelChannelMap(image); cache_info->number_channels=GetPixelChannels(image); (void) memcpy(cache_info->channel_map,image->channel_map,MaxPixelChannels* sizeof(*image->channel_map)); cache_info->metacontent_extent=image->metacontent_extent; cache_info->mode=mode; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; packet_size=cache_info->number_channels*sizeof(Quantum); if (image->metacontent_extent != 0) packet_size+=cache_info->metacontent_extent; length=number_pixels*packet_size; columns=(size_t) (length/cache_info->rows/packet_size); if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) || ((ssize_t) cache_info->rows < 0)) ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed", image->filename); cache_info->length=length; if (image->ping != MagickFalse) { cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->type=PingCache; return(MagickTrue); } status=AcquireMagickResource(AreaResource,cache_info->length); length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length))) { status=AcquireMagickResource(MemoryResource,cache_info->length); if (((cache_info->type == UndefinedCache) && (status != MagickFalse)) || (cache_info->type == MemoryCache)) { cache_info->mapped=MagickFalse; cache_info->pixels=(Quantum *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) cache_info->length)); if (cache_info->pixels == (Quantum *) NULL) cache_info->pixels=source_info.pixels; else { /* Create memory pixel cache. */ status=MagickTrue; cache_info->type=MemoryCache; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ number_pixels*cache_info->number_channels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->mapped != MagickFalse ? "Anonymous" : "Heap",type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(status); } } RelinquishMagickResource(MemoryResource,cache_info->length); } /* Create pixel cache on disk. */ status=AcquireMagickResource(DiskResource,cache_info->length); if ((status == MagickFalse) || (cache_info->type == DistributedCache)) { DistributeCacheInfo *server_info; if (cache_info->type == DistributedCache) RelinquishMagickResource(DiskResource,cache_info->length); server_info=AcquireDistributeCacheInfo(exception); if (server_info != (DistributeCacheInfo *) NULL) { status=OpenDistributePixelCache(server_info,image); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", GetDistributeCacheHostname(server_info)); server_info=DestroyDistributeCacheInfo(server_info); } else { /* Create a distributed pixel cache. */ cache_info->type=DistributedCache; cache_info->server_info=server_info; (void) FormatLocaleString(cache_info->cache_filename, MagickPathExtent,"%s:%d",GetDistributeCacheHostname( (DistributeCacheInfo *) cache_info->server_info), GetDistributeCachePort((DistributeCacheInfo *) cache_info->server_info)); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, GetDistributeCacheFile((DistributeCacheInfo *) cache_info->server_info),type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(MagickTrue); } } RelinquishMagickResource(DiskResource,cache_info->length); (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { (void) ClosePixelCacheOnDisk(cache_info); *cache_info->cache_filename='\0'; } if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse) { RelinquishMagickResource(DiskResource,cache_info->length); ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", image->filename); return(MagickFalse); } status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+ cache_info->length); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToExtendCache", image->filename); return(MagickFalse); } length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if (length != (MagickSizeType) ((size_t) length)) cache_info->type=DiskCache; else { status=AcquireMagickResource(MapResource,cache_info->length); if ((status == MagickFalse) && (cache_info->type != MapCache) && (cache_info->type != MemoryCache)) cache_info->type=DiskCache; else { cache_info->pixels=(Quantum *) MapBlob(cache_info->file,mode, cache_info->offset,(size_t) cache_info->length); if (cache_info->pixels == (Quantum *) NULL) { cache_info->type=DiskCache; cache_info->pixels=source_info.pixels; } else { /* Create file-backed memory-mapped pixel cache. */ status=MagickTrue; (void) ClosePixelCacheOnDisk(cache_info); cache_info->type=MapCache; cache_info->mapped=MagickTrue; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ number_pixels*cache_info->number_channels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,(double) cache_info->number_channels, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(status); } } RelinquishMagickResource(MapResource,cache_info->length); } status=MagickTrue; if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info,exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(status); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Set pixel cache to undefined if any resource limit is exceeded'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss, struct _7z_folder *f, size_t numFolders) { const unsigned char *p; uint64_t *usizes; size_t unpack_streams; int type; unsigned i; uint32_t numDigests; memset(ss, 0, sizeof(*ss)); for (i = 0; i < numFolders; i++) f[i].numUnpackStreams = 1; if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; if (type == kNumUnPackStream) { unpack_streams = 0; for (i = 0; i < numFolders; i++) { if (parse_7zip_uint64(a, &(f[i].numUnpackStreams)) < 0) return (-1); if (UMAX_ENTRY < f[i].numUnpackStreams) return (-1); unpack_streams += (size_t)f[i].numUnpackStreams; } if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } else unpack_streams = numFolders; ss->unpack_streams = unpack_streams; if (unpack_streams) { ss->unpackSizes = calloc(unpack_streams, sizeof(*ss->unpackSizes)); ss->digestsDefined = calloc(unpack_streams, sizeof(*ss->digestsDefined)); ss->digests = calloc(unpack_streams, sizeof(*ss->digests)); if (ss->unpackSizes == NULL || ss->digestsDefined == NULL || ss->digests == NULL) return (-1); } usizes = ss->unpackSizes; for (i = 0; i < numFolders; i++) { unsigned pack; uint64_t sum; if (f[i].numUnpackStreams == 0) continue; sum = 0; if (type == kSize) { for (pack = 1; pack < f[i].numUnpackStreams; pack++) { if (parse_7zip_uint64(a, usizes) < 0) return (-1); sum += *usizes++; } } *usizes++ = folder_uncompressed_size(&f[i]) - sum; } if (type == kSize) { if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } for (i = 0; i < unpack_streams; i++) { ss->digestsDefined[i] = 0; ss->digests[i] = 0; } numDigests = 0; for (i = 0; i < numFolders; i++) { if (f[i].numUnpackStreams != 1 || !f[i].digest_defined) numDigests += (uint32_t)f[i].numUnpackStreams; } if (type == kCRC) { struct _7z_digests tmpDigests; unsigned char *digestsDefined = ss->digestsDefined; uint32_t * digests = ss->digests; int di = 0; memset(&tmpDigests, 0, sizeof(tmpDigests)); if (read_Digests(a, &(tmpDigests), numDigests) < 0) { free_Digest(&tmpDigests); return (-1); } for (i = 0; i < numFolders; i++) { if (f[i].numUnpackStreams == 1 && f[i].digest_defined) { *digestsDefined++ = 1; *digests++ = f[i].digest; } else { unsigned j; for (j = 0; j < f[i].numUnpackStreams; j++, di++) { *digestsDefined++ = tmpDigests.defineds[di]; *digests++ = tmpDigests.digests[di]; } } } free_Digest(&tmpDigests); if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } /* * Must be kEnd. */ if (type != kEnd) return (-1); return (0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Issue #718: Fix TALOS-CAN-152 If a 7-Zip archive declares a rediculously large number of substreams, it can overflow an internal counter, leading a subsequent memory allocation to be too small for the substream data. Thanks to the Open Source and Threat Intelligence project at Cisco for reporting this issue.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parse_codes(struct archive_read *a) { int i, j, val, n, r; unsigned char bitlengths[MAX_SYMBOLS], zerocount, ppmd_flags; unsigned int maxorder; struct huffman_code precode; struct rar *rar = (struct rar *)(a->format->data); struct rar_br *br = &(rar->br); free_codes(a); /* Skip to the next byte */ rar_br_consume_unalined_bits(br); /* PPMd block flag */ if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; if ((rar->is_ppmd_block = rar_br_bits(br, 1)) != 0) { rar_br_consume(br, 1); if (!rar_br_read_ahead(a, br, 7)) goto truncated_data; ppmd_flags = rar_br_bits(br, 7); rar_br_consume(br, 7); /* Memory is allocated in MB */ if (ppmd_flags & 0x20) { if (!rar_br_read_ahead(a, br, 8)) goto truncated_data; rar->dictionary_size = (rar_br_bits(br, 8) + 1) << 20; rar_br_consume(br, 8); } if (ppmd_flags & 0x40) { if (!rar_br_read_ahead(a, br, 8)) goto truncated_data; rar->ppmd_escape = rar->ppmd7_context.InitEsc = rar_br_bits(br, 8); rar_br_consume(br, 8); } else rar->ppmd_escape = 2; if (ppmd_flags & 0x20) { maxorder = (ppmd_flags & 0x1F) + 1; if(maxorder > 16) maxorder = 16 + (maxorder - 16) * 3; if (maxorder == 1) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); return (ARCHIVE_FATAL); } /* Make sure ppmd7_contest is freed before Ppmd7_Construct * because reading a broken file cause this abnormal sequence. */ __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); rar->bytein.a = a; rar->bytein.Read = &ppmd_read; __archive_ppmd7_functions.PpmdRAR_RangeDec_CreateVTable(&rar->range_dec); rar->range_dec.Stream = &rar->bytein; __archive_ppmd7_functions.Ppmd7_Construct(&rar->ppmd7_context); if (!__archive_ppmd7_functions.Ppmd7_Alloc(&rar->ppmd7_context, rar->dictionary_size, &g_szalloc)) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unable to initialize PPMd range decoder"); return (ARCHIVE_FATAL); } __archive_ppmd7_functions.Ppmd7_Init(&rar->ppmd7_context, maxorder); rar->ppmd_valid = 1; } else { if (!rar->ppmd_valid) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid PPMd sequence"); return (ARCHIVE_FATAL); } if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unable to initialize PPMd range decoder"); return (ARCHIVE_FATAL); } } } else { rar_br_consume(br, 1); /* Keep existing table flag */ if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; if (!rar_br_bits(br, 1)) memset(rar->lengthtable, 0, sizeof(rar->lengthtable)); rar_br_consume(br, 1); memset(&bitlengths, 0, sizeof(bitlengths)); for (i = 0; i < MAX_SYMBOLS;) { if (!rar_br_read_ahead(a, br, 4)) goto truncated_data; bitlengths[i++] = rar_br_bits(br, 4); rar_br_consume(br, 4); if (bitlengths[i-1] == 0xF) { if (!rar_br_read_ahead(a, br, 4)) goto truncated_data; zerocount = rar_br_bits(br, 4); rar_br_consume(br, 4); if (zerocount) { i--; for (j = 0; j < zerocount + 2 && i < MAX_SYMBOLS; j++) bitlengths[i++] = 0; } } } memset(&precode, 0, sizeof(precode)); r = create_code(a, &precode, bitlengths, MAX_SYMBOLS, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) { free(precode.tree); free(precode.table); return (r); } for (i = 0; i < HUFFMAN_TABLE_SIZE;) { if ((val = read_next_symbol(a, &precode)) < 0) { free(precode.tree); free(precode.table); return (ARCHIVE_FATAL); } if (val < 16) { rar->lengthtable[i] = (rar->lengthtable[i] + val) & 0xF; i++; } else if (val < 18) { if (i == 0) { free(precode.tree); free(precode.table); archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Internal error extracting RAR file."); return (ARCHIVE_FATAL); } if(val == 16) { if (!rar_br_read_ahead(a, br, 3)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 3) + 3; rar_br_consume(br, 3); } else { if (!rar_br_read_ahead(a, br, 7)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 7) + 11; rar_br_consume(br, 7); } for (j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++) { rar->lengthtable[i] = rar->lengthtable[i-1]; i++; } } else { if(val == 18) { if (!rar_br_read_ahead(a, br, 3)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 3) + 3; rar_br_consume(br, 3); } else { if (!rar_br_read_ahead(a, br, 7)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 7) + 11; rar_br_consume(br, 7); } for(j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++) rar->lengthtable[i++] = 0; } } free(precode.tree); free(precode.table); r = create_code(a, &rar->maincode, &rar->lengthtable[0], MAINCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->offsetcode, &rar->lengthtable[MAINCODE_SIZE], OFFSETCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->lowoffsetcode, &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE], LOWOFFSETCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->lengthcode, &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE + LOWOFFSETCODE_SIZE], LENGTHCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); } if (!rar->dictionary_size || !rar->lzss.window) { /* Seems as though dictionary sizes are not used. Even so, minimize * memory usage as much as possible. */ void *new_window; unsigned int new_size; if (rar->unp_size >= DICTIONARY_MAX_SIZE) new_size = DICTIONARY_MAX_SIZE; else new_size = rar_fls((unsigned int)rar->unp_size) << 1; new_window = realloc(rar->lzss.window, new_size); if (new_window == NULL) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for uncompressed data."); return (ARCHIVE_FATAL); } rar->lzss.window = (unsigned char *)new_window; rar->dictionary_size = new_size; memset(rar->lzss.window, 0, rar->dictionary_size); rar->lzss.mask = rar->dictionary_size - 1; } rar->start_new_table = 0; return (ARCHIVE_OK); truncated_data: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return (ARCHIVE_FATAL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Issue 719: Fix for TALOS-CAN-154 A RAR file with an invalid zero dictionary size was not being rejected, leading to a zero-sized allocation for the dictionary storage which was then overwritten during the dictionary initialization. Thanks to the Open Source and Threat Intelligence project at Cisco for reporting this.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xcf_load_channel_props (XcfInfo *info, GimpImage *image, GimpChannel **channel) { PropType prop_type; guint32 prop_size; while (TRUE) { if (! xcf_load_prop (info, &prop_type, &prop_size)) return FALSE; switch (prop_type) { case PROP_END: return TRUE; case PROP_ACTIVE_CHANNEL: info->active_channel = *channel; break; case PROP_SELECTION: { GimpChannel *mask; mask = gimp_selection_new (image, gimp_item_get_width (GIMP_ITEM (*channel)), gimp_item_get_height (GIMP_ITEM (*channel))); gimp_image_take_mask (image, mask); tile_manager_unref (GIMP_DRAWABLE (mask)->private->tiles); GIMP_DRAWABLE (mask)->private->tiles = GIMP_DRAWABLE (*channel)->private->tiles; GIMP_DRAWABLE (*channel)->private->tiles = NULL; g_object_unref (*channel); *channel = mask; (*channel)->boundary_known = FALSE; (*channel)->bounds_known = FALSE; } break; case PROP_OPACITY: { guint32 opacity; info->cp += xcf_read_int32 (info->fp, &opacity, 1); gimp_channel_set_opacity (*channel, opacity / 255.0, FALSE); } break; case PROP_VISIBLE: { gboolean visible; info->cp += xcf_read_int32 (info->fp, (guint32 *) &visible, 1); gimp_item_set_visible (GIMP_ITEM (*channel), visible ? TRUE : FALSE, FALSE); } break; case PROP_LINKED: { gboolean linked; info->cp += xcf_read_int32 (info->fp, (guint32 *) &linked, 1); gimp_item_set_linked (GIMP_ITEM (*channel), linked ? TRUE : FALSE, FALSE); } break; case PROP_LOCK_CONTENT: { gboolean lock_content; info->cp += xcf_read_int32 (info->fp, (guint32 *) &lock_content, 1); gimp_item_set_lock_content (GIMP_ITEM (*channel), lock_content ? TRUE : FALSE, FALSE); } break; case PROP_SHOW_MASKED: { gboolean show_masked; info->cp += xcf_read_int32 (info->fp, (guint32 *) &show_masked, 1); gimp_channel_set_show_masked (*channel, show_masked); } break; case PROP_COLOR: { guchar col[3]; info->cp += xcf_read_int8 (info->fp, (guint8 *) col, 3); gimp_rgb_set_uchar (&(*channel)->color, col[0], col[1], col[2]); } break; case PROP_TATTOO: { GimpTattoo tattoo; info->cp += xcf_read_int32 (info->fp, (guint32 *) &tattoo, 1); gimp_item_set_tattoo (GIMP_ITEM (*channel), tattoo); } break; case PROP_PARASITES: { glong base = info->cp; while ((info->cp - base) < prop_size) { GimpParasite *p = xcf_load_parasite (info); if (! p) return FALSE; gimp_item_parasite_attach (GIMP_ITEM (*channel), p, FALSE); gimp_parasite_free (p); } if (info->cp - base != prop_size) gimp_message_literal (info->gimp, G_OBJECT (info->progress), GIMP_MESSAGE_WARNING, "Error while loading a channel's parasites"); } break; default: #ifdef GIMP_UNSTABLE g_printerr ("unexpected/unknown channel property: %d (skipping)\n", prop_type); #endif if (! xcf_skip_unknown_prop (info, prop_size)) return FALSE; break; } } return FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Bug 767873 - (CVE-2016-4994) Multiple Use-After-Free when parsing... ...XCF channel and layer properties The properties PROP_ACTIVE_LAYER, PROP_FLOATING_SELECTION, PROP_ACTIVE_CHANNEL saves the current object pointer the @info structure. Others like PROP_SELECTION (for channel) and PROP_GROUP_ITEM (for layer) will delete the current object and create a new object, leaving the pointers in @info invalid (dangling). Therefore, if a property from the first type will come before the second, the result will be an UaF in the last lines of xcf_load_image (when it actually using the pointers from @info). I wasn't able to exploit this bug because that g_object_instance->c_class gets cleared by the last g_object_unref and GIMP_IS_{LAYER,CHANNEL} detects that and return FALSE. (cherry picked from commit 6d804bf9ae77bc86a0a97f9b944a129844df9395)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: check_compat_entry_size_and_hooks(struct compat_ipt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ipt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip_checkentry(&e->ip)) return -EINVAL; ret = xt_compat_check_entry_offsets(e, e->target_offset, e->next_offset); if (ret) return ret; off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ip, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ipt_get_target(e); target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: check_entry_size_and_hooks(struct ip6t_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip6_checkentry(&e->ipv6)) return -EINVAL; err = xt_check_entry_offsets(e, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int xt_compat_check_entry_offsets(const void *base, unsigned int target_offset, unsigned int next_offset) { const struct compat_xt_entry_target *t; const char *e = base; if (target_offset + sizeof(*t) > next_offset) return -EINVAL; t = (void *)(e + target_offset); if (t->u.target_size < sizeof(*t)) return -EINVAL; if (target_offset + t->u.target_size > next_offset) return -EINVAL; if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 && target_offset + sizeof(struct compat_xt_standard_target) != next_offset) return -EINVAL; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ip6t_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip6_checkentry(&e->ipv6)) return -EINVAL; ret = xt_compat_check_entry_offsets(e, e->target_offset, e->next_offset); if (ret) return ret; off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ipv6, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ip6t_get_target(e); target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET6, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ip6t_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct ip6t_entry *)e); if (ret) return ret; off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ipv6, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ip6t_get_target(e); target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET6, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'netfilter: x_tables: make sure e->next_offset covers remaining blob size Otherwise this function may read data beyond the ruleset blob. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline int check_entry_size_and_hooks(struct arpt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 || (unsigned char *)e + sizeof(struct arpt_entry) >= limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_err("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'netfilter: x_tables: make sure e->next_offset covers remaining blob size Otherwise this function may read data beyond the ruleset blob. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: check_compat_entry_size_and_hooks(struct compat_ipt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ipt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct ipt_entry *)e); if (ret) return ret; off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ip, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ipt_get_target(e); target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'netfilter: x_tables: make sure e->next_offset covers remaining blob size Otherwise this function may read data beyond the ruleset blob. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void DumpBIH(unsigned char *BIH) { printf("biSize = %i \n", (int)(BIH[3] << 24) + (BIH[2] << 16) + (BIH[1] << 8) + (BIH[0])); printf("biWidth = %i \n", (int)(BIH[7] << 24) + (BIH[6] << 16) + (BIH[5] << 8) + (BIH[4])); printf("biHeight = %i \n", (int)(BIH[11] << 24) + (BIH[10] << 16) + (BIH[9] << 8) + (BIH[8])); printf("biPlanes = %i \n", (int)(BIH[13] << 8) + (BIH[12])); printf("biBitCount = %i \n", (int)(BIH[15] << 8) + (BIH[14])); printf("biCompress = %i \n", (int)(BIH[19] << 24) + (BIH[18] << 16) + (BIH[17] << 8) + (BIH[16])); printf("biSizeImage = %i \n", (int)(BIH[23] << 24) + (BIH[22] << 16) + (BIH[21] << 8) + (BIH[20])); printf("biXPels = %i \n", (int)(BIH[27] << 24) + (BIH[26] << 16) + (BIH[25] << 8) + (BIH[24])); printf("biYPels = %i \n", (int)(BIH[31] << 24) + (BIH[30] << 16) + (BIH[29] << 8) + (BIH[28])); printf("biClrUsed = %i \n", (int)(BIH[35] << 24) + (BIH[34] << 16) + (BIH[33] << 8) + (BIH[32])); printf("biClrImprtnt= %i \n", (int)(BIH[39] << 24) + (BIH[38] << 16) + (BIH[37] << 8) + (BIH[36])); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'ico: Be more careful when parsing headers There is some redundancy between the ico directory and the bitmap image header. If the two disagree on the icon dimensions, just toss the image, instead of risking crashes or OOM later. Also add some more debug spew that helped in tracking this down, and make error messages more unique. The commit also includes a test image that has an example of this discrepancy and triggers the early exit. https://bugzilla.gnome.org/show_bug.cgi?id=769170'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline signed short ReadPropertySignedShort(const EndianType endian, const unsigned char *buffer) { union { unsigned short unsigned_value; signed short signed_value; } quantum; unsigned short value; if (endian == LSBEndian) { value=(unsigned short) ((buffer[1] << 8) | buffer[0]); quantum.unsigned_value=(value & 0xffff); return(quantum.signed_value); } value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) | ((unsigned char *) buffer)[1]); quantum.unsigned_value=(value & 0xffff); return(quantum.signed_value); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline signed int ReadPropertyMSBLong(const unsigned char **p, size_t *length) { union { unsigned int unsigned_value; signed int signed_value; } quantum; int c; register ssize_t i; unsigned char buffer[4]; size_t value; if (*length < 4) return(-1); for (i=0; i < 4; i++) { c=(int) (*(*p)++); (*length)--; buffer[i]=(unsigned char) c; } value=(size_t) (buffer[0] << 24); value|=buffer[1] << 16; value|=buffer[2] << 8; value|=buffer[3]; quantum.unsigned_value=(value & 0xffffffff); return(quantum.signed_value); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline signed short ReadPropertyMSBShort(const unsigned char **p, size_t *length) { union { unsigned short unsigned_value; signed short signed_value; } quantum; int c; register ssize_t i; unsigned char buffer[2]; unsigned short value; if (*length < 2) return((unsigned short) ~0); for (i=0; i < 2; i++) { c=(int) (*(*p)++); (*length)--; buffer[i]=(unsigned char) c; } value=(unsigned short) (buffer[0] << 8); value|=buffer[1]; quantum.unsigned_value=(value & 0xffff); return(quantum.signed_value); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType GetEXIFProperty(const Image *image, const char *property,ExceptionInfo *exception) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER "\n" #define EXIF_NUM_FORMATS 12 #define EXIF_FMT_BYTE 1 #define EXIF_FMT_STRING 2 #define EXIF_FMT_USHORT 3 #define EXIF_FMT_ULONG 4 #define EXIF_FMT_URATIONAL 5 #define EXIF_FMT_SBYTE 6 #define EXIF_FMT_UNDEFINED 7 #define EXIF_FMT_SSHORT 8 #define EXIF_FMT_SLONG 9 #define EXIF_FMT_SRATIONAL 10 #define EXIF_FMT_SINGLE 11 #define EXIF_FMT_DOUBLE 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_GPS_OFFSET 0x8825 #define TAG_INTEROP_OFFSET 0xa005 #define EXIFMultipleValues(size,format,arg) \ { \ ssize_t \ component; \ \ size_t \ length; \ \ unsigned char \ *p1; \ \ length=0; \ p1=p; \ for (component=0; component < components; component++) \ { \ length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \ format", ",arg); \ if (length >= (MagickPathExtent-1)) \ length=MagickPathExtent-1; \ p1+=size; \ } \ if (length > 1) \ buffer[length-2]='\0'; \ value=AcquireString(buffer); \ } #define EXIFMultipleFractions(size,format,arg1,arg2) \ { \ ssize_t \ component; \ \ size_t \ length; \ \ unsigned char \ *p1; \ \ length=0; \ p1=p; \ for (component=0; component < components; component++) \ { \ length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \ format", ",(arg1),(arg2)); \ if (length >= (MagickPathExtent-1)) \ length=MagickPathExtent-1; \ p1+=size; \ } \ if (length > 1) \ buffer[length-2]='\0'; \ value=AcquireString(buffer); \ } typedef struct _DirectoryInfo { const unsigned char *directory; size_t entry; ssize_t offset; } DirectoryInfo; typedef struct _TagInfo { size_t tag; const char *description; } TagInfo; static TagInfo EXIFTag[] = { { 0x001, "exif:InteroperabilityIndex" }, { 0x002, "exif:InteroperabilityVersion" }, { 0x100, "exif:ImageWidth" }, { 0x101, "exif:ImageLength" }, { 0x102, "exif:BitsPerSample" }, { 0x103, "exif:Compression" }, { 0x106, "exif:PhotometricInterpretation" }, { 0x10a, "exif:FillOrder" }, { 0x10d, "exif:DocumentName" }, { 0x10e, "exif:ImageDescription" }, { 0x10f, "exif:Make" }, { 0x110, "exif:Model" }, { 0x111, "exif:StripOffsets" }, { 0x112, "exif:Orientation" }, { 0x115, "exif:SamplesPerPixel" }, { 0x116, "exif:RowsPerStrip" }, { 0x117, "exif:StripByteCounts" }, { 0x11a, "exif:XResolution" }, { 0x11b, "exif:YResolution" }, { 0x11c, "exif:PlanarConfiguration" }, { 0x11d, "exif:PageName" }, { 0x11e, "exif:XPosition" }, { 0x11f, "exif:YPosition" }, { 0x118, "exif:MinSampleValue" }, { 0x119, "exif:MaxSampleValue" }, { 0x120, "exif:FreeOffsets" }, { 0x121, "exif:FreeByteCounts" }, { 0x122, "exif:GrayResponseUnit" }, { 0x123, "exif:GrayResponseCurve" }, { 0x124, "exif:T4Options" }, { 0x125, "exif:T6Options" }, { 0x128, "exif:ResolutionUnit" }, { 0x12d, "exif:TransferFunction" }, { 0x131, "exif:Software" }, { 0x132, "exif:DateTime" }, { 0x13b, "exif:Artist" }, { 0x13e, "exif:WhitePoint" }, { 0x13f, "exif:PrimaryChromaticities" }, { 0x140, "exif:ColorMap" }, { 0x141, "exif:HalfToneHints" }, { 0x142, "exif:TileWidth" }, { 0x143, "exif:TileLength" }, { 0x144, "exif:TileOffsets" }, { 0x145, "exif:TileByteCounts" }, { 0x14a, "exif:SubIFD" }, { 0x14c, "exif:InkSet" }, { 0x14d, "exif:InkNames" }, { 0x14e, "exif:NumberOfInks" }, { 0x150, "exif:DotRange" }, { 0x151, "exif:TargetPrinter" }, { 0x152, "exif:ExtraSample" }, { 0x153, "exif:SampleFormat" }, { 0x154, "exif:SMinSampleValue" }, { 0x155, "exif:SMaxSampleValue" }, { 0x156, "exif:TransferRange" }, { 0x157, "exif:ClipPath" }, { 0x158, "exif:XClipPathUnits" }, { 0x159, "exif:YClipPathUnits" }, { 0x15a, "exif:Indexed" }, { 0x15b, "exif:JPEGTables" }, { 0x15f, "exif:OPIProxy" }, { 0x200, "exif:JPEGProc" }, { 0x201, "exif:JPEGInterchangeFormat" }, { 0x202, "exif:JPEGInterchangeFormatLength" }, { 0x203, "exif:JPEGRestartInterval" }, { 0x205, "exif:JPEGLosslessPredictors" }, { 0x206, "exif:JPEGPointTransforms" }, { 0x207, "exif:JPEGQTables" }, { 0x208, "exif:JPEGDCTables" }, { 0x209, "exif:JPEGACTables" }, { 0x211, "exif:YCbCrCoefficients" }, { 0x212, "exif:YCbCrSubSampling" }, { 0x213, "exif:YCbCrPositioning" }, { 0x214, "exif:ReferenceBlackWhite" }, { 0x2bc, "exif:ExtensibleMetadataPlatform" }, { 0x301, "exif:Gamma" }, { 0x302, "exif:ICCProfileDescriptor" }, { 0x303, "exif:SRGBRenderingIntent" }, { 0x320, "exif:ImageTitle" }, { 0x5001, "exif:ResolutionXUnit" }, { 0x5002, "exif:ResolutionYUnit" }, { 0x5003, "exif:ResolutionXLengthUnit" }, { 0x5004, "exif:ResolutionYLengthUnit" }, { 0x5005, "exif:PrintFlags" }, { 0x5006, "exif:PrintFlagsVersion" }, { 0x5007, "exif:PrintFlagsCrop" }, { 0x5008, "exif:PrintFlagsBleedWidth" }, { 0x5009, "exif:PrintFlagsBleedWidthScale" }, { 0x500A, "exif:HalftoneLPI" }, { 0x500B, "exif:HalftoneLPIUnit" }, { 0x500C, "exif:HalftoneDegree" }, { 0x500D, "exif:HalftoneShape" }, { 0x500E, "exif:HalftoneMisc" }, { 0x500F, "exif:HalftoneScreen" }, { 0x5010, "exif:JPEGQuality" }, { 0x5011, "exif:GridSize" }, { 0x5012, "exif:ThumbnailFormat" }, { 0x5013, "exif:ThumbnailWidth" }, { 0x5014, "exif:ThumbnailHeight" }, { 0x5015, "exif:ThumbnailColorDepth" }, { 0x5016, "exif:ThumbnailPlanes" }, { 0x5017, "exif:ThumbnailRawBytes" }, { 0x5018, "exif:ThumbnailSize" }, { 0x5019, "exif:ThumbnailCompressedSize" }, { 0x501a, "exif:ColorTransferFunction" }, { 0x501b, "exif:ThumbnailData" }, { 0x5020, "exif:ThumbnailImageWidth" }, { 0x5021, "exif:ThumbnailImageHeight" }, { 0x5022, "exif:ThumbnailBitsPerSample" }, { 0x5023, "exif:ThumbnailCompression" }, { 0x5024, "exif:ThumbnailPhotometricInterp" }, { 0x5025, "exif:ThumbnailImageDescription" }, { 0x5026, "exif:ThumbnailEquipMake" }, { 0x5027, "exif:ThumbnailEquipModel" }, { 0x5028, "exif:ThumbnailStripOffsets" }, { 0x5029, "exif:ThumbnailOrientation" }, { 0x502a, "exif:ThumbnailSamplesPerPixel" }, { 0x502b, "exif:ThumbnailRowsPerStrip" }, { 0x502c, "exif:ThumbnailStripBytesCount" }, { 0x502d, "exif:ThumbnailResolutionX" }, { 0x502e, "exif:ThumbnailResolutionY" }, { 0x502f, "exif:ThumbnailPlanarConfig" }, { 0x5030, "exif:ThumbnailResolutionUnit" }, { 0x5031, "exif:ThumbnailTransferFunction" }, { 0x5032, "exif:ThumbnailSoftwareUsed" }, { 0x5033, "exif:ThumbnailDateTime" }, { 0x5034, "exif:ThumbnailArtist" }, { 0x5035, "exif:ThumbnailWhitePoint" }, { 0x5036, "exif:ThumbnailPrimaryChromaticities" }, { 0x5037, "exif:ThumbnailYCbCrCoefficients" }, { 0x5038, "exif:ThumbnailYCbCrSubsampling" }, { 0x5039, "exif:ThumbnailYCbCrPositioning" }, { 0x503A, "exif:ThumbnailRefBlackWhite" }, { 0x503B, "exif:ThumbnailCopyRight" }, { 0x5090, "exif:LuminanceTable" }, { 0x5091, "exif:ChrominanceTable" }, { 0x5100, "exif:FrameDelay" }, { 0x5101, "exif:LoopCount" }, { 0x5110, "exif:PixelUnit" }, { 0x5111, "exif:PixelPerUnitX" }, { 0x5112, "exif:PixelPerUnitY" }, { 0x5113, "exif:PaletteHistogram" }, { 0x1000, "exif:RelatedImageFileFormat" }, { 0x1001, "exif:RelatedImageLength" }, { 0x1002, "exif:RelatedImageWidth" }, { 0x800d, "exif:ImageID" }, { 0x80e3, "exif:Matteing" }, { 0x80e4, "exif:DataType" }, { 0x80e5, "exif:ImageDepth" }, { 0x80e6, "exif:TileDepth" }, { 0x828d, "exif:CFARepeatPatternDim" }, { 0x828e, "exif:CFAPattern2" }, { 0x828f, "exif:BatteryLevel" }, { 0x8298, "exif:Copyright" }, { 0x829a, "exif:ExposureTime" }, { 0x829d, "exif:FNumber" }, { 0x83bb, "exif:IPTC/NAA" }, { 0x84e3, "exif:IT8RasterPadding" }, { 0x84e5, "exif:IT8ColorTable" }, { 0x8649, "exif:ImageResourceInformation" }, { 0x8769, "exif:ExifOffset" }, { 0x8773, "exif:InterColorProfile" }, { 0x8822, "exif:ExposureProgram" }, { 0x8824, "exif:SpectralSensitivity" }, { 0x8825, "exif:GPSInfo" }, { 0x8827, "exif:ISOSpeedRatings" }, { 0x8828, "exif:OECF" }, { 0x8829, "exif:Interlace" }, { 0x882a, "exif:TimeZoneOffset" }, { 0x882b, "exif:SelfTimerMode" }, { 0x9000, "exif:ExifVersion" }, { 0x9003, "exif:DateTimeOriginal" }, { 0x9004, "exif:DateTimeDigitized" }, { 0x9101, "exif:ComponentsConfiguration" }, { 0x9102, "exif:CompressedBitsPerPixel" }, { 0x9201, "exif:ShutterSpeedValue" }, { 0x9202, "exif:ApertureValue" }, { 0x9203, "exif:BrightnessValue" }, { 0x9204, "exif:ExposureBiasValue" }, { 0x9205, "exif:MaxApertureValue" }, { 0x9206, "exif:SubjectDistance" }, { 0x9207, "exif:MeteringMode" }, { 0x9208, "exif:LightSource" }, { 0x9209, "exif:Flash" }, { 0x920a, "exif:FocalLength" }, { 0x920b, "exif:FlashEnergy" }, { 0x920c, "exif:SpatialFrequencyResponse" }, { 0x920d, "exif:Noise" }, { 0x9211, "exif:ImageNumber" }, { 0x9212, "exif:SecurityClassification" }, { 0x9213, "exif:ImageHistory" }, { 0x9214, "exif:SubjectArea" }, { 0x9215, "exif:ExposureIndex" }, { 0x9216, "exif:TIFF-EPStandardID" }, { 0x927c, "exif:MakerNote" }, { 0x9C9b, "exif:WinXP-Title" }, { 0x9C9c, "exif:WinXP-Comments" }, { 0x9C9d, "exif:WinXP-Author" }, { 0x9C9e, "exif:WinXP-Keywords" }, { 0x9C9f, "exif:WinXP-Subject" }, { 0x9286, "exif:UserComment" }, { 0x9290, "exif:SubSecTime" }, { 0x9291, "exif:SubSecTimeOriginal" }, { 0x9292, "exif:SubSecTimeDigitized" }, { 0xa000, "exif:FlashPixVersion" }, { 0xa001, "exif:ColorSpace" }, { 0xa002, "exif:ExifImageWidth" }, { 0xa003, "exif:ExifImageLength" }, { 0xa004, "exif:RelatedSoundFile" }, { 0xa005, "exif:InteroperabilityOffset" }, { 0xa20b, "exif:FlashEnergy" }, { 0xa20c, "exif:SpatialFrequencyResponse" }, { 0xa20d, "exif:Noise" }, { 0xa20e, "exif:FocalPlaneXResolution" }, { 0xa20f, "exif:FocalPlaneYResolution" }, { 0xa210, "exif:FocalPlaneResolutionUnit" }, { 0xa214, "exif:SubjectLocation" }, { 0xa215, "exif:ExposureIndex" }, { 0xa216, "exif:TIFF/EPStandardID" }, { 0xa217, "exif:SensingMethod" }, { 0xa300, "exif:FileSource" }, { 0xa301, "exif:SceneType" }, { 0xa302, "exif:CFAPattern" }, { 0xa401, "exif:CustomRendered" }, { 0xa402, "exif:ExposureMode" }, { 0xa403, "exif:WhiteBalance" }, { 0xa404, "exif:DigitalZoomRatio" }, { 0xa405, "exif:FocalLengthIn35mmFilm" }, { 0xa406, "exif:SceneCaptureType" }, { 0xa407, "exif:GainControl" }, { 0xa408, "exif:Contrast" }, { 0xa409, "exif:Saturation" }, { 0xa40a, "exif:Sharpness" }, { 0xa40b, "exif:DeviceSettingDescription" }, { 0xa40c, "exif:SubjectDistanceRange" }, { 0xa420, "exif:ImageUniqueID" }, { 0xc4a5, "exif:PrintImageMatching" }, { 0xa500, "exif:Gamma" }, { 0xc640, "exif:CR2Slice" }, { 0x10000, "exif:GPSVersionID" }, { 0x10001, "exif:GPSLatitudeRef" }, { 0x10002, "exif:GPSLatitude" }, { 0x10003, "exif:GPSLongitudeRef" }, { 0x10004, "exif:GPSLongitude" }, { 0x10005, "exif:GPSAltitudeRef" }, { 0x10006, "exif:GPSAltitude" }, { 0x10007, "exif:GPSTimeStamp" }, { 0x10008, "exif:GPSSatellites" }, { 0x10009, "exif:GPSStatus" }, { 0x1000a, "exif:GPSMeasureMode" }, { 0x1000b, "exif:GPSDop" }, { 0x1000c, "exif:GPSSpeedRef" }, { 0x1000d, "exif:GPSSpeed" }, { 0x1000e, "exif:GPSTrackRef" }, { 0x1000f, "exif:GPSTrack" }, { 0x10010, "exif:GPSImgDirectionRef" }, { 0x10011, "exif:GPSImgDirection" }, { 0x10012, "exif:GPSMapDatum" }, { 0x10013, "exif:GPSDestLatitudeRef" }, { 0x10014, "exif:GPSDestLatitude" }, { 0x10015, "exif:GPSDestLongitudeRef" }, { 0x10016, "exif:GPSDestLongitude" }, { 0x10017, "exif:GPSDestBearingRef" }, { 0x10018, "exif:GPSDestBearing" }, { 0x10019, "exif:GPSDestDistanceRef" }, { 0x1001a, "exif:GPSDestDistance" }, { 0x1001b, "exif:GPSProcessingMethod" }, { 0x1001c, "exif:GPSAreaInformation" }, { 0x1001d, "exif:GPSDateStamp" }, { 0x1001e, "exif:GPSDifferential" }, { 0x00000, (const char *) NULL } }; const StringInfo *profile; const unsigned char *directory, *exif; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; MagickBooleanType status; register ssize_t i; size_t entry, length, number_entries, tag, tag_value; SplayTreeInfo *exif_resources; ssize_t all, id, level, offset, tag_offset; static int tag_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; /* If EXIF data exists, then try to parse the request for a tag. */ profile=GetImageProfile(image,"exif"); if (profile == (const StringInfo *) NULL) return(MagickFalse); if ((property == (const char *) NULL) || (*property == '\0')) return(MagickFalse); while (isspace((int) ((unsigned char) *property)) != 0) property++; if (strlen(property) <= 5) return(MagickFalse); all=0; tag=(~0UL); switch (*(property+5)) { case '*': { /* Caller has asked for all the tags in the EXIF data. */ tag=0; all=1; /* return the data in description=value format */ break; } case '!': { tag=0; all=2; /* return the data in tagid=value format */ break; } case '#': case '@': { int c; size_t n; /* Check for a hex based tag specification first. */ tag=(*(property+5) == '@') ? 1UL : 0UL; property+=6; n=strlen(property); if (n != 4) return(MagickFalse); /* Parse tag specification as a hex number. */ n/=4; do { for (i=(ssize_t) n-1L; i >= 0; i--) { c=(*property++); tag<<=4; if ((c >= '0') && (c <= '9')) tag|=(c-'0'); else if ((c >= 'A') && (c <= 'F')) tag|=(c-('A'-10)); else if ((c >= 'a') && (c <= 'f')) tag|=(c-('a'-10)); else return(MagickFalse); } } while (*property != '\0'); break; } default: { /* Try to match the text with a tag name instead. */ for (i=0; ; i++) { if (EXIFTag[i].tag == 0) break; if (LocaleCompare(EXIFTag[i].description,property) == 0) { tag=(size_t) EXIFTag[i].tag; break; } } break; } } if (tag == (~0UL)) return(MagickFalse); length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); while (length != 0) { if (ReadPropertyByte(&exif,&length) != 0x45) continue; if (ReadPropertyByte(&exif,&length) != 0x78) continue; if (ReadPropertyByte(&exif,&length) != 0x69) continue; if (ReadPropertyByte(&exif,&length) != 0x66) continue; if (ReadPropertyByte(&exif,&length) != 0x00) continue; if (ReadPropertyByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadPropertySignedShort(LSBEndian,exif); endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadPropertyUnsignedShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadPropertySignedLong(endian,exif+4); if ((offset < 0) || (size_t) offset >= length) return(MagickFalse); /* Set the pointer to the first IFD and follow it were it leads. */ status=MagickFalse; directory=exif+offset; level=0; entry=0; tag_offset=0; exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL, (void *(*)(void *)) NULL,(void *(*)(void *)) NULL); do { /* If there is anything on the stack then pop it off. */ if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; tag_offset=directory_stack[level].offset; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=(size_t) ReadPropertyUnsignedShort(endian,directory); for ( ; entry < number_entries; entry++) { register unsigned char *p, *q; size_t format; ssize_t number_bytes, components; q=(unsigned char *) (directory+(12*entry)+2); if (GetValueFromSplayTree(exif_resources,q) == q) break; (void) AddValueToSplayTree(exif_resources,q,q); tag_value=(size_t) ReadPropertyUnsignedShort(endian,q)+tag_offset; format=(size_t) ReadPropertyUnsignedShort(endian,q+2); if (format >= (sizeof(tag_bytes)/sizeof(*tag_bytes))) break; components=(ssize_t) ReadPropertySignedLong(endian,q+4); number_bytes=(size_t) components*tag_bytes[format]; if (number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { ssize_t offset; /* The directory entry contains an offset. */ offset=(ssize_t) ReadPropertySignedLong(endian,q+8); if ((offset < 0) || (size_t) offset >= length) continue; if ((ssize_t) (offset+number_bytes) < offset) continue; /* prevent overflow */ if ((size_t) (offset+number_bytes) > length) continue; p=(unsigned char *) (exif+offset); } if ((all != 0) || (tag == (size_t) tag_value)) { char buffer[MagickPathExtent], *value; value=(char *) NULL; *buffer='\0'; switch (format) { case EXIF_FMT_BYTE: case EXIF_FMT_UNDEFINED: { EXIFMultipleValues(1,"%.20g",(double) (*(unsigned char *) p1)); break; } case EXIF_FMT_SBYTE: { EXIFMultipleValues(1,"%.20g",(double) (*(signed char *) p1)); break; } case EXIF_FMT_SSHORT: { EXIFMultipleValues(2,"%hd",ReadPropertySignedShort(endian,p1)); break; } case EXIF_FMT_USHORT: { EXIFMultipleValues(2,"%hu",ReadPropertyUnsignedShort(endian,p1)); break; } case EXIF_FMT_ULONG: { EXIFMultipleValues(4,"%.20g",(double) ReadPropertyUnsignedLong(endian,p1)); break; } case EXIF_FMT_SLONG: { EXIFMultipleValues(4,"%.20g",(double) ReadPropertySignedLong(endian,p1)); break; } case EXIF_FMT_URATIONAL: { EXIFMultipleFractions(8,"%.20g/%.20g",(double) ReadPropertyUnsignedLong(endian,p1),(double) ReadPropertyUnsignedLong(endian,p1+4)); break; } case EXIF_FMT_SRATIONAL: { EXIFMultipleFractions(8,"%.20g/%.20g",(double) ReadPropertySignedLong(endian,p1),(double) ReadPropertySignedLong(endian,p1+4)); break; } case EXIF_FMT_SINGLE: { EXIFMultipleValues(4,"%f",(double) *(float *) p1); break; } case EXIF_FMT_DOUBLE: { EXIFMultipleValues(8,"%f",*(double *) p1); break; } default: case EXIF_FMT_STRING: { value=(char *) NULL; if (~((size_t) number_bytes) >= 1) value=(char *) AcquireQuantumMemory((size_t) number_bytes+1UL, sizeof(*value)); if (value != (char *) NULL) { register ssize_t i; for (i=0; i < (ssize_t) number_bytes; i++) { value[i]='.'; if ((isprint((int) p[i]) != 0) || (p[i] == '\0')) value[i]=(char) p[i]; } value[i]='\0'; } break; } } if (value != (char *) NULL) { char *key; register const char *p; key=AcquireString(property); switch (all) { case 1: { const char *description; register ssize_t i; description="unknown"; for (i=0; ; i++) { if (EXIFTag[i].tag == 0) break; if (EXIFTag[i].tag == tag_value) { description=EXIFTag[i].description; break; } } (void) FormatLocaleString(key,MagickPathExtent,"%s", description); if (level == 2) (void) SubstituteString(&key,"exif:","exif:thumbnail:"); break; } case 2: { if (tag_value < 0x10000) (void) FormatLocaleString(key,MagickPathExtent,"#%04lx", (unsigned long) tag_value); else if (tag_value < 0x20000) (void) FormatLocaleString(key,MagickPathExtent,"@%04lx", (unsigned long) (tag_value & 0xffff)); else (void) FormatLocaleString(key,MagickPathExtent,"unknown"); break; } default: { if (level == 2) (void) SubstituteString(&key,"exif:","exif:thumbnail:"); } } p=(const char *) NULL; if (image->properties != (void *) NULL) p=(const char *) GetValueFromSplayTree((SplayTreeInfo *) image->properties,key); if (p == (const char *) NULL) (void) SetImageProperty((Image *) image,key,value,exception); value=DestroyString(value); key=DestroyString(key); status=MagickTrue; } } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET) || (tag_value == TAG_GPS_OFFSET)) { ssize_t offset; offset=(ssize_t) ReadPropertySignedLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { ssize_t tag_offset1; tag_offset1=(ssize_t) ((tag_value == TAG_GPS_OFFSET) ? 0x10000 : 0); directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; directory_stack[level].offset=tag_offset; level++; directory_stack[level].directory=exif+offset; directory_stack[level].offset=tag_offset1; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadPropertySignedLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; directory_stack[level].offset=tag_offset1; level++; } } break; } } } while (level > 0); exif_resources=DestroySplayTree(exif_resources); return(status); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline signed int ReadProfileLong(const EndianType endian, unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned int value; if (endian == LSBEndian) { value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8 ) | (buffer[0])); quantum.unsigned_value=(value & 0xffffffff); return(quantum.signed_value); } value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]); quantum.unsigned_value=(value & 0xffffffff); return(quantum.signed_value); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER "\n" #define EXIF_NUM_FORMATS 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_INTEROP_OFFSET 0xa005 typedef struct _DirectoryInfo { unsigned char *directory; size_t entry; } DirectoryInfo; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; size_t entry, length, number_entries; ssize_t id, level, offset; static int format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; unsigned char *directory, *exif; /* Set EXIF resolution tag. */ length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); if ((id != 0x4949) && (id != 0x4D4D)) { while (length != 0) { if (ReadProfileByte(&exif,&length) != 0x45) continue; if (ReadProfileByte(&exif,&length) != 0x78) continue; if (ReadProfileByte(&exif,&length) != 0x69) continue; if (ReadProfileByte(&exif,&length) != 0x66) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); } endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadProfileShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadProfileLong(endian,exif+4); if ((offset < 0) || (size_t) offset >= length) return(MagickFalse); directory=exif+offset; level=0; entry=0; do { if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=ReadProfileShort(endian,directory); for ( ; entry < number_entries; entry++) { int components; register unsigned char *p, *q; size_t number_bytes; ssize_t format, tag_value; q=(unsigned char *) (directory+2+(12*entry)); tag_value=(ssize_t) ReadProfileShort(endian,q); format=(ssize_t) ReadProfileShort(endian,q+2); if ((format-1) >= EXIF_NUM_FORMATS) break; components=(ssize_t) ReadProfileLong(endian,q+4); number_bytes=(size_t) components*format_bytes[format]; if ((ssize_t) number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { /* The directory entry contains an offset. */ offset=(ssize_t) ReadProfileLong(endian,q+8); if ((size_t) (offset+number_bytes) > length) continue; if (~length < number_bytes) continue; /* prevent overflow */ p=(unsigned char *) (exif+offset); } switch (tag_value) { case 0x011a: { (void) WriteProfileLong(endian,(size_t) (image->resolution.x+0.5),p); (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x011b: { (void) WriteProfileLong(endian,(size_t) (image->resolution.y+0.5),p); (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x0112: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) image->orientation,p); break; } (void) WriteProfileShort(endian,(unsigned short) image->orientation, p); break; } case 0x0128: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) (image->units+1),p); break; } (void) WriteProfileShort(endian,(unsigned short) (image->units+1),p); break; } default: break; } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET)) { offset=(ssize_t) ReadProfileLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; level++; directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadProfileLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; } } break; } } } while (level > 0); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: MagickExport MagickBooleanType SetImageProfile(Image *image,const char *name, const StringInfo *profile,ExceptionInfo *exception) { char key[MaxTextExtent], property[MaxTextExtent]; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) image->profiles=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory, DestroyProfile); (void) CopyMagickString(key,name,MaxTextExtent); status=AddValueToSplayTree((SplayTreeInfo *) image->profiles, ConstantString(key),CloneStringInfo(profile)); if ((status != MagickFalse) && ((LocaleCompare(name,"iptc") == 0) || (LocaleCompare(name,"8bim") == 0))) (void) GetProfilesFromResourceBlock(image,profile,exception); /* Inject profile into image properties. */ (void) FormatLocaleString(property,MaxTextExtent,"%s:sans",name); (void) GetImageProperty(image,property,exception); return(status); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': ''</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int sched_read_attr(struct sched_attr __user *uattr, struct sched_attr *attr, unsigned int usize) { int ret; if (!access_ok(VERIFY_WRITE, uattr, usize)) return -EFAULT; /* * If we're handed a smaller struct than we know of, * ensure all the unknown bits are 0 - i.e. old * user-space does not get uncomplete information. */ if (usize < sizeof(*attr)) { unsigned char *addr; unsigned char *end; addr = (void *)attr + usize; end = (void *)attr + sizeof(*attr); for (; addr < end; addr++) { if (*addr) goto err_size; } attr->size = usize; } ret = copy_to_user(uattr, attr, usize); if (ret) return -EFAULT; out: return ret; err_size: ret = -E2BIG; goto out; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'sched: Fix information leak in sys_sched_getattr() We're copying the on-stack structure to userspace, but forgot to give the right number of bytes to copy. This allows the calling process to obtain up to PAGE_SIZE bytes from the stack (and possibly adjacent kernel memory). This fix copies only as much as we actually have on the stack (attr->size defaults to the size of the struct) and leaves the rest of the userspace-provided buffer untouched. Found using kmemcheck + trinity. Fixes: d50dde5a10f30 ("sched: Add new scheduler syscalls to support an extended scheduling parameters ABI") Cc: Dario Faggioli <[email protected]> Cc: Juri Lelli <[email protected]> Cc: Ingo Molnar <[email protected]> Signed-off-by: Vegard Nossum <[email protected]> Signed-off-by: Peter Zijlstra <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Thomas Gleixner <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static long vop_ioctl(struct file *f, unsigned int cmd, unsigned long arg) { struct vop_vdev *vdev = f->private_data; struct vop_info *vi = vdev->vi; void __user *argp = (void __user *)arg; int ret; switch (cmd) { case MIC_VIRTIO_ADD_DEVICE: { struct mic_device_desc dd, *dd_config; if (copy_from_user(&dd, argp, sizeof(dd))) return -EFAULT; if (mic_aligned_desc_size(&dd) > MIC_MAX_DESC_BLK_SIZE || dd.num_vq > MIC_MAX_VRINGS) return -EINVAL; dd_config = kzalloc(mic_desc_size(&dd), GFP_KERNEL); if (!dd_config) return -ENOMEM; if (copy_from_user(dd_config, argp, mic_desc_size(&dd))) { ret = -EFAULT; goto free_ret; } mutex_lock(&vdev->vdev_mutex); mutex_lock(&vi->vop_mutex); ret = vop_virtio_add_device(vdev, dd_config); if (ret) goto unlock_ret; list_add_tail(&vdev->list, &vi->vdev_list); unlock_ret: mutex_unlock(&vi->vop_mutex); mutex_unlock(&vdev->vdev_mutex); free_ret: kfree(dd_config); return ret; } case MIC_VIRTIO_COPY_DESC: { struct mic_copy_desc copy; mutex_lock(&vdev->vdev_mutex); ret = vop_vdev_inited(vdev); if (ret) goto _unlock_ret; if (copy_from_user(&copy, argp, sizeof(copy))) { ret = -EFAULT; goto _unlock_ret; } ret = vop_virtio_copy_desc(vdev, &copy); if (ret < 0) goto _unlock_ret; if (copy_to_user( &((struct mic_copy_desc __user *)argp)->out_len, &copy.out_len, sizeof(copy.out_len))) ret = -EFAULT; _unlock_ret: mutex_unlock(&vdev->vdev_mutex); return ret; } case MIC_VIRTIO_CONFIG_CHANGE: { void *buf; mutex_lock(&vdev->vdev_mutex); ret = vop_vdev_inited(vdev); if (ret) goto __unlock_ret; buf = kzalloc(vdev->dd->config_len, GFP_KERNEL); if (!buf) { ret = -ENOMEM; goto __unlock_ret; } if (copy_from_user(buf, argp, vdev->dd->config_len)) { ret = -EFAULT; goto done; } ret = vop_virtio_config_change(vdev, buf); done: kfree(buf); __unlock_ret: mutex_unlock(&vdev->vdev_mutex); return ret; } default: return -ENOIOCTLCMD; }; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'misc: mic: Fix for double fetch security bug in VOP driver The MIC VOP driver does two successive reads from user space to read a variable length data structure. Kernel memory corruption can result if the data structure changes between the two reads. This patch disallows the chance of this happening. Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=116651 Reported by: Pengfei Wang <[email protected]> Reviewed-by: Sudeep Dutt <[email protected]> Signed-off-by: Ashutosh Dixit <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]>'</s>